]> arthur.barton.de Git - netatalk.git/blob - libevent/test/regress_util.c
Add libevent
[netatalk.git] / libevent / test / regress_util.c
1 /*
2  * Copyright (c) 2009-2010 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 #ifdef WIN32
27 #include <winsock2.h>
28 #include <windows.h>
29 #include <ws2tcpip.h>
30 #endif
31
32 #include "event2/event-config.h"
33
34 #include <sys/types.h>
35
36 #ifndef WIN32
37 #include <sys/socket.h>
38 #include <netinet/in.h>
39 #include <arpa/inet.h>
40 #include <unistd.h>
41 #endif
42 #ifdef _EVENT_HAVE_NETINET_IN6_H
43 #include <netinet/in6.h>
44 #endif
45 #ifdef _EVENT_HAVE_SYS_WAIT_H
46 #include <sys/wait.h>
47 #endif
48 #include <signal.h>
49 #include <stdio.h>
50 #include <stdlib.h>
51 #include <string.h>
52
53 #include "event2/event.h"
54 #include "event2/util.h"
55 #include "../ipv6-internal.h"
56 #include "../util-internal.h"
57 #include "../log-internal.h"
58 #include "../strlcpy-internal.h"
59
60 #include "regress.h"
61
62 enum entry_status { NORMAL, CANONICAL, BAD };
63
64 /* This is a big table of results we expect from generating and parsing */
65 static struct ipv4_entry {
66         const char *addr;
67         ev_uint32_t res;
68         enum entry_status status;
69 } ipv4_entries[] = {
70         { "1.2.3.4", 0x01020304u, CANONICAL },
71         { "255.255.255.255", 0xffffffffu, CANONICAL },
72         { "256.0.0.0", 0, BAD },
73         { "ABC", 0, BAD },
74         { "1.2.3.4.5", 0, BAD },
75         { "176.192.208.244", 0xb0c0d0f4, CANONICAL },
76         { NULL, 0, BAD },
77 };
78
79 static struct ipv6_entry {
80         const char *addr;
81         ev_uint32_t res[4];
82         enum entry_status status;
83 } ipv6_entries[] = {
84         { "::", { 0, 0, 0, 0, }, CANONICAL },
85         { "0:0:0:0:0:0:0:0", { 0, 0, 0, 0, }, NORMAL },
86         { "::1", { 0, 0, 0, 1, }, CANONICAL },
87         { "::1.2.3.4", { 0, 0, 0, 0x01020304, }, CANONICAL },
88         { "ffff:1::", { 0xffff0001u, 0, 0, 0, }, CANONICAL },
89         { "ffff:0000::", { 0xffff0000u, 0, 0, 0, }, NORMAL },
90         { "ffff::1234", { 0xffff0000u, 0, 0, 0x1234, }, CANONICAL },
91         { "0102::1.2.3.4", {0x01020000u, 0, 0, 0x01020304u }, NORMAL },
92         { "::9:c0a8:1:1", { 0, 0, 0x0009c0a8u, 0x00010001u }, CANONICAL },
93         { "::ffff:1.2.3.4", { 0, 0, 0x000ffffu, 0x01020304u }, CANONICAL },
94         { "FFFF::", { 0xffff0000u, 0, 0, 0 }, NORMAL },
95         { "foobar.", { 0, 0, 0, 0 }, BAD },
96         { "foobar", { 0, 0, 0, 0 }, BAD },
97         { "fo:obar", { 0, 0, 0, 0 }, BAD },
98         { "ffff", { 0, 0, 0, 0 }, BAD },
99         { "fffff::", { 0, 0, 0, 0 }, BAD },
100         { "fffff::", { 0, 0, 0, 0 }, BAD },
101         { "::1.0.1.1000", { 0, 0, 0, 0 }, BAD },
102         { "1:2:33333:4::", { 0, 0, 0, 0 }, BAD },
103         { "1:2:3:4:5:6:7:8:9", { 0, 0, 0, 0 }, BAD },
104         { "1::2::3", { 0, 0, 0, 0 }, BAD },
105         { ":::1", { 0, 0, 0, 0 }, BAD },
106         { NULL, { 0, 0, 0, 0,  }, BAD },
107 };
108
109 static void
110 regress_ipv4_parse(void *ptr)
111 {
112         int i;
113         for (i = 0; ipv4_entries[i].addr; ++i) {
114                 char written[128];
115                 struct ipv4_entry *ent = &ipv4_entries[i];
116                 struct in_addr in;
117                 int r;
118                 r = evutil_inet_pton(AF_INET, ent->addr, &in);
119                 if (r == 0) {
120                         if (ent->status != BAD) {
121                                 TT_FAIL(("%s did not parse, but it's a good address!",
122                                         ent->addr));
123                         }
124                         continue;
125                 }
126                 if (ent->status == BAD) {
127                         TT_FAIL(("%s parsed, but we expected an error", ent->addr));
128                         continue;
129                 }
130                 if (ntohl(in.s_addr) != ent->res) {
131                         TT_FAIL(("%s parsed to %lx, but we expected %lx", ent->addr,
132                                 (unsigned long)ntohl(in.s_addr),
133                                 (unsigned long)ent->res));
134                         continue;
135                 }
136                 if (ent->status == CANONICAL) {
137                         const char *w = evutil_inet_ntop(AF_INET, &in, written,
138                                                                                          sizeof(written));
139                         if (!w) {
140                                 TT_FAIL(("Tried to write out %s; got NULL.", ent->addr));
141                                 continue;
142                         }
143                         if (strcmp(written, ent->addr)) {
144                                 TT_FAIL(("Tried to write out %s; got %s",
145                                         ent->addr, written));
146                                 continue;
147                         }
148                 }
149
150         }
151
152 }
153
154 static void
155 regress_ipv6_parse(void *ptr)
156 {
157 #ifdef AF_INET6
158         int i, j;
159
160         for (i = 0; ipv6_entries[i].addr; ++i) {
161                 char written[128];
162                 struct ipv6_entry *ent = &ipv6_entries[i];
163                 struct in6_addr in6;
164                 int r;
165                 r = evutil_inet_pton(AF_INET6, ent->addr, &in6);
166                 if (r == 0) {
167                         if (ent->status != BAD)
168                                 TT_FAIL(("%s did not parse, but it's a good address!",
169                                         ent->addr));
170                         continue;
171                 }
172                 if (ent->status == BAD) {
173                         TT_FAIL(("%s parsed, but we expected an error", ent->addr));
174                         continue;
175                 }
176                 for (j = 0; j < 4; ++j) {
177                         /* Can't use s6_addr32 here; some don't have it. */
178                         ev_uint32_t u =
179                                 (in6.s6_addr[j*4  ] << 24) |
180                                 (in6.s6_addr[j*4+1] << 16) |
181                                 (in6.s6_addr[j*4+2] << 8) |
182                                 (in6.s6_addr[j*4+3]);
183                         if (u != ent->res[j]) {
184                                 TT_FAIL(("%s did not parse as expected.", ent->addr));
185                                 continue;
186                         }
187                 }
188                 if (ent->status == CANONICAL) {
189                         const char *w = evutil_inet_ntop(AF_INET6, &in6, written,
190                                                                                          sizeof(written));
191                         if (!w) {
192                                 TT_FAIL(("Tried to write out %s; got NULL.", ent->addr));
193                                 continue;
194                         }
195                         if (strcmp(written, ent->addr)) {
196                                 TT_FAIL(("Tried to write out %s; got %s", ent->addr, written));
197                                 continue;
198                         }
199                 }
200
201         }
202 #else
203         TT_BLATHER(("Skipping IPv6 address parsing."));
204 #endif
205 }
206
207 static struct sa_port_ent {
208         const char *parse;
209         int safamily;
210         const char *addr;
211         int port;
212 } sa_port_ents[] = {
213         { "[ffff::1]:1000", AF_INET6, "ffff::1", 1000 },
214         { "[ffff::1]", AF_INET6, "ffff::1", 0 },
215         { "[ffff::1", 0, NULL, 0 },
216         { "[ffff::1]:65599", 0, NULL, 0 },
217         { "[ffff::1]:0", 0, NULL, 0 },
218         { "[ffff::1]:-1", 0, NULL, 0 },
219         { "::1", AF_INET6, "::1", 0 },
220         { "1:2::1", AF_INET6, "1:2::1", 0 },
221         { "192.168.0.1:50", AF_INET, "192.168.0.1", 50 },
222         { "1.2.3.4", AF_INET, "1.2.3.4", 0 },
223         { NULL, 0, NULL, 0 },
224 };
225
226 static void
227 regress_sockaddr_port_parse(void *ptr)
228 {
229         struct sockaddr_storage ss;
230         int i, r;
231
232         for (i = 0; sa_port_ents[i].parse; ++i) {
233                 struct sa_port_ent *ent = &sa_port_ents[i];
234                 int len = sizeof(ss);
235                 memset(&ss, 0, sizeof(ss));
236                 r = evutil_parse_sockaddr_port(ent->parse, (struct sockaddr*)&ss, &len);
237                 if (r < 0) {
238                         if (ent->safamily)
239                                 TT_FAIL(("Couldn't parse %s!", ent->parse));
240                         continue;
241                 } else if (! ent->safamily) {
242                         TT_FAIL(("Shouldn't have been able to parse %s!", ent->parse));
243                         continue;
244                 }
245                 if (ent->safamily == AF_INET) {
246                         struct sockaddr_in sin;
247                         memset(&sin, 0, sizeof(sin));
248 #ifdef _EVENT_HAVE_STRUCT_SOCKADDR_IN_SIN_LEN
249                         sin.sin_len = sizeof(sin);
250 #endif
251                         sin.sin_family = AF_INET;
252                         sin.sin_port = htons(ent->port);
253                         r = evutil_inet_pton(AF_INET, ent->addr, &sin.sin_addr);
254                         if (1 != r) {
255                                 TT_FAIL(("Couldn't parse ipv4 target %s.", ent->addr));
256                         } else if (memcmp(&sin, &ss, sizeof(sin))) {
257                                 TT_FAIL(("Parse for %s was not as expected.", ent->parse));
258                         } else if (len != sizeof(sin)) {
259                                 TT_FAIL(("Length for %s not as expected.",ent->parse));
260                         }
261                 } else {
262                         struct sockaddr_in6 sin6;
263                         memset(&sin6, 0, sizeof(sin6));
264 #ifdef _EVENT_HAVE_STRUCT_SOCKADDR_IN6_SIN6_LEN
265                         sin6.sin6_len = sizeof(sin6);
266 #endif
267                         sin6.sin6_family = AF_INET6;
268                         sin6.sin6_port = htons(ent->port);
269                         r = evutil_inet_pton(AF_INET6, ent->addr, &sin6.sin6_addr);
270                         if (1 != r) {
271                                 TT_FAIL(("Couldn't parse ipv6 target %s.", ent->addr));
272                         } else if (memcmp(&sin6, &ss, sizeof(sin6))) {
273                                 TT_FAIL(("Parse for %s was not as expected.", ent->parse));
274                         } else if (len != sizeof(sin6)) {
275                                 TT_FAIL(("Length for %s not as expected.",ent->parse));
276                         }
277                 }
278         }
279 }
280
281
282 static void
283 regress_sockaddr_port_format(void *ptr)
284 {
285         struct sockaddr_storage ss;
286         int len;
287         const char *cp;
288         char cbuf[128];
289         int r;
290
291         len = sizeof(ss);
292         r = evutil_parse_sockaddr_port("192.168.1.1:80",
293             (struct sockaddr*)&ss, &len);
294         tt_int_op(r,==,0);
295         cp = evutil_format_sockaddr_port(
296                 (struct sockaddr*)&ss, cbuf, sizeof(cbuf));
297         tt_ptr_op(cp,==,cbuf);
298         tt_str_op(cp,==,"192.168.1.1:80");
299
300         len = sizeof(ss);
301         r = evutil_parse_sockaddr_port("[ff00::8010]:999",
302             (struct sockaddr*)&ss, &len);
303         tt_int_op(r,==,0);
304         cp = evutil_format_sockaddr_port(
305                 (struct sockaddr*)&ss, cbuf, sizeof(cbuf));
306         tt_ptr_op(cp,==,cbuf);
307         tt_str_op(cp,==,"[ff00::8010]:999");
308
309         ss.ss_family=99;
310         cp = evutil_format_sockaddr_port(
311                 (struct sockaddr*)&ss, cbuf, sizeof(cbuf));
312         tt_ptr_op(cp,==,cbuf);
313         tt_str_op(cp,==,"<addr with socktype 99>");
314 end:
315         ;
316 }
317
318 static struct sa_pred_ent {
319         const char *parse;
320
321         int is_loopback;
322 } sa_pred_entries[] = {
323         { "127.0.0.1",   1 },
324         { "127.0.3.2",   1 },
325         { "128.1.2.3",   0 },
326         { "18.0.0.1",    0 },
327         { "129.168.1.1", 0 },
328
329         { "::1",         1 },
330         { "::0",         0 },
331         { "f::1",        0 },
332         { "::501",       0 },
333         { NULL,          0 },
334
335 };
336
337 static void
338 test_evutil_sockaddr_predicates(void *ptr)
339 {
340         struct sockaddr_storage ss;
341         int r, i;
342
343         for (i=0; sa_pred_entries[i].parse; ++i) {
344                 struct sa_pred_ent *ent = &sa_pred_entries[i];
345                 int len = sizeof(ss);
346
347                 r = evutil_parse_sockaddr_port(ent->parse, (struct sockaddr*)&ss, &len);
348
349                 if (r<0) {
350                         TT_FAIL(("Couldn't parse %s!", ent->parse));
351                         continue;
352                 }
353
354                 /* sockaddr_is_loopback */
355                 if (ent->is_loopback != evutil_sockaddr_is_loopback((struct sockaddr*)&ss)) {
356                         TT_FAIL(("evutil_sockaddr_loopback(%s) not as expected",
357                                 ent->parse));
358                 }
359         }
360 }
361
362 static void
363 test_evutil_strtoll(void *ptr)
364 {
365         const char *s;
366         char *endptr;
367
368         tt_want(evutil_strtoll("5000000000", NULL, 10) ==
369                 ((ev_int64_t)5000000)*1000);
370         tt_want(evutil_strtoll("-5000000000", NULL, 10) ==
371                 ((ev_int64_t)5000000)*-1000);
372         s = " 99999stuff";
373         tt_want(evutil_strtoll(s, &endptr, 10) == (ev_int64_t)99999);
374         tt_want(endptr == s+6);
375         tt_want(evutil_strtoll("foo", NULL, 10) == 0);
376  }
377
378 static void
379 test_evutil_snprintf(void *ptr)
380 {
381         char buf[16];
382         int r;
383         r = evutil_snprintf(buf, sizeof(buf), "%d %d", 50, 100);
384         tt_str_op(buf, ==, "50 100");
385         tt_int_op(r, ==, 6);
386
387         r = evutil_snprintf(buf, sizeof(buf), "longish %d", 1234567890);
388         tt_str_op(buf, ==, "longish 1234567");
389         tt_int_op(r, ==, 18);
390
391       end:
392         ;
393 }
394
395 static void
396 test_evutil_casecmp(void *ptr)
397 {
398         tt_int_op(evutil_ascii_strcasecmp("ABC", "ABC"), ==, 0);
399         tt_int_op(evutil_ascii_strcasecmp("ABC", "abc"), ==, 0);
400         tt_int_op(evutil_ascii_strcasecmp("ABC", "abcd"), <, 0);
401         tt_int_op(evutil_ascii_strcasecmp("ABC", "abb"), >, 0);
402         tt_int_op(evutil_ascii_strcasecmp("ABCd", "abc"), >, 0);
403
404         tt_int_op(evutil_ascii_strncasecmp("Libevent", "LibEvEnT", 100), ==, 0);
405         tt_int_op(evutil_ascii_strncasecmp("Libevent", "LibEvEnT", 4), ==, 0);
406         tt_int_op(evutil_ascii_strncasecmp("Libevent", "LibEXXXX", 4), ==, 0);
407         tt_int_op(evutil_ascii_strncasecmp("Libevent", "LibE", 4), ==, 0);
408         tt_int_op(evutil_ascii_strncasecmp("Libe", "LibEvEnT", 4), ==, 0);
409         tt_int_op(evutil_ascii_strncasecmp("Lib", "LibEvEnT", 4), <, 0);
410         tt_int_op(evutil_ascii_strncasecmp("abc", "def", 99), <, 0);
411         tt_int_op(evutil_ascii_strncasecmp("Z", "qrst", 1), >, 0);
412 end:
413         ;
414 }
415
416 static int logsev = 0;
417 static char *logmsg = NULL;
418
419 static void
420 logfn(int severity, const char *msg)
421 {
422         logsev = severity;
423         tt_want(msg);
424         if (msg) {
425                 if (logmsg)
426                         free(logmsg);
427                 logmsg = strdup(msg);
428         }
429 }
430
431 static int fatal_want_severity = 0;
432 static const char *fatal_want_message = NULL;
433 static void
434 fatalfn(int exitcode)
435 {
436         if (logsev != fatal_want_severity ||
437             !logmsg ||
438             strcmp(logmsg, fatal_want_message))
439                 exit(0);
440         else
441                 exit(exitcode);
442 }
443
444 #ifndef WIN32
445 #define CAN_CHECK_ERR
446 static void
447 check_error_logging(void (*fn)(void), int wantexitcode,
448     int wantseverity, const char *wantmsg)
449 {
450         pid_t pid;
451         int status = 0, exitcode;
452         fatal_want_severity = wantseverity;
453         fatal_want_message = wantmsg;
454         if ((pid = fork()) == 0) {
455                 /* child process */
456                 fn();
457                 exit(0); /* should be unreachable. */
458         } else {
459                 wait(&status);
460                 exitcode = WEXITSTATUS(status);
461                 tt_int_op(wantexitcode, ==, exitcode);
462         }
463 end:
464         ;
465 }
466
467 static void
468 errx_fn(void)
469 {
470         event_errx(2, "Fatal error; too many kumquats (%d)", 5);
471 }
472
473 static void
474 err_fn(void)
475 {
476         errno = ENOENT;
477         event_err(5,"Couldn't open %s", "/very/bad/file");
478 }
479
480 static void
481 sock_err_fn(void)
482 {
483         evutil_socket_t fd = socket(AF_INET, SOCK_STREAM, 0);
484 #ifdef WIN32
485         EVUTIL_SET_SOCKET_ERROR(WSAEWOULDBLOCK);
486 #else
487         errno = EAGAIN;
488 #endif
489         event_sock_err(20, fd, "Unhappy socket");
490 }
491 #endif
492
493 static void
494 test_evutil_log(void *ptr)
495 {
496         evutil_socket_t fd = -1;
497         char buf[128];
498
499         event_set_log_callback(logfn);
500         event_set_fatal_callback(fatalfn);
501 #define RESET() do {                            \
502                 logsev = 0;     \
503                 if (logmsg) free(logmsg);       \
504                 logmsg = NULL;                  \
505         } while (0)
506 #define LOGEQ(sev,msg) do {                     \
507                 tt_int_op(logsev,==,sev);       \
508                 tt_assert(logmsg != NULL);      \
509                 tt_str_op(logmsg,==,msg);       \
510         } while (0)
511
512 #ifdef CAN_CHECK_ERR
513         /* We need to disable these tests for now.  Previously, the logging
514          * module didn't enforce the requirement that a fatal callback
515          * actually exit.  Now, it exits no matter what, so if we wan to
516          * reinstate these tests, we'll need to fork for each one. */
517         check_error_logging(errx_fn, 2, _EVENT_LOG_ERR,
518             "Fatal error; too many kumquats (5)");
519         RESET();
520 #endif
521
522         event_warnx("Far too many %s (%d)", "wombats", 99);
523         LOGEQ(_EVENT_LOG_WARN, "Far too many wombats (99)");
524         RESET();
525
526         event_msgx("Connecting lime to coconut");
527         LOGEQ(_EVENT_LOG_MSG, "Connecting lime to coconut");
528         RESET();
529
530         event_debug(("A millisecond passed! We should log that!"));
531 #ifdef USE_DEBUG
532         LOGEQ(_EVENT_LOG_DEBUG, "A millisecond passed! We should log that!");
533 #else
534         tt_int_op(logsev,==,0);
535         tt_ptr_op(logmsg,==,NULL);
536 #endif
537         RESET();
538
539         /* Try with an errno. */
540         errno = ENOENT;
541         event_warn("Couldn't open %s", "/bad/file");
542         evutil_snprintf(buf, sizeof(buf),
543             "Couldn't open /bad/file: %s",strerror(ENOENT));
544         LOGEQ(_EVENT_LOG_WARN,buf);
545         RESET();
546
547 #ifdef CAN_CHECK_ERR
548         evutil_snprintf(buf, sizeof(buf),
549             "Couldn't open /very/bad/file: %s",strerror(ENOENT));
550         check_error_logging(err_fn, 5, _EVENT_LOG_ERR, buf);
551         RESET();
552 #endif
553
554         /* Try with a socket errno. */
555         fd = socket(AF_INET, SOCK_STREAM, 0);
556 #ifdef WIN32
557         evutil_snprintf(buf, sizeof(buf),
558             "Unhappy socket: %s",
559             evutil_socket_error_to_string(WSAEWOULDBLOCK));
560         EVUTIL_SET_SOCKET_ERROR(WSAEWOULDBLOCK);
561 #else
562         evutil_snprintf(buf, sizeof(buf),
563             "Unhappy socket: %s", strerror(EAGAIN));
564         errno = EAGAIN;
565 #endif
566         event_sock_warn(fd, "Unhappy socket");
567         LOGEQ(_EVENT_LOG_WARN, buf);
568         RESET();
569
570 #ifdef CAN_CHECK_ERR
571         check_error_logging(sock_err_fn, 20, _EVENT_LOG_ERR, buf);
572         RESET();
573 #endif
574
575 #undef RESET
576 #undef LOGEQ
577 end:
578         if (logmsg)
579                 free(logmsg);
580         if (fd >= 0)
581                 evutil_closesocket(fd);
582 }
583
584 static void
585 test_evutil_strlcpy(void *arg)
586 {
587         char buf[8];
588
589         /* Successful case. */
590         tt_int_op(5, ==, strlcpy(buf, "Hello", sizeof(buf)));
591         tt_str_op(buf, ==, "Hello");
592
593         /* Overflow by a lot. */
594         tt_int_op(13, ==, strlcpy(buf, "pentasyllabic", sizeof(buf)));
595         tt_str_op(buf, ==, "pentasy");
596
597         /* Overflow by exactly one. */
598         tt_int_op(8, ==, strlcpy(buf, "overlong", sizeof(buf)));
599         tt_str_op(buf, ==, "overlon");
600 end:
601         ;
602 }
603
604 struct example_struct {
605         const char *a;
606         const char *b;
607         long c;
608 };
609
610 static void
611 test_evutil_upcast(void *arg)
612 {
613         struct example_struct es1;
614         const char **cp;
615         es1.a = "World";
616         es1.b = "Hello";
617         es1.c = -99;
618
619         tt_int_op(evutil_offsetof(struct example_struct, b), ==, sizeof(char*));
620
621         cp = &es1.b;
622         tt_ptr_op(EVUTIL_UPCAST(cp, struct example_struct, b), ==, &es1);
623
624 end:
625         ;
626 }
627
628 static void
629 test_evutil_integers(void *arg)
630 {
631         ev_int64_t i64;
632         ev_uint64_t u64;
633         ev_int32_t i32;
634         ev_uint32_t u32;
635         ev_int16_t i16;
636         ev_uint16_t u16;
637         ev_int8_t  i8;
638         ev_uint8_t  u8;
639
640         void *ptr;
641         ev_intptr_t iptr;
642         ev_uintptr_t uptr;
643
644         ev_ssize_t ssize;
645
646         tt_int_op(sizeof(u64), ==, 8);
647         tt_int_op(sizeof(i64), ==, 8);
648         tt_int_op(sizeof(u32), ==, 4);
649         tt_int_op(sizeof(i32), ==, 4);
650         tt_int_op(sizeof(u16), ==, 2);
651         tt_int_op(sizeof(i16), ==, 2);
652         tt_int_op(sizeof(u8), ==,  1);
653         tt_int_op(sizeof(i8), ==,  1);
654
655         tt_int_op(sizeof(ev_ssize_t), ==, sizeof(size_t));
656         tt_int_op(sizeof(ev_intptr_t), >=, sizeof(void *));
657         tt_int_op(sizeof(ev_uintptr_t), ==, sizeof(intptr_t));
658
659         u64 = 1000000000;
660         u64 *= 1000000000;
661         tt_assert(u64 / 1000000000 == 1000000000);
662         i64 = -1000000000;
663         i64 *= 1000000000;
664         tt_assert(i64 / 1000000000 == -1000000000);
665
666         u64 = EV_UINT64_MAX;
667         i64 = EV_INT64_MAX;
668         tt_assert(u64 > 0);
669         tt_assert(i64 > 0);
670         u64++;
671         i64++;
672         tt_assert(u64 == 0);
673         tt_assert(i64 == EV_INT64_MIN);
674         tt_assert(i64 < 0);
675
676         u32 = EV_UINT32_MAX;
677         i32 = EV_INT32_MAX;
678         tt_assert(u32 > 0);
679         tt_assert(i32 > 0);
680         u32++;
681         i32++;
682         tt_assert(u32 == 0);
683         tt_assert(i32 == EV_INT32_MIN);
684         tt_assert(i32 < 0);
685
686         u16 = EV_UINT16_MAX;
687         i16 = EV_INT16_MAX;
688         tt_assert(u16 > 0);
689         tt_assert(i16 > 0);
690         u16++;
691         i16++;
692         tt_assert(u16 == 0);
693         tt_assert(i16 == EV_INT16_MIN);
694         tt_assert(i16 < 0);
695
696         u8 = EV_UINT8_MAX;
697         i8 = EV_INT8_MAX;
698         tt_assert(u8 > 0);
699         tt_assert(i8 > 0);
700         u8++;
701         i8++;
702         tt_assert(u8 == 0);
703         tt_assert(i8 == EV_INT8_MIN);
704         tt_assert(i8 < 0);
705
706         ssize = EV_SSIZE_MAX;
707         tt_assert(ssize > 0);
708         ssize++;
709         tt_assert(ssize < 0);
710         tt_assert(ssize == EV_SSIZE_MIN);
711
712         ptr = &ssize;
713         iptr = (ev_intptr_t)ptr;
714         uptr = (ev_uintptr_t)ptr;
715         ptr = (void *)iptr;
716         tt_assert(ptr == &ssize);
717         ptr = (void *)uptr;
718         tt_assert(ptr == &ssize);
719
720         iptr = -1;
721         tt_assert(iptr < 0);
722 end:
723         ;
724 }
725
726 struct evutil_addrinfo *
727 ai_find_by_family(struct evutil_addrinfo *ai, int family)
728 {
729         while (ai) {
730                 if (ai->ai_family == family)
731                         return ai;
732                 ai = ai->ai_next;
733         }
734         return NULL;
735 }
736
737 struct evutil_addrinfo *
738 ai_find_by_protocol(struct evutil_addrinfo *ai, int protocol)
739 {
740         while (ai) {
741                 if (ai->ai_protocol == protocol)
742                         return ai;
743                 ai = ai->ai_next;
744         }
745         return NULL;
746 }
747
748
749 int
750 _test_ai_eq(const struct evutil_addrinfo *ai, const char *sockaddr_port,
751     int socktype, int protocol, int line)
752 {
753         struct sockaddr_storage ss;
754         int slen = sizeof(ss);
755         int gotport;
756         char buf[128];
757         memset(&ss, 0, sizeof(ss));
758         if (socktype > 0)
759                 tt_int_op(ai->ai_socktype, ==, socktype);
760         if (protocol > 0)
761                 tt_int_op(ai->ai_protocol, ==, protocol);
762
763         if (evutil_parse_sockaddr_port(
764                     sockaddr_port, (struct sockaddr*)&ss, &slen)<0) {
765                 TT_FAIL(("Couldn't parse expected address %s on line %d",
766                         sockaddr_port, line));
767                 return -1;
768         }
769         if (ai->ai_family != ss.ss_family) {
770                 TT_FAIL(("Address family %d did not match %d on line %d",
771                         ai->ai_family, ss.ss_family, line));
772                 return -1;
773         }
774         if (ai->ai_addr->sa_family == AF_INET) {
775                 struct sockaddr_in *sin = (struct sockaddr_in*)ai->ai_addr;
776                 evutil_inet_ntop(AF_INET, &sin->sin_addr, buf, sizeof(buf));
777                 gotport = ntohs(sin->sin_port);
778                 if (ai->ai_addrlen != sizeof(struct sockaddr_in)) {
779                         TT_FAIL(("Addr size mismatch on line %d", line));
780                         return -1;
781                 }
782         } else {
783                 struct sockaddr_in6 *sin6 = (struct sockaddr_in6*)ai->ai_addr;
784                 evutil_inet_ntop(AF_INET6, &sin6->sin6_addr, buf, sizeof(buf));
785                 gotport = ntohs(sin6->sin6_port);
786                 if (ai->ai_addrlen != sizeof(struct sockaddr_in6)) {
787                         TT_FAIL(("Addr size mismatch on line %d", line));
788                         return -1;
789                 }
790         }
791         if (evutil_sockaddr_cmp(ai->ai_addr, (struct sockaddr*)&ss, 1)) {
792                 TT_FAIL(("Wanted %s, got %s:%d on line %d", sockaddr_port,
793                         buf, gotport, line));
794                 return -1;
795         } else {
796                 TT_BLATHER(("Wanted %s, got %s:%d on line %d", sockaddr_port,
797                         buf, gotport, line));
798         }
799         return 0;
800 end:
801         TT_FAIL(("Test failed on line %d", line));
802         return -1;
803 }
804
805 static void
806 test_evutil_rand(void *arg)
807 {
808         char buf1[32];
809         char buf2[32];
810         int counts[256];
811         int i, j, k, n=0;
812
813         memset(buf2, 0, sizeof(buf2));
814         memset(counts, 0, sizeof(counts));
815
816         for (k=0;k<32;++k) {
817                 /* Try a few different start and end points; try to catch
818                  * the various misaligned cases of arc4random_buf */
819                 int startpoint = _evutil_weakrand() % 4;
820                 int endpoint = 32 - (_evutil_weakrand() % 4);
821
822                 memset(buf2, 0, sizeof(buf2));
823
824                 /* Do 6 runs over buf1, or-ing the result into buf2 each
825                  * time, to make sure we're setting each byte that we mean
826                  * to set. */
827                 for (i=0;i<8;++i) {
828                         memset(buf1, 0, sizeof(buf1));
829                         evutil_secure_rng_get_bytes(buf1 + startpoint,
830                             endpoint-startpoint);
831                         n += endpoint - startpoint;
832                         for (j=0; j<32; ++j) {
833                                 if (j >= startpoint && j < endpoint) {
834                                         buf2[j] |= buf1[j];
835                                         ++counts[(unsigned char)buf1[j]];
836                                 } else {
837                                         tt_assert(buf1[j] == 0);
838                                         tt_int_op(buf1[j], ==, 0);
839
840                                 }
841                         }
842                 }
843
844                 /* This will give a false positive with P=(256**8)==(2**64)
845                  * for each character. */
846                 for (j=startpoint;j<endpoint;++j) {
847                         tt_int_op(buf2[j], !=, 0);
848                 }
849         }
850
851         /* for (i=0;i<256;++i) { printf("%3d %2d\n", i, counts[i]); } */
852 end:
853         ;
854 }
855
856 static void
857 test_evutil_getaddrinfo(void *arg)
858 {
859         struct evutil_addrinfo *ai = NULL, *a;
860         struct evutil_addrinfo hints;
861
862         struct sockaddr_in6 *sin6;
863         struct sockaddr_in *sin;
864         char buf[128];
865         const char *cp;
866         int r;
867
868         /* Try using it as a pton. */
869         memset(&hints, 0, sizeof(hints));
870         hints.ai_family = PF_UNSPEC;
871         hints.ai_socktype = SOCK_STREAM;
872         r = evutil_getaddrinfo("1.2.3.4", "8080", &hints, &ai);
873         tt_int_op(r, ==, 0);
874         tt_assert(ai);
875         tt_ptr_op(ai->ai_next, ==, NULL); /* no ambiguity */
876         test_ai_eq(ai, "1.2.3.4:8080", SOCK_STREAM, IPPROTO_TCP);
877         evutil_freeaddrinfo(ai);
878         ai = NULL;
879
880         memset(&hints, 0, sizeof(hints));
881         hints.ai_family = PF_UNSPEC;
882         hints.ai_protocol = IPPROTO_UDP;
883         r = evutil_getaddrinfo("1001:b0b::f00f", "4321", &hints, &ai);
884         tt_int_op(r, ==, 0);
885         tt_assert(ai);
886         tt_ptr_op(ai->ai_next, ==, NULL); /* no ambiguity */
887         test_ai_eq(ai, "[1001:b0b::f00f]:4321", SOCK_DGRAM, IPPROTO_UDP);
888         evutil_freeaddrinfo(ai);
889         ai = NULL;
890
891         /* Try out the behavior of nodename=NULL */
892         memset(&hints, 0, sizeof(hints));
893         hints.ai_family = PF_INET;
894         hints.ai_protocol = IPPROTO_TCP;
895         hints.ai_flags = EVUTIL_AI_PASSIVE; /* as if for bind */
896         r = evutil_getaddrinfo(NULL, "9999", &hints, &ai);
897         tt_int_op(r,==,0);
898         tt_assert(ai);
899         tt_ptr_op(ai->ai_next, ==, NULL);
900         test_ai_eq(ai, "0.0.0.0:9999", SOCK_STREAM, IPPROTO_TCP);
901         evutil_freeaddrinfo(ai);
902         ai = NULL;
903         hints.ai_flags = 0; /* as if for connect */
904         r = evutil_getaddrinfo(NULL, "9998", &hints, &ai);
905         tt_assert(ai);
906         tt_int_op(r,==,0);
907         test_ai_eq(ai, "127.0.0.1:9998", SOCK_STREAM, IPPROTO_TCP);
908         tt_ptr_op(ai->ai_next, ==, NULL);
909         evutil_freeaddrinfo(ai);
910         ai = NULL;
911
912         hints.ai_flags = 0; /* as if for connect */
913         hints.ai_family = PF_INET6;
914         r = evutil_getaddrinfo(NULL, "9997", &hints, &ai);
915         tt_assert(ai);
916         tt_int_op(r,==,0);
917         tt_ptr_op(ai->ai_next, ==, NULL);
918         test_ai_eq(ai, "[::1]:9997", SOCK_STREAM, IPPROTO_TCP);
919         evutil_freeaddrinfo(ai);
920         ai = NULL;
921
922         hints.ai_flags = EVUTIL_AI_PASSIVE; /* as if for bind. */
923         hints.ai_family = PF_INET6;
924         r = evutil_getaddrinfo(NULL, "9996", &hints, &ai);
925         tt_assert(ai);
926         tt_int_op(r,==,0);
927         tt_ptr_op(ai->ai_next, ==, NULL);
928         test_ai_eq(ai, "[::]:9996", SOCK_STREAM, IPPROTO_TCP);
929         evutil_freeaddrinfo(ai);
930         ai = NULL;
931
932         /* Now try an unspec one. We should get a v6 and a v4. */
933         hints.ai_family = PF_UNSPEC;
934         r = evutil_getaddrinfo(NULL, "9996", &hints, &ai);
935         tt_assert(ai);
936         tt_int_op(r,==,0);
937         a = ai_find_by_family(ai, PF_INET6);
938         tt_assert(a);
939         test_ai_eq(a, "[::]:9996", SOCK_STREAM, IPPROTO_TCP);
940         a = ai_find_by_family(ai, PF_INET);
941         tt_assert(a);
942         test_ai_eq(a, "0.0.0.0:9996", SOCK_STREAM, IPPROTO_TCP);
943         evutil_freeaddrinfo(ai);
944         ai = NULL;
945
946         /* Try out AI_NUMERICHOST: successful case.  Also try
947          * multiprotocol. */
948         memset(&hints, 0, sizeof(hints));
949         hints.ai_family = PF_UNSPEC;
950         hints.ai_flags = EVUTIL_AI_NUMERICHOST;
951         r = evutil_getaddrinfo("1.2.3.4", NULL, &hints, &ai);
952         tt_int_op(r, ==, 0);
953         a = ai_find_by_protocol(ai, IPPROTO_TCP);
954         tt_assert(a);
955         test_ai_eq(a, "1.2.3.4", SOCK_STREAM, IPPROTO_TCP);
956         a = ai_find_by_protocol(ai, IPPROTO_UDP);
957         tt_assert(a);
958         test_ai_eq(a, "1.2.3.4", SOCK_DGRAM, IPPROTO_UDP);
959         evutil_freeaddrinfo(ai);
960         ai = NULL;
961
962         /* Try the failing case of AI_NUMERICHOST */
963         memset(&hints, 0, sizeof(hints));
964         hints.ai_family = PF_UNSPEC;
965         hints.ai_flags = EVUTIL_AI_NUMERICHOST;
966         r = evutil_getaddrinfo("www.google.com", "80", &hints, &ai);
967         tt_int_op(r, ==, EVUTIL_EAI_NONAME);
968         tt_int_op(ai, ==, NULL);
969
970         /* Try symbolic service names wit AI_NUMERICSERV */
971         memset(&hints, 0, sizeof(hints));
972         hints.ai_family = PF_UNSPEC;
973         hints.ai_socktype = SOCK_STREAM;
974         hints.ai_flags = EVUTIL_AI_NUMERICSERV;
975         r = evutil_getaddrinfo("1.2.3.4", "http", &hints, &ai);
976         tt_int_op(r,==,EVUTIL_EAI_NONAME);
977
978         /* Try symbolic service names */
979         memset(&hints, 0, sizeof(hints));
980         hints.ai_family = PF_UNSPEC;
981         hints.ai_socktype = SOCK_STREAM;
982         r = evutil_getaddrinfo("1.2.3.4", "http", &hints, &ai);
983         if (r!=0) {
984                 TT_DECLARE("SKIP", ("Symbolic service names seem broken."));
985         } else {
986                 tt_assert(ai);
987                 test_ai_eq(ai, "1.2.3.4:80", SOCK_STREAM, IPPROTO_TCP);
988                 evutil_freeaddrinfo(ai);
989                 ai = NULL;
990         }
991
992         /* Now do some actual lookups. */
993         memset(&hints, 0, sizeof(hints));
994         hints.ai_family = PF_INET;
995         hints.ai_protocol = IPPROTO_TCP;
996         hints.ai_socktype = SOCK_STREAM;
997         r = evutil_getaddrinfo("www.google.com", "80", &hints, &ai);
998         if (r != 0) {
999                 TT_DECLARE("SKIP", ("Couldn't resolve www.google.com"));
1000         } else {
1001                 tt_assert(ai);
1002                 tt_int_op(ai->ai_family, ==, PF_INET);
1003                 tt_int_op(ai->ai_protocol, ==, IPPROTO_TCP);
1004                 tt_int_op(ai->ai_socktype, ==, SOCK_STREAM);
1005                 tt_int_op(ai->ai_addrlen, ==, sizeof(struct sockaddr_in));
1006                 sin = (struct sockaddr_in*)ai->ai_addr;
1007                 tt_int_op(sin->sin_family, ==, AF_INET);
1008                 tt_int_op(sin->sin_port, ==, htons(80));
1009                 tt_int_op(sin->sin_addr.s_addr, !=, 0xffffffff);
1010
1011                 cp = evutil_inet_ntop(AF_INET, &sin->sin_addr, buf, sizeof(buf));
1012                 TT_BLATHER(("www.google.com resolved to %s",
1013                         cp?cp:"<unwriteable>"));
1014                 evutil_freeaddrinfo(ai);
1015                 ai = NULL;
1016         }
1017
1018         hints.ai_family = PF_INET6;
1019         r = evutil_getaddrinfo("ipv6.google.com", "80", &hints, &ai);
1020         if (r != 0) {
1021                 TT_BLATHER(("Couldn't do an ipv6 lookup for ipv6.google.com"));
1022         } else {
1023                 tt_assert(ai);
1024                 tt_int_op(ai->ai_family, ==, PF_INET6);
1025                 tt_int_op(ai->ai_addrlen, ==, sizeof(struct sockaddr_in6));
1026                 sin6 = (struct sockaddr_in6*)ai->ai_addr;
1027                 tt_int_op(sin6->sin6_port, ==, htons(80));
1028
1029                 cp = evutil_inet_ntop(AF_INET6, &sin6->sin6_addr, buf,
1030                     sizeof(buf));
1031                 TT_BLATHER(("ipv6.google.com resolved to %s",
1032                         cp?cp:"<unwriteable>"));
1033         }
1034
1035 end:
1036         if (ai)
1037                 evutil_freeaddrinfo(ai);
1038 }
1039
1040 #ifdef WIN32
1041 static void
1042 test_evutil_loadsyslib(void *arg)
1043 {
1044         HANDLE h=NULL;
1045
1046         h = evutil_load_windows_system_library(TEXT("kernel32.dll"));
1047         tt_assert(h);
1048
1049 end:
1050         if (h)
1051                 CloseHandle(h);
1052
1053 }
1054 #endif
1055
1056 struct testcase_t util_testcases[] = {
1057         { "ipv4_parse", regress_ipv4_parse, 0, NULL, NULL },
1058         { "ipv6_parse", regress_ipv6_parse, 0, NULL, NULL },
1059         { "sockaddr_port_parse", regress_sockaddr_port_parse, 0, NULL, NULL },
1060         { "sockaddr_port_format", regress_sockaddr_port_format, 0, NULL, NULL },
1061         { "sockaddr_predicates", test_evutil_sockaddr_predicates, 0,NULL,NULL },
1062         { "evutil_snprintf", test_evutil_snprintf, 0, NULL, NULL },
1063         { "evutil_strtoll", test_evutil_strtoll, 0, NULL, NULL },
1064         { "evutil_casecmp", test_evutil_casecmp, 0, NULL, NULL },
1065         { "strlcpy", test_evutil_strlcpy, 0, NULL, NULL },
1066         { "log", test_evutil_log, TT_FORK, NULL, NULL },
1067         { "upcast", test_evutil_upcast, 0, NULL, NULL },
1068         { "integers", test_evutil_integers, 0, NULL, NULL },
1069         { "rand", test_evutil_rand, TT_FORK, NULL, NULL },
1070         { "getaddrinfo", test_evutil_getaddrinfo, TT_FORK, NULL, NULL },
1071 #ifdef WIN32
1072         { "loadsyslib", test_evutil_loadsyslib, TT_FORK, NULL, NULL },
1073 #endif
1074         END_OF_TESTCASES,
1075 };
1076