/**
* Ends the download stream
*/
void CCNGet::endStream()
{
	stream = ccn_fetch_close(stream);
	ccn_destroy(&ccn);
	ccn_charbuf_destroy(&templ);
	ccn_charbuf_destroy(&name);
}
Example #2
0
void CcnLAC_dtor(CcnLAC self) {
	if (self->pm != NULL) PollMgr_detach(self->pm, ccn_get_connection_fd(self->ccnh), &CcnLAC_initPollCb, self);
	if (self->nbs != NULL) NBS_pollDetach(self->nbs);
	ccn_destroy(&(self->ccnh));
	if (self->ccnbor != NULL) CcnbOR_dtor(self->ccnbor);
	free(self);
}
Example #3
0
void 
ospfn_stop_signal_handler(int sig)
{
	signal(sig, SIG_IGN);
	writeLogg(ospfn->logFile,__FILE__,__FUNCTION__,__LINE__,"Signal for ospfn stop\n");
	hash_iterate_delete_npt (ospfn->prefix_table);
    	ccn_destroy(&ccn_handle);	
    	ospf_apiclient_close(ospfn->oclient);	
	free_all_nexthop();	
	writeLogg(ospfn->logFile,__FILE__,__FUNCTION__,__LINE__,"Exiting ospfn...\n");	
	exit(0);
}
Example #4
0
void NdnMediaProcess::run() {
    int res = 0;
	int ret;
	
	// now a separate thread for ccn_run
	//pthread_create(&ccn_thread, NULL, ccn_event_run, (void *)(ndnState.ccn));

	res = ccn_run(ndnState.ccn, 0);
	// also a separate thread to ccn_put content and sending probe interest
    for(;;) {
        if (ndnState.active != 0) {
            
            /* check each local user's buffer to find out if there are some packets 
             * to be sent.If have, send it. */ 
            doPendingSend();

            /* find the new or resetted remote user in the remote user list,send the 
             * first interest for the user.*/
            checkInterest();

			fetchNdnText();
        }
        else /* other module has stopped this thread */
            res = -1;

		if (res >= 0) {
			ret = poll(pfds, 1, 10);	
			if (ret >= 0) {
				/*
				int c = 0;
				while(pthread_mutex_trylock(&ccn_mutex) != 0) {
					c++;
					usleep(200);
					if (c> 10000) {
						fprintf(stderr, "cannot obtain lock at ccn_run\n");
						abort();
					}
				}
				*/
				pthread_mutex_lock(&ccn_mutex);
				res = ccn_run(ndnState.ccn, 0);
				pthread_mutex_unlock(&ccn_mutex);
			}
		}

        if (res < 0)
            break;
    }
    
    ccn_destroy(&ndnState.ccn);
    ndnState.ccn = NULL;
}
Example #5
0
void
ccnr_internal_client_stop(struct ccnr_handle *ccnr)
{
    ccnr->notice = NULL; /* ccn_destroy will free */
    if (ccnr->notice_push != NULL)
        ccn_schedule_cancel(ccnr->sched, ccnr->notice_push);
    ccn_indexbuf_destroy(&ccnr->chface);
    ccn_destroy(&ccnr->internal_client);
    ccn_charbuf_destroy(&ccnr->service_ccnb);
    ccn_charbuf_destroy(&ccnr->neighbor_ccnb);
    if (ccnr->internal_client_refresh != NULL)
        ccn_schedule_cancel(ccnr->sched, ccnr->internal_client_refresh);
}
Example #6
0
void
ccndc_destroy_data(struct ccndc_data **data) {
    struct ccndc_data *self = *data;
    
    if (self != NULL) {
        ccn_charbuf_destroy(&self->no_name);
        ccn_charbuf_destroy(&self->local_scope_template);
        ccn_disconnect(self->ccn_handle);
        ccn_destroy(&self->ccn_handle);
        free(self);
        *data = NULL;
    }
}
Example #7
0
int
main(int argc, char *argv[])
{
	int res;
	struct ccn *ccn = NULL;
	struct ccn_charbuf *name = NULL;
	struct ccn_closure *incoming;

	if (argc != 2)
		usage(argv[0]);

	name = ccn_charbuf_create();

	res = ccn_name_from_uri(name, argv[1]);
	if (res < 0) {
		fprintf(stderr, "invalid ccn URI: %s\n", argv[1]);
		usage(argv[0]);
	}
	ccn = ccn_create();

	res = ccn_connect(ccn, NULL);
	if (res < 0) {
		fprintf(stderr, "can't connect to ccn: %d\n", res);
		ccn_perror(ccn, "ccn_connect");
		exit(1);
	}

	incoming = calloc(1, sizeof(*incoming));
	incoming->p = incoming_handler;
	g_working = true;
	gettimeofday(&g_start, NULL);
	res = ccn_express_interest(ccn, name, incoming, NULL);

	while (g_working && res >= 0)
		res = ccn_run(ccn, 100);

	free(incoming);

	if (res < 0) {
		ccn_perror(ccn, "ccn_run");
		exit(1);
	}

	ccn_charbuf_destroy(&name);
	ccn_destroy(&ccn);

	return 0;
}
Example #8
0
/**
 * Creates a new ccn_fetch object using the given ccn connection.
 * If h == NULL, attempts to create a new connection automatically.
 * @returns NULL if the creation was not successful
 * (only can happen for the h == NULL case).
 */
extern struct ccn_fetch *
ccn_fetch_new(struct ccn *h) {
	struct ccn_fetch *f = calloc(1, sizeof(*f));
	if (h == NULL) {
		h = ccn_create();
		int connRes = ccn_connect(h, NULL);
		if (connRes < 0) {
			ccn_destroy(&h);
			free(f);
			return NULL;
		}
		f->localConnect = 1;
	}
	f->h = h;
	return f;
}
Example #9
0
int NdnMediaProcess::startThread() {
    struct ccn *h;

    /* Shut down any lingering session */
    while (ndnState.ccn != NULL) {
        ndnState.active = 0;
        printf("waiting for old session to die\n");
    }
    h = ccn_create();
    if (ccn_connect(h, NULL) == -1) {
        ccn_perror(h, "Failed to contact ccnd");
        ccn_destroy(&h);
        return (-1);
    }
	pthread_mutexattr_init(&ccn_attr);
	pthread_mutexattr_settype(&ccn_attr, PTHREAD_MUTEX_RECURSIVE);     
	pthread_mutex_init(&ccn_mutex, &ccn_attr);

    ndnState.ccn = h; 
	pfds[0].fd = ccn_get_connection_fd(ndnState.ccn);
	pfds[0].events = POLLIN;
	clock = new QTimer(this);
	connect(clock, SIGNAL(timeout()), this, SLOT(tick()));
	clock->start(PER_PACKET_LEN);
	
    if (! isRunning()) {
        fprintf(stderr, "Starting voice thread in media_pro\n"); 
        ndnState.active = true;

        start(QThread::HighestPriority);
#ifdef Q_OS_LINUX
        int policy;
        struct sched_param param;
        if (pthread_getschedparam(pthread_self(), &policy, &param) == 0) {
            if (policy == SCHED_OTHER) {
                policy = SCHED_FIFO;
                param.sched_priority = 1;
                pthread_setschedparam(pthread_self(), policy, &param);
            }
        }
#endif
    }
	else
		fprintf(stderr, "what the hell\n");
    return 0;
}
Example #10
0
int
ccnr_internal_client_start(struct ccnr_handle *ccnr)
{
    if (ccnr->internal_client != NULL)
        return(-1);
    if (ccnr->face0 == NULL)
        abort();
    ccnr->internal_client = ccn_create();
    if (ccnr_init_repo_keystore(ccnr, ccnr->internal_client) < 0) {
        ccn_destroy(&ccnr->internal_client);
        return(-1);
    }
    ccnr->internal_client_refresh = ccn_schedule_event(ccnr->sched, 50000,
                         ccnr_internal_client_refresh,
                         NULL, CCN_INTEREST_LIFETIME_MICROSEC);
    return(0);
}
Example #11
0
int
ccn_proxy_destroy(struct ccn_proxy **proxy)
{
    struct ccn_proxy *p = *proxy;
    DEBUG_PRINT("IN %d %s\n", __LINE__, __func__);

    ccn_destroy(&(p->handle));

    ccn_charbuf_destroy(&(p->handle_name));

    ccn_indexbuf_destroy(&(p->prefix_comps));
    ccn_charbuf_destroy(&(p->prefix));

    ccn_charbuf_destroy(&(p->filter));

    free(p);

    DEBUG_PRINT("OUT %d %s\n", __LINE__, __func__);
    return(0);
}
Example #12
0
int GroupManager::ccn_free() {

    if (ccn != NULL) {
        ccn_disconnect(ccn);
        ccn_destroy(&ccn);
    }
    if (cached_keystore != NULL) ccn_keystore_destroy(&cached_keystore);
    if (join_closure != NULL) {
        free(join_closure);
        join_closure = NULL;
    }
    if (req_closure != NULL) {
        free(req_closure);
        req_closure = NULL;
    }
	if (leave_closure != NULL) {
		free(leave_closure);
		leave_closure = NULL;
	}
    return 0;
}
Example #13
0
/**
 * Destroys a ccn_fetch object.
 * Only destroys the underlying ccn connection if it was automatically created.
 * Forces all underlying streams to close immediately.
 * @returns NULL in all cases.
 */
extern struct ccn_fetch *
ccn_fetch_destroy(struct ccn_fetch *f) {
	// destroys a ccn_fetch object
	// always returns NULL
	// only destroys the underlying ccn connection if it was
	// automatically created, otherwise does not alter it
	if (f != NULL) {
		struct ccn *h = f->h;
		if (h != NULL && f->localConnect) {
			ccn_disconnect(h);
			ccn_destroy(&f->h);
		}
		// take down all of the streams
		while (f->nStreams > 0) {
			struct ccn_fetch_stream *fs = f->streams[0];
			if (fs == NULL) break;
			ccn_fetch_close(fs);
		}
		free(f);
	}
	return NULL;
}
Example #14
0
int
main(int argc, char **argv)
{
    int opt;
    int res;
    struct ccn *h;
    struct ccns_slice *slice;
    struct ccns_handle *ccns;
    struct ccn_charbuf *prefix = ccn_charbuf_create();
    struct ccn_charbuf *roothash = NULL;
    struct ccn_charbuf *topo = ccn_charbuf_create();
    struct ccn_charbuf *clause = ccn_charbuf_create();
    int timeout = 10*1000;
    unsigned i, j, n;
 
    slice = ccns_slice_create();
    ccn_charbuf_reset(prefix);
    ccn_charbuf_reset(topo);
    while ((opt = getopt(argc, argv, "hf:p:r:t:w:")) != -1) {
        switch (opt) {
            case 'f':
                ccn_charbuf_reset(clause);
                if (0 > ccn_name_from_uri(clause, optarg)) usage(argv[0]);
                ccns_slice_add_clause(slice, clause);
                break;
            case 'p':
                ccn_charbuf_reset(prefix);
                if (0 > ccn_name_from_uri(prefix, optarg)) usage(argv[0]);
                break;
            case 'r':
                n = strlen(optarg);
                if (n == 0) {
                    roothash = ccn_charbuf_create();
                    break;
                }
                if ((n % 2) != 0)
                    usage(argv[0]);
                roothash = ccn_charbuf_create_n(n / 2);
                for (i = 0; i < (n / 2); i++) {
                    j = (hex_value(optarg[2*i]) << 4) | hex_value(optarg[1+2*i]);
                    ccn_charbuf_append_value(roothash, j, 1);
                }
                break;
            case 't':
                ccn_charbuf_reset(topo);
                if (0 > ccn_name_from_uri(topo, optarg)) usage(argv[0]);
                break;
            case 'w':
                timeout = atoi(optarg);
                if (timeout < -1) usage(argv[0]);
                timeout *= 1000;
                break;
            default:
            case 'h':
                usage(argv[0]);
        }
    }

    ccns_slice_set_topo_prefix(slice, topo, prefix);
    h = ccn_create();
    res = ccn_connect(h, NULL);
    ccns = ccns_open(h, slice, &sync_cb, roothash, NULL);
    ccn_run(h, timeout);
    ccns_close(&ccns, NULL, NULL);
    ccns_slice_destroy(&slice);
    ccn_destroy(&h);
    exit(res);
}
Example #15
0
int
main(int argc, char **argv)
{
    struct ccn *h = NULL;
    struct ccn_charbuf *name = NULL;
    struct ccn_charbuf *null_name = NULL;
    struct ccn_charbuf *name_prefix = NULL;
    struct ccn_charbuf *newface = NULL;
    struct ccn_charbuf *prefixreg = NULL;
    struct ccn_charbuf *resultbuf = NULL;
    struct ccn_charbuf *temp = NULL;
    struct ccn_charbuf *templ = NULL;
    const unsigned char *ptr = NULL;
    size_t length = 0;
    const char *arg = NULL;
    const char *progname = NULL;
    struct ccn_parsed_ContentObject pcobuf = {0};
    struct ccn_face_instance face_instance_storage = {0};
    struct ccn_face_instance *face_instance = &face_instance_storage;
    struct ccn_forwarding_entry forwarding_entry_storage = {0};
    struct ccn_forwarding_entry *forwarding_entry = &forwarding_entry_storage;
    struct ccn_signing_params sp = CCN_SIGNING_PARAMS_INIT;
    struct ccn_charbuf *keylocator_templ = NULL;
    struct ccn_keystore *keystore = NULL;
    long expire = -1;
    int ipproto;
    unsigned char ccndid_storage[32] = {0};
    const unsigned char *ccndid = NULL;
    size_t ccndid_size = 0;
    int res;
    int opt;

    progname = argv[0];
    while ((opt = getopt(argc, argv, "h")) != -1) {
        switch (opt) {
        case 'h':
        default:
            usage(progname);
        }
    }

    /* Sanity check the URI and argument count */
    arg = argv[optind];
    if (arg == NULL)
        usage(progname);
    name = ccn_charbuf_create();
    res = ccn_name_from_uri(name, arg);
    if (res < 0) {
        fprintf(stderr, "%s: bad ccn URI: %s\n", progname, arg);
        exit(1);
    }
    if (argc - optind < 3 || argc - optind > 4)
        usage(progname);

    h = ccn_create();
    res = ccn_connect(h, NULL);
    if (res < 0) {
        ccn_perror(h, "ccn_connect");
        exit(1);
    }

    newface = ccn_charbuf_create();
    temp = ccn_charbuf_create();
    templ = ccn_charbuf_create();
    keylocator_templ = ccn_charbuf_create();

    resultbuf = ccn_charbuf_create();
    name_prefix = ccn_charbuf_create();
    null_name = ccn_charbuf_create();
    CHKRES(ccn_name_init(null_name));

    keystore = ccn_keystore_create();

    /* We need to figure out our local ccnd's CCIDID */
    /* Set up our Interest template to indicate scope 1 */
    ccn_charbuf_reset(templ);
    ccnb_element_begin(templ, CCN_DTAG_Interest);
    ccnb_element_begin(templ, CCN_DTAG_Name);
    ccnb_element_end(templ);	/* </Name> */
    ccnb_tagged_putf(templ, CCN_DTAG_Scope, "1");
    ccnb_element_end(templ);	/* </Interest> */

    ccn_charbuf_reset(name);
    CHKRES(res = ccn_name_from_uri(name, "ccnx:/%C1.M.S.localhost/%C1.M.SRV/ccnd/KEY"));
    CHKRES(res = ccn_get(h, name, templ, 200, resultbuf, &pcobuf, NULL, 0));
    res = ccn_ref_tagged_BLOB(CCN_DTAG_PublisherPublicKeyDigest,
                              resultbuf->buf,
                              pcobuf.offset[CCN_PCO_B_PublisherPublicKeyDigest],
                              pcobuf.offset[CCN_PCO_E_PublisherPublicKeyDigest],
                              &ccndid, &ccndid_size);
    CHKRES(res);
    if (ccndid_size > sizeof(ccndid_storage))
        CHKRES(-1);
    memcpy(ccndid_storage, ccndid, ccndid_size);
    ccndid = ccndid_storage;

    face_instance->action = "newface";
    face_instance->ccnd_id = ccndid;
    face_instance->ccnd_id_size = ccndid_size;
    if (strcmp(argv[optind + 1], "tcp") == 0)
        ipproto = 6;
    else if (strcmp(argv[optind + 1], "udp") == 0)
        ipproto = 17;
    else
        ipproto = atoi(argv[optind + 1]);
    face_instance->descr.ipproto = ipproto; // XXX - 6 = tcp or 17 = udp
    face_instance->descr.address = argv[optind + 2];
    face_instance->descr.port = argv[optind + 3];
    if (face_instance->descr.port == NULL)
        face_instance->descr.port = CCN_DEFAULT_UNICAST_PORT;
    face_instance->descr.mcast_ttl = -1;
    face_instance->lifetime = (~0U) >> 1;

    CHKRES(res = ccnb_append_face_instance(newface, face_instance));
    temp->length = 0;
    CHKRES(ccn_charbuf_putf(temp, "%s/.ccnx/.ccnx_keystore", getenv("HOME")));
    res = ccn_keystore_init(keystore,
                            ccn_charbuf_as_string(temp),
                            "Th1s1sn0t8g00dp8ssw0rd.");
    CHKRES(res);

    ccnb_element_begin(keylocator_templ, CCN_DTAG_SignedInfo);
    ccnb_element_begin(keylocator_templ, CCN_DTAG_KeyLocator);
    ccnb_element_begin(keylocator_templ, CCN_DTAG_Key);
    CHKRES(ccn_append_pubkey_blob(keylocator_templ, ccn_keystore_public_key(keystore)));
    ccnb_element_end(keylocator_templ);	/* </Key> */
    ccnb_element_end(keylocator_templ);	/* </KeyLocator> */
    ccnb_element_end(keylocator_templ);    /* </SignedInfo> */
    sp.template_ccnb = keylocator_templ;
    sp.sp_flags |= CCN_SP_TEMPL_KEY_LOCATOR;
    sp.freshness = expire;
    ccn_charbuf_reset(temp);
    res = ccn_sign_content(h, temp, null_name, &sp,
                           newface->buf, newface->length);
    CHKRES(res);

    /* Create the new face */
    CHKRES(ccn_name_init(name));
    CHKRES(ccn_name_append_str(name, "ccnx"));
    CHKRES(ccn_name_append(name, ccndid, ccndid_size));
    CHKRES(ccn_name_append(name, "newface", 7));
    CHKRES(ccn_name_append(name, temp->buf, temp->length));
    res = ccn_get(h, name, templ, 1000, resultbuf, &pcobuf, NULL, 0);
    if (res < 0) {
        fprintf(stderr, "no response from face creation request\n");
        exit(1);
    }
    ptr = resultbuf->buf;
    length = resultbuf->length;
    res = ccn_content_get_value(resultbuf->buf, resultbuf->length, &pcobuf, &ptr, &length);
    CHKRES(res);
    face_instance = ccn_face_instance_parse(ptr, length);
    if (face_instance == NULL)
        CHKRES(res = -1);
    CHKRES(face_instance->faceid);

    /* Finally, register the prefix */
    ccn_charbuf_reset(name_prefix);
    CHKRES(ccn_name_from_uri(name_prefix, arg));
    forwarding_entry->action = "prefixreg";
    forwarding_entry->name_prefix = name_prefix;
    forwarding_entry->ccnd_id = ccndid;
    forwarding_entry->ccnd_id_size = ccndid_size;
    forwarding_entry->faceid = face_instance->faceid;
    forwarding_entry->flags = -1; /* let ccnd decide */
    forwarding_entry->lifetime = (~0U) >> 1;
    prefixreg = ccn_charbuf_create();
    CHKRES(res = ccnb_append_forwarding_entry(prefixreg, forwarding_entry));
    ccn_charbuf_reset(temp);
    res = ccn_sign_content(h, temp, null_name, &sp,
                           prefixreg->buf, prefixreg->length);
    CHKRES(res);
    CHKRES(ccn_name_init(name));
    CHKRES(ccn_name_append_str(name, "ccnx"));
    CHKRES(ccn_name_append(name, ccndid, ccndid_size));
    CHKRES(ccn_name_append_str(name, "prefixreg"));
    CHKRES(ccn_name_append(name, temp->buf, temp->length));
    res = ccn_get(h, name, templ, 1000, resultbuf, &pcobuf, NULL, 0);
    if (res < 0) {
        fprintf(stderr, "no response from prefix registration request\n");
        exit(1);
    }
    fprintf(stderr, "Prefix %s will be forwarded to face %d\n", arg, face_instance->faceid);

    /* We're about to exit, so don't bother to free everything. */
    ccn_destroy(&h);
    exit(res < 0);
}
Example #16
0
int main(int argc, char** argv){
	struct ccn * ccn = NULL;
	//struct ccn_charbuf * name = NULL;
	struct ccn_closure * incoming = NULL;
	//const char * arg = NULL;
	int res;
	int micros;
	char ch;
	struct mydata * mydata = NULL;
	int allow_stale = 0;
	int use_decimal = 1;

	// TANG: comment out unused variables
	//int lineMarker = -1;
	int start = 0;
	int flying = -1;
	
	int i = 0;
	
	char* urlFile = NULL;
		
	//By default, we will send all the urls listed in the file starting from position 0
	while ((ch = getopt(argc, argv, "n:s:f:hd")) != -1) {
        switch (ch) {
            case 'f':
				urlFile = optarg;
				//printf("file name = %s \n", optarg);
                break;
			case 's':
				start = atoi(optarg);
				//printf("start = %d \n", start);
				break;
            case 'n':
                res = atoi(optarg);
                if (1 <= res)
                flying = res;
                else
                    usage(argv[0]);
				//printf("flying = %d \n", flying);
                break;
			case 'd':
				DEBUG = 1;
				break;
            case 'h':
            default:
                usage(argv[0]);
        }
    }

	//Initialize the URL list	
	char ** urlList = NULL;

	int lineCount = getLineCount(urlFile);
	// printf("There are %d URLs in the file %s\n", lineCount, urlFile);
	
	if(flying == -1)
		flying = lineCount; //By default, all the URLs in the urlFile will be queried

	urlList = malloc(lineCount * sizeof(char*));

	char line[2000];

	int idx = 0;
	int lineIdx = 0;

	FILE *file = fopen(urlFile, "r");
	if(file == NULL){
		printf("Cannot open file %s, exiting...\n", urlFile);
		exit(-1);
	}

	while(fgets(line, sizeof line, file) != NULL){	/* read a line */
		if(lineIdx >= start && lineIdx < start + flying){
			urlList[idx] = malloc((strlen(line)) * sizeof(char));
			strcpy(urlList[idx], line);	
			urlList[idx][strlen(line)-1] = '\0';

			if(DEBUG){
				printf("URL %d = %s \n", idx, line);
				printf("URL length = %zu \n", strlen(line));
			}
				
			idx++;
		}
		lineIdx++;
	}
	

	ccn = ccn_create();
    if (ccn_connect(ccn, NULL) == -1) {
        perror("Could not connect to ccnd");
        exit(1);
    }

	mydata = calloc(1, sizeof(*mydata));
    mydata->h = ccn;
    mydata->allow_stale = allow_stale;
    mydata->use_decimal = use_decimal;
    mydata->excl = NULL;
	//Initialize the ooo data
	mydata->ooo = malloc(sizeof(struct ooodata) * flying);

    for (i = 0; i < flying; i++) {
        incoming = &mydata->ooo[i].closure;
        incoming->p = &incoming_content;
        incoming->data = mydata;
        incoming->intdata = -1;
    }

	//Build and send out a group of interests
	ask_set(mydata, urlList, flying);
	
	/* Run a little while to see if there is anything there*/
	res = ccn_run(ccn, 500);
	
    /* We got something, run until end of data or somebody kills us */
    while (res >= 0) {
        micros = 50000000;
        res = ccn_run(ccn, micros / 1000);
    }
	
	printf("Exiting....");

	fclose(urlFile);
	//Release the dynamically allocated memory
	free(mydata->ooo);
	free(mydata);
	ccn_destroy(&ccn);
    exit(res < 0);
}
Example #17
0
/**
 * Process options and then loop through command line CCNx URIs retrieving
 * the data and writing it to stdout.
 */
int
main(int argc, char **argv)
{
    struct ccn *ccn = NULL;
    struct ccn_charbuf *name = NULL;
    struct ccn_charbuf *templ = NULL;
    struct ccn_closure *incoming = NULL;
    const char *arg = NULL;
    int i;
    int res;
    int opt;
    struct mydata *mydata;
    int allow_stale = 0;
    int *done;
    int exit_status = 0;
    
    done = calloc(1, sizeof(*done));
    
    while ((opt = getopt(argc, argv, "ha")) != -1) {
        switch (opt) {
            case 'a':
                allow_stale = 1;
                break;
            case 'h':
            default:
                usage(argv[0]);
        }
    }
    arg = argv[optind];
    if (arg == NULL)
        usage(argv[0]);
    name = ccn_charbuf_create();
    /* Check the args first */
    for (i = optind; argv[i] != NULL; i++) {
        name->length = 0;
        res = ccn_name_from_uri(name, argv[i]);
        if (res < 0) {
            fprintf(stderr, "%s: bad ccn URI: %s\n", argv[0], argv[i]);
            exit(1);
        }
    }
    for (i = optind; (arg = argv[i]) != NULL; i++) {
        *done = 0;
        name->length = 0;
        res = ccn_name_from_uri(name, arg);
        ccn = ccn_create();
        if (ccn_connect(ccn, NULL) == -1) {
            perror("Could not connect to ccnd");
            exit(1);
        }
        ccn_resolve_version(ccn, name, CCN_V_HIGHEST, 50);
        ccn_name_append_numeric(name, CCN_MARKER_SEQNUM, 0);
        incoming = calloc(1, sizeof(*incoming));
        incoming->p = &incoming_content;
        mydata = calloc(1, sizeof(*mydata));
        mydata->allow_stale = allow_stale;
        mydata->done = done;
        incoming->data = mydata;
        templ = make_template(mydata, NULL);
        ccn_express_interest(ccn, name, incoming, templ);
        ccn_charbuf_destroy(&templ);
        /* Run a little while to see if there is anything there */
        res = ccn_run(ccn, 200);
        if ((!*done) && incoming->intdata == 0) {
            fprintf(stderr, "%s: not found: %s\n", argv[0], arg);
            res = -1;
        }
        /* We got something; run until end of data or somebody kills us */
        while (res >= 0 && !*done) {
            fflush(stdout);
            res = ccn_run(ccn, 333);
        }
        if (res < 0)
            exit_status = 1;
        ccn_destroy(&ccn);
        fflush(stdout);
        free(incoming);
        incoming = NULL;
    }
    ccn_charbuf_destroy(&name);
    free(done);
    exit(exit_status);
}
Example #18
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);
}
Example #19
0
int
main(int argc, char **argv)
{
    int opt;
    int res;
    char *prog = argv[0];
    struct ccn *h;
    struct ccns_slice *slice;
    struct ccn_charbuf *prefix = ccn_charbuf_create();
    struct ccn_charbuf *topo = ccn_charbuf_create();
    struct ccn_charbuf *clause = ccn_charbuf_create();
    struct ccn_charbuf *slice_name = ccn_charbuf_create();
    struct ccn_charbuf *slice_uri = ccn_charbuf_create();
    enum {
        CREATE = 0,
        DELETE = 1
    } cmd = CREATE;
    unsigned verbose = 0;
    unsigned i;
    
    if (prefix == NULL || topo == NULL || clause == NULL ||
        slice_name == NULL || slice_uri == NULL) {
        fprintf(stderr, "Unable to allocate required memory.\n");
        exit(1);
    }
    
    while ((opt = getopt(argc, argv, "vh")) != -1) {
        switch (opt) {
            case 'v':
                verbose = 1;
                break;
            default:
            case 'h':
                usage(prog);
                break;
        }
    }
    argc -= optind;
    argv += optind;
    
    if (argc < 3)
        usage(prog);
    if (strcmp(argv[0], "create") == 0)
        cmd = CREATE;
    else if (strcmp(argv[0], "delete") == 0)
        cmd = DELETE;
    else
        usage(prog);
    
    slice = ccns_slice_create();
    
    ccn_charbuf_reset(topo);
    if (0 > ccn_name_from_uri(topo, argv[1])) usage(prog);
    ccn_charbuf_reset(prefix);
    if (0 > ccn_name_from_uri(prefix, argv[2])) usage(prog);
    if (0 > ccns_slice_set_topo_prefix(slice, topo, prefix)) usage(prog);
    for (i = 3; i < argc; i++) {
        ccn_charbuf_reset(clause);
        if (0 > ccn_name_from_uri(clause, argv[i])) usage(prog);
        else
            if (0 > ccns_slice_add_clause(slice, clause)) usage(prog);
    }
    
    h = ccn_create();
    res = ccn_connect(h, NULL);
    if (0 > res) {
        fprintf(stderr, "Unable to connect to ccnd.\n");
        exit(1);
    }
    switch(cmd) {
        case CREATE:
            res = ccns_write_slice(h, slice, slice_name);
            break;
        case DELETE:
            ccns_slice_name(slice_name, slice);
            res = ccns_delete_slice(h, slice_name);
            break;
    }
    if (verbose || res < 0) {
        ccn_uri_append(slice_uri, slice_name->buf, slice_name->length, 1);
        printf("%s slice %s %s\n",
               cmd == CREATE ? "create" : "delete",
               ccn_charbuf_as_string(slice_uri),
               (res < 0) ? "failed" : "succeeded");
    }
    ccns_slice_destroy(&slice);
    ccn_destroy(&h);
    ccn_charbuf_destroy(&prefix);
    ccn_charbuf_destroy(&topo);
    ccn_charbuf_destroy(&clause);
    ccn_charbuf_destroy(&slice_name);
    ccn_charbuf_destroy(&slice_uri);
    
    exit(res);
}
Example #20
0
void CcnCC_dtor(CcnCC self) {
	ccn_destroy(&(self->ccnh));
	free(self);
}
Example #21
0
int
main(int argc, char **argv)
{
    struct ccn *ccn = NULL;
    struct ccn_charbuf *c = NULL;
    struct ccn_charbuf *templ = NULL;
    int i;
    int res;
    int opt;
    FILE* closethis = NULL;
    
    while ((opt = getopt(argc, argv, "ho:")) != -1) {
        switch (opt) {
            case 'o':
                if (strcmp(optarg, "-") == 0)
                    mydata.output = stdout;
                else
                    mydata.output = closethis = fopen(optarg, "wb");
                if (mydata.output == NULL) {
                    perror(optarg);
                    exit(1);
                }
                break;
            case 'h': /* FALLTHRU */
            default: usage(argv[0]);
        }
    }
    
    ccn = ccn_create();
    if (ccn_connect(ccn, NULL) == -1) {
        perror("Could not connect to ccnd");
        exit(1);
    }
    c = ccn_charbuf_create();
    /* set scope to only address ccnd, expire anything we get */
    templ = local_scope_rm_template();
    for (i = optind; argv[i] != NULL; i++) {
        c->length = 0;
        res = ccn_name_from_uri(c, argv[i]);
        if (res < 0) {
            fprintf(stderr, "%s: bad ccn URI: %s\n", argv[0], argv[i]);
            exit(1);
        }
        ccn_express_interest(ccn, c, &incoming_content_action, templ);
    }
    if (i == optind)
        usage(argv[0]);
    ccn_charbuf_destroy(&templ);
    ccn_charbuf_destroy(&c);
    for (i = 0;; i++) {
        res = mydata.nseen;
        ccn_run(ccn, 100); /* stop if we run dry for 1/10 sec */
        if (res == mydata.nseen)
            break;
    }
    if (closethis != NULL)
        fclose(closethis);
    ccn_destroy(&ccn);
    fprintf(stderr, "marked stale: %d\n", mydata.nseen);
    exit(0);
}
Example #22
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);
}
Example #23
0
int
main(int argc, char **argv)
{
    const char *progname = argv[0];
    struct ccn *ccn = NULL;
    struct ccn_charbuf *name = NULL;
    struct ccn_seqwriter *w = NULL;
    int blocksize = CCN_MAX_CONTENT_PAYLOAD / 2;
    int freshness = -1;
    int torepo = 0;
    int scope = 1;
    int i;
    int status = 0;
    int res;
    ssize_t read_res;
    size_t blockread;
    unsigned char *buf = NULL;
    struct ccn_charbuf *templ;
    char *symmetric_suffix = NULL;
    const char *password = NULL;
    char *dir = NULL;
    
    while ((res = getopt(argc, argv, "hrb:s:x:d:p:o:")) != -1) {
        switch (res) {
            case 'b':
                blocksize = atoi(optarg);
                if (blocksize <= 0 || blocksize > CCN_MAX_CONTENT_PAYLOAD)
                    usage(progname);
                break;
            case 'r':
                torepo = 1;
                break;
            case 's':
                scope = atoi(optarg);
                if (scope < 1 || scope > 3)
                    usage(progname);
                break;
            case 'x':
                freshness = atoi(optarg);
                if (freshness < 0)
                    usage(progname);
                break;
            case 'd':
                symmetric_suffix = optarg;
                break;
            case 'p':
                password = optarg;
                break;
            case 'o':
                dir = optarg;
                break;
            case 'h':
                usage(progname);
                break;
        }
    }
    argc -= optind;
    argv += optind;
    if (argc != 1)
        usage(progname);
    name = ccn_charbuf_create();
    res = ccn_name_from_uri(name, argv[0]);
    if (res < 0) {
        fprintf(stderr, "%s: bad CCN URI: %s\n", progname, argv[0]);
        exit(1);
    }
    ccn = ccn_create();
    if (ccn_connect(ccn, NULL) == -1) {
        perror("Could not connect to ccnd");
        exit(1);
    }
    
    buf = calloc(1, blocksize);
    
    w = ccn_seqw_create(ccn, name);
    if (w == NULL) {
        fprintf(stderr, "ccn_seqw_create failed\n");
        exit(1);
    }

    if (symmetric_suffix != NULL) {
        struct ccn_charbuf *key_digest = ccn_charbuf_create();

        if (ccn_get_key_digest_from_suffix(ccn, dir, symmetric_suffix, password, key_digest)) {
            perror("Can't access keystore");
            exit(1);
        }
        ccn_seqw_set_key_digest(w, key_digest->buf, key_digest->length);
        ccn_charbuf_destroy(&key_digest);
    }
    
    ccn_seqw_set_block_limits(w, blocksize, blocksize);
    if (freshness > -1)
        ccn_seqw_set_freshness(w, freshness);
    if (torepo) {
        struct ccn_charbuf *name_v = ccn_charbuf_create();
        ccn_seqw_get_name(w, name_v);
        ccn_name_from_uri(name_v, "%C1.R.sw");
        ccn_name_append_nonce(name_v);
        templ = make_template(scope);
        res = ccn_get(ccn, name_v, templ, 60000, NULL, NULL, NULL, 0);
        ccn_charbuf_destroy(&templ);
        ccn_charbuf_destroy(&name_v);
        if (res < 0) {
            fprintf(stderr, "No response from repository\n");
            exit(1);
        }
    }
    blockread = 0;
    for (i = 0;; i++) {
        while (blockread < blocksize) {
            if (ccn_run(ccn, 1) < 0) {
                fprintf(stderr, "Lost connection to ccnd: %s\n",
                        strerror(ccn_geterror(ccn)));
                exit(1);
            }
            read_res = read(0, buf + blockread, blocksize - blockread);
            if (read_res == 0)
                goto cleanup;
            if (read_res < 0) {
                perror("read");
                status = 1;
                goto cleanup;
            }
            blockread += read_res;
        }
        res = ccn_seqw_write(w, buf, blockread);
        while (res == -1) {
            if (ccn_run(ccn, 100) < 0) {
                fprintf(stderr, "Lost connection to ccnd: %s\n",
                        strerror(ccn_geterror(ccn)));
                exit(1);
            }
            res = ccn_seqw_write(w, buf, blockread);
        }
        if (res != blockread)
            abort(); /* hmm, ccn_seqw_write did a short write or something */
        blockread = 0;
    }
    
cleanup:
    // flush out any remaining data and close
    if (blockread > 0) {
        res = ccn_seqw_write(w, buf, blockread);
        while (res == -1) {
            if (ccn_run(ccn, 100) < 0) {
                fprintf(stderr, "Lost connection to ccnd: %s\n",
                        strerror(ccn_geterror(ccn)));
                exit(1);
            }
            res = ccn_seqw_write(w, buf, blockread);
        }
    }
    ccn_seqw_close(w);
    ccn_run(ccn, 1);
    free(buf);
    buf = NULL;
    ccn_charbuf_destroy(&name);
    ccn_destroy(&ccn);
    exit(status);
}
Example #24
0
int
main(int argc, char **argv)
{
    const char *progname = argv[0];
    struct ccn *ccn = NULL;
    struct ccn_charbuf *name = NULL;
    struct ccn_seqwriter *w = NULL;
    int blocksize = 1024;
    int torepo = 0;
    int scope = 1;
    int i;
    int status = 0;
    int res;
    ssize_t read_res;
    size_t blockread;
    unsigned char *buf = NULL;
    struct ccn_charbuf *templ;

    while ((res = getopt(argc, argv, "hrb:s:")) != -1) {
        switch (res) {
        case 'b':
            blocksize = atoi(optarg);
            if (blocksize <= 0 || blocksize > 4096)
                usage(progname);
            break;
        case 'r':
            torepo = 1;
            break;
        case 's':
            scope = atoi(optarg);
            if (scope < 1 || scope > 3)
                usage(progname);
            break;
        default:
        case 'h':
            usage(progname);
            break;
        }
    }
    argc -= optind;
    argv += optind;
    if (argc != 1)
        usage(progname);
    name = ccn_charbuf_create();
    res = ccn_name_from_uri(name, argv[0]);
    if (res < 0) {
        fprintf(stderr, "%s: bad CCN URI: %s\n", progname, argv[0]);
        exit(1);
    }
    ccn = ccn_create();
    if (ccn_connect(ccn, NULL) == -1) {
        perror("Could not connect to ccnd");
        exit(1);
    }

    buf = calloc(1, blocksize);

    w = ccn_seqw_create(ccn, name);
    if (w == NULL) {
        fprintf(stderr, "ccn_seqw_create failed\n");
        exit(1);
    }
    ccn_seqw_set_block_limits(w, blocksize, blocksize);
    if (torepo) {
        struct ccn_charbuf *name_v = ccn_charbuf_create();
        ccn_seqw_get_name(w, name_v);
        ccn_name_from_uri(name_v, "%C1.R.sw");
        ccn_name_append_nonce(name_v);
        templ = make_template(scope);
        res = ccn_get(ccn, name_v, templ, 60000, NULL, NULL, NULL, 0);
        ccn_charbuf_destroy(&templ);
        ccn_charbuf_destroy(&name_v);
        if (res < 0) {
            fprintf(stderr, "No response from repository\n");
            exit(1);
        }
    }
    blockread = 0;
    for (i = 0;; i++) {
        while (blockread < blocksize) {
            ccn_run(ccn, 1);
            read_res = read(0, buf + blockread, blocksize - blockread);
            if (read_res == 0)
                goto cleanup;
            if (read_res < 0) {
                perror("read");
                status = 1;
                goto cleanup;
            }
            blockread += read_res;
        }
        res = ccn_seqw_write(w, buf, blockread);
        while (res == -1) {
            ccn_run(ccn, 100);
            res = ccn_seqw_write(w, buf, blockread);
        }
        if (res != blockread)
            abort(); /* hmm, ccn_seqw_write did a short write or something */
        blockread = 0;
    }

cleanup:
    // flush out any remaining data and close
    if (blockread > 0) {
        res = ccn_seqw_write(w, buf, blockread);
        while (res == -1) {
            ccn_run(ccn, 100);
            res = ccn_seqw_write(w, buf, blockread);
        }
    }
    ccn_seqw_close(w);
    ccn_run(ccn, 1);
    free(buf);
    buf = NULL;
    ccn_charbuf_destroy(&name);
    ccn_destroy(&ccn);
    exit(status);
}
Example #25
0
int
main(int argc, char **argv)
{
    struct ccn *ccn = NULL;
    struct ccn_charbuf *name = NULL;
    struct ccn_charbuf *templ = NULL;
    struct ccn_closure *incoming = NULL;
    const char *arg = NULL;
    int res;
    int opt;
    struct mydata *mydata;
    int allow_stale = 0;
    
    while ((opt = getopt(argc, argv, "ha")) != -1) {
        switch (opt) {
            case 'a':
                allow_stale = 1;
                break;
            case 'h':
            default:
                usage(argv[0]);
        }
    }
    arg = argv[optind];
    if (arg == NULL)
        usage(argv[0]);
    name = ccn_charbuf_create();
    res = ccn_name_from_uri(name, arg);
    if (res < 0) {
        fprintf(stderr, "%s: bad ccn URI: %s\n", argv[0], arg);
        exit(1);
    }
    if (argv[optind + 1] != NULL)
        fprintf(stderr, "%s warning: extra arguments ignored\n", argv[0]);
    ccn = ccn_create();
    if (ccn_connect(ccn, NULL) == -1) {
        perror("Could not connect to ccnd");
        exit(1);
    }
    ccn_name_append(name, "0", 1);
    incoming = calloc(1, sizeof(*incoming));
    incoming->p = &incoming_content;
    mydata = calloc(1, sizeof(*mydata));
    mydata->allow_stale = allow_stale;
    incoming->data = mydata;
    templ = make_template(mydata, NULL);
    ccn_express_interest(ccn, name, incoming, templ);
    ccn_charbuf_destroy(&templ);
    ccn_charbuf_destroy(&name);
    /* Run a little while to see if there is anything there */
    res = ccn_run(ccn, 200);
    if (incoming->intdata == 0) {
        fprintf(stderr, "%s: not found: %s\n", argv[0], arg);
        exit(1);
    }
    /* We got something, run until end of data or somebody kills us */
    while (res >= 0) {
        fflush(stdout);
        res = ccn_run(ccn, 200);
    }
    ccn_destroy(&ccn);
    exit(res < 0);
}
Example #26
0
static void
pyccn_Capsule_Destructor(PyObject *capsule)
{
	const char *name;
	void *pointer;
	enum _pyccn_capsules type;

	assert(PyCapsule_CheckExact(capsule));

	name = PyCapsule_GetName(capsule);
	type = name2type(name);

	pointer = PyCapsule_GetPointer(capsule, name);
	assert(pointer);

	switch (type) {
	case CLOSURE:
	{
		PyObject *py_obj_closure;
		struct ccn_closure *p = pointer;

		py_obj_closure = PyCapsule_GetContext(capsule);
		assert(py_obj_closure);
		Py_DECREF(py_obj_closure); /* No longer referencing Closure object */

		/* If we store something else, than ourselves, it probably is a bug */
		assert(capsule == p->data);

		free(p);
	}
		break;
	case CONTENT_OBJECT:
	{
		struct content_object_data *context;
		struct ccn_charbuf *p = pointer;

		context = PyCapsule_GetContext(capsule);
		if (context) {
			if (context->pco)
				free(context->pco);
			ccn_indexbuf_destroy(&context->comps);
			free(context);
		}
		ccn_charbuf_destroy(&p);
	}
		break;
	case HANDLE:
	{
		struct ccn *p = pointer;
		ccn_disconnect(p);
		ccn_destroy(&p);
	}
		break;
	case INTEREST:
	{
		struct interest_data *context;
		struct ccn_charbuf *p = pointer;

		context = PyCapsule_GetContext(capsule);
		if (context) {
			if (context->pi)
				free(context->pi);
			free(context);
		}
		ccn_charbuf_destroy(&p);
	}
		break;
	case PKEY_PRIV:
	case PKEY_PUB:
	{
		struct ccn_pkey *p = pointer;
		ccn_pubkey_free(p);
	}
		break;
	case EXCLUSION_FILTER:
	case KEY_LOCATOR:
	case NAME:
	case SIGNATURE:
	case SIGNED_INFO:
	{
		struct ccn_charbuf *p = pointer;
		ccn_charbuf_destroy(&p);
	}
		break;
	case SIGNING_PARAMS:
	{
		struct ccn_signing_params *p = pointer;

		if (p->template_ccnb)
			ccn_charbuf_destroy(&p->template_ccnb);

		free(p);
	}
		break;
	default:
		debug("Got capsule: %s\n", PyCapsule_GetName(capsule));
		panic("Unable to destroy the object: got an unknown capsule");
	}
}
Example #27
0
int main(void) {
	int res;
	struct ccn *ccn= NULL;
	struct ccn_charbuf *name = NULL;
	struct ccn_charbuf *result = NULL;
	struct ccn_closure in_interest = {.p=&incoming_interest};
	struct ccn_signing_params sp = CCN_SIGNING_PARAMS_INIT; // Parameters for creating signed content objects.
	char rawcontentbuf[1024] = "";
	size_t content_size;

	// 1. Name
	name = ccn_charbuf_create();
	res = ccn_name_from_uri(name, URI);
	if (res < 0) {
		fprintf(stderr, "bad ccn URI: %s\n", URI);
		exit(1);
	}

	// 2. ccn_create, and ccn_connect
	ccn = ccn_create();
	res = ccn_connect(ccn, NULL);
	if (res < 0) {
		fprintf(stderr, "can't connect to ccnd: %d\n", res);
		ccn_perror(ccn, "ccn_connect");
		exit(1);
	}

	// 3. Create the signed content object, set up &sp - signing params;

	// Extend a Name with a new version stamp if requested
	/*int versioned = 0;
	const char *postver = NULL;
	memcmp(postver, "%00", 3);
	if (versioned) {
		res = ccn_create_version(ccn, name, CCN_V_REPLACE | CCN_V_NOW | CCN_V_HIGH, 0, 0);
		if (res < 0) {
			fprintf(stderr, "%s: ccn_create_version() failed\n");
			exit(1);
		}
		if (postver != NULL) {
			res = ccn_name_from_uri(name, postver);
			if (res < 0) {
				fprintf(stderr, "-V %s: invalid name suffix\n", postver);
				exit(0);
			}
		}
	} */

	// Ask for a FinalBlockID if appropriate
	/*int setfinal = 0;
	if (setfinal)
		sp.sp_flags |= CCN_SP_FINAL_BLOCK;
	*/

	// Set content type
	//sp.type = content_type;

	// Set freshness
	/* The template_ccnb may contain a ccnb-encoded SignedInfo to supply selected fields from under
	 * the direction of sp_flags.
	 */
	/*int expire = -1;
	if (expire >= 0) {
		if (sp.template_ccnb == NULL) {
			sp.template_ccnb = ccn_charbuf_create();
			ccn_charbuf_append_tt(sp.template_ccnb, CCN_DTAG_SignedInfo, CCN_DTAG);
			}
		else if (sp.template_ccnb -> length > 0) {
			sp.template_ccnb -> length--;
		}
		ccnb_tagged_putf(sp.template_ccnb, CCN_DTAG_FreshnessSeconds, "%ld", expire);
		sp.sp_flags |= CCN_SP_TEMPL_FRESHNESS;
		ccn_charbuf_append_closer(sp.template_ccnb);
	}
	*/

	// Set key locator, if supplied
	/*const char *key_uri = NULL;
	//key_uri = optarg;
	if (key_uri != NULL) {
		struct ccn_charbuf *c = ccn_charbuf_create();
		res = ccn_name_from_uri(c, key_uri);
		if (res < 0) {
			fprintf(stderr, "%s is not a valid ccnx URI\n", key_uri);
			exit(1);
		}
		if (sp.template_ccnb == NULL) {
			sp.template_ccnb = ccn_charbuf_create();
			ccn_charbuf_append_tt(sp.template_ccnb, CCN_DTAG_SignedInfo, CCN_DTAG);
		}
		else if (sp.template_ccnb -> length > 0) {
			sp.template_ccnb -> length--;
		}
		ccn_charbuf_append_tt(sp.template_ccnb, CCN_DTAG_KeyLocator, CCN_DTAG);
		ccn_charbuf_append_tt(sp.template_ccnb, CCN_DTAG_KeyName, CCN_DTAG);
		ccn_charbuf_append(sp.template_ccnb, c->buf, c->length);
		ccn_charbuf_append_closer(sp.template_ccnb);
		ccn_charbuf_append_closer(sp.template_ccnb);
		sp.sp_flags |= CCN_SP_TEMPL_KEY_LOCATOR;
		ccn_charbuf_append_closer(sp.template_ccnb);
		ccn_charbuf_destroy(&c);
	}
	*/

	// Set up a handler for interest
	ccn_set_interest_filter(ccn, name, &in_interest);


	// 4. Use ccn_sign_content to create the signed content object with composed &sp,
	// if (force) { ccn_put; } # ccn_get means send ccn binary. For normal clients, this should be a ContentObject sent in response to an Interest.
	// else { ccn_set_interest_filter; ccn_run; }

	result = ccn_charbuf_create();
	result -> length = 0;
	strcat(rawcontentbuf, CONTENTDATA);
	content_size = strlen(rawcontentbuf);
	//sp.sp_flags |= CCN_SP_FINAL_BLOCK;
	res = ccn_sign_content(ccn, result, name, &sp, rawcontentbuf, content_size);
	if (res < 0) {
		ccn_perror(ccn, "ccn_sign_content");
		exit(1);
	}

	printf("Content signed, trying to send the data...\n");
	res = ccn_put(ccn, result->buf, result->length);
	if (res < 0) {
		ccn_perror(ccn, "ccn_put");
		printf("Failed to send content object: res = %d\n", res);
		exit(1);
	}
	else
		printf("ccn_put done, content object sent.\n");

	// ccn_run serves as the event loop when timeout = -1
	res = ccn_run(ccn, -1);  // Loop here all the time until it is killed, then "Event loop..."
	printf("Event loop...\n");
	if (res < 0) {
		ccn_perror(ccn, "ccn_run");
		printf("Error: ccn_run\n");
		exit(1);
	}

	ccn_destroy(&ccn);
	ccn_charbuf_destroy(&name);
	ccn_charbuf_destroy(&result);
	ccn_charbuf_destroy(&sp.template_ccnb);
	printf("ccn handle is destroyed... \n");

	return 0;

}
Example #28
0
File: ccnls.c Project: Emat12/ccnx
int
main(int argc, char **argv)
{
    struct ccn *ccn = NULL;
    struct ccn_charbuf *c = NULL;
    struct ccn_charbuf *templ = NULL;
    struct upcalldata *data = NULL;
    int i;
    int n;
    int res;
    long counter = 0;
    struct ccn_closure *cl = NULL;
    int timeout_ms = 500;
    const char *env_timeout = getenv("CCN_LINGER");
    const char *env_verify = getenv("CCN_VERIFY");
    const char *env_scope = getenv("CCN_SCOPE");

    if (argv[1] == NULL || argv[2] != NULL)
        usage(argv[0]);

    if (env_timeout != NULL && (i = atoi(env_timeout)) > 0)
        timeout_ms = i * 1000;

    c = ccn_charbuf_create();
    res = ccn_name_from_uri(c, argv[1]);
    if (res < 0)
        usage(argv[0]);
        
    ccn = ccn_create();
    if (ccn_connect(ccn, NULL) == -1) {
        perror("Could not connect to ccnd");
        exit(1);
    }
    
    data = calloc(1, sizeof(*data));
    data->magic = 856372;
    data->warn = 1492;
    data->counter = &counter;
    data->option = 0;
    if (env_verify && *env_verify)
        data->option |= MUST_VERIFY;
    data->scope = -1;
    if (env_scope != NULL && (i = atoi(env_scope)) >= 0)
      data->scope = i;
    cl = calloc(1, sizeof(*cl));
    cl->p = &incoming_content;
    cl->data = data;
    if (data->scope > -1) {
        templ = ccn_charbuf_create();
        ccn_charbuf_append_tt(templ, CCN_DTAG_Interest, CCN_DTAG);
        ccn_charbuf_append_tt(templ, CCN_DTAG_Name, CCN_DTAG);
        ccn_charbuf_append_closer(templ); /* </Name> */
        ccnb_tagged_putf(templ, CCN_DTAG_Scope, "%d", data->scope);
        ccn_charbuf_append_closer(templ); /* </Interest> */
    }
    ccn_express_interest(ccn, c, cl, templ);
    ccn_charbuf_destroy(&templ);
    cl = NULL;
    data = NULL;
    for (i = 0;; i++) {
        n = counter;
        ccn_run(ccn, timeout_ms); /* stop if we run dry for 1/2 sec */
        fflush(stdout);
        if (counter == n)
            break;
    }
    ccn_destroy(&ccn);
    ccn_charbuf_destroy(&c);
    exit(0);
}
Example #29
0
int
main(int argc, char **argv)
{
    const char *progname = argv[0];
    struct ccn *ccn = NULL;
    struct ccn_charbuf *root = NULL;
    struct ccn_charbuf *name = NULL;
    struct ccn_charbuf *temp = NULL;
    struct ccn_charbuf *templ = NULL;
    struct ccn_charbuf *signed_info = NULL;
    struct ccn_charbuf *keylocator = NULL;
    struct ccn_charbuf *finalblockid = NULL;
    struct ccn_keystore *keystore = NULL;
    long expire = -1;
    long blocksize = 1024;
    int i;
    int status = 0;
    int res;
    ssize_t read_res;
    unsigned char *buf = NULL;
    struct mydata mydata = { 0 };
    struct ccn_closure in_content = {.p=&incoming_content, .data=&mydata};
    struct ccn_closure in_interest = {.p=&incoming_interest, .data=&mydata};
    while ((res = getopt(argc, argv, "hx:b:")) != -1) {
        switch (res) {
            case 'x':
                expire = atol(optarg);
                if (expire <= 0)
                    usage(progname);
                break;
	    case 'b':
	        blocksize = atol(optarg);
                break;
            default:
            case 'h':
                usage(progname);
                break;
        }
    }
    argc -= optind;
    argv += optind;
    if (argv[0] == NULL)
        usage(progname);
    name = ccn_charbuf_create();
    res = ccn_name_from_uri(name, argv[0]);
    if (res < 0) {
        fprintf(stderr, "%s: bad ccn URI: %s\n", progname, argv[0]);
        exit(1);
    }
    if (argv[1] != NULL)
        fprintf(stderr, "%s warning: extra arguments ignored\n", progname);

    ccn = ccn_create();
    if (ccn_connect(ccn, NULL) == -1) {
        perror("Could not connect to ccnd");
        exit(1);
    }
    
    buf = calloc(1, blocksize);
    root = name;
    name = ccn_charbuf_create();
    temp = ccn_charbuf_create();
    templ = ccn_charbuf_create();
    signed_info = ccn_charbuf_create();
    keystore = ccn_keystore_create();
    temp->length = 0;
    ccn_charbuf_putf(temp, "%s/.ccnx/.ccnx_keystore", getenv("HOME"));
    res = ccn_keystore_init(keystore,
                            ccn_charbuf_as_string(temp),
                            "Th1s1sn0t8g00dp8ssw0rd.");
    if (res != 0) {
        printf("Failed to initialize keystore\n");
        exit(1);
    }
    
    name->length = 0;
    ccn_charbuf_append(name, root->buf, root->length);
    
    /* Set up a handler for interests */
    ccn_set_interest_filter(ccn, name, &in_interest);
    
    /* Initiate check to see whether there is already something there. */
    temp->length = 0;
    ccn_charbuf_putf(temp, "%d", 0);
    ccn_name_append(name, temp->buf, temp->length);
    templ->length = 0;
    ccn_charbuf_append_tt(templ, CCN_DTAG_Interest, CCN_DTAG);
    ccn_charbuf_append_tt(templ, CCN_DTAG_Name, CCN_DTAG);
    ccn_charbuf_append_closer(templ); /* </Name> */
    ccn_charbuf_append_tt(templ, CCN_DTAG_MaxSuffixComponents, CCN_DTAG);
    ccn_charbuf_append_tt(templ, 1, CCN_UDATA);
    ccn_charbuf_append(templ, "1", 1);
    ccn_charbuf_append_closer(templ); /* </MaxSuffixComponents> */
    // XXX - use pubid
    ccn_charbuf_append_closer(templ); /* </Interest> */
    res = ccn_express_interest(ccn, name, &in_content, templ);
    if (res < 0) abort();
    
    /* Construct a key locator contining the key itself */
    keylocator = ccn_charbuf_create();
    ccn_charbuf_append_tt(keylocator, CCN_DTAG_KeyLocator, CCN_DTAG);
    ccn_charbuf_append_tt(keylocator, CCN_DTAG_Key, CCN_DTAG);
    res = ccn_append_pubkey_blob(keylocator, ccn_keystore_public_key(keystore));
    if (res < 0)
        ccn_charbuf_destroy(&keylocator);
    else {
        ccn_charbuf_append_closer(keylocator); /* </Key> */
        ccn_charbuf_append_closer(keylocator); /* </KeyLocator> */
    }
    
    for (i = 0;; i++) {
        read_res = read_full(0, buf, blocksize);
        if (read_res < 0) {
            perror("read");
            read_res = 0;
            status = 1;
        }
        signed_info->length = 0;
        if (read_res < blocksize) {
            temp->length = 0;
            ccn_charbuf_putf(temp, "%d", i);
            ccn_name_append(name, temp->buf, temp->length);
            finalblockid = ccn_charbuf_create();
            ccn_charbuf_append_tt(finalblockid, temp->length, CCN_BLOB);
            ccn_charbuf_append(finalblockid, temp->buf, temp->length);
        }
        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_DATA,
                                     /*freshness*/ expire,
                                     finalblockid,
                                     keylocator);
        /* Put the keylocator in the first block only. */
        ccn_charbuf_destroy(&keylocator);
        if (res < 0) {
            fprintf(stderr, "Failed to create signed_info (res == %d)\n", res);
            exit(1);
        }
        name->length = 0;
        ccn_charbuf_append(name, root->buf, root->length);
        temp->length = 0;
        ccn_charbuf_putf(temp, "%d", i);
        ccn_name_append(name, temp->buf, temp->length);
        temp->length = 0;
        ccn_charbuf_append(temp, buf, read_res);
        temp->length = 0;
        res = ccn_encode_ContentObject(temp,
                                       name,
                                       signed_info,
                                       buf,
                                       read_res,
                                       NULL,
                                       ccn_keystore_private_key(keystore));
        if (res != 0) {
            fprintf(stderr, "Failed to encode ContentObject (res == %d)\n", res);
            exit(1);
        }
        if (i == 0) {
            /* Finish check for old content */
            if (mydata.content_received == 0)
                ccn_run(ccn, 100);
            if (mydata.content_received > 0) {
                fprintf(stderr, "%s: name is in use: %s\n", progname, argv[0]);
                exit(1);
            }
            mydata.outstanding++; /* the first one is free... */
        }
        res = ccn_put(ccn, temp->buf, temp->length);
        if (res < 0) {
            fprintf(stderr, "ccn_put failed (res == %d)\n", res);
            exit(1);
        }
        if (read_res < blocksize)
            break;
        if (mydata.outstanding > 0)
            mydata.outstanding--;
        else
            res = 10;
        res = ccn_run(ccn, res * 100);
        if (res < 0) {
            status = 1;
            break;
        }
    }
    
    free(buf);
    buf = NULL;
    ccn_charbuf_destroy(&root);
    ccn_charbuf_destroy(&name);
    ccn_charbuf_destroy(&temp);
    ccn_charbuf_destroy(&signed_info);
    ccn_charbuf_destroy(&finalblockid);
    ccn_keystore_destroy(&keystore);
    ccn_destroy(&ccn);
    exit(status);
}
Example #30
0
int
main(int argc, char **argv)
{
    const char *progname = argv[0];
    struct ccn *ccn = NULL;
    struct ccn_charbuf *c = NULL;
    struct upcalldata *data = NULL;
    int opt;
    int i;
    long n;
    int res;
    long counter = 0;
    struct ccn_closure *cl = NULL;
    
    while ((opt = getopt(argc, argv, "h")) != -1) {
        switch (opt) {
            case 'h':
            default:
                usage(argv[0]);
        }
    }

    if (argv[optind] == NULL || argv[optind + 1] != NULL)
        usage(argv[0]);

    passive_templ = create_passive_templ();
    c = ccn_charbuf_create();
    res = ccn_name_from_uri(c, argv[optind]);
    if (res < 0) {
        fprintf(stderr, "%s: bad ccn URI: %s\n", progname, argv[optind]);
        exit(1);
    }
        
    ccn = ccn_create();
    if (ccn_connect(ccn, NULL) == -1) {
        perror("Could not connect to ccnd");
        exit(1);
    }
    
    data = calloc(1, sizeof(*data));
    data->magic = 856372;
    data->warn = 1492;
    data->counter = &counter;
    cl = calloc(1, sizeof(*cl));
    cl->p = &incoming_content;
    cl->data = data;
    ccn_express_interest(ccn, c, cl, passive_templ);
    cl = NULL;
    data = NULL;
    ccn_charbuf_destroy(&c);
    for (i = 0;; i++) {
        n = counter;
        ccn_run(ccn, 1000); /* stop if we run dry for 1 sec */
        fflush(stdout);
        if (counter == n)
            break;
    }
    ccn_destroy(&ccn);
    ccn_charbuf_destroy(&passive_templ);
    exit(0);
}