示例#1
0
int
encode_sample_test(const struct ccn_pkey *signing_key, const struct ccn_pkey *verification_key, 
			const char *algorithm, char *paths[], char *contents[], 
			struct ccn_charbuf *signed_info, char *outname)
{
    int result = 0;
    int fd;
    struct path * cur_path = NULL;
    struct ccn_charbuf *buffer = ccn_charbuf_create();
    struct ccn_skeleton_decoder dd = {0};
    ssize_t res;

    printf("Encoding sample message data length %d\n", (int)strlen(contents[0]));
    cur_path = path_create(paths[0]);
    if (encode_message(buffer, cur_path, contents[0], strlen(contents[0]), signed_info, signing_key, 
			algorithm)) {
        printf("Failed to encode message!\n");
	result = 1;
    } else {
        printf("Encoded sample message length is %d\n", (int)buffer->length);

        res = ccn_skeleton_decode(&dd, buffer->buf, buffer->length);
        if (!(res == buffer->length && dd.state == 0)) {
            printf("Failed to decode!  Result %d State %d\n", (int)res, dd.state);
            result = 1;
        }
        if (outname != NULL) {
            fd = open(outname, O_WRONLY|O_CREAT|O_TRUNC, S_IRWXU);
            if (fd == -1)
                perror(outname);
            res = write(fd, buffer->buf, buffer->length);
            close(fd);
        }
        if (decode_message(buffer, cur_path, contents[0], strlen(contents[0]), verification_key) != 0) {
            result = 1;
        }
        printf("Expect signature verification failure: ");
        if (buffer->length >= 20)
            buffer->buf[buffer->length - 20] += 1;
        if (decode_message(buffer, cur_path, contents[0], strlen(contents[0]), verification_key) == 0) {
            result = 1;
        }
    }
    path_destroy(&cur_path);
    ccn_charbuf_destroy(&buffer);
    printf("Done with sample message\n");
    return result;
}
示例#2
0
    void decode_parcels_impl(
        Parcelport & parcelport
      , Connection connection
      , boost::shared_ptr<Buffer> buffer
      , boost::shared_ptr<std::vector<util::serialization_chunk> > chunks)
    {
        std::vector<util::serialization_chunk> *chunks_ = 0;
        if(chunks) chunks_ = chunks.get();

#if defined(HPX_HAVE_SECURITY)
        connection->first_message_ = decode_message(parcelport_, buffer, chunks_,
            connection->first_message_);
#else
        decode_message(parcelport, buffer, chunks_);
#endif
    }
示例#3
0
    void decode_parcels_impl(
        Parcelport & parcelport
      , boost::shared_ptr<Buffer> buffer
      , boost::shared_ptr<std::vector<util::serialization_chunk> > chunks
      , bool first_message)
    {
        std::vector<util::serialization_chunk> *chunks_ = 0;
        if(chunks) chunks_ = chunks.get();

#if defined(HPX_HAVE_SECURITY)
        decode_message(parcelport, buffer, chunks_, first_message);
#else
        decode_message(parcelport, buffer, chunks_);
#endif
        buffer->parcels_decoded_ = true;
    }
        void handle_read_data(boost::system::error_code const& e,
            boost::tuple<Handler> handler)
        {
            if (e) {
                boost::get<0>(handler)(e);

                // Issue a read operation to read the next parcel.
                async_read(boost::get<0>(handler));
            }
            else {
                // complete data point and pass it along
                receive_data_.time_ = timer_.elapsed_nanoseconds() -
                    receive_data_.time_;

                // now send acknowledgment message
                void (parcelport_connection::*f)(boost::system::error_code const&, 
                          boost::tuple<Handler>)
                    = &parcelport_connection::handle_write_ack<Handler>;

                // hold on to received data to avoid data races
                parcelset::shmem::data_buffer data(in_buffer_);
                performance_counters::parcels::data_point receive_data = 
                    receive_data_;

                window_.async_write_ack(
                    boost::bind(f, shared_from_this(), 
                        boost::asio::placeholders::error, handler));

                // add parcel data to incoming parcel queue
                decode_message(parcelport_, data, receive_data);

                // Inform caller that data has been received ok.
                boost::get<0>(handler)(e);
            }
        }
示例#5
0
//gcc router.c -o router graph.c socket_open_read_write.c -w message_encode_decode.c -w
//./router port_number
int main(int argc, char *argv[]){
    /*Initializing globals*/
	memset(message_history_table,0,TABLE_SIZE);
    ROUTER_ID=atoi(argv[1]);
    message_count=0;
    
    //Setting up socket
	int port_number=ROUTER_BASE_PORT+ROUTER_ID;
    int my_socket=set_up_socket(port_number);
    char *msg_string;
    char c;
    msg *received_message;
	//listening now
    listen_again:
    initialize_graph();
    msg_string=read_from_socket(my_socket);
    received_message=decode_message(msg_string);    
   // free(msg_string);
    do_stuff(received_message);
   // printf("Press y to continue listening(you may have to press twice for assurance).n to kill the socket and exit.\n");
   // c=getchar();
   // c=getchar();
    //if(c=='y')
        goto listen_again;       
    close(my_socket);
    return 0; 

}
示例#6
0
int zmq::gssapi_client_t::decode (msg_t *msg_)
{
    zmq_assert (state == connected);

    if (do_encryption)
      return decode_message (msg_);

    return 0;
}
示例#7
0
void game_loop()
{
	int player_input;
	socklen_t slen = sizeof(client_config.addr);

	printf("Nospiediet '%c', lai sāktu spēli!\n", 'b');

	bash_set_window_size(client_config.width, client_config.height);
	bash_hide_cursor();
	client_config.state = PLAYER_STATE_INITIAL;

	memset(field, DEFAULT_BLANK_CHAR, sizeof(field));
	do {
		if ((resp_len = recvfrom(sender, msg, MAX_MESSAGE_SIZE, 0,
			(struct sockaddr *) &client_config.addr, &slen)) == -1) {
			if (errno != EAGAIN)
				error("Error while receving game updates");
		}

		if (resp_len > 0) {
			decode_message(msg, resp_len);
		}

		if ((player_input = fgetc(stdin)) != EOF) {
			send_player_action(player_input);

			switch (player_input) {
			case 'Q':
			case 'q':
				client_config.state = PLAYER_STATE_LEFT;
				break;
			}

		}

		/* Draw only when in game */
		if (client_config.state == PLAYER_STATE_ACTIVE)
			game_draw();
	} while (client_config.state < PLAYER_STATE_DEAD);

	switch (client_config.state) {
	case PLAYER_STATE_DEAD:
		printf("Jūs nomirāt!\n");
		break;
	case PLAYER_STATE_END:
		/*
				if (client_config.winner == client_config.id)
					printf("Jūs uzvarējāt!\n");
				else
					printf("Jūs zaudējāt!\n");
		 */
		break;
	}
}
示例#8
0
/* MAIN FUNCTION */
int main()
{
    // global setup
    flags.flag_operation_code = 0b00;       // it means no operation required
    flags.flag_bluetooth_message = 0b0;     // initialization
    flags.flag_timeout_expired = 0b0;
    flags.flag_timeout_measurement = 0b0;
    state = IDLE;
    rn42.attach(&isr_bluetooth);            // attach interrupt to serial port
    myled = 0;                              // turn off the led
    bluetooth_setup();
    number_of_asterisk = 0;
    i = 0;

    //infinite loop
    while(1) {

        switch(state) {

            case IDLE:
                while(!flags.flag_bluetooth_message){};
                state = DECODE;
                break;
            case DECODE:
                decode_message();
                flags.flag_bluetooth_message = 0b0;     //clear the bit
                state = EXECUTION;
                break;
            case EXECUTION:
                switch(flags.flag_operation_code) {

                    case 0b01:      //obtainmesurement
                        send_reply();
                        wait(0.1);
                        line_following();
                        state = IDLE;
                        flags.flag_operation_code = 0b00;       //nop
                        break;
                    case 0b10:      //obtainstatus
                        send_reply();
                        state = IDLE;
                        flags.flag_operation_code = 0b00;       //nop
                        break;
                }
                break;
        }
    }

}
int check_function(){

	msg a;
	time_t current_time;
	a.sender_id=10;
	a.receiver_id=20;
	a.msg_type=1;
	current_time=time(&current_time);
	a.timestamp=(double)current_time;
	//printf("time:%lf\n",a.timestamp );
	a.message=(char *)malloc(sizeof(char)*300);
	a.message="This is the message I am trying to post.";
	char *m_msg=code_message(&a);
	msg *myMessage=decode_message(m_msg);
	printf("%d ,%d ,%d ,%lf, %s\n", myMessage->sender_id,myMessage->receiver_id,myMessage->msg_type,myMessage->timestamp,myMessage->message);
}
示例#10
0
void sinsp_decoder_syslog::on_write(sinsp_evt* evt, char *data, uint32_t len)
{
	char pri[PRI_BUF_SIZE];
	char* tc = data + 1;
	char* te = data + len;
	uint32_t j = 0;

	while(tc < te && *tc != '>' && *tc != '\0' && j < PRI_BUF_SIZE - 1)
	{
		pri[j++] = *tc;
		tc++;
	}

	pri[j] = 0;

	decode_message(data, len, pri, j);
}
示例#11
0
void *
get_data_routine ( void* parg )
{
    ISP_EID eid = EID_OK;
    IspMessage ispmsg;

    recv_size = MESSAGE_SIZE;
    eid = serial_recv(&serial_dev,
                      recv_buffer,
                      &recv_size);
    printf("Received %d bytes\n", recv_size);

    if (eid == EID_OK)
    {
        eid = decode_message(recv_buffer, &ispmsg);
        if (eid == EID_OK)
        {
            // process message
            switch (ispmsg.hdr.typ)
            {
                case MSGT_ACK:
                    printf("Message sent successfully: %d\n", ispmsg.msg.ack.resp);
                    break;

                case MSGT_SIG_READ:
                    for (int i = 0; i < recv_size; ++i)
                        printf("%02X ", recv_buffer[i]);
                    printf("\n");
                    printf("-------------\n");
                    printf("Length: %4d\n", ispmsg.hdr.len);
                    printf("CRC: %04x\n", ispmsg.hdr.crc);
                    printf("Signature: ");
                    for (int i = 0; i < ispmsg.hdr.len; ++i)
                        printf("%02X ", ispmsg.msg.data[i]);
                    printf("\n");
                    break;

                default:
                    printf("Invalid message type: %d\n", ispmsg.hdr.typ);
                    break;
            }
        }
    }

    return (void *)(eid);
}
示例#12
0
int zmq::gssapi_mechanism_base_t::process_ready (msg_t *msg_)
{
    if (do_encryption) {
        const int rc = decode_message (msg_);
        if (rc != 0)
            return rc;
    }

    const unsigned char *ptr = static_cast <unsigned char *> (msg_->data ());
    size_t bytes_left = msg_->size ();

    if (bytes_left < 6 || memcmp (ptr, "\x05READY", 6)) {
        errno = EPROTO;
        return -1;
    }
    ptr += 6;
    bytes_left -= 6;
    return parse_metadata (ptr, bytes_left);
}
 int expect_message(SrsMessage** pmsg, T** ppacket)
 {
     *pmsg = NULL;
     *ppacket = NULL;
     
     int ret = ERROR_SUCCESS;
     
     while (true) {
         SrsMessage* msg = NULL;
         if ((ret = recv_message(&msg)) != ERROR_SUCCESS) {
             if (ret != ERROR_SOCKET_TIMEOUT && !srs_is_client_gracefully_close(ret)) {
                 srs_error("recv message failed. ret=%d", ret);
             }
             return ret;
         }
         srs_verbose("recv message success.");
         
         SrsPacket* packet = NULL;
         if ((ret = decode_message(msg, &packet)) != ERROR_SUCCESS) {
             srs_error("decode message failed. ret=%d", ret);
             srs_freep(msg);
             srs_freep(packet);
             return ret;
         }
         
         T* pkt = dynamic_cast<T*>(packet);
         if (!pkt) {
             srs_info("drop message(type=%d, size=%d, time=%"PRId64", sid=%d).", 
                 msg->header.message_type, msg->header.payload_length,
                 msg->header.timestamp, msg->header.stream_id);
             srs_freep(msg);
             srs_freep(packet);
             continue;
         }
         
         *pmsg = msg;
         *ppacket = pkt;
         break;
     }
     
     return ret;
 }
示例#14
0
void
process_message (char *message, int msg_len, int msg_buf_len)
{
  errno = 0;

  switch (decode_message (message)) {
    case HELO:
      helo (message);
      break;

    case SRVCTL:
      server_control (message);
      break;

    case IOINT:
      ioint (message);
      break;

    case IOCMD:
      iocmd (message);
      break;

    case IOIO:
      ioio (message);
      break;

    case READ:
      bdm_server_read (message);
      break;

    case WRITE:
      bdm_server_write (message, msg_len, msg_buf_len);
      break;

    case QUIT:
      quit ();
      break;

    default:
      break;
  }
}
示例#15
0
/*************************************************************
 * Reads encrypted text and creates encoded and              *
 * plain text files                                          *
 *************************************************************/
int 
main(int argc, char* argv[])
{
	FILE *f_plane_ptr, *f_encoded_ptr, *f_crypted_ptr;

	/* exit program and print error if encrypted text file could not be opened to read */

	/* exit program and print error if encoded text file could not be opened to write */

	decrypt_message(f_crypted_ptr, f_encoded_ptr);

	/* close encrypted and encoded files */

	/* exit program and print error if plain text file could not be opened to write */

	/* exit program and print error if encoded text file could not be opened to read */

	decode_message(f_encoded_ptr, f_plane_ptr);

	/* close encoded and plain files */

	return 0;
}
示例#16
0
int main(int argc, char **argv)
{
  int r;
  int broadcast = 1;

  if (argc < 2)
    barf("need a hostname");

  if (argc >= 3) {
    service = strdup(argv[2]);
  }

  ctx.sockfd = socket(AF_INET, SOCK_DGRAM, 0);
  if (ctx.sockfd < 0)
    barf(strerror(errno));

  if (lookup(argv[1]) < 0)
    barf("bad lookup");

  /* request broadcast permissions if possible */
  setsockopt(ctx.sockfd, SOL_SOCKET, SO_BROADCAST, &broadcast, sizeof(broadcast));
  
  /* trasmit query */
  r = sendto(ctx.sockfd, query, 4, 0, (struct sockaddr *)&ctx.saddr, sizeof(ctx.saddr));
  if (r<0)
    barf(strerror(errno));

  while (collect_response()) {
    message *m;
    m = decode_message(inmsg, inlen);
    report_message(m);
    printf ("\n");
  }

  return 0;
}
示例#17
0
/**
 * This parses a TLV record instead of a SNAC packet, which is itself 
 * inside of a FLAP PDU. We identify the precise item by the SNAC-family,
 * SNAC-subtype, and TLV-tag */
static void 
parse_tlv(struct TCPRECORD *sess, struct NetFrame *frame, const unsigned char *px, unsigned length)
{
	struct FerretEngine *eng = sess->eng;
	struct Ferret *ferret = eng->ferret;
	struct AIMPARSER *aim = &sess->layer7.aim;
	unsigned h;

	/* This function is going to process the data within a SNAC TLV field. 
	 * We are just going to handle this all in a big switch/case statement. */
#define HASH(x,y,z) (((x)<<16)|((y)<<8)|(z))
	h = HASH(aim->pdu.family, aim->pdu.subtype, aim->tlv_tag);

	/* If we are in the middle of parsing the string, just grab
	 * it in our re-assembly buffer */
	if (px != NULL) {
		strfrag_append(sess->str, px, length);
		return;
	}
	
	/* Process the string we've reassembled. We are going to hash on the full context
	 * of the PDU rather than just the TLV tag */
	switch (h) {
	case 0x00170203: /* family=Sign-on, subtype=Logon, tag=client-id-string */
		JOTDOWN(ferret, 
			JOT_SRC("ID-IP",frame),
			JOT_PRINT("AIM-Client-ID", sess->str->the_string, sess->str->length),
			0);
		break;
	case 0x0017020e: /* family=Sign-on, subtype=Logon, tag=country */
		JOTDOWN(ferret, 
			JOT_SRC("ID-IP",frame),
			JOT_PRINT("AIM-Country", sess->str->the_string, sess->str->length),
			0);
		break;
	case 0x0017020f: /* family=Sign-on, subtype=Logon, tag=language */
		JOTDOWN(ferret, 
			JOT_SRC("ID-IP",frame),
			JOT_PRINT("AIM-Language", sess->str->the_string, sess->str->length),
			0);
		break;
	case 0x00170225: /* family=Sign-on, subtype=Logon, tag=password hash */
		JOTDOWN(ferret, 
			JOT_SRC("ID-IP",frame),
			JOT_HEXSTR("AIM-Password-Hash", sess->str->the_string, sess->str->length),
			0);
		break;
		break;
	case 0x00170201: /* family=Sign-on, subtype=Logon, tag=screen-name */
	case 0x00170601: /* family=Sign-on, subtype=Sign-on, tag=screen-name  */
		/* This is the sign-on 'screen-name' in the packet that the user sends to
		 * the logon server (logon.oscar.aol.com). The server will respond with
		 * a 'challenge'. The user will then send the screen-name and hash of 
		 * challenge and password to the real server he wants to connect to */
		JOTDOWN(ferret, 
			JOT_SRC("ID-IP",frame),
			JOT_PRINT("AIM-Screen-Name", sess->str->the_string, sess->str->length),
			0);
		break;
	case 0x00170301: /* family=Logon, subtype=Reply, tag=screen-name  */
		JOTDOWN(ferret, 
			JOT_DST("ID-IP",frame), /* logon reply screen name sent from server*/
			JOT_PRINT("AIM-Screen-Name", sess->str->the_string, sess->str->length),
			0);
		break;
	case 0x00170311: /* family=Logon, subtype=Reply, tag=email  */
		JOTDOWN(ferret, 
			JOT_DST("ID-IP",frame), /* logon reply screen name sent from server*/
			JOT_PRINT("e-mail", sess->str->the_string, sess->str->length),
			0);
		break;
	case 0x00170349: /* family=Logon, subtype=Reply, tag=auth-protocol  */
		JOTDOWN(ferret, 
			JOT_DST("ID-IP",frame), /* logon reply screen name sent from server*/
			JOT_HEXSTR("AIM-digest-sig", sess->str->the_string, sess->str->length),
			0);
		break;
	case 0x00170700: /*AIM Sign-on(0x17), Sign-on Reply(7), Challenge(10)*/
		/* This is the 'challenge' sent back by logon.oscar.aol.com. The user
		 * will hash this with his password in order to logon to all the other
		 * servers.
		 *
		 * Because of this, we need to attach this string to the session going
		 * in the reverse direction. That will enable us to log the authentication
		 * process in case we want to log the hashes */
		JOTDOWN(ferret, 
			JOT_SRC("ID-IP",frame),
			JOT_PRINT("AIM-Challenge", sess->str->the_string, sess->str->length),
			0);
		break;
	case 0x0017038e: /* authorization cookie */
		/* This is a long string to pull out, but it gives anybody who has
		 * this cookie the ability to log onto any AIM service */
		JOTDOWN(ferret, 
			JOT_DST("ID-IP",frame),
			JOT_HEXSTR("AIM-Auth-Cookie", sess->str->the_string, sess->str->length),
			0);
		break;	
	case  0x00030b00: /* INCOMING oncoming buddy name */
	case  0x00020600:
		if (sess->str->length) {
			JOTDOWN(ferret, 
				JOT_DST("ID-IP",frame),
				JOT_PRINT("AIM-Buddy", sess->str->the_string, sess->str->length),
				0);
			JOTDOWN(ferret, 
				JOT_DST("ID-IP",frame),
				JOT_PRINT("friend", sess->str->the_string, sess->str->length),
				0);
		}
		break;
	case 0x00021500: /* OUTGOING user info query*/
		if (sess->str->length) {
			JOTDOWN(ferret, 
				JOT_SRC("ID-IP",frame),
				JOT_PRINT("AIM-Buddy", sess->str->the_string, sess->str->length),
				0);
			JOTDOWN(ferret, 
				JOT_SRC("ID-IP",frame),
				JOT_PRINT("friend", sess->str->the_string, sess->str->length),
				0);
		}
		break;
	case 0x00040700: /* Messaging, incoming */
		if (sess->str->length) {
			JOTDOWN(ferret, 
				JOT_DST("ID-IP",frame),
				JOT_PRINT("AIM-Buddy", sess->str->the_string, sess->str->length),
				0);
			JOTDOWN(ferret, 
				JOT_DST("ID-IP",frame),
				JOT_PRINT("friend", sess->str->the_string, sess->str->length),
				0);

			strfrag_xfer(sess->str+1, sess->str);
		}
		break;
	case 0x00040702: /* Messaging, INCOMING */
		decode_message(sess, frame, sess->str[0].the_string, sess->str[0].length, 0);
		break;
	case 0x00040600: /* Messaging, outgoing */
		if (sess->str->length) {
			JOTDOWN(ferret, 
				JOT_SRC("ID-IP",frame),
				JOT_PRINT("AIM-Buddy", sess->str->the_string, sess->str->length),
				0);
			JOTDOWN(ferret, 
				JOT_SRC("ID-IP",frame),
				JOT_PRINT("friend", sess->str->the_string, sess->str->length),
				0);

			strfrag_xfer(sess->str+1, sess->str);
		}
		break;
	case 0x00040602: /* Messaging, outgoing */
		decode_message(sess, frame, sess->str[0].the_string, sess->str[0].length, 1);
		break;
	case 0x00020604: /* Buddy Info - away message */
		if (sess->str->length) {
			JOTDOWN(ferret, 
				JOT_DST("ID-IP",frame),
				JOT_PRINT("AIM-Buddy", sess->str[1].the_string, sess->str[1].length),
				JOT_PRINT("Away-Message", sess->str[0].the_string, sess->str[0].length),
				0);
		}
		break;
	case 0x00041400: /* typing, outgoing */
		if (sess->str->length) {
			JOTDOWN(ferret, 
				JOT_SRC("ID-IP",frame),
				JOT_PRINT("AIM-Buddy", sess->str->the_string, sess->str->length),
				0);
			JOTDOWN(ferret, 
				JOT_SRC("ID-IP",frame),
				JOT_PRINT("friend", sess->str->the_string, sess->str->length),
				0);
		}
		break;
	case 0x00040605: /* File transfer */
		parse_message_filexfer_rendezvous(sess, frame, sess->str->the_string, sess->str->length);
		break;

	case 0x00040701:
	case 0x00040703:
	case 0x00040705:
	case 0x0004070b:
	case 0x0004070f:
	case 0x00040713:
	case 0x00040716:
	case 0x0004071d:
	case 0x00040603: /* Messaging, outgoing, server-ack requested */
		break;
	case 0x00130601: /* SNAC Server Side Information Entry List*/
	case 0x001306c9: 
	case 0x001306d6: 
	case 0x0013066a:
	case 0x0013066d: 
	case 0x00130631: 
		/* This is the start of an SSI Entry list, maybe we should 
		 * remember this??? */
		break;
	case 0x00130731:
		if (sess->str[1].length && sess->str[0].length) {
			JOTDOWN(ferret, 
				JOT_DST("ID-IP",frame),
				JOT_PRINT("AIM-Buddy", sess->str[1].the_string, sess->str[1].length),
				JOT_PRINT("AIM-Description", sess->str[0].the_string, sess->str[0].length),
				0);
		}
		break;
	/* Others that I've seen */
	case 0x0017064b:
	case 0x0017065a:
	case 0x0017024c:
	case 0x00170216:
	case 0x00170217:
	case 0x00170218:
	case 0x00170219:
	case 0x0017021a:
	case 0x00170214:
	case 0x0017024a:
	case 0x00170305:
	case 0x00170306:
	case 0x00170313:
	case 0x00170354:
	case 0x00170340:
	case 0x00170343:
	case 0x00170341:
	case 0x00170342:
	case 0x00170348:
	case 0x00170344:
	case 0x00170347:
	case 0x00170345:
	case 0x00170346:
	case 0x00020301:
	case 0x00020302:
	case 0x00020305:
	case 0x00020303:
	case 0x00020304:
	case 0x00030302:
	case 0x00030301:
	case 0x00030304:
	case 0x00040504:
	case 0x00090302:
	case 0x00090301:
	case 0x00020405:
	case 0x00011e1d:
	case 0x00011e06:
	case 0x0004060d:
	case 0x00020601: /* Buddy Info - User Class */
	case 0x00020603: /* Buddy Info - Online Since AND Away Msg Encoding ??? */
	case 0x00020605: /* Buddy Info - Member Since */
	case 0x0002060b: /* Buddy Info - unknown timestamp */
	case 0x0002060d: /* Buddy Info - Capabilities List */
	case 0x0002060f: /* Buddy Info - Session Length */
	case 0x0002061d: /* Buddy Info - Available Message */
	case 0x0002061f: /* Buddy Info - unknown */
	case 0x00020623: /* Buddy Info - unknown timestamp */
	case 0x00020626: /* Buddy Info - unknown timestamp (member since?) */
	case 0x00020627: /* Buddy Info - unknown timestamp */

		break;
	case 0x001306C8: /*SSI: members of this group */
		break;
	default:
		/* TODO: add SAMPLE here */
		switch (h&0xFFFFFF00) {
		case 0x00130300:
			break;
		default:
			FRAMERR(frame, "%s: unknown TLV tag: 0x%08x\n", "AIM", h);
		}
		break;
	}
	strfrag_finish(sess->str);
}
示例#18
0
文件: main.c 项目: anichno/SchoolCode
/*
 * Description: The main driver function for this program.
 * Input:       Command line arguments
 * Result:      EXIT_SUCCESS or EXIT_FAILURE
 * PRE:         None.
 * POST:        The appropriate encryption/decryption function will be called.
 */
int main( int argc, char** argv )
{
  if( argc == 1 ) // Program was executed with no arguments, so show usage.
  {
    show_usage( argv[ 0 ] );
  }
  else if( strcasecmp( argv[ 1 ], "-e" ) == 0 ) // Encrypt
  {
    if( argv[ 2 ] == NULL )
    {
      show_usage( argv[ 0 ] );
      return EXIT_FAILURE;
    }

    //pontifex -e deck.txt plaintext.txt ciphertext.txt
    printf( "Reading in deck...\n" );
    card_ptr deck = read_deck_from_file( argv[ 2 ] );
    printf( "Reading in plaintext...\n" );
    char* plaintext = read_filetext( argv[ 3 ] );
    printf( "Encrypting...\n" );
    char* ciphertext = encode_message( plaintext, deck );
    write_filetext( ciphertext, argv[ 4 ] );
  }
  else if( strcasecmp( argv[ 1 ], "-d" ) == 0 ) // Decrypt
  {
    if( argv[ 2 ] == NULL )
    {
      show_usage( argv[ 0 ] );
      return EXIT_FAILURE;
    }

    //pontifex -d deck.txt ciphertext.txt decrypted.txt
    printf( "Reading in deck...\n" );
    card_ptr deck = read_deck_from_file( argv[ 2 ] );
    printf( "Reading in ciphertext...\n" );
    char* ciphertext = read_filetext( argv[ 3 ] );
    printf( "Decrypting...\n" );
    char* plaintext = decode_message( ciphertext, deck );
    write_filetext( plaintext, argv[ 4 ] );
  }
  else if( strcasecmp( argv[ 1 ], "-a" ) == 0 ) // Create a new deck with all cards in ascending order
  {
    if( argv[ 2 ] == NULL )
    {
      show_usage( argv[ 0 ] );
      return EXIT_FAILURE;
    }
    printf( "Creating a new deck with cards in ascending order...\n" );
    fflush( stdout );

    //pontifex -a deck.txt
    card_ptr deck = new_deck();
    write_deck_to_file( deck, argv[ 2 ] );
  }
  else if( strcasecmp( argv[ 1 ], "-r" ) == 0 ) // Create a new, randomly shuffled deck
  {
    if( argv[ 2 ] == NULL )
    {
      show_usage( argv[ 0 ] );
      return EXIT_FAILURE;
    }
    printf( "Creating a new, randomly shuffled deck...\n" );

    //pontifex -r deck.txt
    card_ptr deck = new_deck();
    deck = shuffle_deck( deck );
    write_deck_to_file( deck, argv[ 2 ] );
  }
  else if( strcasecmp( argv[ 1 ], "-k" ) == 0 ) // Show key sequence
  {
    if( argv[ 2 ] == NULL )
    {
      show_usage( argv[ 0 ] );
      return EXIT_FAILURE;
    }
    printf( "Showing key sequence generated by deck in given file...\n" );

    //pontifex -k deck.txt
    printf( "Reading in deck...\n" );
    card_ptr deck = read_deck_from_file( argv[ 2 ] );
    char* keystream = generate_keystream( deck, 8 );
    int i;
    for( i = 0; i < 8; i++ )
    {
      int key = keystream[ i ] - 64;
      printf( "%d ", key );
    }
    printf( "\n" );
  }
  else if( strcasecmp( argv[ 1 ], "-f" ) == 0 ) // Test reading a deck from a file
  {
    if( argv[ 2 ] == NULL )
    {
      show_usage( argv[ 0 ] );
      return EXIT_FAILURE;
    }
    printf( "Testing reading deck from a file...\n" );

    //pontifex -f deck.txt
    printf( "Reading in deck...\n" );
    card_ptr deck = read_deck_from_file( argv[ 2 ] );
    show_deck( deck );
  }
  else if( strcasecmp( argv[ 1 ], "-m" ) == 0 ) // Test move joker steps
  {
    if( argv[ 2 ] == NULL )
    {
      show_usage( argv[ 0 ] );
      return EXIT_FAILURE;
    }
    printf( "Testing move joker steps with deck in given file...\n" );

    //pontifex -m deck.txt
    printf( "Reading in deck...\n" );
    card_ptr deck = read_deck_from_file( argv[ 2 ] );

    card_ptr currentCard = deck;
    while( currentCard->number != JOKER_A )
    {
      currentCard = currentCard->next;
    }
    deck = swap_joker1( deck, currentCard );

    currentCard = deck;
    while( currentCard->number != JOKER_B )
    {
      currentCard = currentCard->next;
    }
    deck = swap_joker2( deck, currentCard );

    show_deck( deck );
  }
  else if( strcasecmp( argv[ 1 ], "-t" ) == 0 ) // Test triple cut step
  {
    if( argv[ 2 ] == NULL )
    {
      show_usage( argv[ 0 ] );
      return EXIT_FAILURE;
    }
    printf( "Testing triple cut step with deck in given file...\n" );

    //pontifex -t deck.txt
    printf( "Reading in deck...\n" );
    card_ptr deck = read_deck_from_file( argv[ 2 ] );
    deck = triple_cut( deck );
    show_deck( deck );
  }
  else if( strcasecmp( argv[ 1 ], "-c" ) == 0 ) // Test count cut step
  {
    if( argv[ 2 ] == NULL )
    {
      show_usage( argv[ 0 ] );
      return EXIT_FAILURE;
    }
    printf( "Testing count cut step with deck in given file...\n" );

    //pontifex -c deck.txt
    printf( "Reading in deck...\n" );
    card_ptr deck = read_deck_from_file( argv[ 2 ] );
    deck = count_cut( deck );
    show_deck( deck );
  }
  else if( strcasecmp( argv[ 1 ], "-p" ) == 0 ) // Test entire pontifex algorithm
  {
    if( argv[ 2 ] == NULL )
    {
      show_usage( argv[ 0 ] );
      return EXIT_FAILURE;
    }
    printf( "Testing all pontifex steps with deck in given file...\n" );

    //pontifex -p deck.txt
    printf( "Reading in deck...\n" );
    card_ptr deck = read_deck_from_file( argv[ 2 ] );
    //	Step 1, find joker A
    card_ptr currentCard = deck;
    while( currentCard->number != JOKER_A )
    {
      currentCard = currentCard->next;
    }
    deck = swap_joker1( deck, currentCard );

    printf( "Step 1:\n" );
    show_deck( deck );

    //	Step 2, find joker B
    currentCard = deck;
    while( currentCard->number != JOKER_B )
    {
      currentCard = currentCard->next;
    }
    deck = swap_joker2( deck, currentCard );

    printf( "Step 2:\n" );
    show_deck( deck );

    //	Step 3, do triple cut
    deck = triple_cut( deck );

    printf( "Step 3:\n" );
    show_deck( deck );

    //	Step 4, do count cut
    deck = count_cut( deck );

    printf( "Step 4:\n" );
    show_deck( deck );

    //	Step 5, find output card
    int streamval = get_output_card( deck );

    printf( "Step 5:\n" );
    printf( "%i\n", streamval );
  }
  else if( strcasecmp( argv[ 1 ], "-o" ) == 0 ) // Test output card step
  {
    if( argv[ 2 ] == NULL )
    {
      show_usage( argv[ 0 ] );
      return EXIT_FAILURE;
    }
    printf( "Testing find output card step with deck in given file...\n" );

    //pontifex -o deck.txt
    printf( "Reading in deck...\n" );
    card_ptr deck = read_deck_from_file( argv[ 2 ] );
    printf( "Output card: %i\n", get_output_card( deck ) );
  }
  else
  {
    printf( "Invalid flag: %s\n", argv[ 1 ] );
    show_usage( argv[ 0 ] );
    return EXIT_FAILURE;
  }

  printf( "Done\n" );
  return EXIT_SUCCESS;
}
示例#19
0
int main(int argc, char* argv[]) {
    int error, socketfd, cfd;
    char hostname[256];
    struct addrinfo hints;
    struct addrinfo *result, *res;
    struct sockaddr peer_sockaddr;
    socklen_t peer_sockaddr_size;
    char port[] = "12345";
    char buff[MAX_BUFF];
    char tmp[MAX_BUFF];
    int i, n, j;
    fd_set fds, fds_backup;
    int fdmax;
    msg *toreceive;
    int client[MAX_CLIENT];


    /* Init variable for client array*/
    for (i = 0; i<MAX_CLIENT; i++) {
        /* -2 mean that there is no client with id = i*/
        client[i] = -2;
    }

    gethostname(hostname, sizeof(hostname));
    fprintf(stderr, "hostname = %s\n", hostname);
    printf("Port: %s\n", port);
    memset(&hints, 0, sizeof(struct addrinfo));
    hints.ai_family = AF_UNSPEC;
    hints.ai_socktype = SOCK_STREAM;
    hints.ai_flags |= AI_PASSIVE;
    hints.ai_protocol = 0;

    if ((error = getaddrinfo(NULL, port, &hints, &result))) {
        fprintf(stderr, "getaddrinfo(%p, %s, %p, %p)  got error %s \n",
                NULL, port, &hints, &result, gai_strerror(error));
        perror("getaddrinfo() error ");
        exit(-1);
    }

    /* Loop all to find available socket to bind socket*/
    for (res = result; res != NULL; res = res->ai_next) {
        socketfd = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
        if (socketfd == -1)
            continue;
        if (bind(socketfd, res->ai_addr, res->ai_addrlen) != -1) {
            fprintf(stderr, "bind() OK !\n");
            break;
        }
        close(socketfd);
    }

    if (res == NULL) {
        perror("bind() error ");
        exit(-1);
    }

    freeaddrinfo(result);

    /* listen to incoming connection */
    if (listen(socketfd, MAX_CONN) == -1) {
        perror("listen() error ");
        exit(-1);
    }

    FD_ZERO(&fds_backup);
    FD_SET(socketfd, &fds_backup);
    /* Set max file descriptor up till now */
    fdmax = socketfd;

    for (;;) {
        fds = fds_backup;
        if (select(fdmax+1, &fds, NULL, NULL, NULL) < 0) {
            perror("select() error ");
            exit(1);
        }
        for(i = 0; i <= fdmax; i++) {
            if (FD_ISSET(i, &fds)) {
                if(i == socketfd) {
                    /* accept connections */
                    peer_sockaddr_size = sizeof(peer_sockaddr);
                    cfd = accept(socketfd, &peer_sockaddr, &peer_sockaddr_size);
                    if (cfd >= MAX_CLIENT) {
                        memset(buff, 0, MAX_BUFF);
                        strcpy(buff, "Full Client. Connection refused !");
                        write(i, buff, strlen(buff)+1);
                        fprintf(stderr, "New client fd = %d\n", cfd);
                        fprintf(stderr, "Full Client. Connection refused !");
                        close(i);
                    }
                    if (cfd == -1) {
                        perror("accept() error ");
                    } else {
                        fprintf(stderr, "New client fd = %d\n", cfd);
                        client[i] = -1;
                        FD_SET(cfd, &fds_backup);
                        /* Keep track of fdmax */
                        if(cfd > fdmax) {
                            fdmax = cfd;
                        }
                    }
                } else {
                    /* Got something from client */
                    n = read(i, buff, MAX_BUFF);
                    if (n == 0) {
                        fprintf(stderr, "Disconnect client fd = %d\n", i);
                        FD_CLR(i, &fds_backup);
                        if (client[i] > 0) {
                            memset(tmp, 0, MAX_BUFF);
                            n = encode_message(buff, MSG_QUIT, tmp);
                            write(client[i], buff, n);
                        }
                        client[i] = -2;
                        close(i);
                        break;
                    } else if (n < 0) {
                        perror("read() error ");
                        FD_CLR(i, &fds_backup);
                        if (client[i] > 0) {
                            memset(tmp, 0, MAX_BUFF);
                            n = encode_message(buff, MSG_QUIT, tmp);
                            write(client[i], buff, n);
                        }
                        client[i] = -2;
                        close(i);
                    } else {
                        /* Code handle client data */
                        toreceive = (msg *) malloc(sizeof(msg));
                        decode_message(toreceive, buff, n);
                        fprintf(stderr, "Message from fd = %d\n", i);
                        fprintf(stderr, "Decoded msg: message_id = %d, len = %d, text = %s\n", toreceive->message_id, toreceive->len, toreceive->text);
                        memset(buff, 0, MAX_BUFF);
                        switch (toreceive->message_id) {
                        case MSG_HOST:
                            fprintf(stdout, "Player %d host game.\n", i);
                            /* Set client i to hosting */
                            client[i] = 0;
                            /* Send accept message to hosting player*/
                            memset(tmp, 0, MAX_BUFF);
                            n = encode_message(buff, MSG_ACCEPT, tmp);
                            write(i, buff, n);
                            break;
                        case MSG_JOIN:
                            fprintf(stdout, "Player %d want join a game. Send game list.\n", i);
                            /* Create game list */
                            for (j=0; j< MAX_CLIENT; j++) {
                                memset(tmp, 0, MAX_BUFF);
                                if (client[j] == 0) {
                                    sprintf(tmp, "Game %02d, Player 1/2\n", j);
                                    strcat(buff, tmp);
                                }
                            }
                            strncpy(tmp, buff, MAX_BUFF);
                            n = encode_message(buff, MSG_GAMELIST, tmp);
                            write(i, buff, n);
                            break;
                        case MSG_CHOSEGAME:
                            j = atoi(toreceive->text);
                            fprintf(stdout, "Player %d want join game of player %d. Notify player.\n", i, j);
                            /* Set pair of player */
                            client[i] = j;
                            client[j] = i;
                            memset(tmp, 0, MAX_BUFF);
                            n = encode_message(buff, MSG_PLAYERJOIN, tmp);
                            write(j, buff, n);
                            break;
                        case MSG_READY:
                        case MSG_BOARD:
                        case MSG_START:
                        case MSG_TOUCH:
                            if (client[i] > 0) {
                                j = client[i];
                                n = encode_message(buff, toreceive->message_id, toreceive->text);
                                write(j, buff, n);
                            } else fprintf(stdout, "Unknown target client.\n");
                            break;
                        default:
                            break;
                        }
                        free(toreceive);
                    }
                }
            }
        }
    }
    close(socketfd);
    return 0;
}
示例#20
0
int
main(int argc, char *argv[])
{
    struct ccn_charbuf *buffer;
    struct ccn_charbuf *signed_info = ccn_charbuf_create();
    struct ccn_skeleton_decoder dd = {0};
    ssize_t res;
    char *outname = NULL;
    int result = 0;
    char * contents[] = {"INVITE sip:[email protected] SIP/2.0\nVia: SIP/2.0/UDP 127.0.0.1:5060;rport;branch=z9hG4bK519044721\nFrom: <sip:[email protected]>;tag=2105643453\nTo: Test User <sip:[email protected]>\nCall-ID: [email protected]\nCSeq: 20 INVITE\nContact: <sip:[email protected]:5060>\nMax-Forwards: 70\nUser-Agent: Linphone-1.7.1/eXosip\nSubject: Phone call\nExpires: 120\nAllow: INVITE, ACK, CANCEL, BYE, OPTIONS, REFER, SUBSCRIBE, NOTIFY, MESSAGE\nContent-Type: application/sdp\nContent-Length:   448\n\nv=0\no=jthornto 123456 654321 IN IP4 127.0.0.1\ns=A conversation\nc=IN IP4 127.0.0.1\nt=0 0\nm=audio 7078 RTP/AVP 111 110 0 3 8 101\na=rtpmap:111 speex/16000/1\na=rtpmap:110 speex/8000/1\na=rtpmap:0 PCMU/8000/1\na=rtpmap:3 GSM/8000/1\na=rtpmap:8 PCMA/8000/1\na=rtpmap:101 telephone-event/8000\na=fmtp:101 0-11\nm=video 9078 RTP/AVP 97 98 99\na=rtpmap:97 theora/90000\na=rtpmap:98 H263-1998/90000\na=fmtp:98 CIF=1;QCIF=1\na=rtpmap:99 MP4V-ES/90000\n",
 
			 "Quaer #%2d zjduer  badone",
                         "",
                         NULL};
    char * paths[] = { "/sip/protocol/parc.com/domain/foo/principal/invite/verb/[email protected]/id", 
		       "/d/e/f",
                       "/zero/length/content",
                       NULL};
    struct path * cur_path = NULL;
    struct ccn_keystore *keystore = ccn_keystore_create();
    struct ccn_keystore *aes_keystore = ccn_aes_keystore_create();
    char *keystore_name = NULL;
    char *keystore_password = NULL;
    char *aes_keystore_name = NULL;
    unsigned char keybuf[32];

    int i;

    while ((i = getopt(argc, argv, "a:k:p:o:")) != -1) {
        switch (i) {
	    case 'a':
                aes_keystore_name = optarg;
                break;
            case 'k':
                keystore_name = optarg;
                break;
            case 'p':
                keystore_password = optarg;
                break;
            case 'o':
                outname = optarg;
                break;
            default:
                printf("Usage: %s [-k <keystore>] [-o <outfilename>]\n", argv[0]);
                exit(1);
        }
    }

    if (keystore_name == NULL)
        keystore_name = "test.keystore";

    if (aes_keystore_name == NULL)
        aes_keystore_name = "test.aeskeystore";

    if (keystore_password == NULL)
        keystore_password = "******";

    res = ccn_keystore_init(keystore, keystore_name, keystore_password);
    if (res != 0) {
        printf ("Initializing keystore in %s\n", keystore_name);
        res = ccn_keystore_file_init(keystore_name, keystore_password,
                                     "ccnxuser", 0, 3650);
        if (res != 0) {
            fprintf (stderr, "Cannot create keystore [%s]", keystore_name);
            return res;
        }
        res = ccn_keystore_init(keystore, keystore_name, keystore_password);
        if (res != 0) {
            printf("Failed to initialize keystore\n");
            exit(1);
        }
    }

    res = ccn_aes_keystore_init(aes_keystore, aes_keystore_name, keystore_password);
    if (res != 0) {
        printf ("Initializing AES keystore in %s\n", aes_keystore_name);
        ccn_generate_symmetric_key(keybuf, 256);
        res = ccn_aes_keystore_file_init(aes_keystore_name, keystore_password, keybuf, 256);
        if (res != 0) {
            fprintf (stderr, "Cannot create keystore [%s]", keystore_name);
            return res;
        }
        res = ccn_aes_keystore_init(aes_keystore, aes_keystore_name, keystore_password);
        if (res != 0) {
            printf("Failed to initialize keystore\n");
            exit(1);
        }
    }

    printf("Creating signed_info\n");
    res = ccn_signed_info_create(signed_info,
                                 /*pubkeyid*/ccn_keystore_key_digest(keystore),
                                 /*publisher_key_id_size*/ccn_keystore_key_digest_length(keystore),
                                 /*timestamp*/NULL,
                                 /*type*/CCN_CONTENT_GONE,
                                 /*freshness*/ 42,
                                 /*finalblockid*/NULL,
                                 /*keylocator*/NULL);
    if (res < 0) {
        printf("Failed to create signed_info!\n");
    }

    res = ccn_skeleton_decode(&dd, signed_info->buf, signed_info->length);
    if (!(res == signed_info->length && dd.state == 0)) {
        printf("Failed to decode signed_info!  Result %d State %d\n", (int)res, dd.state);
        result = 1;
    }
    memset(&dd, 0, sizeof(dd));
    printf("Done with signed_info\n");

    result = encode_sample_test(ccn_keystore_key(keystore), ccn_keystore_public_key(keystore), 
		ccn_keystore_digest_algorithm(keystore), paths, contents, signed_info, outname);

    if (! result) {
    	result = encode_sample_test(ccn_keystore_key(aes_keystore), ccn_keystore_key(aes_keystore), 
                        ccn_keystore_digest_algorithm(aes_keystore),
			paths, contents, signed_info, outname);
    }

    /* Now exercise as unit tests */

    for (i = 0; paths[i] != NULL && contents[i] != NULL; i++) {
        printf("Unit test case %d\n", i);
        cur_path = path_create(paths[i]);
        buffer = ccn_charbuf_create();
        if (encode_message(buffer, cur_path, contents[i], strlen(contents[i]), signed_info,
                       ccn_keystore_key(keystore), ccn_keystore_digest_algorithm(keystore))) {
            printf("Failed encode\n");
            result = 1;
        } else if (decode_message(buffer, cur_path, contents[i], strlen(contents[i]), 
                       ccn_keystore_public_key(keystore))) {
            printf("Failed decode\n");
            result = 1;
        }
        ccn_charbuf_destroy(&buffer);
        buffer = ccn_charbuf_create();
        if (encode_message(buffer, cur_path, contents[i], strlen(contents[i]), signed_info,
                       ccn_keystore_key(aes_keystore), ccn_keystore_digest_algorithm(aes_keystore))) {
            printf("Failed encode\n");
            result = 1;
        } else if (decode_message(buffer, cur_path, contents[i], strlen(contents[i]), ccn_keystore_key(aes_keystore))) {
            printf("Failed decode\n");
            result = 1;
        }
        path_destroy(&cur_path);
        ccn_charbuf_destroy(&buffer);
    }

    /* Test the uri encode / decode routines */

    init_all_chars_percent_encoded();
    init_all_chars_mixed_encoded();
    const char *uri_tests[] = {
        "_+4", "ccnx:/this/is/a/test",       "",     "ccnx:/this/is/a/test",
        ".+4", "../test2?x=2",              "?x=2", "ccnx:/this/is/a/test2",
        "_-X", "../should/error",           "",     "",
        "_+2", "/missing/scheme",           "",     "ccnx:/missing/scheme",
        ".+0", "../../../../../././#/",     "#/",   "ccnx:/",
        ".+1", all_chars_percent_encoded,   "",     all_chars_percent_encoded_canon,
        "_+1", all_chars_percent_encoded_canon, "", all_chars_percent_encoded_canon,
        ".+4", "ccnx:/.../.%2e./...././.....///?...", "?...", "ccnx:/.../.../..../.....",
        "_-X", "/%3G?bad-pecent-encode",    "",     "",
        "_-X", "/%3?bad-percent-encode",    "",     "",
        "_-X", "/%#bad-percent-encode",    "",     "",
        "_+3", "ccnx://[email protected]:42/ignore/host/part of uri", "", "ccnx:/ignore/host/part%20of%20uri",
        NULL, NULL, NULL, NULL
    };
    const char **u;
    struct ccn_charbuf *uri_out = ccn_charbuf_create();
    buffer = ccn_charbuf_create();
    for (u = uri_tests; *u != NULL; u += 4, i++) {
        printf("Unit test case %d\n", i);
        if (u[0][0] != '.')
            buffer->length = 0;
        res = ccn_name_from_uri(buffer, u[1]);
        if (!expected_res(res, u[0][1])) {
            printf("Failed: ccn_name_from_uri wrong res %d\n", (int)res);
            result = 1;
        }
        if (res >= 0) {
            if (res > strlen(u[1])) {
                printf("Failed: ccn_name_from_uri long res %d\n", (int)res);
                result = 1;
            }
            else if (0 != strcmp(u[1] + res, u[2])) {
                printf("Failed: ccn_name_from_uri expecting leftover '%s', got '%s'\n", u[2], u[1] + res);
                result = 1;
            }
            uri_out->length = 0;
            res = ccn_uri_append(uri_out, buffer->buf, buffer->length,
                                 CCN_URI_PERCENTESCAPE | CCN_URI_INCLUDESCHEME);
            if (!expected_res(res, u[0][2])) {
                printf("Failed: ccn_uri_append wrong res %d\n", (int)res);
                result = 1;
            }
            if (res >= 0) {
                if (uri_out->length != strlen(u[3])) {
                    printf("Failed: ccn_uri_append produced wrong number of characters\n");
                    result = 1;
                }
                ccn_charbuf_reserve(uri_out, 1)[0] = 0;
                if (0 != strcmp((const char *)uri_out->buf, u[3])) {
                    printf("Failed: ccn_uri_append produced wrong output\n");
                    printf("Expected: %s\n", u[3]);
                    printf("  Actual: %s\n", (const char *)uri_out->buf);
                    result = 1;
                }
            }
        }
    }
    ccn_charbuf_destroy(&buffer);
    ccn_charbuf_destroy(&uri_out);
    printf("Name marker tests\n");
    do {
        const char *expected_uri = "ccnx:/example.com/.../%01/%FE/%01%02%03%04%05%06%07%08/%FD%10%10%10%10%1F%FF/%00%81";
        const char *expected_chopped_uri = "ccnx:/example.com/.../%01/%FE";
        const char *expected_bumped_uri = "ccnx:/example.com/.../%01/%FF";
        const char *expected_bumped2_uri = "ccnx:/example.com/.../%01/%00%00";

        printf("Unit test case %d\n", i++);
        buffer = ccn_charbuf_create();
        uri_out = ccn_charbuf_create();
        res = ccn_name_init(buffer);
        res |= ccn_name_append_str(buffer, "example.com");
        res |= ccn_name_append_numeric(buffer, CCN_MARKER_NONE, 0);
        res |= ccn_name_append_numeric(buffer, CCN_MARKER_NONE, 1);
        res |= ccn_name_append_numeric(buffer, 0xFE, 0);
        res |= ccn_name_append_numeric(buffer, CCN_MARKER_NONE, 0x0102030405060708ULL);
        res |= ccn_name_append_numeric(buffer, CCN_MARKER_VERSION, 0x101010101FFFULL);
        res |= ccn_name_append_numeric(buffer, CCN_MARKER_SEQNUM, 129);
        res |= ccn_uri_append(uri_out, buffer->buf, buffer->length,
                              CCN_URI_PERCENTESCAPE | CCN_URI_INCLUDESCHEME);
        if (res < 0) {
            printf("Failed: name marker tests had negative res\n");
            result = 1;
        }
        if (0 != strcmp(ccn_charbuf_as_string(uri_out), expected_uri)) {
            printf("Failed: name marker tests produced wrong output\n");
            printf("Expected: %s\n", expected_uri);
            printf("  Actual: %s\n", (const char *)uri_out->buf);
            result = 1;
        }
        res = ccn_name_chop(buffer, NULL, 100);
        if (res != -1) {
            printf("Failed: ccn_name_chop did not produce error \n");
            result = 1;
        }
        res = ccn_name_chop(buffer, NULL, 4);
        if (res != 4) {
            printf("Failed: ccn_name_chop got wrong length\n");
            result = 1;
        }
        uri_out->length = 0;
        ccn_uri_append(uri_out, buffer->buf, buffer->length, CCN_URI_INCLUDESCHEME);
        if (0 != strcmp(ccn_charbuf_as_string(uri_out), expected_chopped_uri)) {
            printf("Failed: ccn_name_chop botch\n");
            printf("Expected: %s\n", expected_chopped_uri);
            printf("  Actual: %s\n", (const char *)uri_out->buf);
            result = 1;
        }
        res = ccn_name_next_sibling(buffer);
        if (res != 4) {
            printf("Failed: ccn_name_next_sibling got wrong length\n");
            result = 1;
        }
        uri_out->length = 0;
        ccn_uri_append(uri_out, buffer->buf, buffer->length, CCN_URI_INCLUDESCHEME);
        if (0 != strcmp(ccn_charbuf_as_string(uri_out), expected_bumped_uri)) {
            printf("Failed: ccn_name_next_sibling botch\n");
            printf("Expected: %s\n", expected_bumped_uri);
            printf("  Actual: %s\n", (const char *)uri_out->buf);
            result = 1;
        }
        ccn_name_next_sibling(buffer);
        uri_out->length = 0;
        ccn_uri_append(uri_out, buffer->buf, buffer->length, 
                       CCN_URI_PERCENTESCAPE | CCN_URI_INCLUDESCHEME);
        if (0 != strcmp(ccn_charbuf_as_string(uri_out), expected_bumped2_uri)) {
            printf("Failed: ccn_name_next_sibling botch\n");
            printf("Expected: %s\n", expected_bumped2_uri);
            printf("  Actual: %s\n", (const char *)uri_out->buf);
            result = 1;
        }
        ccn_charbuf_destroy(&buffer);
        ccn_charbuf_destroy(&uri_out);
    } while (0);

    do {
        const char *expected_uri_mixed = "ccnx:/example.com/.../%01/%FE/=0102030405060708/=FD101010101FFF/=0081";
        
        printf("Unit test case %d\n", i++);
        buffer = ccn_charbuf_create();
        uri_out = ccn_charbuf_create();
        res = ccn_name_init(buffer);
        res |= ccn_name_append_str(buffer, "example.com");
        res |= ccn_name_append_numeric(buffer, CCN_MARKER_NONE, 0);
        res |= ccn_name_append_numeric(buffer, CCN_MARKER_NONE, 1);
        res |= ccn_name_append_numeric(buffer, 0xFE, 0);
        res |= ccn_name_append_numeric(buffer, CCN_MARKER_NONE, 0x0102030405060708ULL);
        res |= ccn_name_append_numeric(buffer, CCN_MARKER_VERSION, 0x101010101FFFULL);
        res |= ccn_name_append_numeric(buffer, CCN_MARKER_SEQNUM, 129);
        res |= ccn_uri_append(uri_out, buffer->buf, buffer->length,
                              CCN_URI_MIXEDESCAPE | CCN_URI_INCLUDESCHEME);
        if (res < 0) {
            printf("Failed: name marker tests had negative res\n");
            result = 1;
        }
        if (0 != strcmp(ccn_charbuf_as_string(uri_out), expected_uri_mixed)) {
            printf("Failed: name marker tests produced wrong output\n");
            printf("Expected: %s\n", expected_uri_mixed);
            printf("  Actual: %s\n", (const char *)uri_out->buf);
            result = 1;
        }
        ccn_charbuf_destroy(&buffer);
        ccn_charbuf_destroy(&uri_out);
    } while (0);
    printf("Empty component encoding test\n");
    do {
        struct ccn_charbuf *name = ccn_charbuf_create();
        struct ccn_charbuf *expected_encoding = ccn_charbuf_create();
        /* manually create an encoding of <Name><Component/></Name> to ensure
         * that the regular encoders do not create a 0-length blob as part of
         * the empty component.
         */
        ccnb_element_begin(expected_encoding, CCN_DTAG_Name);
        ccnb_element_begin(expected_encoding, CCN_DTAG_Component);
        ccnb_element_end(expected_encoding);
        ccnb_element_end(expected_encoding);
        ccn_name_from_uri(name, "ccnx:/...");
        if (expected_encoding->length != name->length) {
            printf("Failed: encoding length %u but expected %u\n", (unsigned) name->length,
                   (unsigned)expected_encoding->length);
            result = 1;
        }
        for (i = 0; i < expected_encoding->length; i++) {
            if (expected_encoding->buf[i] != name->buf[i]) {
                printf("Failed: encoding mismatch at %d, got %d but expected %d\n",
                       i, name->buf[i], expected_encoding->buf[i]);
                result = 1;
            }
        }
        
    } while (0);
    
    printf("Timestamp tests\n");
    do {
        intmax_t sec;
        int nsec;
        int r;
        int f;
        struct ccn_charbuf *a[2];
        int t0 = 1363899678;
        
        printf("Unit test case %d\n", i++);
        /* Run many increasing inputs and make sure the output is in order. */
        a[0] = ccn_charbuf_create();
        a[1] = ccn_charbuf_create();
        ccnb_append_timestamp_blob(a[1], CCN_MARKER_NONE, t0 - 1, 0);
        for (f = 0, nsec = 0, sec = t0; sec < t0 + 20; nsec += 122099) {
            while (nsec >= 1000000000) {
                sec++;
                nsec -= 1000000000;
            }
            ccn_charbuf_reset(a[f]);
            r = ccnb_append_timestamp_blob(a[f], CCN_MARKER_NONE, sec, nsec);
            if (r != 0 || a[f]->length != 7 || memcmp(a[1-f]->buf, a[f]->buf, 6) > 0) {
                printf("Failed ccnb_append_timestamp_blob(...,%jd,%d)\n", sec, nsec);
                result = 1;
            }
            f = 1 - f;
        }
        ccn_charbuf_destroy(&a[0]);
        ccn_charbuf_destroy(&a[1]);
    } while (0);
    printf("Message digest tests\n");
    do {
        printf("Unit test case %d\n", i++);
        struct ccn_digest *dg = ccn_digest_create(CCN_DIGEST_SHA256);
        if (dg == NULL) {
            printf("Failed: ccn_digest_create returned NULL\n");
            result = 1;
            break;
        }
        printf("Unit test case %d\n", i++);
        const unsigned char expected_digest[] = {
            0xb3, 0x82, 0xcd, 0xb0, 0xe9, 0x5d, 0xf7, 0x3b, 0xe7, 0xdc, 0x19, 0x81, 0x3a, 0xfd, 0xdf, 0x89, 0xfb, 0xd4, 0xd4, 0xa0, 0xdb, 0x11, 0xa6, 0xba, 0x24, 0x16, 0x5b, 0xad, 0x9d, 0x90, 0x72, 0xb0
        };
        unsigned char actual_digest[sizeof(expected_digest)] = {0};
        const char *data = "Content-centric";
        if (ccn_digest_size(dg) != sizeof(expected_digest)) {
            printf("Failed: wrong digest size\n");
            result = 1;
            break;
        }
        printf("Unit test case %d\n", i++);
        ccn_digest_init(dg);
        res = ccn_digest_update(dg, data, strlen(data));
        if (res != 0)
            printf("Warning: check res %d\n", (int)res);
        printf("Unit test case %d\n", i++);
        res = ccn_digest_final(dg, actual_digest, sizeof(expected_digest));
        if (res != 0)
            printf("Warning: check res %d\n", (int)res);
        if (0 != memcmp(actual_digest, expected_digest, sizeof(expected_digest))) {
            printf("Failed: wrong digest\n");
            result = 1;
            break;
        }
    } while (0);
    printf("Really basic PRNG test\n");
    do {
        unsigned char r1[42];
        unsigned char r2[42];
        printf("Unit test case %d\n", i++);
        ccn_add_entropy(&i, sizeof(i), 0); /* Not much entropy, really. */
        ccn_random_bytes(r1, sizeof(r1));
        memcpy(r2, r1, sizeof(r2));
        ccn_random_bytes(r2, sizeof(r2));
        if (0 == memcmp(r1, r2, sizeof(r2))) {
            printf("Failed: badly broken PRNG\n");
            result = 1;
            break;
        }
    } while (0);
    printf("Bloom filter tests\n");
    do {
        unsigned char seed1[4] = "1492";
        const char *a[13] = {
            "one", "two", "three", "four",
            "five", "six", "seven", "eight",
            "nine", "ten", "eleven", "twelve",
            "thirteen"
        };
        struct ccn_bloom *b1 = NULL;
        struct ccn_bloom *b2 = NULL;
        int j, k, t1, t2;
        unsigned short us;

        printf("Unit test case %d\n", i++);
        b1 = ccn_bloom_create(13, seed1);

        for (j = 0; j < 13; j++)
            if (ccn_bloom_match(b1, a[j], strlen(a[j]))) break;
        if (j < 13) {
            printf("Failed: \"%s\" matched empty Bloom filter\n", a[j]);
            result = 1;
            break;
        }
        printf("Unit test case %d\n", i++);
        for (j = 0; j < 13; j++)
            ccn_bloom_insert(b1, a[j], strlen(a[j]));
        for (j = 0; j < 13; j++)
            if (!ccn_bloom_match(b1, a[j], strlen(a[j]))) break;
        if (j < 13) {
            printf("Failed: \"%s\" not found when it should have been\n", a[j]);
            result = 1;
            break;
        }
        printf("Unit test case %d\n", i++);
        for (j = 0, k = 0; j < 13; j++)
            if (ccn_bloom_match(b1, a[j]+1, strlen(a[j]+1)))
                k++;
        if (k > 0) {
            printf("Mmm, found %d false positives\n", k);
            if (k > 2) {
                result = 1;
                break;
            }
        }
        unsigned char seed2[5] = "aqfb\0";
        for (; seed2[3] <= 'f'; seed2[3]++) {
            printf("Unit test case %d (%4s)    ", i++, seed2);
            b2 = ccn_bloom_create(13, seed2);
            for (j = 0; j < 13; j++)
                ccn_bloom_insert(b2, a[j], strlen(a[j]));
            for (j = 0, k = 0, us = ~0; us > 0; us--) {
                t1 = ccn_bloom_match(b1, &us, sizeof(us));
                t2 = ccn_bloom_match(b2, &us, sizeof(us));
                j += (t1 | t2);
                k += (t1 & t2);
            }
            printf("either=%d both=%d wiresize=%d\n", j, k, ccn_bloom_wiresize(b1));
            if (k > 12) {
                printf("Failed: Bloom seeding may not be effective\n");
                result = 1;
            }
            ccn_bloom_destroy(&b2);
        }
        ccn_bloom_destroy(&b1);
    } while (0);
    printf("ccn_sign_content() tests\n");
    do {
        struct ccn *h = ccn_create();
	int res;
	res = unit_tests_for_signing(h, &i, 0);
	if (res == 1)
            result = 1;
        printf("Unit test case %d\n", i++);
        ccn_destroy(&h);
    } while (0);
    do {
        struct ccn *h = ccn_create();
	int res;
	res = ccn_load_default_key(h, aes_keystore_name, keystore_password);
	if (res < 0) {
            result = 1;
            printf("Failed: res == %d\n", (int)res);
        } else 
            res = unit_tests_for_signing(h, &i, 1);
	if (res == 1)
            result = 1;
        printf("Unit test case %d\n", i++);
        ccn_destroy(&h);
    } while (0);
    printf("link tests\n");
    printf("link tests\n");
    do {
        struct ccn_charbuf *l = ccn_charbuf_create();
        struct ccn_charbuf *name = ccn_charbuf_create();
        struct ccn_parsed_Link pl = {0};
        struct ccn_buf_decoder decoder;
        struct ccn_buf_decoder *d;
        struct ccn_indexbuf *comps = ccn_indexbuf_create();
        printf("Unit test case %d\n", i++);
        ccn_name_from_uri(name, "ccnx:/test/link/name");
        ccnb_append_Link(l, name, "label", NULL);
        d = ccn_buf_decoder_start(&decoder, l->buf, l->length);
        res = ccn_parse_Link(d, &pl, comps);
        if (res != 3 /* components in name */) {
            printf("Failed: ccn_parse_Link res == %d\n", (int)res);
            result = 1;
        }
    } while (0);

    exit(result);
}
示例#21
0
int
main (int argc, char *argv[]) {
    struct ccn_charbuf *buffer = ccn_charbuf_create();
    struct ccn_charbuf *signed_info = ccn_charbuf_create();
    struct ccn_skeleton_decoder dd = {0};
    ssize_t res;
    char *outname = NULL;
    int fd;
    int result = 0;
    char * contents[] = {"INVITE sip:[email protected] SIP/2.0\nVia: SIP/2.0/UDP 127.0.0.1:5060;rport;branch=z9hG4bK519044721\nFrom: <sip:[email protected]>;tag=2105643453\nTo: Test User <sip:[email protected]>\nCall-ID: [email protected]\nCSeq: 20 INVITE\nContact: <sip:[email protected]:5060>\nMax-Forwards: 70\nUser-Agent: Linphone-1.7.1/eXosip\nSubject: Phone call\nExpires: 120\nAllow: INVITE, ACK, CANCEL, BYE, OPTIONS, REFER, SUBSCRIBE, NOTIFY, MESSAGE\nContent-Type: application/sdp\nContent-Length:   448\n\nv=0\no=jthornto 123456 654321 IN IP4 127.0.0.1\ns=A conversation\nc=IN IP4 127.0.0.1\nt=0 0\nm=audio 7078 RTP/AVP 111 110 0 3 8 101\na=rtpmap:111 speex/16000/1\na=rtpmap:110 speex/8000/1\na=rtpmap:0 PCMU/8000/1\na=rtpmap:3 GSM/8000/1\na=rtpmap:8 PCMA/8000/1\na=rtpmap:101 telephone-event/8000\na=fmtp:101 0-11\nm=video 9078 RTP/AVP 97 98 99\na=rtpmap:97 theora/90000\na=rtpmap:98 H263-1998/90000\na=fmtp:98 CIF=1;QCIF=1\na=rtpmap:99 MP4V-ES/90000\n", 
 
			 "Quaer #%2d zjduer  badone",
                         "",
                         NULL};
    char * paths[] = { "/sip/protocol/parc.com/domain/foo/principal/invite/verb/[email protected]/id", 
		       "/d/e/f",
                       "/zero/length/content",
                       NULL};
    struct path * cur_path = NULL;
    struct ccn_keystore *keystore = ccn_keystore_create();
    char *home = getenv("HOME");
    char *keystore_suffix = "/.ccnx/.ccnx_keystore";
    char *keystore_name = NULL;

    int i;

    if (argc == 3 && strcmp(argv[1], "-o") == 0) {
	outname = argv[2];
    } else {
	printf("Usage: %s -o <outfilename>\n", argv[0]);
	exit(1);
    }

    if (home == NULL) {
        printf("Unable to determine home directory for keystore\n");
        exit(1);
    }
    keystore_name = calloc(1, strlen(home) + strlen(keystore_suffix) + 1);
    
    strcat(keystore_name, home);
    strcat(keystore_name, keystore_suffix);

    if (0 != ccn_keystore_init(keystore, keystore_name, "Th1s1sn0t8g00dp8ssw0rd.")) {
        printf("Failed to initialize keystore\n");
        exit(1);
    }

    printf("Creating signed_info\n");
    res = ccn_signed_info_create(signed_info,
                                 /*pubkeyid*/ccn_keystore_public_key_digest(keystore),
                                 /*publisher_key_id_size*/ccn_keystore_public_key_digest_length(keystore),
                                 /*datetime*/NULL,
                                 /*type*/CCN_CONTENT_GONE,
                                 /*freshness*/ 42,
                                 /*finalblockid*/NULL,
                                 /*keylocator*/NULL);
    if (res < 0) {
        printf("Failed to create signed_info!\n");
    }
    
    res = ccn_skeleton_decode(&dd, signed_info->buf, signed_info->length);
    if (!(res == signed_info->length && dd.state == 0)) {
        printf("Failed to decode signed_info!  Result %d State %d\n", (int)res, dd.state);
        result = 1;
    }
    memset(&dd, 0, sizeof(dd));
    printf("Done with signed_info\n");

    printf("Encoding sample message data length %d\n", (int)strlen(contents[0]));
    cur_path = path_create(paths[0]);
    if (encode_message(buffer, cur_path, contents[0], strlen(contents[0]), signed_info, ccn_keystore_private_key(keystore))) {
	printf("Failed to encode message!\n");
    } else {
	printf("Encoded sample message length is %d\n", (int)buffer->length);

	res = ccn_skeleton_decode(&dd, buffer->buf, buffer->length);
	if (!(res == buffer->length && dd.state == 0)) {
	    printf("Failed to decode!  Result %d State %d\n", (int)res, dd.state);
	    result = 1;
	}
        if (outname != NULL) {
            fd = open(outname, O_WRONLY|O_CREAT|O_TRUNC, S_IRWXU);
            if (fd == -1)
                perror(outname);
            res = write(fd, buffer->buf, buffer->length);
            close(fd);
	}
        if (decode_message(buffer, cur_path, contents[0], strlen(contents[0]), ccn_keystore_public_key(keystore)) != 0) {
	    result = 1;
	}
        printf("Expect signature verification failure: ");
        if (buffer->length >= 20)
            buffer->buf[buffer->length - 20] += 1;
	if (decode_message(buffer, cur_path, contents[0], strlen(contents[0]), ccn_keystore_public_key(keystore)) == 0) {
	    result = 1;
	}
    }
    path_destroy(&cur_path);
    ccn_charbuf_destroy(&buffer);
    printf("Done with sample message\n");
    
    /* Now exercise as unit tests */
    
    for (i = 0; paths[i] != NULL && contents[i] != NULL; i++) {
	printf("Unit test case %d\n", i);
	cur_path = path_create(paths[i]);
	buffer = ccn_charbuf_create();
	if (encode_message(buffer, cur_path, contents[i], strlen(contents[i]), signed_info, ccn_keystore_private_key(keystore))) {
	    printf("Failed encode\n");
            result = 1;
	} else if (decode_message(buffer, cur_path, contents[i], strlen(contents[i]), ccn_keystore_public_key(keystore))) {
	    printf("Failed decode\n");
            result = 1;
	}
	path_destroy(&cur_path);
	ccn_charbuf_destroy(&buffer);
    }
    
    /* Test the uri encode / decode routines */
        
    init_all_chars_percent_encoded();
    const char *uri_tests[] = {
        "_+4", "ccnx:/this/is/a/test",       "",     "ccnx:/this/is/a/test",
        ".+4", "../test2?x=2",              "?x=2", "ccnx:/this/is/a/test2",
        "_-X", "../should/error",           "",     "",
        "_+2", "/missing/scheme",           "",     "ccnx:/missing/scheme",
        ".+0", "../../../../../././#/",     "#/",   "ccnx:/",
        ".+1", all_chars_percent_encoded,   "",     all_chars_percent_encoded_canon,
        "_+1", all_chars_percent_encoded_canon, "", all_chars_percent_encoded_canon,
        ".+4", "ccnx:/.../.%2e./...././.....///?...", "?...", "ccnx:/.../.../..../.....",
        "_-X", "/%3G?bad-pecent-encode",    "",     "",
        "_-X", "/%3?bad-percent-encode",    "",     "",
        "_-X", "/%#bad-percent-encode",    "",     "",
        "_+3", "ccnx://[email protected]:42/ignore/host/part of uri", "", "ccnx:/ignore/host/part%20of%20uri",
        NULL, NULL, NULL, NULL
    };
    const char **u;
    struct ccn_charbuf *uri_out = ccn_charbuf_create();
    buffer = ccn_charbuf_create();
    for (u = uri_tests; *u != NULL; u += 4, i++) {
        printf("Unit test case %d\n", i);
        if (u[0][0] != '.')
            buffer->length = 0;
        res = ccn_name_from_uri(buffer, u[1]);
        if (!expected_res(res, u[0][1])) {
            printf("Failed: ccn_name_from_uri wrong res %d\n", (int)res);
            result = 1;
        }
        if (res >= 0) {
            if (res > strlen(u[1])) {
                printf("Failed: ccn_name_from_uri long res %d\n", (int)res);
                result = 1;
            }
            else if (0 != strcmp(u[1] + res, u[2])) {
                printf("Failed: ccn_name_from_uri expecting leftover '%s', got '%s'\n", u[2], u[1] + res);
                result = 1;
            }
            uri_out->length = 0;
            res = ccn_uri_append(uri_out, buffer->buf, buffer->length, 1);
            if (!expected_res(res, u[0][2])) {
                printf("Failed: ccn_uri_append wrong res %d\n", (int)res);
                result = 1;
            }
            if (res >= 0) {
                if (uri_out->length != strlen(u[3])) {
                    printf("Failed: ccn_uri_append produced wrong number of characters\n");
                    result = 1;
                }
                ccn_charbuf_reserve(uri_out, 1)[0] = 0;
                if (0 != strcmp((const char *)uri_out->buf, u[3])) {
                    printf("Failed: ccn_uri_append produced wrong output\n");
                    printf("Expected: %s\n", u[3]);
                    printf("  Actual: %s\n", (const char *)uri_out->buf);
                    result = 1;
                }
            }
        }
    }
    ccn_charbuf_destroy(&buffer);
    ccn_charbuf_destroy(&uri_out);
    printf("Name marker tests\n");
    do {
        const char *expected_uri = "ccnx:/example.com/.../%01/%FE/%01%02%03%04%05%06%07%08/%FD%10%10%10%10%1F%FF/%00%81";
        const char *expected_chopped_uri = "ccnx:/example.com/.../%01/%FE";
        const char *expected_bumped_uri = "ccnx:/example.com/.../%01/%FF";
        const char *expected_bumped2_uri = "ccnx:/example.com/.../%01/%00%00";

        printf("Unit test case %d\n", i++);
        buffer = ccn_charbuf_create();
        uri_out = ccn_charbuf_create();
        res = ccn_name_init(buffer);
        res |= ccn_name_append_str(buffer, "example.com");
        res |= ccn_name_append_numeric(buffer, CCN_MARKER_NONE, 0);
        res |= ccn_name_append_numeric(buffer, CCN_MARKER_NONE, 1);
        res |= ccn_name_append_numeric(buffer, 0xFE, 0);
        res |= ccn_name_append_numeric(buffer, CCN_MARKER_NONE, 0x0102030405060708ULL);
        res |= ccn_name_append_numeric(buffer, CCN_MARKER_VERSION, 0x101010101FFFULL);
        res |= ccn_name_append_numeric(buffer, CCN_MARKER_SEQNUM, 129);
        res |= ccn_uri_append(uri_out, buffer->buf, buffer->length, 1);
        if (res < 0) {
            printf("Failed: name marker tests had negative res\n");
            result = 1;
        }
        if (0 != strcmp(ccn_charbuf_as_string(uri_out), expected_uri)) {
            printf("Failed: name marker tests produced wrong output\n");
            printf("Expected: %s\n", expected_uri);
            printf("  Actual: %s\n", (const char *)uri_out->buf);
            result = 1;
        }
        res = ccn_name_chop(buffer, NULL, 100);
        if (res != -1) {
            printf("Failed: ccn_name_chop did not produce error \n");
            result = 1;
        }
        res = ccn_name_chop(buffer, NULL, 4);
        if (res != 4) {
            printf("Failed: ccn_name_chop got wrong length\n");
            result = 1;
        }
        uri_out->length = 0;
        ccn_uri_append(uri_out, buffer->buf, buffer->length, 1);
        if (0 != strcmp(ccn_charbuf_as_string(uri_out), expected_chopped_uri)) {
            printf("Failed: ccn_name_chop botch\n");
            printf("Expected: %s\n", expected_chopped_uri);
            printf("  Actual: %s\n", (const char *)uri_out->buf);
            result = 1;
        }
        res = ccn_name_next_sibling(buffer);
        if (res != 4) {
            printf("Failed: ccn_name_next_sibling got wrong length\n");
            result = 1;
        }
        uri_out->length = 0;
        ccn_uri_append(uri_out, buffer->buf, buffer->length, 1);
        if (0 != strcmp(ccn_charbuf_as_string(uri_out), expected_bumped_uri)) {
            printf("Failed: ccn_name_next_sibling botch\n");
            printf("Expected: %s\n", expected_bumped_uri);
            printf("  Actual: %s\n", (const char *)uri_out->buf);
            result = 1;
        }
        ccn_name_next_sibling(buffer);
        uri_out->length = 0;
        ccn_uri_append(uri_out, buffer->buf, buffer->length, 1);
        if (0 != strcmp(ccn_charbuf_as_string(uri_out), expected_bumped2_uri)) {
            printf("Failed: ccn_name_next_sibling botch\n");
            printf("Expected: %s\n", expected_bumped2_uri);
            printf("  Actual: %s\n", (const char *)uri_out->buf);
            result = 1;
        }
        ccn_charbuf_destroy(&buffer);
        ccn_charbuf_destroy(&uri_out);
    } while (0);
    printf("Message digest tests\n");
    do {
        printf("Unit test case %d\n", i++);
        struct ccn_digest *dg = ccn_digest_create(CCN_DIGEST_SHA256);
        if (dg == NULL) {
            printf("Failed: ccn_digest_create returned NULL\n");
            result = 1;
            break;
        }
        printf("Unit test case %d\n", i++);
        const unsigned char expected_digest[] = {
            0xb3, 0x82, 0xcd, 0xb0, 0xe9, 0x5d, 0xf7, 0x3b, 0xe7, 0xdc, 0x19, 0x81, 0x3a, 0xfd, 0xdf, 0x89, 0xfb, 0xd4, 0xd4, 0xa0, 0xdb, 0x11, 0xa6, 0xba, 0x24, 0x16, 0x5b, 0xad, 0x9d, 0x90, 0x72, 0xb0
        };
        unsigned char actual_digest[sizeof(expected_digest)] = {0};
        const char *data = "Content-centric";
        if (ccn_digest_size(dg) != sizeof(expected_digest)) {
            printf("Failed: wrong digest size\n");
            result = 1;
            break;
        }
        printf("Unit test case %d\n", i++);
        ccn_digest_init(dg);
        res = ccn_digest_update(dg, data, strlen(data));
        if (res != 0)
            printf("Warning: check res %d\n", (int)res);
        printf("Unit test case %d\n", i++);
        res = ccn_digest_final(dg, actual_digest, sizeof(expected_digest));
        if (res != 0)
            printf("Warning: check res %d\n", (int)res);
        if (0 != memcmp(actual_digest, expected_digest, sizeof(expected_digest))) {
            printf("Failed: wrong digest\n");
            result = 1;
            break;
        }
    } while (0);
    printf("Really basic PRNG test\n");
    do {
        unsigned char r1[42];
        unsigned char r2[42];
        printf("Unit test case %d\n", i++);
        ccn_add_entropy(&i, sizeof(i), 0); /* Not much entropy, really. */
        ccn_random_bytes(r1, sizeof(r1));
        memcpy(r2, r1, sizeof(r2));
        ccn_random_bytes(r2, sizeof(r2));
        if (0 == memcmp(r1, r2, sizeof(r2))) {
            printf("Failed: badly broken PRNG\n");
            result = 1;
            break;
        }
    } while (0);
    printf("Bloom filter tests\n");
    do {
        unsigned char seed1[4] = "1492";
        const char *a[13] = {
            "one", "two", "three", "four",
            "five", "six", "seven", "eight",
            "nine", "ten", "eleven", "twelve",
            "thirteen"
        };
        struct ccn_bloom *b1 = NULL;
        struct ccn_bloom *b2 = NULL;
        int j, k, t1, t2;
        unsigned short us;
        
        printf("Unit test case %d\n", i++);
        b1 = ccn_bloom_create(13, seed1);
        
        for (j = 0; j < 13; j++)
            if (ccn_bloom_match(b1, a[j], strlen(a[j]))) break;
        if (j < 13) {
            printf("Failed: \"%s\" matched empty Bloom filter\n", a[j]);
            result = 1;
            break;
        }
        printf("Unit test case %d\n", i++);
        for (j = 0; j < 13; j++)
            ccn_bloom_insert(b1, a[j], strlen(a[j]));
        for (j = 0; j < 13; j++)
            if (!ccn_bloom_match(b1, a[j], strlen(a[j]))) break;
        if (j < 13) {
            printf("Failed: \"%s\" not found when it should have been\n", a[j]);
            result = 1;
            break;
        }
        printf("Unit test case %d\n", i++);
        for (j = 0, k = 0; j < 13; j++)
            if (ccn_bloom_match(b1, a[j]+1, strlen(a[j]+1)))
                k++;
        if (k > 0) {
            printf("Mmm, found %d false positives\n", k);
            if (k > 2) {
                result = 1;
                break;
            }
        }
        unsigned char seed2[5] = "aqfb\0";
        for (; seed2[3] <= 'f'; seed2[3]++) {
            printf("Unit test case %d (%4s)    ", i++, seed2);
            b2 = ccn_bloom_create(13, seed2);
            for (j = 0; j < 13; j++)
                ccn_bloom_insert(b2, a[j], strlen(a[j]));
            for (j = 0, k = 0, us = ~0; us > 0; us--) {
                t1 = ccn_bloom_match(b1, &us, sizeof(us));
                t2 = ccn_bloom_match(b2, &us, sizeof(us));
                j += (t1 | t2);
                k += (t1 & t2);
            }
            printf("either=%d both=%d wiresize=%d\n", j, k, ccn_bloom_wiresize(b1));
            if (k > 12) {
                printf("Failed: Bloom seeding may not be effective\n");
                result = 1;
            }
            ccn_bloom_destroy(&b2);
        }
        ccn_bloom_destroy(&b1);
    } while (0);
    printf("ccn_sign_content() tests\n");
    do {
        struct ccn *h = ccn_create();
        struct ccn_charbuf *co = ccn_charbuf_create();
        struct ccn_signing_params sparm = CCN_SIGNING_PARAMS_INIT;
        struct ccn_parsed_ContentObject pco = {0};
        struct ccn_charbuf *name = ccn_charbuf_create();
        
        printf("Unit test case %d\n", i++);
        ccn_name_from_uri(name, "ccnx:/test/data/%00%42");
        res = ccn_sign_content(h, co, name, NULL, "DATA", 4);
        if (res != 0) {
            printf("Failed: res == %d\n", (int)res);
            result = 1;
        }
        sparm.template_ccnb = ccn_charbuf_create();
        res = ccn_parse_ContentObject(co->buf, co->length, &pco, NULL);
        if (res != 0) {
            printf("Failed: ccn_parse_ContentObject res == %d\n", (int)res);
            result = 1;
            break;
        }
        ccn_charbuf_append(sparm.template_ccnb,
            co->buf + pco.offset[CCN_PCO_B_SignedInfo],
            pco.offset[CCN_PCO_E_SignedInfo] - pco.offset[CCN_PCO_B_SignedInfo]);
        sparm.sp_flags = CCN_SP_TEMPL_TIMESTAMP;
        printf("Unit test case %d\n", i++);
        res = ccn_sign_content(h, co, name, &sparm, "DATA", 4);
        if (res != 0) {
            printf("Failed: res == %d\n", (int)res);
            result = 1;
        }
        printf("Unit test case %d\n", i++);
        sparm.sp_flags = -1;
        res = ccn_sign_content(h, co, name, &sparm, "DATA", 4);
        if (res != -1) {
            printf("Failed: res == %d\n", (int)res);
            result = 1;
        }
        ccn_charbuf_destroy(&name);
        ccn_charbuf_destroy(&sparm.template_ccnb);
        ccn_charbuf_destroy(&co);
        ccn_destroy(&h);
    } while (0);
    printf("link tests\n");
    do {
        struct ccn_charbuf *l = ccn_charbuf_create();
        struct ccn_charbuf *name = ccn_charbuf_create();
        struct ccn_parsed_Link pl = {0};
        struct ccn_buf_decoder decoder;
        struct ccn_buf_decoder *d;
        struct ccn_indexbuf *comps = ccn_indexbuf_create();
        printf("Unit test case %d\n", i++);
        ccn_name_from_uri(name, "ccnx:/test/link/name");
        ccnb_append_Link(l, name, "label", NULL);
        d = ccn_buf_decoder_start(&decoder, l->buf, l->length);
        res = ccn_parse_Link(d, &pl, comps);
        if (res != 3 /* components in name */) {
            printf("Failed: ccn_parse_Link res == %d\n", (int)res);
            result = 1;
        }        
    } while (0);
    
    exit(result);
}