chiark / gitweb /
a10571342947db4e17593ae681f3bf612da6a9ed
[disorder] / lib / test.c
1 /*
2  * This file is part of DisOrder.
3  * Copyright (C) 2005, 2007 Richard Kettlewell
4  *
5  * This program is free software; you can redistribute it and/or modify
6  * it under the terms of the GNU General Public License as published by
7  * the Free Software Foundation; either version 2 of the License, or
8  * (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful, but
11  * WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  * General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this program; if not, write to the Free Software
17  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
18  * USA
19  */
20 /** @file lib/test.c @brief Library tests */
21
22 #include <config.h>
23 #include "types.h"
24
25 #include <stdio.h>
26 #include <string.h>
27 #include <stdlib.h>
28 #include <errno.h>
29 #include <ctype.h>
30 #include <assert.h>
31 #include <sys/types.h>
32 #include <sys/stat.h>
33 #include <unistd.h>
34 #include <signal.h>
35 #include <sys/wait.h>
36 #include <stddef.h>
37 #include <sys/socket.h>
38 #include <netdb.h>
39 #include <netinet/in.h>
40
41 #include "mem.h"
42 #include "log.h"
43 #include "vector.h"
44 #include "charset.h"
45 #include "mime.h"
46 #include "hex.h"
47 #include "heap.h"
48 #include "unicode.h"
49 #include "inputline.h"
50 #include "wstat.h"
51 #include "signame.h"
52 #include "cache.h"
53 #include "filepart.h"
54 #include "hash.h"
55 #include "selection.h"
56 #include "syscalls.h"
57 #include "kvp.h"
58 #include "sink.h"
59 #include "printf.h"
60 #include "basen.h"
61 #include "split.h"
62 #include "configuration.h"
63 #include "addr.h"
64 #include "base64.h"
65 #include "url.h"
66
67 static int tests, errors;
68 static int fail_first;
69
70 static void count_error() {
71   ++errors;
72   if(fail_first)
73     abort();
74 }
75
76 /** @brief Checks that @p expr is nonzero */
77 #define insist(expr) do {                               \
78   if(!(expr)) {                                         \
79     count_error();                                              \
80     fprintf(stderr, "%s:%d: error checking %s\n",       \
81             __FILE__, __LINE__, #expr);                 \
82   }                                                     \
83   ++tests;                                              \
84 } while(0)
85
86 static const char *format(const char *s) {
87   struct dynstr d;
88   int c;
89   char buf[10];
90   
91   dynstr_init(&d);
92   while((c = (unsigned char)*s++)) {
93     if(c >= ' ' && c <= '~')
94       dynstr_append(&d, c);
95     else {
96       sprintf(buf, "\\x%02X", (unsigned)c);
97       dynstr_append_string(&d, buf);
98     }
99   }
100   dynstr_terminate(&d);
101   return d.vec;
102 }
103
104 static const char *format_utf32(const uint32_t *s) {
105   struct dynstr d;
106   uint32_t c;
107   char buf[64];
108   
109   dynstr_init(&d);
110   while((c = *s++)) {
111     sprintf(buf, " %04lX", (long)c);
112     dynstr_append_string(&d, buf);
113   }
114   dynstr_terminate(&d);
115   return d.vec;
116 }
117
118 #define check_string(GOT, WANT) do {                                    \
119   const char *got = GOT;                                                \
120   const char *want = WANT;                                              \
121                                                                         \
122   if(want == 0) {                                                       \
123     fprintf(stderr, "%s:%d: %s returned 0\n",                           \
124             __FILE__, __LINE__, #GOT);                                  \
125     count_error();                                                      \
126   } else if(strcmp(want, got)) {                                        \
127     fprintf(stderr, "%s:%d: %s returned:\n%s\nexpected:\n%s\n",         \
128             __FILE__, __LINE__, #GOT, format(got), format(want));       \
129     count_error();                                                      \
130   }                                                                     \
131   ++tests;                                                              \
132  } while(0)
133
134 #define check_string_prefix(GOT, WANT) do {                             \
135   const char *got = GOT;                                                \
136   const char *want = WANT;                                              \
137                                                                         \
138   if(want == 0) {                                                       \
139     fprintf(stderr, "%s:%d: %s returned 0\n",                           \
140             __FILE__, __LINE__, #GOT);                                  \
141     count_error();                                                      \
142   } else if(strncmp(want, got, strlen(want))) {                         \
143     fprintf(stderr, "%s:%d: %s returned:\n%s\nexpected:\n%s...\n",      \
144             __FILE__, __LINE__, #GOT, format(got), format(want));       \
145     count_error();                                                      \
146   }                                                                     \
147   ++tests;                                                              \
148  } while(0)
149
150 #define check_integer(GOT, WANT) do {                           \
151   const intmax_t got = GOT, want = WANT;                        \
152   if(got != want) {                                             \
153     fprintf(stderr, "%s:%d: %s returned: %jd  expected: %jd\n", \
154             __FILE__, __LINE__, #GOT, got, want);               \
155     count_error();                                              \
156   }                                                             \
157   ++tests;                                                      \
158 } while(0)
159
160 static uint32_t *ucs4parse(const char *s) {
161   struct dynstr_ucs4 d;
162   char *e;
163
164   dynstr_ucs4_init(&d);
165   while(*s) {
166     errno = 0;
167     dynstr_ucs4_append(&d, strtoul(s, &e, 0));
168     if(errno) fatal(errno, "strtoul (%s)", s);
169     s = e;
170   }
171   dynstr_ucs4_terminate(&d);
172   return d.vec;
173 }
174
175 static void test_utf8(void) {
176   /* Test validutf8, convert to UCS-4, check the answer is right,
177    * convert back to UTF-8, check we got to where we started */
178 #define U8(CHARS, WORDS) do {                   \
179   uint32_t *w = ucs4parse(WORDS);               \
180   uint32_t *ucs;                                \
181   char *u8;                                     \
182                                                 \
183   insist(validutf8(CHARS));                     \
184   ucs = utf8_to_utf32(CHARS, strlen(CHARS), 0); \
185   insist(ucs != 0);                             \
186   insist(!utf32_cmp(w, ucs));                   \
187   u8 = utf32_to_utf8(ucs, utf32_len(ucs), 0);   \
188   insist(u8 != 0);                              \
189   check_string(u8, CHARS);                      \
190 } while(0)
191
192   fprintf(stderr, "test_utf8\n");
193 #define validutf8(S) utf8_valid((S), strlen(S))
194
195   /* empty string */
196
197   U8("", "");
198   
199   /* ASCII characters */
200
201   U8(" !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~",
202      "0x20 0x21 0x22 0x23 0x24 0x25 0x26 0x27 0x28 0x29 0x2a 0x2b 0x2c 0x2d "
203      "0x2e 0x2f 0x30 0x31 0x32 0x33 0x34 0x35 0x36 0x37 0x38 0x39 0x3a "
204      "0x3b 0x3c 0x3d 0x3e 0x3f 0x40 0x41 0x42 0x43 0x44 0x45 0x46 0x47 "
205      "0x48 0x49 0x4a 0x4b 0x4c 0x4d 0x4e 0x4f 0x50 0x51 0x52 0x53 0x54 "
206      "0x55 0x56 0x57 0x58 0x59 0x5a 0x5b 0x5c 0x5d 0x5e 0x5f 0x60 0x61 "
207      "0x62 0x63 0x64 0x65 0x66 0x67 0x68 0x69 0x6a 0x6b 0x6c 0x6d 0x6e "
208      "0x6f 0x70 0x71 0x72 0x73 0x74 0x75 0x76 0x77 0x78 0x79 0x7a 0x7b "
209      "0x7c 0x7d 0x7e");
210   U8("\001\002\003\004\005\006\007\010\011\012\013\014\015\016\017\020\021\022\023\024\025\026\027\030\031\032\033\034\035\036\037\177",
211      "0x1 0x2 0x3 0x4 0x5 0x6 0x7 0x8 0x9 0xa 0xb 0xc 0xd 0xe 0xf 0x10 "
212      "0x11 0x12 0x13 0x14 0x15 0x16 0x17 0x18 0x19 0x1a 0x1b 0x1c 0x1d "
213      "0x1e 0x1f 0x7f");
214
215   /* from RFC3629 */
216
217   /* UTF8-2      = %xC2-DF UTF8-tail */
218   insist(!validutf8("\xC0\x80"));
219   insist(!validutf8("\xC1\x80"));
220   insist(!validutf8("\xC2\x7F"));
221   U8("\xC2\x80", "0x80");
222   U8("\xDF\xBF", "0x7FF");
223   insist(!validutf8("\xDF\xC0"));
224
225   /*  UTF8-3      = %xE0 %xA0-BF UTF8-tail / %xE1-EC 2( UTF8-tail ) /
226    *                %xED %x80-9F UTF8-tail / %xEE-EF 2( UTF8-tail )
227    */
228   insist(!validutf8("\xE0\x9F\x80"));
229   U8("\xE0\xA0\x80", "0x800");
230   U8("\xE0\xBF\xBF", "0xFFF");
231   insist(!validutf8("\xE0\xC0\xBF"));
232
233   insist(!validutf8("\xE1\x80\x7F"));
234   U8("\xE1\x80\x80", "0x1000");
235   U8("\xEC\xBF\xBF", "0xCFFF");
236   insist(!validutf8("\xEC\xC0\xBF"));
237   
238   U8("\xED\x80\x80", "0xD000");
239   U8("\xED\x9F\xBF", "0xD7FF");
240   insist(!validutf8("\xED\xA0\xBF"));
241
242   insist(!validutf8("\xEE\x7f\x80"));
243   U8("\xEE\x80\x80", "0xE000");
244   U8("\xEF\xBF\xBF", "0xFFFF");
245   insist(!validutf8("\xEF\xC0\xBF"));
246
247   /*  UTF8-4      = %xF0 %x90-BF 2( UTF8-tail ) / %xF1-F3 3( UTF8-tail ) /
248    *                %xF4 %x80-8F 2( UTF8-tail )
249    */
250   insist(!validutf8("\xF0\x8F\x80\x80"));
251   U8("\xF0\x90\x80\x80", "0x10000");
252   U8("\xF0\xBF\xBF\xBF", "0x3FFFF");
253   insist(!validutf8("\xF0\xC0\x80\x80"));
254
255   insist(!validutf8("\xF1\x80\x80\x7F"));
256   U8("\xF1\x80\x80\x80", "0x40000");
257   U8("\xF3\xBF\xBF\xBF", "0xFFFFF");
258   insist(!validutf8("\xF3\xC0\x80\x80"));
259
260   insist(!validutf8("\xF4\x80\x80\x7F"));
261   U8("\xF4\x80\x80\x80", "0x100000");
262   U8("\xF4\x8F\xBF\xBF", "0x10FFFF");
263   insist(!validutf8("\xF4\x90\x80\x80"));
264   insist(!validutf8("\xF4\x80\xFF\x80"));
265
266   /* miscellaneous non-UTF-8 rubbish */
267   insist(!validutf8("\x80"));
268   insist(!validutf8("\xBF"));
269   insist(!validutf8("\xC0"));
270   insist(!validutf8("\xC0\x7F"));
271   insist(!validutf8("\xC0\xC0"));
272   insist(!validutf8("\xE0"));
273   insist(!validutf8("\xE0\x7F"));
274   insist(!validutf8("\xE0\xC0"));
275   insist(!validutf8("\xE0\x80"));
276   insist(!validutf8("\xE0\x80\x7f"));
277   insist(!validutf8("\xE0\x80\xC0"));
278   insist(!validutf8("\xF0"));
279   insist(!validutf8("\xF0\x7F"));
280   insist(!validutf8("\xF0\xC0"));
281   insist(!validutf8("\xF0\x80"));
282   insist(!validutf8("\xF0\x80\x7f"));
283   insist(!validutf8("\xF0\x80\xC0"));
284   insist(!validutf8("\xF0\x80\x80\x7f"));
285   insist(!validutf8("\xF0\x80\x80\xC0"));
286   insist(!validutf8("\xF5\x80\x80\x80"));
287   insist(!validutf8("\xF8"));
288 }
289
290 static int test_multipart_callback(const char *s, void *u) {
291   struct vector *parts = u;
292
293   vector_append(parts, (char *)s);
294   return 0;
295 }
296
297 static void test_mime(void) {
298   char *t, *n, *v;
299   struct vector parts[1];
300   struct kvp *k;
301
302   fprintf(stderr, "test_mime\n");
303
304   t = 0;
305   k = 0;
306   insist(!mime_content_type("text/plain", &t, &k));
307   check_string(t, "text/plain");
308   insist(k == 0);
309
310   insist(mime_content_type("TEXT ((broken) comment", &t, &k) < 0);
311   insist(mime_content_type("TEXT ((broken) comment\\", &t, &k) < 0);
312   
313   t = 0;
314   k = 0;
315   insist(!mime_content_type("TEXT ((nested)\\ comment) /plain", &t, &k));
316   check_string(t, "text/plain");
317   insist(k == 0);
318
319   t = 0;
320   k = 0;
321   insist(!mime_content_type(" text/plain ; Charset=\"utf-\\8\"", &t, &k));
322   check_string(t, "text/plain");
323   insist(k != 0);
324   insist(k->next == 0);
325   check_string(k->name, "charset");
326   check_string(k->value, "utf-8");
327
328   t = 0;
329   k = 0;
330   insist(!mime_content_type("text/plain;charset = ISO-8859-1 ", &t, &k));
331   insist(k != 0);
332   insist(k->next == 0);
333   check_string(t, "text/plain");
334   check_string(k->name, "charset");
335   check_string(k->value, "ISO-8859-1");
336
337   t = n = v = 0;
338   insist(!mime_rfc2388_content_disposition("form-data; name=\"field1\"", &t, &n, &v));
339   check_string(t, "form-data");
340   check_string(n, "name");
341   check_string(v, "field1");
342
343   insist(!mime_rfc2388_content_disposition("inline", &t, &n, &v));
344   check_string(t, "inline");
345   insist(n == 0);
346   insist(v == 0);
347
348   /* Current versions of the code only understand a single arg to these
349    * headers.  This is a bug at the level they work at but suffices for
350    * DisOrder's current purposes. */
351
352   insist(!mime_rfc2388_content_disposition(
353               "attachment; filename=genome.jpeg;\n"
354               "modification-date=\"Wed, 12 Feb 1997 16:29:51 -0500\"",
355          &t, &n, &v));
356   check_string(t, "attachment");
357   check_string(n, "filename");
358   check_string(v, "genome.jpeg");
359
360   vector_init(parts);
361   insist(mime_multipart("--outer\r\n"
362                         "Content-Type: text/plain\r\n"
363                         "Content-Disposition: inline\r\n"
364                         "Content-Description: text-part-1\r\n"
365                         "\r\n"
366                         "Some text goes here\r\n"
367                         "\r\n"
368                         "--outer\r\n"
369                         "Content-Type: multipart/mixed; boundary=inner\r\n"
370                         "Content-Disposition: attachment\r\n"
371                         "Content-Description: multipart-2\r\n"
372                         "\r\n"
373                         "--inner\r\n"
374                         "Content-Type: text/plain\r\n"
375                         "Content-Disposition: inline\r\n"
376                         "Content-Description: text-part-2\r\n"
377                         "\r\n"
378                         "Some more text here.\r\n"
379                         "\r\n"
380                         "--inner\r\n"
381                         "Content-Type: image/jpeg\r\n"
382                         "Content-Disposition: attachment\r\n"
383                         "Content-Description: jpeg-1\r\n"
384                         "\r\n"
385                         "<jpeg data>\r\n"
386                         "--inner--\r\n"
387                         "--outer--\r\n",
388                         test_multipart_callback,
389                         "outer",
390                         parts) == 0);
391   check_integer(parts->nvec, 2);
392   check_string(parts->vec[0],
393                "Content-Type: text/plain\r\n"
394                "Content-Disposition: inline\r\n"
395                "Content-Description: text-part-1\r\n"
396                "\r\n"
397                "Some text goes here\r\n");
398   check_string(parts->vec[1],
399                "Content-Type: multipart/mixed; boundary=inner\r\n"
400                "Content-Disposition: attachment\r\n"
401                "Content-Description: multipart-2\r\n"
402                "\r\n"
403                "--inner\r\n"
404                "Content-Type: text/plain\r\n"
405                "Content-Disposition: inline\r\n"
406                "Content-Description: text-part-2\r\n"
407                "\r\n"
408                "Some more text here.\r\n"
409                "\r\n"
410                "--inner\r\n"
411                "Content-Type: image/jpeg\r\n"
412                "Content-Disposition: attachment\r\n"
413                "Content-Description: jpeg-1\r\n"
414                "\r\n"
415                "<jpeg data>\r\n"
416                "--inner--");
417   /* No trailing CRLF is _correct_ - see RFC2046 5.1.1 note regarding CRLF
418    * preceding the boundary delimiter line.  An implication of this is that we
419    * must cope with partial lines at the end of the input when recursively
420    * decomposing a multipart message. */
421   vector_init(parts);
422   insist(mime_multipart("--inner\r\n"
423                         "Content-Type: text/plain\r\n"
424                         "Content-Disposition: inline\r\n"
425                         "Content-Description: text-part-2\r\n"
426                         "\r\n"
427                         "Some more text here.\r\n"
428                         "\r\n"
429                         "--inner\r\n"
430                         "Content-Type: image/jpeg\r\n"
431                         "Content-Disposition: attachment\r\n"
432                         "Content-Description: jpeg-1\r\n"
433                         "\r\n"
434                         "<jpeg data>\r\n"
435                         "--inner--",
436                         test_multipart_callback,
437                         "inner",
438                         parts) == 0);
439   check_integer(parts->nvec, 2);
440   check_string(parts->vec[0],
441                "Content-Type: text/plain\r\n"
442                "Content-Disposition: inline\r\n"
443                "Content-Description: text-part-2\r\n"
444                "\r\n"
445                "Some more text here.\r\n");
446   check_string(parts->vec[1],
447                "Content-Type: image/jpeg\r\n"
448                "Content-Disposition: attachment\r\n"
449                "Content-Description: jpeg-1\r\n"
450                "\r\n"
451                "<jpeg data>");
452  
453   /* XXX mime_parse */
454
455   check_string(mime_qp(""), "");
456   check_string(mime_qp("foobar"), "foobar");
457   check_string(mime_qp("foo=20bar"), "foo bar");
458   check_string(mime_qp("x \r\ny"), "x\r\ny");
459   check_string(mime_qp("x=\r\ny"), "xy");
460   check_string(mime_qp("x= \r\ny"), "xy");
461   check_string(mime_qp("x =\r\ny"), "x y");
462   check_string(mime_qp("x = \r\ny"), "x y");
463
464   check_string(mime_to_qp(""), "");
465   check_string(mime_to_qp("foobar\n"), "foobar\n");
466   check_string(mime_to_qp("foobar \n"), "foobar=20\n");
467   check_string(mime_to_qp("foobar\t\n"), "foobar=09\n"); 
468   check_string(mime_to_qp("foobar \t \n"), "foobar=20=09=20\n");
469   check_string(mime_to_qp(" foo=bar"), " foo=3Dbar\n");
470   check_string(mime_to_qp("copyright \xC2\xA9"), "copyright =C2=A9\n");
471   check_string(mime_to_qp("foo\nbar\nbaz\n"), "foo\nbar\nbaz\n");
472   check_string(mime_to_qp("wibble wobble wibble wobble wibble wobble wibble wobble wibble wobble wibble"), "wibble wobble wibble wobble wibble wobble wibble wobble wibble wobble wibb=\nle\n");
473  
474   /* from RFC2045 */
475   check_string(mime_qp("Now's the time =\r\n"
476 "for all folk to come=\r\n"
477 " to the aid of their country."),
478                "Now's the time for all folk to come to the aid of their country.");
479
480 #define check_base64(encoded, decoded) do {                     \
481     check_string(mime_base64(encoded, 0), decoded);             \
482     check_string(mime_to_base64((const uint8_t *)decoded,       \
483                                          (sizeof decoded) - 1), \
484                  encoded);                                      \
485   } while(0)
486     
487   
488   check_base64("",  "");
489   check_base64("BBBB", "\x04\x10\x41");
490   check_base64("////", "\xFF\xFF\xFF");
491   check_base64("//BB", "\xFF\xF0\x41");
492   check_base64("BBBB//BB////",
493              "\x04\x10\x41" "\xFF\xF0\x41" "\xFF\xFF\xFF");
494   check_base64("BBBBBA==",
495                "\x04\x10\x41" "\x04");
496   check_base64("BBBBBBA=",
497                "\x04\x10\x41" "\x04\x10");
498
499   /* Check that decoding handles various kinds of rubbish OK */
500   check_string(mime_base64("B B B B  / / B B / / / /", 0),
501              "\x04\x10\x41" "\xFF\xF0\x41" "\xFF\xFF\xFF");
502   check_string(mime_base64("B\r\nBBB.// B-B//~//", 0),
503                "\x04\x10\x41" "\xFF\xF0\x41" "\xFF\xFF\xFF");
504   check_string(mime_base64("BBBB BB==", 0),
505                "\x04\x10\x41" "\x04");
506   check_string(mime_base64("BBBB BB = =", 0),
507                "\x04\x10\x41" "\x04");
508   check_string(mime_base64("BBBB BBB=", 0),
509                "\x04\x10\x41" "\x04\x10");
510   check_string(mime_base64("BBBB BBB = ", 0),
511                "\x04\x10\x41" "\x04\x10");
512   check_string(mime_base64("BBBB=", 0),
513                "\x04\x10\x41");
514   check_string(mime_base64("BBBBBB==", 0),
515                "\x04\x10\x41" "\x04");
516   check_string(mime_base64("BBBBBBB=", 0),
517                "\x04\x10\x41" "\x04\x10");
518   /* Not actually valid base64 */
519   check_string(mime_base64("BBBBx=", 0),
520                "\x04\x10\x41");
521 }
522
523 static void test_cookies(void) {
524   struct cookiedata cd[1];
525
526   fprintf(stderr, "test_cookies\n");
527
528   /* These are the examples from RFC2109 */
529   insist(!parse_cookie("$Version=\"1\"; Customer=\"WILE_E_COYOTE\"; $Path=\"/acme\"", cd));
530   insist(!strcmp(cd->version, "1"));
531   insist(cd->ncookies = 1);
532   insist(find_cookie(cd, "Customer") == &cd->cookies[0]);
533   check_string(cd->cookies[0].value, "WILE_E_COYOTE");
534   check_string(cd->cookies[0].path, "/acme");
535   insist(cd->cookies[0].domain == 0);
536   insist(!parse_cookie("$Version=\"1\";\n"
537                        "Customer=\"WILE_E_COYOTE\"; $Path=\"/acme\";\n"
538                        "Part_Number=\"Rocket_Launcher_0001\"; $Path=\"/acme\"",
539                        cd));
540   insist(cd->ncookies = 2);
541   insist(find_cookie(cd, "Customer") == &cd->cookies[0]);
542   insist(find_cookie(cd, "Part_Number") == &cd->cookies[1]);
543   check_string(cd->cookies[0].value, "WILE_E_COYOTE");
544   check_string(cd->cookies[0].path, "/acme");
545   insist(cd->cookies[0].domain == 0);
546   check_string(cd->cookies[1].value, "Rocket_Launcher_0001");
547   check_string(cd->cookies[1].path, "/acme");
548   insist(cd->cookies[1].domain == 0);
549   insist(!parse_cookie("$Version=\"1\";\n"
550                        "Customer=\"WILE_E_COYOTE\"; $Path=\"/acme\";\n"
551                        "Part_Number=\"Rocket_Launcher_0001\"; $Path=\"/acme\";\n"
552                        "Shipping=\"FedEx\"; $Path=\"/acme\"",
553                        cd));
554   insist(cd->ncookies = 3);
555   insist(find_cookie(cd, "Customer") == &cd->cookies[0]);
556   insist(find_cookie(cd, "Part_Number") == &cd->cookies[1]);
557   insist(find_cookie(cd, "Shipping") == &cd->cookies[2]);
558   check_string(cd->cookies[0].value, "WILE_E_COYOTE");
559   check_string(cd->cookies[0].path, "/acme");
560   insist(cd->cookies[0].domain == 0);
561   check_string(cd->cookies[1].value, "Rocket_Launcher_0001");
562   check_string(cd->cookies[1].path, "/acme");
563   insist(cd->cookies[1].domain == 0);
564   check_string(cd->cookies[2].value, "FedEx");
565   check_string(cd->cookies[2].path, "/acme");
566   insist(cd->cookies[2].domain == 0);
567 }
568
569 static void test_hex(void) {
570   unsigned n;
571   static const unsigned char h[] = { 0x00, 0xFF, 0x80, 0x7F };
572   uint8_t *u;
573   size_t ul;
574
575   fprintf(stderr, "test_hex\n");
576
577   for(n = 0; n <= UCHAR_MAX; ++n) {
578     if(!isxdigit(n))
579       insist(unhexdigitq(n) == -1);
580   }
581   insist(unhexdigitq('0') == 0);
582   insist(unhexdigitq('1') == 1);
583   insist(unhexdigitq('2') == 2);
584   insist(unhexdigitq('3') == 3);
585   insist(unhexdigitq('4') == 4);
586   insist(unhexdigitq('5') == 5);
587   insist(unhexdigitq('6') == 6);
588   insist(unhexdigitq('7') == 7);
589   insist(unhexdigitq('8') == 8);
590   insist(unhexdigitq('9') == 9);
591   insist(unhexdigitq('a') == 10);
592   insist(unhexdigitq('b') == 11);
593   insist(unhexdigitq('c') == 12);
594   insist(unhexdigitq('d') == 13);
595   insist(unhexdigitq('e') == 14);
596   insist(unhexdigitq('f') == 15);
597   insist(unhexdigitq('A') == 10);
598   insist(unhexdigitq('B') == 11);
599   insist(unhexdigitq('C') == 12);
600   insist(unhexdigitq('D') == 13);
601   insist(unhexdigitq('E') == 14);
602   insist(unhexdigitq('F') == 15);
603   check_string(hex(h, sizeof h), "00ff807f");
604   check_string(hex(0, 0), "");
605   u = unhex("00ff807f", &ul);
606   insist(ul == 4);
607   insist(memcmp(u, h, 4) == 0);
608   u = unhex("00FF807F", &ul);
609   insist(ul == 4);
610   insist(memcmp(u, h, 4) == 0);
611   u = unhex("", &ul);
612   insist(ul == 0);
613   fprintf(stderr, "2 ERROR reports expected {\n");
614   insist(unhex("F", 0) == 0);
615   insist(unhex("az", 0) == 0);
616   fprintf(stderr, "}\n");
617 }
618
619 static void test_casefold(void) {
620   uint32_t c, l;
621   const char *input, *canon_folded, *compat_folded, *canon_expected, *compat_expected;
622
623   fprintf(stderr, "test_casefold\n");
624
625   /* This isn't a very exhaustive test.  Unlike for normalization, there don't
626    * seem to be any public test vectors for these algorithms. */
627   
628   for(c = 1; c < 256; ++c) {
629     input = utf32_to_utf8(&c, 1, 0);
630     canon_folded = utf8_casefold_canon(input, strlen(input), 0);
631     compat_folded = utf8_casefold_compat(input, strlen(input), 0);
632     switch(c) {
633     default:
634       if((c >= 'A' && c <= 'Z')
635          || (c >= 0xC0 && c <= 0xDE && c != 0xD7))
636         l = c ^ 0x20;
637       else
638         l = c;
639       break;
640     case 0xB5:                          /* MICRO SIGN */
641       l = 0x3BC;                        /* GREEK SMALL LETTER MU */
642       break;
643     case 0xDF:                          /* LATIN SMALL LETTER SHARP S */
644       check_string(canon_folded, "ss");
645       check_string(compat_folded, "ss");
646       l = 0;
647       break;
648     }
649     if(l) {
650       uint32_t *d;
651       /* Case-folded data is now normalized */
652       d = utf32_decompose_canon(&l, 1, 0);
653       canon_expected = utf32_to_utf8(d, utf32_len(d), 0);
654       if(strcmp(canon_folded, canon_expected)) {
655         fprintf(stderr, "%s:%d: canon-casefolding %#lx got '%s', expected '%s'\n",
656                 __FILE__, __LINE__, (unsigned long)c,
657                 format(canon_folded), format(canon_expected));
658         count_error();
659       }
660       ++tests;
661       d = utf32_decompose_compat(&l, 1, 0);
662       compat_expected = utf32_to_utf8(d, utf32_len(d), 0);
663       if(strcmp(compat_folded, compat_expected)) {
664         fprintf(stderr, "%s:%d: compat-casefolding %#lx got '%s', expected '%s'\n",
665                 __FILE__, __LINE__, (unsigned long)c,
666                 format(compat_folded), format(compat_expected));
667         count_error();
668       }
669       ++tests;
670     }
671   }
672   check_string(utf8_casefold_canon("", 0, 0), "");
673 }
674
675 struct {
676   const char *in;
677   const char *expect[10];
678 } wtest[] = {
679   /* Empty string */
680   { "", { 0 } },
681   /* Only whitespace and punctuation */
682   { "    ", { 0 } },
683   { " '   ", { 0 } },
684   { " !  ", { 0 } },
685   { " \"\"  ", { 0 } },
686   { " @  ", { 0 } },
687   /* Basics */
688   { "wibble", { "wibble", 0 } },
689   { " wibble", { "wibble", 0 } },
690   { " wibble ", { "wibble", 0 } },
691   { "wibble ", { "wibble", 0 } },
692   { "wibble spong", { "wibble", "spong", 0 } },
693   { " wibble  spong", { "wibble", "spong", 0 } },
694   { " wibble  spong   ", { "wibble", "spong", 0 } },
695   { "wibble   spong  ", { "wibble", "spong", 0 } },
696   { "wibble   spong splat foo zot  ", { "wibble", "spong", "splat", "foo", "zot", 0 } },
697   /* Apostrophes */
698   { "wibble 'spong", { "wibble", "spong", 0 } },
699   { " wibble's", { "wibble's", 0 } },
700   { " wibblespong'   ", { "wibblespong", 0 } },
701   { "wibble   sp''ong  ", { "wibble", "sp", "ong", 0 } },
702 };
703 #define NWTEST (sizeof wtest / sizeof *wtest)
704
705 static void test_words(void) {
706   size_t t, nexpect, ngot, i;
707   int right;
708   
709   fprintf(stderr, "test_words\n");
710   for(t = 0; t < NWTEST; ++t) {
711     char **got = utf8_word_split(wtest[t].in, strlen(wtest[t].in), &ngot, 0);
712
713     for(nexpect = 0; wtest[t].expect[nexpect]; ++nexpect)
714       ;
715     if(nexpect == ngot) {
716       for(i = 0; i < ngot; ++i)
717         if(strcmp(wtest[t].expect[i], got[i]))
718           break;
719       right = i == ngot;
720     } else
721       right = 0;
722     if(!right) {
723       fprintf(stderr, "word split %zu failed\n", t);
724       fprintf(stderr, "input: %s\n", wtest[t].in);
725       fprintf(stderr, "    | %-30s | %-30s\n",
726               "expected", "got");
727       for(i = 0; i < nexpect || i < ngot; ++i) {
728         const char *e = i < nexpect ? wtest[t].expect[i] : "<none>";
729         const char *g = i < ngot ? got[i] : "<none>";
730         fprintf(stderr, " %2zu | %-30s | %-30s\n", i, e, g);
731       }
732       count_error();
733     }
734     ++tests;
735   }
736 }
737
738 /** @brief Less-than comparison function for integer heap */
739 static inline int int_lt(int a, int b) { return a < b; }
740
741 /** @struct iheap
742  * @brief A heap with @c int elements */
743 HEAP_TYPE(iheap, int, int_lt);
744 HEAP_DEFINE(iheap, int, int_lt);
745
746 /** @brief Tests for @ref heap.h */
747 static void test_heap(void) {
748   struct iheap h[1];
749   int n;
750   int last = -1;
751
752   fprintf(stderr, "test_heap\n");
753
754   iheap_init(h);
755   for(n = 0; n < 1000; ++n)
756     iheap_insert(h, random() % 100);
757   for(n = 0; n < 1000; ++n) {
758     const int latest = iheap_remove(h);
759     if(last > latest)
760       fprintf(stderr, "should have %d <= %d\n", last, latest);
761     insist(last <= latest);
762     last = latest;
763   }
764   putchar('\n');
765 }
766
767 /** @brief Open a Unicode test file */
768 static FILE *open_unicode_test(const char *path) {
769   const char *base;
770   FILE *fp;
771   char buffer[1024];
772   int w;
773
774   if((base = strrchr(path, '/')))
775     ++base;
776   else
777     base = path;
778   if(!(fp = fopen(base, "r"))) {
779     snprintf(buffer, sizeof buffer,
780              "wget http://www.unicode.org/Public/5.0.0/ucd/%s", path);
781     if((w = system(buffer)))
782       fatal(0, "%s: %s", buffer, wstat(w));
783     if(chmod(base, 0444) < 0)
784       fatal(errno, "chmod %s", base);
785     if(!(fp = fopen(base, "r")))
786       fatal(errno, "%s", base);
787   }
788   return fp;
789 }
790
791 /** @brief Run breaking tests for utf32_grapheme_boundary() etc */
792 static void breaktest(const char *path,
793                       int (*breakfn)(const uint32_t *, size_t, size_t)) {
794   FILE *fp = open_unicode_test(path);
795   int lineno = 0;
796   char *l, *lp;
797   size_t bn, n;
798   char break_allowed[1024];
799   uint32_t buffer[1024];
800
801   while(!inputline(path, fp, &l, '\n')) {
802     ++lineno;
803     if(l[0] == '#') continue;
804     bn = 0;
805     lp = l;
806     while(*lp) {
807       if(*lp == ' ' || *lp == '\t') {
808         ++lp;
809         continue;
810       }
811       if(*lp == '#')
812         break;
813       if((unsigned char)*lp == 0xC3 && (unsigned char)lp[1] == 0xB7) {
814         /* 00F7 DIVISION SIGN */
815         break_allowed[bn] = 1;
816         lp += 2;
817         continue;
818       }
819       if((unsigned char)*lp == 0xC3 && (unsigned char)lp[1] == 0x97) {
820         /* 00D7 MULTIPLICATION SIGN */
821         break_allowed[bn] = 0;
822         lp += 2;
823         continue;
824       }
825       if(isxdigit((unsigned char)*lp)) {
826         buffer[bn++] = strtoul(lp, &lp, 16);
827         continue;
828       }
829       fatal(0, "%s:%d: evil line: %s", path, lineno, l);
830     }
831     for(n = 0; n <= bn; ++n) {
832       if(breakfn(buffer, bn, n) != break_allowed[n]) {
833         fprintf(stderr,
834                 "%s:%d: offset %zu: mismatch\n"
835                 "%s\n"
836                 "\n",
837                 path, lineno, n, l);
838         count_error();
839       }
840       ++tests;
841     }
842     xfree(l);
843   }
844   fclose(fp);
845 }
846
847 /** @brief Tests for @ref lib/unicode.h */
848 static void test_unicode(void) {
849   FILE *fp;
850   int lineno = 0;
851   char *l, *lp;
852   uint32_t buffer[1024];
853   uint32_t *c[6], *NFD_c[6], *NFKD_c[6], *NFC_c[6], *NFKC_c[6]; /* 1-indexed */
854   int cn, bn;
855
856   fprintf(stderr, "test_unicode\n");
857   fp = open_unicode_test("NormalizationTest.txt");
858   while(!inputline("NormalizationTest.txt", fp, &l, '\n')) {
859     ++lineno;
860     if(*l == '#' || *l == '@')
861       continue;
862     bn = 0;
863     cn = 1;
864     lp = l;
865     c[cn++] = &buffer[bn];
866     while(*lp && *lp != '#') {
867       if(*lp == ' ') {
868         ++lp;
869         continue;
870       }
871       if(*lp == ';') {
872         buffer[bn++] = 0;
873         if(cn == 6)
874           break;
875         c[cn++] = &buffer[bn];
876         ++lp;
877         continue;
878       }
879       buffer[bn++] = strtoul(lp, &lp, 16);
880     }
881     buffer[bn] = 0;
882     assert(cn == 6);
883     for(cn = 1; cn <= 5; ++cn) {
884       NFD_c[cn] = utf32_decompose_canon(c[cn], utf32_len(c[cn]), 0);
885       NFKD_c[cn] = utf32_decompose_compat(c[cn], utf32_len(c[cn]), 0);
886       NFC_c[cn] = utf32_compose_canon(c[cn], utf32_len(c[cn]), 0);
887       NFKC_c[cn] = utf32_compose_compat(c[cn], utf32_len(c[cn]), 0);
888     }
889 #define unt_check(T, A, B) do {                                 \
890     ++tests;                                                    \
891     if(utf32_cmp(c[A], T##_c[B])) {                             \
892       fprintf(stderr,                                           \
893               "NormalizationTest.txt:%d: c%d != "#T"(c%d)\n",   \
894               lineno, A, B);                                    \
895       fprintf(stderr, "      c%d:%s\n",                         \
896               A, format_utf32(c[A]));                           \
897       fprintf(stderr, "      c%d:%s\n",                         \
898               B, format_utf32(c[B]));                           \
899       fprintf(stderr, "%4s(c%d):%s\n",                          \
900               #T, B, format_utf32(T##_c[B]));                   \
901       count_error();                                            \
902     }                                                           \
903   } while(0)
904     unt_check(NFD, 3, 1);
905     unt_check(NFD, 3, 2);
906     unt_check(NFD, 3, 3);
907     unt_check(NFD, 5, 4);
908     unt_check(NFD, 5, 5);
909     unt_check(NFKD, 5, 1);
910     unt_check(NFKD, 5, 2);
911     unt_check(NFKD, 5, 3);
912     unt_check(NFKD, 5, 4);
913     unt_check(NFKD, 5, 5);
914     unt_check(NFC, 2, 1);
915     unt_check(NFC, 2, 2);
916     unt_check(NFC, 2, 3);
917     unt_check(NFC, 4, 4);
918     unt_check(NFC, 4, 5);
919     unt_check(NFKC, 4, 1);
920     unt_check(NFKC, 4, 2);
921     unt_check(NFKC, 4, 3);
922     unt_check(NFKC, 4, 4);
923     unt_check(NFKC, 4, 5);
924     for(cn = 1; cn <= 5; ++cn) {
925       xfree(NFD_c[cn]);
926       xfree(NFKD_c[cn]);
927     }
928     xfree(l);
929   }
930   fclose(fp);
931   breaktest("auxiliary/GraphemeBreakTest.txt", utf32_is_grapheme_boundary);
932   breaktest("auxiliary/WordBreakTest.txt", utf32_is_word_boundary);
933   insist(utf32_combining_class(0x40000) == 0);
934   insist(utf32_combining_class(0xE0000) == 0);
935 }
936
937 static void test_signame(void) {
938   fprintf(stderr, "test_signame\n");
939   insist(find_signal("SIGTERM") == SIGTERM);
940   insist(find_signal("SIGHUP") == SIGHUP);
941   insist(find_signal("SIGINT") == SIGINT);
942   insist(find_signal("SIGQUIT") == SIGQUIT);
943   insist(find_signal("SIGKILL") == SIGKILL);
944   insist(find_signal("SIGYOURMUM") == -1);
945 }
946
947 static void test_cache(void) {
948   const struct cache_type t1 = { 1 }, t2 = { 10 };
949   const char v11[] = "spong", v12[] = "wibble", v2[] = "blat";
950   fprintf(stderr, "test_cache\n");
951   cache_put(&t1, "1_1", v11);
952   cache_put(&t1, "1_2", v12);
953   cache_put(&t2, "2", v2);
954   insist(cache_count() == 3);
955   insist(cache_get(&t2, "2") == v2);
956   insist(cache_get(&t1, "1_1") == v11);
957   insist(cache_get(&t1, "1_2") == v12);
958   insist(cache_get(&t1, "2") == 0);
959   insist(cache_get(&t2, "1_1") == 0);
960   insist(cache_get(&t2, "1_2") == 0);
961   insist(cache_get(&t1, "2") == 0);
962   insist(cache_get(&t2, "1_1") == 0);
963   insist(cache_get(&t2, "1_2") == 0);
964   sleep(2);
965   cache_expire();
966   insist(cache_count() == 1);
967   insist(cache_get(&t1, "1_1") == 0);
968   insist(cache_get(&t1, "1_2") == 0);
969   insist(cache_get(&t2, "2") == v2);
970   cache_clean(0);
971   insist(cache_count() == 0);
972   insist(cache_get(&t2, "2") == 0); 
973 }
974
975 static void test_filepart(void) {
976   fprintf(stderr, "test_filepart\n");
977   check_string(d_dirname("/"), "/");
978   check_string(d_dirname("////"), "/");
979   check_string(d_dirname("/spong"), "/");
980   check_string(d_dirname("////spong"), "/");
981   check_string(d_dirname("/foo/bar"), "/foo");
982   check_string(d_dirname("////foo/////bar"), "////foo");
983   check_string(d_dirname("./bar"), ".");
984   check_string(d_dirname(".//bar"), ".");
985   check_string(d_dirname("."), ".");
986   check_string(d_dirname(".."), ".");
987   check_string(d_dirname("../blat"), "..");
988   check_string(d_dirname("..//blat"), "..");
989   check_string(d_dirname("wibble"), ".");
990   check_string(extension("foo.c"), ".c");
991   check_string(extension(".c"), ".c");
992   check_string(extension("."), ".");
993   check_string(extension("foo"), "");
994   check_string(extension("./foo"), "");
995   check_string(extension("./foo.c"), ".c");
996   check_string(strip_extension("foo.c"), "foo");
997   check_string(strip_extension("foo.mp3"), "foo");
998   check_string(strip_extension("foo.---"), "foo.---");
999   check_string(strip_extension("foo.---xyz"), "foo.---xyz");
1000   check_string(strip_extension("foo.bar/wibble.spong"), "foo.bar/wibble");
1001 }
1002
1003 static void test_selection(void) {
1004   hash *h;
1005   fprintf(stderr, "test_selection\n");
1006   insist((h = selection_new()) != 0);
1007   selection_set(h, "one", 1);
1008   selection_set(h, "two", 1);
1009   selection_set(h, "three", 0);
1010   selection_set(h, "four", 1);
1011   insist(selection_selected(h, "one") == 1);
1012   insist(selection_selected(h, "two") == 1);
1013   insist(selection_selected(h, "three") == 0);
1014   insist(selection_selected(h, "four") == 1);
1015   insist(selection_selected(h, "five") == 0);
1016   insist(hash_count(h) == 3);
1017   selection_flip(h, "one"); 
1018   selection_flip(h, "three"); 
1019   insist(selection_selected(h, "one") == 0);
1020   insist(selection_selected(h, "three") == 1);
1021   insist(hash_count(h) == 3);
1022   selection_live(h, "one");
1023   selection_live(h, "two");
1024   selection_live(h, "three");
1025   selection_cleanup(h);
1026   insist(selection_selected(h, "one") == 0);
1027   insist(selection_selected(h, "two") == 1);
1028   insist(selection_selected(h, "three") == 1);
1029   insist(selection_selected(h, "four") == 0);
1030   insist(selection_selected(h, "five") == 0);
1031   insist(hash_count(h) == 2);
1032   selection_empty(h);
1033   insist(selection_selected(h, "one") == 0);
1034   insist(selection_selected(h, "two") == 0);
1035   insist(selection_selected(h, "three") == 0);
1036   insist(selection_selected(h, "four") == 0);
1037   insist(selection_selected(h, "five") == 0);
1038   insist(hash_count(h) == 0);
1039 }
1040
1041 static void test_wstat(void) {
1042   pid_t pid;
1043   int w;
1044   
1045   fprintf(stderr, "test_wstat\n");
1046   if(!(pid = xfork())) {
1047     _exit(1);
1048   }
1049   while(waitpid(pid, &w, 0) < 0 && errno == EINTR)
1050     ;
1051   check_string(wstat(w), "exited with status 1");
1052   if(!(pid = xfork())) {
1053     kill(getpid(), SIGTERM);
1054     _exit(-1);
1055   }
1056   while(waitpid(pid, &w, 0) < 0 && errno == EINTR)
1057     ;
1058   check_string_prefix(wstat(w), "terminated by signal 15");
1059 }
1060
1061 static void test_kvp(void) {
1062   struct kvp *k;
1063   size_t n;
1064   
1065   fprintf(stderr, "test_kvp\n");
1066   /* decoding */
1067 #define KVP_URLDECODE(S) kvp_urldecode((S), strlen(S))
1068   insist(KVP_URLDECODE("=%zz") == 0);
1069   insist(KVP_URLDECODE("=%0") == 0);
1070   insist(KVP_URLDECODE("=%0z") == 0);
1071   insist(KVP_URLDECODE("=%%") == 0);
1072   insist(KVP_URLDECODE("==%") == 0);
1073   insist(KVP_URLDECODE("wibble") == 0);
1074   insist(KVP_URLDECODE("") == 0);
1075   insist(KVP_URLDECODE("wibble&") == 0);
1076   insist((k = KVP_URLDECODE("one=bl%61t+foo")) != 0);
1077   check_string(kvp_get(k, "one"), "blat foo");
1078   insist(kvp_get(k, "ONE") == 0);
1079   insist(k->next == 0);
1080   insist((k = KVP_URLDECODE("wibble=splat&bar=spong")) != 0);
1081   check_string(kvp_get(k, "wibble"), "splat");
1082   check_string(kvp_get(k, "bar"), "spong");
1083   insist(kvp_get(k, "ONE") == 0);
1084   insist(k->next->next == 0);
1085   /* encoding */
1086   insist(kvp_set(&k, "bar", "spong") == 0);
1087   insist(kvp_set(&k, "bar", "foo") == 1);
1088   insist(kvp_set(&k, "zog", "%") == 1);
1089   insist(kvp_set(&k, "wibble", 0) == 1);
1090   insist(kvp_set(&k, "wibble", 0) == 0);
1091   check_string(kvp_urlencode(k, 0),
1092                "bar=foo&zog=%25");
1093   check_string(kvp_urlencode(k, &n),
1094                "bar=foo&zog=%25");
1095   insist(n == strlen("bar=foo&zog=%25"));
1096   check_string(urlencodestring("abc% +\n"),
1097                "abc%25%20%2b%0a");
1098 }
1099
1100 static void test_sink(void) {
1101   struct sink *s;
1102   struct dynstr d[1];
1103   FILE *fp;
1104   char *l;
1105   
1106   fprintf(stderr, "test_sink\n");
1107
1108   fp = tmpfile();
1109   assert(fp != 0);
1110   s = sink_stdio("tmpfile", fp);
1111   insist(sink_printf(s, "test: %d\n", 999) == 10);
1112   insist(sink_printf(s, "wibble: %s\n", "foobar") == 15);
1113   rewind(fp);
1114   insist(inputline("tmpfile", fp, &l, '\n') == 0);
1115   check_string(l, "test: 999");
1116   insist(inputline("tmpfile", fp, &l, '\n') == 0);
1117   check_string(l, "wibble: foobar");
1118   insist(inputline("tmpfile", fp, &l, '\n') == -1);
1119   
1120   dynstr_init(d);
1121   s = sink_dynstr(d);
1122   insist(sink_printf(s, "test: %d\n", 999) == 10);
1123   insist(sink_printf(s, "wibble: %s\n", "foobar") == 15);
1124   dynstr_terminate(d);
1125   check_string(d->vec, "test: 999\nwibble: foobar\n");
1126 }
1127
1128 static const char *do_printf(const char *fmt, ...) {
1129   va_list ap;
1130   char *s;
1131   int rc;
1132
1133   va_start(ap, fmt);
1134   rc = byte_vasprintf(&s, fmt, ap);
1135   va_end(ap);
1136   if(rc < 0)
1137     return 0;
1138   return s;
1139 }
1140
1141 static void test_printf(void) {
1142   char c;
1143   short s;
1144   int i;
1145   long l;
1146   long long ll;
1147   intmax_t m;
1148   ssize_t ssz;
1149   ptrdiff_t p;
1150   char *cp;
1151   char buffer[16];
1152   
1153   fprintf(stderr, "test_printf\n");
1154   check_string(do_printf("%d", 999), "999");
1155   check_string(do_printf("%d", -999), "-999");
1156   check_string(do_printf("%i", 999), "999");
1157   check_string(do_printf("%i", -999), "-999");
1158   check_string(do_printf("%u", 999), "999");
1159   check_string(do_printf("%2u", 999), "999");
1160   check_string(do_printf("%10u", 999), "       999");
1161   check_string(do_printf("%-10u", 999), "999       ");
1162   check_string(do_printf("%010u", 999), "0000000999");
1163   check_string(do_printf("%-10d", -999), "-999      ");
1164   check_string(do_printf("%-010d", -999), "-999      "); /* "-" beats "0" */
1165   check_string(do_printf("%66u", 999), "                                                               999");
1166   check_string(do_printf("%o", 999), "1747");
1167   check_string(do_printf("%#o", 999), "01747");
1168   check_string(do_printf("%#o", 0), "0");
1169   check_string(do_printf("%x", 999), "3e7");
1170   check_string(do_printf("%#x", 999), "0x3e7");
1171   check_string(do_printf("%#X", 999), "0X3E7");
1172   check_string(do_printf("%#x", 0), "0");
1173   check_string(do_printf("%hd", (short)999), "999");
1174   check_string(do_printf("%hhd", (short)99), "99");
1175   check_string(do_printf("%ld", 100000L), "100000");
1176   check_string(do_printf("%lld", 10000000000LL), "10000000000");
1177   check_string(do_printf("%qd", 10000000000LL), "10000000000");
1178   check_string(do_printf("%jd", (intmax_t)10000000000LL), "10000000000");
1179   check_string(do_printf("%zd", (ssize_t)2000000000), "2000000000");
1180   check_string(do_printf("%td", (ptrdiff_t)2000000000), "2000000000");
1181   check_string(do_printf("%hu", (short)999), "999");
1182   check_string(do_printf("%hhu", (short)99), "99");
1183   check_string(do_printf("%lu", 100000L), "100000");
1184   check_string(do_printf("%llu", 10000000000LL), "10000000000");
1185   check_string(do_printf("%ju", (uintmax_t)10000000000LL), "10000000000");
1186   check_string(do_printf("%zu", (size_t)2000000000), "2000000000");
1187   check_string(do_printf("%tu", (ptrdiff_t)2000000000), "2000000000");
1188   check_string(do_printf("%p", (void *)0x100), "0x100");
1189   check_string(do_printf("%s", "wibble"), "wibble");
1190   check_string(do_printf("%s-%s", "wibble", "wobble"), "wibble-wobble");
1191   check_string(do_printf("%10s", "wibble"), "    wibble");
1192   check_string(do_printf("%010s", "wibble"), "    wibble"); /* 0 ignored for %s */
1193   check_string(do_printf("%-10s", "wibble"), "wibble    ");
1194   check_string(do_printf("%2s", "wibble"), "wibble");
1195   check_string(do_printf("%.2s", "wibble"), "wi");
1196   check_string(do_printf("%.2s", "w"), "w");
1197   check_string(do_printf("%4.2s", "wibble"), "  wi");
1198   check_string(do_printf("%c", 'a'), "a");
1199   check_string(do_printf("%4c", 'a'), "   a");
1200   check_string(do_printf("%-4c", 'a'), "a   ");
1201   check_string(do_printf("%*c", 0, 'a'), "a");
1202   check_string(do_printf("x%hhny", &c), "xy");
1203   insist(c == 1);
1204   check_string(do_printf("xx%hnyy", &s), "xxyy");
1205   insist(s == 2);
1206   check_string(do_printf("xxx%nyyy", &i), "xxxyyy");
1207   insist(i == 3);
1208   check_string(do_printf("xxxx%lnyyyy", &l), "xxxxyyyy");
1209   insist(l == 4);
1210   check_string(do_printf("xxxxx%llnyyyyy", &ll), "xxxxxyyyyy");
1211   insist(ll == 5);
1212   check_string(do_printf("xxxxxx%jnyyyyyy", &m), "xxxxxxyyyyyy");
1213   insist(m == 6);
1214   check_string(do_printf("xxxxxxx%znyyyyyyy", &ssz), "xxxxxxxyyyyyyy");
1215   insist(ssz == 7);
1216   check_string(do_printf("xxxxxxxx%tnyyyyyyyy", &p), "xxxxxxxxyyyyyyyy");
1217   insist(p == 8);
1218   check_string(do_printf("%*d", 5, 99), "   99");
1219   check_string(do_printf("%*d", -5, 99), "99   ");
1220   check_string(do_printf("%.*d", 5, 99), "00099");
1221   check_string(do_printf("%.*d", -5, 99), "99");
1222   check_string(do_printf("%.0d", 0), "");
1223   check_string(do_printf("%.d", 0), "");
1224   check_string(do_printf("%.d", 0), "");
1225   check_string(do_printf("%%"), "%");
1226   check_string(do_printf("wibble"), "wibble");
1227   insist(do_printf("%") == 0);
1228   insist(do_printf("%=") == 0);
1229   i = byte_asprintf(&cp, "xyzzy %d", 999);
1230   insist(i == 9);
1231   check_string(cp, "xyzzy 999");
1232   i = byte_snprintf(buffer, sizeof buffer, "xyzzy %d", 999);
1233   insist(i == 9);
1234   check_string(buffer, "xyzzy 999");
1235   i = byte_snprintf(buffer, sizeof buffer, "%*d", 32, 99);
1236   insist(i == 32);
1237   check_string(buffer, "               ");
1238   {
1239     /* bizarre workaround for compiler checking of format strings */
1240     char f[] = "xyzzy %";
1241     i = byte_asprintf(&cp, f);
1242     insist(i == -1);
1243   }
1244 }
1245
1246 static void test_basen(void) {
1247   unsigned long v[64];
1248   char buffer[1024];
1249
1250   fprintf(stderr, "test_basen\n");
1251   v[0] = 999;
1252   insist(basen(v, 1, buffer, sizeof buffer, 10) == 0);
1253   check_string(buffer, "999");
1254
1255   v[0] = 1+2*7+3*7*7+4*7*7*7;
1256   insist(basen(v, 1, buffer, sizeof buffer, 7) == 0);
1257   check_string(buffer, "4321");
1258
1259   v[0] = 0x00010203;
1260   v[1] = 0x04050607;
1261   v[2] = 0x08090A0B;
1262   v[3] = 0x0C0D0E0F;
1263   insist(basen(v, 4, buffer, sizeof buffer, 256) == 0);
1264   check_string(buffer, "123456789abcdef");
1265
1266   v[0] = 0x00010203;
1267   v[1] = 0x04050607;
1268   v[2] = 0x08090A0B;
1269   v[3] = 0x0C0D0E0F;
1270   insist(basen(v, 4, buffer, sizeof buffer, 16) == 0);
1271   check_string(buffer, "102030405060708090a0b0c0d0e0f");
1272
1273   v[0] = 0x00010203;
1274   v[1] = 0x04050607;
1275   v[2] = 0x08090A0B;
1276   v[3] = 0x0C0D0E0F;
1277   insist(basen(v, 4, buffer, 10, 16) == -1);
1278 }
1279
1280 static void test_split(void) {
1281   char **v;
1282   int nv;
1283
1284   fprintf(stderr, "test_split\n");
1285   insist(split("\"misquoted", &nv, SPLIT_COMMENTS|SPLIT_QUOTES, 0, 0) == 0);
1286   insist(split("\'misquoted", &nv, SPLIT_COMMENTS|SPLIT_QUOTES, 0, 0) == 0);
1287   insist(split("\'misquoted\\", &nv, SPLIT_COMMENTS|SPLIT_QUOTES, 0, 0) == 0);
1288   insist(split("\'misquoted\\\"", &nv, SPLIT_COMMENTS|SPLIT_QUOTES, 0, 0) == 0);
1289   insist(split("\'mis\\escaped\'", &nv, SPLIT_COMMENTS|SPLIT_QUOTES, 0, 0) == 0);
1290
1291   insist((v = split("", &nv, SPLIT_COMMENTS|SPLIT_QUOTES, 0, 0)));
1292   check_integer(nv, 0);
1293   insist(*v == 0);
1294
1295   insist((v = split("wibble", &nv, SPLIT_COMMENTS|SPLIT_QUOTES, 0, 0)));
1296   check_integer(nv, 1);
1297   check_string(v[0], "wibble");
1298   insist(v[1] == 0);
1299
1300   insist((v = split("   wibble \t\r\n wobble   ", &nv,
1301                     SPLIT_COMMENTS|SPLIT_QUOTES, 0, 0)));
1302   check_integer(nv, 2);
1303   check_string(v[0], "wibble");
1304   check_string(v[1], "wobble");
1305   insist(v[2] == 0);
1306
1307   insist((v = split("wibble wobble #splat", &nv,
1308                     SPLIT_COMMENTS|SPLIT_QUOTES, 0, 0)));
1309   check_integer(nv, 2);
1310   check_string(v[0], "wibble");
1311   check_string(v[1], "wobble");
1312   insist(v[2] == 0);
1313
1314   insist((v = split("\"wibble wobble\" #splat", &nv,
1315                     SPLIT_COMMENTS|SPLIT_QUOTES, 0, 0)));
1316   check_integer(nv, 1);
1317   check_string(v[0], "wibble wobble");
1318   insist(v[1] == 0);
1319
1320   insist((v = split("\"wibble \\\"\\nwobble\"", &nv,
1321                     SPLIT_COMMENTS|SPLIT_QUOTES, 0, 0)));
1322   check_integer(nv, 1);
1323   check_string(v[0], "wibble \"\nwobble");
1324   insist(v[1] == 0);
1325
1326   insist((v = split("\"wibble wobble\" #splat", &nv,
1327                     SPLIT_QUOTES, 0, 0)));
1328   check_integer(nv, 2);
1329   check_string(v[0], "wibble wobble");
1330   check_string(v[1], "#splat");
1331   insist(v[2] == 0);
1332
1333   insist((v = split("\"wibble wobble\" #splat", &nv,
1334                     SPLIT_COMMENTS, 0, 0)));
1335   check_integer(nv, 2);
1336   check_string(v[0], "\"wibble");
1337   check_string(v[1], "wobble\"");
1338   insist(v[2] == 0);
1339
1340   check_string(quoteutf8("wibble"), "wibble");
1341   check_string(quoteutf8("  wibble  "), "\"  wibble  \"");
1342   check_string(quoteutf8("wibble wobble"), "\"wibble wobble\"");
1343   check_string(quoteutf8("wibble\"wobble"), "\"wibble\\\"wobble\"");
1344   check_string(quoteutf8("wibble\nwobble"), "\"wibble\\nwobble\"");
1345   check_string(quoteutf8("wibble\\wobble"), "\"wibble\\\\wobble\"");
1346   check_string(quoteutf8("wibble'wobble"), "\"wibble'wobble\"");
1347 }
1348
1349 static void test_hash(void) {
1350   hash *h;
1351   int i, *ip;
1352   char **keys;
1353
1354   fprintf(stderr, "test_hash\n");
1355   h = hash_new(sizeof(int));
1356   for(i = 0; i < 10000; ++i)
1357     insist(hash_add(h, do_printf("%d", i), &i, HASH_INSERT) == 0);
1358   check_integer(hash_count(h), 10000);
1359   for(i = 0; i < 10000; ++i) {
1360     insist((ip = hash_find(h, do_printf("%d", i))) != 0);
1361     check_integer(*ip, i);
1362     insist(hash_add(h, do_printf("%d", i), &i, HASH_REPLACE) == 0);
1363   }
1364   check_integer(hash_count(h), 10000);
1365   keys = hash_keys(h);
1366   for(i = 0; i < 10000; ++i)
1367     insist(keys[i] != 0);
1368   insist(keys[10000] == 0);
1369   for(i = 0; i < 10000; ++i)
1370     insist(hash_remove(h, do_printf("%d", i)) == 0);
1371   check_integer(hash_count(h), 0);
1372 }
1373
1374 static void test_addr(void) {
1375   struct stringlist a;
1376   const char *s[2];
1377   struct addrinfo *ai;
1378   char *name;
1379   const struct sockaddr_in *sin;
1380
1381   static const struct addrinfo pref = {
1382     AI_PASSIVE,
1383     PF_INET,
1384     SOCK_STREAM,
1385     0,
1386     0,
1387     0,
1388     0,
1389     0
1390   };
1391
1392   printf("test_addr\n");
1393
1394   a.n = 1;
1395   a.s = (char **)s;
1396   s[0] = "smtp";
1397   ai = get_address(&a, &pref, &name);
1398   insist(ai != 0);
1399   check_integer(ai->ai_family, PF_INET);
1400   check_integer(ai->ai_socktype, SOCK_STREAM);
1401   check_integer(ai->ai_protocol, IPPROTO_TCP);
1402   check_integer(ai->ai_addrlen, sizeof(struct sockaddr_in));
1403   sin = (const struct sockaddr_in *)ai->ai_addr;
1404   check_integer(sin->sin_family, AF_INET);
1405   check_integer(sin->sin_addr.s_addr, 0);
1406   check_integer(ntohs(sin->sin_port), 25);
1407   check_string(name, "host * service smtp");
1408
1409   a.n = 2;
1410   s[0] = "localhost";
1411   s[1] = "nntp";
1412   ai = get_address(&a, &pref, &name);
1413   insist(ai != 0);
1414   check_integer(ai->ai_family, PF_INET);
1415   check_integer(ai->ai_socktype, SOCK_STREAM);
1416   check_integer(ai->ai_protocol, IPPROTO_TCP);
1417   check_integer(ai->ai_addrlen, sizeof(struct sockaddr_in));
1418   sin = (const struct sockaddr_in *)ai->ai_addr;
1419   check_integer(sin->sin_family, AF_INET);
1420   check_integer(ntohl(sin->sin_addr.s_addr), 0x7F000001);
1421   check_integer(ntohs(sin->sin_port), 119);
1422   check_string(name, "host localhost service nntp");
1423 }
1424
1425 static void test_url(void) {
1426   struct url p;
1427   
1428   printf("test_url\n");
1429
1430   insist(parse_url("http://www.example.com/example/path", &p) == 0);
1431   check_string(p.scheme, "http");
1432   check_string(p.host, "www.example.com");
1433   insist(p.port == -1);
1434   check_string(p.path, "/example/path");
1435   insist(p.query == 0);
1436
1437   insist(parse_url("https://www.example.com:82/example%2fpath?+query+", &p) == 0);
1438   check_string(p.scheme, "https");
1439   check_string(p.host, "www.example.com");
1440   insist(p.port == 82);
1441   check_string(p.path, "/example/path");
1442   check_string(p.query, "+query+");
1443 }
1444
1445 int main(void) {
1446   mem_init();
1447   fail_first = !!getenv("FAIL_FIRST");
1448   insist('\n' == 0x0A);
1449   insist('\r' == 0x0D);
1450   insist(' ' == 0x20);
1451   insist('0' == 0x30);
1452   insist('9' == 0x39);
1453   insist('A' == 0x41);
1454   insist('Z' == 0x5A);
1455   insist('a' == 0x61);
1456   insist('z' == 0x7A);
1457   /* addr.c */
1458   test_addr();
1459   /* asprintf.c */
1460   /* authhash.c */
1461   /* basen.c */
1462   test_basen();
1463   /* charset.c */
1464   /* client.c */
1465   /* configuration.c */
1466   /* event.c */
1467   /* filepart.c */
1468   test_filepart();
1469   /* fprintf.c */
1470   /* heap.c */
1471   test_heap();
1472   /* hex.c */
1473   test_hex();
1474   /* inputline.c */
1475   /* kvp.c */
1476   test_kvp();
1477   /* log.c */
1478   /* mem.c */
1479   /* mime.c */
1480   test_mime();
1481   test_cookies();
1482   /* mixer.c */
1483   /* plugin.c */
1484   /* printf.c */
1485   test_printf();
1486   /* queue.c */
1487   /* sink.c */
1488   test_sink();
1489   /* snprintf.c */
1490   /* split.c */
1491   test_split();
1492   /* syscalls.c */
1493   /* table.c */
1494   /* unicode.c */
1495   test_unicode();
1496   /* utf8.c */
1497   test_utf8();
1498   /* vector.c */
1499   /* words.c */
1500   test_casefold();
1501   test_words();
1502   /* wstat.c */
1503   test_wstat();
1504   /* signame.c */
1505   test_signame();
1506   /* cache.c */
1507   test_cache();
1508   /* selection.c */
1509   test_selection();
1510   test_hash();
1511   test_url();
1512   fprintf(stderr,  "%d errors out of %d tests\n", errors, tests);
1513   return !!errors;
1514 }
1515   
1516 /*
1517 Local Variables:
1518 c-basic-offset:2
1519 comment-column:40
1520 fill-column:79
1521 indent-tabs-mode:nil
1522 End:
1523 */