Esempio n. 1
0
int main()
{
        struct body_s *bod, *out;
        struct buf_s *buf;
        int n = 0,i=0;
        ssize_t len = 0;
        uint16_t cmdid = 0;
        int32_t num=-16;
        struct darray_s *da;
        struct head_s *head;
        
        bod = (struct body_s*)calloc(PACKET_SIZE, sizeof(struct body_s));
        out = (struct body_s*)calloc(1, sizeof(struct body_s));

        printf("boy size:%d\n", sizeof(struct body_s));
        
        printf("num:%lld, zigzag:%lld\n", (int64_t)num, zigzag((int64_t)num));

        head = (struct head_s*)calloc(1, sizeof(struct head_s)); 
        if (head == NULL) return 0;
        
        head->cmdid = 0xF001;
        head->seq = 0x10001;
        head->uid = 0x1000;
        head->aid = 0x0001;

        buf = buf_calloc(1024);
        len = enpacket(head, (u_char*)NULL, 0, 0, NULL, 0, buf);
        printf("packet buf:%p, len:%d\n", buf->buf_pos, (int)buf->buf_len); 
        hexdump((u_char *)buf->buf_pos, buf->buf_len);        
        
        memset(head, 0, sizeof(struct head_s));
        len = dehead(buf, head);
        if (len==-1) {
                printf("errno:%d, errstr:%s\n", errno, strerror(errno));
                exit(1);
        }
        printf("cmdid:%x\n", head->cmdid); 
        switch (head->cmdid){
        case 0xF001:
                //out->a17 = (u_char*)calloc(1,10);
                da = darray_calloc(1, sizeof(*bod));
                
                if (depacket_da(buf, NULL, 0, da) == -1)
                        perror("ERR DEBODY\n");

                printf("da used %d\n",da->da_used);
                body_handler(head, (struct body_s*)da->da_values);

                darray_free(da);
                break;
        default:
                break;
        }
        
        free(bod);
        free(out);

        free(head);
        buf_free(buf);
        
        


}
Esempio n. 2
0
int main(int argc, char ** argv)
{
    keystore_t * ks = NULL;
    keystore_t * ksu = NULL;
    identkey_t * idk = NULL;
    khm_size cb;
    void * buf = NULL;
    void * cbuf = NULL;
    khm_handle h = NULL;

    __try {
        ks = ks_keystore_create_new();
        leave_if(ks == NULL);

        testk(ks_keystore_set_string(ks, KCDB_RES_DISPLAYNAME, L"Test keystore"));
        testk(ks_keystore_set_string(ks, KCDB_RES_DESCRIPTION, L"Some description"));
        testk(ks_keystore_set_key_password(ks, "foobarbaz", 10));

        idk = ks_identkey_create_new();
        leave_if(idk == NULL);

        idk->provider_name = _wcsdup(L"Foo provider");
        idk->identity_name = _wcsdup(L"My identity");
        idk->display_name = _wcsdup(L"My identity display name");

        testk(ks_keystore_add_identkey(ks, idk));
        ks_datablob_copy(&idk->plain_key, "This is a plain key", 20, 0);

        printf("\nBefore locking ======\n");
        dump_keystore(ks);

        testk(ks_keystore_lock(ks));

        printf("\nAfter locking ======\n");
        dump_keystore(ks);

        testk(ks_keystore_unlock(ks));

        printf("\nAfter unlocking ======\n");
        dump_keystore(ks);

        testk(ks_keystore_lock(ks));
        testnk(ks_keystore_set_key_password(ks, "wrongpassword", 14));

        cb = 0;
        test_if(ks_keystore_serialize(ks, NULL, &cb) == KHM_ERROR_TOO_LONG);
        printf("\nSize of serialized buffer: %d\n", cb);

        buf = malloc(cb);
        testk(ks_keystore_serialize(ks, buf, &cb));

        printf("Serialized buffer:\n");
        hexdump(buf, cb);

        testk(ks_keystore_unserialize(buf, cb, &ksu));

        printf("Unserialized buffer:\n");
        dump_keystore(ksu);

        testk(khc_memory_store_create(&h));

        {
            khm_int32 i32;

            khm_int64 i64;

            testk(khc_memory_store_add(h, L"A", KC_SPACE, NULL, 0));

            i32 = 12;
            testk(khc_memory_store_add(h, L"IValue", KC_INT32, &i32, sizeof(i32)));

            testk(khc_memory_store_add(h, L"SValue", KC_STRING, L"The rain in Spain stays mainly on the plane?", 1024));

            testk(khc_memory_store_add(h, L"BValue", KC_BINARY,
                                       "Lorem ipsum dolo"
                                       "r sit amet, cons"
                                       "ectetur adipisic"
                                       "ing elit, sed do"
                                       " eiusmod tempor", 79));

            testk(khc_memory_store_add(h, L"New space! This is a new space!", KC_SPACE, NULL, 0));

            testk(khc_memory_store_add(h, L"Fooblarg", KC_SPACE, NULL, 0));

            i64 = 0x9382393029348239i64;
            testk(khc_memory_store_add(h, L"64bit integer value", KC_INT64, &i64, sizeof(i64)));

            testk(khc_memory_store_add(h, L"Bonorum", KC_STRING,
                                       L"Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur?",
                                       KCONF_MAXCB_STRING));

            testk(khc_memory_store_add(h, NULL, KC_ENDSPACE, NULL, 0));

            testk(khc_memory_store_add(h, NULL, KC_ENDSPACE, NULL, 0));

            testk(khc_memory_store_add(h, L"Another space! This is a new space!", KC_SPACE, NULL, 0));

            testk(khc_memory_store_add(h, NULL, KC_ENDSPACE, NULL, 0));

            testk(khc_memory_store_add(h, NULL, KC_ENDSPACE, NULL, 0));
        }

        cb = 0;
        test_if(ks_serialize_configuration(h, NULL, &cb) == KHM_ERROR_TOO_LONG);
        test_if(cb > 0);

        cbuf = malloc(cb);
        testk(ks_serialize_configuration(h, cbuf, &cb));

        printf("Serialized configuration:\n");
        hexdump(cbuf, cb);

        testk(khc_memory_store_release(h));

        testk(ks_unserialize_configuration(cbuf, cb, &h));

        {
            int i = 0;
            printf("\nDump of unserialized configuration space:\n");
            testk(khc_memory_store_enum(h, config_dump_cb, &i));
        }

        printf("Success!\n");

    } __finally {
        if (ks)
            ks_keystore_release(ks);
        if (ksu)
            ks_keystore_release(ksu);
        if (buf)
            free(buf);
        if (cbuf)
            free(cbuf);
        if (h)
            khc_memory_store_release(h);
    }

    return 0;
}
Esempio n. 3
0
/* Inquiry a device and returns TRUE if is supported. */
static int
leo_identify_scanner (Leo_Scanner * dev)
{
  CDB cdb;
  SANE_Status status;
  size_t size;
  int i;

  DBG (DBG_proc, "leo_identify_scanner: enter\n");

  size = 5;
  MKSCSI_INQUIRY (cdb, size);
  status = sanei_scsi_cmd2 (dev->sfd, cdb.data, cdb.len,
			    NULL, 0, dev->buffer, &size);

  if (status)
    {
      DBG (DBG_error,
	   "leo_identify_scanner: inquiry failed with status %s\n",
	   sane_strstatus (status));
      return (SANE_FALSE);
    }

  size = dev->buffer[4] + 5;	/* total length of the inquiry data */

  if (size < 36)
    {
      DBG (DBG_error,
	   "leo_identify_scanner: not enough data to identify device\n");
      return (SANE_FALSE);
    }

  MKSCSI_INQUIRY (cdb, size);
  status = sanei_scsi_cmd2 (dev->sfd, cdb.data, cdb.len,
			    NULL, 0, dev->buffer, &size);

  if (status)
    {
      DBG (DBG_error,
	   "leo_identify_scanner: inquiry failed with status %s\n",
	   sane_strstatus (status));
      return (SANE_FALSE);
    }

  dev->scsi_type = dev->buffer[0] & 0x1f;
  memcpy (dev->scsi_vendor, dev->buffer + 0x08, 0x08);
  dev->scsi_vendor[0x08] = 0;
  memcpy (dev->scsi_product, dev->buffer + 0x10, 0x010);
  dev->scsi_product[0x10] = 0;
  memcpy (dev->scsi_version, dev->buffer + 0x20, 0x04);
  dev->scsi_version[0x04] = 0;

  DBG (DBG_info, "device is \"%s\" \"%s\" \"%s\"\n",
       dev->scsi_vendor, dev->scsi_product, dev->scsi_version);

  /* Lookup through the supported scanners table to find if this
   * backend supports that one. */
  for (i = 0; i < NELEMS (scanners); i++)
    {
      if (dev->scsi_type == scanners[i].scsi_type &&
	  strcmp (dev->scsi_vendor, scanners[i].scsi_vendor) == 0 &&
	  strcmp (dev->scsi_product, scanners[i].scsi_product) == 0)
	{

	  DBG (DBG_error, "leo_identify_scanner: scanner supported\n");

	  /* Get the full inquiry, since that scanner does not fill
	     the length correctly. */
	  size = 0x30;
	  MKSCSI_INQUIRY (cdb, size);
	  status = sanei_scsi_cmd2 (dev->sfd, cdb.data, cdb.len,
				    NULL, 0, dev->buffer, &size);
	  if (status != SANE_STATUS_GOOD)
	    {
	      return (SANE_FALSE);
	    }

	  hexdump (DBG_info2, "inquiry", dev->buffer, size);

	  dev->def = &(scanners[i]);
	  dev->res_range.min = 1;
	  dev->res_range.max = B16TOI (&dev->buffer[42]);

	  dev->x_resolution_max = B16TOI (&dev->buffer[40]);
	  dev->y_resolution_max = B16TOI (&dev->buffer[42]);


	  return (SANE_TRUE);
	}
    }

  DBG (DBG_proc, "leo_identify_scanner: exit, device not supported\n");

  return (SANE_FALSE);
}
Esempio n. 4
0
int main(int argc, char **argv)
	{
	unsigned char rkey[16];
	unsigned char rkey2[16];
	AES_KEY key;
	AES_KEY key2;
	unsigned char plaintext[BIG_TEST_SIZE];
	unsigned char ciphertext[BIG_TEST_SIZE];
	unsigned char checktext[BIG_TEST_SIZE];
	unsigned char iv[AES_BLOCK_SIZE*4];
	unsigned char saved_iv[AES_BLOCK_SIZE*4];
	int err = 0;
	unsigned int n;
	unsigned matches;

	assert(BIG_TEST_SIZE >= TEST_SIZE);

	RAND_pseudo_bytes(rkey, sizeof rkey);
	RAND_pseudo_bytes(plaintext, sizeof plaintext);
	RAND_pseudo_bytes(iv, sizeof iv);
	memcpy(saved_iv, iv, sizeof saved_iv);

	/* Forward IGE only... */

	/* Straight encrypt/decrypt */
	AES_set_encrypt_key(rkey, 8*sizeof rkey, &key);
	AES_ige_encrypt(plaintext, ciphertext, TEST_SIZE, &key, iv,
					AES_ENCRYPT);

	AES_set_decrypt_key(rkey, 8*sizeof rkey, &key);
	memcpy(iv, saved_iv, sizeof iv);
	AES_ige_encrypt(ciphertext, checktext, TEST_SIZE, &key, iv,
					AES_DECRYPT);

	if(memcmp(checktext, plaintext, TEST_SIZE))
		{
		printf("Encrypt+decrypt doesn't match\n");
		hexdump(stdout, "Plaintext", plaintext, TEST_SIZE);
		hexdump(stdout, "Checktext", checktext, TEST_SIZE);
		++err;
		}

	/* Now check encrypt chaining works */
	AES_set_encrypt_key(rkey, 8*sizeof rkey, &key);
	memcpy(iv, saved_iv, sizeof iv);
	AES_ige_encrypt(plaintext, ciphertext, TEST_SIZE/2, &key, iv,
					AES_ENCRYPT);
	AES_ige_encrypt(plaintext+TEST_SIZE/2,
					ciphertext+TEST_SIZE/2, TEST_SIZE/2,
					&key, iv, AES_ENCRYPT);

	AES_set_decrypt_key(rkey, 8*sizeof rkey, &key);
	memcpy(iv, saved_iv, sizeof iv);
	AES_ige_encrypt(ciphertext, checktext, TEST_SIZE, &key, iv,
					AES_DECRYPT);

	if(memcmp(checktext, plaintext, TEST_SIZE))
		{
		printf("Chained encrypt+decrypt doesn't match\n");
		hexdump(stdout, "Plaintext", plaintext, TEST_SIZE);
		hexdump(stdout, "Checktext", checktext, TEST_SIZE);
		++err;
		}

	/* And check decrypt chaining */
	AES_set_encrypt_key(rkey, 8*sizeof rkey, &key);
	memcpy(iv, saved_iv, sizeof iv);
	AES_ige_encrypt(plaintext, ciphertext, TEST_SIZE/2, &key, iv,
					AES_ENCRYPT);
	AES_ige_encrypt(plaintext+TEST_SIZE/2,
					ciphertext+TEST_SIZE/2, TEST_SIZE/2,
					&key, iv, AES_ENCRYPT);

	AES_set_decrypt_key(rkey, 8*sizeof rkey, &key);
	memcpy(iv, saved_iv, sizeof iv);
	AES_ige_encrypt(ciphertext, checktext, TEST_SIZE/2, &key, iv,
					AES_DECRYPT);
	AES_ige_encrypt(ciphertext+TEST_SIZE/2,
					checktext+TEST_SIZE/2, TEST_SIZE/2, &key, iv,
					AES_DECRYPT);

	if(memcmp(checktext, plaintext, TEST_SIZE))
		{
		printf("Chained encrypt+chained decrypt doesn't match\n");
		hexdump(stdout, "Plaintext", plaintext, TEST_SIZE);
		hexdump(stdout, "Checktext", checktext, TEST_SIZE);
		++err;
		}

	/* make sure garble extends forwards only */
	AES_set_encrypt_key(rkey, 8*sizeof rkey, &key);
	memcpy(iv, saved_iv, sizeof iv);
	AES_ige_encrypt(plaintext, ciphertext, sizeof plaintext, &key, iv,
					AES_ENCRYPT);

	/* corrupt halfway through */
	++ciphertext[sizeof ciphertext/2];
	AES_set_decrypt_key(rkey, 8*sizeof rkey, &key);
	memcpy(iv, saved_iv, sizeof iv);
	AES_ige_encrypt(ciphertext, checktext, sizeof checktext, &key, iv,
					AES_DECRYPT);

	matches=0;
	for(n=0 ; n < sizeof checktext ; ++n)
		if(checktext[n] == plaintext[n])
			++matches;

	if(matches > sizeof checktext/2+sizeof checktext/100)
		{
		printf("More than 51%% matches after garbling\n");
		++err;
		}

	if(matches < sizeof checktext/2)
		{
		printf("Garble extends backwards!\n");
		++err;
		}

	/* Bi-directional IGE */

	/* Note that we don't have to recover the IV, because chaining isn't */
	/* possible with biIGE, so the IV is not updated. */

	RAND_pseudo_bytes(rkey2, sizeof rkey2);

	/* Straight encrypt/decrypt */
	AES_set_encrypt_key(rkey, 8*sizeof rkey, &key);
	AES_set_encrypt_key(rkey2, 8*sizeof rkey2, &key2);
	AES_bi_ige_encrypt(plaintext, ciphertext, TEST_SIZE, &key, &key2, iv,
					   AES_ENCRYPT);

	AES_set_decrypt_key(rkey, 8*sizeof rkey, &key);
	AES_set_decrypt_key(rkey2, 8*sizeof rkey2, &key2);
	AES_bi_ige_encrypt(ciphertext, checktext, TEST_SIZE, &key, &key2, iv,
					   AES_DECRYPT);

	if(memcmp(checktext, plaintext, TEST_SIZE))
		{
		printf("Encrypt+decrypt doesn't match\n");
		hexdump(stdout, "Plaintext", plaintext, TEST_SIZE);
		hexdump(stdout, "Checktext", checktext, TEST_SIZE);
		++err;
		}

	/* make sure garble extends both ways */
	AES_set_encrypt_key(rkey, 8*sizeof rkey, &key);
	AES_set_encrypt_key(rkey2, 8*sizeof rkey2, &key2);
	AES_ige_encrypt(plaintext, ciphertext, sizeof plaintext, &key, iv,
					AES_ENCRYPT);

	/* corrupt halfway through */
	++ciphertext[sizeof ciphertext/2];
	AES_set_decrypt_key(rkey, 8*sizeof rkey, &key);
	AES_set_decrypt_key(rkey2, 8*sizeof rkey2, &key2);
	AES_ige_encrypt(ciphertext, checktext, sizeof checktext, &key, iv,
					AES_DECRYPT);

	matches=0;
	for(n=0 ; n < sizeof checktext ; ++n)
		if(checktext[n] == plaintext[n])
			++matches;

	if(matches > sizeof checktext/100)
		{
		printf("More than 1%% matches after bidirectional garbling\n");
		++err;
		}

	/* make sure garble extends both ways (2) */
	AES_set_encrypt_key(rkey, 8*sizeof rkey, &key);
	AES_set_encrypt_key(rkey2, 8*sizeof rkey2, &key2);
	AES_ige_encrypt(plaintext, ciphertext, sizeof plaintext, &key, iv,
					AES_ENCRYPT);

	/* corrupt right at the end */
	++ciphertext[sizeof ciphertext-1];
	AES_set_decrypt_key(rkey, 8*sizeof rkey, &key);
	AES_set_decrypt_key(rkey2, 8*sizeof rkey2, &key2);
	AES_ige_encrypt(ciphertext, checktext, sizeof checktext, &key, iv,
					AES_DECRYPT);

	matches=0;
	for(n=0 ; n < sizeof checktext ; ++n)
		if(checktext[n] == plaintext[n])
			++matches;

	if(matches > sizeof checktext/100)
		{
		printf("More than 1%% matches after bidirectional garbling (2)\n");
		++err;
		}

	/* make sure garble extends both ways (3) */
	AES_set_encrypt_key(rkey, 8*sizeof rkey, &key);
	AES_set_encrypt_key(rkey2, 8*sizeof rkey2, &key2);
	AES_ige_encrypt(plaintext, ciphertext, sizeof plaintext, &key, iv,
					AES_ENCRYPT);

	/* corrupt right at the start */
	++ciphertext[0];
	AES_set_decrypt_key(rkey, 8*sizeof rkey, &key);
	AES_set_decrypt_key(rkey2, 8*sizeof rkey2, &key2);
	AES_ige_encrypt(ciphertext, checktext, sizeof checktext, &key, iv,
					AES_DECRYPT);

	matches=0;
	for(n=0 ; n < sizeof checktext ; ++n)
		if(checktext[n] == plaintext[n])
			++matches;

	if(matches > sizeof checktext/100)
		{
		printf("More than 1%% matches after bidirectional garbling (3)\n");
		++err;
		}

	err += run_test_vectors();

	return err;
	}
Esempio n. 5
0
static void decode_tcp (const uint8_t *packet, size_t pk_len, int pk_layer) {
	union {
		const struct mytcphdr *t;
		const uint8_t *d;
	} t_u;
	uint16_t sport=0, dport=0;
	uint32_t seq=0, ackseq=0;
	uint8_t doff=0, res1=0;
	uint16_t window=0, chksum=0, c_chksum=0, urgptr=0;
	size_t data_len=0, tcpopt_len=0;
	int bad_cksum=0;
	union {
		const ip_pseudo_t *ipph_ptr;
		const uint8_t *ptr;
	} ipph_u;
	struct chksumv c[2];

	t_u.d=packet;

	if (pk_layer == 4) { /* this is inside an icmp error reflection, check that */
		if (r_u.i.proto != IPPROTO_ICMP) {
			ERR("FIXME in TCP not inside an ICMP error?");
			return;
		}
		/*
		 * ok so why the special treatment? well the packet may be incomplete, so its ok if we dont have
		 * a full udp header, we really are only looking for the source and dest ports, we _need_ those
		 * everything else is optional at this point
		 */
		if (pk_len < 4) {
			ERR("TCP header too incomplete to get source and dest ports, halting processing");
			return;
		}
		if (pk_len >= 4 && pk_len < sizeof(struct mytcphdr)) {
			/*
			 * this is reversed from a response, the host never responded so flip src/dest ports
			 */
			r_u.i.sport=ntohs(t_u.t->dest);
			r_u.i.dport=ntohs(t_u.t->source);

			return;
		}
	}

	if (pk_len < sizeof(struct mytcphdr)) {
		ERR("short tcp header");
		return;
	}

	sport=ntohs(t_u.t->source);
	dport=ntohs(t_u.t->dest);
	seq=ntohl(t_u.t->seq);
	ackseq=ntohl(t_u.t->ack_seq);
	doff=t_u.t->doff; res1=t_u.t->res1;
	window=ntohs(t_u.t->window);
	chksum=ntohs(t_u.t->check);
	urgptr=ntohs(t_u.t->urg_ptr);

	if (pk_layer == 2) {
		uint32_t eackseq=0, high=0;

		TCPHASHTRACK(eackseq, r_u.i.host_addr, sport, dport, s->ss->syn_key);

		if (GET_LDOCONNECT()) {
			DBG(M_PKT, "window size is %u or whatever", s->ss->window_size);
			high=eackseq + s->ss->window_size;
		}
		else {
			high=eackseq + 2; /* should always be +1, but lets just accept someone who didnt inc th seq */
		}

		if (SEQ_WITHIN(ackseq, eackseq, high)) {
			DBG(M_PKT, "packet within my %08x-%08x window, with %08x expecting %08x", eackseq, high, ackseq, eackseq);
		}
		else if (! GET_SNIFF() && ! GET_IGNORESEQ() && ! (GET_IGNORERSEQ() && t_u.t->rst)) {
			DBG(M_PKT, "not my packet ackseq %08x expecting somewhere around %08x-%08x", ackseq, eackseq, high);
			return;
		}
	} /* layer 3 seq checking */

	if (doff && ((size_t)(doff * 4) > pk_len)) {
		ERR("datalength exceeds capture length, truncating to zero (doff %u bytes pk_len " STFMT ")", doff * 4, pk_len);
		doff=0;
	}

	if (doff && (size_t )(doff * 4) < sizeof(struct mytcphdr)) {
		ERR("doff is too small, increasing to min size and hoping for no tcpoptions");
		doff=sizeof(struct mytcphdr) / 4;
	}

	if (doff) {
		tcpopt_len=((doff * 4) -  sizeof(struct mytcphdr));
		data_len=pk_len - (doff * 4);
	}
	else {
		tcpopt_len=pk_len - sizeof(struct mytcphdr);
		data_len=0;
	}

	ipph_u.ipph_ptr=&ipph;
	/* its not natural to use _this_ size... */
	ipph.len=ntohs(pk_len);

	c[0].len=sizeof(ipph);
	c[0].ptr=ipph_u.ptr;

	c[1].len=pk_len;
	c[1].ptr=packet;

	c_chksum=do_ipchksumv((const struct chksumv *)&c[0], 2);
	if (c_chksum != 0) {
		DBG(M_PKT, "bad tcp checksum, ipchksumv returned 0x%04x", c_chksum);
		bad_cksum=1;
	}

	if (ISDBG(M_PKT) || GET_SNIFF()) {
		char tcpflags[16];

		memset(tcpflags, '-', sizeof(tcpflags));
		tcpflags[8]='\0';
		if (t_u.t->fin) tcpflags[0]='F';
		if (t_u.t->syn) tcpflags[1]='S';
		if (t_u.t->rst) tcpflags[2]='R';
		if (t_u.t->psh) tcpflags[3]='P';
		if (t_u.t->ack) tcpflags[4]='A';
		if (t_u.t->urg) tcpflags[5]='U';
		if (t_u.t->ece) tcpflags[6]='E';
		if (t_u.t->cwr) tcpflags[7]='C';

		INF("TCP : size " STFMT " sport %u dport %u seq 0x%08x ack_seq 0x%08x window %u",
		pk_len, sport, dport, seq, ackseq, window);
		INF("TCP : doff %u res1 %u flags `%s' chksum 0x%04x%s urgptr 0x%04x",
		doff, res1, tcpflags, chksum, (bad_cksum != 0 ? " [bad cksum]" : " [cksum ok]"), urgptr);
		INF("TCP : options length " STFMT " data length " STFMT, tcpopt_len, data_len);
	}

	packet += sizeof(struct mytcphdr);
	pk_len -= sizeof(struct mytcphdr);

	if (tcpopt_len && (ISDBG(M_PKT) || GET_SNIFF())) {
		decode_tcpopts(packet, tcpopt_len);
	}

	if (data_len && (ISDBG(M_PKT) || GET_SNIFF())) {
		INF("TCP : dumping packet data");
		hexdump(packet + tcpopt_len, data_len);
	}

	if (pk_layer == 2) {
		r_u.i.sport=sport;
		r_u.i.dport=dport;
		r_u.i.type=0;

		r_u.i.tseq=seq;
		r_u.i.mseq=ackseq;

		r_u.i.window_size=window;

		if (t_u.t->fin) r_u.i.type |= TH_FIN;
		if (t_u.t->syn) r_u.i.type |= TH_SYN;
		if (t_u.t->rst) r_u.i.type |= TH_RST;
		if (t_u.t->psh) r_u.i.type |= TH_PSH;
		if (t_u.t->ack) r_u.i.type |= TH_ACK;
		if (t_u.t->urg) r_u.i.type |= TH_URG;
		if (t_u.t->ece) r_u.i.type |= TH_ECE;
		if (t_u.t->cwr) r_u.i.type |= TH_CWR;

		r_u.i.subtype=0;

		if (bad_cksum) {
			r_u.i.flags |= REPORT_BADTRANSPORT_CKSUM;
		}

		if (GET_WATCHERRORS() || GET_LDOCONNECT()) {
			report_push();
		}
		else if (t_u.t->syn /* close enough */) {
			report_push();
		}
	}
	else if (pk_layer == 4) {
		r_u.i.sport=dport;
		r_u.i.dport=sport;
		r_u.i.mseq=ackseq;
		r_u.i.tseq=seq;
		r_u.i.window_size=0;
	}
	else {
		ERR("fixme");
		return;
	}

	return;
}
Esempio n. 6
0
static int run_test_case(unsigned test_num, const struct test_case *test) {
  size_t key_len, plaintext_len, additional_data_len, nonce_len, ciphertext_len,
      tag_len;
  uint8_t *key = NULL, *plaintext = NULL, *additional_data = NULL,
          *nonce = NULL, *ciphertext = NULL, *tag = NULL, *out = NULL;
  int ret = 0;
  AES_KEY aes_key;
  GCM128_CONTEXT ctx;

  if (!decode_hex(&key, &key_len, test->key, test_num, "key") ||
      !decode_hex(&plaintext, &plaintext_len, test->plaintext, test_num,
                  "plaintext") ||
      !decode_hex(&additional_data, &additional_data_len, test->additional_data,
                  test_num, "additional_data") ||
      !decode_hex(&nonce, &nonce_len, test->nonce, test_num, "nonce") ||
      !decode_hex(&ciphertext, &ciphertext_len, test->ciphertext, test_num,
                  "ciphertext") ||
      !decode_hex(&tag, &tag_len, test->tag, test_num, "tag")) {
    goto out;
  }

  if (plaintext_len != ciphertext_len) {
    fprintf(stderr, "%u: plaintext and ciphertext have differing lengths.\n",
            test_num);
    goto out;
  }

  if (key_len != 16 && key_len != 24 && key_len != 32) {
    fprintf(stderr, "%u: bad key length.\n", test_num);
    goto out;
  }

  if (tag_len != 16) {
    fprintf(stderr, "%u: bad tag length.\n", test_num);
    goto out;
  }

  out = OPENSSL_malloc(plaintext_len);
  if (AES_set_encrypt_key(key, key_len*8, &aes_key)) {
    fprintf(stderr, "%u: AES_set_encrypt_key failed.\n", test_num);
    goto out;
  }

  CRYPTO_gcm128_init(&ctx, &aes_key, (block128_f) AES_encrypt);
  CRYPTO_gcm128_setiv(&ctx, nonce, nonce_len);
  memset(out, 0, plaintext_len);
  if (additional_data) {
    CRYPTO_gcm128_aad(&ctx, additional_data, additional_data_len);
  }
  if (plaintext) {
    CRYPTO_gcm128_encrypt(&ctx, plaintext, out, plaintext_len);
  }
  if (!CRYPTO_gcm128_finish(&ctx, tag, tag_len) ||
      (ciphertext && memcmp(out, ciphertext, plaintext_len) != 0)) {
    fprintf(stderr, "%u: encrypt failed.\n", test_num);
    hexdump("got ", out, plaintext_len);
    hexdump("want", ciphertext, plaintext_len);
    goto out;
  }

  CRYPTO_gcm128_setiv(&ctx, nonce, nonce_len);
  memset(out, 0, plaintext_len);
  if (additional_data) {
    CRYPTO_gcm128_aad(&ctx, additional_data, additional_data_len);
  }
  if (ciphertext) {
    CRYPTO_gcm128_decrypt(&ctx, ciphertext, out, plaintext_len);
  }
  if (!CRYPTO_gcm128_finish(&ctx, tag, tag_len)) {
    fprintf(stderr, "%u: decrypt failed.\n", test_num);
    goto out;
  }
  if (plaintext && memcmp(out, plaintext, plaintext_len)) {
    fprintf(stderr, "%u: plaintext doesn't match.\n", test_num);
    goto out;
  }

  ret = 1;

out:
  OPENSSL_free(key);
  OPENSSL_free(plaintext);
  OPENSSL_free(additional_data);
  OPENSSL_free(nonce);
  OPENSSL_free(ciphertext);
  OPENSSL_free(tag);
  OPENSSL_free(out);
  return ret;
}
Esempio n. 7
0
int parse_pscl_DP ( 
    uchar_t *packet,
    ushort_t  pkttype )
{
   double etime; 
   Stream *stream, *strm_tim;
   ushort_t  newtype ;
   int dasid, event, streamid, chan, pktnum;
   int nsamp, yr, day, hr, min, sec, msec;
   char dtype[2], ptype[64], key[64], skey[64], stime[64];
   PktPar pack;
   int i;


   dasid = bcd2hex( &packet[4] , 4 );
   pktnum = bcd2hex( &packet[14] , 4 );
   event = bcd2hex( &packet[16], 4 ); 
   streamid = bcd2hex( &packet[18], 2 ); 
   streamid++;
   chan = bcd2hex( &packet[19], 2 ); 
   chan++;

   nsamp = bcd2hex( &packet[20], 4 ); 
   sprintf( (char *) &dtype[0], "%02x", packet[23] ); 
 
   sprintf( skey, "%d_%d\0", dasid, streamid );
  
   if( PsclSTRM == NULL ) return 0;
   stream = ( Stream *) getarr( PsclSTRM, (char *)&skey[0]);
   if( stream == NULL ) {
      complain( 0, "Can't get %s stream info\n", skey); 
      hexdump( stderr, packet, 64 );
      return 0;
   }
  
   if( stream->samprate <= 0 ) return 0;

   switch ( dtype[0] )  {

    case 'c':
       strcpy( (char *) &dtype[0], "c0");
       if( stream->samprate >= 100 )  {
         sprintf( &ptype[0], "CPSCLHS\0");
         newtype = CPSCLHS;
       } else { 
         sprintf( &ptype[0], "CPSCLLS\0");
         newtype = CPSCLLS;
       }
       break;

    case '1':
       strcpy( (char *) &dtype[0], "s2");
       if( stream->samprate >= 100 )  {
         sprintf( &ptype[0], "PSCLHS\0");
         newtype = PSCLHS;
       } else { 
         sprintf( &ptype[0], "PSCLLS\0");
         newtype = PSCLLS;
       }
       break;

    case '3':
       strcpy( (char *) &dtype[0], "s4");
       if( stream->samprate >= 100 )  {
         sprintf( &ptype[0], "PSCLHS\0");
         newtype = PSCLHS;
       } else { 
         sprintf( &ptype[0], "PSCLLS\0");
         newtype = PSCLLS;
       }
       break;

    default:
       complain( 0, "Can't recognize a PASSCAL data packet type. HS?LS?\n");
       return -1;
   }
   
   Par.chan = chan;               
   Par.staid =  dasid;
   
   if( !get_packet( newtype, &pack) ) return -1;
   
   strcpy( &pack.datatype[0], &dtype[0]);
   strcpy( &pack.pkttype[0], &ptype[0]);
 
   pack.nsamp = nsamp;
   pack.nchan = 1;               
   pack.srate = stream->samprate;               
   Par.packet = pack;
   
   yr = bcd2hex( &packet[3] , 2 ); 
   if(yr < 50) yr += 2000;
   else yr += 1900;
   sprintf( (char *) &stime[0], "%02x%02x%02x%02x%02x%02x\0", 
     packet[6], packet[7], packet[8], packet[9],
     packet[10], packet[11]); 
   sscanf( (char *) &stime[0], "%3d%2d%2d%2d%3d", 
     &day, &hr, &min, &sec, &msec); 
   sprintf( (char *) &stime[0], "%02d%03d:%02d:%02d:%02d.%03d\0", 
     yr, day, hr, min, sec, msec); 
   Par.time = str2epoch( (char *) &stime[0] );

   sprintf( (char *) &key[0], "%d", newtype );
   setarr( RawPkts, (char *) &key[0], (char *) &Par.raw);
   
   Par.hdrtype = ( int )decode( pack.hdrtype );
   return (int) pkttype;
}
Esempio n. 8
0
void print_sigcontext(struct sigcontext *sc)
{
	hexdump(out, sc, sizeof(*sc), 0, 1, sigcontext_desc, NULL, NULL);
}
Esempio n. 9
0
void print_fpstate(struct _fpstate *fpstate)
{
	hexdump(out, fpstate, sizeof(*fpstate), 0, 1, fpstate_desc, NULL, NULL);
}
Esempio n. 10
0
int
main(int argc, char **argv)
{
	FILE *fo;
	FILE *fi;
	char name[256];
	char *basename;
	char *p;
	int i, len;

	if (argc < 3)
	{
		fprintf(stderr, "usage: fontdump output.c input.dat\n");
		return 1;
	}

	fo = fopen(argv[1], "wb");
	if (!fo)
	{
		fprintf(stderr, "fontdump: could not open output file '%s'\n", argv[1]);
		return 1;
	}

	for (i = 2; i < argc; i++)
	{
		fi = fopen(argv[i], "rb");
		if (!fi)
		{
			fprintf(stderr, "fontdump: could not open input file '%s'\n", argv[i]);
			return 1;
		}

		basename = strrchr(argv[i], '/');
		if (!basename)
			basename = strrchr(argv[i], '\\');
		if (basename)
			basename++;
		else
			basename = argv[i];
		strcpy(name, basename);
		p = name;
		while (*p)
		{
			if ((*p == '/') || (*p == '.') || (*p == '\\') || (*p == '-'))
				*p = '_';
			p ++;
		}

		fseek(fi, 0, SEEK_END);
		len = ftell(fi);
		fseek(fi, 0, SEEK_SET);

		fprintf(fo, "const unsigned int pdf_font_%s_len = %d;\n", name, len);

		fprintf(fo, "#ifdef __linux__\n");
		fprintf(fo, "asm(\".globl pdf_font_%s_buf\");\n", name);
		fprintf(fo, "asm(\".balign 8\");\n");
		fprintf(fo, "asm(\"pdf_font_%s_buf:\");\n", name);
		fprintf(fo, "asm(\".incbin \\\"%s\\\"\");\n", argv[i]);
		fprintf(fo, "#else\n");
		fprintf(fo, "const unsigned char pdf_font_%s_buf[%d] = {\n", name, len);
		hexdump(fo, fi);
		fprintf(fo, "};\n");
		fprintf(fo, "#endif\n");

		fclose(fi);
	}

	return 0;
}
Esempio n. 11
0
File: main.c Progetto: znuh/unsorted
int main(int argc, char **argv)
{
	uint8_t eeprom[0xFF];
	int16_t ir_data[16][4];
	struct mlx_conv_s conv_tbl;
	double temp[16][4];
	uint16_t cfg, ptat, trim;
	int16_t v_cp;
	double ptat_f;
	SDL_Surface *screen;
	int fd;
#ifdef TEST
	int i;
#endif
	int quit = 0;

	assert(argc > 1);
	fd = open(argv[1], O_RDWR);
	assert(fd >= 0);

	read_eeprom(fd, eeprom);
	hexdump(eeprom, 255);
#ifdef TEST
	eeprom[0xda] = 0x78;
	eeprom[0xdb] = 0x1a;
	eeprom[0xdc] = 0x33;
	eeprom[0xdd] = 0x5b;
	eeprom[0xde] = 0xcc;
	eeprom[0xdf] = 0xed;
	eeprom[0xd4] = 0xd0;
	eeprom[0xd5] = 0xca;
	eeprom[0xd6] = 0x00;
	eeprom[0xd7] = 0x00;
	eeprom[0xd8] = 0x23;
	eeprom[0xd9] = 0x08;
	eeprom[0xe0] = 0xe4;
	eeprom[0xe1] = 0xd5;
	eeprom[0xe2] = 0x2a;
	eeprom[0xe3] = 0x21;
	eeprom[0xe4] = 0x99;
	eeprom[0xe5] = 0x79;
	for (i = 0; i < 64; i++) {
		eeprom[i] = 0xd6;
		eeprom[i + 64] = 0xc1;
		eeprom[i + 128] = 0x8f;
	}
#endif
	prepare_conv(eeprom, &conv_tbl);

	assert(ioctl(fd, I2C_SLAVE, 0x60) >= 0);

	do {
		config_mlx(fd, eeprom);

		mlx_read_ram(fd, MLX_RAM_CONFIG, &cfg, 1);
#ifdef DEBUG
		printf("cfg: %04x\n", cfg);
#endif
	} while (!(cfg & (1 << 10)));

	mlx_read_ram(fd, MLX_RAM_TRIM, &trim, 1);
#ifdef DEBUG
	printf("osc: %04x\n", trim);
#endif

	screen = sdl_init();

	while (!quit) {
		SDL_Event evt;
		mlx_read_ram(fd, MLX_RAM_TGC, (uint16_t *) & v_cp, 1);
#ifdef DEBUG
		printf("tgc: %04x\n", (uint16_t) v_cp);
#endif

		mlx_read_ram(fd, MLX_RAM_PTAT, &ptat, 1);
		ptat_f = ptat_to_kelvin(ptat, &conv_tbl);
#ifdef DEBUG
		printf("ptat: %04x (%.1f)\n", ptat, kelvin_to_celsius(ptat_f));
#endif
		mlx_read_ram(fd, MLX_RAM_IR, (uint16_t *) ir_data, 16 * 4);
#ifdef TEST
		v_cp = 0xffd8;
		ptat_f = 28.16 + 273.15;
		ir_data[0][0] = 0x0090;
#endif
		convert_ir(ir_data, temp, &conv_tbl, ptat_f, v_cp);
#ifdef DEBUG
		dump_ir(ir_data);
		dump_temps(temp);
#endif
		draw_picture(screen, temp, kelvin_to_celsius(ptat_f));
		while (SDL_PollEvent(&evt)) {
			if (evt.type == SDL_KEYDOWN) {
				switch (evt.key.keysym.sym) {
				case SDLK_q:
				case SDLK_ESCAPE:
					quit = 1;
					break;
				default:
					break;
				}
			}

		}
	}

	close(fd);

	return 0;
}
Esempio n. 12
0
uint16_t readXML(char* filePath)
{
    XMLDoc doc;
    XMLSearch search;
    XMLNode* node;
//    XMLNode* child;
    
    XMLNode *name,*user,*hop,*pass,*submit; 

    XMLDoc_init(&doc);
    XMLDoc_parse_file_DOM(filePath, &doc);

    XMLSearch_init(&search);
    XMLSearch_search_set_tag(&search, "cred");
    //XMLSearch_search_add_attribute(&search, "presence", NULL);
    //XMLSearch_search_add_attribute(&search, "value", "a*");
    
    uint8_t* buffptr = flashMemory;
    uint8_t* nextCredential_ptr;
    uint8_t* encryptStart;
    uint16_t length;

    node = doc.nodes[doc.i_root];
    if (XMLSearch_node_matches(node, &search))
            fprintf( stderr, "Found match: <%s>\n", node->tag);
    while ((node = XMLSearch_next(node, &search)) != NULL) {
            
        //child = XMLNode_next(node);
        //XMLNode* XMLNode_get_child(const XMLNode* node, int i_child);
        if (XMLNode_get_children_count(node) != 5)
        {
            fprintf( stderr, "[ERROR] BAD XML FILE");
        }
        else
        {
            name = XMLNode_get_child(node, 0);
            user = XMLNode_get_child(node, 1);
            hop = XMLNode_get_child(node, 2);
            pass = XMLNode_get_child(node, 3);
            submit = XMLNode_get_child(node, 4);

            fprintf( stderr, "Name: %s\n", name->text);
            fprintf( stderr, "User: %s\n", user->text);
            fprintf( stderr, "Hop:  %s\n", hop->text);
            fprintf( stderr, "Pass: %s\n", pass->text);
            fprintf( stderr, "Submit: %s\n", submit->text);
            
            
            if(name->text != 0)
                buffptr = buffptr + sprintf((char*)buffptr, "%s", name->text);
            else
                *buffptr = 0;
            buffptr += 1;
            
            nextCredential_ptr = buffptr;
            buffptr += 2;
            
            encryptStart = buffptr; // encryption must start here ! 
            
            if(user->text != 0)
                buffptr = buffptr + sprintf((char*)buffptr, "%s", user->text);
            else
                *buffptr = 0;
            buffptr += 1;
            
            if(hop->text != 0)
                buffptr = buffptr + sprintf((char*)buffptr, "%s", hop->text);
            else
                *buffptr = 0;
            buffptr += 1;
            
            if(pass->text != 0)
                buffptr = buffptr + sprintf((char*)buffptr, "%s", pass->text);
            else
                *buffptr = 0;
            buffptr += 1;
            
            if(submit->text != 0)
                buffptr = buffptr + sprintf((char*)buffptr, "%s", submit->text);
            else
                *buffptr = 0;
            buffptr += 1;
            
            // call encryption here !
            uint8_t source[4096];
            uint8_t dest[4096];
            uint16_t len = buffptr - encryptStart;
            // buffptr must be incremented to meet block size of encryption
            
	    if( (len % 16) != 0)
            {
            // block must be multiple of 16
	    len = ((len / 16) + 1) * 16;
            buffptr = encryptStart + len;
	    }


            memset((void*)source, 0, sizeof(source));
            memset((void*)dest, 0, sizeof(source));

            // copy credentials into 
            memcpy((void*)(source), (void*)encryptStart, len);

            fprintf(stderr, "\n PLAIN BLOCK TEXT\n" );

            fprintf(stderr, "\n ENCRYPTED BLOCK LEN %d\n",len );
            // start encryption here!
            length = ncrypt(source, dest, len);
            hexdump(encryptStart, len);
            memcpy((void*)encryptStart, dest, len);
            hexdump(encryptStart, len);
            fprintf(stderr, "\n -----------------\n " );


            uint16_t ptr = ((buffptr) - flashMemory);
            *nextCredential_ptr = (ptr & 0x00FF);
            *(nextCredential_ptr+1) = (ptr & 0xFF00)>> 8;

       }
        
    }

    *nextCredential_ptr = 0;
    *(nextCredential_ptr+1) = 0;

    uint16_t size = (buffptr - flashMemory);

    hexdump(flashMemory, size);
    
    XMLSearch_free(&search, true);
    XMLDoc_free(&doc);
    
    return size;
}
Esempio n. 13
0
int main(int argc, char **argv)
{


    int option = 0;      // For getopt temp option

    usbDevice_t *dev;
    ucp_cmd_t buffer;    //room for dummy report ID
    int         err;

    //Initialize globalArgs before we get to work
    globalArgs.rFlag = 0;   //False
    globalArgs.iFlag = 0;   //False
    globalArgs.wFlag = 0;   //False
    globalArgs.fFlag = 0;   //False
    globalArgs.pFlag = 0;   //False
    globalArgs.hashFlag = 0;   //False
    globalArgs.kFlag = 0;   //False
    strncpy(globalArgs.pin,"0000",sizeof(globalArgs.pin)); //Default pin
    globalArgs.offset = 0; //Default
    globalArgs.size = 512; //Default
    globalArgs.fileName = NULL;
    globalArgs.file = NULL;

    //Check if no arguments at all
    if(argc==1) printUsage(argv[0]);

    //If there's some argument, parse them
    while((option = getopt(argc, argv, "rwif:o:p:Pk:s:h?")) !=-1){
    //Check option flags
    switch(option){
        case 'r':
            globalArgs.rFlag = 1; //True
            break;
        case 'w':
            globalArgs.wFlag = 1; //True
            break;
        case 'i':
            globalArgs.iFlag = 1; //True
            break;
        case 'f':
            globalArgs.fFlag = 1; //True
            globalArgs.fileName = optarg;
            printf("File: %s\n",globalArgs.fileName);
            break;
        case 'o':
            globalArgs.offset = atoi(optarg);
            break;
        case 'p':
            globalArgs.pFlag = 1; //True
            strncpy(globalArgs.pin,optarg, sizeof(globalArgs.pin));
            break;
        case 'P':
            globalArgs.hashFlag=1; //True
            break;
        case 'k':
            globalArgs.kFlag = 1; //True
            globalArgs.keyboard = optarg;
            printf("Keyboard: %s\n", globalArgs.keyboard);
        case 's':
            globalArgs.size = atoi(optarg);
            break;
        case 'h':
        case '?':
            printUsage(argv[0]);
            break;
        //Unknown flag, don't know what to do
        default:
            //After getopt prints the error
            printUsage(argv[0]);
            break;
    }
    }

    //Check that only one action is done at a time
    if(globalArgs.rFlag + globalArgs.wFlag + globalArgs.iFlag > 1) printUsage(argv[0]);
    //Check that not set PIN and read HASH are given at a time
    if(globalArgs.pFlag + globalArgs.hashFlag > 1) printUsage(argv[0]);
    //Check that if write from file to device, we are given a file and a pin to encrypt!
    if(globalArgs.wFlag  && !globalArgs.fFlag) printUsage(argv[0]);
    if(globalArgs.wFlag && !globalArgs.pFlag) printUsage(argv[0]);
    //Also check pin for read flag
    if(globalArgs.rFlag && !globalArgs.pFlag) printUsage(argv[0]);

    //Try to open the device, exit if no device present.
    if((dev = openDevice()) == NULL) exit(1);

    //Clean the buffer before working with it
    memset((void*)&buffer, 0, sizeof(buffer));
    

    //Check and perform the desired commands
    if(globalArgs.rFlag){  //READ COMMAND
        buffer.cmd = UCP_CMD_READ;
        deviceRead.offset = globalArgs.offset;
        deviceRead.size = globalArgs.size;
        memcpy((void*)&buffer.buff, (void*)&deviceRead, sizeof(deviceRead));

        //give some feedback
        fprintf(stderr,"Reading from the MemType: offset=%d bytes, size=%d bytes.\n",deviceRead.offset, deviceRead.size);

    }else if(globalArgs.wFlag){  //WRITE COMMAND
        buffer.cmd = UCP_CMD_WRITE;
        deviceRead.offset = globalArgs.offset;
        deviceRead.size = readXML(globalArgs.fileName);
        memcpy((void*)&buffer.buff, (void*)&deviceRead, sizeof(deviceRead));

        //give some feedback
        fprintf(stderr,"Writing to the MemType: offset=%d bytes, size=%d bytes.\n",deviceRead.offset, deviceRead.size);

    }else if(globalArgs.iFlag){  //INFO COMMAND
        buffer.cmd = UCP_CMD_INFO;
    }else if(globalArgs.hashFlag){ //READ PIN HASH COMMAND
        buffer.cmd = UCP_CMD_READ_PIN;
    }else if(globalArgs.pFlag){ //SET PIN COMMAND
        buffer.cmd = UCP_CMD_SET_PIN;
        buffer.buff[0] = 16; //sizeof hash in bytes
    }else if(globalArgs.kFlag){
        buffer.cmd = UCP_CMD_KEYBOARD;
    }
       
        //Add a dummy report ID and send data to device 
        buffer.reportid = 2;
        if((err = usbhidSetReport(dev, (char*)&buffer, sizeof(buffer))) != 0)
            fprintf(stderr, "Error sending data to device: %s\n", usbErrorMessage(err));

        //Read back report 
        int len = sizeof(buffer);
        if((err = usbhidGetReport(dev, 2, (char*)&buffer, &len)) != 0)
        {   //... if not OK, print error
            fprintf(stderr, "Error reading data from device: %s\n", usbErrorMessage(err));
        }
        else //... if OK, do things :)
        {
            fprintf( stderr, "\nMemType CMD Response: ");
            hexdump( (void*)&buffer.cmd, sizeof(buffer.cmd)+sizeof(buffer.buff));
            fprintf( stderr, "Received data from the device: \n");
            switch(buffer.cmd)
            {
                case UCP_CMD_RESET:
                    fprintf( stderr, "RESET\n");
                    break;
                case UCP_CMD_READ:
                    fprintf( stderr, "READ\n");
                    cmdRead(dev, deviceRead.size);
                    break;
                case UCP_CMD_WRITE:
                    fprintf( stderr, "WRITE\n");
                    cmdWrite(dev, flashMemory, deviceRead.size);
                    fprintf(stderr, "[ENCRYPTION TEST] only hexdump");
                    break;
                case UCP_CMD_SET_PIN:
                    fprintf(stderr, "SET PIN\n");
                    cmdSetPin(dev);
                    break;
                case UCP_CMD_READ_PIN:
                    fprintf(stderr, "READ PIN HASH\n");
                    cmdReadPinHash(dev);
                    break;
                case UCP_CMD_KEYBOARD:
                    fprintf(stderr, "KEYBOARD\n");
                    cmdKeyboard(dev);
                    break;
                case UCP_CMD_DATA:
                    fprintf( stderr, "DATA\n");
                    break;
                case UCP_CMD_INFO:
                    fprintf( stderr, "sizeof(info) -> %lu\n", sizeof(deviceInfo));
                    memcpy((void*)&deviceInfo, (void*)buffer.buff, sizeof(deviceInfo));
                    
                    /* Call info */
                    cmdInfo(&deviceInfo);
                    break;
                case UCP_CMD_ERROR:  //Wait! the device returned one error!
                    switch( (unsigned char) buffer.buff[0] )
                    {
                        case UCP_ERR:
                            fprintf( stderr, "GENERIC ERROR\n");
                            break;
                        case UCP_ERR_PACKET:
                            fprintf( stderr, "PACKET ERROR\n");
                            break;
                        case UCP_ERR_CMD:
                            fprintf( stderr, "CMD ERROR\n");
                            break;
                        case UCP_ERR_ADDR:
                            fprintf( stderr, "ADDR ERROR\n");
                            break;
                        case UCP_ERR_SIZE:
                            fprintf( stderr, "SIZE ERRROR\n");
                            break;
                        case UCP_ERR_PROTOCOL:
                            fprintf( stderr, "PROTOCOL ERROR\n");
                            break;
                        case UCP_ERR_LOCKED:
                            fprintf( stderr, "DEVICE LOCKED ERROR\n");
                            break; 
                        default:
                            fprintf( stderr, "UNKNOWN ERROR\n");
                    }
                    break;
                default:
                    fprintf( stderr, "UNKNOWN CMD ERROR\n");
            }
        }

    usbhidCloseDevice(dev);
    
    return 0;
}
Esempio n. 14
0
static bool gridseed_check_new_task(struct cgpu_info *gridseed, GRIDSEED_INFO *info)
{
	cgtimer_t ts_now, ts_res;
	bool ret = false;

	cgtimer_time(&ts_now);
	mutex_lock(&info->qlock);
	cgtimer_sub(&ts_now, &info->query_ts, &ts_res);
#ifndef WIN32
	if (ts_res.tv_sec > 0 || ts_res.tv_nsec > 350000000) {
#else
	if (ts_res.QuadPart > 3500000) {
#endif
		info->query_qlen = false;
		info->dev_queue_len = 1;
		info->needworks = 1;
		cgtimer_time(&info->query_ts);
	}
	mutex_unlock(&info->qlock);
}

/*
 * Thread to read response from Miner device
 */
static void *gridseed_get_results(void *userdata)
{
	struct cgpu_info *gridseed = (struct cgpu_info *)userdata;
	GRIDSEED_INFO *info = gridseed->device_data;
	struct thr_info *thr = info->thr;
	char threadname[24];
	unsigned char readbuf[GRIDSEED_READBUF_SIZE];
	int offset = 0, ret;

	snprintf(threadname, sizeof(threadname), "GridSeed_Recv/%d", gridseed->device_id);
	RenameThread(threadname);
	applog(LOG_NOTICE, "GridSeed: recv thread running, %s", threadname);

	while(likely(!gridseed->shutdown)) {
		unsigned char buf[GRIDSEED_READ_SIZE];

		if (offset >= GRIDSEED_READ_SIZE)
			gridseed_parse_results(gridseed, info, thr, readbuf, &offset);

		if (unlikely(offset + GRIDSEED_READ_SIZE >= GRIDSEED_READBUF_SIZE)) {
			applog(LOG_ERR, "Read buffer overflow, resetting %d", gridseed->device_id);
			offset = 0;
		}

		ret = gc3355_get_data(gridseed, buf, sizeof(buf));
		if (ret == LIBUSB_ERROR_NO_DEVICE)
			gridseed->shutdown = true;
		if (unlikely(ret != 0))
			continue;

		if (opt_debug) {
			applog(LOG_DEBUG, "GridSeed: get %d bytes", GRIDSEED_READ_SIZE);
			hexdump((uint8_t *)buf, GRIDSEED_READ_SIZE);
		}

		memcpy(readbuf + offset, buf, GRIDSEED_READ_SIZE);
		offset += GRIDSEED_READ_SIZE;
	}
	return NULL;
}

/*
 * Thread to send task and queue length query command to device
 */
static void *gridseed_send_command(void *userdata)
{
	struct cgpu_info *gridseed = (struct cgpu_info *)userdata;
	GRIDSEED_INFO *info = gridseed->device_data;
	char threadname[24];
	int i;

	snprintf(threadname, sizeof(threadname), "GridSeed_Send/%d", gridseed->device_id);
	RenameThread(threadname);
	applog(LOG_NOTICE, "GridSeed: send thread running, %s", threadname);

	while(likely(!gridseed->shutdown)) {
		cgsleep_ms(10);
		if (info->usefifo == 0) {
			/* mark the first work in queue as complete after several ms */
			if (gridseed_check_new_task(gridseed, info))
				continue;
		} else {
			/* send query command to device */
			if (gridseed_send_query_cmd(gridseed, info))
				continue;
		}
		/* send task to device */
		mutex_lock(&info->qlock);
		for(i=0; i<info->soft_queue_len; i++) {
			if (info->workqueue[i] && info->workqueue[i]->devflag == false) {
				if (gridseed_send_task(gridseed, info, info->workqueue[i])) {
					info->workqueue[i]->devflag = true;
					break;
				}
			}
		}
		mutex_unlock(&info->qlock);
		/* recv LTC task and send to device */
		gridseed_recv_ltc(gridseed, info);
	}
	return NULL;
}

/*========== functions for struct device_drv ===========*/

static void gridseed_detect(bool __maybe_unused hotplug)
{
	usb_detect(&gridseed_drv, gridseed_detect_one);
}
Esempio n. 15
0
void sockaddr_str_test_conversions()
{
	int i;
	char buf[1024];

#define hexdump(what) \
	osmo_hexdump_buf(buf, sizeof(buf), (void*)(&what), sizeof(what), "", false)

	for (i = 0; i < ARRAY_SIZE(oip_data); i++) {
		struct osmo_sockaddr_str *x = &oip_data[i];
		int rc;
		printf("\n\n");
		dump_oip(x);

		printf("  osmo_sockaddr_str_is_set() = %s\n", osmo_sockaddr_str_is_set(x) ? "true" : "false");

		{
			struct in_addr a = {};

			rc = osmo_sockaddr_str_to_in_addr(x, &a);
			printf("  osmo_sockaddr_str_to_in_addr() %s in_addr=%s\n", rc_name(rc), hexdump(a));

			if (rc == 0) {
				struct osmo_sockaddr_str back;
				rc = osmo_sockaddr_str_from_in_addr(&back, &a, x->port);
				printf("   -> osmo_sockaddr_str_from_in_addr() %s ", rc_name(rc));
				dump_oip(&back);
				if (memcmp(x, &back, sizeof(back)))
					printf("      DIFFERS!\n");
			}
		}

		{
			struct in6_addr a = {};

			rc = osmo_sockaddr_str_to_in6_addr(x, &a);
			printf("  osmo_sockaddr_str_to_in6_addr() %s in6_addr=%s\n", rc_name(rc), hexdump(a));

			if (rc == 0) {
				struct osmo_sockaddr_str back;
				rc = osmo_sockaddr_str_from_in6_addr(&back, &a, x->port);
				printf("   -> osmo_sockaddr_str_from_in6_addr() %s ", rc_name(rc));
				dump_oip(&back);
				if (memcmp(x, &back, sizeof(back)))
					printf("      DIFFERS!\n");
			}
		}

		{
			uint32_t a = 0;

			rc = osmo_sockaddr_str_to_32(x, &a);
			printf("  osmo_sockaddr_str_to_32() %s uint32_t=0x%x\n", rc_name(rc), a);

			if (rc == 0) {
				struct osmo_sockaddr_str back;
				rc = osmo_sockaddr_str_from_32(&back, a, x->port);
				printf("   -> osmo_sockaddr_str_from_32() %s ", rc_name(rc));
				dump_oip(&back);
				if (memcmp(x, &back, sizeof(back)))
					printf("      DIFFERS!\n");
			}
		}

		{
			uint32_t a = 0;

			rc = osmo_sockaddr_str_to_32n(x, &a);
			printf("  osmo_sockaddr_str_to_32n() %s uint32_t=0x%x\n", rc_name(rc), a);

			if (rc == 0) {
				struct osmo_sockaddr_str back;
				rc = osmo_sockaddr_str_from_32n(&back, a, x->port);
				printf("   -> osmo_sockaddr_str_from_32n() %s ", rc_name(rc));
				dump_oip(&back);
				if (memcmp(x, &back, sizeof(back)))
					printf("      DIFFERS!\n");
			}
		}

		{
			struct sockaddr_in a = {};

			rc = osmo_sockaddr_str_to_sockaddr_in(x, &a);
			printf("  osmo_sockaddr_str_to_sockaddr_in() %s sockaddr_in=%s\n", rc_name(rc), hexdump(a));

			if (rc == 0) {
				struct osmo_sockaddr_str back;
				rc = osmo_sockaddr_str_from_sockaddr_in(&back, &a);
				printf("   -> osmo_sockaddr_str_from_sockaddr_in() %s ", rc_name(rc));
				dump_oip(&back);
				if (memcmp(x, &back, sizeof(back)))
					printf("      DIFFERS!\n");
			}
		}

		{
			struct sockaddr_in6 a = {};

			rc = osmo_sockaddr_str_to_sockaddr_in6(x, &a);
			printf("  osmo_sockaddr_str_to_sockaddr_in6() %s sockaddr_in6=%s\n", rc_name(rc), hexdump(a));

			if (rc == 0) {
				struct osmo_sockaddr_str back;
				rc = osmo_sockaddr_str_from_sockaddr_in6(&back, &a);
				printf("   -> osmo_sockaddr_str_from_sockaddr_in6() %s ", rc_name(rc));
				dump_oip(&back);
				if (memcmp(x, &back, sizeof(back)))
					printf("      DIFFERS!\n");
			}
		}

		{
			struct sockaddr_storage a = {};

			rc = osmo_sockaddr_str_to_sockaddr(x, &a);
			printf("  osmo_sockaddr_str_to_sockaddr() %s sockaddr_storage=%s\n", rc_name(rc), hexdump(a));

			if (rc == 0) {
				struct osmo_sockaddr_str back;
				rc = osmo_sockaddr_str_from_sockaddr(&back, &a);
				printf("   -> osmo_sockaddr_str_from_sockaddr() %s ", rc_name(rc));
				dump_oip(&back);
				if (memcmp(x, &back, sizeof(back)))
					printf("      DIFFERS!\n");
			}
		}

		{
			struct osmo_sockaddr_str from_str;
			rc = osmo_sockaddr_str_from_str(&from_str, x->ip, x->port);
			printf("  osmo_sockaddr_str_from_str() %s ", rc_name(rc));
			dump_oip(&from_str);
			if (rc == 0 && memcmp(x, &from_str, sizeof(from_str)))
				printf("      DIFFERS!\n");
		}
	}

}
Esempio n. 16
0
void print_siginfo(siginfo_t *info)
{
	hexdump(out, info, sizeof(*info), 0, 1, NULL, NULL, NULL);
}
Esempio n. 17
0
int
main(int argc, char ** argv)
{
    ssize_t received, sent, bytes;
    struct sigaction old_signal_action;

    /* Input sanitation */
    if (argc != 3) {
        fprintf(stderr, "USAGE: %s listen_port bank_port\n", argv[0]);
        return EXIT_FAILURE;
    }

    /* Capture SIGINT and SIGTERM */
    memset(&session_data.signal_action, '\0', sizeof(struct sigaction));
    sigfillset(&session_data.signal_action.sa_mask);
    session_data.signal_action.sa_handler = &handle_signal;
    sigemptyset(&session_data.termination_signals);
    sigaction(SIGINT, NULL, &old_signal_action);
    if (old_signal_action.sa_handler != SIG_IGN) {
        sigaction(SIGINT, &session_data.signal_action, NULL);
        sigaddset(&session_data.termination_signals, SIGINT);
    }
    sigaction(SIGTERM, NULL, &old_signal_action);
    if (old_signal_action.sa_handler != SIG_IGN) {
        sigaction(SIGTERM, &session_data.signal_action, NULL);
        sigaddset(&session_data.termination_signals, SIGTERM);
    }

    /* Socket initialization */
    if ((session_data.csock = init_client_socket(argv[2])) < 0) {
        fprintf(stderr, "ERROR: unable to connect to server\n");
        return EXIT_FAILURE;
    }
    if ((session_data.ssock = init_server_socket(argv[1])) < 0) {
        fprintf(stderr, "ERROR: unable to start server\n");
        destroy_socket(session_data.csock);
        return EXIT_FAILURE;
    }

    /* Provide a dumb echo tunnel service TODO send/recv threads */
    while (!handle_connection(session_data.ssock, &session_data.conn)) {
        session_data.mode = A2B;
        session_data.count = 0;
        while (!handle_relay(&received, &sent)) {
            /* Report leaky transmissions */
            if (sent != received) {
                bytes = sent - received;
                if (bytes < 0) {
                    bytes = -bytes;
                }
                fprintf(stderr, "ERROR: %li byte(s) lost\n", (long)(bytes));
            }
            /* NOTE: modality is swapped after relay */
            if (session_data.mode == A2B) {
                fprintf(stderr,
                        "INFO: server sent message [id: %08i]\n",
                        session_data.count);
            }
            if (session_data.mode == B2A) {
                fprintf(stderr,
                        "INFO: client sent message [id: %08i]\n",
                        session_data.count);
            }
#ifndef NDEBUG
            /* Report entire transmission */
            hexdump(stderr, session_data.buffer, MAX_COMMAND_LENGTH);
#endif
        }
        time(&session_data.terminated);
        fprintf(stderr, "INFO: tunnel closed [%i msg / %li sec]\n",
                session_data.count,
                (long)(session_data.terminated - session_data.established));
        /* Disconnect from defunct clients */
        destroy_socket(session_data.conn);
        /* Re-establish with the server TODO should this be necessary? */
        destroy_socket(session_data.csock);
        session_data.csock = init_client_socket(argv[2]);
    }

    /* Teardown */
    handle_signal(0);
    return EXIT_SUCCESS;
}
Esempio n. 18
0
void print_stat(const struct kernel_stat64 *s)
{
	hexdump(out, s, sizeof(*s), 0, 0, stat64_desc, NULL, NULL);
}
Esempio n. 19
0
int main(int argc, char *argv[])
{
    int c;
    const char *datafilename;
    FILE *datafile;
    char *outfile     = NULL;
    char *prefixvalue = NULL;
    char *targetaddr  = NULL;
    unsigned char icmp_body[2048];
    unsigned int  icmp_len = 0;
    unsigned int verbose=0;
    unsigned int fakesend=0;
    struct option longoptions[]={
        {"debug",    0, NULL, 'v'},
        {"verbose",  0, NULL, 'v'},
        {"fake",     0, NULL, 'T'},
        {"testing",  0, NULL, 'T'},
        {"prefix",   1, NULL, 'p'},
        {"target",   1, NULL, 'a'},
        {"sequence", 1, NULL, 'S'},
        {"instance", 1, NULL, 'I'},
        {"dagid",    1, NULL, 'G'},
        {"daoack",   0, NULL, 'K'},
        {"datafile", 1, NULL, 'd'},
        {"dest",     1, NULL, 't'},
        {"myid",     1, NULL, 'M'},
        {"ack-request",0,NULL,'A'},
        {"iface",    1, NULL, 'i'},
        {"outpcap",  1, NULL, 'O'},
        {0,0,0,0},
    };

    class rpl_debug *deb = new rpl_debug(verbose, stderr);
    class network_interface *iface = NULL;
    class dag_network       *dn = NULL;
    class pcap_network_interface *piface = NULL;
    struct in6_addr target, *dest = NULL;
    struct in6_addr myid;
    prefix_node *dag_me = NULL;
    rpl_node *destnode = NULL;
    bool initted = false;
    bool ackreq  = false;
    bool daoack  = false;
    memset(icmp_body, 0, sizeof(icmp_body));

    while((c=getopt_long(argc, argv, "AD:G:I:KO:R:S:Ta:d:i:h?p:t:v", longoptions, NULL))!=EOF){
        switch(c) {
        case 'A':
            ackreq=true;  /* XXX todo */
            break;

        case 'd':
            datafilename=optarg;
            if(datafilename[0]=='-' && datafilename[1]=='\0') {
                datafile = stdin;
                datafilename="<stdin>";
            } else {
                datafile = fopen(datafilename, "r");
            }
            if(!datafile) {
                perror(datafilename);
                exit(1);
            }
            icmp_len = read_hex_values(datafile, icmp_body);
            break;

        case 'i':
            if(!initted) {
                if(fakesend) {
                    fprintf(stderr, "Using faked interfaces\n");
                    pcap_network_interface::scan_devices(deb, false);
                } else {
                    network_interface::scan_devices(deb, false);
                }
                initted = true;
            }
            if(outfile == NULL) {
                    fprintf(stderr, "Must specify pcap outfile (-O)\n");
                    usage();
                    exit(2);
            }

            iface = network_interface::find_by_name(optarg);
            if(iface && fakesend) {
                if(iface->faked()) {
                    piface = (pcap_network_interface *)iface;
                    piface->set_pcap_out(outfile, DLT_EN10MB);
                } else {
                    fprintf(stderr, "interface %s is not faked\n", optarg);
                    exit(1);
                }
            }
            break;

        case 'T':
            if(initted) {
                fprintf(stderr, "--fake MUST be first argument\n");
                exit(16);
            }
            fakesend=1;
            break;

        case 'O':
            outfile=optarg;
            break;

        case 'G':
            if(!iface) {
                fprintf(stderr, "--dagid must follow --interface argument\n");
                usage();
                exit(17);
            }
            dn = iface->find_or_make_dag_by_dagid(optarg);
            break;

        case 'K':
            daoack = true;
            break;

        case 'R':
	    check_dag(dn);
            dn->set_dagrank(atoi(optarg));
            break;

        case 'S':
	    check_dag(dn);
            dn->set_sequence(atoi(optarg));
            break;

        case 'I':
	    check_dag(dn);
            dn->set_instanceid(atoi(optarg));
            break;

        case 'a':
            {
                char *targetvalue = optarg;
                ip_subnet targetaddr;
                err_t e = ttosubnet(targetvalue, strlen(targetvalue),
                                    AF_INET6, &targetaddr);
                check_dag(dn);
                if(!dest) {
                    fprintf(stderr, "destination must be set before target addresses\n");
                    usage();
                }
                if(dag_me == NULL) {
                    fprintf(stderr, "myid must be set before target addresses\n");
                    usage();
                }
                dn->add_childnode(destnode, iface, targetaddr);
            }
            break;

        case 'p':
            prefixvalue = optarg;
            {
                ip_subnet prefix;
                err_t e = ttosubnet(prefixvalue, strlen(prefixvalue),
                                    AF_INET6, &prefix);
                if(e!=NULL) {
                    fprintf(stderr, "Invalid prefix: %s\n",prefixvalue);
                    usage();
                }
                check_dag(dn);
                dn->set_prefix(prefix);
            }
            break;

        case 't':
            if(inet_pton(AF_INET6, optarg, &target)!=1) {
                fprintf(stderr, "Invalid ipv6 address: %s\n", optarg);
                usage();
            }
            dest = &target;
            destnode = new rpl_node(target, dn, deb);
            break;

        case 'M':
            if(inet_pton(AF_INET6, optarg, &myid)!=1) {
                fprintf(stderr, "Invalid ipv6 address in --myid: %s\n", optarg);
                usage();
            }
            dag_me = new prefix_node(deb, myid, 128);
            check_dag(dn);
            dn->dag_me = dag_me;
            break;

        case 'v':
            verbose++;
            deb = new rpl_debug(verbose, stderr);
            break;

        case '?':
        case 'h':
        default:
            usage();
            break;
        }
    }

    if(datafilename!=NULL && icmp_len > 0) {
        /* nothing for now */
    } else if(daoack) {
        icmp_len = dn->build_daoack(icmp_body, sizeof(icmp_body));
    } else if(prefixvalue) {
        fprintf(stderr, "building DAO\n");
        icmp_len = dn->build_dao(icmp_body, sizeof(icmp_body));
    } else {
        fprintf(stderr, "either a prefix is needed to send a DAO, or --daoack\n");
        usage();
    }

    if(icmp_len == 0) {
        fprintf(stderr, "length of generated packet is 0, none sent\n");
        if(!prefixvalue) {
            fprintf(stderr, "No prefix value set\n");
        }
        usage();
        exit(1);
    }

    if(verbose) {
        printf("Sending ICMP of length: %u\n", icmp_len);
        if(icmp_len > 0) {
            hexdump(icmp_body, 0, icmp_len);
        }
    }

    if(iface != NULL && icmp_len > 0) {
        if(piface != NULL) {
            piface->send_raw_icmp(dest, icmp_body, icmp_len);
        } else {
            iface->send_raw_icmp(dest, icmp_body, icmp_len);
        }
    }

    exit(0);
}
Esempio n. 20
0
UT_Error IE_Imp_StarOffice::_loadFile(GsfInput * input)
{
	try {
		UT_DEBUGMSG(("SDW: Starting import\n"));
		mOle = GSF_INFILE (gsf_infile_msole_new(input, NULL));
		if (!mOle)
			return UT_IE_BOGUSDOCUMENT;

		// firstly, load metadata
		SDWDocInfo::load(mOle, getDoc());

		mDocStream = gsf_infile_child_by_name(mOle, "StarWriterDocument");
		if (!mDocStream)
			return UT_IE_BOGUSDOCUMENT;

		gsf_off_t size = gsf_input_size(mDocStream);

		if (!appendStrux(PTX_Section, PP_NOPROPS))
			return UT_IE_NOMEMORY;

		UT_DEBUGMSG(("SDW: Attempting to load DocHdr...\n"));
		mDocHdr.load(mDocStream);
		UT_DEBUGMSG(("SDW: ...success\n"));

		// Ask for and verify the password
		if (mDocHdr.cryptor) {
			if (!mDocHdr.cryptor->SetPassword(GetPassword().c_str())) {
				UT_DEBUGMSG(("SDW: Wrong password\n"));
				return UT_IE_PROTECTED;
			}
		}

		// do the actual reading
		char type;
		bool done = false;
		UT_uint32 recSize;
		while (!done) {
			if (gsf_input_tell(mDocStream) == size)
				break;
			readChar(mDocStream, type);
			gsf_off_t eor;
			readRecSize(mDocStream, recSize, &eor);

			switch (type) {
				case SWG_CONTENTS: {
					gsf_off_t flagsEnd = 0;
					UT_uint32 nNodes;
					// sw/source/core/sw3io/sw3sectn.cxx#L129
					if (mDocHdr.nVersion >= SWG_LAYFRAMES) {
						UT_uint8 flags;
						readFlagRec(mDocStream, flags, &flagsEnd);
					}
					if (mDocHdr.nVersion >= SWG_LONGIDX)
						streamRead(mDocStream, nNodes);
					else {
						if (mDocHdr.nVersion >= SWG_LAYFRAMES) {
							UT_uint16 sectidDummy;
							streamRead(mDocStream, sectidDummy);
						}
						UT_uint16 nodes16;
						streamRead(mDocStream, nodes16);
						nNodes = (UT_uint32)nodes16;
					}
					if (flagsEnd) {
						UT_ASSERT(flagsEnd >= gsf_input_tell(mDocStream));
						if (gsf_input_tell(mDocStream) != flagsEnd) {
							UT_DEBUGMSG(("SDW: have not read all flags\n"));
							if (gsf_input_seek(mDocStream, flagsEnd, G_SEEK_SET))
								return UT_IE_BOGUSDOCUMENT;
						}
					}
					bool done2 = false;
					UT_uint32 size2;
					while (!done2) {
						readChar(mDocStream, type);
						gsf_off_t eor2;
						readRecSize(mDocStream, size2, &eor2);

						switch (type) {
							case SWG_TEXTNODE: { // sw/source/core/sw3io/sw3nodes.cxx#L788
								UT_DEBUGMSG(("SDW: Found Textnode! (start at 0x%08llX end at 0x%08llX)\n", 
											 (long long)gsf_input_tell(mDocStream), 
											 (long long)eor2));
								UT_uint8 flags;
								gsf_off_t newPos;
								readFlagRec(mDocStream, flags, &newPos);
								// XXX check flags
								if (gsf_input_seek(mDocStream, newPos, G_SEEK_SET))
									return UT_IE_BOGUSDOCUMENT;

								// Read the actual text
								UT_UCS4Char* str;
								readByteString(mDocStream, str);
								UT_UCS4String textNode(str);
								free(str);
								UT_DEBUGMSG(("SDW: ...length=%zu contents are: |%s|\n", textNode.length(), textNode.utf8_str()));

								// now get the attributes
								UT_String attrs;
								UT_String pAttrs;
								UT_Vector charAttributes;
								while (gsf_input_tell(mDocStream) < eor2) {
									char attVal;
									streamRead(mDocStream, attVal);
									UT_uint32 attSize;
									gsf_off_t eoa; // end of attribute
									readRecSize(mDocStream, attSize, &eoa);
									if (attVal == SWG_ATTRIBUTE) {
										TextAttr* a = new TextAttr;
										streamRead(mDocStream, *a, eoa);
										UT_DEBUGMSG(("SDW: ...found text-sub-node, which=0x%x, ver=0x%x, start=%u, end=%u - data:%s len:%llu data is:",
													 a->which, a->ver, a->start,
													 a->end, a->data?"Yes":"No",
													 (long long unsigned)a->dataLen));
#ifdef DEBUG
										hexdump(a->data, a->dataLen);
                    putc('\n', stderr);
#endif
										charAttributes.addItem(a);
									}
									else if (attVal == SWG_ATTRSET) {
									  // bah, yet another loop
										UT_DEBUGMSG(("SDW: ...paragraph attributes found\n"));
										while (gsf_input_tell(mDocStream) < eoa) {
											// reusing attVal and attSize
											streamRead(mDocStream, attVal);
											gsf_off_t eoa2; // end of attribute
											readRecSize(mDocStream, attSize, &eoa2);
											if (attVal == SWG_ATTRIBUTE) {
												TextAttr a;
												streamRead(mDocStream, a, eoa2);
                        if (!a.attrVal.empty()) {
  												if (a.isPara)
	  												UT_String_setProperty(pAttrs, a.attrName, a.attrVal);
		  										else
			  										UT_String_setProperty(attrs, a.attrName, a.attrVal);
                        }
						UT_DEBUGMSG(("SDW: ......found paragraph attr, which=0x%x, ver=0x%x, start=%u, end=%u (string now %s) Data:%s Len=%lld Data:", a.which, a.ver, (a.startSet?a.start:0), (a.endSet?a.end:0), attrs.c_str(), (a.data ? "Yes" : "No"), (long long)a.dataLen));
#ifdef DEBUG
												hexdump(a.data, a.dataLen);
                        putc('\n', stderr);
#endif
											}
											if (gsf_input_seek(mDocStream, eoa2, G_SEEK_SET))
												return UT_IE_BOGUSDOCUMENT;
										}
									}
									else {
										UT_DEBUGMSG(("SDW: ...unknown attribute '%c' found (start=%" GSF_OFF_T_FORMAT " end=%" GSF_OFF_T_FORMAT ")\n", attVal, gsf_input_tell(mDocStream), eoa));
									}
									if (gsf_input_seek(mDocStream, eoa, G_SEEK_SET))
										return UT_IE_BOGUSDOCUMENT;
								}

								PP_PropertyVector attributes = {
									"props",
									pAttrs.c_str()
								};
								// first, insert the paragraph
								if (!appendStrux(PTX_Block, attributes))
									return UT_IE_NOMEMORY;

								UT_String pca(attrs); // character attributes for the whole paragraph
								// now insert the spans of text
								UT_uint32 len = textNode.length();
								UT_uint32 lastInsPos = 0;
								for (UT_uint32 i = 1; i < len; i++) {
									bool doInsert = false; // whether there was an attribute change
									for (UT_sint32 j = 0; j < charAttributes.getItemCount(); j++) {
										const TextAttr* a = reinterpret_cast<const TextAttr*>(charAttributes[j]);
										// clear the last attribute, if set
										if (a->endSet && a->end == (i - 1)) {
											if (a->isOff) {
												UT_String propval = UT_String_getPropVal(pca, a->attrName);
												UT_String_setProperty(attrs, a->attrName, propval);
											}
											else
												UT_String_removeProperty(attrs, a->attrName);
										}

										// now set new attribute, if needed
										if (a->startSet && a->start == (i - 1)) {
											if (a->isPara)
												UT_String_setProperty(pAttrs, a->attrName, a->attrVal);
											else if (a->isOff)
												UT_String_removeProperty(attrs, a->attrName);
											else
												UT_String_setProperty(attrs, a->attrName, a->attrVal);
										}

										// insert if this is the last character, or if there was a format change
										if ((a->endSet && a->end == i) || (a->startSet && a->start == i))
											doInsert = true;
									}
									if (doInsert || i == (len - 1)) {
										attributes[1] = attrs.c_str();
										UT_DEBUGMSG(("SDW: Going to appendFmt with %s\n", attributes[1].c_str()));
										if (!appendFmt(attributes))
											return UT_IE_NOMEMORY; /* leave cast alone! */
										UT_DEBUGMSG(("SDW: About to insert %u-%u\n", lastInsPos, i));
										size_t spanLen = i - lastInsPos;
										if (i == (len - 1)) spanLen++;
										UT_UCS4String span = textNode.substr(lastInsPos, spanLen);
										appendSpan(span.ucs4_str(), spanLen);
										lastInsPos = i;
									}
								}

								UT_VECTOR_PURGEALL(TextAttr*, charAttributes);
								break;

							}
							case SWG_JOBSETUP: {
								// flags are apparently unused here. no idea why they are there.
								gsf_off_t newpos;
								UT_uint8 flags;
								readFlagRec(mDocStream, flags, &newpos);
								if (gsf_input_seek(mDocStream, newpos, G_SEEK_SET))
									return UT_IE_BOGUSDOCUMENT;
								UT_uint16 len, system;
								streamRead(mDocStream, len);
								streamRead(mDocStream, system);
								char printerName[64];
								streamRead(mDocStream, printerName, 64);
								char deviceName[32], portName[32], driverName[32];
								streamRead(mDocStream, deviceName, 32);
								streamRead(mDocStream, portName, 32);
								streamRead(mDocStream, driverName, 32);
								UT_DEBUGMSG(("SDW: Jobsetup: len %u sys 0x%x printer |%.64s| device |%.32s| port |%.32s| driver |%.32s|\n", len, system, printerName, deviceName, portName, driverName));

								if (system == JOBSET_FILE364_SYSTEM || system == JOBSET_FILE605_SYSTEM) {
									UT_uint16 len2, system2;
									streamRead(mDocStream, len2);
									streamRead(mDocStream, system2);
									UT_uint32 ddl; // driver data length
									streamRead(mDocStream, ddl);
									// now the interesting data
									UT_uint16 orient; // 0=portrait 1=landscape
									streamRead(mDocStream, orient);
									UT_uint16 paperBin;
									streamRead(mDocStream, paperBin);
									UT_uint16 paperFormat;
									streamRead(mDocStream, paperFormat);
									UT_uint32 width, height;
									streamRead(mDocStream, width);
									streamRead(mDocStream, height);
									UT_DEBUGMSG(("SDW: orient %u bin %u format %u width %u height %u\n", orient, paperBin, paperFormat, width, height));
									// rest of the data is ignored, seems to be printer specific anyway.
									// Use A4, Portrait by default
									PP_PropertyVector attributes = {
										"pagetype", "a4", // A4/Letter/...
										"orientation", "portrait",
										"width", "210",
										"height", "297",
										"units", "mm"
									};
									const char* sdwPaperToAbi[] = {
										"A3",
										"A4",
										"A5",
										"B4",
										"B5",
										"Letter",
										"Legal",
										"Tabloid/Ledger",
										"Custom"
									};
									if (paperFormat < sizeof(sdwPaperToAbi)/sizeof(*sdwPaperToAbi)) {
										attributes[1] = sdwPaperToAbi[paperFormat];
                                    }
									const char* sdwOrientToAbi[] = {
										"portrait",
										"landscape"
									};
									if (orient < sizeof(sdwOrientToAbi)/sizeof(*sdwOrientToAbi)) {
										attributes[3] = sdwOrientToAbi[orient];
                                    }
									attributes[5] = UT_std_string_sprintf("%f", static_cast<double>(width)/100);
									attributes[7] = UT_std_string_sprintf("%f", static_cast<double>(height)/100);

									getDoc()->setPageSizeFromFile(attributes);
								}
								break;

							}
							case SWG_EOF:
								done2 = true;
								break;
							default:
								UT_DEBUGMSG(("SDW: SWG_CONTENT: Skipping %u bytes for record type '%c' (starting at 0x%08llX)\n",
											 size2, type,
											 (long long)gsf_input_tell(mDocStream)));
						}
						if (gsf_input_seek(mDocStream, eor2, G_SEEK_SET))
							return UT_IE_BOGUSDOCUMENT;
					}
					break;
				}
				case SWG_STRINGPOOL:
				{
					if (mDocHdr.nVersion <= SWG_POOLIDS) {
						UT_ASSERT_HARMLESS(UT_NOT_IMPLEMENTED);
						break;
					}
					UT_uint8 encoding;
					streamRead(mDocStream, encoding);
					UT_iconv_t cd = findConverter(encoding);
					if (!UT_iconv_isValid(cd))
						throw UT_IE_IMPORTERROR;
					UT_uint16 count;
					streamRead(mDocStream, count);
					while (count--) {
						UT_uint16 id;
						streamRead(mDocStream, id);
						char* str;
						UT_uint16 len;
						::readByteString(mDocStream, str, &len);
						if (id == IDX_NOCONV_FF) {
							UT_ASSERT_HARMLESS(UT_NOT_IMPLEMENTED);
						}
						// FIXME: find a way to not have to copy and free 
						// the result of UT_convert_cd.... --hub
						UT_DEBUGMSG(("SDW: StringPool: found 0x%04x <-> %.*s\n", id, len, str));
						UT_UCS4Char* convertedString = reinterpret_cast<UT_UCS4Char*>(UT_convert_cd(str, len + 1, cd, NULL, NULL));
						mStringPool.insert(stringpool_map::value_type(id, convertedString));
						FREEP(convertedString);
                        delete [] str;
					}
                    UT_iconv_close(cd);
					break;
				}
				case SWG_COMMENT: // skip over comments
					break;
				case SWG_EOF:
					done = true;
					break;
				default:
					UT_DEBUGMSG(("SDW: Skipping %u bytes for record type '%c' (starting at 0x%08llX)\n", recSize, type, (long long)gsf_input_tell(mDocStream)));
			}
			// Seek to the end of the record, in case it wasn't read completely
			if (gsf_input_seek(mDocStream, eor, G_SEEK_SET))
				return UT_IE_BOGUSDOCUMENT;
		}

		UT_DEBUGMSG(("SDW: Done\n"));

		return UT_OK;
	}
	catch(UT_Error e) {
		UT_DEBUGMSG(("SDW: error %d\n", e));
		return e;
	}
	catch(...) {
		UT_DEBUGMSG(("SDW: Unknown error\n"));
		return UT_IE_BOGUSDOCUMENT;
	}
}
Esempio n. 21
0
static int run_test_vectors(void)
	{
	unsigned int n;
	int errs = 0;

	for(n=0 ; n < sizeof(ige_test_vectors)/sizeof(ige_test_vectors[0]) ; ++n)
		{
		const struct ige_test * const v = &ige_test_vectors[n];
		AES_KEY key;
		unsigned char buf[MAX_VECTOR_SIZE];
		unsigned char iv[AES_BLOCK_SIZE*2];

		assert(v->length <= MAX_VECTOR_SIZE);

		if(v->encrypt == AES_ENCRYPT)
			AES_set_encrypt_key(v->key, 8*sizeof v->key, &key);
		else
			AES_set_decrypt_key(v->key, 8*sizeof v->key, &key);
		memcpy(iv, v->iv, sizeof iv);
		AES_ige_encrypt(v->in, buf, v->length, &key, iv, v->encrypt);

		if(memcmp(v->out, buf, v->length))
			{
			printf("IGE test vector %d failed\n", n);
			hexdump(stdout, "key", v->key, sizeof v->key);
			hexdump(stdout, "iv", v->iv, sizeof v->iv);
			hexdump(stdout, "in", v->in, v->length);
			hexdump(stdout, "expected", v->out, v->length);
			hexdump(stdout, "got", buf, v->length);

			++errs;
			}

                /* try with in == out */
		memcpy(iv, v->iv, sizeof iv);
                memcpy(buf, v->in, v->length);
		AES_ige_encrypt(buf, buf, v->length, &key, iv, v->encrypt);

		if(memcmp(v->out, buf, v->length))
			{
			printf("IGE test vector %d failed (with in == out)\n", n);
			hexdump(stdout, "key", v->key, sizeof v->key);
			hexdump(stdout, "iv", v->iv, sizeof v->iv);
			hexdump(stdout, "in", v->in, v->length);
			hexdump(stdout, "expected", v->out, v->length);
			hexdump(stdout, "got", buf, v->length);

			++errs;
			}
		}

	for(n=0 ; n < sizeof(bi_ige_test_vectors)/sizeof(bi_ige_test_vectors[0])
			; ++n)
		{
		const struct bi_ige_test * const v = &bi_ige_test_vectors[n];
		AES_KEY key1;
		AES_KEY key2;
		unsigned char buf[MAX_VECTOR_SIZE];

		assert(v->length <= MAX_VECTOR_SIZE);

		if(v->encrypt == AES_ENCRYPT)
			{
			AES_set_encrypt_key(v->key1, 8*v->keysize, &key1);
			AES_set_encrypt_key(v->key2, 8*v->keysize, &key2);
			}
		else
			{
			AES_set_decrypt_key(v->key1, 8*v->keysize, &key1);
			AES_set_decrypt_key(v->key2, 8*v->keysize, &key2);
			}

		AES_bi_ige_encrypt(v->in, buf, v->length, &key1, &key2, v->iv,
						   v->encrypt);

		if(memcmp(v->out, buf, v->length))
			{
			printf("Bidirectional IGE test vector %d failed\n", n);
			hexdump(stdout, "key 1", v->key1, sizeof v->key1);
			hexdump(stdout, "key 2", v->key2, sizeof v->key2);
			hexdump(stdout, "iv", v->iv, sizeof v->iv);
			hexdump(stdout, "in", v->in, v->length);
			hexdump(stdout, "expected", v->out, v->length);
			hexdump(stdout, "got", buf, v->length);

			++errs;
			}
		}

	return errs;
	}
Esempio n. 22
0
int
main(int argc, char *argv[])
{
    const char *archive;
    struct zip *za, *z_in;
    struct zip_source *zs;
    char buf[100];
    int c, arg, err, flags, idx;

    flags = 0;
    prg = argv[0];

    if (argc < 2) {
	fprintf(stderr, usage, prg);
	return 1;
    }

    while ((c=getopt(argc, argv, "cent")) != -1) {
	switch (c) {
	case 'c':
	    flags |= ZIP_CHECKCONS;
	    break;
	case 'e':
	    flags |= ZIP_EXCL;
	    break;
	case 'n':
	    flags |= ZIP_CREATE;
	    break;
	case 't':
	    flags |= ZIP_TRUNCATE;
	    break;

	default:
	    fprintf(stderr, usage, argv[0]);
	    return 1;
	}
    }
    
    arg = optind;

    archive = argv[arg++];

    if (flags == 0)
	flags = ZIP_CREATE;

    if ((za=zip_open(archive, flags, &err)) == NULL) {
	zip_error_to_str(buf, sizeof(buf), err, errno);
	fprintf(stderr, "can't open zip archive `%s': %s\n", archive, buf);
	return 1;
    }

    err = 0;
    while (arg < argc) {
	if (strcmp(argv[arg], "add") == 0 && arg+2 < argc) {
	    /* add */
    	    if ((zs=zip_source_buffer(za, argv[arg+2], strlen(argv[arg+2]), 0)) == NULL) {
		fprintf(stderr, "can't create zip_source from buffer: %s\n", zip_strerror(za));
		err = 1;
		break;
	    }

	    if (zip_add(za, argv[arg+1], zs) == -1) {
		zip_source_free(zs);
		fprintf(stderr, "can't add file `%s': %s\n", argv[arg+1], zip_strerror(za));
		err = 1;
		break;
	    }
	    arg += 3;
	} else if (strcmp(argv[arg], "add_dir") == 0 && arg+1 < argc) {
	    /* add directory */
	    if (zip_add_dir(za, argv[arg+1]) < 0) {
		fprintf(stderr, "can't add directory `%s': %s\n", argv[arg+1], zip_strerror(za));
		err = 1;
		break;
	    }
	    arg += 2;
	} else if (strcmp(argv[arg], "add_file") == 0 && arg+4 < argc) {
	    /* add */
    	    if ((zs=zip_source_file(za, argv[arg+2], atoi(argv[arg+3]), atoi(argv[arg+4]))) == NULL) {
		fprintf(stderr, "can't create zip_source from file: %s\n", zip_strerror(za));
		err = 1;
		break;
	    }

	    if (zip_add(za, argv[arg+1], zs) == -1) {
		zip_source_free(zs);
		fprintf(stderr, "can't add file `%s': %s\n", argv[arg+1], zip_strerror(za));
		err = 1;
		break;
	    }
	    arg += 5;
	} else if (strcmp(argv[arg], "add_from_zip") == 0 && arg+5 < argc) {
	    /* add from another zip file */
	    idx = atoi(argv[arg+3]);
	    if ((z_in=zip_open(argv[arg+2], ZIP_CHECKCONS, &err)) == NULL) {
		zip_error_to_str(buf, sizeof(buf), err, errno);
		fprintf(stderr, "can't open source zip archive `%s': %s\n", argv[arg+2], buf);
		err = 1;
		break;
	    }
	    if ((zs=zip_source_zip(za, z_in, idx, 0, atoi(argv[arg+4]), atoi(argv[arg+5]))) == NULL) {
		fprintf(stderr, "error creating file source from `%s' index '%d': %s\n", argv[arg+2], idx, zip_strerror(za));
		zip_close(z_in);
		err = 1;
		break;
	    }
	    if (zip_add(za, argv[arg+1], zs) == -1) {
		fprintf(stderr, "can't add file `%s': %s\n", argv[arg+1], zip_strerror(za));
		zip_source_free(zs);
		zip_close(z_in);
		err = 1;
		break;
	    }
	    arg += 6;
	} else if (strcmp(argv[arg], "count_extra") == 0 && arg+2 < argc) {
	    zip_int16_t count;
	    zip_flags_t ceflags = 0;
	    idx = atoi(argv[arg+1]);
	    ceflags = get_flags(argv[arg+2]);
	    if ((count=zip_file_extra_fields_count(za, idx, ceflags)) < 0) {
		fprintf(stderr, "can't get extra field count for file at index `%d': %s\n", idx, zip_strerror(za));
		err = 1;
		break;
	    } else {
		printf("Extra field count: %d\n", count);
	    }
	    arg += 3;
	} else if (strcmp(argv[arg], "count_extra_by_id") == 0 && arg+3 < argc) {
	    zip_int16_t count, eid;
	    zip_flags_t ceflags = 0;
	    idx = atoi(argv[arg+1]);
	    eid = atoi(argv[arg+2]);
	    ceflags = get_flags(argv[arg+3]);
	    if ((count=zip_file_extra_fields_count_by_id(za, idx, eid, ceflags)) < 0) {
		fprintf(stderr, "can't get extra field count for file at index `%d' and for id `%d': %s\n", idx, eid, zip_strerror(za));
		err = 1;
		break;
	    } else {
		printf("Extra field count: %d\n", count);
	    }
	    arg += 4;
	} else if (strcmp(argv[arg], "delete") == 0 && arg+1 < argc) {
	    /* delete */
	    idx = atoi(argv[arg+1]);
	    if (zip_delete(za, idx) < 0) {
		fprintf(stderr, "can't delete file at index `%d': %s\n", idx, zip_strerror(za));
		err = 1;
		break;
	    }
	    arg += 2;
	} else if (strcmp(argv[arg], "delete_extra") == 0 && arg+1 < argc) {
	    zip_flags_t geflags;
	    zip_uint16_t eid;
	    idx = atoi(argv[arg+1]);
	    eid = atoi(argv[arg+2]);
	    geflags = get_flags(argv[arg+3]);
	    if ((zip_file_extra_field_delete(za, idx, eid, geflags)) < 0) {
		fprintf(stderr, "can't delete extra field data for file at index `%d', extra field id `%d': %s\n", idx, eid, zip_strerror(za));
		err = 1;
		break;
	    }
	    arg += 4;
	} else if (strcmp(argv[arg], "delete_extra_by_id") == 0 && arg+1 < argc) {
	    zip_flags_t geflags;
	    zip_uint16_t eid, eidx;
	    idx = atoi(argv[arg+1]);
	    eid = atoi(argv[arg+2]);
	    eidx = atoi(argv[arg+3]);
	    geflags = get_flags(argv[arg+4]);
	    if ((zip_file_extra_field_delete_by_id(za, idx, eid, eidx, geflags)) < 0) {
		fprintf(stderr, "can't delete extra field data for file at index `%d', extra field id `%d', extra field idx `%d': %s\n", idx, eid, eidx, zip_strerror(za));
		err = 1;
		break;
	    }
	    arg += 5;
	} else if (strcmp(argv[arg], "get_archive_comment") == 0) {
	    const char *comment;
	    int len;
	    /* get archive comment */
	    if ((comment=zip_get_archive_comment(za, &len, 0)) == NULL)
		printf("No archive comment\n");
	    else
		printf("Archive comment: %.*s\n", len, comment);
	    arg += 1;
	} else if (strcmp(argv[arg], "get_extra") == 0 && arg+3 < argc) {
	    zip_flags_t geflags;
	    zip_uint16_t id, eidx, eflen;
	    const zip_uint8_t *efdata;
	    /* get extra field data */
	    idx = atoi(argv[arg+1]);
	    eidx = atoi(argv[arg+2]);
	    geflags = get_flags(argv[arg+3]);
	    if ((efdata=zip_file_extra_field_get(za, idx, eidx, &id, &eflen, geflags)) == NULL) {
		fprintf(stderr, "can't get extra field data for file at index %d, extra field %d, flags %u: %s\n", idx, eidx, geflags, zip_strerror(za));
		err = 1;
	    } else {
		printf("Extra field 0x%04x: len %d", id, eflen);
		if (eflen > 0) {
		    printf(", data ");
		    hexdump(efdata, eflen);
		}
		printf("\n");
	    }
	    arg += 4;
	} else if (strcmp(argv[arg], "get_extra_by_id") == 0 && arg+4 < argc) {
	    zip_flags_t geflags;
	    zip_uint16_t eid, eidx, eflen;
	    const zip_uint8_t *efdata;
	    idx = atoi(argv[arg+1]);
	    eid = atoi(argv[arg+2]);
	    eidx = atoi(argv[arg+3]);
	    geflags = get_flags(argv[arg+4]);
	    if ((efdata=zip_file_extra_field_get_by_id(za, idx, eid, eidx, &eflen, geflags)) == NULL) {
		fprintf(stderr, "can't get extra field data for file at index %d, extra field id %d, ef index %d, flags %u: %s\n", idx, eid, eidx, geflags, zip_strerror(za));
		err = 1;
	    } else {
		printf("Extra field 0x%04x: len %d", eid, eflen);
		if (eflen > 0) {
		    printf(", data ");
		    hexdump(efdata, eflen);
		}
		printf("\n");
	    }
	    arg += 5;
	} else if (strcmp(argv[arg], "get_file_comment") == 0 && arg+1 < argc) {
	    const char *comment;
	    int len;
	    /* get file comment */
	    idx = atoi(argv[arg+1]);
	    if ((comment=zip_get_file_comment(za, idx, &len, 0)) == NULL) {
		fprintf(stderr, "can't get comment for `%s': %s\n", zip_get_name(za, idx, 0), zip_strerror(za));
		err = 1;
		break;
	    } else if (len == 0)
		printf("No comment for `%s'\n", zip_get_name(za, idx, 0));
	    else
		printf("File comment for `%s': %.*s\n", zip_get_name(za, idx, 0), len, comment);
	    arg += 2;
	} else if (strcmp(argv[arg], "rename") == 0 && arg+2 < argc) {
	    /* rename */
	    idx = atoi(argv[arg+1]);
	    if (zip_rename(za, idx, argv[arg+2]) < 0) {
		fprintf(stderr, "can't rename file at index `%d' to `%s': %s\n", idx, argv[arg+2], zip_strerror(za));
		err = 1;
		break;
	    }
	    arg += 3;
	} else if (strcmp(argv[arg], "set_extra") == 0 && arg+5 < argc) {
	    zip_flags_t geflags;
	    zip_uint16_t eid, eidx;
	    const zip_uint8_t *efdata;
	    idx = atoi(argv[arg+1]);
	    eid = atoi(argv[arg+2]);
	    eidx = atoi(argv[arg+3]);
	    geflags = get_flags(argv[arg+4]);
	    efdata = (zip_uint8_t *)argv[arg+5];
	    if ((zip_file_extra_field_set(za, idx, eid, eidx, efdata, (zip_uint16_t)strlen((const char *)efdata), geflags)) < 0) {
		fprintf(stderr, "can't set extra field data for file at index `%d', extra field id `%d', index `%d': %s\n", idx, eid, eidx, zip_strerror(za));
		err = 1;
		break;
	    }
	    arg += 6;
	} else if (strcmp(argv[arg], "set_file_comment") == 0 && arg+2 < argc) {
	    /* set file comment */
	    idx = atoi(argv[arg+1]);
	    if (zip_file_set_comment(za, idx, argv[arg+2], (zip_uint16_t)strlen(argv[arg+2]), 0) < 0) {
		fprintf(stderr, "can't set file comment at index `%d' to `%s': %s\n", idx, argv[arg+2], zip_strerror(za));
		err = 1;
		break;
	    }
	    arg += 3;
        } else if (strcmp(argv[arg], "set_file_compression") == 0 && arg+3 < argc) {
            /* set file compression */
            zip_int32_t method;
            zip_uint32_t flags;
            idx = atoi(argv[arg+1]);
            method = get_compression_method(argv[arg+2]);
            flags = atoi(argv[arg+3]);
            if (zip_set_file_compression(za, idx, method, flags) < 0) {
		fprintf(stderr, "can't set file compression method at index `%d' to `%s', flags `%d': %s\n", idx, argv[arg+2], flags, zip_strerror(za));
		err = 1;
		break;
            }
            arg += 4;
	} else {
	    fprintf(stderr, "unrecognized command `%s', or not enough arguments\n", argv[arg]);
	    err = 1;
	    break;
	}
    }

    if (zip_close(za) == -1) {
	fprintf(stderr, "can't close zip archive `%s': %s\n", archive, zip_strerror(za));
	return 1;
    }

    return err;
}
Esempio n. 23
0
void write_metadata(const char *filename, FLAC__StreamMetadata *block, unsigned block_number, FLAC__bool raw, FLAC__bool hexdump_application)
{
	unsigned i, j;

/*@@@ yuck, should do this with a varargs function or something: */
#define PPR if(filename)printf("%s:",filename);
	PPR; printf("METADATA block #%u\n", block_number);
	PPR; printf("  type: %u (%s)\n", (unsigned)block->type, block->type < FLAC__METADATA_TYPE_UNDEFINED? FLAC__MetadataTypeString[block->type] : "UNKNOWN");
	PPR; printf("  is last: %s\n", block->is_last? "true":"false");
	PPR; printf("  length: %u\n", block->length);

	switch(block->type) {
		case FLAC__METADATA_TYPE_STREAMINFO:
			PPR; printf("  minimum blocksize: %u samples\n", block->data.stream_info.min_blocksize);
			PPR; printf("  maximum blocksize: %u samples\n", block->data.stream_info.max_blocksize);
			PPR; printf("  minimum framesize: %u bytes\n", block->data.stream_info.min_framesize);
			PPR; printf("  maximum framesize: %u bytes\n", block->data.stream_info.max_framesize);
			PPR; printf("  sample_rate: %u Hz\n", block->data.stream_info.sample_rate);
			PPR; printf("  channels: %u\n", block->data.stream_info.channels);
			PPR; printf("  bits-per-sample: %u\n", block->data.stream_info.bits_per_sample);
#ifdef _MSC_VER
			PPR; printf("  total samples: %I64u\n", block->data.stream_info.total_samples);
#else
			PPR; printf("  total samples: %llu\n", (unsigned long long)block->data.stream_info.total_samples);
#endif
			PPR; printf("  MD5 signature: ");
			for(i = 0; i < 16; i++) {
				printf("%02x", (unsigned)block->data.stream_info.md5sum[i]);
			}
			printf("\n");
			break;
		case FLAC__METADATA_TYPE_PADDING:
			/* nothing to print */
			break;
		case FLAC__METADATA_TYPE_APPLICATION:
			PPR; printf("  application ID: ");
			for(i = 0; i < 4; i++)
				printf("%02x", block->data.application.id[i]);
			printf("\n");
			PPR; printf("  data contents:\n");
			if(0 != block->data.application.data) {
				if(hexdump_application)
					hexdump(filename, block->data.application.data, block->length - FLAC__STREAM_METADATA_HEADER_LENGTH, "    ");
				else
					(void) local_fwrite(block->data.application.data, 1, block->length - FLAC__STREAM_METADATA_HEADER_LENGTH, stdout);
			}
			break;
		case FLAC__METADATA_TYPE_SEEKTABLE:
			PPR; printf("  seek points: %u\n", block->data.seek_table.num_points);
			for(i = 0; i < block->data.seek_table.num_points; i++) {
				if(block->data.seek_table.points[i].sample_number != FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER) {
#ifdef _MSC_VER
					PPR; printf("    point %u: sample_number=%I64u, stream_offset=%I64u, frame_samples=%u\n", i, block->data.seek_table.points[i].sample_number, block->data.seek_table.points[i].stream_offset, block->data.seek_table.points[i].frame_samples);
#else
					PPR; printf("    point %u: sample_number=%llu, stream_offset=%llu, frame_samples=%u\n", i, (unsigned long long)block->data.seek_table.points[i].sample_number, (unsigned long long)block->data.seek_table.points[i].stream_offset, block->data.seek_table.points[i].frame_samples);
#endif
				}
				else {
					PPR; printf("    point %u: PLACEHOLDER\n", i);
				}
			}
			break;
		case FLAC__METADATA_TYPE_VORBIS_COMMENT:
			PPR; printf("  vendor string: ");
			write_vc_field(0, &block->data.vorbis_comment.vendor_string, raw, stdout);
			PPR; printf("  comments: %u\n", block->data.vorbis_comment.num_comments);
			for(i = 0; i < block->data.vorbis_comment.num_comments; i++) {
				PPR; printf("    comment[%u]: ", i);
				write_vc_field(0, &block->data.vorbis_comment.comments[i], raw, stdout);
			}
			break;
		case FLAC__METADATA_TYPE_CUESHEET:
			PPR; printf("  media catalog number: %s\n", block->data.cue_sheet.media_catalog_number);
#ifdef _MSC_VER
			PPR; printf("  lead-in: %I64u\n", block->data.cue_sheet.lead_in);
#else
			PPR; printf("  lead-in: %llu\n", (unsigned long long)block->data.cue_sheet.lead_in);
#endif
			PPR; printf("  is CD: %s\n", block->data.cue_sheet.is_cd? "true":"false");
			PPR; printf("  number of tracks: %u\n", block->data.cue_sheet.num_tracks);
			for(i = 0; i < block->data.cue_sheet.num_tracks; i++) {
				const FLAC__StreamMetadata_CueSheet_Track *track = block->data.cue_sheet.tracks+i;
				const FLAC__bool is_last = (i == block->data.cue_sheet.num_tracks-1);
				const FLAC__bool is_leadout = is_last && track->num_indices == 0;
				PPR; printf("    track[%u]\n", i);
#ifdef _MSC_VER
				PPR; printf("      offset: %I64u\n", track->offset);
#else
				PPR; printf("      offset: %llu\n", (unsigned long long)track->offset);
#endif
				if(is_last) {
					PPR; printf("      number: %u (%s)\n", (unsigned)track->number, is_leadout? "LEAD-OUT" : "INVALID");
				}
				else {
					PPR; printf("      number: %u\n", (unsigned)track->number);
				}
				if(!is_leadout) {
					PPR; printf("      ISRC: %s\n", track->isrc);
					PPR; printf("      type: %s\n", track->type == 1? "DATA" : "AUDIO");
					PPR; printf("      pre-emphasis: %s\n", track->pre_emphasis? "true":"false");
					PPR; printf("      number of index points: %u\n", track->num_indices);
					for(j = 0; j < track->num_indices; j++) {
						const FLAC__StreamMetadata_CueSheet_Index *index = track->indices+j;
						PPR; printf("        index[%u]\n", j);
#ifdef _MSC_VER
						PPR; printf("          offset: %I64u\n", index->offset);
#else
						PPR; printf("          offset: %llu\n", (unsigned long long)index->offset);
#endif
						PPR; printf("          number: %u\n", (unsigned)index->number);
					}
				}
			}
			break;
		case FLAC__METADATA_TYPE_PICTURE:
			PPR; printf("  type: %u (%s)\n", block->data.picture.type, block->data.picture.type < FLAC__STREAM_METADATA_PICTURE_TYPE_UNDEFINED? FLAC__StreamMetadata_Picture_TypeString[block->data.picture.type] : "UNDEFINED");
			PPR; printf("  MIME type: %s\n", block->data.picture.mime_type);
			PPR; printf("  description: %s\n", block->data.picture.description);
			PPR; printf("  width: %u\n", (unsigned)block->data.picture.width);
			PPR; printf("  height: %u\n", (unsigned)block->data.picture.height);
			PPR; printf("  depth: %u\n", (unsigned)block->data.picture.depth);
			PPR; printf("  colors: %u%s\n", (unsigned)block->data.picture.colors, block->data.picture.colors? "" : " (unindexed)");
			PPR; printf("  data length: %u\n", (unsigned)block->data.picture.data_length);
			PPR; printf("  data:\n");
			if(0 != block->data.picture.data)
				hexdump(filename, block->data.picture.data, block->data.picture.data_length, "    ");
			break;
		default:
			PPR; printf("  data contents:\n");
			if(0 != block->data.unknown.data)
				hexdump(filename, block->data.unknown.data, block->length, "    ");
			break;
	}
#undef PPR
}
Esempio n. 24
0
/*
 * Returns DEFAULT_BLK_SZ bytes of random data per call
 * returns 0 if generation succeeded, <0 if something went wrong
 */
static int _get_more_prng_bytes(struct prng_context *ctx, int cont_test)
{
	int i;
	unsigned char tmp[DEFAULT_BLK_SZ];
	unsigned char *output = NULL;


	dbgprint(KERN_CRIT "Calling _get_more_prng_bytes for context %p\n",
		ctx);

	hexdump("Input DT: ", ctx->DT, DEFAULT_BLK_SZ);
	hexdump("Input I: ", ctx->I, DEFAULT_BLK_SZ);
	hexdump("Input V: ", ctx->V, DEFAULT_BLK_SZ);

	/*
	 * This algorithm is a 3 stage state machine
	 */
	for (i = 0; i < 3; i++) {

		switch (i) {
		case 0:
			/*
			 * Start by encrypting the counter value
			 * This gives us an intermediate value I
			 */
			memcpy(tmp, ctx->DT, DEFAULT_BLK_SZ);
			output = ctx->I;
			hexdump("tmp stage 0: ", tmp, DEFAULT_BLK_SZ);
			break;
		case 1:

			/*
			 * Next xor I with our secret vector V
			 * encrypt that result to obtain our
			 * pseudo random data which we output
			 */
			xor_vectors(ctx->I, ctx->V, tmp, DEFAULT_BLK_SZ);
			hexdump("tmp stage 1: ", tmp, DEFAULT_BLK_SZ);
			output = ctx->rand_data;
			break;
		case 2:
#ifdef CONFIG_CRYPTO_FIPS
// fail fast if we're in a FIPS error state
			if (unlikely(fips_error()))
				return -EINVAL;
#endif
			/*
			 * First check that we didn't produce the same
			 * random data that we did last time around through this
			 */
#if FIPS_FUNC_TEST == 5
			memcpy(ctx->rand_data, ctx->last_rand_data, DEFAULT_BLK_SZ);
#endif
			if (!memcmp(ctx->rand_data, ctx->last_rand_data,
					DEFAULT_BLK_SZ)) {
				if (cont_test) {
#ifdef CONFIG_CRYPTO_FIPS
					set_fips_error();

					if (fips_panic)
						panic("FIPS: cprng %p Failed repetition check!\n", ctx);
#else
					panic("cprng %p Failed repetition check!\n",
						ctx);
#endif
				}

				printk(KERN_ERR
					"ctx %p Failed repetition check!\n",
					ctx);

				ctx->flags |= PRNG_NEED_RESET;
				return -EINVAL;
			}
			memcpy(ctx->last_rand_data, ctx->rand_data,
				DEFAULT_BLK_SZ);

			/*
			 * Lastly xor the random data with I
			 * and encrypt that to obtain a new secret vector V
			 */
			xor_vectors(ctx->rand_data, ctx->I, tmp,
				DEFAULT_BLK_SZ);
			output = ctx->V;
			hexdump("tmp stage 2: ", tmp, DEFAULT_BLK_SZ);
			break;
		}


		/* do the encryption */
		crypto_cipher_encrypt_one(ctx->tfm, output, tmp);

	}

	/*
	 * Now update our DT value
	 */
	for (i = DEFAULT_BLK_SZ - 1; i >= 0; i--) {
		ctx->DT[i] += 1;
		if (ctx->DT[i] != 0)
			break;
	}

	dbgprint("Returning new block for context %p\n", ctx);
	ctx->rand_data_valid = 0;

	hexdump("Output DT: ", ctx->DT, DEFAULT_BLK_SZ);
	hexdump("Output I: ", ctx->I, DEFAULT_BLK_SZ);
	hexdump("Output V: ", ctx->V, DEFAULT_BLK_SZ);
	hexdump("New Random Data: ", ctx->rand_data, DEFAULT_BLK_SZ);

	return 0;
}
Esempio n. 25
0
static void decode_udp (const uint8_t *packet, size_t pk_len, int pk_layer) {
	union {
		const struct myudphdr *u;
		const uint8_t *d;
	} u_u;
	uint16_t sport=0, dport=0, len=0, chksum=0, c_chksum=0;
	int bad_cksum=0;
	union {
		const ip_pseudo_t *ipph_ptr;
		const uint8_t *ptr;
	} ipph_u;
	struct chksumv c[2];

	u_u.d=packet;

	if (pk_layer == 4) { /* this is inside an icmp error reflection, check that */
		if (r_u.i.proto != IPPROTO_ICMP) {
			ERR("FIXME in UDP not inside a ICMP error?");
			return;
		}
		/* see TCP comment above about special treatment */
		if (pk_len < 4) {
			ERR("UDP header too short to get source and dest ports");
			return;
		}
		if (pk_len >= 4 && pk_len < sizeof(struct myudphdr)) {
			/* this is reversed from a response, the host never responded so flip src/dest ports */
			r_u.i.sport=ntohs(u_u.u->dest);
			r_u.i.dport=ntohs(u_u.u->source);
			r_u.i.tseq=0;
			r_u.i.mseq=0;

			return;
		}
	}

	if (pk_len < sizeof(struct myudphdr)) {
		ERR("short udp header");
		return;
	}
	sport=ntohs(u_u.u->source);
	dport=ntohs(u_u.u->dest);
	len=ntohs(u_u.u->len);
	chksum=ntohs(u_u.u->check);

	ipph_u.ipph_ptr=&ipph;
	ipph.len=ntohs(pk_len);

	c[0].len=sizeof(ipph);
	c[0].ptr=ipph_u.ptr;

	c[1].len=pk_len;
	c[1].ptr=packet;

	c_chksum=do_ipchksumv((const struct chksumv *)&c[0], 2);
	if (c_chksum != 0) {
		DBG(M_PKT, "bad udp checksum, ipchksumv returned 0x%x", c_chksum);
		bad_cksum=1;
	}

	if (ISDBG(M_PKT) || GET_SNIFF()) {
		INF("UDP : pklen " STFMT " sport %u dport %u len %u checksum %04x%s",
		pk_len, sport, dport, len, chksum, bad_cksum == 0 ? " [bad cksum]" : " [cksum ok]");
	}

	if (pk_layer == 2) {
		r_u.i.sport=sport;
		r_u.i.dport=dport;
		r_u.i.type=0;
		r_u.i.subtype=0;
		r_u.i.tseq=0;
		r_u.i.mseq=0;

		report_push();
        }
	else if (pk_layer == 4) {
		/* this is reversed from a response, the host never responded so flip src/dest ports */
		r_u.i.sport=dport;
		r_u.i.dport=sport;
		r_u.i.tseq=0;
		r_u.i.mseq=0;
	}
	else {
		ERR("FIXME at decode UDP at layer %d", pk_layer);
		return;
	}

	pk_len -= sizeof(struct myudphdr);
	packet += sizeof(struct myudphdr);

	if (pk_len && (ISDBG(M_PKT) || GET_SNIFF())) {
		INF("UDP : dumping UDP payload");
		hexdump(packet, pk_len);
	}

	return;
}
Esempio n. 26
0
int main(int argc, char *argv[])
{
	u_int8_t *mapping;
	u_int8_t aModExpOperandA_l[192];
	u_int8_t aModExpOperandB_l[192];
	u_int8_t aModExpExpectedRes_l[192];
	u_int8_t aModulus_l[192];
	u_int8_t aReciprocal_l[192];
	u_int8_t gtothex[192];
	struct pkprogram expModP;

	memset(&expModP, 0, sizeof(expModP));

	progname = argv[0];

	mapping = mapvulcanpk();

	/* initialize chip */
	vulcanpk_init(mapping);

	memcpy(aModExpOperandA_l, aModExpOperandA, 192);
	bigendianize((u_int32_t *)aModExpOperandA_l, 192 / sizeof(u_int32_t));

	memcpy(aModExpOperandB_l, aModExpOperandB, 192);
	bigendianize((u_int32_t *)aModExpOperandB_l, 192 / sizeof(u_int32_t));

	memcpy(aModExpExpectedRes_l, aModExpExpectedRes, 192);
	bigendianize((u_int32_t *)aModExpExpectedRes_l, 192 /
		     sizeof(u_int32_t));

	memcpy(aModulus_l, aModulus, 192);
	bigendianize((u_int32_t *)aModulus_l, 192 / sizeof(u_int32_t));

	memcpy(aReciprocal_l, aReciprocal, 192);
	bigendianize((u_int32_t *)aReciprocal_l, 192 / sizeof(u_int32_t));

	expModP.valuesLittleEndian = FALSE;

	/* g-value */
	expModP.aValues[0]  = aModExpOperandA_l;
	expModP.aValueLen[0] = 192;

	/* ^x-value */
	expModP.aValues[2]  = aModExpOperandB_l;
	expModP.aValueLen[2] = 192;

	/* register 2 is result. */
	/* register 3 is scratch */

	/* M = modulus */
	expModP.aValues[8]  = aModulus_l;
	expModP.aValueLen[8] = 192;

	/* reciprocal M(1) */
	expModP.aValues[9]  = aReciprocal_l;
	expModP.aValueLen[9] = 192;

	/* registers 6,7,8 is M(2),M(3),M(4), scratch */

	expModP.chunksize = 3;  /* *64 = 192 bytes/chunk */
	expModP.oOffset   = 3;  /* B(1) is result */
	expModP.oValue    = gtothex;
	expModP.oValueLen = sizeof(gtothex);

	/* ask to have the exponentiation done now! */
	expModP.pk_program[0] = /* sizes are ModLen=48(*32=1536),
	                           EXP_len=1535+1, RED_len=0 */
				(0 << 24) | (1535 << 8) | (48);
	expModP.pk_program[1] = /* opcode 1100=0xC (mod-exp),
	                           with A=0, B=2(6),M=8(24)*/
				(0xC << 24) | (24 << 16) | (6 << 8) | (0 << 0);

	expModP.pk_proglen = 2;
	execute_pkprogram(mapping, &expModP);

	printf("got: \n");
	hexdump(gtothex, 0, 192);

	printf("expected: \n");
	hexdump(aModExpExpectedRes_l, 0, 192);

	if (memcmp(gtothex, aModExpExpectedRes_l, 192) == 0)
		printf("SUCCESS\n");

	exit(0);
}
Esempio n. 27
0
/* Send the gamma */
static SANE_Status
leo_send_gamma (Leo_Scanner * dev)
{
  CDB cdb;
  SANE_Status status;
  struct
  {
    unsigned char gamma_R[GAMMA_LENGTH];
    unsigned char gamma_G[GAMMA_LENGTH];	/* also gray */
    unsigned char gamma_B[GAMMA_LENGTH];
  }
  param;
  size_t i;
  size_t size;

  DBG (DBG_proc, "leo_send_gamma: enter\n");

  size = sizeof (param);
  assert (size == 3 * GAMMA_LENGTH);
  MKSCSI_SEND_10 (cdb, 0x03, 0x01, size);

  if (dev->val[OPT_CUSTOM_GAMMA].w)
    {
      /* Use the custom gamma. */
      if (dev->scan_mode == LEO_GRAYSCALE)
	{
	  /* Gray */
	  for (i = 0; i < GAMMA_LENGTH; i++)
	    {
	      param.gamma_R[i] = dev->gamma_GRAY[i];
	      param.gamma_G[i] = 0;
	      param.gamma_B[i] = 0;
	    }
	}
      else
	{
	  /* Color */
	  for (i = 0; i < GAMMA_LENGTH; i++)
	    {
	      param.gamma_R[i] = dev->gamma_R[i];
	      param.gamma_G[i] = dev->gamma_G[i];
	      param.gamma_B[i] = dev->gamma_B[i];
	    }
	}
    }
  else
    {
      for (i = 0; i < GAMMA_LENGTH; i++)
	{
	  param.gamma_R[i] = gamma_init[i];
	  param.gamma_G[i] = gamma_init[i];
	  param.gamma_B[i] = gamma_init[i];
	}
    }

  hexdump (DBG_info2, "leo_send_gamma:", cdb.data, cdb.len);

  status = sanei_scsi_cmd2 (dev->sfd, cdb.data, cdb.len,
			    &param, size, NULL, NULL);

  DBG (DBG_proc, "leo_send_gamma: exit, status=%d\n", status);

  return (status);
}
Esempio n. 28
0
void t_readjunk (transfer * const t)
{
  int i,j;
  int show;
  
  updatecontext();
  
  i = recv(t->con.clientsocket, gdata.sendbuff, BUFFERSIZE, MSG_DONTWAIT);
  
  if (gdata.debug > 52)
    {
      ioutput(OUT_S, COLOR_BLUE, "Read %d:", i);
      hexdump(OUT_S, COLOR_BLUE, "", gdata.sendbuff, i);
    }
  
  if (i < 0)
    {
      t_closeconn(t,"Connection Lost",errno);
    }
  else if (i < 1)
    {
      t_closeconn(t,"Connection Lost",0);
    }
  else
    {
      t->con.lastcontact = gdata.curtime;
      
      for (j=0; j<i; j++)
        {
          int byte;

          if (t->mirc_dcc64)
            {
              byte = 7-((t->bytesgot+j)%8);
              t->curack &= ~(0xFFULL << (byte*8));
              t->curack |= (ir_uint64)(gdata.sendbuff[j]) << (byte*8);
            }
          else
            {
              byte = 3-((t->bytesgot+j)%4);
              t->curack &= ~(0xFFUL << (byte*8));
              t->curack |= (ir_uint64)gdata.sendbuff[j] << (byte*8);
            }
          
          if (byte == 0)
            {
              show = verify_acknowlede(t);
              t->lastack = t->curack;
            
              if (t->tr_status == TRANSFER_STATUS_WAITING)
                show ++;

              if ((gdata.debug >54) && (show > 0))
                {
                  ioutput(OUT_S, COLOR_BLUE,
                          "XDCC [%02i:%s on %s]: Acknowleged %" LLPRINTFMT "d Bytes",
                          t->id, t->nick, gdata.networks[ t->net ].name,
                          t->lastack );
                }
            }
        }
      
      t->bytesgot += i;
    }
  
  return;
}
Esempio n. 29
0
/* Set a window. */
static SANE_Status
leo_set_window (Leo_Scanner * dev)
{
  size_t size;
  CDB cdb;
  unsigned char window[48];
  SANE_Status status;

  DBG (DBG_proc, "leo_set_window: enter\n");

  size = sizeof (window);
  MKSCSI_SET_WINDOW (cdb, size);

  memset (window, 0, size);

  /* size of the windows descriptor block */
  window[7] = sizeof (window) - 8;
  window[1] = sizeof (window) - 2;

  /* X and Y resolution */
  Ito16 (dev->x_resolution, &window[10]);
  Ito16 (dev->y_resolution, &window[12]);

  /* Upper Left (X,Y) */
  Ito32 (dev->x_tl, &window[14]);
  Ito32 (dev->y_tl, &window[18]);

  /* Width and length */
  Ito32 (dev->width, &window[22]);
  Ito32 (dev->length, &window[26]);


  /* Image Composition */
  switch (dev->scan_mode)
    {
    case LEO_BW:
      window[33] = 0x00;
      break;
    case LEO_HALFTONE:
      window[33] = 0x01;
      break;
    case LEO_GRAYSCALE:
      window[33] = 0x02;
      break;
    case LEO_COLOR:
      window[33] = 0x05;
      break;
    }

  /* Depth */
  window[34] = dev->depth;

  /* Unknown - invariants */
  window[31] = 0x80;
  window[43] = 0x01;

  hexdump (DBG_info2, "windows", window, sizeof (window));

  status = sanei_scsi_cmd2 (dev->sfd, cdb.data, cdb.len,
			    window, sizeof (window), NULL, NULL);

  DBG (DBG_proc, "leo_set_window: exit, status=%d\n", status);

  return status;
}
Esempio n. 30
0
		//The value
		uv_assert_ret(m_symbolSectionHeader);
		uv_assert_err_ret(m_symbolSectionHeader->getSymbolStringIndex(name, &offset));	
		
		ELF_SYMBOL_DEBUG
		({
			UVDData *data = NULL;
			m_relocatableData.getRelocatableData(&data);
			printf_elf_symbol_debug("name: %s, %s, symbol string table index: 0x%.8X, relocatable data: 0x%.8X, data: 0x%.8X\n", name.c_str(), m_sName.c_str(), offset, (unsigned int)&m_relocatableData, (unsigned int)data);
		});
		
		m_symbol.st_name = offset;

	}
	
	ELF_SYMBOL_DEBUG(hexdump((char *)&m_symbol, sizeof(m_symbol)));

	return UV_ERR_OK;
}

uv_err_t UVDElfSymbol::getData(UVDData **data)
{
	uint32_t isEmpty = 0;

	//CHECKME: what if its a zero sized symbol?  Do those exist?	
	uv_assert_err_ret(m_relocatableData.isEmpty(&isEmpty));

	//Undefined symbols will not have associated data
	if( isEmpty )
	{
		uv_assert_ret(data);