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