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