Beispiel #1
0
static void test_iostream_temp_create_write_error(void)
{
	struct ostream *output;

	test_begin("iostream_temp_create_sized() write error");
	output = iostream_temp_create_sized(".", 0, "test", 1);

	test_assert(o_stream_send(output, "123", 3) == 3);
	test_assert(o_stream_get_fd(output) != -1);
	test_assert(output->offset == 3);
	test_assert(o_stream_temp_move_to_memory(output) == 0);
	test_assert(o_stream_get_fd(output) == -1);
	test_assert(o_stream_send(output, "45", 2) == 2);
	test_assert(output->offset == 5);

	const unsigned char *data;
	size_t size;
	struct istream *input = iostream_temp_finish(&output, 128);
	test_assert(i_stream_read_bytes(input, &data, &size, 5) == 1 &&
		    memcmp(data, "12345", 5) == 0);
	i_stream_destroy(&input);

	test_end();
}
Beispiel #2
0
static void test_p_strarray_dup(void)
{
	const char *input[][3] = {
		{ NULL },
		{ "a", NULL },
		{ "foobar", NULL },
		{ "a", "foo", NULL }
	};
	const char **ret;
	unsigned int i, j;

	test_begin("p_strarray_dup");

	for (i = 0; i < N_ELEMENTS(input); i++) {
		ret = p_strarray_dup(default_pool, input[i]);
		for (j = 0; input[i][j] != NULL; j++) {
			test_assert(strcmp(input[i][j], ret[j]) == 0);
			test_assert(input[i][j] != ret[j]);
		}
		test_assert(ret[j] == NULL);
		i_free(ret);
	}
	test_end();
}
Beispiel #3
0
static void test_base64_random(void)
{
	string_t *str, *dest;
	char buf[10];
	unsigned int i, j, max;

	str = t_str_new(256);
	dest = t_str_new(256);

	test_begin("base64 encode/decode with random input");
	for (i = 0; i < 1000; i++) {
		max = rand() % sizeof(buf);
		for (j = 0; j < max; j++)
			buf[j] = rand();

		str_truncate(str, 0);
		str_truncate(dest, 0);
		base64_encode(buf, max, str);
		base64_decode(str_data(str), str_len(str), NULL, dest);
		test_assert(str_len(dest) == max &&
			    memcmp(buf, str_data(dest), max) == 0);
	}
	test_end();
}
Beispiel #4
0
static void test_base64_encode(void)
{
	static const char *input[] = {
		"hello world",
		"foo barits",
		"just niin"
	};
	static const char *output[] = {
		"aGVsbG8gd29ybGQ=",
		"Zm9vIGJhcml0cw==",
		"anVzdCBuaWlu"
	};
	string_t *str;
	unsigned int i;

	test_begin("base64_encode()");
	str = t_str_new(256);
	for (i = 0; i < N_ELEMENTS(input); i++) {
		str_truncate(str, 0);
		base64_encode(input[i], strlen(input[i]), str);
		test_assert(strcmp(output[i], str_c(str)) == 0);
	}
	test_end();
}
Beispiel #5
0
int main()
{
    begin_test_data(expected_t)
        test_data(                                        "nothing to skip!",  0, test_pair(1,1), PDS_OK ),
        test_data(                                          "\t    \r\n end",  8, test_pair(1,2), PDS_OK ),
        test_data(                                                "/**/ end",  5, test_pair(1,1), PDS_OK ),
        test_data(                   "/* a\tlonger\tcomment */\t\r\n\r\nend", 27, test_pair(1,3), PDS_OK ),
        test_data("  \t/*line 1 */\n \t\t/*line 2*/\n \t\t\t/*line 3*/\nend", 44, test_pair(1,4), PDS_OK ),
        test_data(                               "  /* /* nested comment */",  5, test_pair(0,1), PDS_INVALID_VALUE ),
        test_data(                            "  /* muti-line \n comment */", 15, test_pair(0,1), PDS_INVALID_VALUE ),
    end_test_data()

    PDS_parser parser;
    memset(&parser, 0, sizeof(PDS_parser));
    PDS_set_error_callback(&parser.callbacks, dummy_error);

    size_t i;
    test_foreach(i)
    {
        parser.line_num = 1;
        parser.first    = test_str(i);
        parser.current  = parser.first;
        parser.last     = parser.first + strlen(parser.first) - 1;
        parser.status   = PDS_OK;
        int ret;
        
        ret = PDS_skip_whitespaces(&parser);
        
        check(test_status(i) == parser.status); 
        check(test_end(i) == parser.current);   
        check(test_expected(i).ret == ret); 
        check(test_expected(i).line == parser.line_num);    
    }

    return EXIT_SUCCESS;
}
Beispiel #6
0
static void test_str_append_n(void)
{
	string_t *str = t_str_new(32);

	test_begin("str_append_n()");
	str_append_n(str, "foo", 0);
	test_assert(str->used == 0);

	str_append_n(str, "\0foo", 4);
	test_assert(str->used == 0);

	str_append_n(str, "foo", 3);
	test_assert(str->used == 3 && memcmp(str_data(str), "foo", 3) == 0);
	str_truncate(str, 0);

	str_append_n(str, "foo", 2);
	test_assert(str->used == 2 && memcmp(str_data(str), "fo", 2) == 0);
	str_truncate(str, 0);

	str_append_n(str, "foo\0bar", 7);
	test_assert(str->used == 3 && memcmp(str_data(str), "foo", 3) == 0);
	str_truncate(str, 0);
	test_end();
}
Beispiel #7
0
static void test_hex_to_binary(void)
{
	static const char *ok_input = "0001fEFf";
	static unsigned char ok_output[] = { 0x00, 0x01, 0xfe, 0xff };
	static const char *error_input[] = {
		"00 01",
		"0x01",
		"0g"
	};
	buffer_t *buf = buffer_create_dynamic(pool_datastack_create(), 10);
	unsigned int i;

	test_begin("hex to binary");
	test_assert(hex_to_binary("", buf) == 0);
	test_assert(buf->used == 0);

	test_assert(hex_to_binary(ok_input, buf) == 0);
	test_assert(buf->used == N_ELEMENTS(ok_output));
	test_assert(memcmp(buf->data, ok_output, buf->used) == 0);

	for (i = 0; i < N_ELEMENTS(error_input); i++)
		test_assert(hex_to_binary(error_input[i], buf) == -1);
	test_end();
}
static void test_dsync_proxy_box_update(void)
{
	struct test_dsync_box_event event;

	test_begin("proxy server box update");

	test_assert(run_cmd("BOX-UPDATE", "updated", "/",
			    "53", "2", TEST_MAILBOX_GUID1, "34343", "22",
			    "58293", "2238427847284728", "2482", NULL) == 1);
	test_assert(test_dsync_worker_next_box_event(test_worker, &event));
	test_assert(event.type == LAST_BOX_TYPE_UPDATE);
	test_assert(strcmp(event.box.name, "updated") == 0);
	test_assert(event.box.name_sep == '/');
	test_assert(memcmp(event.box.mailbox_guid.guid, test_mailbox_guid1, MAIL_GUID_128_SIZE) == 0);
	test_assert(event.box.flags == DSYNC_MAILBOX_FLAG_DELETED_MAILBOX);
	test_assert(event.box.uid_validity == 34343);
	test_assert(event.box.uid_next == 22);
	test_assert(event.box.message_count == 58293);
	test_assert(event.box.highest_modseq == 2238427847284728);
	test_assert(event.box.first_recent_uid == 2482);
	test_assert(event.box.last_change == 53);

	test_end();
}
static void test_ds_realloc()
{
	test_begin("data-stack realloc");
	T_BEGIN {
		size_t i;
		unsigned char *p;
		size_t left = t_get_bytes_available();
		while (left < 10000) {
			t_malloc_no0(left); /* force a new block */
			left = t_get_bytes_available();
		}
		left -= 64; /* make room for the sentry if DEBUG */
		p = t_malloc_no0(1);
		p[0] = 1;
		for (i = 2; i <= left; i++) {
			/* grow it */
			test_assert_idx(t_try_realloc(p, i), i);
			p[i-1] = i;
			test_assert_idx(p[i-2] == (unsigned char)(i-1), i);
		}
		test_assert(t_get_bytes_available() < 64 + MEM_ALIGN(1));
	} T_END;
	test_end();
}
Beispiel #10
0
/*
static void
test_delete_content_property(gs_grid_storage_t * gs)
{
	gs_error_t **err = NULL;
	gchar **result = NULL;

	char *nameRef = test_init(gs, "Ref_linked", NULL);
	char *nameCont = gen_random(7);
	gs_container_t *container = container_init(gs, nameCont);

	hc_ul_content_from_file(gs, nameCont, "Content", "file_test.txt", err);
	gs_content_t *nameContent =
		gs_get_content_from_path(container, "Content", err);

	char *props[] = { "key1=value1", "key2=value2", NULL };
	char *propDel[] = { "key1", NULL };
	hc_set_content_property(nameContent, props, err);

	hc_delete_content_property(nameContent, propDel, err);
	g_assert_true(err == NULL);

	hc_get_content_properties(nameContent, &result, err);
	g_assert_true(err == NULL);
	if (result == NULL)
		g_test_fail();
	else
		g_assert_true(strcmp(result[0], "key2=value2") == 0);

	gs_content_free(nameContent);
	test_end(gs, nameRef, container);
}
*/
static void
test_copy_content(gs_grid_storage_t * gs)
{
	gs_error_t **err = NULL;

	char *nameRef = test_init(gs, "Ref_linked", NULL);
	char *nameCont = gen_random(7);
	gs_container_t *container = container_init(gs, nameCont);

	hc_ul_content_from_file(gs, nameCont, "Content", "file_test.txt", err);
	gs_content_t *nameContent =
		gs_get_content_from_path(container, "Content", err);

	hc_copy_content(container, "Content", "Content_copy", err);
	g_assert_true(err == NULL);

	gs_content_t *nameContent2 =
		gs_get_content_from_path(container, "Content_copy", err);
	g_assert_true(nameContent != NULL);

	gs_content_free(nameContent);
	gs_content_free(nameContent2);
	test_end(gs, nameRef, container);
}
Beispiel #11
0
static void
test_set_content_property_wrong(gs_grid_storage_t * gs)	// to be improved
{
	gs_error_t **err = NULL;
	gchar **result = NULL;

	char *nameRef = test_init(gs, "Ref_linked", NULL);
	char *nameCont = gen_random(7);
	gs_container_t *container = container_init(gs, nameCont);

	hc_ul_content_from_file(gs, nameCont, "Content", "file_test.txt", err);
	gs_content_t *content = gs_get_content_from_path(container, "Content", err);

	char *props[] = { "wrong_property" };

	hc_set_content_property(content, props, err);
	if (err == NULL)
		g_test_fail();

	hc_get_content_properties(content, &result, err);

	gs_content_free(content);
	test_end(gs, nameRef, container);
}
Beispiel #12
0
static void test_tco_second_timeout_none(void)
{
    TestData td;
    const uint16_t ticks = TCO_SECS_TO_TICKS(256);
    QDict *ad;

    td.args = "-watchdog-action none";
    td.noreboot = false;
    test_init(&td);

    stop_tco(&td);
    clear_tco_status(&td);
    reset_on_second_timeout(true);
    set_tco_timeout(&td, ticks);
    load_tco(&td);
    start_tco(&td);
    clock_step(ticks * TCO_TICK_NSEC * 2);
    ad = get_watchdog_action();
    g_assert(!strcmp(qdict_get_str(ad, "action"), "none"));
    qobject_unref(ad);

    stop_tco(&td);
    test_end(&td);
}
Beispiel #13
0
static void
test_run (void)
{
  FlowIPResolver *ip_resolver;
  gint            i;

  ip_resolver = flow_ip_resolver_new ();

  for (i = 0; resolve_names [i]; i++)
  {
    flow_ip_resolver_resolve_name (ip_resolver, resolve_names [i],
                                   (FlowIPLookupFunc *) resolved, ip_resolver);
  }

  to_resolve = i;

  for (i = 0; resolve_addrs [i]; i++)
  {
    FlowIPAddr *ip_addr;

    ip_addr = flow_ip_addr_new ();
    if (!flow_ip_addr_set_string (ip_addr, resolve_addrs [i]))
      test_end (TEST_RESULT_FAILED, "IP address parser failed");

    flow_ip_resolver_resolve_ip_addr (ip_resolver, ip_addr,
                                      (FlowIPLookupFunc *) resolved, ip_resolver);

    g_object_unref (ip_addr);
  }

  to_resolve += i;

  test_run_main_loop ();

  g_object_unref (ip_resolver);
}
static void test_imap_bodystructure_parse(void)
{
	struct message_part *parts;
	const char *error;
	string_t *str = t_str_new(128);
	pool_t pool = pool_alloconly_create("imap bodystructure parse", 1024);

	test_begin("imap bodystructure parser");
	parts = msg_parse(pool, FALSE);

	test_assert(imap_body_parse_from_bodystructure(testmsg_bodystructure,
						       str, &error) == 0);
	test_assert(strcmp(str_c(str), testmsg_body) == 0);

	test_assert(imap_bodystructure_parse(testmsg_bodystructure,
					     pool, parts, &error) == 0);

	str_truncate(str, 0);
	imap_bodystructure_write(parts, str, TRUE);
	test_assert(strcmp(str_c(str), testmsg_bodystructure) == 0);

	pool_unref(&pool);
	test_end();
}
Beispiel #15
0
int main(void)
{
	struct timeval t;
	int r;
	long i;

	// sanity check
	r = gettimeofday(&t, NULL);
	if (r < 0) {
		printf("error with gettimeofday! (%i)\n", r);
		exit(1);
	} else {
		/* printf("time is: %s", ctime(&t.tv_sec)); */
		/* printf("time as int is: %lius\n", t.tv_sec * 1000000 + t.tv_usec); */
	}

	test_start();
	for (i = 0; i < N; i++) {
		gettimeofday(&t, NULL);
	}
	test_end();

	return 0;
}
Beispiel #16
0
int main(int argc, char **argv)
{
    int err;
    pthread_t *tid_enqueuer, *tid_dequeuer;
    void *tret;
    unsigned long long *count_enqueuer, *count_dequeuer;
    unsigned long long tot_enqueues = 0, tot_dequeues = 0;
    unsigned long long tot_successful_enqueues = 0,
                       tot_successful_dequeues = 0;
    unsigned long long end_dequeues = 0;
    int i, a;

    if (argc < 4) {
        show_usage(argc, argv);
        return -1;
    }

    err = sscanf(argv[1], "%u", &nr_dequeuers);
    if (err != 1) {
        show_usage(argc, argv);
        return -1;
    }

    err = sscanf(argv[2], "%u", &nr_enqueuers);
    if (err != 1) {
        show_usage(argc, argv);
        return -1;
    }

    err = sscanf(argv[3], "%lu", &duration);
    if (err != 1) {
        show_usage(argc, argv);
        return -1;
    }

    for (i = 4; i < argc; i++) {
        if (argv[i][0] != '-')
            continue;
        switch (argv[i][1]) {
        case 'a':
            if (argc < i + 2) {
                show_usage(argc, argv);
                return -1;
            }
            a = atoi(argv[++i]);
            cpu_affinities[next_aff++] = a;
            use_affinity = 1;
            printf_verbose("Adding CPU %d affinity\n", a);
            break;
        case 'c':
            if (argc < i + 2) {
                show_usage(argc, argv);
                return -1;
            }
            rduration = atol(argv[++i]);
            break;
        case 'd':
            if (argc < i + 2) {
                show_usage(argc, argv);
                return -1;
            }
            wdelay = atol(argv[++i]);
            break;
        case 'v':
            verbose_mode = 1;
            break;
        }
    }

    printf_verbose("running test for %lu seconds, %u enqueuers, "
                   "%u dequeuers.\n",
                   duration, nr_enqueuers, nr_dequeuers);
    printf_verbose("Writer delay : %lu loops.\n", rduration);
    printf_verbose("Reader duration : %lu loops.\n", wdelay);
    printf_verbose("thread %-6s, tid %lu\n",
                   "main", urcu_get_thread_id());

    tid_enqueuer = calloc(nr_enqueuers, sizeof(*tid_enqueuer));
    tid_dequeuer = calloc(nr_dequeuers, sizeof(*tid_dequeuer));
    count_enqueuer = calloc(nr_enqueuers, 2 * sizeof(*count_enqueuer));
    count_dequeuer = calloc(nr_dequeuers, 2 * sizeof(*count_dequeuer));
    cds_lfq_init_rcu(&q, call_rcu);
    err = create_all_cpu_call_rcu_data(0);
    if (err) {
        printf("Per-CPU call_rcu() worker threads unavailable. Using default global worker thread.\n");
    }

    next_aff = 0;

    for (i = 0; i < nr_enqueuers; i++) {
        err = pthread_create(&tid_enqueuer[i], NULL, thr_enqueuer,
                             &count_enqueuer[2 * i]);
        if (err != 0)
            exit(1);
    }
    for (i = 0; i < nr_dequeuers; i++) {
        err = pthread_create(&tid_dequeuer[i], NULL, thr_dequeuer,
                             &count_dequeuer[2 * i]);
        if (err != 0)
            exit(1);
    }

    cmm_smp_mb();

    test_go = 1;

    for (i = 0; i < duration; i++) {
        sleep(1);
        if (verbose_mode) {
            fwrite(".", sizeof(char), 1, stdout);
            fflush(stdout);
        }
    }

    test_stop = 1;

    for (i = 0; i < nr_enqueuers; i++) {
        err = pthread_join(tid_enqueuer[i], &tret);
        if (err != 0)
            exit(1);
        tot_enqueues += count_enqueuer[2 * i];
        tot_successful_enqueues += count_enqueuer[2 * i + 1];
    }
    for (i = 0; i < nr_dequeuers; i++) {
        err = pthread_join(tid_dequeuer[i], &tret);
        if (err != 0)
            exit(1);
        tot_dequeues += count_dequeuer[2 * i];
        tot_successful_dequeues += count_dequeuer[2 * i + 1];
    }

    test_end(&q, &end_dequeues);
    err = cds_lfq_destroy_rcu(&q);
    assert(!err);

    printf_verbose("total number of enqueues : %llu, dequeues %llu\n",
                   tot_enqueues, tot_dequeues);
    printf_verbose("total number of successful enqueues : %llu, "
                   "successful dequeues %llu\n",
                   tot_successful_enqueues, tot_successful_dequeues);
    printf("SUMMARY %-25s testdur %4lu nr_enqueuers %3u wdelay %6lu "
           "nr_dequeuers %3u "
           "rdur %6lu nr_enqueues %12llu nr_dequeues %12llu "
           "successful enqueues %12llu successful dequeues %12llu "
           "end_dequeues %llu nr_ops %12llu\n",
           argv[0], duration, nr_enqueuers, wdelay,
           nr_dequeuers, rduration, tot_enqueues, tot_dequeues,
           tot_successful_enqueues,
           tot_successful_dequeues, end_dequeues,
           tot_enqueues + tot_dequeues);
    if (tot_successful_enqueues != tot_successful_dequeues + end_dequeues)
        printf("WARNING! Discrepancy between nr succ. enqueues %llu vs "
               "succ. dequeues + end dequeues %llu.\n",
               tot_successful_enqueues,
               tot_successful_dequeues + end_dequeues);

    free_all_cpu_call_rcu_data();
    free(count_enqueuer);
    free(count_dequeuer);
    free(tid_enqueuer);
    free(tid_dequeuer);
    return 0;
}
Beispiel #17
0
int main(int argc, char **argv)
{
	int err;
	pthread_t *tid_enqueuer, *tid_dequeuer;
	void *tret;
	unsigned long long *count_enqueuer, *count_dequeuer;
	unsigned long long tot_enqueues = 0, tot_dequeues = 0;
	unsigned long long tot_successful_enqueues = 0,
			   tot_successful_dequeues = 0;
	unsigned long long end_dequeues = 0;
	int i, a;

	if (argc < 4) {
		show_usage(argc, argv);
		return -1;
	}

	err = sscanf(argv[1], "%u", &nr_dequeuers);
	if (err != 1) {
		show_usage(argc, argv);
		return -1;
	}

	err = sscanf(argv[2], "%u", &nr_enqueuers);
	if (err != 1) {
		show_usage(argc, argv);
		return -1;
	}
	
	err = sscanf(argv[3], "%lu", &duration);
	if (err != 1) {
		show_usage(argc, argv);
		return -1;
	}

	for (i = 4; i < argc; i++) {
		if (argv[i][0] != '-')
			continue;
		switch (argv[i][1]) {
		case 'a':
			if (argc < i + 2) {
				show_usage(argc, argv);
				return -1;
			}
			a = atoi(argv[++i]);
			cpu_affinities[next_aff++] = a;
			use_affinity = 1;
			printf_verbose("Adding CPU %d affinity\n", a);
			break;
		case 'c':
			if (argc < i + 2) {
				show_usage(argc, argv);
				return -1;
			}
			rduration = atol(argv[++i]);
			break;
		case 'd':
			if (argc < i + 2) {
				show_usage(argc, argv);
				return -1;
			}
			wdelay = atol(argv[++i]);
			break;
		case 'v':
			verbose_mode = 1;
			break;
		}
	}

	printf_verbose("running test for %lu seconds, %u enqueuers, "
		       "%u dequeuers.\n",
		       duration, nr_enqueuers, nr_dequeuers);
	printf_verbose("Writer delay : %lu loops.\n", rduration);
	printf_verbose("Reader duration : %lu loops.\n", wdelay);
	printf_verbose("thread %-6s, thread id : %lx, tid %lu\n",
			"main", pthread_self(), (unsigned long)gettid());

	tid_enqueuer = malloc(sizeof(*tid_enqueuer) * nr_enqueuers);
	tid_dequeuer = malloc(sizeof(*tid_dequeuer) * nr_dequeuers);
	count_enqueuer = malloc(2 * sizeof(*count_enqueuer) * nr_enqueuers);
	count_dequeuer = malloc(2 * sizeof(*count_dequeuer) * nr_dequeuers);
	cds_wfq_init(&q);

	next_aff = 0;

	for (i = 0; i < nr_enqueuers; i++) {
		err = pthread_create(&tid_enqueuer[i], NULL, thr_enqueuer,
				     &count_enqueuer[2 * i]);
		if (err != 0)
			exit(1);
	}
	for (i = 0; i < nr_dequeuers; i++) {
		err = pthread_create(&tid_dequeuer[i], NULL, thr_dequeuer,
				     &count_dequeuer[2 * i]);
		if (err != 0)
			exit(1);
	}

	cmm_smp_mb();

	test_go = 1;

	for (i = 0; i < duration; i++) {
		sleep(1);
		if (verbose_mode)
			write (1, ".", 1);
	}

	test_stop = 1;

	for (i = 0; i < nr_enqueuers; i++) {
		err = pthread_join(tid_enqueuer[i], &tret);
		if (err != 0)
			exit(1);
		tot_enqueues += count_enqueuer[2 * i];
		tot_successful_enqueues += count_enqueuer[2 * i + 1];
	}
	for (i = 0; i < nr_dequeuers; i++) {
		err = pthread_join(tid_dequeuer[i], &tret);
		if (err != 0)
			exit(1);
		tot_dequeues += count_dequeuer[2 * i];
		tot_successful_dequeues += count_dequeuer[2 * i + 1];
	}
	
	test_end(&q, &end_dequeues);

	printf_verbose("total number of enqueues : %llu, dequeues %llu\n",
		       tot_enqueues, tot_dequeues);
	printf_verbose("total number of successful enqueues : %llu, "
		       "successful dequeues %llu\n",
		       tot_successful_enqueues, tot_successful_dequeues);
	printf("SUMMARY %-25s testdur %4lu nr_enqueuers %3u wdelay %6lu "
		"nr_dequeuers %3u "
		"rdur %6lu nr_enqueues %12llu nr_dequeues %12llu "
		"successful enqueues %12llu successful dequeues %12llu "
		"end_dequeues %llu nr_ops %12llu\n",
		argv[0], duration, nr_enqueuers, wdelay,
		nr_dequeuers, rduration, tot_enqueues, tot_dequeues,
		tot_successful_enqueues,
		tot_successful_dequeues, end_dequeues,
		tot_enqueues + tot_dequeues);
	if (tot_successful_enqueues != tot_successful_dequeues + end_dequeues)
		printf("WARNING! Discrepancy between nr succ. enqueues %llu vs "
		       "succ. dequeues + end dequeues %llu.\n",
		       tot_successful_enqueues,
		       tot_successful_dequeues + end_dequeues);

	free(count_enqueuer);
	free(count_dequeuer);
	free(tid_enqueuer);
	free(tid_dequeuer);
	return 0;
}
Beispiel #18
0
static void
read_from_shunt (FlowShunt *shunt, FlowPacket *packet, gpointer data)
{
  guint    packet_size;
  gpointer packet_data;
  guint    pause_ms;

  if (reads_are_blocked)
    test_end (TEST_RESULT_FAILED, "got read while blocked");

  if (data != shunt)
    test_end (TEST_RESULT_FAILED, "read callback user_data does not match");

  if (finished_reading)
    test_end (TEST_RESULT_FAILED, "got read callback after end-of-stream");

  if (!packet)
    test_end (TEST_RESULT_FAILED, "got read with NULL packet");

  packet_data = flow_packet_get_data (packet);
  if (!packet_data)
    test_end (TEST_RESULT_FAILED, "got NULL packet data");

  if (flow_packet_get_format (packet) == FLOW_PACKET_FORMAT_OBJECT)
  {
    gpointer object = packet_data;

    if (FLOW_IS_DETAILED_EVENT (object))
    {
      if (flow_detailed_event_matches (object, FLOW_STREAM_DOMAIN, FLOW_STREAM_BEGIN))
      {
        test_print ("Read: Beginning of stream marker\n");

        if (started_reading)
          test_end (TEST_RESULT_FAILED, "got multiple beginning-of-stream markers");

        started_reading = TRUE;
      }
      else if (flow_detailed_event_matches (object, FLOW_STREAM_DOMAIN, FLOW_STREAM_SEGMENT_BEGIN))
      {
        test_print ("Read: Beginning of segment marker\n");

        if (!started_reading)
          test_end (TEST_RESULT_FAILED, "segment started before stream");

        if (finished_reading)
          test_end (TEST_RESULT_FAILED, "segment started after stream end");

        if (in_segment)
          test_end (TEST_RESULT_FAILED, "got nested beginning-of-segment markers");

        in_segment = TRUE;
      }
      else if (flow_detailed_event_matches (object, FLOW_STREAM_DOMAIN, FLOW_STREAM_END))
      {
        test_print ("Read: End of stream marker\n");

        if (!started_reading)
          test_end (TEST_RESULT_FAILED, "stream ended without starting");

        if (finished_reading)
          test_end (TEST_RESULT_FAILED, "got multiple end-of-stream markers");

        if (in_segment)
          test_end (TEST_RESULT_FAILED, "stream ended inside an open segment");

        if (dest_index != BUFFER_SIZE)
          test_end (TEST_RESULT_FAILED, "did not pass through all the data");

        finished_reading = TRUE;

        /* Wait a bit before quitting, so shunts have a chance to generate invalid events */
        g_timeout_add (1000, (GSourceFunc) test_quit_main_loop, NULL);
      }
      else if (flow_detailed_event_matches (object, FLOW_STREAM_DOMAIN, FLOW_STREAM_SEGMENT_END))
      {
        test_print ("Read: End of segment marker\n");

        if (!started_reading)
          test_end (TEST_RESULT_FAILED, "segment end before stream start");

        if (finished_reading)
          test_end (TEST_RESULT_FAILED, "segment end after stream end");

        if (!in_segment)
          test_end (TEST_RESULT_FAILED, "end of segment, but no segment open");

        in_segment = FALSE;
      }
    }
    else if (FLOW_IS_IP_SERVICE (object))
    {
      FlowIPAddr *ip_addr;
      gchar      *string;

      ip_addr = flow_ip_service_find_address (FLOW_IP_SERVICE (object), FLOW_IP_ADDR_ANY_FAMILY);
      if (!ip_addr)
        test_end (TEST_RESULT_FAILED, "no suitable address passed for remote end");

      string = flow_ip_addr_get_string (ip_addr);
      test_print ("Read: Got remote IP service %s:%d.\n", string, flow_ip_service_get_port (FLOW_IP_SERVICE (object)));

      g_object_unref (ip_addr);
    }
    else if (!FLOW_IS_EVENT (object))
    {
      test_end (TEST_RESULT_FAILED, "got a weird object from read shunt");
    }
  }
  else if (flow_packet_get_format (packet) == FLOW_PACKET_FORMAT_BUFFER)
  {
    packet_size = flow_packet_get_size (packet);
    if (packet_size == 0)
      test_end (TEST_RESULT_FAILED, "got zero-size buffer packet");

    test_print ("Read: %d byte packet at offset %d\n", packet_size, dest_index);

    if (!started_reading)
      test_end (TEST_RESULT_FAILED, "got data before start of stream");

    if (finished_reading)
      test_end (TEST_RESULT_FAILED, "got data after end of stream");

    if (!in_segment)
      test_end (TEST_RESULT_FAILED, "got data outside segment");

    if (dest_index + packet_size > BUFFER_SIZE)
      test_end (TEST_RESULT_FAILED, "read too much data");

    if (memcmp (packet_data, buffer + dest_index, packet_size))
      test_end (TEST_RESULT_FAILED, "output data did not match input");

    dest_index += packet_size;

    if (dest_index == BUFFER_SIZE)
      test_print ("Read: Complete at %d bytes\n", dest_index);
  }
  else
  {
    test_end (TEST_RESULT_FAILED, "got unknown packet format");
  }

  flow_packet_unref (packet);

  pause_ms = get_pause_interval_ms ();
  if (pause_ms > 0)
  {
    test_print ("Blocking reads for %.2fs\n", (float) pause_ms / 1000.0);
    reads_are_blocked = TRUE;
    flow_shunt_block_reads (shunt);
    g_timeout_add (pause_ms, (GSourceFunc) read_pause_ended, shunt);
  }
}
Beispiel #19
0
static void
read_from_listener (FlowShunt *shunt, FlowPacket *packet, gpointer data)
{
  gpointer packet_data;

  if (data != shunt)
    test_end (TEST_RESULT_FAILED, "listener read callback user_data does not match");

  if (!packet)
    test_end (TEST_RESULT_FAILED, "listener got read with NULL packet");

  packet_data = flow_packet_get_data (packet);
  if (!packet_data)
    test_end (TEST_RESULT_FAILED, "listener got NULL packet data");

  if (flow_packet_get_format (packet) == FLOW_PACKET_FORMAT_OBJECT)
  {
    if (FLOW_IS_DETAILED_EVENT (packet_data))
    {
      gpointer object = packet_data;

      if (flow_detailed_event_matches (object, FLOW_STREAM_DOMAIN, FLOW_STREAM_BEGIN))
      {
        test_print ("Listener: Beginning of stream marker\n");
      }
      else if (flow_detailed_event_matches (object, FLOW_STREAM_DOMAIN, FLOW_STREAM_SEGMENT_BEGIN))
      {
        test_print ("Listener: Beginning of segment marker\n");
      }
      else if (flow_detailed_event_matches (object, FLOW_STREAM_DOMAIN, FLOW_STREAM_END))
      {
        test_print ("Listener: End of stream marker\n");
      }
      else if (flow_detailed_event_matches (object, FLOW_STREAM_DOMAIN, FLOW_STREAM_SEGMENT_END))
      {
        test_print ("Listener: End of segment marker\n");
      }
      else
      {
        gchar *message;

        message = g_strdup_printf ("listener got unexpected event: %s", flow_event_get_description (FLOW_EVENT (object)));
        test_end (TEST_RESULT_FAILED, message);
      }
    }
    else if (FLOW_IS_ANONYMOUS_EVENT (packet_data))
    {
      FlowAnonymousEvent *anonymous_event = packet_data;

      /* Listener anonymous events always contain shunts for established incoming connections */

      if (recipient_shunt)
        test_end (TEST_RESULT_FAILED, "listener got more than one connect");

      test_print ("Listener: Got connection\n");

      recipient_shunt = flow_anonymous_event_get_data (anonymous_event);
      flow_anonymous_event_set_destroy_notify (anonymous_event, NULL);

      flow_shunt_set_read_func (recipient_shunt, read_from_shunt, recipient_shunt);
    }
    else
    {
      test_end (TEST_RESULT_FAILED, "listener got a weird object");
    }
  }
  else if (flow_packet_get_format (packet) == FLOW_PACKET_FORMAT_BUFFER)
  {
    test_end (TEST_RESULT_FAILED, "listener got data buffer");
  }
  else
  {
    test_end (TEST_RESULT_FAILED, "listener got unknown packet format");
  }

  flow_packet_unref (packet);
}
Beispiel #20
0
void test_priorityq(void)
{
#define PQ_MAX_ITEMS 100
	static const int input[] = {
		1, 2, 3, 4, 5, 6, 7, 8, -1,
		8, 7, 6, 5, 4, 3, 2, 1, -1,
		8, 7, 5, 6, 1, 3, 4, 2, -1,
		-1
	};
	static const int output[] = {
		1, 2, 3, 4, 5, 6, 7, 8
	};
	struct pq_test_item *item, items[PQ_MAX_ITEMS];
	struct priorityq_item *const *all_items;
	unsigned int i, j;
	struct priorityq *pq;
	pool_t pool;
	int prev;

	pool = pool_alloconly_create("priorityq items", 1024);

	/* simple tests with popping only */
	test_begin("priorityq");
	for (i = 0; input[i] != -1; i++) {
		p_clear(pool);
		pq = priorityq_init(cmp_int, 1);
		for (j = 0; input[i] != -1; i++, j++) {
			test_assert(priorityq_count(pq) == j);
			item = p_new(pool, struct pq_test_item, 1);
			item->num = input[i];
			priorityq_add(pq, &item->item);
		}
		all_items = priorityq_items(pq);
		test_assert(priorityq_count(pq) == N_ELEMENTS(output));
		item = (struct pq_test_item *)all_items[0];
		test_assert(item->num == output[0]);
		for (j = 1; j < N_ELEMENTS(output); j++) {
			item = (struct pq_test_item *)all_items[j];
			test_assert(item->num > output[0]);
			test_assert(item->num <= output[N_ELEMENTS(output)-1]);
		}
		for (j = 0; j < N_ELEMENTS(output); j++) {
			test_assert(priorityq_count(pq) == N_ELEMENTS(output) - j);

			item = (struct pq_test_item *)priorityq_peek(pq);
			test_assert(output[j] == item->num);
			item = (struct pq_test_item *)priorityq_pop(pq);
			test_assert(output[j] == item->num);
		}
		test_assert(priorityq_count(pq) == 0);
		test_assert(priorityq_peek(pq) == NULL);
		test_assert(priorityq_pop(pq) == NULL);
		priorityq_deinit(&pq);
	}
	test_end();

	/* randomized tests, remove elements */
	test_begin("priorityq randomized");
	for (i = 0; i < 100; i++) {
		pq = priorityq_init(cmp_int, 1);
		for (j = 0; j < PQ_MAX_ITEMS; j++) {
			items[j].num = rand();
			priorityq_add(pq, &items[j].item);
		}
		for (j = 0; j < PQ_MAX_ITEMS; j++) {
			if (rand() % 3 == 0) {
				priorityq_remove(pq, &items[j].item);
				items[j].num = -1;
			}
		}
		prev = 0;
		while (priorityq_count(pq) > 0) {
			item = (struct pq_test_item *)priorityq_pop(pq);
			test_assert(item->num >= 0 && prev <= item->num);
			prev = item->num;
			item->num = -1;
		}
		for (j = 0; j < PQ_MAX_ITEMS; j++) {
			test_assert(items[j].num == -1);
		}
		priorityq_deinit(&pq);
	}
	test_end();
	pool_unref(&pool);
}
Beispiel #21
0
/* Test basic operations */
static void test01(struct sb *sb, struct inode *inode)
{
	/*
	 * FIXME: map_region() are not supporting to read segments on
	 * multiple leaves at once.
	 */
#define CAN_HANDLE_A_LEAF	1

	/* Create by ascending order */
	if (test_start("test01.1")) {
		struct block_segment seg;
		int err, segs;

		/* Set fake backend mark to modify backend objects. */
		tux3_start_backend(sb);

		for (int i = 0, j = 0; i < 30; i++, j++) {
			segs = d_map_region(inode, 2*i, 1, &seg, 1, MAP_WRITE);
			test_assert(segs == 1);
		}
#ifdef CAN_HANDLE_A_LEAF
		for (int i = 0; i < 30; i++) {
			segs = check_map_region(inode, 2*i, 1, &seg, 1);
			test_assert(segs == 1);
		}
#else
		segs = check_map_region(inode, 0, 30*2, seg, ARRAY_SIZE(seg));
		test_assert(segs == 30*2);
#endif

		/* btree_chop and dleaf_chop test */
		int index = 31*2;
		while (index--) {
			err = btree_chop(&tux_inode(inode)->btree, index,
					 TUXKEY_LIMIT);
			test_assert(!err);
#ifdef CAN_HANDLE_A_LEAF
			for (int i = 0; i < 30; i++) {
				if (index <= i*2)
					break;
				segs = check_map_region(inode, 2*i, 1, &seg, 1);
				test_assert(segs == 1);
			}
#else
			segs = check_map_region(inode, 0, 30*2, seg,
						ARRAY_SIZE(seg));
			test_assert(segs == i*2);
#endif
		}

		/* Check if truncated all */
		segs = map_region(inode, 0, INT_MAX, &seg, 1, MAP_READ);
		test_assert(segs == 1);
		test_assert(seg.count == INT_MAX);
		test_assert(seg.state == BLOCK_SEG_HOLE);

		tux3_end_backend();

		test_assert(force_delta(sb) == 0);
		clean_main(sb, inode);
	}
	test_end();

	/* Create by descending order */
	if (test_start("test01.2")) {
		struct block_segment seg;
		int err, segs;

		/* Set fake backend mark to modify backend objects. */
		tux3_start_backend(sb);

		for (int i = 30; i >= 0; i--) {
			segs = d_map_region(inode, 2*i, 1, &seg, 1, MAP_WRITE);
			test_assert(segs == 1);
		}
#ifdef CAN_HANDLE_A_LEAF
		for (int i = 30; i >= 0; i--) {
			segs = check_map_region(inode, 2*i, 1, &seg, 1);
			test_assert(segs == 1);
		}
#else
		segs = check_map_region(inode, 0, 30*2, seg, ARRAY_SIZE(seg));
		test_assert(segs == i*2);
#endif

		err = btree_chop(&tux_inode(inode)->btree, 0, TUXKEY_LIMIT);
		test_assert(!err);

		/* Check if truncated all */
		segs = map_region(inode, 0, INT_MAX, &seg, 1, MAP_READ);
		test_assert(segs == 1);
		test_assert(seg.count == INT_MAX);
		test_assert(seg.state == BLOCK_SEG_HOLE);

		tux3_end_backend();

		test_assert(force_delta(sb) == 0);
		clean_main(sb, inode);
	}
	test_end();

	test_assert(force_delta(sb) == 0);
	clean_main(sb, inode);
}
Beispiel #22
0
enum fatal_test_state fatal_data_stack(unsigned int stage)
{
#ifdef DEBUG
#define NONEXISTENT_STACK_FRAME_ID (data_stack_frame_t)999999999
	/* If we abort, then we'll be left with a dangling t_push()
	   keep a record of our temporary stack id, so we can clean up. */
	static data_stack_frame_t t_id = NONEXISTENT_STACK_FRAME_ID;
	static unsigned char *undo_ptr = NULL;
	static unsigned char undo_data;
	static bool things_are_messed_up = FALSE;
	if (stage != 0) {
		/* Presume that we need to clean up from the prior test:
		   undo the evil write, then we will be able to t_pop cleanly,
		   and finally we can end the test stanza. */
		if (things_are_messed_up || undo_ptr == NULL)
			return FATAL_TEST_ABORT; /* abort, things are messed up with t_pop */
		*undo_ptr = undo_data;
		undo_ptr = NULL;
		/* t_pop mustn't abort, that would cause recursion */
		things_are_messed_up = TRUE;
		if (t_id != NONEXISTENT_STACK_FRAME_ID && !t_pop(&t_id))
			return FATAL_TEST_ABORT; /* abort, things are messed up with us */
		things_are_messed_up = FALSE;
		t_id = NONEXISTENT_STACK_FRAME_ID;
		test_end();
	}

	switch(stage) {
	case 0: {
		unsigned char *p;
		test_begin("fatal data-stack underrun");
		t_id = t_push_named("fatal_data_stack underrun");
		size_t left = t_get_bytes_available();
		p = t_malloc_no0(left-80); /* will fit */
		p = t_malloc_no0(100); /* won't fit, will get new block */
		int seek = 0;
		/* Seek back for the canary, don't assume endianness */
		while(seek > -60 &&
		      ((p[seek+1] != 0xDB) ||
		       ((p[seek]   != 0xBA || p[seek+2] != 0xAD) &&
			(p[seek+2] != 0xBA || p[seek]   != 0xAD))))
			seek--;
		if (seek <= -60)
			return FATAL_TEST_ABORT; /* abort, couldn't find header */
		undo_ptr = p + seek;
		undo_data = *undo_ptr;
		*undo_ptr = '*';
		/* t_malloc_no0 will panic block header corruption */
		test_expect_fatal_string("Corrupted data stack canary");
		(void)t_malloc_no0(10);
		return FATAL_TEST_FAILURE;
	}

	case 1: case 2: {
		test_begin(stage == 1 ? "fatal t_malloc_no0 overrun near" : "fatal t_malloc_no0 overrun far");
		t_id = t_push_named(stage == 1 ? "fatal t_malloc_no0 overrun first" : "fatal t_malloc_no0 overrun far");
		unsigned char *p = t_malloc_no0(10);
		undo_ptr = p + 10 + (stage == 1 ? 0 : 8*4-1); /* presumes sentry size */
		undo_data = *undo_ptr;
		*undo_ptr = '*';
		/* t_pop will now fail */
		test_expect_fatal_string("buffer overflow");
		(void)t_pop(&t_id);
		t_id = NONEXISTENT_STACK_FRAME_ID; /* We're FUBAR, mustn't pop next entry */
		return FATAL_TEST_FAILURE;
	}

	case 3: case 4: {
		test_begin(stage == 3 ? "fatal t_buffer_get overrun near" : "fatal t_buffer_get overrun far");
		t_id = t_push_named(stage == 3 ? "fatal t_buffer overrun near" : "fatal t_buffer_get overrun far");
		unsigned char *p = t_buffer_get(10);
		undo_ptr = p + 10 + (stage == 3 ? 0 : 8*4-1);
		undo_data = *undo_ptr;
		*undo_ptr = '*';
		/* t_pop will now fail */
		test_expect_fatal_string("buffer overflow");
		(void)t_pop(&t_id);
		t_id = NONEXISTENT_STACK_FRAME_ID; /* We're FUBAR, mustn't pop next entry */
		return FATAL_TEST_FAILURE;
	}

	default:
		things_are_messed_up = TRUE;
		return FATAL_TEST_FINISHED;
	}
#else
	return stage == 0 ? FATAL_TEST_FINISHED : FATAL_TEST_ABORT;
#endif
}
Beispiel #23
0
static void test_fts_filter_stopwords_normalizer_stemmer_no(void)
{
	int ret;
	struct fts_filter *normalizer;
	struct fts_filter *stemmer;
	struct fts_filter *filter;
	const char *error;
	const char *token = NULL;
	const char * const tokens[] = {
		/* Nynorsk*/
		"Alle", "har", "plikter", "andsynes", "samfunnet", "d\xC3\xA5",
		"personlegdomen", "til", "den", "einskilde", "einast", "der",
		"kan", "f\xC3\xA5", "frie", "og", "fullgode",
		"voksterk\xC3\xA5r",
		/* Bokmal */
		"Alle", "mennesker", "er", "f\xC3\xB8""dt", "frie", "og", "med",
		"samme", "menneskeverd", "og", "menneskerettigheter", "De",
		"er", "utstyrt", "med", "fornuft", "og", "samvittighet",
		"og", "b\xC3\xB8r", "handle", "mot", "hverandre", "i",
		"brorskapets", "\xC3\xA5nd", NULL};

	const char * const bases[] = {
		/* Nynorsk*/
		"all", NULL, "plikt", "andsyn", "samfunn", NULL,
		"personlegdom", NULL, NULL, "einskild", "ein", NULL, NULL,
		"fa", "frie", NULL, "fullgod", "voksterk",
		/* Bokmal */
		"all", "mennesk", NULL, "f\xC3\xB8""dt", "frie", NULL, NULL,
		NULL, "menneskeverd", NULL, "menneskerett", "de", NULL,
		"utstyrt", NULL, "fornuft", NULL, "samvitt", NULL, "b\xC3\xB8r",
		"handl", NULL, "hverandr", NULL, "brorskap", "and", NULL};
	const char * const *tpp;
	const char * const *bpp;

	test_begin("fts filters with stopwords, default normalizer and stemming chained, Norwegian");

	test_assert(fts_filter_create(fts_filter_stopwords, NULL, &norwegian_language, stopword_settings, &filter, &error) == 0);
	test_assert(fts_filter_create(fts_filter_normalizer_icu, filter, NULL, NULL, &normalizer, &error) == 0);
	test_assert(fts_filter_create(fts_filter_stemmer_snowball, normalizer, &norwegian_language, NULL, &stemmer, &error) == 0);

	bpp = bases;
	for (tpp = tokens; *tpp != NULL; tpp++) {
		token = *tpp;
		ret = fts_filter_filter(stemmer, &token, &error);
		if (ret <= 0) {
			test_assert(ret == 0);
			test_assert(*bpp == NULL);
		} else {
			test_assert(*bpp != NULL);
			test_assert(null_strcmp(*bpp, token) == 0);
		}
		bpp++;
	}
	fts_filter_unref(&stemmer);
	fts_filter_unref(&normalizer);
	fts_filter_unref(&filter);
	test_assert(stemmer == NULL);
	test_assert(filter == NULL);
	test_assert(normalizer == NULL);
	test_end();
}
Beispiel #24
0
static void test_fts_filter_stopwords_fin(void)
{
	const struct fts_language finnish = { .name = "fi" };
	struct fts_filter *filter;
	const char *error;
	int ret;
	const char *input[] = {"olla", "vaiko", "eik\xC3\xB6", "olla",
	                       "kenest\xC3\xA4", "ja", "joista", "jonka",
	                       "testi", NULL};
	const char *output[] = {NULL, "vaiko", "eik\xC3\xB6", NULL, NULL,
	                        NULL, NULL, NULL, "testi"};
	const char *input2[] =
		{"kuka", "kenet", "keneen", "testi", "eiv\xC3\xA4t", NULL};
	const char *output2[] = {NULL, NULL, NULL, "testi", NULL};
	const char **ip, **op;
	const char *token;

	test_begin("fts filter stopwords, Finnish");
	test_assert(fts_filter_create(fts_filter_stopwords, NULL, &finnish, stopword_settings, &filter, &error) == 0);

	ip = input;
	op = output;
	while (*ip != NULL) {
		token = *ip;
		ret = fts_filter_filter(filter, &token, &error);
		if (ret <= 0) {
			test_assert(ret == 0);
			test_assert(*op == NULL);
		} else {
			test_assert(*op != NULL);
			test_assert(strcmp(*ip, token)  == 0);
		}
		op++;
		ip++;
	}

	fts_filter_unref(&filter);
	test_assert(filter == NULL);

	test_assert(fts_filter_create(fts_filter_stopwords, NULL, &finnish, stopword_settings, &filter, &error) == 0);
	ip = input2;
	op = output2;
	while (*ip != NULL) {
		token = *ip;
		ret = fts_filter_filter(filter, &token, &error);
		if (ret <= 0) {
			test_assert(ret == 0);
			test_assert(*op == NULL);
		} else {
			test_assert(*op != NULL);
			test_assert(strcmp(*ip, token)  == 0);
		}
		op++;
		ip++;
	}

	fts_filter_unref(&filter);
	test_assert(filter == NULL);
	test_end();
}

static void test_fts_filter_stopwords_fra(void)
{
	struct fts_filter *filter;
	const char *error;
	int ret;

	const char *input[] = {"e\xC3\xBBt", "soyez", "soi", "peut", "que",
	                       "quelconque", "\xC3\xA9t\xC3\xA9",
	                       "l\xE2\x80\x99""av\xC3\xA8nement",
	                       NULL};
	const char *output[] = {NULL, NULL, NULL, "peut", NULL,
	                        "quelconque", NULL, 
	                        "l\xE2\x80\x99""av\xC3\xA8nement",};
	const char **ip, **op;
	const char *token;

	test_begin("fts filter stopwords, French");
	test_assert(fts_filter_create(fts_filter_stopwords, NULL, &french_language, stopword_settings, &filter, &error) == 0);

	ip = input;
	op = output;
	while (*ip != NULL) {
		token = *ip;
		ret = fts_filter_filter(filter, &token, &error);
		if (ret <= 0) {
			test_assert(ret == 0);
			test_assert(*op == NULL);
		} else {
			test_assert(*op != NULL);
			test_assert(strcmp(*ip, token)  == 0);
		}
		op++;
		ip++;
	}

	fts_filter_unref(&filter);
	test_assert(filter == NULL);
	test_end();
}

static void test_fts_filter_stopwords_no(void)
{
	struct fts_filter *filter;
	const char *error;
	int ret;

	const char *input[] = {"og", "d\xC3\xA5", "medlemsstatane", "har",
	                       "bunde", "seg", "til", "\xC3\xA5", "fremje",
	                       "allmenn", "v\xC3\xB8rdnad", "for", "pakta",
	                       "og", "halde", "seg", "etter", "menneskerettane",
	                       "og", "den", "grunnleggjande", "fridomen", "i",
	                       "samarbeid", "med", "Dei", "Sameinte",
	                       "Nasjonane", NULL};

	const char *output[] = {NULL, NULL, "medlemsstatane", NULL,
	                       "bunde", NULL, NULL, NULL, "fremje",
	                       "allmenn", "v\xC3\xB8rdnad", NULL, "pakta",
	                       NULL, "halde", NULL, NULL, "menneskerettane",
	                       NULL, NULL, "grunnleggjande", "fridomen", NULL,
	                       "samarbeid", NULL, "Dei", "Sameinte",
	                       "Nasjonane"};
	const char **ip, **op;
	const char *token;

	test_begin("fts filter stopwords, Norwegian");
	test_assert(fts_filter_create(fts_filter_stopwords, NULL, &norwegian_language, stopword_settings, &filter, &error) == 0);

	ip = input;
	op = output;
	while (*ip != NULL) {
		token = *ip;
		ret = fts_filter_filter(filter, &token, &error);
		if (ret <= 0) {
			test_assert(ret == 0);
			test_assert(*op == NULL);
		} else {
			test_assert(*op != NULL);
			test_assert(strcmp(*ip, token)  == 0);
		}
		op++;
		ip++;
	}

	fts_filter_unref(&filter);
	test_assert(filter == NULL);
	test_end();
}

static void test_fts_filter_stopwords_fail_lazy_init(void)
{
	const struct fts_language unknown = { .name = "bebobidoop" };
	struct fts_filter *filter = NULL;
	const char *error = NULL, *token = "foobar";

	test_begin("fts filter stopwords, fail filter() (lazy init)");
	test_assert(fts_filter_create(fts_filter_stopwords, NULL, &unknown, stopword_settings, &filter, &error) == 0);
	test_assert(filter != NULL && error == NULL);
	test_assert(fts_filter_filter(filter, &token, &error) < 0 && error != NULL);
	fts_filter_unref(&filter);
	test_end();

}

#ifdef HAVE_FTS_STEMMER
static void test_fts_filter_stemmer_snowball_stem_english(void)
{
	struct fts_filter *stemmer;
	const char *error;
	const char *token = NULL;
	const char * const tokens[] = {
		"dries" ,"friendlies", "All", "human", "beings", "are",
		 "born", "free", "and", "equal", "in", "dignity", "and",
		 "rights", "They", "are", "endowed", "with", "reason", "and",
		 "conscience", "and", "should", "act", "towards", "one",
		 "another", "in", "a", "spirit", "of", "brotherhood", NULL};
	const char * const bases[] = {
		"dri" ,"friend", "All", "human", "be", "are", "born", "free",
		"and", "equal", "in", "digniti", "and", "right", "They", "are",
		"endow", "with", "reason", "and", "conscienc", "and", "should",
		"act", "toward", "one", "anoth", "in", "a", "spirit", "of",
		"brotherhood", NULL};
	const char * const *tpp;
	const char * const *bpp;

	test_begin("fts filter stem English");
	test_assert(fts_filter_create(fts_filter_stemmer_snowball, NULL, &english_language, NULL, &stemmer, &error) == 0);
	bpp = bases;
	for (tpp=tokens; *tpp != NULL; tpp++) {
		token = *tpp;
		test_assert(fts_filter_filter(stemmer, &token, &error) > 0);
		test_assert(token != NULL);
		test_assert(null_strcmp(token, *bpp) == 0);
		bpp++;
	}
	fts_filter_unref(&stemmer);
	test_assert(stemmer == NULL);
	test_end();
}

static void test_fts_filter_stemmer_snowball_stem_french(void)
{
	struct fts_filter *stemmer;
	const char *error;
	const char *token = NULL;
	const char * const tokens[] = {
		"Tous", "les", "\xC3\xAAtres", "humains", "naissent",
		"libres", "et",	"\xC3\xA9gaux", "en", "dignit\xC3\xA9",
		"et", "en", "droits", NULL};
	const char * const bases[] = {
		"Tous" ,"le", "\xC3\xAAtre", "humain", "naissent", "libr", "et",
		"\xC3\xA9gal", "en", "dignit", "et", "en", "droit", NULL};
	const char * const *tpp;
	const char * const *bpp;

	test_begin("fts filter stem French");
	test_assert(fts_filter_create(fts_filter_stemmer_snowball, NULL, &french_language, NULL, &stemmer, &error) == 0);
	bpp = bases;
	for (tpp=tokens; *tpp != NULL; tpp++) {
		token = *tpp;
		test_assert(fts_filter_filter(stemmer, &token, &error) > 0);
		test_assert(token != NULL);
		test_assert(null_strcmp(token, *bpp) == 0);
		bpp++;
	}
	fts_filter_unref(&stemmer);
	test_assert(stemmer == NULL);
	test_end();
}

static void test_fts_filter_stopwords_stemmer_eng(void)
{
	int ret;
	struct fts_filter *stemmer;
	struct fts_filter *filter;
	const char *error;
	const char *token = NULL;
	const char * const tokens[] = {
		"dries" ,"friendlies", "All", "human", "beings", "are",
		 "born", "free", "and", "equal", "in", "dignity", "and",
		 "rights", "They", "are", "endowed", "with", "reason", "and",
		 "conscience", "and", "should", "act", "towards", "one",
		 "another", "in", "a", "spirit", "of", "brotherhood", NULL};
	const char * const bases[] = {
		"dri" ,"friend", "All", "human", "be", NULL, "born", "free",
		NULL, "equal", NULL, "digniti", NULL, "right", "They", NULL,
		"endow", NULL, "reason", NULL, "conscienc", NULL, "should",
		"act", "toward", "one", "anoth", NULL, NULL, "spirit", NULL,
		"brotherhood", NULL};
	const char * const *tpp;
	const char * const *bpp;

	test_begin("fts filters stopwords and stemming chained, English");

	test_assert(fts_filter_create(fts_filter_stopwords, NULL, &english_language, stopword_settings, &filter, &error) == 0);
	test_assert(fts_filter_create(fts_filter_stemmer_snowball, filter, &english_language, NULL, &stemmer, &error) == 0);

	bpp = bases;
	for (tpp=tokens; *tpp != NULL; tpp++) {
		token = *tpp;
		ret = fts_filter_filter(stemmer, &token, &error);
		test_assert(ret >= 0);
		if (ret == 0)
			test_assert(*bpp == NULL);
		else {
			test_assert(*bpp != NULL);
			test_assert(null_strcmp(*bpp, token)  == 0);
		}
		bpp++;
	}
	fts_filter_unref(&stemmer);
	fts_filter_unref(&filter);
	test_assert(stemmer == NULL);
	test_assert(filter == NULL);
	test_end();
}
#endif

#ifdef HAVE_LIBICU
static void test_fts_filter_normalizer_swedish_short(void)
{
	struct fts_filter *norm = NULL;
	const char *input[] = {
		"Vem",
		"\xC3\x85",
		"\xC3\x85\xC3\x84\xC3\x96",
		"Vem kan segla f\xC3\xB6rutan vind?\n"
		"\xC3\x85\xC3\x84\xC3\x96\xC3\xB6\xC3\xA4\xC3\xA5"
	};
	const char *expected_output[] = {
		"vem",
		"a",
		"aao",
		"vem kan segla forutan vind?\naaooaa"
	};
	const char * const settings[] =
		{"id", "Any-Lower; NFKD; [: Nonspacing Mark :] Remove; NFC", NULL};
	const char *error = NULL;
	const char *token = NULL;
	unsigned int i;

	test_begin("fts filter normalizer Swedish short text");

	test_assert(fts_filter_create(fts_filter_normalizer_icu, NULL, NULL, settings, &norm, &error) == 0);
	for (i = 0; i < N_ELEMENTS(input); i++) {
		token = input[i];
		test_assert_idx(fts_filter_filter(norm, &token, &error) == 1, i);
		test_assert_idx(null_strcmp(token, expected_output[i]) == 0, i);
	}
	fts_filter_unref(&norm);
	test_assert(norm == NULL);
	test_end();
}

static void test_fts_filter_normalizer_swedish_short_default_id(void)
{
	struct fts_filter *norm = NULL;
	const char *input[] = {
		"Vem",
		"\xC3\x85",
		"\xC3\x85\xC3\x84\xC3\x96",
		"Vem kan segla f\xC3\xB6rutan vind?\n"
		"\xC3\x85\xC3\x84\xC3\x96\xC3\xB6\xC3\xA4\xC3\xA5"
	};
	const char *expected_output[] = {
		"vem",
		"a",
		"aao",
		"vemkanseglaforutanvind?\naaooaa"
	};
	const char *error = NULL;
	const char *token = NULL;
	unsigned int i;

	test_begin("fts filter normalizer Swedish short text using default ID");

	test_assert(fts_filter_create(fts_filter_normalizer_icu, NULL, NULL, NULL, &norm, &error) == 0);
	for (i = 0; i < N_ELEMENTS(input); i++) {
		token = input[i];
		test_assert_idx(fts_filter_filter(norm, &token, &error) == 1, i);
		test_assert_idx(null_strcmp(token, expected_output[i]) == 0, i);
	}
	fts_filter_unref(&norm);
	test_assert(norm == NULL);
	test_end();
}

/* UDHRDIR comes from Automake AM_CPPFLAGS */
#define UDHR_FRA_NAME "/udhr_fra.txt"
static void test_fts_filter_normalizer_french(void)
{
	struct fts_filter *norm = NULL;
	FILE *input;
	const char * const settings[] =
		{"id", "Any-Lower; NFKD; [: Nonspacing Mark :] Remove", NULL};
	char buf[4096] = {0};
	const char *error = NULL;
	const char *tokens;
	unsigned char sha512_digest[SHA512_RESULTLEN];
	struct sha512_ctx ctx;
	const unsigned char correct_digest[] = {
		0x78, 0x1e, 0xb9, 0x04, 0xa4, 0x92, 0xca, 0x88,
		0x1e, 0xef, 0x7b, 0xc8, 0x3e, 0x4a, 0xa8, 0xdb,
		0x9c, 0xd4, 0x42, 0x5c, 0x64, 0x81, 0x06, 0xd5,
		0x72, 0x93, 0x38, 0x0c, 0x09, 0xce, 0xbe, 0xdf,
		0x65, 0xff, 0x36, 0x35, 0x05, 0x77, 0xcc, 0xc6,
		0xff, 0x44, 0x2c, 0x31, 0x10, 0x00, 0xf6, 0x8d,
		0x15, 0x25, 0x1e, 0x54, 0x67, 0x2a, 0x5b, 0xc1,
		0xdb, 0x84, 0xc5, 0x0d, 0x43, 0x7e, 0x8c, 0x70};
	const char *udhr_path;

	test_begin("fts filter normalizer French UDHR");

	udhr_path = t_strconcat(UDHRDIR, UDHR_FRA_NAME, NULL);
	test_assert(fts_filter_create(fts_filter_normalizer_icu, NULL, NULL, settings, &norm, &error) == 0);
	input = fopen(udhr_path, "r");
	test_assert(input != NULL);
	sha512_init(&ctx);
	while (NULL != fgets(buf, sizeof(buf), input)) {
		tokens = buf;
		if (fts_filter_filter(norm, &tokens, &error) != 1){
			break;
		}
		sha512_loop(&ctx, tokens, strlen(tokens));
	}
	fclose(input);
	sha512_result(&ctx, sha512_digest);
	test_assert(memcmp(sha512_digest, correct_digest,
			   sizeof(sha512_digest)) == 0);
	fts_filter_unref(&norm);
	test_assert(norm == NULL);
	test_end();
}

static void test_fts_filter_normalizer_empty(void)
{
	/* test just a couple of these */
	static const char *empty_tokens[] = {
		"\xC2\xAF", /* U+00AF */
		"\xCC\x80", /* U+0300 */
		"\xF3\xA0\x87\xAF", /* U+E01EF */
		"\xCC\x80\xF3\xA0\x87\xAF" /* U+0300 U+E01EF */
	};
	const char * const settings[] =
		{"id", "Any-Lower; NFKD; [: Nonspacing Mark :] Remove; [\\x20] Remove", NULL};
	struct fts_filter *norm;
	const char *error;
	unsigned int i;

	test_begin("fts filter normalizer empty tokens");
	test_assert(fts_filter_create(fts_filter_normalizer_icu, NULL, NULL, settings, &norm, &error) == 0);
	for (i = 0; i < N_ELEMENTS(empty_tokens); i++) {
		const char *token = empty_tokens[i];
		test_assert_idx(fts_filter_filter(norm, &token, &error) == 0, i);
	}
	fts_filter_unref(&norm);
	test_end();
}

static void test_fts_filter_normalizer_baddata(void)
{
	const char * const settings[] =
		{"id", "Any-Lower; NFKD; [: Nonspacing Mark :] Remove", NULL};
	struct fts_filter *norm;
	const char *token, *error;
	string_t *str;
	unsigned int i;

	test_begin("fts filter normalizer bad data");

	test_assert(fts_filter_create(fts_filter_normalizer_icu, NULL, NULL, settings, &norm, &error) == 0);
	str = t_str_new(128);
	for (i = 1; i < 0x1ffff; i++) {
		str_truncate(str, 0);
		uni_ucs4_to_utf8_c(i, str);
		token = str_c(str);
		T_BEGIN {
			test_assert_idx(fts_filter_filter(norm, &token, &error) >= 0, i);
		} T_END;
	}

	str_truncate(str, 0);
	uni_ucs4_to_utf8_c(0x7fffffff, str);
	token = str_c(str);
	test_assert(fts_filter_filter(norm, &token, &error) >= 0);

	fts_filter_unref(&norm);
	test_end();
}

static void test_fts_filter_normalizer_invalid_id(void)
{
	struct fts_filter *norm = NULL;
	const char *settings[] =
		{"id", "Any-One-Out-There; DKFN; [: Nonspacing Mark :] Remove",
		 NULL};
	const char *error = NULL, *token = "foo";

	test_begin("fts filter normalizer invalid id");
	test_assert(fts_filter_create(fts_filter_normalizer_icu, NULL, NULL, settings, &norm, &error) == 0);
	test_assert(error == NULL);
	test_assert(fts_filter_filter(norm, &token, &error) < 0 && error != NULL);
	fts_filter_unref(&norm);
	test_end();
}

#ifdef HAVE_FTS_STEMMER
static void test_fts_filter_normalizer_stopwords_stemmer_eng(void)
{
	int ret;
	struct fts_filter *normalizer;
	struct fts_filter *stemmer;
	struct fts_filter *filter;
	const char *error;
	const char * const id_settings[] =
		//{"id", "Any-Lower; NFKD; [: Nonspacing Mark :] Remove; NFC", NULL};
		{"id", "Lower", NULL};
	const char *token = NULL;
	const char * const tokens[] = {
		"dries" ,"friendlies", "All", "human", "beings", "are",
		"born", "free", "and", "equal", "in", "dignity", "and",
		"rights", "They", "are", "endowed", "with", "reason", "and",
		"conscience", "and", "should", "act", "towards", "one",
		"another", "in", "a", "spirit", "of", "brotherhood", "ABCFoo",
		NULL};
	const char * const bases[] = {
		"dri" ,"friend", "all", "human", "be", NULL, "born", "free",
		NULL, "equal", NULL, "digniti", NULL, "right", NULL, NULL,
		"endow", NULL, "reason", NULL, "conscienc", NULL, "should",
		"act", "toward", "one", "anoth", NULL, NULL, "spirit", NULL,
		"brotherhood", "abcfoo", NULL};
	const char * const *tpp;
	const char * const *bpp;

	test_begin("fts filters normalizer, stopwords and stemming chained, English");

	test_assert(fts_filter_create(fts_filter_normalizer_icu, NULL, NULL, id_settings, &normalizer, &error) == 0);
	test_assert(fts_filter_create(fts_filter_stopwords, normalizer, &english_language, stopword_settings, &filter, &error) == 0);
	test_assert(fts_filter_create(fts_filter_stemmer_snowball, filter, &english_language, NULL, &stemmer, &error) == 0);

	bpp = bases;
	for (tpp = tokens; *tpp != NULL; tpp++) {
		token = *tpp;
		ret = fts_filter_filter(stemmer, &token, &error);
		if (ret <= 0) {
			test_assert(ret == 0);
			test_assert(*bpp == NULL);
		} else {
			test_assert(*bpp != NULL);
			test_assert(strcmp(*bpp, token)  == 0);
		}
		bpp++;
	}
	fts_filter_unref(&stemmer);
	fts_filter_unref(&filter);
	fts_filter_unref(&normalizer);
	test_assert(stemmer == NULL);
	test_assert(filter == NULL);
	test_assert(normalizer == NULL);
	test_end();
}
Beispiel #25
0
static
void test_gen_and_get_info_rsa_pem(void)
{
	test_begin("test_gen_and_get_info_rsa_pem");

	const char *error = NULL;
	bool ret = FALSE;
	struct dcrypt_keypair pair;
	string_t* buf = str_new(default_pool, 4096);

	ret = dcrypt_keypair_generate(&pair, DCRYPT_KEY_RSA, 1024, NULL, NULL);
	test_assert(ret == TRUE);

	/* test public key */
	enum dcrypt_key_format format;
	enum dcrypt_key_version version;
	enum dcrypt_key_kind kind;
	enum dcrypt_key_encryption_type encryption_type;
	const char *encryption_key_hash;
	const char *key_hash;

	ret = dcrypt_key_store_public(pair.pub, DCRYPT_FORMAT_PEM, buf,
			&error);
	test_assert(ret == TRUE);

	ret = dcrypt_key_string_get_info(str_c(buf), &format, &version,
			&kind, &encryption_type, &encryption_key_hash,
			&key_hash, &error);
	test_assert(ret == TRUE);
	test_assert(format == DCRYPT_FORMAT_PEM);
	test_assert(version == DCRYPT_KEY_VERSION_NA);

	test_assert(kind == DCRYPT_KEY_KIND_PUBLIC);
	test_assert(encryption_type == DCRYPT_KEY_ENCRYPTION_TYPE_NONE);
	test_assert(encryption_key_hash == NULL);
	test_assert(key_hash == NULL);

	/* test private key */
	buffer_set_used_size(buf, 0);
	ret = dcrypt_key_store_private(pair.priv, DCRYPT_FORMAT_PEM, NULL,
			buf, NULL, NULL, &error);

	test_assert(ret == TRUE);

	ret = dcrypt_key_string_get_info(str_c(buf), &format, &version,
			&kind, &encryption_type, &encryption_key_hash,
			&key_hash, &error);

	test_assert(ret == TRUE);
	test_assert(format == DCRYPT_FORMAT_PEM);
	test_assert(version == DCRYPT_KEY_VERSION_NA);

	test_assert(kind == DCRYPT_KEY_KIND_PRIVATE);

	test_assert(encryption_type == DCRYPT_KEY_ENCRYPTION_TYPE_NONE);
	test_assert(encryption_key_hash == NULL);
	test_assert(key_hash == NULL);

	dcrypt_keypair_free(&pair);
	buffer_free(&buf);

	test_end();
}
Beispiel #26
0
static
void test_load_v1_keys(void)
{
	test_begin("test_load_v1_keys");

	const char *error = NULL;
	const char *data1 = "1\t716\t1\t0567e6bf9579813ae967314423b0fceb14bda24749303923de9a9bb9370e0026f995901a57e63113eeb2baf0c940e978d00686cbb52bd5014bc318563375876255\t0300E46DA2125427BE968EB3B649910CDC4C405E5FFDE18D433A97CABFEE28CEEFAE9EE356C792004FFB80981D67E741B8CC036A34235A8D2E1F98D1658CFC963D07EB\td0cfaca5d335f9edc41c84bb47465184cb0e2ec3931bebfcea4dd433615e77a0\t7c9a1039ea2e4fed73e81dd3ffc3fa22ea4a28352939adde7bf8ea858b00fa4f";

	enum dcrypt_key_format format;
	enum dcrypt_key_version version;
	enum dcrypt_key_kind kind;
	enum dcrypt_key_encryption_type encryption_type;
	const char *encryption_key_hash = NULL;
	const char *key_hash = NULL;

	bool ret = dcrypt_key_string_get_info(data1, &format, &version,
			&kind, &encryption_type, &encryption_key_hash,
			&key_hash, &error);

	test_assert(ret == TRUE);
	test_assert(error == NULL);
	test_assert(format == DCRYPT_FORMAT_DOVECOT);
	test_assert(version == DCRYPT_KEY_VERSION_1);
	test_assert(kind == DCRYPT_KEY_KIND_PRIVATE);
	test_assert(encryption_type == DCRYPT_KEY_ENCRYPTION_TYPE_KEY);
	test_assert(strcmp(encryption_key_hash, "d0cfaca5d335f9edc41c84bb47465184cb0e2ec3931bebfcea4dd433615e77a0") == 0);
	test_assert(strcmp(key_hash, "7c9a1039ea2e4fed73e81dd3ffc3fa22ea4a28352939adde7bf8ea858b00fa4f") == 0);

	const char* data2 = "1\t716\t0301EB00973C4EFC8FCECA4EA33E941F50B561199A5159BCB6C2EED9DD1D62D65E38A254979D89E28F0C28883E71EE2AD264CD16B863FA094A8F6F69A56B62E8918040\t7c9a1039ea2e4fed73e81dd3ffc3fa22ea4a28352939adde7bf8ea858b00fa4f";

	error = NULL;
	encryption_key_hash = NULL;
	key_hash = NULL;

	ret = dcrypt_key_string_get_info(data2, &format, &version,
			&kind, &encryption_type, &encryption_key_hash,
			&key_hash, &error);

	test_assert(ret == TRUE);
	test_assert(error == NULL);
	test_assert(format == DCRYPT_FORMAT_DOVECOT);
	test_assert(version == DCRYPT_KEY_VERSION_1);
	test_assert(kind == DCRYPT_KEY_KIND_PUBLIC);
	test_assert(encryption_type == DCRYPT_KEY_ENCRYPTION_TYPE_NONE);
	test_assert(encryption_key_hash == NULL);
	test_assert(strcmp(key_hash, "7c9a1039ea2e4fed73e81dd3ffc3fa22ea4a28352939adde7bf8ea858b00fa4f") == 0);

	/* This is the key that should be able to decrypt key1 */
	const char *data3 = "1\t716\t0\t048FD04FD3612B22D32790C592CF21CEF417EFD2EA34AE5F688FA5B51BED29E05A308B68DA78E16E90B47A11E133BD9A208A2894FD01B0BEE865CE339EA3FB17AC\td0cfaca5d335f9edc41c84bb47465184cb0e2ec3931bebfcea4dd433615e77a0";

	error = NULL;
	encryption_key_hash = NULL;
	key_hash = NULL;

	ret = dcrypt_key_string_get_info(data3, &format, &version,
			&kind, &encryption_type, &encryption_key_hash,
			&key_hash, &error);
	test_assert(ret == TRUE);
	test_assert(error == NULL);
	test_assert(format == DCRYPT_FORMAT_DOVECOT);
	test_assert(version == DCRYPT_KEY_VERSION_1);
	test_assert(kind == DCRYPT_KEY_KIND_PRIVATE);
	test_assert(encryption_type == DCRYPT_KEY_ENCRYPTION_TYPE_NONE);
	test_assert(encryption_key_hash == NULL);
	test_assert(strcmp(key_hash, "d0cfaca5d335f9edc41c84bb47465184cb0e2ec3931bebfcea4dd433615e77a0") == 0);

	/* key3's key_hash should and does match key1's encryption_key_hash */
	struct dcrypt_private_key *pkey = NULL;
	struct dcrypt_private_key *pkey2 = NULL;
	pkey = NULL;
	error = NULL;

	ret = dcrypt_key_load_private(&pkey2, format, data3, NULL, NULL, &error);
	test_assert(ret == TRUE);
	test_assert(error == NULL);

	ret = dcrypt_key_load_private(&pkey, format, data1, NULL, pkey2, &error);
	test_assert(ret == TRUE);
	test_assert(error == NULL);

	dcrypt_key_free_private(&pkey2);
	dcrypt_key_free_private(&pkey);

	test_end();
}
Beispiel #27
0
static
void test_cipher_test_vectors(void)
{
	static struct {
		const char *key;
		const char *iv;
		const char *pt;
		const char *ct;
	} vectors[] =
	{
		{ "2b7e151628aed2a6abf7158809cf4f3c", "000102030405060708090a0b0c0d0e0f", "6bc1bee22e409f96e93d7e117393172a", "7649abac8119b246cee98e9b12e9197d" },
		{ "2b7e151628aed2a6abf7158809cf4f3c", "7649ABAC8119B246CEE98E9B12E9197D", "ae2d8a571e03ac9c9eb76fac45af8e51", "5086cb9b507219ee95db113a917678b2" }
	};


	test_begin("test_cipher_test_vectors");

	buffer_t *key,*iv,*pt,*ct,*res_enc,*res_dec;

	key = buffer_create_dynamic(pool_datastack_create(), 16);
	iv = buffer_create_dynamic(pool_datastack_create(), 16);
	pt = buffer_create_dynamic(pool_datastack_create(), 16);
	ct = buffer_create_dynamic(pool_datastack_create(), 16);

	res_enc = buffer_create_dynamic(pool_datastack_create(), 32);
	res_dec = buffer_create_dynamic(pool_datastack_create(), 32);

	for(size_t i = 0; i < N_ELEMENTS(vectors); i++) {
		struct dcrypt_context_symmetric *ctx;

		buffer_set_used_size(key, 0);
		buffer_set_used_size(iv, 0);
		buffer_set_used_size(pt, 0);
		buffer_set_used_size(ct, 0);
		buffer_set_used_size(res_enc, 0);
		buffer_set_used_size(res_dec, 0);

		hex_to_binary(vectors[i].key, key);
		hex_to_binary(vectors[i].iv, iv);
		hex_to_binary(vectors[i].pt, pt);
		hex_to_binary(vectors[i].ct, ct);

		if (!dcrypt_ctx_sym_create("AES-128-CBC", DCRYPT_MODE_ENCRYPT, &ctx, NULL)) {
			test_assert_failed("dcrypt_ctx_sym_create", __FILE__, __LINE__-1);
			continue;
		}

		dcrypt_ctx_sym_set_padding(ctx, FALSE);

		dcrypt_ctx_sym_set_key(ctx, key->data, key->used);
		dcrypt_ctx_sym_set_iv(ctx, iv->data, iv->used);

		test_assert_idx(dcrypt_ctx_sym_init(ctx, NULL), i);

		test_assert_idx(dcrypt_ctx_sym_update(ctx, pt->data, pt->used, res_enc, NULL), i);
		test_assert_idx(dcrypt_ctx_sym_final(ctx, res_enc, NULL), i);

		test_assert_idx(buffer_cmp(ct, res_enc), i);

		dcrypt_ctx_sym_destroy(&ctx);

		if (!dcrypt_ctx_sym_create("AES-128-CBC", DCRYPT_MODE_DECRYPT, &ctx, NULL)) {
			test_assert_failed("dcrypt_ctx_sym_create", __FILE__, __LINE__-1);
			continue;
		}

		dcrypt_ctx_sym_set_padding(ctx, FALSE);

		dcrypt_ctx_sym_set_key(ctx, key->data, key->used);
		dcrypt_ctx_sym_set_iv(ctx, iv->data, iv->used);

		test_assert_idx(dcrypt_ctx_sym_init(ctx, NULL), i);
		test_assert_idx(dcrypt_ctx_sym_update(ctx, res_enc->data, res_enc->used, res_dec, NULL), i);
		test_assert_idx(dcrypt_ctx_sym_final(ctx, res_dec, NULL), i);

		test_assert_idx(buffer_cmp(pt, res_dec), i);

		dcrypt_ctx_sym_destroy(&ctx);
	}

	test_end();
}
/** The main entry point of GridLAB-D
 Exit codes
 - \b 0 run completed ok
 - \b 1 command-line processor stopped
 - \b 2 environment startup failed
 - \b 3 test procedure failed
 - \b 4 user rejects conditions of use
 - \b 5 simulation stopped before completing
 - \b 6 initialization failed
 **/
int main(int argc, /**< the number entries on command-line argument list \p argv */
		 char *argv[]) /**< a list of pointers to the command-line arguments */
{
	int rv = 0;
	time_t t_load = time(NULL);
	global_process_id = getpid();
#if defined WIN32 && _DEBUG 
	atexit(pause_at_exit);
#endif
	/* main initialization */
	if (!output_init(argc,argv) || !exec_init())
		exit(6);

	/* process command line arguments */
	if (cmdarg_load(argc,argv)==FAILED)
	{
		output_fatal("shutdown after command line rejected");
		/*	TROUBLESHOOT
			The command line is not valid and the system did not
			complete its startup procedure.  Correct the problem
			with the command line and try again.
		 */
		exit(1);
	}

	/* setup the random number generator */
	random_init();

	/* pidfile */
	if (strcmp(global_pidfile,"")!=0)
	{
		FILE *fp = fopen(global_pidfile,"w");
		if (fp==NULL)
		{
			output_fatal("unable to create pidfile '%s'", global_pidfile);
			/*	TROUBLESHOOT
				The system must allow creation of the process id file at
				the location indicated in the message.  Create and/or
				modify access rights to the path for that file and try again.
			 */
			exit(1);
		}
#ifdef WIN32
#define getpid _getpid
#endif
		fprintf(fp,"%d\n",getpid());
		output_verbose("process id %d written to %s", getpid(), global_pidfile);
		fclose(fp);
		atexit(delete_pidfile);
	}

	/* do legal stuff */
#ifdef LEGAL_NOTICE
	if (strcmp(global_pidfile,"")==0 && legal_notice()==FAILED)
		exit(4);
#endif

	/* set up the test */
	if (global_test_mode)
	{
#ifndef _NO_CPPUNIT
		output_message("Entering test mode");
		if (test_start(argc,argv)==FAILED)
		{
			output_fatal("shutdown after startup test failed");
			/*	TROUBLESHOOT
				A self-test procedure failed and the system stopped.
				Check the output of the test stream and correct the 
				indicated problem.  If the test stream is not redirected
				so as to save the output, try using the <b>--redirect</b>
				command line option.
			 */
			exit(3);
		}
		exit(0); /* There is no environment to speak of, so exit. */
#else
		output_message("Unit Tests not enabled.  Recompile with _NO_CPPUNIT unset");
#endif
	}
	
	/* start the processing environment */
	output_verbose("load time: %d sec", time(NULL) - t_load);
	output_verbose("starting up %s environment", global_environment);
	if (environment_start(argc,argv)==FAILED)
	{
		output_fatal("environment startup failed: %s", strerror(errno));
		/*	TROUBLESHOOT
			The requested environment could not be started.  This usually
			follows a more specific message regarding the startup problem.
			Follow the recommendation for the indicated problem.
		 */
		rv = 2;
	}

	/* post process the test */
	if (global_test_mode)
	{
#ifndef _NO_CPPUNIT
		output_message("Exiting test mode");
		if (test_end(argc,argv)==FAILED)
		{
			output_error("shutdown after end test failed");
			exit(3);
		}
#endif
	}

	/* save the model */
	if (strcmp(global_savefile,"")!=0)
	{
		if (saveall(global_savefile)==FAILED)
			output_error("save to '%s' failed", global_savefile);
	}

	/* do module dumps */
	if (global_dumpall!=FALSE)
	{
		output_verbose("dumping module data");
		module_dumpall();
	}

	/* KML output */
	if (strcmp(global_kmlfile,"")!=0)
		kml_dump(global_kmlfile);

	/* wrap up */
	output_verbose("shutdown complete");

	/* profile results */
	if (global_profiler)
		class_profiles();

	/* restore locale */
	locale_pop();

	/* compute elapsed runtime */
	output_verbose("elapsed runtime %d seconds", realtime_runtime());

	exit(rv);
}
Beispiel #29
0
LRESULT CALLBACK WndProc ( HWND hwnd, UINT message, WPARAM wParam,LPARAM lParam)
        
{
	static int startx = START_X, starty = START_Y;
	static HBITMAP hBitmap;
	static int                    cxClient, cyClient, cxSource, cySource ;
	HDC                           hdc, hdcMem ;
	int                           x, y ;
	PAINTSTRUCT                  ps ;

 	int i;

	switch (message)
	{
		case   WM_CREATE:
			test_init();
			return 0 ;
			
		case   WM_SIZE:
			return 0 ;
		case   WM_TIMER:
			OutputDebugString("TIMER");
			//Invalidate();
			g_frame_id+=1;
			if(g_frame_id >= g_frame_num)
				g_frame_id=0;
			//SendMessage(hwnd, WM_PAINT, 0, 0);
			InvalidateRect(hwnd, NULL, FALSE);
			return 1;
			
		case   WM_PAINT:
			cxSource      = WIDTH;
			cySource      = HEIGHT;
			cxClient = WIDTH;
			cyClient = HEIGHT;
			OutputDebugString("Paint\n");
			
			hdc = GetDC (hwnd);
			hdcMem = CreateCompatibleDC (hdc);
			hBitmap = CreateCompatibleBitmap (hdc, WIDTH, HEIGHT);

			fill_datas();
			
			SetBitmapBits(hBitmap, sizeof datas, datas);
			GetBitmapBits(hBitmap, sizeof datas, datas);				

			ReleaseDC (hwnd, hdc) ;
			SelectObject (hdcMem, hBitmap) ;
			
			hdc = BeginPaint(hwnd, &ps);
			for (y = starty ; y < starty + cyClient ; y += cySource)
			{
				for (x = startx ; x < startx + cxClient ; x += cxSource)
				{
					BitBlt (hdc, x, y, cxSource, cySource, hdcMem, 0, 0, SRCCOPY) ;
					//StretchBlt (hdc, x, y, cxClient, cyClient,hdcMem, 0, 0, cxSource, cySource, MERGECOPY) ;
				}
			}
			EndPaint (hwnd, &ps) ;
			DeleteDC (hdcMem) ;
			DeleteObject (hBitmap) ;
			return 0 ;
			
		case   WM_DESTROY:
			PostQuitMessage (0) ;
			test_end();
			return 0 ;
	}
	return DefWindowProc (hwnd, message, wParam, lParam) ;
}
Beispiel #30
0
static
void test_cipher_aead_test_vectors(void)
{
	struct dcrypt_context_symmetric *ctx;
	const char *error = NULL;

	test_begin("test_cipher_aead_test_vectors");

	if (!dcrypt_ctx_sym_create("aes-128-gcm", DCRYPT_MODE_ENCRYPT, &ctx, &error)) {
		test_assert_failed("dcrypt_ctx_sym_create", __FILE__, __LINE__-1);
		return;
	}

	buffer_t *key, *iv, *aad, *pt, *ct, *tag, *tag_res, *res;

	key = buffer_create_dynamic(pool_datastack_create(), 16);
	iv = buffer_create_dynamic(pool_datastack_create(), 16);
	aad = buffer_create_dynamic(pool_datastack_create(), 16);
	pt = buffer_create_dynamic(pool_datastack_create(), 16);
	ct = buffer_create_dynamic(pool_datastack_create(), 16);
	tag = buffer_create_dynamic(pool_datastack_create(), 16);
	res = buffer_create_dynamic(pool_datastack_create(), 16);
	tag_res = buffer_create_dynamic(pool_datastack_create(), 16);

	hex_to_binary("feffe9928665731c6d6a8f9467308308", key);
	hex_to_binary("cafebabefacedbaddecaf888", iv);
	hex_to_binary("d9313225f88406e5a55909c5aff5269a86a7a9531534f7da2e4c303d8a318a721c3c0c95956809532fcf0e2449a6b525b16aedf5aa0de657ba637b391aafd255", pt);
	hex_to_binary("42831ec2217774244b7221b784d0d49ce3aa212f2c02a4e035c17e2329aca12e21d514b25466931c7d8f6a5aac84aa051ba30b396a0aac973d58e091473f5985", ct);
	hex_to_binary("4d5c2af327cd64a62cf35abd2ba6fab4", tag);

	dcrypt_ctx_sym_set_key(ctx, key->data, key->used);
	dcrypt_ctx_sym_set_iv(ctx, iv->data, iv->used);
	dcrypt_ctx_sym_set_aad(ctx, aad->data, aad->used);
	test_assert(dcrypt_ctx_sym_init(ctx, &error));
	test_assert(dcrypt_ctx_sym_update(ctx, pt->data, pt->used, res, &error));
	test_assert(dcrypt_ctx_sym_final(ctx, res, &error));
	test_assert(dcrypt_ctx_sym_get_tag(ctx, tag_res));

	test_assert(buffer_cmp(ct, res) == TRUE);
	test_assert(buffer_cmp(tag, tag_res) == TRUE);

	dcrypt_ctx_sym_destroy(&ctx);

	if (!dcrypt_ctx_sym_create("aes-128-gcm", DCRYPT_MODE_DECRYPT, &ctx, &error)) {
		test_assert_failed("dcrypt_ctx_sym_create", __FILE__, __LINE__-1);
	} else {

		buffer_set_used_size(res, 0);

		dcrypt_ctx_sym_set_key(ctx, key->data, key->used);
		dcrypt_ctx_sym_set_iv(ctx, iv->data, iv->used);
		dcrypt_ctx_sym_set_aad(ctx, aad->data, aad->used);
		dcrypt_ctx_sym_set_tag(ctx, tag->data, tag->used);
		test_assert(dcrypt_ctx_sym_init(ctx, &error));
		test_assert(dcrypt_ctx_sym_update(ctx, ct->data, ct->used, res, &error));
		test_assert(dcrypt_ctx_sym_final(ctx, res, &error));

		test_assert(buffer_cmp(pt, res) == TRUE);

		dcrypt_ctx_sym_destroy(&ctx);
	}

	test_end();
}