xref: /freebsd/contrib/ntp/sntp/libevent/test/regress_util.c (revision 5a3935b6d66c1810125b0a92a0f26e207236f6fb)
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 
65 enum entry_status { NORMAL, CANONICAL, BAD };
66 
67 /* This is a big table of results we expect from generating and parsing */
68 static 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 
82 static 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 
112 static void
113 regress_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 
157 static void
158 regress_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 				(in6.s6_addr[j*4  ] << 24) |
183 				(in6.s6_addr[j*4+1] << 16) |
184 				(in6.s6_addr[j*4+2] << 8) |
185 				(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 
210 static 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 
229 static void
230 regress_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 
285 static void
286 regress_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>");
317 end:
318 	;
319 }
320 
321 static 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 
340 static void
341 test_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 
365 static void
366 test_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 
381 static void
382 test_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 
416 static void
417 test_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);
433 end:
434 	;
435 }
436 
437 static void
438 test_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 
469 end:
470 	if (cp)
471 		mm_free(cp);
472 }
473 
474 static int logsev = 0;
475 static char *logmsg = NULL;
476 
477 static void
478 logfn(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 
489 static int fatal_want_severity = 0;
490 static const char *fatal_want_message = NULL;
491 static void
492 fatalfn(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
504 static void
505 check_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 	}
521 end:
522 	;
523 }
524 
525 static void
526 errx_fn(void)
527 {
528 	event_errx(2, "Fatal error; too many kumquats (%d)", 5);
529 }
530 
531 static void
532 err_fn(void)
533 {
534 	errno = ENOENT;
535 	event_err(5,"Couldn't open %s", "/very/bad/file");
536 }
537 
538 static void
539 sock_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 
551 static void
552 test_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
635 end:
636 	if (logmsg)
637 		free(logmsg);
638 	if (fd >= 0)
639 		evutil_closesocket(fd);
640 }
641 
642 static void
643 test_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");
658 end:
659 	;
660 }
661 
662 struct example_struct {
663 	const char *a;
664 	const char *b;
665 	long c;
666 };
667 
668 static void
669 test_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 
682 end:
683 	;
684 }
685 
686 static void
687 test_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 	ssize = EV_SSIZE_MAX;
765 	tt_assert(ssize > 0);
766 	ssize++;
767 	tt_assert(ssize < 0);
768 	tt_assert(ssize == EV_SSIZE_MIN);
769 
770 	ptr = &ssize;
771 	iptr = (ev_intptr_t)ptr;
772 	uptr = (ev_uintptr_t)ptr;
773 	ptr = (void *)iptr;
774 	tt_assert(ptr == &ssize);
775 	ptr = (void *)uptr;
776 	tt_assert(ptr == &ssize);
777 
778 	iptr = -1;
779 	tt_assert(iptr < 0);
780 end:
781 	;
782 }
783 
784 struct evutil_addrinfo *
785 ai_find_by_family(struct evutil_addrinfo *ai, int family)
786 {
787 	while (ai) {
788 		if (ai->ai_family == family)
789 			return ai;
790 		ai = ai->ai_next;
791 	}
792 	return NULL;
793 }
794 
795 struct evutil_addrinfo *
796 ai_find_by_protocol(struct evutil_addrinfo *ai, int protocol)
797 {
798 	while (ai) {
799 		if (ai->ai_protocol == protocol)
800 			return ai;
801 		ai = ai->ai_next;
802 	}
803 	return NULL;
804 }
805 
806 
807 int
808 test_ai_eq_(const struct evutil_addrinfo *ai, const char *sockaddr_port,
809     int socktype, int protocol, int line)
810 {
811 	struct sockaddr_storage ss;
812 	int slen = sizeof(ss);
813 	int gotport;
814 	char buf[128];
815 	memset(&ss, 0, sizeof(ss));
816 	if (socktype > 0)
817 		tt_int_op(ai->ai_socktype, ==, socktype);
818 	if (protocol > 0)
819 		tt_int_op(ai->ai_protocol, ==, protocol);
820 
821 	if (evutil_parse_sockaddr_port(
822 		    sockaddr_port, (struct sockaddr*)&ss, &slen)<0) {
823 		TT_FAIL(("Couldn't parse expected address %s on line %d",
824 			sockaddr_port, line));
825 		return -1;
826 	}
827 	if (ai->ai_family != ss.ss_family) {
828 		TT_FAIL(("Address family %d did not match %d on line %d",
829 			ai->ai_family, ss.ss_family, line));
830 		return -1;
831 	}
832 	if (ai->ai_addr->sa_family == AF_INET) {
833 		struct sockaddr_in *sin = (struct sockaddr_in*)ai->ai_addr;
834 		evutil_inet_ntop(AF_INET, &sin->sin_addr, buf, sizeof(buf));
835 		gotport = ntohs(sin->sin_port);
836 		if (ai->ai_addrlen != sizeof(struct sockaddr_in)) {
837 			TT_FAIL(("Addr size mismatch on line %d", line));
838 			return -1;
839 		}
840 	} else {
841 		struct sockaddr_in6 *sin6 = (struct sockaddr_in6*)ai->ai_addr;
842 		evutil_inet_ntop(AF_INET6, &sin6->sin6_addr, buf, sizeof(buf));
843 		gotport = ntohs(sin6->sin6_port);
844 		if (ai->ai_addrlen != sizeof(struct sockaddr_in6)) {
845 			TT_FAIL(("Addr size mismatch on line %d", line));
846 			return -1;
847 		}
848 	}
849 	if (evutil_sockaddr_cmp(ai->ai_addr, (struct sockaddr*)&ss, 1)) {
850 		TT_FAIL(("Wanted %s, got %s:%d on line %d", sockaddr_port,
851 			buf, gotport, line));
852 		return -1;
853 	} else {
854 		TT_BLATHER(("Wanted %s, got %s:%d on line %d", sockaddr_port,
855 			buf, gotport, line));
856 	}
857 	return 0;
858 end:
859 	TT_FAIL(("Test failed on line %d", line));
860 	return -1;
861 }
862 
863 static void
864 test_evutil_rand(void *arg)
865 {
866 	char buf1[32];
867 	char buf2[32];
868 	int counts[256];
869 	int i, j, k, n=0;
870 	struct evutil_weakrand_state seed = { 12346789U };
871 
872 	memset(buf2, 0, sizeof(buf2));
873 	memset(counts, 0, sizeof(counts));
874 
875 	for (k=0;k<32;++k) {
876 		/* Try a few different start and end points; try to catch
877 		 * the various misaligned cases of arc4random_buf */
878 		int startpoint = evutil_weakrand_(&seed) % 4;
879 		int endpoint = 32 - (evutil_weakrand_(&seed) % 4);
880 
881 		memset(buf2, 0, sizeof(buf2));
882 
883 		/* Do 6 runs over buf1, or-ing the result into buf2 each
884 		 * time, to make sure we're setting each byte that we mean
885 		 * to set. */
886 		for (i=0;i<8;++i) {
887 			memset(buf1, 0, sizeof(buf1));
888 			evutil_secure_rng_get_bytes(buf1 + startpoint,
889 			    endpoint-startpoint);
890 			n += endpoint - startpoint;
891 			for (j=0; j<32; ++j) {
892 				if (j >= startpoint && j < endpoint) {
893 					buf2[j] |= buf1[j];
894 					++counts[(unsigned char)buf1[j]];
895 				} else {
896 					tt_assert(buf1[j] == 0);
897 					tt_int_op(buf1[j], ==, 0);
898 
899 				}
900 			}
901 		}
902 
903 		/* This will give a false positive with P=(256**8)==(2**64)
904 		 * for each character. */
905 		for (j=startpoint;j<endpoint;++j) {
906 			tt_int_op(buf2[j], !=, 0);
907 		}
908 	}
909 
910 	evutil_weakrand_seed_(&seed, 0);
911 	for (i = 0; i < 10000; ++i) {
912 		ev_int32_t r = evutil_weakrand_range_(&seed, 9999);
913 		tt_int_op(0, <=, r);
914 		tt_int_op(r, <, 9999);
915 	}
916 
917 	/* for (i=0;i<256;++i) { printf("%3d %2d\n", i, counts[i]); } */
918 end:
919 	;
920 }
921 
922 static void
923 test_evutil_getaddrinfo(void *arg)
924 {
925 	struct evutil_addrinfo *ai = NULL, *a;
926 	struct evutil_addrinfo hints;
927 	int r;
928 
929 	/* Try using it as a pton. */
930 	memset(&hints, 0, sizeof(hints));
931 	hints.ai_family = PF_UNSPEC;
932 	hints.ai_socktype = SOCK_STREAM;
933 	r = evutil_getaddrinfo("1.2.3.4", "8080", &hints, &ai);
934 	tt_int_op(r, ==, 0);
935 	tt_assert(ai);
936 	tt_ptr_op(ai->ai_next, ==, NULL); /* no ambiguity */
937 	test_ai_eq(ai, "1.2.3.4:8080", SOCK_STREAM, IPPROTO_TCP);
938 	evutil_freeaddrinfo(ai);
939 	ai = NULL;
940 
941 	memset(&hints, 0, sizeof(hints));
942 	hints.ai_family = PF_UNSPEC;
943 	hints.ai_protocol = IPPROTO_UDP;
944 	r = evutil_getaddrinfo("1001:b0b::f00f", "4321", &hints, &ai);
945 	tt_int_op(r, ==, 0);
946 	tt_assert(ai);
947 	tt_ptr_op(ai->ai_next, ==, NULL); /* no ambiguity */
948 	test_ai_eq(ai, "[1001:b0b::f00f]:4321", SOCK_DGRAM, IPPROTO_UDP);
949 	evutil_freeaddrinfo(ai);
950 	ai = NULL;
951 
952 	/* Try out the behavior of nodename=NULL */
953 	memset(&hints, 0, sizeof(hints));
954 	hints.ai_family = PF_INET;
955 	hints.ai_protocol = IPPROTO_TCP;
956 	hints.ai_flags = EVUTIL_AI_PASSIVE; /* as if for bind */
957 	r = evutil_getaddrinfo(NULL, "9999", &hints, &ai);
958 	tt_int_op(r,==,0);
959 	tt_assert(ai);
960 	tt_ptr_op(ai->ai_next, ==, NULL);
961 	test_ai_eq(ai, "0.0.0.0:9999", SOCK_STREAM, IPPROTO_TCP);
962 	evutil_freeaddrinfo(ai);
963 	ai = NULL;
964 	hints.ai_flags = 0; /* as if for connect */
965 	r = evutil_getaddrinfo(NULL, "9998", &hints, &ai);
966 	tt_assert(ai);
967 	tt_int_op(r,==,0);
968 	test_ai_eq(ai, "127.0.0.1:9998", SOCK_STREAM, IPPROTO_TCP);
969 	tt_ptr_op(ai->ai_next, ==, NULL);
970 	evutil_freeaddrinfo(ai);
971 	ai = NULL;
972 
973 	hints.ai_flags = 0; /* as if for connect */
974 	hints.ai_family = PF_INET6;
975 	r = evutil_getaddrinfo(NULL, "9997", &hints, &ai);
976 	tt_assert(ai);
977 	tt_int_op(r,==,0);
978 	tt_ptr_op(ai->ai_next, ==, NULL);
979 	test_ai_eq(ai, "[::1]:9997", SOCK_STREAM, IPPROTO_TCP);
980 	evutil_freeaddrinfo(ai);
981 	ai = NULL;
982 
983 	hints.ai_flags = EVUTIL_AI_PASSIVE; /* as if for bind. */
984 	hints.ai_family = PF_INET6;
985 	r = evutil_getaddrinfo(NULL, "9996", &hints, &ai);
986 	tt_assert(ai);
987 	tt_int_op(r,==,0);
988 	tt_ptr_op(ai->ai_next, ==, NULL);
989 	test_ai_eq(ai, "[::]:9996", SOCK_STREAM, IPPROTO_TCP);
990 	evutil_freeaddrinfo(ai);
991 	ai = NULL;
992 
993 	/* Now try an unspec one. We should get a v6 and a v4. */
994 	hints.ai_family = PF_UNSPEC;
995 	r = evutil_getaddrinfo(NULL, "9996", &hints, &ai);
996 	tt_assert(ai);
997 	tt_int_op(r,==,0);
998 	a = ai_find_by_family(ai, PF_INET6);
999 	tt_assert(a);
1000 	test_ai_eq(a, "[::]:9996", SOCK_STREAM, IPPROTO_TCP);
1001 	a = ai_find_by_family(ai, PF_INET);
1002 	tt_assert(a);
1003 	test_ai_eq(a, "0.0.0.0:9996", SOCK_STREAM, IPPROTO_TCP);
1004 	evutil_freeaddrinfo(ai);
1005 	ai = NULL;
1006 
1007 	/* Try out AI_NUMERICHOST: successful case.  Also try
1008 	 * multiprotocol. */
1009 	memset(&hints, 0, sizeof(hints));
1010 	hints.ai_family = PF_UNSPEC;
1011 	hints.ai_flags = EVUTIL_AI_NUMERICHOST;
1012 	r = evutil_getaddrinfo("1.2.3.4", NULL, &hints, &ai);
1013 	tt_int_op(r, ==, 0);
1014 	a = ai_find_by_protocol(ai, IPPROTO_TCP);
1015 	tt_assert(a);
1016 	test_ai_eq(a, "1.2.3.4", SOCK_STREAM, IPPROTO_TCP);
1017 	a = ai_find_by_protocol(ai, IPPROTO_UDP);
1018 	tt_assert(a);
1019 	test_ai_eq(a, "1.2.3.4", SOCK_DGRAM, IPPROTO_UDP);
1020 	evutil_freeaddrinfo(ai);
1021 	ai = NULL;
1022 
1023 	/* Try the failing case of AI_NUMERICHOST */
1024 	memset(&hints, 0, sizeof(hints));
1025 	hints.ai_family = PF_UNSPEC;
1026 	hints.ai_flags = EVUTIL_AI_NUMERICHOST;
1027 	r = evutil_getaddrinfo("www.google.com", "80", &hints, &ai);
1028 	tt_int_op(r, ==, EVUTIL_EAI_NONAME);
1029 	tt_ptr_op(ai, ==, NULL);
1030 
1031 	/* Try symbolic service names wit AI_NUMERICSERV */
1032 	memset(&hints, 0, sizeof(hints));
1033 	hints.ai_family = PF_UNSPEC;
1034 	hints.ai_socktype = SOCK_STREAM;
1035 	hints.ai_flags = EVUTIL_AI_NUMERICSERV;
1036 	r = evutil_getaddrinfo("1.2.3.4", "http", &hints, &ai);
1037 	tt_int_op(r,==,EVUTIL_EAI_NONAME);
1038 
1039 	/* Try symbolic service names */
1040 	memset(&hints, 0, sizeof(hints));
1041 	hints.ai_family = PF_UNSPEC;
1042 	hints.ai_socktype = SOCK_STREAM;
1043 	r = evutil_getaddrinfo("1.2.3.4", "http", &hints, &ai);
1044 	if (r!=0) {
1045 		TT_DECLARE("SKIP", ("Symbolic service names seem broken."));
1046 	} else {
1047 		tt_assert(ai);
1048 		test_ai_eq(ai, "1.2.3.4:80", SOCK_STREAM, IPPROTO_TCP);
1049 		evutil_freeaddrinfo(ai);
1050 		ai = NULL;
1051 	}
1052 
1053 end:
1054 	if (ai)
1055 		evutil_freeaddrinfo(ai);
1056 }
1057 
1058 static void
1059 test_evutil_getaddrinfo_live(void *arg)
1060 {
1061 	struct evutil_addrinfo *ai = NULL;
1062 	struct evutil_addrinfo hints;
1063 
1064 	struct sockaddr_in6 *sin6;
1065 	struct sockaddr_in *sin;
1066 	char buf[128];
1067 	const char *cp;
1068 	int r;
1069 
1070 	/* Now do some actual lookups. */
1071 	memset(&hints, 0, sizeof(hints));
1072 	hints.ai_family = PF_INET;
1073 	hints.ai_protocol = IPPROTO_TCP;
1074 	hints.ai_socktype = SOCK_STREAM;
1075 	r = evutil_getaddrinfo("www.google.com", "80", &hints, &ai);
1076 	if (r != 0) {
1077 		TT_DECLARE("SKIP", ("Couldn't resolve www.google.com"));
1078 	} else {
1079 		tt_assert(ai);
1080 		tt_int_op(ai->ai_family, ==, PF_INET);
1081 		tt_int_op(ai->ai_protocol, ==, IPPROTO_TCP);
1082 		tt_int_op(ai->ai_socktype, ==, SOCK_STREAM);
1083 		tt_int_op(ai->ai_addrlen, ==, sizeof(struct sockaddr_in));
1084 		sin = (struct sockaddr_in*)ai->ai_addr;
1085 		tt_int_op(sin->sin_family, ==, AF_INET);
1086 		tt_int_op(sin->sin_port, ==, htons(80));
1087 		tt_int_op(sin->sin_addr.s_addr, !=, 0xffffffff);
1088 
1089 		cp = evutil_inet_ntop(AF_INET, &sin->sin_addr, buf, sizeof(buf));
1090 		TT_BLATHER(("www.google.com resolved to %s",
1091 			cp?cp:"<unwriteable>"));
1092 		evutil_freeaddrinfo(ai);
1093 		ai = NULL;
1094 	}
1095 
1096 	hints.ai_family = PF_INET6;
1097 	r = evutil_getaddrinfo("ipv6.google.com", "80", &hints, &ai);
1098 	if (r != 0) {
1099 		TT_BLATHER(("Couldn't do an ipv6 lookup for ipv6.google.com"));
1100 	} else {
1101 		tt_assert(ai);
1102 		tt_int_op(ai->ai_family, ==, PF_INET6);
1103 		tt_int_op(ai->ai_addrlen, ==, sizeof(struct sockaddr_in6));
1104 		sin6 = (struct sockaddr_in6*)ai->ai_addr;
1105 		tt_int_op(sin6->sin6_port, ==, htons(80));
1106 
1107 		cp = evutil_inet_ntop(AF_INET6, &sin6->sin6_addr, buf,
1108 		    sizeof(buf));
1109 		TT_BLATHER(("ipv6.google.com resolved to %s",
1110 			cp?cp:"<unwriteable>"));
1111 	}
1112 
1113 end:
1114 	if (ai)
1115 		evutil_freeaddrinfo(ai);
1116 }
1117 
1118 #ifdef _WIN32
1119 static void
1120 test_evutil_loadsyslib(void *arg)
1121 {
1122 	HANDLE h=NULL;
1123 
1124 	h = evutil_load_windows_system_library_(TEXT("kernel32.dll"));
1125 	tt_assert(h);
1126 
1127 end:
1128 	if (h)
1129 		CloseHandle(h);
1130 
1131 }
1132 #endif
1133 
1134 /** Test mm_malloc(). */
1135 static void
1136 test_event_malloc(void *arg)
1137 {
1138 	void *p = NULL;
1139 	(void)arg;
1140 
1141 	/* mm_malloc(0) should simply return NULL. */
1142 #ifndef EVENT__DISABLE_MM_REPLACEMENT
1143 	errno = 0;
1144 	p = mm_malloc(0);
1145 	tt_assert(p == NULL);
1146 	tt_int_op(errno, ==, 0);
1147 #endif
1148 
1149 	/* Trivial case. */
1150 	errno = 0;
1151 	p = mm_malloc(8);
1152 	tt_assert(p != NULL);
1153 	tt_int_op(errno, ==, 0);
1154 	mm_free(p);
1155 
1156  end:
1157 	errno = 0;
1158 	return;
1159 }
1160 
1161 static void
1162 test_event_calloc(void *arg)
1163 {
1164 	void *p = NULL;
1165 	(void)arg;
1166 
1167 #ifndef EVENT__DISABLE_MM_REPLACEMENT
1168 	/* mm_calloc() should simply return NULL
1169 	 * if either argument is zero. */
1170 	errno = 0;
1171 	p = mm_calloc(0, 0);
1172 	tt_assert(p == NULL);
1173 	tt_int_op(errno, ==, 0);
1174 	errno = 0;
1175 	p = mm_calloc(0, 1);
1176 	tt_assert(p == NULL);
1177 	tt_int_op(errno, ==, 0);
1178 	errno = 0;
1179 	p = mm_calloc(1, 0);
1180 	tt_assert(p == NULL);
1181 	tt_int_op(errno, ==, 0);
1182 #endif
1183 
1184 	/* Trivial case. */
1185 	errno = 0;
1186 	p = mm_calloc(8, 8);
1187 	tt_assert(p != NULL);
1188 	tt_int_op(errno, ==, 0);
1189 	mm_free(p);
1190 	p = NULL;
1191 
1192 	/* mm_calloc() should set errno = ENOMEM and return NULL
1193 	 * in case of potential overflow. */
1194 	errno = 0;
1195 	p = mm_calloc(EV_SIZE_MAX/2, EV_SIZE_MAX/2 + 8);
1196 	tt_assert(p == NULL);
1197 	tt_int_op(errno, ==, ENOMEM);
1198 
1199  end:
1200 	errno = 0;
1201 	if (p)
1202 		mm_free(p);
1203 
1204 	return;
1205 }
1206 
1207 static void
1208 test_event_strdup(void *arg)
1209 {
1210 	void *p = NULL;
1211 	(void)arg;
1212 
1213 #ifndef EVENT__DISABLE_MM_REPLACEMENT
1214 	/* mm_strdup(NULL) should set errno = EINVAL and return NULL. */
1215 	errno = 0;
1216 	p = mm_strdup(NULL);
1217 	tt_assert(p == NULL);
1218 	tt_int_op(errno, ==, EINVAL);
1219 #endif
1220 
1221 	/* Trivial cases. */
1222 
1223 	errno = 0;
1224 	p = mm_strdup("");
1225 	tt_assert(p != NULL);
1226 	tt_int_op(errno, ==, 0);
1227 	tt_str_op(p, ==, "");
1228 	mm_free(p);
1229 
1230 	errno = 0;
1231 	p = mm_strdup("foo");
1232 	tt_assert(p != NULL);
1233 	tt_int_op(errno, ==, 0);
1234 	tt_str_op(p, ==, "foo");
1235 	mm_free(p);
1236 
1237 	/* XXX
1238 	 * mm_strdup(str) where str is a string of length EV_SIZE_MAX
1239 	 * should set errno = ENOMEM and return NULL. */
1240 
1241  end:
1242 	errno = 0;
1243 	return;
1244 }
1245 
1246 static void
1247 test_evutil_usleep(void *arg)
1248 {
1249 	struct timeval tv1, tv2, tv3, diff1, diff2;
1250 	const struct timeval quarter_sec = {0, 250*1000};
1251 	const struct timeval tenth_sec = {0, 100*1000};
1252 	long usec1, usec2;
1253 
1254 	evutil_gettimeofday(&tv1, NULL);
1255 	evutil_usleep_(&quarter_sec);
1256 	evutil_gettimeofday(&tv2, NULL);
1257 	evutil_usleep_(&tenth_sec);
1258 	evutil_gettimeofday(&tv3, NULL);
1259 
1260 	evutil_timersub(&tv2, &tv1, &diff1);
1261 	evutil_timersub(&tv3, &tv2, &diff2);
1262 	usec1 = diff1.tv_sec * 1000000 + diff1.tv_usec;
1263 	usec2 = diff2.tv_sec * 1000000 + diff2.tv_usec;
1264 
1265 	tt_int_op(usec1, >, 200000);
1266 	tt_int_op(usec1, <, 300000);
1267 	tt_int_op(usec2, >,  80000);
1268 	tt_int_op(usec2, <, 120000);
1269 
1270 end:
1271 	;
1272 }
1273 
1274 static void
1275 test_evutil_monotonic_res(void *data_)
1276 {
1277 	/* Basic santity-test for monotonic timers.  What we'd really like
1278 	 * to do is make sure that they can't go backwards even when the
1279 	 * system clock goes backwards. But we haven't got a good way to
1280 	 * move the system clock backwards.
1281 	 */
1282 	struct basic_test_data *data = data_;
1283 	struct evutil_monotonic_timer timer;
1284 	const int precise = strstr(data->setup_data, "precise") != NULL;
1285 	const int fallback = strstr(data->setup_data, "fallback") != NULL;
1286 	struct timeval tv[10], delay;
1287 	int total_diff = 0;
1288 
1289 	int flags = 0, wantres, acceptdiff, i;
1290 	if (precise)
1291 		flags |= EV_MONOT_PRECISE;
1292 	if (fallback)
1293 		flags |= EV_MONOT_FALLBACK;
1294 	if (precise || fallback) {
1295 #ifdef _WIN32
1296 		wantres = 10*1000;
1297 		acceptdiff = 1000;
1298 #else
1299 		wantres = 1000;
1300 		acceptdiff = 300;
1301 #endif
1302 	} else {
1303 		wantres = 40*1000;
1304 		acceptdiff = 20*1000;
1305 	}
1306 
1307 	TT_BLATHER(("Precise = %d", precise));
1308 	TT_BLATHER(("Fallback = %d", fallback));
1309 
1310 	/* First, make sure we match up with usleep. */
1311 
1312 	delay.tv_sec = 0;
1313 	delay.tv_usec = wantres;
1314 
1315 	tt_int_op(evutil_configure_monotonic_time_(&timer, flags), ==, 0);
1316 
1317 	for (i = 0; i < 10; ++i) {
1318 		evutil_gettime_monotonic_(&timer, &tv[i]);
1319 		evutil_usleep_(&delay);
1320 	}
1321 
1322 	for (i = 0; i < 9; ++i) {
1323 		struct timeval diff;
1324 		tt_assert(evutil_timercmp(&tv[i], &tv[i+1], <));
1325 		evutil_timersub(&tv[i+1], &tv[i], &diff);
1326 		tt_int_op(diff.tv_sec, ==, 0);
1327 		total_diff += diff.tv_usec;
1328 		TT_BLATHER(("Difference = %d", (int)diff.tv_usec));
1329 	}
1330 	tt_int_op(abs(total_diff/9 - wantres), <, acceptdiff);
1331 
1332 end:
1333 	;
1334 }
1335 
1336 static void
1337 test_evutil_monotonic_prc(void *data_)
1338 {
1339 	struct basic_test_data *data = data_;
1340 	struct evutil_monotonic_timer timer;
1341 	const int precise = strstr(data->setup_data, "precise") != NULL;
1342 	const int fallback = strstr(data->setup_data, "fallback") != NULL;
1343 	struct timeval tv[10];
1344 	int total_diff = 0;
1345 	int i, maxstep = 25*1000,flags=0;
1346 	if (precise)
1347 		maxstep = 500;
1348 	if (precise)
1349 		flags |= EV_MONOT_PRECISE;
1350 	if (fallback)
1351 		flags |= EV_MONOT_FALLBACK;
1352 	tt_int_op(evutil_configure_monotonic_time_(&timer, flags), ==, 0);
1353 
1354 	/* find out what precision we actually see. */
1355 
1356 	evutil_gettime_monotonic_(&timer, &tv[0]);
1357 	for (i = 1; i < 10; ++i) {
1358 		do {
1359 			evutil_gettime_monotonic_(&timer, &tv[i]);
1360 		} while (evutil_timercmp(&tv[i-1], &tv[i], ==));
1361 	}
1362 
1363 	total_diff = 0;
1364 	for (i = 0; i < 9; ++i) {
1365 		struct timeval diff;
1366 		tt_assert(evutil_timercmp(&tv[i], &tv[i+1], <));
1367 		evutil_timersub(&tv[i+1], &tv[i], &diff);
1368 		tt_int_op(diff.tv_sec, ==, 0);
1369 		total_diff += diff.tv_usec;
1370 		TT_BLATHER(("Step difference = %d", (int)diff.tv_usec));
1371 	}
1372 	TT_BLATHER(("Average step difference = %d", total_diff / 9));
1373 	tt_int_op(total_diff/9, <, maxstep);
1374 
1375 end:
1376 	;
1377 }
1378 
1379 struct testcase_t util_testcases[] = {
1380 	{ "ipv4_parse", regress_ipv4_parse, 0, NULL, NULL },
1381 	{ "ipv6_parse", regress_ipv6_parse, 0, NULL, NULL },
1382 	{ "sockaddr_port_parse", regress_sockaddr_port_parse, 0, NULL, NULL },
1383 	{ "sockaddr_port_format", regress_sockaddr_port_format, 0, NULL, NULL },
1384 	{ "sockaddr_predicates", test_evutil_sockaddr_predicates, 0,NULL,NULL },
1385 	{ "evutil_snprintf", test_evutil_snprintf, 0, NULL, NULL },
1386 	{ "evutil_strtoll", test_evutil_strtoll, 0, NULL, NULL },
1387 	{ "evutil_casecmp", test_evutil_casecmp, 0, NULL, NULL },
1388 	{ "evutil_rtrim", test_evutil_rtrim, 0, NULL, NULL },
1389 	{ "strlcpy", test_evutil_strlcpy, 0, NULL, NULL },
1390 	{ "log", test_evutil_log, TT_FORK, NULL, NULL },
1391 	{ "upcast", test_evutil_upcast, 0, NULL, NULL },
1392 	{ "integers", test_evutil_integers, 0, NULL, NULL },
1393 	{ "rand", test_evutil_rand, TT_FORK, NULL, NULL },
1394 	{ "getaddrinfo", test_evutil_getaddrinfo, TT_FORK, NULL, NULL },
1395 	{ "getaddrinfo_live", test_evutil_getaddrinfo_live, TT_FORK|TT_OFF_BY_DEFAULT, NULL, NULL },
1396 #ifdef _WIN32
1397 	{ "loadsyslib", test_evutil_loadsyslib, TT_FORK, NULL, NULL },
1398 #endif
1399 	{ "mm_malloc", test_event_malloc, 0, NULL, NULL },
1400 	{ "mm_calloc", test_event_calloc, 0, NULL, NULL },
1401 	{ "mm_strdup", test_event_strdup, 0, NULL, NULL },
1402 	{ "usleep", test_evutil_usleep, 0, NULL, NULL },
1403 	{ "monotonic_res", test_evutil_monotonic_res, 0, &basic_setup, (void*)"" },
1404 	{ "monotonic_res_precise", test_evutil_monotonic_res, TT_OFF_BY_DEFAULT, &basic_setup, (void*)"precise" },
1405 	{ "monotonic_res_fallback", test_evutil_monotonic_res, TT_OFF_BY_DEFAULT, &basic_setup, (void*)"fallback" },
1406 	{ "monotonic_prc", test_evutil_monotonic_prc, 0, &basic_setup, (void*)"" },
1407 	{ "monotonic_prc_precise", test_evutil_monotonic_prc, 0, &basic_setup, (void*)"precise" },
1408 	{ "monotonic_prc_fallback", test_evutil_monotonic_prc, 0, &basic_setup, (void*)"fallback" },
1409 	END_OF_TESTCASES,
1410 };
1411 
1412