Пример #1
0
static int mod_instantiate(CONF_SECTION *conf, void *instance)
{
	struct rlm_realm_t *inst = instance;

	if (strcasecmp(inst->format_string, "suffix") == 0) {
		inst->format = REALM_FORMAT_SUFFIX;

	} else if (strcasecmp(inst->format_string, "prefix") == 0) {
		inst->format = REALM_FORMAT_PREFIX;

	} else {
		cf_log_err_cs(conf, "Invalid value \"%s\" for format",
			      inst->format_string);
		return -1;
	}

	if (strcmp(inst->delim, "\\\\") == 0) {
		/* it's OK */
	} else if (strlen(inst->delim) != 1) {
		cf_log_err_cs(conf, "Invalid value \"%s\" for delimiter",
			      inst->delim);
		return -1;
	}

#ifdef HAVE_TRUST_ROUTER_TR_DH_H
	/* initialize the trust router integration code */
	if (strcmp(inst->trust_router, "none") != 0) {
		if (!tr_init()) return -1;
	} else {
		rad_const_free(&inst->trust_router);
	}
#endif

	return 0;
}
Пример #2
0
tracking_run* trackcorr_c_init() {
    int step;
    tracking_run *ret;
    
    /* Remaining globals:
    see below for communication globals.
    */
    
    ret = (tracking_run *) malloc(sizeof(tracking_run));
    tr_init(ret, "parameters/sequence.par", "parameters/track.par",
        "parameters/criteria.par", "parameters/ptv.par");
    
    fb_init(ret->fb, 4, ret->cpar->num_cams, MAX_TARGETS, 
        "res/rt_is", "res/ptv_is", "res/added", ret->seq_par->img_base_name);

    /* Prime the buffer with first frames */
    for (step = ret->seq_par->first; step < ret->seq_par->first + 3; step++) {
        fb_read_frame_at_end(ret->fb, step, 0);
        fb_next(ret->fb);
    }
    fb_prev(ret->fb);
    
    ret->lmax = norm((ret->tpar->dvxmin - ret->tpar->dvxmax), \
        (ret->tpar->dvymin - ret->tpar->dvymax), \
        (ret->tpar->dvzmin - ret->tpar->dvzmax));
    volumedimension (glob_cal, &(ret->vpar->X_lay[1]), &(ret->vpar->X_lay[0]), &(ret->ymax), 
        &(ret->ymin), &(ret->vpar->Zmax_lay[1]), &(ret->vpar->Zmin_lay[0]), cpar);

    // Denis - globals below are used in trackcorr_finish
    npart=0;
    nlinks=0;
    
    return ret;
}
Пример #3
0
int main()
{
	int path[TR_MAX_DEPTH];
	struct tree *t = tr_init();
	struct generic_data d;

	d.val = 1;
	tr_insert_root(t, d);

	d.val = 2;
	path[0] = 1;
	tr_insert(t, d, path, 1);
		
	d.val = 3;
	path[0] = 0;
	tr_insert(t, d, path, 1);

	d.val = 4;
	path[0] = 0;
	path[1] = 1;
	tr_insert(t, d, path, 2);

	d.val = 5;
	path[0] = 0;
	path[1] = 1;
	path[2] = 1;
	tr_insert(t, d, path, 3);

	//tr_walk_df(t, print_data);
	tr_walk_bf(t, print_data);
	printf("Tree height: %d\n", tr_height(t, &t->root));

}
Пример #4
0
TestResult *tr_create(void)
{
  TestResult *tr;

  tr = emalloc (sizeof(TestResult));
  tr_init (tr);
  return tr;
}
Пример #5
0
int libbt_init(struct libbt_config *p_btcfg)
{
	engine =  tr_init( "stb" );
	tr_setBindPort(engine, p_btcfg->bindPort);
	tr_setGlobalUploadLimit(engine, p_btcfg->uploadLimit );
    tr_setGlobalDownloadLimit(engine, p_btcfg->downloadLimit );
    tr_natTraversalEnable(engine, p_btcfg->natTraversal );

	g_tor_array = (tr_torrent_t*)calloc(MAX_DOWNLOAD_NS, sizeof(tr_torrent_t*));
	
	return 0;
}
Пример #6
0
void
tr_table_initialize(struct tr_table *table, VALUE rbstring)
{
        const struct rb_u_string *string = RVAL2USTRING_ANY(rbstring);

        struct tr tr;
        tr_init(&tr, USTRING_STR(string), USTRING_END(string));

        table->exclude = tr_should_exclude(&tr);

        for (size_t i = 0; i < lengthof(table->continuous); i++)
                table->continuous[i] = true;

        table->sparse = Qnil;

        tr_table_add(table, string);
}
Пример #7
0
static void
tr_table_add(struct tr_table *table, const struct rb_u_string *string)
{
        struct tr tr;
        tr_init(&tr, USTRING_STR(string), USTRING_END(string));

        bool exclude = tr_should_exclude(&tr);

        bool buffer[lengthof(table->continuous)];

        for (size_t i = 0; i < lengthof(buffer); i++)
                buffer[i] = exclude;

        while (tr_next(&tr) != TR_FINISHED)
                tr_table_set(table, buffer, tr.now, !exclude);

        for (size_t i = 0; i < lengthof(table->continuous); i++)
                table->continuous[i] = table->continuous[i] && buffer[i];
}
Пример #8
0
// Programa principal
int main(void)
{
   	//Inicialitza el display LCD
   	LCDInit(LS_NONE);
     
   	//Neteja la pantalla
   	LCDClear();
    
   	//Inicialitza el comptador
   	freq_counter_init();

   	// inicialitza el mesurador de inductancia i capacitat
   	LC_init();

   	//inicialitza el mesurador de transistors
   	tr_init();

   	//inicialitza el mesurador de resistencia
   	r_init();

   	//inicialitza els polsadors i les interrupcions d'aquets
   	polsadors_init();

	
   	// inicialitza el menu del lcd
	menu_init();
   	while(1)
   	{
		if (flag_polsador == 1)
		{
			flag_polsador = 0;
    		menu(polsador);
		}
	}

   return 0;
}
Пример #9
0
int main()
{
    //-------------------------------------------------------
    // init, destroy tests 
    // test, where memory allocation is not successful
    
    root_t *root = tr_init();
    tr_destroy(root);
    tr_destroy(root);
    tr_destroy(NULL);
    
    //-------------------------------------------------------
    
    //-------------------------------------------------------
    // insert & delete & dump tests
    // test, where memory allocation is not successful
    
    root = tr_init();
    
    tr_insert(root, 0);
    tr_insert(root, 10);
    tr_insert(root, -10);
    tr_insert(root, 5);
    tr_insert(root, 15);
    tr_insert(root, 3);

    tr_delete(root, 13);
    tr_delete(root, 15);
    tr_delete(root, 0);

    tr_insert(root, 5);
    tr_insert(root, 6);
    tr_insert(root, 7);
    tr_insert(root, 8);
    tr_insert(root, 9);

    tr_fdump(root, stdout);

    tr_delete(root, 2);
    tr_delete(root, 7);
    tr_delete(root, 5);
    tr_delete(root, 6);
    tr_delete(root, 8);
    tr_delete(root, 9);

    tr_destroy(root);
    tr_insert(root, 0);
    tr_delete(root, 0);
    tr_insert(NULL, 0);
    tr_delete(NULL, 0);
    //-------------------------------------------------------

    //-------------------------------------------------------
    // height & elem & ok tests

    root = tr_init();

    tr_dump(root);

    tr_insert(root, 0);
    tr_elem(root, -1);
    tr_elem(root, 1);
    tr_elem(root, 0);


    tr_dump(NULL);
    tr_dump(root);
    tr_nok(root);
    tr_nok(NULL);

    tr_destroy(root);
    tr_elem(root, 0);
    tr_elem(NULL, 0);
     //-------------------------------------------------------
    

    //-------------------------------------------------------
    //iterator test 
    root = tr_init();
    tr_insert(root, 0);
    tr_insert(root, 10);
    tr_insert(root, -10);
    tr_insert(root, 5);
    tr_insert(root, 15);
    tr_insert(root, 3);


    int status;
    void *node = tr_itfirst(root, NULL);
    node = tr_itfirst(NULL, &status);
    node = tr_itfirst (NULL, NULL);
    node = tr_itfirst(root, &status);

    while (!tr_itislast(root, node, &status)) 
        node = tr_itnext (node);

    while (node != tr_itfirst(root, NULL)) 
        node = tr_itprev (node);


    node = tr_itleft(node);
    node = tr_itright(node);
    printf("%d\n", tr_itgetheight(node));
    printf("%d\n", tr_itgetkey(NULL, &status));

    printf("%d\n", tr_itgetkey(node, &status));

    tr_itleft(NULL);
    tr_itright(NULL);

    tr_itislast(NULL, node, NULL);
    tr_itnext (NULL);
    tr_itprev (NULL);



    tr_destroy(root);

    //-------------------------------------------------------
    return 0;
}            
Пример #10
0
int main(int argc, char **argv)
{
	if (argc > 1)
		while (++argv, --argc) {
			if (!strcmp("-c", argv[0]))
				color_on = 1;
			else if (!strcmp("-h", argv[0]))
				printf("liblisp unit tests\n\tusage ./%s (-c)? (-h)?\n", argv[0]);
			else
				printf("unknown argument '%s'\n", argv[0]);
		}

	unit_test_start("liblisp");
	{
		print_note("util.c");

		test(is_number("0xfAb"));
		test(is_number("-01234567"));
		test(is_number("+1000000000000000000000000000003"));
		test(!is_number(""));
		test(!is_number("+"));
		test(!is_number("-"));

		test(unbalanced("(((", '(', ')') > 0);
		test(unbalanced("))",  '(', ')') < 0);
		test(unbalanced("",    '(', ')') == 0);
		test(unbalanced("\"(", '(', ')') == 0);
		test(unbalanced("( \"))))(()()()(()\\\"())\")",  '(', ')') == 0);
		test(unbalanced("(a (b) c (d (e (f) \")\" g)))", '(', ')') == 0);
		test(unbalanced("((a b) c", '(', ')')  > 0);

		test(!is_fnumber(""));
		test(!is_fnumber("1e"));
		test(!is_fnumber("-1e"));
		test(!is_fnumber("1-e"));
		test(is_fnumber("+0."));
		test(is_fnumber("123"));	/*this passes, see header */
		test(is_fnumber("1e-3"));
		test(is_fnumber("1.003e+34"));
		test(is_fnumber("1e34"));
		test(is_fnumber("93.04"));

		test(match("", ""));
		test(match("abc", "abc"));
		test(!match("abC", "abc"));
		test(match("aaa*", "aaaXX"));
		test(!match("aaa*", "XXaaaXX"));
		test(match(".bc", "abc"));
		test(match("a.c", "aXc"));
		test(!match("a\\.c", "aXc"));
		test(match("a\\.c", "a.c"));

		char *s = NULL;
		state(s = vstrcatsep(",", "a", "b", "c", "", "foo", "bar", NULL));
		test(!sstrcmp("a,b,c,,foo,bar", s));
		free(s);

		char *t = NULL, *s1 = "Hello,", *s2 = " World!";
		state(t = calloc(16, 1));
		state(strcpy(t, s1));
		test(((size_t) (lstrcatend(t, s2) - t)) == (strlen(s1) + strlen(s2)));
		free(t);

		/*test tr, or translate, functionality */
		size_t trinsz = 0;
		uint8_t trout[128] = { 0 }, *trin = (uint8_t *) "aaabbbcdaacccdeeefxxxa";
		tr_state_t *tr1;
		state(tr1 = tr_new());
		state(trinsz = strlen((char *)trin));
		test(tr_init(tr1, "", (uint8_t *) "abc", (uint8_t *) "def") == TR_OK);
		test(tr_block(tr1, trin, trout, trinsz) == trinsz);
		test(!strcmp((char *)trout, "dddeeefdddfffdeeefxxxd"));
		test(tr_init(tr1, "s", (uint8_t *) "abc", (uint8_t *) "def") == TR_OK);
		state(memset(trout, 0, 128));
		test(tr_block(tr1, trin, trout, trinsz) <= trinsz);
		test(!strcmp((char *)trout, "defddfdeeefxxxd"));
		state(tr_delete(tr1));

		/*know collisions for the djb2 hash algorithm */
		test(djb2("heliotropes", strlen("heliotropes")) ==
		     djb2("neurospora", strlen("neurospora")));
		test(djb2("depravement", strlen("depravement")) ==
		     djb2("serafins", strlen("serafins")));
		/*should not collide */
		test(djb2("heliotropes", strlen("heliotropes")) !=
		     djb2("serafins", strlen("serafins")));
	}

	{ /*io.c test */
		io_t *in, *out;
		print_note("io.c");

		/*string input */
		static const char hello[] = "Hello\n";
		/**@note io_sin currently duplicates "hello" internally*/
		state(in = io_sin(hello, strlen(hello)));
		test(io_is_in(in));
		test(io_getc(in) == 'H');
		test(io_getc(in) == 'e');
		test(io_getc(in) == 'l');
		test(io_getc(in) == 'l');
		test(io_getc(in) == 'o');
		test(io_getc(in) == '\n');
		test(io_getc(in) == EOF);
		test(io_getc(in) == EOF);
		test(!io_error(in));
		test(io_seek(in, 0, SEEK_SET) >= 0);
		test(io_getc(in) == 'H');
		test(io_seek(in, 3, SEEK_SET) >= 0);
		test(io_getc(in) == 'l');
		test(io_ungetc('x', in) == 'x');
		test(io_getc(in) == 'x');
		test(io_getc(in) == 'o');
		state(io_close(in));

		/*string output */
		char *s = NULL;
		static const char hello_world[] = "Hello,\n\tWorld!\n";
		/**@note io_sin currently duplicates hello_world internally*/
		state(in = io_sin(hello_world, strlen(hello_world))); 
		test(!strcmp(s = io_getline(in), "Hello,"));
		s = (free(s), NULL);
		test(!strcmp(s = io_getline(in), "\tWorld!"));
		s = (free(s), NULL);
		test(!io_getline(in));
		test(io_seek(in, 0, SEEK_SET) >= 0);
		test(!strcmp(s = io_getdelim(in, EOF), "Hello,\n\tWorld!\n"));
		s = (free(s), NULL);
		state(io_close(in));

		state(out = io_sout(1));
		test(io_puts("Hello, World", out) != EOF);
		test(!strcmp("Hello, World", io_get_string(out)));
		test(io_putc('\n', out) != EOF);
		test(!strcmp("Hello, World\n", io_get_string(out)));
		test(io_seek(out, -6, SEEK_CUR) >= 0);
		test(io_puts("Mars\n", out) != EOF);
		test(!strcmp("Hello, Mars\n\n", io_get_string(out)));
		free(io_get_string(out));
		state(io_close(out));

		static const char block_in[16] = {1, 3, 4, 6};
		static char block_out[16] = {0};
		state((in = io_sin(block_in, 16)));
		test(io_getc(in) == 1);
		test(io_read(block_out, 15, in) == 15);
		test(!memcmp(block_out, block_in+1, 15));

		state(io_close(in));
	}

	{ /* hash.c hash table tests */
		hash_table_t *h = NULL;
		print_note("hash.c");
		state(h = hash_create(1));
		return_if(!h);
		test(!hash_insert(h, "key1", "val1"));
		test(!hash_insert(h, "key2", "val2"));
		/* assuming the hash algorithm is djb2, then
		 *  "heliotropes"  collides with "neurospora"
		 *  "depravement"  collides with "serafins"
		 *  "playwright"   collides with "snush" (for djb2a)
		 * See:
		 * <https://programmers.stackexchange.com/questions/49550/which-hashing-algorithm-is-best-for-uniqueness-and-speed> */
		test(!hash_insert(h, "heliotropes", "val3"));
		test(!hash_insert(h, "neurospora", "val4"));
		test(!hash_insert(h, "depravement", "val5"));
		test(!hash_insert(h, "serafins", "val6"));
		test(!hash_insert(h, "playwright", "val7"));
		test(!hash_insert(h, "snush", "val8"));
		test(!hash_insert(h, "", "val9"));
		test(!hash_insert(h, "nil", ""));
		test(!hash_insert(h, "a", "x"));
		test(!hash_insert(h, "a", "y"));
		test(!hash_insert(h, "a", "z"));
		test(!sstrcmp("val1", hash_lookup(h, "key1")));
		test(!sstrcmp("val2", hash_lookup(h, "key2")));
		test(!sstrcmp("val3", hash_lookup(h, "heliotropes")));
		test(!sstrcmp("val4", hash_lookup(h, "neurospora")));
		test(!sstrcmp("val5", hash_lookup(h, "depravement")));
		test(!sstrcmp("val6", hash_lookup(h, "serafins")));
		test(!sstrcmp("val7", hash_lookup(h, "playwright")));
		test(!sstrcmp("val8", hash_lookup(h, "snush")));
		test(!sstrcmp("val9", hash_lookup(h, "")));
		test(!sstrcmp("", hash_lookup(h, "nil")));
		test(!sstrcmp("z", hash_lookup(h, "a")));
		test(hash_get_load_factor(h) <= 0.75f);

		state(hash_destroy(h));
	}

	{			/* lisp.c (and the lisp interpreter in general) */
		lisp_t *l;

		print_note("lisp.c");
		/*while unit testing eschews state being held across tests it is makes
		 *little sense in this case*/
		state(l = lisp_init());
		state(io_close(lisp_get_logging(l)));
		test(!lisp_set_logging(l, io_nout()));
		return_if(!l);
		test(!lisp_eval_string(l, ""));
		test(is_int(lisp_eval_string(l, "2")));
		test(get_int(lisp_eval_string(l, "(+ 2 2)")) == 4);
		test(get_int(lisp_eval_string(l, "(* 3 2)")) == 6);

		lisp_cell_t *x = NULL, *y = NULL, *z = NULL;
		char *t = NULL;
		state(x = lisp_intern(l, lstrdup_or_abort("foo")));
		state(y = lisp_intern(l, t = lstrdup_or_abort("foo")));	/*this one needs freeing! */
		state(z = lisp_intern(l, lstrdup_or_abort("bar")));
		test(x == y && x != NULL);
		test(x != z);
		free(t);	/*free the non-interned string */

		test(is_proc(lisp_eval_string(l, "(define square (lambda (x) (* x x)))")));
		test(get_int(lisp_eval_string(l, "(square 4)")) == 16);

		test(!is_list(cons(l, gsym_tee(), gsym_tee())));
		test(is_list(cons(l, gsym_tee(), gsym_nil())));
		test(!is_list(cons(l, gsym_nil(), cons(l, gsym_tee(), gsym_tee()))));
		test(is_list(mk_list(l, gsym_tee(), gsym_nil(), gsym_tee(), NULL)));

		test(gsym_error() == lisp_eval_string(l, "(> 'a 1)"));
		test(is_sym(x));
		test(is_asciiz(x));
		test(!is_str(x));
		test(gsym_error() == lisp_eval_string(l, "(eval (cons quote 0))"));

		char *serial = NULL;
		test(!strcmp((serial = lisp_serialize(l, cons(l, gsym_tee(), gsym_error()))), "(t . error)"));
		state(free(serial));

		state(lisp_destroy(l));
	}
	return unit_test_end("liblisp");	/*should be zero! */
}
Пример #11
0
/*******************************************************************************
 * main
 ******************************************************************************/
int main(int argc, char ** argv) {

	/* vars */
	int i, error, nat;
	tr_handle_t * h;
	tr_torrent_t * tor;
	tr_stat_t * s;
	double tf_sharing = 0.0;
	char tf_string[80];
	int tf_seeders, tf_leechers;

	/* Get options */
	if (parseCommandLine(argc, argv)) {
		printf("Transmission %s [%d] - tfCLI [%d]\nhttp://transmission.m0k.org/ - http://tf-b4rt.berlios.de/\n\n",
			VERSION_STRING, VERSION_REVISION, VERSION_REVISION_CLI);
		printf(USAGE, argv[0], TR_DEFAULT_PORT);
		return 1;
	}

	/* show help */
	if (showHelp) {
		printf("Transmission %s [%d] - tfCLI [%d]\nhttp://transmission.m0k.org/ - http://tf-b4rt.berlios.de/\n\n",
			VERSION_STRING, VERSION_REVISION, VERSION_REVISION_CLI);
		printf(USAGE, argv[0], TR_DEFAULT_PORT);
		return 0;
	}

	// verbose
	if (verboseLevel < 0) {
		verboseLevel = 0;
	} else if (verboseLevel > 9) {
		verboseLevel = 9;
	}
	if (verboseLevel) {
		static char env[11];
		sprintf(env, "TR_DEBUG=%d", verboseLevel);
		putenv(env);
	}

	// check port
	if (bindPort < 1 || bindPort > 65535) {
		printf("Invalid port '%d'\n", bindPort);
		return 1;
	}

	// Initialize libtransmission
	h = tr_init();

	// Open and parse torrent file
	if (!(tor = tr_torrentInit(h, torrentPath, 0, &error))) {
		printf("Failed opening torrent file `%s'\n", torrentPath);
		goto failed;
	}

	/* show info */
	if (showInfo) {
		// info
		tr_info_t * info = tr_torrentInfo(tor);
		// stat
		s = tr_torrentStat(tor);
		// Print torrent info (quite à la btshowmetainfo)
		printf("hash:     ");
		for (i = 0; i < SHA_DIGEST_LENGTH; i++) {
			printf("%02x", info->hash[i]);
		}
		printf("\n");
        printf( "tracker:  %s:%d\n",
                s->trackerAddress, s->trackerPort );
        printf( "announce: %s\n", s->trackerAnnounce );
		printf("size:     %"PRIu64" (%"PRIu64" * %d + %"PRIu64")\n",
			info->totalSize, info->totalSize / info->pieceSize,
			info->pieceSize, info->totalSize % info->pieceSize);
		if (info->comment[0]) {
			printf("comment:  %s\n", info->comment);
		}
		if (info->creator[0]) {
			printf("creator:  %s\n", info->creator);
		}
		printf("file(s):\n");
		for (i = 0; i < info->fileCount; i++) {
			printf(" %s (%"PRIu64")\n", info->files[i].name,
				info->files[i].length);
		}
		// cleanup
		goto cleanup;
	}

	/* show scrape */
	if (showScrape) {
		int seeders, leechers, downloaded;
		if (tr_torrentScrape(tor, &seeders, &leechers, &downloaded)) {
			printf("Scrape failed.\n");
		} else {
			printf("%d seeder(s), %d leecher(s), %d download(s).\n",
					seeders, leechers, downloaded);
		}
		// cleanup
		goto cleanup;
	}

	/* start up transmission */

	// Create PID file if wanted by user
	if (tf_pid != NULL) {
		FILE * pid_file;
		pid_file = fopen(tf_pid, "w+");
		if (pid_file != NULL) {
			fprintf(pid_file, "%d", getpid());
			fclose(pid_file);
		}
	}

	// signal
	signal(SIGINT, sigHandler);

	// If running torrentflux, Download limit = 0 means no limit
	if (tf_stat_file != NULL) { /* tfCLI */
		// up
		switch (uploadLimit) {
			case 0:
				uploadLimit = -1;
				break;
			case -2:
				uploadLimit = 0;
				break;
		}
		// down
		switch (downloadLimit) {
			case 0:
				downloadLimit = -1;
				break;
			case -2:
				downloadLimit = 0;
				break;
		}
	}

	// init some things
	tr_setBindPort(h, bindPort);
	tr_setGlobalUploadLimit(h, uploadLimit);
	tr_setGlobalDownloadLimit(h, downloadLimit);

	// nat-traversal
	if (natTraversal) {
		tr_natTraversalEnable(h);
	} else {
		tr_natTraversalDisable(h);
	}

	// set folder
	tr_torrentSetFolder(tor, ".");

	// start the torrent
	tr_torrentStart(tor);

	/* main-loop */
	while (!mustDie) {

		// status-string
		char string[80];
		int chars = 0;
		//
		int result;
		char stat_state;

		// sleep
		sleep(displayInterval);

		// Check if we must stop
		if (tf_stat_file != NULL) { /* tfCLI */
			tf_stat = fopen(tf_stat_file, "r");
			if (tf_stat != NULL) {
				// Get state
				stat_state = fgetc(tf_stat);
				// Close the file
				fclose(tf_stat);
				// Torrentflux asked to shutdown the torrent
				if (stat_state == '0') {
					mustDie = 1;
				}
			}
		}

		// torrent-stat
		s = tr_torrentStat(tor);

		if (s->status & TR_STATUS_CHECK) { /* --- CHECK --- */

			if (tf_stat_file == NULL) { /* standalone */

				// status-string
				chars = snprintf(string, 80,
					"Checking files... %.2f %%", 100.0 * s->progress );

			} else { /* tfCLI */

				// write tf-stat-file
				tr_info_t * info = tr_torrentInfo(tor);
				tf_stat = fopen(tf_stat_file, "w+");
				if (tf_stat != NULL) {
					fprintf(tf_stat, "%d\n%.1f\n%s\n0 kB/s\n0 kB/s\n%s\n0\n0\n0.0\n%d\n0\n%" PRIu64 "\n%" PRIu64,
						1,                          /* State             */
						100.0 * s->progress,        /* checking progress */
						"Checking existing data",   /* State text        */
						                            /* download speed    */
						                            /* upload speed      */
						tf_user,                    /* user              */
						                            /* seeds             */
						                            /* peers             */
						                            /* sharing           */
						seedLimit,                  /* seedlimit         */
						                            /* uploaded bytes    */
						s->downloaded,              /* downloaded bytes  */
						info->totalSize);           /* global size       */
					fclose(tf_stat);
				}

			}

		} else if (s->status & TR_STATUS_DOWNLOAD) { /* --- DOWNLOAD --- */

			if (tf_stat_file == NULL) { /* standalone */

				// status-string
				chars = snprintf(string, 80,
					"Progress: %.2f %%, %d peer%s, dl from %d (%.2f KB/s), "
					"ul to %d (%.2f KB/s)", 100.0 * s->progress,
					s->peersTotal, ( s->peersTotal == 1 ) ? "" : "s",
					s->peersUploading, s->rateDownload,
					s->peersDownloading, s->rateUpload);

			} else { /* tfCLI */

				// sharing
				if (s->downloaded != 0) {
					tf_sharing =
						((double)(s->uploaded) / (double)(s->downloaded)) * 100;
				}

				// seeders + leechers
				if (s->seeders < 0) {
					tf_seeders = 0;
				} else {
					tf_seeders = s->seeders;
				}
				if (s->leechers < 0) {
					tf_leechers = 0;
				} else {
					tf_leechers = s->leechers;
				}

				// eta
				if (s->eta != -1) {
					// sanity-check. value of eta >= 7 days is not really of use
					if (s->eta < 604800) {
						if ((s->eta / (24 * 60 * 60)) != 0) {
							sprintf(tf_string,"%d:%02d:%02d:%02d",
								s->eta / (24 * 60 * 60),
								((s->eta) % (24 * 60 * 60)) / (60 * 60),
								((s->eta) % (60 * 60) / 60),
								s->eta % 60);
						} else if ((s->eta / (60 * 60)) != 0) {
							sprintf(tf_string, "%d:%02d:%02d",
								(s->eta) / (60 * 60),
								((s->eta) % (60 * 60) / 60),
								s->eta % 60);
						} else {
							sprintf(tf_string, "%d:%02d",
								(s->eta) / 60, s->eta % 60);
						}
					} else {
						sprintf(tf_string,"-");
					}
				} else {
					sprintf(tf_string,"-");
				}
				if ((s->seeders == -1) && (s->peersTotal == 0)) {
					sprintf(tf_string,"Connecting to Peers");
				}

				// write tf-stat-file
				tf_stat = fopen(tf_stat_file, "w+");
				if (tf_stat != NULL) {
					tr_info_t * info = tr_torrentInfo( tor );
					fprintf(tf_stat, "%d\n%.1f\n%s\n%.1f kB/s\n%.1f kB/s\n%s\n%d (%d)\n%d (%d)\n%.1f\n%d\n%" PRIu64 "\n%" PRIu64 "\n%" PRIu64,
						1,                                /* State            */
						100.0 * s->progress,              /* progress         */
						tf_string,                        /* Estimated time   */
						s->rateDownload,                  /* download speed   */
						s->rateUpload,                    /* upload speed     */
						tf_user,                          /* user             */
						s->peersUploading, tf_seeders,    /* seeds            */
						s->peersDownloading, tf_leechers, /* peers            */
						tf_sharing,                       /* sharing          */
						seedLimit,                        /* seedlimit        */
						s->uploaded,                      /* uploaded bytes   */
						s->downloaded,                    /* downloaded bytes */
						info->totalSize);                 /* global size      */
					fclose(tf_stat);
				}
			}

		} else if (s->status & TR_STATUS_SEED) { /* --- SEED --- */

			// info
			tr_info_t * info = tr_torrentInfo(tor);

			if (tf_stat_file == NULL) { /* standalone */

				// status-string
				chars = snprintf(string, 80,
					"Seeding, uploading to %d of %d peer(s), %.2f KB/s",
					s->peersDownloading, s->peersTotal,
					s->rateUpload);

			} else { /* tfCLI */

				// sharing
				if (s->downloaded != 0) {
					tf_sharing =
						((double)(s->uploaded) /
							(double)(s->downloaded)) * 100;
				} else {
					tf_sharing =
						((double)(s->uploaded) /
							(double)(info->totalSize)) * 100;
				}

				// If we reached the seeding limit, we have to quit transmission
				if ((seedLimit != 0) &&
					((tf_sharing > (double)(seedLimit)) ||
					(seedLimit == -1))) {
					mustDie = 1;
				}

				// seeders + leechers
				if (s->seeders < 0) {
					tf_seeders = 0;
				} else {
					tf_seeders = s->seeders;
				}
				if (s->leechers < 0) {
					tf_leechers = 0;
				} else {
					tf_leechers = s->leechers;
				}

				// write tf-stat-file
				tf_stat = fopen(tf_stat_file, "w+");
				if (tf_stat != NULL) {
					fprintf(tf_stat, "%d\n%.1f\n%s\n%.1f kB/s\n%.1f kB/s\n%s\n%d (%d)\n%d (%d)\n%.1f\n%d\n%" PRIu64 "\n%" PRIu64 "\n%" PRIu64,
						1,                                /* State            */
						100.0 * s->progress,              /* progress         */
						"Download Succeeded!",            /* State text       */
						s->rateDownload,                  /* download speed   */
						s->rateUpload,                    /* upload speed     */
						tf_user,                          /* user             */
						s->peersUploading, tf_seeders,    /* seeds            */
						s->peersDownloading, tf_leechers, /* peers            */
						tf_sharing,                       /* sharing          */
						seedLimit,                        /* seedlimit        */
						s->uploaded,                      /* uploaded bytes   */
						s->downloaded,                    /* downloaded bytes */
						info->totalSize);                 /* global size      */
					fclose(tf_stat);
				}
			}

		}

		// status-string
		if (tf_stat_file == NULL) { /* standalone */
			memset( &string[chars], ' ', 79 - chars );
			string[79] = '\0';
			// print status to stderr
			fprintf(stderr, "\r%s", string);
		}

		// errors
		if (s->error & TR_ETRACKER) {
			if (tf_stat_file == NULL) { /* standalone */
				// print errors to stderr
				fprintf(stderr, "\n%s\n", s->trackerError);
			} else { /* tfCLI */
				// append errors to stat-file
				tf_stat = fopen(tf_stat_file, "a+");
				if (tf_stat != NULL) {
					fprintf(tf_stat, "\n%s\n", s->trackerError);
					fclose(tf_stat);
				}
			}
		} else if (verboseLevel > 0) {
			if (tf_stat_file == NULL) { /* standalone */
				// stderr
				fprintf(stderr, "\n");
			}
		}

		// finishCall
		if (tr_getFinished(tor)) {
			result = system(finishCall);
		}

	} /* main-loop */

	// mark torrent as stopped in tf-stat-file
	if (tf_stat_file != NULL) { /* tfCLI */

		// info
		tr_info_t * info = tr_torrentInfo(tor);

		// sharing
		if (s->downloaded != 0) {
			tf_sharing =
				((double)(s->uploaded) / (double)(s->downloaded)) * 100;
		} else {
			tf_sharing =
				((double)(s->uploaded) / (double)(info->totalSize)) * 100;
		}

		// write tf-stat-file
		tf_stat = fopen(tf_stat_file, "w+");
		if (tf_stat != NULL) {
			float progress;
			if (s->status & TR_STATUS_SEED) {
				sprintf(tf_string,"Download Succeeded!");
				progress = 100;
			} else {
				sprintf(tf_string,"Torrent Stopped");
				progress = -(1 + s->progress) * 100;
			}
			fprintf(tf_stat, "%d\n%.1f\n%s\n\n\n%s\n\n\n%.1f\n%d\n%" PRIu64 "\n%" PRIu64 "\n%" PRIu64,
				0,                          /* State            */
				progress,                   /* progress         */
				tf_string,                  /* State text       */
				                            /* download speed   */
				                            /* upload speed     */
				tf_user,                    /* user             */
				                            /* seeds            */
				                            /* peers            */
				tf_sharing,                 /* sharing          */
				seedLimit,                  /* seedlimit        */
				s->uploaded,                /* uploaded bytes   */
				s->downloaded,              /* downloaded bytes */
				info->totalSize);           /* global size      */
			fclose(tf_stat);
		}
	}

	// stderr
	if (tf_stat_file == NULL) { /* standalone */
		fprintf(stderr, "\n");
	}

	// Try for 5 seconds to notify the tracker that we are leaving
	// and to delete any port mappings for nat traversal
	tr_torrentStop(tor);
	tr_natTraversalDisable(h);
	for (i = 0; i < 10; i++) {
		s = tr_torrentStat(tor);
		nat = tr_natTraversalStatus(h);
		if (s->status & TR_STATUS_PAUSE && TR_NAT_TRAVERSAL_DISABLED == nat) {
			// The 'stopped' tracker message was sent
			// and port mappings were deleted
			break;
		}
		usleep(500000);
	}

	// Remove PID file if created !
	if (tf_pid != NULL) {
		remove(tf_pid);
	}

cleanup:
	tr_torrentClose(h, tor);

failed:
	tr_close(h);

	return 0;
}
Пример #12
0
/**************************************************************************
* The main function.
**************************************************************************/
int main(int argc, char** argv)
{
  DBState dbState;
  char *m_paramfile, *m_instfile, *m_timefile, *m_resfile;
  pca_timer_t timer;
  PcaCArrayFloat timing;
  uint i = 0;
  float timeSum = 0.0;

  /* check arguments */
  if (argc < 2) {
    fprintf(stderr, "Usage: %s [dataset idx]\n", argv[0]);
    exit(-1);
  }
    
  /* initialize memory managers */
#ifdef VERBOSE
#ifdef PCA_DB_MEM
  printf("Using custom memory management.\n");
#else
  printf("Using standard malloc/free.\n");
#endif
#endif
  ll_init(NUM_LL_BLOCKS);
  rb_init(NUM_RB_BLOCKS);
  tr_init(NUM_TR_BLOCKS);

  /* load up db state and create timing array */
  m_paramfile = (char*) malloc(strlen("data/") + strlen(argv[1]) + 
			       strlen("-db-param.dat") + 1);
  m_instfile = (char*)  malloc(strlen("data/") + strlen(argv[1]) + 
			       strlen("-db-inst.dat") + 1);
  sprintf(m_paramfile, "data/%s-db-param.dat", argv[1]);
  sprintf(m_instfile, "data/%s-db-inst.dat", argv[1]);
  DBState_load(&dbState, m_paramfile, m_instfile);
  pca_create_carray_1d(float, timing, dbState.num_cycles, PCA_REAL);

  /* run the database */
#ifdef VERBOSE
  printf("Running with %d total record(s)... ", dbState.total_records);
#endif
  while (dbState.p_currcmd < dbState.p_lastcmd) {
    timer = startTimer();
    runDatabase(&dbState);
    timing.data[i++] = stopTimer(timer);
    timeSum = timeSum + timing.data[i-1];
  }
  printf("Done.  Latency: %f s.\n", timeSum/((float)dbState.num_cycles));

  /* output timings */
  m_timefile = (char*) malloc(strlen("data/") + strlen(argv[1]) +
			      strlen("-db-timing.dat") + 1);
  sprintf(m_timefile, "data/%s-db-timing.dat", argv[1]);
  writeToFile(float, m_timefile, timing);
  clean_mem(float, timing);

  /* output results of database */
  m_resfile = (char*) malloc(strlen("data/") + strlen(argv[1]) +
			     strlen("-db-results.dat") + 1);
  sprintf(m_resfile, "data/%s-db-results.dat", argv[1]);
  writeToFile(int, m_resfile, dbState.sresults);

  /* cleanup */ 
  free(m_paramfile);
  free(m_instfile);
  free(m_timefile);
  free(m_resfile);
  DBState_clean(&dbState);
  ll_clean();
  rb_clean();
  tr_clean();

  return 0;
}
Пример #13
0
void tr_reset(TestResult *tr)
{
  tr_init(tr);
}