1/*
2 * Copyright (c) 2009-2012 Nick Mathewson and Niels Provos
3 *
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions
6 * are met:
7 * 1. Redistributions of source code must retain the above copyright
8 *    notice, this list of conditions and the following disclaimer.
9 * 2. Redistributions in binary form must reproduce the above copyright
10 *    notice, this list of conditions and the following disclaimer in the
11 *    documentation and/or other materials provided with the distribution.
12 * 3. The name of the author may not be used to endorse or promote products
13 *    derived from this software without specific prior written permission.
14 *
15 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
16 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
17 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
18 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
19 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
20 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
21 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
22 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
23 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
24 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
25 */
26#include "../util-internal.h"
27
28#ifdef _WIN32
29#include <winsock2.h>
30#include <windows.h>
31#include <ws2tcpip.h>
32#endif
33
34#include "event2/event-config.h"
35
36#include <sys/types.h>
37
38#ifndef _WIN32
39#include <sys/socket.h>
40#include <netinet/in.h>
41#include <arpa/inet.h>
42#include <unistd.h>
43#endif
44#ifdef EVENT__HAVE_NETINET_IN6_H
45#include <netinet/in6.h>
46#endif
47#ifdef EVENT__HAVE_SYS_WAIT_H
48#include <sys/wait.h>
49#endif
50#include <signal.h>
51#include <stdio.h>
52#include <stdlib.h>
53#include <string.h>
54
55#include "event2/event.h"
56#include "event2/util.h"
57#include "../ipv6-internal.h"
58#include "../log-internal.h"
59#include "../strlcpy-internal.h"
60#include "../mm-internal.h"
61#include "../time-internal.h"
62
63#include "regress.h"
64
65enum entry_status { NORMAL, CANONICAL, BAD };
66
67/* This is a big table of results we expect from generating and parsing */
68static struct ipv4_entry {
69	const char *addr;
70	ev_uint32_t res;
71	enum entry_status status;
72} ipv4_entries[] = {
73	{ "1.2.3.4", 0x01020304u, CANONICAL },
74	{ "255.255.255.255", 0xffffffffu, CANONICAL },
75	{ "256.0.0.0", 0, BAD },
76	{ "ABC", 0, BAD },
77	{ "1.2.3.4.5", 0, BAD },
78	{ "176.192.208.244", 0xb0c0d0f4, CANONICAL },
79	{ NULL, 0, BAD },
80};
81
82static struct ipv6_entry {
83	const char *addr;
84	ev_uint32_t res[4];
85	enum entry_status status;
86} ipv6_entries[] = {
87	{ "::", { 0, 0, 0, 0, }, CANONICAL },
88	{ "0:0:0:0:0:0:0:0", { 0, 0, 0, 0, }, NORMAL },
89	{ "::1", { 0, 0, 0, 1, }, CANONICAL },
90	{ "::1.2.3.4", { 0, 0, 0, 0x01020304, }, CANONICAL },
91	{ "ffff:1::", { 0xffff0001u, 0, 0, 0, }, CANONICAL },
92	{ "ffff:0000::", { 0xffff0000u, 0, 0, 0, }, NORMAL },
93	{ "ffff::1234", { 0xffff0000u, 0, 0, 0x1234, }, CANONICAL },
94	{ "0102::1.2.3.4", {0x01020000u, 0, 0, 0x01020304u }, NORMAL },
95	{ "::9:c0a8:1:1", { 0, 0, 0x0009c0a8u, 0x00010001u }, CANONICAL },
96	{ "::ffff:1.2.3.4", { 0, 0, 0x000ffffu, 0x01020304u }, CANONICAL },
97	{ "FFFF::", { 0xffff0000u, 0, 0, 0 }, NORMAL },
98	{ "foobar.", { 0, 0, 0, 0 }, BAD },
99	{ "foobar", { 0, 0, 0, 0 }, BAD },
100	{ "fo:obar", { 0, 0, 0, 0 }, BAD },
101	{ "ffff", { 0, 0, 0, 0 }, BAD },
102	{ "fffff::", { 0, 0, 0, 0 }, BAD },
103	{ "fffff::", { 0, 0, 0, 0 }, BAD },
104	{ "::1.0.1.1000", { 0, 0, 0, 0 }, BAD },
105	{ "1:2:33333:4::", { 0, 0, 0, 0 }, BAD },
106	{ "1:2:3:4:5:6:7:8:9", { 0, 0, 0, 0 }, BAD },
107	{ "1::2::3", { 0, 0, 0, 0 }, BAD },
108	{ ":::1", { 0, 0, 0, 0 }, BAD },
109	{ NULL, { 0, 0, 0, 0,  }, BAD },
110};
111
112static void
113regress_ipv4_parse(void *ptr)
114{
115	int i;
116	for (i = 0; ipv4_entries[i].addr; ++i) {
117		char written[128];
118		struct ipv4_entry *ent = &ipv4_entries[i];
119		struct in_addr in;
120		int r;
121		r = evutil_inet_pton(AF_INET, ent->addr, &in);
122		if (r == 0) {
123			if (ent->status != BAD) {
124				TT_FAIL(("%s did not parse, but it's a good address!",
125					ent->addr));
126			}
127			continue;
128		}
129		if (ent->status == BAD) {
130			TT_FAIL(("%s parsed, but we expected an error", ent->addr));
131			continue;
132		}
133		if (ntohl(in.s_addr) != ent->res) {
134			TT_FAIL(("%s parsed to %lx, but we expected %lx", ent->addr,
135				(unsigned long)ntohl(in.s_addr),
136				(unsigned long)ent->res));
137			continue;
138		}
139		if (ent->status == CANONICAL) {
140			const char *w = evutil_inet_ntop(AF_INET, &in, written,
141											 sizeof(written));
142			if (!w) {
143				TT_FAIL(("Tried to write out %s; got NULL.", ent->addr));
144				continue;
145			}
146			if (strcmp(written, ent->addr)) {
147				TT_FAIL(("Tried to write out %s; got %s",
148					ent->addr, written));
149				continue;
150			}
151		}
152
153	}
154
155}
156
157static void
158regress_ipv6_parse(void *ptr)
159{
160#ifdef AF_INET6
161	int i, j;
162
163	for (i = 0; ipv6_entries[i].addr; ++i) {
164		char written[128];
165		struct ipv6_entry *ent = &ipv6_entries[i];
166		struct in6_addr in6;
167		int r;
168		r = evutil_inet_pton(AF_INET6, ent->addr, &in6);
169		if (r == 0) {
170			if (ent->status != BAD)
171				TT_FAIL(("%s did not parse, but it's a good address!",
172					ent->addr));
173			continue;
174		}
175		if (ent->status == BAD) {
176			TT_FAIL(("%s parsed, but we expected an error", ent->addr));
177			continue;
178		}
179		for (j = 0; j < 4; ++j) {
180			/* Can't use s6_addr32 here; some don't have it. */
181			ev_uint32_t u =
182			    ((ev_uint32_t)in6.s6_addr[j*4  ] << 24) |
183			    ((ev_uint32_t)in6.s6_addr[j*4+1] << 16) |
184			    ((ev_uint32_t)in6.s6_addr[j*4+2] << 8) |
185			    ((ev_uint32_t)in6.s6_addr[j*4+3]);
186			if (u != ent->res[j]) {
187				TT_FAIL(("%s did not parse as expected.", ent->addr));
188				continue;
189			}
190		}
191		if (ent->status == CANONICAL) {
192			const char *w = evutil_inet_ntop(AF_INET6, &in6, written,
193											 sizeof(written));
194			if (!w) {
195				TT_FAIL(("Tried to write out %s; got NULL.", ent->addr));
196				continue;
197			}
198			if (strcmp(written, ent->addr)) {
199				TT_FAIL(("Tried to write out %s; got %s", ent->addr, written));
200				continue;
201			}
202		}
203
204	}
205#else
206	TT_BLATHER(("Skipping IPv6 address parsing."));
207#endif
208}
209
210static struct sa_port_ent {
211	const char *parse;
212	int safamily;
213	const char *addr;
214	int port;
215} sa_port_ents[] = {
216	{ "[ffff::1]:1000", AF_INET6, "ffff::1", 1000 },
217	{ "[ffff::1]", AF_INET6, "ffff::1", 0 },
218	{ "[ffff::1", 0, NULL, 0 },
219	{ "[ffff::1]:65599", 0, NULL, 0 },
220	{ "[ffff::1]:0", 0, NULL, 0 },
221	{ "[ffff::1]:-1", 0, NULL, 0 },
222	{ "::1", AF_INET6, "::1", 0 },
223	{ "1:2::1", AF_INET6, "1:2::1", 0 },
224	{ "192.168.0.1:50", AF_INET, "192.168.0.1", 50 },
225	{ "1.2.3.4", AF_INET, "1.2.3.4", 0 },
226	{ NULL, 0, NULL, 0 },
227};
228
229static void
230regress_sockaddr_port_parse(void *ptr)
231{
232	struct sockaddr_storage ss;
233	int i, r;
234
235	for (i = 0; sa_port_ents[i].parse; ++i) {
236		struct sa_port_ent *ent = &sa_port_ents[i];
237		int len = sizeof(ss);
238		memset(&ss, 0, sizeof(ss));
239		r = evutil_parse_sockaddr_port(ent->parse, (struct sockaddr*)&ss, &len);
240		if (r < 0) {
241			if (ent->safamily)
242				TT_FAIL(("Couldn't parse %s!", ent->parse));
243			continue;
244		} else if (! ent->safamily) {
245			TT_FAIL(("Shouldn't have been able to parse %s!", ent->parse));
246			continue;
247		}
248		if (ent->safamily == AF_INET) {
249			struct sockaddr_in sin;
250			memset(&sin, 0, sizeof(sin));
251#ifdef EVENT__HAVE_STRUCT_SOCKADDR_IN_SIN_LEN
252			sin.sin_len = sizeof(sin);
253#endif
254			sin.sin_family = AF_INET;
255			sin.sin_port = htons(ent->port);
256			r = evutil_inet_pton(AF_INET, ent->addr, &sin.sin_addr);
257			if (1 != r) {
258				TT_FAIL(("Couldn't parse ipv4 target %s.", ent->addr));
259			} else if (memcmp(&sin, &ss, sizeof(sin))) {
260				TT_FAIL(("Parse for %s was not as expected.", ent->parse));
261			} else if (len != sizeof(sin)) {
262				TT_FAIL(("Length for %s not as expected.",ent->parse));
263			}
264		} else {
265			struct sockaddr_in6 sin6;
266			memset(&sin6, 0, sizeof(sin6));
267#ifdef EVENT__HAVE_STRUCT_SOCKADDR_IN6_SIN6_LEN
268			sin6.sin6_len = sizeof(sin6);
269#endif
270			sin6.sin6_family = AF_INET6;
271			sin6.sin6_port = htons(ent->port);
272			r = evutil_inet_pton(AF_INET6, ent->addr, &sin6.sin6_addr);
273			if (1 != r) {
274				TT_FAIL(("Couldn't parse ipv6 target %s.", ent->addr));
275			} else if (memcmp(&sin6, &ss, sizeof(sin6))) {
276				TT_FAIL(("Parse for %s was not as expected.", ent->parse));
277			} else if (len != sizeof(sin6)) {
278				TT_FAIL(("Length for %s not as expected.",ent->parse));
279			}
280		}
281	}
282}
283
284
285static void
286regress_sockaddr_port_format(void *ptr)
287{
288	struct sockaddr_storage ss;
289	int len;
290	const char *cp;
291	char cbuf[128];
292	int r;
293
294	len = sizeof(ss);
295	r = evutil_parse_sockaddr_port("192.168.1.1:80",
296	    (struct sockaddr*)&ss, &len);
297	tt_int_op(r,==,0);
298	cp = evutil_format_sockaddr_port_(
299		(struct sockaddr*)&ss, cbuf, sizeof(cbuf));
300	tt_ptr_op(cp,==,cbuf);
301	tt_str_op(cp,==,"192.168.1.1:80");
302
303	len = sizeof(ss);
304	r = evutil_parse_sockaddr_port("[ff00::8010]:999",
305	    (struct sockaddr*)&ss, &len);
306	tt_int_op(r,==,0);
307	cp = evutil_format_sockaddr_port_(
308		(struct sockaddr*)&ss, cbuf, sizeof(cbuf));
309	tt_ptr_op(cp,==,cbuf);
310	tt_str_op(cp,==,"[ff00::8010]:999");
311
312	ss.ss_family=99;
313	cp = evutil_format_sockaddr_port_(
314		(struct sockaddr*)&ss, cbuf, sizeof(cbuf));
315	tt_ptr_op(cp,==,cbuf);
316	tt_str_op(cp,==,"<addr with socktype 99>");
317end:
318	;
319}
320
321static struct sa_pred_ent {
322	const char *parse;
323
324	int is_loopback;
325} sa_pred_entries[] = {
326	{ "127.0.0.1",	 1 },
327	{ "127.0.3.2",	 1 },
328	{ "128.1.2.3",	 0 },
329	{ "18.0.0.1",	 0 },
330	{ "129.168.1.1", 0 },
331
332	{ "::1",	 1 },
333	{ "::0",	 0 },
334	{ "f::1",	 0 },
335	{ "::501",	 0 },
336	{ NULL,		 0 },
337
338};
339
340static void
341test_evutil_sockaddr_predicates(void *ptr)
342{
343	struct sockaddr_storage ss;
344	int r, i;
345
346	for (i=0; sa_pred_entries[i].parse; ++i) {
347		struct sa_pred_ent *ent = &sa_pred_entries[i];
348		int len = sizeof(ss);
349
350		r = evutil_parse_sockaddr_port(ent->parse, (struct sockaddr*)&ss, &len);
351
352		if (r<0) {
353			TT_FAIL(("Couldn't parse %s!", ent->parse));
354			continue;
355		}
356
357		/* sockaddr_is_loopback */
358		if (ent->is_loopback != evutil_sockaddr_is_loopback_((struct sockaddr*)&ss)) {
359			TT_FAIL(("evutil_sockaddr_loopback(%s) not as expected",
360				ent->parse));
361		}
362	}
363}
364
365static void
366test_evutil_strtoll(void *ptr)
367{
368	const char *s;
369	char *endptr;
370
371	tt_want(evutil_strtoll("5000000000", NULL, 10) ==
372		((ev_int64_t)5000000)*1000);
373	tt_want(evutil_strtoll("-5000000000", NULL, 10) ==
374		((ev_int64_t)5000000)*-1000);
375	s = " 99999stuff";
376	tt_want(evutil_strtoll(s, &endptr, 10) == (ev_int64_t)99999);
377	tt_want(endptr == s+6);
378	tt_want(evutil_strtoll("foo", NULL, 10) == 0);
379 }
380
381static void
382test_evutil_snprintf(void *ptr)
383{
384	char buf[16];
385	int r;
386	ev_uint64_t u64 = ((ev_uint64_t)1000000000)*200;
387	ev_int64_t i64 = -1 * (ev_int64_t) u64;
388	size_t size = 8000;
389	ev_ssize_t ssize = -9000;
390
391	r = evutil_snprintf(buf, sizeof(buf), "%d %d", 50, 100);
392	tt_str_op(buf, ==, "50 100");
393	tt_int_op(r, ==, 6);
394
395	r = evutil_snprintf(buf, sizeof(buf), "longish %d", 1234567890);
396	tt_str_op(buf, ==, "longish 1234567");
397	tt_int_op(r, ==, 18);
398
399	r = evutil_snprintf(buf, sizeof(buf), EV_U64_FMT, EV_U64_ARG(u64));
400	tt_str_op(buf, ==, "200000000000");
401	tt_int_op(r, ==, 12);
402
403	r = evutil_snprintf(buf, sizeof(buf), EV_I64_FMT, EV_I64_ARG(i64));
404	tt_str_op(buf, ==, "-200000000000");
405	tt_int_op(r, ==, 13);
406
407	r = evutil_snprintf(buf, sizeof(buf), EV_SIZE_FMT" "EV_SSIZE_FMT,
408	    EV_SIZE_ARG(size), EV_SSIZE_ARG(ssize));
409	tt_str_op(buf, ==, "8000 -9000");
410	tt_int_op(r, ==, 10);
411
412      end:
413	;
414}
415
416static void
417test_evutil_casecmp(void *ptr)
418{
419	tt_int_op(evutil_ascii_strcasecmp("ABC", "ABC"), ==, 0);
420	tt_int_op(evutil_ascii_strcasecmp("ABC", "abc"), ==, 0);
421	tt_int_op(evutil_ascii_strcasecmp("ABC", "abcd"), <, 0);
422	tt_int_op(evutil_ascii_strcasecmp("ABC", "abb"), >, 0);
423	tt_int_op(evutil_ascii_strcasecmp("ABCd", "abc"), >, 0);
424
425	tt_int_op(evutil_ascii_strncasecmp("Libevent", "LibEvEnT", 100), ==, 0);
426	tt_int_op(evutil_ascii_strncasecmp("Libevent", "LibEvEnT", 4), ==, 0);
427	tt_int_op(evutil_ascii_strncasecmp("Libevent", "LibEXXXX", 4), ==, 0);
428	tt_int_op(evutil_ascii_strncasecmp("Libevent", "LibE", 4), ==, 0);
429	tt_int_op(evutil_ascii_strncasecmp("Libe", "LibEvEnT", 4), ==, 0);
430	tt_int_op(evutil_ascii_strncasecmp("Lib", "LibEvEnT", 4), <, 0);
431	tt_int_op(evutil_ascii_strncasecmp("abc", "def", 99), <, 0);
432	tt_int_op(evutil_ascii_strncasecmp("Z", "qrst", 1), >, 0);
433end:
434	;
435}
436
437static void
438test_evutil_rtrim(void *ptr)
439{
440#define TEST_TRIM(s, result) \
441	do {						\
442	    if (cp) mm_free(cp);			\
443	    cp = mm_strdup(s);				\
444	    tt_assert(cp);				\
445	    evutil_rtrim_lws_(cp);			\
446	    tt_str_op(cp, ==, result);			\
447	} while(0)
448
449	char *cp = NULL;
450	(void) ptr;
451
452	TEST_TRIM("", "");
453	TEST_TRIM("a", "a");
454	TEST_TRIM("abcdef ghi", "abcdef ghi");
455
456	TEST_TRIM(" ", "");
457	TEST_TRIM("  ", "");
458	TEST_TRIM("a ", "a");
459	TEST_TRIM("abcdef  gH       ", "abcdef  gH");
460
461	TEST_TRIM("\t\t", "");
462	TEST_TRIM(" \t", "");
463	TEST_TRIM("\t", "");
464	TEST_TRIM("a \t", "a");
465	TEST_TRIM("a\t ", "a");
466	TEST_TRIM("a\t", "a");
467	TEST_TRIM("abcdef  gH    \t  ", "abcdef  gH");
468
469end:
470	if (cp)
471		mm_free(cp);
472}
473
474static int logsev = 0;
475static char *logmsg = NULL;
476
477static void
478logfn(int severity, const char *msg)
479{
480	logsev = severity;
481	tt_want(msg);
482	if (msg) {
483		if (logmsg)
484			free(logmsg);
485		logmsg = strdup(msg);
486	}
487}
488
489static int fatal_want_severity = 0;
490static const char *fatal_want_message = NULL;
491static void
492fatalfn(int exitcode)
493{
494	if (logsev != fatal_want_severity ||
495	    !logmsg ||
496	    strcmp(logmsg, fatal_want_message))
497		exit(0);
498	else
499		exit(exitcode);
500}
501
502#ifndef _WIN32
503#define CAN_CHECK_ERR
504static void
505check_error_logging(void (*fn)(void), int wantexitcode,
506    int wantseverity, const char *wantmsg)
507{
508	pid_t pid;
509	int status = 0, exitcode;
510	fatal_want_severity = wantseverity;
511	fatal_want_message = wantmsg;
512	if ((pid = regress_fork()) == 0) {
513		/* child process */
514		fn();
515		exit(0); /* should be unreachable. */
516	} else {
517		wait(&status);
518		exitcode = WEXITSTATUS(status);
519		tt_int_op(wantexitcode, ==, exitcode);
520	}
521end:
522	;
523}
524
525static void
526errx_fn(void)
527{
528	event_errx(2, "Fatal error; too many kumquats (%d)", 5);
529}
530
531static void
532err_fn(void)
533{
534	errno = ENOENT;
535	event_err(5,"Couldn't open %s", "/very/bad/file");
536}
537
538static void
539sock_err_fn(void)
540{
541	evutil_socket_t fd = socket(AF_INET, SOCK_STREAM, 0);
542#ifdef _WIN32
543	EVUTIL_SET_SOCKET_ERROR(WSAEWOULDBLOCK);
544#else
545	errno = EAGAIN;
546#endif
547	event_sock_err(20, fd, "Unhappy socket");
548}
549#endif
550
551static void
552test_evutil_log(void *ptr)
553{
554	evutil_socket_t fd = -1;
555	char buf[128];
556
557	event_set_log_callback(logfn);
558	event_set_fatal_callback(fatalfn);
559#define RESET() do {				\
560		logsev = 0;	\
561		if (logmsg) free(logmsg);	\
562		logmsg = NULL;			\
563	} while (0)
564#define LOGEQ(sev,msg) do {			\
565		tt_int_op(logsev,==,sev);	\
566		tt_assert(logmsg != NULL);	\
567		tt_str_op(logmsg,==,msg);	\
568	} while (0)
569
570#ifdef CAN_CHECK_ERR
571	/* We need to disable these tests for now.  Previously, the logging
572	 * module didn't enforce the requirement that a fatal callback
573	 * actually exit.  Now, it exits no matter what, so if we wan to
574	 * reinstate these tests, we'll need to fork for each one. */
575	check_error_logging(errx_fn, 2, EVENT_LOG_ERR,
576	    "Fatal error; too many kumquats (5)");
577	RESET();
578#endif
579
580	event_warnx("Far too many %s (%d)", "wombats", 99);
581	LOGEQ(EVENT_LOG_WARN, "Far too many wombats (99)");
582	RESET();
583
584	event_msgx("Connecting lime to coconut");
585	LOGEQ(EVENT_LOG_MSG, "Connecting lime to coconut");
586	RESET();
587
588	event_debug(("A millisecond passed! We should log that!"));
589#ifdef USE_DEBUG
590	LOGEQ(EVENT_LOG_DEBUG, "A millisecond passed! We should log that!");
591#else
592	tt_int_op(logsev,==,0);
593	tt_ptr_op(logmsg,==,NULL);
594#endif
595	RESET();
596
597	/* Try with an errno. */
598	errno = ENOENT;
599	event_warn("Couldn't open %s", "/bad/file");
600	evutil_snprintf(buf, sizeof(buf),
601	    "Couldn't open /bad/file: %s",strerror(ENOENT));
602	LOGEQ(EVENT_LOG_WARN,buf);
603	RESET();
604
605#ifdef CAN_CHECK_ERR
606	evutil_snprintf(buf, sizeof(buf),
607	    "Couldn't open /very/bad/file: %s",strerror(ENOENT));
608	check_error_logging(err_fn, 5, EVENT_LOG_ERR, buf);
609	RESET();
610#endif
611
612	/* Try with a socket errno. */
613	fd = socket(AF_INET, SOCK_STREAM, 0);
614#ifdef _WIN32
615	evutil_snprintf(buf, sizeof(buf),
616	    "Unhappy socket: %s",
617	    evutil_socket_error_to_string(WSAEWOULDBLOCK));
618	EVUTIL_SET_SOCKET_ERROR(WSAEWOULDBLOCK);
619#else
620	evutil_snprintf(buf, sizeof(buf),
621	    "Unhappy socket: %s", strerror(EAGAIN));
622	errno = EAGAIN;
623#endif
624	event_sock_warn(fd, "Unhappy socket");
625	LOGEQ(EVENT_LOG_WARN, buf);
626	RESET();
627
628#ifdef CAN_CHECK_ERR
629	check_error_logging(sock_err_fn, 20, EVENT_LOG_ERR, buf);
630	RESET();
631#endif
632
633#undef RESET
634#undef LOGEQ
635end:
636	if (logmsg)
637		free(logmsg);
638	if (fd >= 0)
639		evutil_closesocket(fd);
640}
641
642static void
643test_evutil_strlcpy(void *arg)
644{
645	char buf[8];
646
647	/* Successful case. */
648	tt_int_op(5, ==, strlcpy(buf, "Hello", sizeof(buf)));
649	tt_str_op(buf, ==, "Hello");
650
651	/* Overflow by a lot. */
652	tt_int_op(13, ==, strlcpy(buf, "pentasyllabic", sizeof(buf)));
653	tt_str_op(buf, ==, "pentasy");
654
655	/* Overflow by exactly one. */
656	tt_int_op(8, ==, strlcpy(buf, "overlong", sizeof(buf)));
657	tt_str_op(buf, ==, "overlon");
658end:
659	;
660}
661
662struct example_struct {
663	const char *a;
664	const char *b;
665	long c;
666};
667
668static void
669test_evutil_upcast(void *arg)
670{
671	struct example_struct es1;
672	const char **cp;
673	es1.a = "World";
674	es1.b = "Hello";
675	es1.c = -99;
676
677	tt_int_op(evutil_offsetof(struct example_struct, b), ==, sizeof(char*));
678
679	cp = &es1.b;
680	tt_ptr_op(EVUTIL_UPCAST(cp, struct example_struct, b), ==, &es1);
681
682end:
683	;
684}
685
686static void
687test_evutil_integers(void *arg)
688{
689	ev_int64_t i64;
690	ev_uint64_t u64;
691	ev_int32_t i32;
692	ev_uint32_t u32;
693	ev_int16_t i16;
694	ev_uint16_t u16;
695	ev_int8_t  i8;
696	ev_uint8_t  u8;
697
698	void *ptr;
699	ev_intptr_t iptr;
700	ev_uintptr_t uptr;
701
702	ev_ssize_t ssize;
703
704	tt_int_op(sizeof(u64), ==, 8);
705	tt_int_op(sizeof(i64), ==, 8);
706	tt_int_op(sizeof(u32), ==, 4);
707	tt_int_op(sizeof(i32), ==, 4);
708	tt_int_op(sizeof(u16), ==, 2);
709	tt_int_op(sizeof(i16), ==, 2);
710	tt_int_op(sizeof(u8), ==,  1);
711	tt_int_op(sizeof(i8), ==,  1);
712
713	tt_int_op(sizeof(ev_ssize_t), ==, sizeof(size_t));
714	tt_int_op(sizeof(ev_intptr_t), >=, sizeof(void *));
715	tt_int_op(sizeof(ev_uintptr_t), ==, sizeof(intptr_t));
716
717	u64 = 1000000000;
718	u64 *= 1000000000;
719	tt_assert(u64 / 1000000000 == 1000000000);
720	i64 = -1000000000;
721	i64 *= 1000000000;
722	tt_assert(i64 / 1000000000 == -1000000000);
723
724	u64 = EV_UINT64_MAX;
725	i64 = EV_INT64_MAX;
726	tt_assert(u64 > 0);
727	tt_assert(i64 > 0);
728	u64++;
729/*	i64++; */
730	tt_assert(u64 == 0);
731/*	tt_assert(i64 == EV_INT64_MIN); */
732/*	tt_assert(i64 < 0); */
733
734	u32 = EV_UINT32_MAX;
735	i32 = EV_INT32_MAX;
736	tt_assert(u32 > 0);
737	tt_assert(i32 > 0);
738	u32++;
739/*	i32++; */
740	tt_assert(u32 == 0);
741/*	tt_assert(i32 == EV_INT32_MIN); */
742/*	tt_assert(i32 < 0); */
743
744	u16 = EV_UINT16_MAX;
745	i16 = EV_INT16_MAX;
746	tt_assert(u16 > 0);
747	tt_assert(i16 > 0);
748	u16++;
749/*	i16++; */
750	tt_assert(u16 == 0);
751/*	tt_assert(i16 == EV_INT16_MIN); */
752/* 	tt_assert(i16 < 0); */
753
754	u8 = EV_UINT8_MAX;
755	i8 = EV_INT8_MAX;
756	tt_assert(u8 > 0);
757	tt_assert(i8 > 0);
758	u8++;
759/*	i8++;*/
760	tt_assert(u8 == 0);
761/*	tt_assert(i8 == EV_INT8_MIN); */
762/*	tt_assert(i8 < 0); */
763
764/*
765	ssize = EV_SSIZE_MAX;
766	tt_assert(ssize > 0);
767	ssize++;
768	tt_assert(ssize < 0);
769	tt_assert(ssize == EV_SSIZE_MIN);
770*/
771
772	ptr = &ssize;
773	iptr = (ev_intptr_t)ptr;
774	uptr = (ev_uintptr_t)ptr;
775	ptr = (void *)iptr;
776	tt_assert(ptr == &ssize);
777	ptr = (void *)uptr;
778	tt_assert(ptr == &ssize);
779
780	iptr = -1;
781	tt_assert(iptr < 0);
782end:
783	;
784}
785
786struct evutil_addrinfo *
787ai_find_by_family(struct evutil_addrinfo *ai, int family)
788{
789	while (ai) {
790		if (ai->ai_family == family)
791			return ai;
792		ai = ai->ai_next;
793	}
794	return NULL;
795}
796
797struct evutil_addrinfo *
798ai_find_by_protocol(struct evutil_addrinfo *ai, int protocol)
799{
800	while (ai) {
801		if (ai->ai_protocol == protocol)
802			return ai;
803		ai = ai->ai_next;
804	}
805	return NULL;
806}
807
808
809int
810test_ai_eq_(const struct evutil_addrinfo *ai, const char *sockaddr_port,
811    int socktype, int protocol, int line)
812{
813	struct sockaddr_storage ss;
814	int slen = sizeof(ss);
815	int gotport;
816	char buf[128];
817	memset(&ss, 0, sizeof(ss));
818	if (socktype > 0)
819		tt_int_op(ai->ai_socktype, ==, socktype);
820	if (protocol > 0)
821		tt_int_op(ai->ai_protocol, ==, protocol);
822
823	if (evutil_parse_sockaddr_port(
824		    sockaddr_port, (struct sockaddr*)&ss, &slen)<0) {
825		TT_FAIL(("Couldn't parse expected address %s on line %d",
826			sockaddr_port, line));
827		return -1;
828	}
829	if (ai->ai_family != ss.ss_family) {
830		TT_FAIL(("Address family %d did not match %d on line %d",
831			ai->ai_family, ss.ss_family, line));
832		return -1;
833	}
834	if (ai->ai_addr->sa_family == AF_INET) {
835		struct sockaddr_in *sin = (struct sockaddr_in*)ai->ai_addr;
836		evutil_inet_ntop(AF_INET, &sin->sin_addr, buf, sizeof(buf));
837		gotport = ntohs(sin->sin_port);
838		if (ai->ai_addrlen != sizeof(struct sockaddr_in)) {
839			TT_FAIL(("Addr size mismatch on line %d", line));
840			return -1;
841		}
842	} else {
843		struct sockaddr_in6 *sin6 = (struct sockaddr_in6*)ai->ai_addr;
844		evutil_inet_ntop(AF_INET6, &sin6->sin6_addr, buf, sizeof(buf));
845		gotport = ntohs(sin6->sin6_port);
846		if (ai->ai_addrlen != sizeof(struct sockaddr_in6)) {
847			TT_FAIL(("Addr size mismatch on line %d", line));
848			return -1;
849		}
850	}
851	if (evutil_sockaddr_cmp(ai->ai_addr, (struct sockaddr*)&ss, 1)) {
852		TT_FAIL(("Wanted %s, got %s:%d on line %d", sockaddr_port,
853			buf, gotport, line));
854		return -1;
855	} else {
856		TT_BLATHER(("Wanted %s, got %s:%d on line %d", sockaddr_port,
857			buf, gotport, line));
858	}
859	return 0;
860end:
861	TT_FAIL(("Test failed on line %d", line));
862	return -1;
863}
864
865static void
866test_evutil_rand(void *arg)
867{
868	char buf1[32];
869	char buf2[32];
870	int counts[256];
871	int i, j, k, n=0;
872	struct evutil_weakrand_state seed = { 12346789U };
873
874	memset(buf2, 0, sizeof(buf2));
875	memset(counts, 0, sizeof(counts));
876
877	for (k=0;k<32;++k) {
878		/* Try a few different start and end points; try to catch
879		 * the various misaligned cases of arc4random_buf */
880		int startpoint = evutil_weakrand_(&seed) % 4;
881		int endpoint = 32 - (evutil_weakrand_(&seed) % 4);
882
883		memset(buf2, 0, sizeof(buf2));
884
885		/* Do 6 runs over buf1, or-ing the result into buf2 each
886		 * time, to make sure we're setting each byte that we mean
887		 * to set. */
888		for (i=0;i<8;++i) {
889			memset(buf1, 0, sizeof(buf1));
890			evutil_secure_rng_get_bytes(buf1 + startpoint,
891			    endpoint-startpoint);
892			n += endpoint - startpoint;
893			for (j=0; j<32; ++j) {
894				if (j >= startpoint && j < endpoint) {
895					buf2[j] |= buf1[j];
896					++counts[(unsigned char)buf1[j]];
897				} else {
898					tt_assert(buf1[j] == 0);
899					tt_int_op(buf1[j], ==, 0);
900
901				}
902			}
903		}
904
905		/* This will give a false positive with P=(256**8)==(2**64)
906		 * for each character. */
907		for (j=startpoint;j<endpoint;++j) {
908			tt_int_op(buf2[j], !=, 0);
909		}
910	}
911
912	evutil_weakrand_seed_(&seed, 0);
913	for (i = 0; i < 10000; ++i) {
914		ev_int32_t r = evutil_weakrand_range_(&seed, 9999);
915		tt_int_op(0, <=, r);
916		tt_int_op(r, <, 9999);
917	}
918
919	/* for (i=0;i<256;++i) { printf("%3d %2d\n", i, counts[i]); } */
920end:
921	;
922}
923
924static void
925test_evutil_getaddrinfo(void *arg)
926{
927	struct evutil_addrinfo *ai = NULL, *a;
928	struct evutil_addrinfo hints;
929	int r;
930
931	/* Try using it as a pton. */
932	memset(&hints, 0, sizeof(hints));
933	hints.ai_family = PF_UNSPEC;
934	hints.ai_socktype = SOCK_STREAM;
935	r = evutil_getaddrinfo("1.2.3.4", "8080", &hints, &ai);
936	tt_int_op(r, ==, 0);
937	tt_assert(ai);
938	tt_ptr_op(ai->ai_next, ==, NULL); /* no ambiguity */
939	test_ai_eq(ai, "1.2.3.4:8080", SOCK_STREAM, IPPROTO_TCP);
940	evutil_freeaddrinfo(ai);
941	ai = NULL;
942
943	memset(&hints, 0, sizeof(hints));
944	hints.ai_family = PF_UNSPEC;
945	hints.ai_protocol = IPPROTO_UDP;
946	r = evutil_getaddrinfo("1001:b0b::f00f", "4321", &hints, &ai);
947	tt_int_op(r, ==, 0);
948	tt_assert(ai);
949	tt_ptr_op(ai->ai_next, ==, NULL); /* no ambiguity */
950	test_ai_eq(ai, "[1001:b0b::f00f]:4321", SOCK_DGRAM, IPPROTO_UDP);
951	evutil_freeaddrinfo(ai);
952	ai = NULL;
953
954	/* Try out the behavior of nodename=NULL */
955	memset(&hints, 0, sizeof(hints));
956	hints.ai_family = PF_INET;
957	hints.ai_protocol = IPPROTO_TCP;
958	hints.ai_flags = EVUTIL_AI_PASSIVE; /* as if for bind */
959	r = evutil_getaddrinfo(NULL, "9999", &hints, &ai);
960	tt_int_op(r,==,0);
961	tt_assert(ai);
962	tt_ptr_op(ai->ai_next, ==, NULL);
963	test_ai_eq(ai, "0.0.0.0:9999", SOCK_STREAM, IPPROTO_TCP);
964	evutil_freeaddrinfo(ai);
965	ai = NULL;
966	hints.ai_flags = 0; /* as if for connect */
967	r = evutil_getaddrinfo(NULL, "9998", &hints, &ai);
968	tt_assert(ai);
969	tt_int_op(r,==,0);
970	test_ai_eq(ai, "127.0.0.1:9998", SOCK_STREAM, IPPROTO_TCP);
971	tt_ptr_op(ai->ai_next, ==, NULL);
972	evutil_freeaddrinfo(ai);
973	ai = NULL;
974
975	hints.ai_flags = 0; /* as if for connect */
976	hints.ai_family = PF_INET6;
977	r = evutil_getaddrinfo(NULL, "9997", &hints, &ai);
978	tt_assert(ai);
979	tt_int_op(r,==,0);
980	tt_ptr_op(ai->ai_next, ==, NULL);
981	test_ai_eq(ai, "[::1]:9997", SOCK_STREAM, IPPROTO_TCP);
982	evutil_freeaddrinfo(ai);
983	ai = NULL;
984
985	hints.ai_flags = EVUTIL_AI_PASSIVE; /* as if for bind. */
986	hints.ai_family = PF_INET6;
987	r = evutil_getaddrinfo(NULL, "9996", &hints, &ai);
988	tt_assert(ai);
989	tt_int_op(r,==,0);
990	tt_ptr_op(ai->ai_next, ==, NULL);
991	test_ai_eq(ai, "[::]:9996", SOCK_STREAM, IPPROTO_TCP);
992	evutil_freeaddrinfo(ai);
993	ai = NULL;
994
995	/* Now try an unspec one. We should get a v6 and a v4. */
996	hints.ai_family = PF_UNSPEC;
997	r = evutil_getaddrinfo(NULL, "9996", &hints, &ai);
998	tt_assert(ai);
999	tt_int_op(r,==,0);
1000	a = ai_find_by_family(ai, PF_INET6);
1001	tt_assert(a);
1002	test_ai_eq(a, "[::]:9996", SOCK_STREAM, IPPROTO_TCP);
1003	a = ai_find_by_family(ai, PF_INET);
1004	tt_assert(a);
1005	test_ai_eq(a, "0.0.0.0:9996", SOCK_STREAM, IPPROTO_TCP);
1006	evutil_freeaddrinfo(ai);
1007	ai = NULL;
1008
1009	/* Try out AI_NUMERICHOST: successful case.  Also try
1010	 * multiprotocol. */
1011	memset(&hints, 0, sizeof(hints));
1012	hints.ai_family = PF_UNSPEC;
1013	hints.ai_flags = EVUTIL_AI_NUMERICHOST;
1014	r = evutil_getaddrinfo("1.2.3.4", NULL, &hints, &ai);
1015	tt_int_op(r, ==, 0);
1016	a = ai_find_by_protocol(ai, IPPROTO_TCP);
1017	tt_assert(a);
1018	test_ai_eq(a, "1.2.3.4", SOCK_STREAM, IPPROTO_TCP);
1019	a = ai_find_by_protocol(ai, IPPROTO_UDP);
1020	tt_assert(a);
1021	test_ai_eq(a, "1.2.3.4", SOCK_DGRAM, IPPROTO_UDP);
1022	evutil_freeaddrinfo(ai);
1023	ai = NULL;
1024
1025	/* Try the failing case of AI_NUMERICHOST */
1026	memset(&hints, 0, sizeof(hints));
1027	hints.ai_family = PF_UNSPEC;
1028	hints.ai_flags = EVUTIL_AI_NUMERICHOST;
1029	r = evutil_getaddrinfo("www.google.com", "80", &hints, &ai);
1030	tt_int_op(r, ==, EVUTIL_EAI_NONAME);
1031	tt_ptr_op(ai, ==, NULL);
1032
1033	/* Try symbolic service names wit AI_NUMERICSERV */
1034	memset(&hints, 0, sizeof(hints));
1035	hints.ai_family = PF_UNSPEC;
1036	hints.ai_socktype = SOCK_STREAM;
1037	hints.ai_flags = EVUTIL_AI_NUMERICSERV;
1038	r = evutil_getaddrinfo("1.2.3.4", "http", &hints, &ai);
1039	tt_int_op(r,==,EVUTIL_EAI_NONAME);
1040
1041	/* Try symbolic service names */
1042	memset(&hints, 0, sizeof(hints));
1043	hints.ai_family = PF_UNSPEC;
1044	hints.ai_socktype = SOCK_STREAM;
1045	r = evutil_getaddrinfo("1.2.3.4", "http", &hints, &ai);
1046	if (r!=0) {
1047		TT_DECLARE("SKIP", ("Symbolic service names seem broken."));
1048	} else {
1049		tt_assert(ai);
1050		test_ai_eq(ai, "1.2.3.4:80", SOCK_STREAM, IPPROTO_TCP);
1051		evutil_freeaddrinfo(ai);
1052		ai = NULL;
1053	}
1054
1055end:
1056	if (ai)
1057		evutil_freeaddrinfo(ai);
1058}
1059
1060static void
1061test_evutil_getaddrinfo_live(void *arg)
1062{
1063	struct evutil_addrinfo *ai = NULL;
1064	struct evutil_addrinfo hints;
1065
1066	struct sockaddr_in6 *sin6;
1067	struct sockaddr_in *sin;
1068	char buf[128];
1069	const char *cp;
1070	int r;
1071
1072	/* Now do some actual lookups. */
1073	memset(&hints, 0, sizeof(hints));
1074	hints.ai_family = PF_INET;
1075	hints.ai_protocol = IPPROTO_TCP;
1076	hints.ai_socktype = SOCK_STREAM;
1077	r = evutil_getaddrinfo("www.google.com", "80", &hints, &ai);
1078	if (r != 0) {
1079		TT_DECLARE("SKIP", ("Couldn't resolve www.google.com"));
1080	} else {
1081		tt_assert(ai);
1082		tt_int_op(ai->ai_family, ==, PF_INET);
1083		tt_int_op(ai->ai_protocol, ==, IPPROTO_TCP);
1084		tt_int_op(ai->ai_socktype, ==, SOCK_STREAM);
1085		tt_int_op(ai->ai_addrlen, ==, sizeof(struct sockaddr_in));
1086		sin = (struct sockaddr_in*)ai->ai_addr;
1087		tt_int_op(sin->sin_family, ==, AF_INET);
1088		tt_int_op(sin->sin_port, ==, htons(80));
1089		tt_int_op(sin->sin_addr.s_addr, !=, 0xffffffff);
1090
1091		cp = evutil_inet_ntop(AF_INET, &sin->sin_addr, buf, sizeof(buf));
1092		TT_BLATHER(("www.google.com resolved to %s",
1093			cp?cp:"<unwriteable>"));
1094		evutil_freeaddrinfo(ai);
1095		ai = NULL;
1096	}
1097
1098	hints.ai_family = PF_INET6;
1099	r = evutil_getaddrinfo("ipv6.google.com", "80", &hints, &ai);
1100	if (r != 0) {
1101		TT_BLATHER(("Couldn't do an ipv6 lookup for ipv6.google.com"));
1102	} else {
1103		tt_assert(ai);
1104		tt_int_op(ai->ai_family, ==, PF_INET6);
1105		tt_int_op(ai->ai_addrlen, ==, sizeof(struct sockaddr_in6));
1106		sin6 = (struct sockaddr_in6*)ai->ai_addr;
1107		tt_int_op(sin6->sin6_port, ==, htons(80));
1108
1109		cp = evutil_inet_ntop(AF_INET6, &sin6->sin6_addr, buf,
1110		    sizeof(buf));
1111		TT_BLATHER(("ipv6.google.com resolved to %s",
1112			cp?cp:"<unwriteable>"));
1113	}
1114
1115end:
1116	if (ai)
1117		evutil_freeaddrinfo(ai);
1118}
1119
1120#ifdef _WIN32
1121static void
1122test_evutil_loadsyslib(void *arg)
1123{
1124	HMODULE h=NULL;
1125
1126	h = evutil_load_windows_system_library_(TEXT("kernel32.dll"));
1127	tt_assert(h);
1128
1129end:
1130	if (h)
1131		CloseHandle(h);
1132
1133}
1134#endif
1135
1136/** Test mm_malloc(). */
1137static void
1138test_event_malloc(void *arg)
1139{
1140	void *p = NULL;
1141	(void)arg;
1142
1143	/* mm_malloc(0) should simply return NULL. */
1144#ifndef EVENT__DISABLE_MM_REPLACEMENT
1145	errno = 0;
1146	p = mm_malloc(0);
1147	tt_assert(p == NULL);
1148	tt_int_op(errno, ==, 0);
1149#endif
1150
1151	/* Trivial case. */
1152	errno = 0;
1153	p = mm_malloc(8);
1154	tt_assert(p != NULL);
1155	tt_int_op(errno, ==, 0);
1156	mm_free(p);
1157
1158 end:
1159	errno = 0;
1160	return;
1161}
1162
1163static void
1164test_event_calloc(void *arg)
1165{
1166	void *p = NULL;
1167	(void)arg;
1168
1169#ifndef EVENT__DISABLE_MM_REPLACEMENT
1170	/* mm_calloc() should simply return NULL
1171	 * if either argument is zero. */
1172	errno = 0;
1173	p = mm_calloc(0, 0);
1174	tt_assert(p == NULL);
1175	tt_int_op(errno, ==, 0);
1176	errno = 0;
1177	p = mm_calloc(0, 1);
1178	tt_assert(p == NULL);
1179	tt_int_op(errno, ==, 0);
1180	errno = 0;
1181	p = mm_calloc(1, 0);
1182	tt_assert(p == NULL);
1183	tt_int_op(errno, ==, 0);
1184#endif
1185
1186	/* Trivial case. */
1187	errno = 0;
1188	p = mm_calloc(8, 8);
1189	tt_assert(p != NULL);
1190	tt_int_op(errno, ==, 0);
1191	mm_free(p);
1192	p = NULL;
1193
1194	/* mm_calloc() should set errno = ENOMEM and return NULL
1195	 * in case of potential overflow. */
1196	errno = 0;
1197	p = mm_calloc(EV_SIZE_MAX/2, EV_SIZE_MAX/2 + 8);
1198	tt_assert(p == NULL);
1199	tt_int_op(errno, ==, ENOMEM);
1200
1201 end:
1202	errno = 0;
1203	if (p)
1204		mm_free(p);
1205
1206	return;
1207}
1208
1209static void
1210test_event_strdup(void *arg)
1211{
1212	void *p = NULL;
1213	(void)arg;
1214
1215#ifndef EVENT__DISABLE_MM_REPLACEMENT
1216	/* mm_strdup(NULL) should set errno = EINVAL and return NULL. */
1217	errno = 0;
1218	p = mm_strdup(NULL);
1219	tt_assert(p == NULL);
1220	tt_int_op(errno, ==, EINVAL);
1221#endif
1222
1223	/* Trivial cases. */
1224
1225	errno = 0;
1226	p = mm_strdup("");
1227	tt_assert(p != NULL);
1228	tt_int_op(errno, ==, 0);
1229	tt_str_op(p, ==, "");
1230	mm_free(p);
1231
1232	errno = 0;
1233	p = mm_strdup("foo");
1234	tt_assert(p != NULL);
1235	tt_int_op(errno, ==, 0);
1236	tt_str_op(p, ==, "foo");
1237	mm_free(p);
1238
1239	/* XXX
1240	 * mm_strdup(str) where str is a string of length EV_SIZE_MAX
1241	 * should set errno = ENOMEM and return NULL. */
1242
1243 end:
1244	errno = 0;
1245	return;
1246}
1247
1248static void
1249test_evutil_usleep(void *arg)
1250{
1251	struct timeval tv1, tv2, tv3, diff1, diff2;
1252	const struct timeval quarter_sec = {0, 250*1000};
1253	const struct timeval tenth_sec = {0, 100*1000};
1254	long usec1, usec2;
1255
1256	evutil_gettimeofday(&tv1, NULL);
1257	evutil_usleep_(&quarter_sec);
1258	evutil_gettimeofday(&tv2, NULL);
1259	evutil_usleep_(&tenth_sec);
1260	evutil_gettimeofday(&tv3, NULL);
1261
1262	evutil_timersub(&tv2, &tv1, &diff1);
1263	evutil_timersub(&tv3, &tv2, &diff2);
1264	usec1 = diff1.tv_sec * 1000000 + diff1.tv_usec;
1265	usec2 = diff2.tv_sec * 1000000 + diff2.tv_usec;
1266
1267	tt_int_op(usec1, >, 200000);
1268	tt_int_op(usec1, <, 300000);
1269	tt_int_op(usec2, >,  80000);
1270	tt_int_op(usec2, <, 120000);
1271
1272end:
1273	;
1274}
1275
1276static void
1277test_evutil_monotonic_res(void *data_)
1278{
1279	/* Basic santity-test for monotonic timers.  What we'd really like
1280	 * to do is make sure that they can't go backwards even when the
1281	 * system clock goes backwards. But we haven't got a good way to
1282	 * move the system clock backwards.
1283	 */
1284	struct basic_test_data *data = data_;
1285	struct evutil_monotonic_timer timer;
1286	const int precise = strstr(data->setup_data, "precise") != NULL;
1287	const int fallback = strstr(data->setup_data, "fallback") != NULL;
1288	struct timeval tv[10], delay;
1289	int total_diff = 0;
1290
1291	int flags = 0, wantres, acceptdiff, i;
1292	if (precise)
1293		flags |= EV_MONOT_PRECISE;
1294	if (fallback)
1295		flags |= EV_MONOT_FALLBACK;
1296	if (precise || fallback) {
1297#ifdef _WIN32
1298		wantres = 10*1000;
1299		acceptdiff = 1000;
1300#else
1301		wantres = 1000;
1302		acceptdiff = 300;
1303#endif
1304	} else {
1305		wantres = 40*1000;
1306		acceptdiff = 20*1000;
1307	}
1308
1309	TT_BLATHER(("Precise = %d", precise));
1310	TT_BLATHER(("Fallback = %d", fallback));
1311
1312	/* First, make sure we match up with usleep. */
1313
1314	delay.tv_sec = 0;
1315	delay.tv_usec = wantres;
1316
1317	tt_int_op(evutil_configure_monotonic_time_(&timer, flags), ==, 0);
1318
1319	for (i = 0; i < 10; ++i) {
1320		evutil_gettime_monotonic_(&timer, &tv[i]);
1321		evutil_usleep_(&delay);
1322	}
1323
1324	for (i = 0; i < 9; ++i) {
1325		struct timeval diff;
1326		tt_assert(evutil_timercmp(&tv[i], &tv[i+1], <));
1327		evutil_timersub(&tv[i+1], &tv[i], &diff);
1328		tt_int_op(diff.tv_sec, ==, 0);
1329		total_diff += diff.tv_usec;
1330		TT_BLATHER(("Difference = %d", (int)diff.tv_usec));
1331	}
1332	tt_int_op(abs(total_diff/9 - wantres), <, acceptdiff);
1333
1334end:
1335	;
1336}
1337
1338static void
1339test_evutil_monotonic_prc(void *data_)
1340{
1341	struct basic_test_data *data = data_;
1342	struct evutil_monotonic_timer timer;
1343	const int precise = strstr(data->setup_data, "precise") != NULL;
1344	const int fallback = strstr(data->setup_data, "fallback") != NULL;
1345	struct timeval tv[10];
1346	int total_diff = 0;
1347	int i, maxstep = 25*1000,flags=0;
1348	if (precise)
1349		maxstep = 500;
1350	if (precise)
1351		flags |= EV_MONOT_PRECISE;
1352	if (fallback)
1353		flags |= EV_MONOT_FALLBACK;
1354	tt_int_op(evutil_configure_monotonic_time_(&timer, flags), ==, 0);
1355
1356	/* find out what precision we actually see. */
1357
1358	evutil_gettime_monotonic_(&timer, &tv[0]);
1359	for (i = 1; i < 10; ++i) {
1360		do {
1361			evutil_gettime_monotonic_(&timer, &tv[i]);
1362		} while (evutil_timercmp(&tv[i-1], &tv[i], ==));
1363	}
1364
1365	total_diff = 0;
1366	for (i = 0; i < 9; ++i) {
1367		struct timeval diff;
1368		tt_assert(evutil_timercmp(&tv[i], &tv[i+1], <));
1369		evutil_timersub(&tv[i+1], &tv[i], &diff);
1370		tt_int_op(diff.tv_sec, ==, 0);
1371		total_diff += diff.tv_usec;
1372		TT_BLATHER(("Step difference = %d", (int)diff.tv_usec));
1373	}
1374	TT_BLATHER(("Average step difference = %d", total_diff / 9));
1375	tt_int_op(total_diff/9, <, maxstep);
1376
1377end:
1378	;
1379}
1380
1381struct testcase_t util_testcases[] = {
1382	{ "ipv4_parse", regress_ipv4_parse, 0, NULL, NULL },
1383	{ "ipv6_parse", regress_ipv6_parse, 0, NULL, NULL },
1384	{ "sockaddr_port_parse", regress_sockaddr_port_parse, 0, NULL, NULL },
1385	{ "sockaddr_port_format", regress_sockaddr_port_format, 0, NULL, NULL },
1386	{ "sockaddr_predicates", test_evutil_sockaddr_predicates, 0,NULL,NULL },
1387	{ "evutil_snprintf", test_evutil_snprintf, 0, NULL, NULL },
1388	{ "evutil_strtoll", test_evutil_strtoll, 0, NULL, NULL },
1389	{ "evutil_casecmp", test_evutil_casecmp, 0, NULL, NULL },
1390	{ "evutil_rtrim", test_evutil_rtrim, 0, NULL, NULL },
1391	{ "strlcpy", test_evutil_strlcpy, 0, NULL, NULL },
1392	{ "log", test_evutil_log, TT_FORK, NULL, NULL },
1393	{ "upcast", test_evutil_upcast, 0, NULL, NULL },
1394	{ "integers", test_evutil_integers, 0, NULL, NULL },
1395	{ "rand", test_evutil_rand, TT_FORK, NULL, NULL },
1396	{ "getaddrinfo", test_evutil_getaddrinfo, TT_FORK, NULL, NULL },
1397	{ "getaddrinfo_live", test_evutil_getaddrinfo_live, TT_FORK|TT_OFF_BY_DEFAULT, NULL, NULL },
1398#ifdef _WIN32
1399	{ "loadsyslib", test_evutil_loadsyslib, TT_FORK, NULL, NULL },
1400#endif
1401	{ "mm_malloc", test_event_malloc, 0, NULL, NULL },
1402	{ "mm_calloc", test_event_calloc, 0, NULL, NULL },
1403	{ "mm_strdup", test_event_strdup, 0, NULL, NULL },
1404	{ "usleep", test_evutil_usleep, 0, NULL, NULL },
1405	{ "monotonic_res", test_evutil_monotonic_res, 0, &basic_setup, (void*)"" },
1406	{ "monotonic_res_precise", test_evutil_monotonic_res, TT_OFF_BY_DEFAULT, &basic_setup, (void*)"precise" },
1407	{ "monotonic_res_fallback", test_evutil_monotonic_res, TT_OFF_BY_DEFAULT, &basic_setup, (void*)"fallback" },
1408	{ "monotonic_prc", test_evutil_monotonic_prc, 0, &basic_setup, (void*)"" },
1409	{ "monotonic_prc_precise", test_evutil_monotonic_prc, 0, &basic_setup, (void*)"precise" },
1410	{ "monotonic_prc_fallback", test_evutil_monotonic_prc, 0, &basic_setup, (void*)"fallback" },
1411	END_OF_TESTCASES,
1412};
1413
1414