Example #1
0
static char* test_checksumming(void) {
  uint32_t my_data[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, -1};

  add_checksum(my_data, 10);

  mu_assert("end modified", my_data[9] != -1);

  mu_assert("closure", verify_checksum(my_data, 10));

  my_data[2] = 1000;

  mu_assert("detect error", !verify_checksum(my_data, 10));
      
  return 0;
}
Example #2
0
/*
 * The function assumes that the following patterns have fixed sizes:
 * - "BeginString=" ("8=") is 2 bytes long
 * - "CheckSum=" ("10=") is 3 bytes long
 * - "MsgType=" ("35=") is 3 bytes long
 */
static bool checksum(struct fix_message *self, struct buffer *buffer)
{
	const char *start;
	int offset;

	start = buffer_start(buffer);

	/* The number of bytes between tag MsgType and buffer's start */
	offset = start - (self->msg_type - 3);

	/*
	 * Checksum tag and its trailing delimiter increase
	 * the message's length by seven bytes - "10=***\x01"
	 */
	if (buffer_size(buffer) + offset < self->body_length + 7)
		return false;

	/* Buffer's start will point to the CheckSum tag */
	buffer_advance(buffer, self->body_length - offset);

	self->check_sum = parse_field(buffer, CheckSum);
	if (!self->check_sum)
		return false;

	if (!verify_checksum(self, buffer))
		return false;

	/* Go back to analyze other fields */
	buffer_advance(buffer, start - buffer_start(buffer));

	return true;
}
Example #3
0
static int fetch_reply(struct bsl_device *dev)
{
	dev->reply_len = 0;

	for (;;) {
		int r = dev->serial->ops->recv(dev->serial,
			       dev->reply_buf + dev->reply_len,
			       sizeof(dev->reply_buf) - dev->reply_len);

		if (r < 0)
			return -1;

		dev->reply_len += r;

		if (dev->reply_buf[0] == DATA_ACK) {
			return 0;
		} else if (dev->reply_buf[0] == DATA_HDR) {
			if (dev->reply_len >= 6 &&
			    dev->reply_len == dev->reply_buf[2] + 6)
				return verify_checksum(dev);
		} else if (dev->reply_buf[0] == DATA_NAK) {
			printc_err("bsl: received NAK\n");
			return -1;
		} else {
			printc_err("bsl: unknown reply type: %02x\n",
				dev->reply_buf[0]);
			return -1;
		}

		if (dev->reply_len >= sizeof(dev->reply_buf)) {
			printc_err("bsl: reply buffer overflow\n");
			return -1;
		}
	}
}
Example #4
0
BCW_API bool hd_private_key::set_serialized(std::string encoded)
{
    if (!is_base58(encoded))
        return false;
    const data_chunk decoded = decode_base58(encoded);
    if (decoded.size() != serialized_length)
        return false;
    if (!verify_checksum(decoded))
        return false;

    auto ds = make_deserializer(decoded.begin(), decoded.end());
    auto prefix = ds.read_big_endian<uint32_t>();
    if (prefix != mainnet_private_prefix && prefix != testnet_private_prefix)
        return false;

    valid_ = true;
    lineage_.testnet = prefix == testnet_private_prefix;
    lineage_.depth = ds.read_byte();
    lineage_.parent_fingerprint = ds.read_little_endian<uint32_t>();
    lineage_.child_number = ds.read_big_endian<uint32_t>();
    c_ = ds.read_bytes<chain_code_size>();
    ds.read_byte();
    k_ = ds.read_bytes<ec_secret_size>();
    K_ = secret_to_public_key(k_);
    return true;
}
Example #5
0
int bladerf_image_read(struct bladerf_image *img, const char *file)
{
    int rv = -1;
    uint8_t *buf = NULL;
    size_t buf_len;

    rv = file_read_buffer(file, &buf, &buf_len);
    if (rv < 0) {
        goto bladerf_image_read_out;
    }

    rv = verify_checksum(buf, buf_len);
    if (rv < 0) {
        goto bladerf_image_read_out;
    }

    /* Note: On success, buf->data = buf, with the data memmove'd over.
     *       Static analysis tools might indicate a false postive leak when
     *       buf goes out of scope with rv == 0 */
    rv = unpack_image(img, buf, buf_len);

bladerf_image_read_out:
    if (rv != 0) {
        free(buf);
    }

    return rv;
}
Example #6
0
int mgos_upd_file_end(struct mgos_upd_hal_ctx *ctx,
                      const struct mgos_upd_file_info *fi, struct mg_str tail) {
  int r = tail.len;
  assert(tail.len == 0);
  if (ctx->cur_fn == (_u8 *) ctx->fs_container_file) {
    if (!cc32xx_vfs_dev_slfs_container_write_meta(
            ctx->cur_fh, FS_INITIAL_SEQ, ctx->fs_size, ctx->fs_block_size,
            ctx->fs_page_size, ctx->fs_erase_size)) {
      ctx->status_msg = "Failed to write fs meta";
      r = -1;
    }
  }
  if (sl_FsClose(ctx->cur_fh, NULL, NULL, 0) != 0) {
    ctx->status_msg = "Close failed";
    r = -1;
  } else {
    struct json_token sha1 = JSON_INVALID_TOKEN;
    json_scanf(ctx->cur_part.ptr, ctx->cur_part.len, "{cs_sha1: %T}", &sha1);
    if (!verify_checksum((const char *) ctx->cur_fn, fi->size, &sha1)) {
      ctx->status_msg = "Checksum mismatch";
      r = -1;
    }
  }
  ctx->cur_fh = -1;
  ctx->cur_fn = NULL;
  return r;
}
Example #7
0
ec_secret wif_to_secret(const std::string& wif)
{
    data_chunk decoded;
    if (!decode_base58(decoded, wif))
        return ec_secret();

    // 1 marker, 32 byte secret, optional 1 compressed flag, 4 checksum bytes
    if (decoded.size() != 1 + hash_size + 4 &&
        decoded.size() != 1 + hash_size + 1 + 4)
        return ec_secret();

    if (!verify_checksum(decoded))
        return ec_secret();

    // Check first byte is valid
    if (decoded[0] != payment_address::wif_version)
        return ec_secret();

    // Checks passed. Drop the 0x80 start byte and checksum.
    decoded.erase(decoded.begin());
    decoded.erase(decoded.end() - 4, decoded.end());

    // If length is still 33 and last byte is 0x01, drop it.
    if (decoded.size() == 33 && decoded[32] == (uint8_t)0x01)
        decoded.erase(decoded.begin()+32);

    ec_secret secret;
    BITCOIN_ASSERT(secret.size() == decoded.size());
    std::copy(decoded.begin(), decoded.end(), secret.begin());
    return secret;
}
Example #8
0
File: ipv4.c Project: nhst/trema
/**
 * Validates if the packet header is valid IPv4 header. This is wrapped around
 * by parse_ipv4 function.
 * @param buf Pointer to buffer containing packet header to verify for being ipv4 header
 * @param packet_len Length of packet passed in the buffer
 * @return bool True if the packet header is a valid IPv4 header, else False
 * @see bool parse_ipv4( buffer *buf )
 */
static bool
valid_ipv4_packet_header( buffer *buf, uint32_t packet_len ) {
  if ( ( size_t ) packet_len < sizeof( ipv4_header_t ) ) {
    debug( "Too short IPv4 packet ( length = %u ).", packet_len );
    return false;
  }

  if ( packet_info( buf )->l3_data.ipv4->version != IPVERSION ) {
    debug( "Unsupported IP version ( version = %#x ).",
           packet_info( buf )->l3_data.ipv4->version );
    return false;
  }

  size_t hdr_len = ( size_t ) packet_info( buf )->l3_data.ipv4->ihl * 4;
  if ( hdr_len < sizeof( ipv4_header_t ) ) {
    debug( "Too short IPv4 header length field value ( length = %u ).",
           hdr_len );
    return false;
  }

  if ( verify_checksum( ( uint16_t * ) packet_info( buf )->l3_data.ipv4, ( uint32_t ) hdr_len ) != 0 ) {
    debug( "Corrupted IPv4 header ( checksum verification error )." );
    return false;
  }

  return true;
}
Example #9
0
static int prepare_to_write(struct mgos_upd_hal_ctx *ctx,
                            const struct mgos_upd_file_info *fi,
                            const char *fname, uint32_t falloc,
                            struct json_token *part) {
  struct json_token expected_sha1 = JSON_INVALID_TOKEN;
  json_scanf(part->ptr, part->len, "{cs_sha1: %T}", &expected_sha1);
  if (verify_checksum(fname, fi->size, &expected_sha1)) {
    LOG(LL_INFO,
        ("Digest matched for %s %u (%.*s)", fname, (unsigned int) fi->size,
         (int) expected_sha1.len, expected_sha1.ptr));
    return 0;
  }
  LOG(LL_INFO, ("Storing %s %u -> %s %u (%.*s)", fi->name,
                (unsigned int) fi->size, fname, (unsigned int) falloc,
                (int) expected_sha1.len, expected_sha1.ptr));
  ctx->cur_fn = (const _u8 *) fname;
  sl_FsDel(ctx->cur_fn, 0);
  _i32 r = sl_FsOpen(ctx->cur_fn, FS_MODE_OPEN_CREATE(falloc, 0), NULL,
                     &ctx->cur_fh);
  if (r < 0) {
    ctx->status_msg = "Failed to create file";
    return r;
  }
  return 1;
}
parse_ek_token::parse_ek_token(const ek_token& value)
  : parse_ek_prefix(slice<0, 8>(value)),
    entropy_(slice<8, 16>(value)),
    sign_(slice<16, 17>(value)),
    data_(slice<17, 49>(value))
{
    valid(verify_magic() && verify_context() && verify_checksum(value));
}
Example #11
0
void main()
{
	int i=0;
	char mymac[6]={0x74,0xf7,0x26,0x00,0x00,0x01};
	unsigned char data[]={0x00,0x01,0x02,0x03,0x04,0x05,0x06,0x07,0x08,0x09,0x04,0x74,0xf7,0x26,0x00,0x00,0x01,0x65,0x00,0x00,0x0a,0x05,0x00,0x01,0x02,0x03,0x05,0x06,0x07,0x08,0x09};

	bowler4_header bh;
	for (i=0; i<sizeof(bowler4_header); i++) bh.bytes[i]=0;
	bh.fields.version=0x04;
	bh.fields.affect=setPriority(5,setState(setAsync(bh.fields.affect)));
	bh.fields.payloadLength=10;
	bh.fields.payloadType=0;


	set_mac_address(mymac,&bh);
	calculate_checksum(&bh);
	printf("Verify?\t%d\n",verify_checksum(&bh));
	printf("Verify?\t%d\n",verify_checksum(&bh));
printf("%X\n",check_mac_address(mymac,&bh) );
	printHeader(bh);


	V4MicroParser_state parser;
	parser.state=align;
	parser.macaddr=&mymac;
	fifoInit(&parser.fifo);
	fifoPrint(&parser.fifo);

	for (i=0; i<sizeof(data); i++){
 		fifoPush(&parser.fifo,data[i]);
		int delta=parser.fifo.inPointer;
		printf("Pushing:\t%i\n",i);
		/*fifoPrint(&parser.fifo);*/
		runParserSM(&parser);
		if (parser.fifo.inPointer!=delta) {printf("\nNew Contents of FIFO:");fifoPrint(&parser.fifo);}

		printf("===================\n");
		

	}
		/* fifoPull(&fifo,15); */
		/* fifoPrint(&fifo); */
}
Example #12
0
File: tbcheck.c Project: Albitex/tb
int main(int argc, char **argv)
{
  int i;
  int val, longindex;
  int only_print = 0;
  int compare = 0;

  numthreads = 1;

  do {
    val = getopt_long(argc, argv, "t:pc", options, &longindex);
    switch (val) {
    case 't':
      numthreads = atoi(optarg);
      break;
    case 'p':
      only_print = 1;
      break;
    case 'c':
      compare = 1;
      break;
    }
  } while (val != EOF);

  if (optind >= argc) {
    printf("No tablebase specified.\n");
    exit(0);
  }

  if (numthreads < 1) numthreads = 1;
  else if (numthreads > MAX_THREADS) numthreads = MAX_THREADS;

  total_work = (numthreads == 1) ? 1 : 100 + 10 * numthreads;

  init_threads(0);

  if (!compare) {
    if (!only_print)
      for (i = optind; i < argc; i++)
	verify_checksum(argv[i]);
    else
      for (i = optind; i < argc; i++) {
	char sum[40];
	printf("%s: ", argv[i]);
	print_checksum(argv[i], sum);
	puts(sum);
      }
  } else {
    for (i = optind; i < argc; i++)
      compare_checksums(argv[i]);
  }

  return 0;
}
Example #13
0
static void checksum_test1(void)
{
	RaucChecksum checksum = {};
	GError *error = NULL;

	checksum.type = 0;
	checksum.digest = NULL;
	g_assert_false(verify_checksum(&checksum, "test/install-content/appfs.img", &error));
	g_assert_error(error, R_CHECKSUM_ERROR, R_CHECKSUM_ERROR_FAILED);
	g_clear_error(&error);

	checksum.type = G_CHECKSUM_SHA256;
	checksum.digest = g_strdup(TEST_DIGEST_FAIL);
	g_assert_false(verify_checksum(&checksum, "test/install-content/appfs.img", &error));
	g_assert_error(error, R_CHECKSUM_ERROR, R_CHECKSUM_ERROR_SIZE_MISMATCH);
	g_clear_error(&error);

	checksum.size = 32768;
	g_assert_false(verify_checksum(&checksum, "test/install-content/appfs.img", &error));
	g_assert_error(error, R_CHECKSUM_ERROR, R_CHECKSUM_ERROR_DIGEST_MISMATCH);
	g_clear_error(&error);

	checksum.size = 0;
	checksum.digest = g_strdup(TEST_DIGEST_GOOD);
	g_assert_false(verify_checksum(&checksum, "test/install-content/appfs.img", &error));
	g_assert_error(error, R_CHECKSUM_ERROR, R_CHECKSUM_ERROR_SIZE_MISMATCH);
	g_clear_error(&error);

	checksum.size = 32768;
	g_assert_true(verify_checksum(&checksum, "test/install-content/appfs.img", &error));
	g_assert_no_error(error);

	g_assert_false(verify_checksum(&checksum, "tesinstall-content/rootfs.img", &error));
	g_assert_error(error, G_FILE_ERROR, G_FILE_ERROR_NOENT);
	g_clear_error(&error);

	g_assert_false(verify_checksum(&checksum, "test/_MISSING_", &error));
	g_assert_error(error, G_FILE_ERROR, G_FILE_ERROR_NOENT);
	g_clear_error(&error);

	g_clear_pointer(&checksum.digest, g_free);
	checksum.size = 0;
	g_assert_true(compute_checksum(&checksum, "test/install-content/appfs.img", &error));
	g_assert_no_error(error);
	g_assert_cmpstr(checksum.digest, ==, TEST_DIGEST_GOOD);
	g_assert(checksum.size == 32768);

	g_clear_pointer(&checksum.digest, g_free);
	checksum.size = 0;
	g_assert_false(compute_checksum(&checksum, "tesinstall-content/rootfs.img", &error));
	g_assert_error(error, G_FILE_ERROR, G_FILE_ERROR_NOENT);
	g_clear_error(&error);
	g_assert_null(checksum.digest);
	g_assert(checksum.size == 0);
}
		bool payment_address::set_encoded(const std::string& encoded_address)
		{
			if (!is_base58(encoded_address))
				return false;
			const data_chunk decoded_address = decode_base58(encoded_address);
			// version + 20 bytes short hash + 4 bytes checksum
			if (decoded_address.size() != 25)
				return false;
			if (!verify_checksum(decoded_address))
				return false;

			version_ = decoded_address[0];
			std::copy_n(decoded_address.begin() + 1, hash_.size(), hash_.begin());
			return true;
		}
Example #15
0
int 
parse_nmea(struct location *loc, char *nmea) 
{
  char lat_degrees[3];
  char lon_degrees[4];

  char lat_minutes[20];
  char lon_minutes[20];

  char *comma, *comma2;
  char *dst;

  if (verify_checksum(nmea) < 0)
    return -1;

  comma = 1 + strchr(nmea, ','); /*comma is now first comma */
  comma = 1 + strchr(comma, ','); /*comma is now after second comma, after time */

  comma2 = strchr(comma, ','); /*comma2 is comma after lat */
  strncpy(lat_degrees, comma, 2);
  lat_degrees[2] = '\0';

  loc->lat_degrees = atoi(lat_degrees);
  if (*(comma2 + 1) == 'S')
    loc->lat_degrees = -loc->lat_degrees;

  strncpy(lat_minutes, comma + 2, comma2 - comma);
  lat_minutes[comma2 - comma] = '\0';

  loc->lat_minutes = atof(lat_minutes);

  comma = 3 + comma2;
  comma2 = strchr(comma, ',');
  strncpy(lon_degrees, comma, 3);
  lon_degrees[3] = '\0';

  loc->lon_degrees = atoi(lon_degrees);
  if (*(comma2 + 1) == 'E')
    loc->lon_degrees = -loc->lon_degrees;

  strncpy(lon_minutes, comma + 3, comma2 - comma);
  lon_minutes[comma2 - comma] = '\0';

  loc->lon_minutes = atof(lon_minutes);

  return 0;

}
Example #16
0
/*
 * First check for the existance of BIOS32 service.
 * The Caller Must make sure the ROM address is addressable
 * by the running thread.
 */
struct bios32 *check_bios32()
{
	struct bios32 *bios;
	char *entry;
	unsigned long address;
	int index, length;
	long sum = 0;

	for(address = rom_start; address <= rom_end; address += PARAGRAPH_SIZE)
	{
		bios = (struct bios32 *)address;

		/* Check the Signature */
		if(bios->signature != BIOS32_SIG)
			continue;

		/*
		 * Now we Found the Signature but we cannot rely on it.
		 * Use the checksum to verify.
		 */
		if(bios->length != 1)
		{
			printf(" Length is Not 1 ");
			continue;
		}
		else if(bios->revision != 0)
		{
			printf(" Revision is Not 0 ");
			continue;
		}

		length = bios->length * PARAGRAPH_SIZE;
		
		sum = verify_checksum((char *)bios, length);
		if(sum != 0)
		{
			printf("Checksum is Invalid (%d)\n", sum);
//			continue;
		}

		return bios;
	}

	return NULL;
}
Example #17
0
/*
 * The function assumes that the following patterns have fixed sizes:
 * - "BeginString=" ("8=") is 2 bytes long
 * - "CheckSum=" ("10=") is 3 bytes long
 * - "MsgType=" ("35=") is 3 bytes long
 */
static int checksum(struct fix_message *self, struct buffer *buffer, unsigned long flags)
{
    const char *start;
    int offset;
    int ret;

    start = buffer_start(buffer);

    /* The number of bytes between tag MsgType and buffer's start */
    offset = start - (self->msg_type - 3);

    /*
     * Checksum tag and its trailing delimiter increase
     * the message's length by seven bytes - "10=***\x01"
     */
    if (buffer_size(buffer) + offset < self->body_length + 7) {
        ret = FIX_MSG_STATE_PARTIAL;
        goto exit;
    }

    if (flags & FIX_PARSE_FLAG_NO_CSUM) {
        ret = 0;
        goto exit;
    }

    /* Buffer's start will point to the CheckSum tag */
    buffer_advance(buffer, self->body_length - offset);

    ret = match_field(buffer, CheckSum, &self->check_sum);
    if (ret)
        goto exit;

    if (!verify_checksum(self, buffer)) {
        ret = FIX_MSG_STATE_GARBLED;
        goto exit;
    }

    /* Go back to analyze other fields */
    buffer_advance(buffer, start - buffer_start(buffer));

exit:
    return ret;
}
Example #18
0
bool unwrap(uint8_t& version, data_chunk& payload, uint32_t& checksum,
    data_slice wrapped)
{
    constexpr size_t version_length = sizeof(version);
    constexpr size_t checksum_length = sizeof(checksum);
    // guard against insufficient buffer length
    if (wrapped.size() < version_length + checksum_length)
        return false;
    if (!verify_checksum(wrapped))
        return false;
    // set return values
    version = wrapped.data()[0];
    payload = data_chunk(wrapped.begin() + version_length,
        wrapped.end() - checksum_length);
    const auto checksum_start = wrapped.end() - checksum_length;
    auto deserial = make_deserializer(checksum_start, wrapped.end());
    checksum = deserial.read_4_bytes();
    return true;
}
Example #19
0
/* ---- */
int
main (int argc, char *argv[])
{
  if (argc < 2)
    {
      print_usage ();
      exit (1);
    }

  if (strcmp (argv[1], "vc") == 0)
    {
      verify_checksum (argc - 2, argv + 2);
    }
  else if (strcmp (argv[1], "datadump") == 0)
    {
      data_dump (argc - 2, argv + 2);
    }
  else if (strcmp (argv[1], "createlog") == 0)
    {
      createlog (argc - 2, argv + 2);
    }
  else if (strcmp (argv[1], "deletelog") == 0)
    {
      deletelog (argc - 2, argv + 2);
    }
  else if (strcmp (argv[1], "synclog") == 0)
    {
      synclog (argc - 2, argv + 2);
    }
  else if (strcmp (argv[1], "infomem") == 0)
    {
      infomem (argc - 2, argv + 2);
    }
  else
    {
      print_usage ();
      exit (1);
    }
}
Example #20
0
gboolean download_file_checksum(const gchar *target, const gchar *url,
		const RaucChecksum *checksum)
{
	g_autofree gchar *tmpname = NULL;
	g_autofree gchar *dir = NULL;
	g_autofree gchar *tmppath = NULL;
	gboolean res = FALSE;

	tmpname = g_strdup_printf(".rauc_%s_%"G_GSIZE_FORMAT, checksum->digest,
			checksum->size);
	dir = g_path_get_dirname(target);
	tmppath = g_build_filename(dir, tmpname, NULL);

	g_unlink(target);
	g_unlink(tmppath);

	if (g_file_test(target, G_FILE_TEST_EXISTS))
		goto out;
	if (g_file_test(tmppath, G_FILE_TEST_EXISTS))
		goto out;

	res = download_file(tmppath, url, checksum->size, NULL);
	if (!res)
		goto out;

	res = verify_checksum(checksum, tmppath, NULL);
	if (!res)
		goto out;

	res = (g_rename(tmppath, target) == 0);
	if (!res)
		goto out;

out:
	return res;
}
Example #21
0
bool hd_public_key::set_encoded(const std::string& encoded)
{
    data_chunk decoded;
    if (!decode_base58(decoded, encoded))
        return false;
    if (decoded.size() != serialized_length)
        return false;
    if (!verify_checksum(decoded))
        return false;

    auto ds = make_deserializer(decoded.begin(), decoded.end());
    auto prefix = ds.read_big_endian<uint32_t>();
    if (prefix != mainnet_public_prefix && prefix != testnet_public_prefix)
        return false;

    valid_ = true;
    lineage_.testnet = prefix == testnet_public_prefix;
    lineage_.depth = ds.read_byte();
    lineage_.parent_fingerprint = ds.read_little_endian<uint32_t>();
    lineage_.child_number = ds.read_big_endian<uint32_t>();
    c_ = ds.read_bytes<chain_code_size>();
    K_ = ds.read_data(33);
    return true;
}
Example #22
0
MTK_NFC_CHIP_TYPE_E msr_nfc_get_chip_type(void)
{
    MTK_NFC_CHIP_TYPE_E eChipType = MTK_NFC_CHIP_TYPE_UNKNOW;
    unsigned char cmd_get_version[] = { 0x05, 0x01, 0x00, 0x06, 0x00};
    unsigned char response_buffer[ MSR3110_READ_BUF_SIZE_MAX] = {0};
    
    int result = 0;
    int pinVal = 0;
    //return eChipType; // test
    /* TRY MSR3110*/
    //////////////////////////////////////////////////////////////////
    //(1) open device node
    handle = open(DevNode_msr3110, O_RDWR | O_NOCTTY);    
    if (handle < 0)
    {
        #ifdef DEBUG_LOG
        ALOGD("OpenDeviceFail,eChipType,%d",eChipType); 
        #endif      
        return 	eChipType;	
    }
    //(1.1) init msr3110
    pinVal = 1;
    ioctl( handle, MSR3110_IOCTL_SET_VEN, ( int)&pinVal);
    //pinVal = 0;
    //ioctl( handle, MSR3110_IOCTL_SET_RST, ( int)&pinVal);    
    usleep( 300000);    
    
    //(2) get chip version
    result = ioctl( handle, MSR3110_IOCTL_CHIP_DETECT, (int)&pinVal);
	
    #ifdef DEBUG_LOG
    ALOGD("MSR3110_IOCTL_CHIP_DETECT = %d", result);
    #endif
    
    if (result == 1) {
        eChipType = MTK_NFC_CHIP_TYPE_MSR3110;
    } else {
        return eChipType;        
    } 

#if 0    
    //(2) get  version sart
    //(2.1) write command
    result = msr_nfc_interface_send( handle, cmd_get_version,  sizeof(cmd_get_version));
    if( result < 0) {
        #ifdef DEBUG_LOG
        ALOGD( "%s: Fail : send command (%d)", __FUNCTION__, result);
        #endif
        return eChipType;
    }   
    usleep( 50000);

    //(2.2) receive response
    result = msr_nfc_interface_recv( handle, response_buffer, MSR3110_READ_BUF_SIZE_MAX);
    if( result < 0) {
        #ifdef DEBUG_LOG
        ALOGD( "%s: Fail : recv command (%d)", __FUNCTION__, result); 
        #endif
        return eChipType;       
    }   
 
    //(2.3) set eChipType
    //(2.3.1) verify checksum
    if (verify_checksum(response_buffer, response_buffer[1] + 2) == 0)
    {
        #ifdef DEBUG_LOG
        ALOGD( "%s: Fail : checksum error", __FUNCTION__);
        #endif    
        return eChipType;
    }

    //(2.3.2) verify return code and length
    if (response_buffer[0] == 0x02 && response_buffer[1] == 0x0B)
    {
        eChipType = MTK_NFC_CHIP_TYPE_MSR3110;
        #ifdef DEBUG_LOG
        ALOGD( "%s: Mount MSR3110 Driver", __FUNCTION__);
        #endif
        ioctl( handle, MSR3110_IOCTL_IRQ_REG, 0);
    }
#endif
	//can not power off for SWP Init
#if 0    
    //(3) power off MSR3110    
    pinVal = 0;
    ioctl( handle, MSR3110_IOCTL_SET_VEN, ( int)&pinVal);
    usleep( 200000);
#endif
	close( handle);
    //////////////////////////////////////////////////////////////////
    /* TRY MSR3110 END*/ 

    #ifdef DEBUG_LOG
    ALOGD("eChipType,%d",eChipType);
    #endif
    
    return eChipType;

}
/* Extract a tar archive. */
static void
untar(FILE *a, const char *path)
{
	char buff[512];
	FILE *f = NULL;
	size_t bytes_read;
	int filesize;
	char *fullPath = NULL;

	printf("Extracting from %s\n", path);
	for (;;) {
		bytes_read = fread(buff, 1, 512, a);
		if (bytes_read < 512) {
			fprintf(stderr,
			    "Short read on %s: expected 512, got %d\n",
			    path, (int)bytes_read);
			return;
		}
		if (is_end_of_archive(buff)) {
			printf("End of %s\n", path);
			return;
		}
		if (!verify_checksum(buff)) {
			fprintf(stderr, "Checksum failure\n");
			return;
		}
		filesize = parseoct(buff + 124, 12);
		switch (buff[156]) {
		case '1':
			printf(" Ignoring hardlink %s\n", buff);
			break;
		case '2':
			printf(" Ignoring symlink %s\n", buff);
			break;
		case '3':
			printf(" Ignoring character device %s\n", buff);
				break;
		case '4':
			printf(" Ignoring block device %s\n", buff);
			break;
		case '5':
			printf(" Extracting dir %s\n", buff);
			fullPath = string_concat(3, basePath, "/", buff);
			create_dir(fullPath, parseoct(buff + 100, 8));
			free(fullPath);
			filesize = 0;
			break;
		case '6':
			printf(" Ignoring FIFO %s\n", buff);
			break;
		default:
			printf(" Extracting file %s\n", buff);
			fullPath = string_concat(3, basePath, "/", buff);
			f = create_file(fullPath, parseoct(buff + 100, 8));
			free(fullPath);
			break;
		}
		while (filesize > 0) {
			bytes_read = fread(buff, 1, 512, a);
			if (bytes_read < 512) {
				fprintf(stderr,
				    "Short read on %s: Expected 512, got %d\n",
				    path, (int)bytes_read);
				return;
			}
			if (filesize < 512)
				bytes_read = filesize;
			if (f != NULL) {
				if (fwrite(buff, 1, bytes_read, f)
				    != bytes_read)
				{
					fprintf(stderr, "Failed write\n");
					fclose(f);
					f = NULL;
				}
			}
			filesize -= bytes_read;
		}
		if (f != NULL) {
			fclose(f);
			f = NULL;
		}
	}
}
Example #24
0
krb5_error_code KRB5_LIB_FUNCTION
krb5_rd_safe(krb5_context context,
	     krb5_auth_context auth_context,
	     const krb5_data *inbuf,
	     krb5_data *outbuf,
	     krb5_replay_data *outdata)
{
    krb5_error_code ret;
    KRB_SAFE safe;
    size_t len;

    krb5_data_zero(outbuf);

    if ((auth_context->flags &
	 (KRB5_AUTH_CONTEXT_RET_TIME | KRB5_AUTH_CONTEXT_RET_SEQUENCE)))
    {
	if (outdata == NULL) {
	    krb5_set_error_message(context, KRB5_RC_REQUIRED,
				   N_("rd_safe: need outdata "
				      "to return data", ""));
	    return KRB5_RC_REQUIRED; /* XXX better error, MIT returns this */
	}
	/* if these fields are not present in the safe-part, silently
           return zero */
	memset(outdata, 0, sizeof(*outdata));
    }

    ret = decode_KRB_SAFE (inbuf->data, inbuf->length, &safe, &len);
    if (ret)
	return ret;
    if (safe.pvno != 5) {
	ret = KRB5KRB_AP_ERR_BADVERSION;
	krb5_clear_error_message (context);
	goto failure;
    }
    if (safe.msg_type != krb_safe) {
	ret = KRB5KRB_AP_ERR_MSG_TYPE;
	krb5_clear_error_message (context);
	goto failure;
    }
    if (!krb5_checksum_is_keyed(context, safe.cksum.cksumtype)
	|| !krb5_checksum_is_collision_proof(context, safe.cksum.cksumtype)) {
	ret = KRB5KRB_AP_ERR_INAPP_CKSUM;
	krb5_clear_error_message (context);
	goto failure;
    }

    /* check sender address */

    if (safe.safe_body.s_address
	&& auth_context->remote_address
	&& !krb5_address_compare (context,
				  auth_context->remote_address,
				  safe.safe_body.s_address)) {
	ret = KRB5KRB_AP_ERR_BADADDR;
	krb5_clear_error_message (context);
	goto failure;
    }

    /* check receiver address */

    if (safe.safe_body.r_address
	&& auth_context->local_address
	&& !krb5_address_compare (context,
				  auth_context->local_address,
				  safe.safe_body.r_address)) {
	ret = KRB5KRB_AP_ERR_BADADDR;
	krb5_clear_error_message (context);
	goto failure;
    }

    /* check timestamp */
    if (auth_context->flags & KRB5_AUTH_CONTEXT_DO_TIME) {
	krb5_timestamp sec;

	krb5_timeofday (context, &sec);

	if (safe.safe_body.timestamp == NULL ||
	    safe.safe_body.usec      == NULL ||
	    abs(*safe.safe_body.timestamp - sec) > context->max_skew) {
	    ret = KRB5KRB_AP_ERR_SKEW;
	    krb5_clear_error_message (context);
	    goto failure;
	}
    }
    /* XXX - check replay cache */

    /* check sequence number. since MIT krb5 cannot generate a sequence
       number of zero but instead generates no sequence number, we accept that
    */

    if (auth_context->flags & KRB5_AUTH_CONTEXT_DO_SEQUENCE) {
	if ((safe.safe_body.seq_number == NULL
	     && auth_context->remote_seqnumber != 0)
	    || (safe.safe_body.seq_number != NULL
		&& *safe.safe_body.seq_number !=
		auth_context->remote_seqnumber)) {
	    ret = KRB5KRB_AP_ERR_BADORDER;
	    krb5_clear_error_message (context);
	    goto failure;
	}
	auth_context->remote_seqnumber++;
    }

    ret = verify_checksum (context, auth_context, &safe);
    if (ret)
	goto failure;

    outbuf->length = safe.safe_body.user_data.length;
    outbuf->data   = malloc(outbuf->length);
    if (outbuf->data == NULL && outbuf->length != 0) {
	ret = ENOMEM;
	krb5_set_error_message(context, ret, N_("malloc: out of memory", ""));
	krb5_data_zero(outbuf);
	goto failure;
    }
    memcpy (outbuf->data, safe.safe_body.user_data.data, outbuf->length);

    if ((auth_context->flags &
	 (KRB5_AUTH_CONTEXT_RET_TIME | KRB5_AUTH_CONTEXT_RET_SEQUENCE))) {

	if(safe.safe_body.timestamp)
	    outdata->timestamp = *safe.safe_body.timestamp;
	if(safe.safe_body.usec)
	    outdata->usec = *safe.safe_body.usec;
	if(safe.safe_body.seq_number)
	    outdata->seq = *safe.safe_body.seq_number;
    }

  failure:
    free_KRB_SAFE (&safe);
    return ret;
}
Example #25
0
KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
krb5_pac_verify(krb5_context context,
		const krb5_pac pac,
		time_t authtime,
		krb5_const_principal principal,
		const krb5_keyblock *server,
		const krb5_keyblock *privsvr)
{
    krb5_error_code ret;

    if (pac->server_checksum == NULL) {
	krb5_set_error_message(context, EINVAL, "PAC missing server checksum");
	return EINVAL;
    }
    if (pac->privsvr_checksum == NULL) {
	krb5_set_error_message(context, EINVAL, "PAC missing kdc checksum");
	return EINVAL;
    }
    if (pac->logon_name == NULL) {
	krb5_set_error_message(context, EINVAL, "PAC missing logon name");
	return EINVAL;
    }

    ret = verify_logonname(context,
			   pac->logon_name,
			   &pac->data,
			   authtime,
			   principal);
    if (ret)
	return ret;

    /*
     * in the service case, clean out data option of the privsvr and
     * server checksum before checking the checksum.
     */
    {
	krb5_data *copy;

	ret = krb5_copy_data(context, &pac->data, &copy);
	if (ret)
	    return ret;

	if (pac->server_checksum->buffersize < 4)
	    return EINVAL;
	if (pac->privsvr_checksum->buffersize < 4)
	    return EINVAL;

	memset((char *)copy->data + pac->server_checksum->offset_lo + 4,
	       0,
	       pac->server_checksum->buffersize - 4);

	memset((char *)copy->data + pac->privsvr_checksum->offset_lo + 4,
	       0,
	       pac->privsvr_checksum->buffersize - 4);

	ret = verify_checksum(context,
			      pac->server_checksum,
			      &pac->data,
			      copy->data,
			      copy->length,
			      server);
	krb5_free_data(context, copy);
	if (ret)
	    return ret;
    }
    if (privsvr) {
	/* The priv checksum covers the server checksum */
	ret = verify_checksum(context,
			      pac->privsvr_checksum,
			      &pac->data,
			      (char *)pac->data.data
			      + pac->server_checksum->offset_lo + 4,
			      pac->server_checksum->buffersize - 4,
			      privsvr);
	if (ret)
	    return ret;
    }

    return 0;
}
Example #26
0
int main(int argc, char* argv[])
{
    FILE* file;
    int arg_index;
    char* buf = 0;
    const unsigned int bufsize = 256;
    const char* tokens[32];
    const int len = sizeof tokens / sizeof tokens[0];
    int token_count;
    struct GGA* gga;
    struct GNS* gns;
    struct GSA* gsa;
    struct RMC* rmc;

    buf = malloc(bufsize);
    if (!buf) {
        goto exit;
    }

    for (arg_index=1; arg_index<argc; ++arg_index) {
        file = fopen(argv[arg_index], "r");
        if (!file) {
            continue;
        }

        while (fgets(buf, bufsize, file)) {
            if (strlen(buf) < 10) continue;

            if (!verify_checksum(buf)) break;


            fprintf(stdout, "%s", buf);

            token_count =  tokenize(buf, tokens, len);

            if (0 !=(gga = parse_gga(tokens, token_count))) {
                fprintf(stdout, "   GGA %02d:%02d:%02d %.6f , %.6f %d, %d, %.2f, %.1f(%s), %.1f(%s) \n",
                        gga->hour, gga->min, gga->sec, gga->lat, gga->lon, gga->quality, gga->sat_count, gga->hdop, gga->altitude, tokens[10], gga->geoid_height, tokens[12]);

                free(gga);
            }
            else if (0 != (gns = parse_gns(tokens, token_count))) {
                fprintf(stdout, "   GNS %02d:%02d:%02d %.6f , %.6f %s, %d, %.2f, %.1f(%s), %.1f(%s) \n",
                        gns->hour, gns->min, gns->sec, gns->lat, gns->lon, gns->mode, gns->sat_count, gns->hdop, gns->altitude, "m", gns->geoid_height, "m");

                free(gns);
            }
            else if (0 != (gsa = parse_gsa(tokens, token_count))) {
                int i;
                int prn;

                fprintf(stdout, "   GSA %c, %d, ", gsa->mode, gsa->fix_type);
                i = 0;
                while (i<12 && 0 != (prn = gsa->prn[i])) {
                    fprintf(stdout,"%d, ", prn);
                    ++i;
                }
                fprintf(stdout, "%.1f, %.1f, %.1f\n", gsa->pdop, gsa->hdop, gsa->vdop);

                free(gsa);
            }
            else if (0 != (rmc = parse_rmc(tokens, token_count))) {
                    fprintf(stdout, "   RMC %02d:%02d:%02d  %.6f , %.6f  %.1f(knots), %.1f(degrees) %02d-%02d-%02d\n",
                            rmc->hour, rmc->min, rmc->sec, rmc->lat, rmc->lon, rmc->speed, rmc->heading, rmc->day, rmc->month, rmc->year);

                    free(rmc);
            } 
        } // while

        fclose(file);
    }

exit: 
    if (buf) {
        free(buf);
    }
    return 0;
}
Example #27
0
/* Handle IP packet */
void sr_handle_ippacket(struct sr_instance* sr,
        uint8_t * packet/* lent */,
        unsigned int len,
        char* interface/* lent */) 
{
    assert(sr);
    assert(packet);
    assert(interface);

    /* Get ethernet header */
    sr_ethernet_hdr_t *eth_hdr = get_eth_hdr(packet);
	if (eth_hdr == NULL) {
		printf("ethernet header NULL!!!\n");
		return;
	}

    /* Get ip header */
    sr_ip_hdr_t *ip_hdr = get_ip_hdr(packet);
	if (ip_hdr == NULL) {
		printf("ip header NULL!!!\n");
		return;
	}

	/* Before doing ttl decrement, check checksum */
	uint16_t old_ip_sum = ip_hdr->ip_sum;
	ip_hdr->ip_sum = 0;

	if (!verify_checksum(ip_hdr, sizeof(sr_ip_hdr_t), old_ip_sum)) {
		fprintf(stderr, "CHECKSUM FAILED!!\n");
		return;
	}
	ip_hdr->ip_sum = old_ip_sum;

    /* Get the arp cache */
    struct sr_arpcache *sr_arp_cache = &sr->cache;

    /* Get the destination interface on the router */
	struct sr_if *sr_iface = sr_get_router_if(sr, ip_hdr->ip_dst);
	/* Get the connected interface on the router */
	struct sr_if *sr_con_if = sr_get_interface(sr, interface);

    /* Check the time exceeded condition, if ttl==0, we need to form icmp 11 and send back */
    if (ip_hdr->ip_ttl <= 1) {
        /* time exceeded message and icmp type 11 */
        printf("TTL time exceeded\n");
        int packet_len = ICMP_T3_PACKET_LEN;
        uint8_t *icmp_t3_hdr = (uint8_t *)malloc(packet_len);

        create_ethernet_hdr(eth_hdr, (sr_ethernet_hdr_t *)icmp_t3_hdr, sr_con_if);
        /* Create ip header */
        create_echo_ip_hdr(ip_hdr, (sr_ip_hdr_t *)((char *)icmp_t3_hdr+ETHER_PACKET_LEN), sr_con_if);

        /* Send icmp type 11 time exceeded */
        /* icmp_t3 type=11, code=0 */
        create_icmp_t3_hdr(ip_hdr, (sr_icmp_t3_hdr_t *)((char *)icmp_t3_hdr+IP_PACKET_LEN), 11, 0);

        /* Send icmp type 11 packet */
		struct sr_arpentry *arp_entry = sr_arpcache_lookup(sr_arp_cache, ip_hdr->ip_src);
		if (arp_entry != NULL) {
			sr_send_packet(sr, icmp_t3_hdr, packet_len, sr_con_if->name);
			free(icmp_t3_hdr);
		} else {
			struct sr_arpreq *arp_req = sr_arpcache_queuereq(sr_arp_cache, ip_hdr->ip_src, icmp_t3_hdr, packet_len, sr_con_if->name);
			handle_arpreq(arp_req, sr);
		}
        return;
    }

    /* Get the protocol from IP */
    uint8_t ip_p = ip_hdr->ip_p;

    /* If the packet is sent to self, meaning the ip is sent to the router */
    if (sr_iface) {
        /* Check the protocol if it is icmp */
        if (ip_p == ip_protocol_icmp) {
            /* Get the icmp header */
            sr_icmp_hdr_t *icmp_hdr = get_icmp_hdr(packet);

            /* Check if it is ICMP echo request */
            /* icmp_echo_req = 8 */
            if (icmp_hdr->icmp_type == 8) {
				/* Do LPM on the routing table */
        		/* Check the routing table and see if the incoming ip matches the routing table ip, and find LPM router entry */
        		struct sr_rt *longest_pref_match = sr_lpm(sr, ip_hdr->ip_src);

				if (longest_pref_match) {
					/* check ARP cache */
					struct sr_arpentry *arp_entry = sr_arpcache_lookup(&sr->cache, longest_pref_match->gw.s_addr);
					struct sr_if *out_iface = sr_get_interface(sr, longest_pref_match->interface);

					/* If hit, meaning the arp mapping has been cached */
					if (arp_entry != NULL) {
						/* We need to send the icmp echo reply */
				        /* Modify ethernet header */
						memcpy(eth_hdr->ether_dhost, eth_hdr->ether_shost, ETHER_ADDR_LEN);
						memcpy(eth_hdr->ether_shost, out_iface->addr, ETHER_ADDR_LEN);

				        /* Modify ip header */
						ip_hdr->ip_off = htons(0b0100000000000000);        /* fragment offset field */
						ip_hdr->ip_ttl = 100;                    			/* time to live */
						uint32_t temp = ip_hdr->ip_src;
						ip_hdr->ip_src = ip_hdr->ip_dst;        /* source address */
						ip_hdr->ip_dst = temp;        			/* dest address */
						ip_hdr->ip_sum = 0;
						ip_hdr->ip_sum = cksum(ip_hdr, sizeof(sr_ip_hdr_t));			/* checksum */

				        /* Modify icmp header */
						unsigned int icmp_whole_size = len - IP_PACKET_LEN;
						icmp_hdr->icmp_type = 0;
						icmp_hdr->icmp_code = 0;
						icmp_hdr->icmp_sum = 0;
						icmp_hdr->icmp_sum = cksum(icmp_hdr, icmp_whole_size);

				        /* Send icmp echo reply */
				        sr_send_packet(sr, packet, len, out_iface->name);
				        return;
					}
					/* Else no hit, we cache it to the queue and send arp request */ 
					else {
						/* Add reply to the ARP queue */
						/* We need to send the icmp echo reply */
				        /* Modify ethernet header */
						memcpy(eth_hdr->ether_dhost, eth_hdr->ether_shost, ETHER_ADDR_LEN);
						memcpy(eth_hdr->ether_shost, sr_con_if->addr, ETHER_ADDR_LEN);

				        /* Modify ip header */
						ip_hdr->ip_off = htons(0b0100000000000000);        /* fragment offset field */
						ip_hdr->ip_ttl = 100;                    			/* time to live */
						uint32_t temp = ip_hdr->ip_src;
						ip_hdr->ip_src = ip_hdr->ip_dst;        /* source address */
						ip_hdr->ip_dst = temp;        			/* dest address */
						ip_hdr->ip_sum = 0;
						ip_hdr->ip_sum = cksum(ip_hdr, sizeof(sr_ip_hdr_t));			/* checksum */

				        /* Modify icmp header */
						unsigned int icmp_whole_size = len - IP_PACKET_LEN;
						icmp_hdr->icmp_type = 0;
						icmp_hdr->icmp_code = 0;
						icmp_hdr->icmp_sum = 0;
						icmp_hdr->icmp_sum = cksum(icmp_hdr, icmp_whole_size);
						struct sr_arpreq *arp_req = sr_arpcache_queuereq(sr_arp_cache, ip_hdr->ip_dst, packet, len, out_iface->name);
						/* Send ARP request, which is a broadcast */
						handle_arpreq(arp_req, sr);
						return;
					}
				} else {
					fprintf(stderr, "Longest prefix doesnt match!!\n");
                	return;
				}

            } else {
                fprintf(stderr, "Not an ICMP request!\n");
                return;
            }
        }
        /* Else it is TCP/UDP request */
        else {
            fprintf(stderr, "*** -> Received TCP/UDP!\n");

			/* Do LPM on the routing table */
    		/* Check the routing table and see if the incoming ip matches the routing table ip, and find LPM router entry */
    		struct sr_rt *longest_pref_match = sr_lpm(sr, ip_hdr->ip_src);

			if (longest_pref_match) {
				/* check ARP cache */
				struct sr_arpentry *arp_entry = sr_arpcache_lookup(&sr->cache, longest_pref_match->gw.s_addr);
				struct sr_if *out_iface = sr_get_interface(sr, longest_pref_match->interface);
				
				/* Send ICMP port unreachable */
				if (arp_entry != NULL) {

					int packet_len = ICMP_T3_PACKET_LEN;
				    uint8_t *icmp_t3_hdr = (uint8_t *)malloc(packet_len);

				    /* Create ethernet header */
				    create_ethernet_hdr(eth_hdr, (sr_ethernet_hdr_t *)icmp_t3_hdr, sr_iface);
					/*memcpy(((sr_ethernet_hdr_t *)icmp_t3_hdr)->ether_dhost, eth_hdr->ether_shost, ETHER_ADDR_LEN);
					memcpy(((sr_ethernet_hdr_t *)icmp_t3_hdr)->ether_shost, eth_hdr->ether_dhost, ETHER_ADDR_LEN);*/

				    /* Create ip header */
				    create_echo_ip_hdr(ip_hdr, (sr_ip_hdr_t *)((char *)icmp_t3_hdr+ETHER_PACKET_LEN), sr_iface);
					/*sr_ip_hdr_t *icmp_t3_hdr_ip = (sr_ip_hdr_t *)((char *)icmp_t3_hdr+ETHER_PACKET_LEN);
					icmp_t3_hdr_ip->ip_src = ip_hdr->ip_dst;
					icmp_t3_hdr_ip->ip_sum = 0;
					icmp_t3_hdr_ip->ip_sum = cksum(icmp_t3_hdr_ip, sizeof(sr_ip_hdr_t));*/
					

					/* Should update source address to be interface address */

				    /* Send icmp type 3 port unreachable */
				    /* Create icmp port unreachable packet */
				    /* icmp_t3 type=3, code=3 */
				    create_icmp_t3_hdr(ip_hdr, (sr_icmp_t3_hdr_t *)((char *)icmp_t3_hdr+IP_PACKET_LEN), 3, 3);

				    /* Send icmp type 3 packet */
				    sr_send_packet(sr, icmp_t3_hdr, packet_len, out_iface->name);

				    free(icmp_t3_hdr);
				    return;
				} else {
				
					int packet_len = ICMP_T3_PACKET_LEN;
				    uint8_t *icmp_t3_hdr = (uint8_t *)malloc(packet_len);

				    /* Create ethernet header */
				    create_ethernet_hdr(eth_hdr, (sr_ethernet_hdr_t *)icmp_t3_hdr, sr_iface);
					/*memcpy(((sr_ethernet_hdr_t *)icmp_t3_hdr)->ether_dhost, eth_hdr->ether_shost, ETHER_ADDR_LEN);
					memcpy(((sr_ethernet_hdr_t *)icmp_t3_hdr)->ether_shost, eth_hdr->ether_dhost, ETHER_ADDR_LEN);*/

				    /* Create ip header */
				    create_echo_ip_hdr(ip_hdr, (sr_ip_hdr_t *)((char *)icmp_t3_hdr+ETHER_PACKET_LEN), sr_iface);
					/*sr_ip_hdr_t *icmp_t3_hdr_ip = (sr_ip_hdr_t *)((char *)icmp_t3_hdr+ETHER_PACKET_LEN);
					icmp_t3_hdr_ip->ip_src = ip_hdr->ip_dst;
					icmp_t3_hdr_ip->ip_sum = 0;
					icmp_t3_hdr_ip->ip_sum = cksum(icmp_t3_hdr_ip, sizeof(sr_ip_hdr_t));*/

				    /* Send icmp type 3 port unreachable */
				    /* Create icmp port unreachable packet */
				    /* icmp_t3 type=3, code=3 */
				    create_icmp_t3_hdr(ip_hdr, (sr_icmp_t3_hdr_t *)((char *)icmp_t3_hdr+IP_PACKET_LEN), 3, 3);

					struct sr_arpreq *arp_req = sr_arpcache_queuereq(sr_arp_cache, ip_hdr->ip_src, icmp_t3_hdr, packet_len, out_iface->name);
					/* Send ARP request, which is a broadcast */
					handle_arpreq(arp_req, sr);
					return;
				}
			} else {
				fprintf(stderr, "Longest prefix doesnt match!!\n");
                return;
			}            
            
        }
    }
    /* Else Check the routing table, perfomr LPM */
    else {
        /* Sanity-check the packet */
        /* minimum length */
        if (!check_min_length(len, IP_PACKET_LEN)) {
            fprintf(stderr, "The packet length is not enough:(\n");
            return;
        }
		
        /* Do LPM on the routing table */
        /* Check the routing table and see if the incoming ip matches the routing table ip, and find LPM router entry */
        struct sr_rt *longest_pref_match = sr_lpm(sr, ip_hdr->ip_dst);
        if (longest_pref_match) {
            /* check ARP cache */
			struct sr_if *out_iface = sr_get_interface(sr, longest_pref_match->interface);

            struct sr_arpentry *arp_entry = sr_arpcache_lookup(&sr->cache, longest_pref_match->gw.s_addr); /* ip_hdr->ip_dst */
         
			/* If hit, meaning the arp_entry is found */
            if (arp_entry) {

				/*fprintf(stderr, "************ found the lpm router entry ***********\n");*/
                /* Send frame to next hop */
                /* update the eth_hdr source and destination ethernet address */
                /* use next_hop_ip->mac mapping in the entry to send the packet */

                ip_hdr->ip_ttl--;

                /* recompute the packet checksum over the modified header */
                ip_hdr->ip_sum = 0;
                uint16_t new_ip_sum = cksum(ip_hdr, sizeof(sr_ip_hdr_t));
                ip_hdr->ip_sum = new_ip_sum;

                memcpy(eth_hdr->ether_shost, out_iface->addr, ETHER_ADDR_LEN);
                memcpy(eth_hdr->ether_dhost, arp_entry->mac, ETHER_ADDR_LEN);
                sr_send_packet(sr, packet, len, out_iface->name);
				print_hdr_ip((uint8_t*)ip_hdr);
                /* free the entry */
                free(arp_entry);
                return;
            } else/* No Hit */ {
                /* send an ARP request for the next-hop IP */
                /* add the packet to the queue of packets waiting on this ARP request */
                /* Add request to ARP queue*/

                ip_hdr->ip_ttl--;

                /* recompute the packet checksum over the modified header */
                ip_hdr->ip_sum = 0;
                uint16_t new_ip_sum = cksum(ip_hdr, sizeof(sr_ip_hdr_t));
                ip_hdr->ip_sum = new_ip_sum;

                struct sr_arpreq *arp_req = sr_arpcache_queuereq(sr_arp_cache, ip_hdr->ip_dst, packet, len, out_iface->name);
                /* send ARP request, this is a broadcast */
                handle_arpreq(arp_req, sr);
                return;
            }
        } else /* if not matched */ {
            /* Send ICMP net unreachable */
			printf("--------------- Net Unreachable ---------------\n");

			/* Do LPM on the routing table */
    		/* Check the routing table and see if the incoming ip matches the routing table ip, and find LPM router entry */
    		struct sr_rt *longest_pref_match = sr_lpm(sr, ip_hdr->ip_src);

			if (longest_pref_match) {
				/* check ARP cache */
				struct sr_arpentry *arp_entry = sr_arpcache_lookup(&sr->cache, longest_pref_match->gw.s_addr);
				struct sr_if *out_iface = sr_get_interface(sr, longest_pref_match->interface);

				if (arp_entry) {
					int packet_len = ICMP_T3_PACKET_LEN;
				    uint8_t *icmp_t3_hdr = (uint8_t *)malloc(packet_len);

				    /* Create ethernet header */
				    create_ethernet_hdr(eth_hdr, (sr_ethernet_hdr_t *)icmp_t3_hdr, out_iface);

				    /* Create ip header */
				    create_echo_ip_hdr(ip_hdr, (sr_ip_hdr_t *)((char *)icmp_t3_hdr+ETHER_PACKET_LEN), out_iface);

				    /* Create icmp net unreachable */
				    /* icmp_t3 type=3, code=0 */
				    create_icmp_t3_hdr(ip_hdr, (sr_icmp_t3_hdr_t *)((char *)icmp_t3_hdr+IP_PACKET_LEN), 3, 0);

				    /* Send icmp type 3 packet */
				    sr_send_packet(sr, icmp_t3_hdr, packet_len, out_iface->name);

				    free(icmp_t3_hdr);
				    return;
				} else {

					int packet_len = ICMP_T3_PACKET_LEN;
				    uint8_t *icmp_t3_hdr = (uint8_t *)malloc(packet_len);

				    /* Create ethernet header */
				    create_ethernet_hdr(eth_hdr, (sr_ethernet_hdr_t *)icmp_t3_hdr, out_iface);

				    /* Create ip header */
				    create_echo_ip_hdr(ip_hdr, (sr_ip_hdr_t *)((char *)icmp_t3_hdr+ETHER_PACKET_LEN), out_iface);
					/*	((sr_ip_hdr_t *)((char *)icmp_t3_hdr+ETHER_PACKET_LEN))->ip_ttl += 1; */

				    /* Send icmp type 3 net unreachable */
				    /* Create icmp net unreachable packet */
				    /* icmp_t3 type=3, code=0 */
				    create_icmp_t3_hdr(ip_hdr, (sr_icmp_t3_hdr_t *)((char *)icmp_t3_hdr+IP_PACKET_LEN), 3, 0);

					struct sr_arpreq *arp_req = sr_arpcache_queuereq(sr_arp_cache, ip_hdr->ip_src, icmp_t3_hdr, packet_len, out_iface->name);
					/* Send ARP request, which is a broadcast */
					handle_arpreq(arp_req, sr);
					return;
				}
			} else {
				fprintf(stderr, "Longest prefix doesnt match!!\n");
                return;
			}
        }
    }

    return;
}
Example #28
0
FILE *
curlfopen(struct repoinfo *cinfo, const char *file, int uncompress, const unsigned char *chksum, Id chksumtype, int markincomplete)
{
  FILE *fp;
  pid_t pid;
  int fd;
  int status;
  char url[4096];
  const char *baseurl = cinfo->baseurl;

  if (!baseurl)
    {
      if (!cinfo->metalink && !cinfo->mirrorlist)
        return 0;
      if (file != cinfo->metalink && file != cinfo->mirrorlist)
	{
	  unsigned char mlchksum[32];
	  Id mlchksumtype = 0;
	  fp = curlfopen(cinfo, cinfo->metalink ? cinfo->metalink : cinfo->mirrorlist, 0, 0, 0, 0);
	  if (!fp)
	    return 0;
	  if (cinfo->metalink)
	    cinfo->baseurl = findmetalinkurl(fp, mlchksum, &mlchksumtype);
	  else
	    cinfo->baseurl = findmirrorlisturl(fp);
	  fclose(fp);
	  if (!cinfo->baseurl)
	    return 0;
#if defined(FEDORA) || defined(MAGEIA)
	  if (strchr(cinfo->baseurl, '$'))
	    {
	      char *b = yum_substitute(cinfo->repo->pool, cinfo->baseurl);
	      free(cinfo->baseurl);
	      cinfo->baseurl = strdup(b);
	    }
#endif
	  if (!chksumtype && mlchksumtype && !strcmp(file, "repodata/repomd.xml"))
	    {
	      chksumtype = mlchksumtype;
	      chksum = mlchksum;
	    }
	  return curlfopen(cinfo, file, uncompress, chksum, chksumtype, markincomplete);
	}
      snprintf(url, sizeof(url), "%s", file);
    }
  else
    {
      const char *path = cinfo->path && strcmp(cinfo->path, "/") != 0 ? cinfo->path : "";
      int l = strlen(baseurl);
      int pl = strlen(path);
      const char *sep = l && baseurl[l - 1] == '/' ? "" : "/";
      const char *psep = pl && cinfo->path[pl - 1] == '/' ? "" : "/";
      snprintf(url, sizeof(url), "%s%s%s%s%s", baseurl, sep, path, psep, file);
    }
  fd = opentmpfile();
  // printf("url: %s\n", url);
  if ((pid = fork()) == (pid_t)-1)
    {
      perror("fork");
      exit(1);
    }
  if (pid == 0)
    {
      if (fd != 1)
	{
          dup2(fd, 1);
	  close(fd);
	}
      execlp("curl", "curl", "-f", "-s", "-L", url, (char *)0);
      perror("curl");
      _exit(0);
    }
  status = 0;
  while (waitpid(pid, &status, 0) != pid)
    ;
  if (lseek(fd, 0, SEEK_END) == 0 && (!status || !chksumtype))
    {
      /* empty file */
      close(fd);
      return 0;
    }
  lseek(fd, 0, SEEK_SET);
  if (status)
    {
      printf("%s: download error %d\n", file, status >> 8 ? status >> 8 : status);
      if (markincomplete)
	cinfo->incomplete = 1;
      close(fd);
      return 0;
    }
  if (chksumtype && !verify_checksum(fd, file, chksum, chksumtype))
    {
      if (markincomplete)
	cinfo->incomplete = 1;
      close(fd);
      return 0;
    }
  fcntl(fd, F_SETFD, FD_CLOEXEC);
  if (uncompress)
    {
      if (solv_xfopen_iscompressed(file) < 0)
	{
	  printf("%s: unsupported compression\n", file);
	  if (markincomplete)
	    cinfo->incomplete = 1;
	  close(fd);
	  return 0;
	}
      fp = solv_xfopen_fd(file, fd, "r");
    }
  else
    fp = fdopen(fd, "r");
  if (!fp)
    close(fd);
  return fp;
}
Example #29
0
/* Extract a tar archive. */
void
untar(FILE *a, const char *path)
{
#ifdef ASSET_VERBOSE
    printf("==== storm untar v1.1.2 ====\n");
    clock_t start = clock() / (CLOCKS_PER_SEC / 1000);
    printf("unpacking archive..\n");
#endif
    
	char buff[512];
	FILE *f = NULL;
	size_t bytes_read;
	int filesize;
    
	for (;;) {
		bytes_read = fread(buff, 1, 512, a);
		if (bytes_read < 512) {
#ifdef ASSET_VERBOSE
			fprintf(stderr,
                    "Short read: expected 512, got %d\n", (int)bytes_read);
#endif
			return;
		}
		if (is_end_of_archive(buff)) {
#ifdef ASSET_VERBOSE
            printf("===== completed in %lums ======\n", (clock() / (CLOCKS_PER_SEC / 1000)) - start);
#endif
			return;
		}
		if (!verify_checksum(buff)) {
#ifdef ASSET_VERBOSE
			fprintf(stderr, "Checksum failure\n");
#endif
			return;
		}
		filesize = parseoct(buff + 124, 12);
        
        char *filepath = malloc(sizeof(buff) + sizeof(path) + sizeof("/"));
        if (filepath) {
            strcpy(filepath, path);
            strcat(filepath, "/");
            strcat(filepath, buff);
        }
        
		switch (buff[156]) {
            case '1':
//                printf("> Ignoring hardlink %s\n", buff);
                break;
            case '2':
//                printf("> Ignoring symlink %s\n", buff);
                break;
            case '3':
//                printf("> Ignoring character device %s\n", buff);
				break;
            case '4':
//                printf("> Ignoring block device %s\n", buff);
                break;
            case '5':
                create_dir(filepath, parseoct(buff + 100, 8));
                filesize = 0;
                break;
            case '6':
//                printf("> Ignoring FIFO %s\n", buff);
                break;
            default:
#ifdef ASSET_VERBOSE
                printf("> %s\n", buff);
#endif
                f = create_file(filepath, parseoct(buff + 100, 8));
                break;
		}
		while (filesize > 0) {
			bytes_read = fread(buff, 1, 512, a);
			if (bytes_read < 512) {
#ifdef ASSET_VERBOSE
				fprintf(stderr,
                        "Short read on %s: Expected 512, got %d\n",
                        path, (int)bytes_read);
#endif  
                if (filepath != NULL) free(filepath); // Clear up any memory left for the file path
				return;
			}
			if (filesize < 512)
				bytes_read = filesize;
			if (f != NULL) {
				if (fwrite(buff, 1, bytes_read, f)
				    != bytes_read)
				{
#ifdef ASSET_VERBOSE
					fprintf(stderr, "Failed write\n");
					fclose(f);
					f = NULL;
#endif
				}
			}
			filesize -= bytes_read;
		}
		if (f != NULL) {
			fclose(f);
			f = NULL;
		}
        
        free(filepath);
	}
}
Example #30
0
static int
dumpchunk(char *name, char *buf, int chunkno, int checkindex)
{
    blockhdr_t *hdr;
    struct region *reg;
    uint32_t count;
    int i;

    hdr = (blockhdr_t *)buf;

    switch (hdr->magic) {
    case COMPRESSED_V1:
        reg = (struct region *)((struct blockhdr_V1 *)hdr + 1);
        break;
    case COMPRESSED_V2:
    case COMPRESSED_V3:
        reg = (struct region *)((struct blockhdr_V2 *)hdr + 1);
        break;
    case COMPRESSED_V4:
        reg = (struct region *)((struct blockhdr_V4 *)hdr + 1);
        if (chunkno > 0) {
            if (sigtype != hdr->csum_type) {
                printf("%s: wrong checksum type in chunk %d\n",
                       name, chunkno);
                return 1;
            }
            if (enctype != hdr->enc_cipher) {
                printf("%s: wrong cipher type in chunk %d\n",
                       name, chunkno);
                return 1;
            }
            if (memcmp(imageid, hdr->imageid, UUID_LENGTH)) {
                printf("%s: wrong image ID in chunk %d\n",
                       name, chunkno);
                return 1;
            }
        }
        if (checksums && hdr->csum_type != CSUM_NONE) {
            if ((hdr->csum_type & CSUM_TYPE) != CSUM_SHA1) {
                printf("%s: unsupported checksum type %d in "
                       "chunk %d", name,
                       (hdr->csum_type & CSUM_TYPE),
                       chunkno);
                return 1;
            }
        }
        break;
    default:
        printf("%s: bad magic (%x!=%x) in chunk %d\n",
               name, hdr->magic, magic, chunkno);
        return 1;
    }
    if (checkindex && hdr->blockindex != chunkno) {
        printf("%s: bad chunk index (%d) in chunk %d\n",
               name, hdr->blockindex, chunkno);
        return 1;
    }
    if (chunkcount && hdr->blocktotal != chunkcount) {
        printf("%s: bad chunkcount (%d!=%lu) in chunk %d\n",
               name, hdr->blocktotal, chunkcount, chunkno);
        return 1;
    }
    if (hdr->size > (CHUNKSIZE - hdr->regionsize)) {
        printf("%s: bad chunksize (%d > %d) in chunk %d\n",
               name, hdr->size, CHUNKSIZE-hdr->regionsize, chunkno);
        return 1;
    }
#if 1
    /* include header overhead */
    wasted += CHUNKSIZE - hdr->size;
#else
    wasted += ((CHUNKSIZE - hdr->regionsize) - hdr->size);
#endif
    if (regmin == 0 || hdr->regioncount < regmin)
        regmin = hdr->regioncount;
    if (regmax == 0 || hdr->regioncount > regmax)
        regmax = hdr->regioncount;

    if (detail > 0) {
        printf("  Chunk %d: %u compressed bytes, ",
               chunkno, hdr->size);
        if (hdr->magic > COMPRESSED_V1) {
            printf("sector range [%u-%u], ",
                   hdr->firstsect, hdr->lastsect-1);
            if (hdr->reloccount > 0)
                printf("%d relocs, ", hdr->reloccount);
        }
        printf("%d regions\n", hdr->regioncount);
        if (hdr->magic >= COMPRESSED_V4) {
            int len;

            if (hdr->csum_type != CSUM_NONE) {
                len = 0;
                switch (hdr->csum_type) {
                case CSUM_SIGNED|CSUM_SHA1:
                    len = CSUM_MAX_LEN;
                    break;
                case CSUM_SHA1:
                    len = CSUM_SHA1_LEN;
                    break;
                }
                if (len) {
                    char csumstr[CSUM_MAX_LEN*2+1];

                    mem_to_hexstr(csumstr,
                                  hdr->checksum, len);
                    printf("    Checksum: 0x%s", csumstr);
                }
                printf("\n");
            }

            if (hdr->enc_cipher != ENC_NONE) {
                len = 0;
                switch (hdr->enc_cipher) {
                case ENC_BLOWFISH_CBC:
                    len = ENC_MAX_KEYLEN;
                    break;
                }
                if (len) {
                    char ivstr[ENC_MAX_KEYLEN*2+1];

                    mem_to_hexstr(ivstr,
                                  hdr->enc_iv, len);
                    printf("    CipherIV: 0x%s", ivstr);
                }
                printf("\n");

            }
        }
    }

    if (hdr->regionsize != DEFAULTREGIONSIZE)
        printf("  WARNING: "
               "unexpected region size (%d!=%d) in chunk %d\n",
               hdr->regionsize, DEFAULTREGIONSIZE, chunkno);

    for (i = 0; i < hdr->regioncount; i++) {
        if (detail > 1)
            printf("    Region %d: %u sectors [%u-%u]\n",
                   i, reg->size, reg->start,
                   reg->start + reg->size - 1);
        if (reg->start < nextsector)
            printf("    WARNING: chunk %d region %d "
                   "may overlap others\n", chunkno, i);
        if (reg->size == 0)
            printf("    WARNING: chunk %d region %d "
                   "zero-length region\n", chunkno, i);
        count = 0;
        if (hdr->magic > COMPRESSED_V1) {
            if (i == 0) {
                if (hdr->firstsect > reg->start)
                    printf("    WARNING: chunk %d bad "
                           "firstsect value (%u>%u)\n",
                           chunkno, hdr->firstsect,
                           reg->start);
                else
                    count = reg->start - hdr->firstsect;
            } else
                count = reg->start - nextsector;
            if (i == hdr->regioncount-1) {
                if (hdr->lastsect < reg->start + reg->size)
                    printf("    WARNING: chunk %d bad "
                           "lastsect value (%u<%u)\n",
                           chunkno, hdr->lastsect,
                           reg->start + reg->size);
                else {
                    if (count > 0) {
                        sectfree += count;
                        if (count < fmin)
                            fmin = count;
                        if (count > fmax)
                            fmax = count;
                        franges++;
                    }
                    count = hdr->lastsect -
                            (reg->start+reg->size);
                }
            }
            if (hdr->firstsect < losect)
                losect = hdr->firstsect;
            if (hdr->lastsect > hisect)
                hisect = hdr->lastsect;
        } else
            count = reg->start - nextsector;
        if (count > 0) {
            sectfree += count;
            if (count < fmin)
                fmin = count;
            if (count > fmax)
                fmax = count;
            franges++;
        }

        count = reg->size;
        sectinuse += count;
        if (count < amin)
            amin = count;
        if (count > amax)
            amax = count;
        if (count < 8)
            adist[0]++;
        else if (count < 16)
            adist[1]++;
        else if (count < 32)
            adist[2]++;
        else if (count < 64)
            adist[3]++;
        else if (count < 128)
            adist[4]++;
        else if (count < 256)
            adist[5]++;
        else if (count < 512)
            adist[6]++;
        else
            adist[7]++;
        aranges++;

        if (dumpmap) {
            switch (hdr->magic) {
            case COMPRESSED_V1:
                if (reg->start - nextsector != 0)
                    printf("F: [%08x-%08x]\n",
                           nextsector, reg->start-1);
                printf("A: [%08x-%08x]\n",
                       reg->start, reg->start + reg->size - 1);
                break;
            case COMPRESSED_V2:
            case COMPRESSED_V3:
                if (i == 0 && hdr->firstsect < reg->start)
                    printf("F: [%08x-%08x]\n",
                           hdr->firstsect, reg->start-1);
                if (i != 0 && reg->start - nextsector != 0)
                    printf("F: [%08x-%08x]\n",
                           nextsector, reg->start-1);
                printf("A: [%08x-%08x]\n",
                       reg->start, reg->start + reg->size - 1);
                if (i == hdr->regioncount-1 &&
                        reg->start+reg->size < hdr->lastsect)
                    printf("F: [%08x-%08x]\n",
                           reg->start+reg->size,
                           hdr->lastsect-1);
                break;
            }
        }

        nextsector = reg->start + reg->size;
        reg++;
    }

    if (hdr->magic == COMPRESSED_V1)
        return 0;

    for (i = 0; i < hdr->reloccount; i++) {
        struct blockreloc *reloc = &((struct blockreloc *)reg)[i];

        relocs++;
        relocbytes += reloc->size;

        if (reloc->sector < hdr->firstsect ||
                reloc->sector >= hdr->lastsect)
            printf("    WARNING: "
                   "Reloc %d at %u not in chunk [%u-%u]\n", i,
                   reloc->sector, hdr->firstsect, hdr->lastsect-1);
        if (detail > 1) {
            char *relocstr;

            switch (reloc->type) {
            case RELOC_FBSDDISKLABEL:
                relocstr = "FBSDDISKLABEL";
                break;
            case RELOC_OBSDDISKLABEL:
                relocstr = "OBSDDISKLABEL";
                break;
            case RELOC_LILOSADDR:
                relocstr = "LILOSADDR";
                break;
            case RELOC_LILOMAPSECT:
                relocstr = "LILOMAPSECT";
                break;
            case RELOC_LILOCKSUM:
                relocstr = "LILOCKSUM";
                break;
            case RELOC_SHORTSECTOR:
                relocstr = "SHORTSECTOR";
                break;
            default:
                relocstr = "??";
                break;
            }
            printf("    Reloc %d: %s sector %d, offset %u-%u\n", i,
                   relocstr, reloc->sector, reloc->sectoff,
                   reloc->sectoff + reloc->size);
        }
    }

#ifdef WITH_CRYPTO
    /*
     * Checksum this image.  Assumes SHA1, because we check for this above.
     */
    if (checksums && hdr->csum_type != CSUM_NONE) {
        if (!verify_checksum(hdr, (unsigned char *)buf,
                             hdr->csum_type)) {
            printf("ERROR: chunk %d fails checksum!\n", chunkno);
            return 1;
        }
    }
#endif

    return 0;
}