chiark / gitweb /
keep cookie more private to disorder.cgi
[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
301   fprintf(stderr, "test_mime\n");
302
303   t = n = v = 0;
304   insist(!mime_content_type("text/plain", &t, &n, &v));
305   check_string(t, "text/plain");
306   insist(n == 0);
307   insist(v == 0);
308
309   insist(mime_content_type("TEXT ((broken) comment", &t, &n, &v) < 0);
310   insist(mime_content_type("TEXT ((broken) comment\\", &t, &n, &v) < 0);
311   
312   t = n = v = 0;
313   insist(!mime_content_type("TEXT ((nested)\\ comment) /plain", &t, &n, &v));
314   check_string(t, "text/plain");
315   insist(n == 0);
316   insist(v == 0);
317
318   t = n = v = 0;
319   insist(!mime_content_type(" text/plain ; Charset=\"utf-\\8\"", &t, &n, &v));
320   check_string(t, "text/plain");
321   check_string(n, "charset");
322   check_string(v, "utf-8");
323
324   t = n = v = 0;
325   insist(!mime_content_type("text/plain;charset = ISO-8859-1 ", &t, &n, &v));
326   check_string(t, "text/plain");
327   check_string(n, "charset");
328   check_string(v, "ISO-8859-1");
329
330   t = n = v = 0;
331   insist(!mime_rfc2388_content_disposition("form-data; name=\"field1\"", &t, &n, &v));
332   check_string(t, "form-data");
333   check_string(n, "name");
334   check_string(v, "field1");
335
336   insist(!mime_rfc2388_content_disposition("inline", &t, &n, &v));
337   check_string(t, "inline");
338   insist(n == 0);
339   insist(v == 0);
340
341   /* Current versions of the code only understand a single arg to these
342    * headers.  This is a bug at the level they work at but suffices for
343    * DisOrder's current purposes. */
344
345   insist(!mime_rfc2388_content_disposition(
346               "attachment; filename=genome.jpeg;\n"
347               "modification-date=\"Wed, 12 Feb 1997 16:29:51 -0500\"",
348          &t, &n, &v));
349   check_string(t, "attachment");
350   check_string(n, "filename");
351   check_string(v, "genome.jpeg");
352
353   vector_init(parts);
354   insist(mime_multipart("--outer\r\n"
355                         "Content-Type: text/plain\r\n"
356                         "Content-Disposition: inline\r\n"
357                         "Content-Description: text-part-1\r\n"
358                         "\r\n"
359                         "Some text goes here\r\n"
360                         "\r\n"
361                         "--outer\r\n"
362                         "Content-Type: multipart/mixed; boundary=inner\r\n"
363                         "Content-Disposition: attachment\r\n"
364                         "Content-Description: multipart-2\r\n"
365                         "\r\n"
366                         "--inner\r\n"
367                         "Content-Type: text/plain\r\n"
368                         "Content-Disposition: inline\r\n"
369                         "Content-Description: text-part-2\r\n"
370                         "\r\n"
371                         "Some more text here.\r\n"
372                         "\r\n"
373                         "--inner\r\n"
374                         "Content-Type: image/jpeg\r\n"
375                         "Content-Disposition: attachment\r\n"
376                         "Content-Description: jpeg-1\r\n"
377                         "\r\n"
378                         "<jpeg data>\r\n"
379                         "--inner--\r\n"
380                         "--outer--\r\n",
381                         test_multipart_callback,
382                         "outer",
383                         parts) == 0);
384   check_integer(parts->nvec, 2);
385   check_string(parts->vec[0],
386                "Content-Type: text/plain\r\n"
387                "Content-Disposition: inline\r\n"
388                "Content-Description: text-part-1\r\n"
389                "\r\n"
390                "Some text goes here\r\n");
391   check_string(parts->vec[1],
392                "Content-Type: multipart/mixed; boundary=inner\r\n"
393                "Content-Disposition: attachment\r\n"
394                "Content-Description: multipart-2\r\n"
395                "\r\n"
396                "--inner\r\n"
397                "Content-Type: text/plain\r\n"
398                "Content-Disposition: inline\r\n"
399                "Content-Description: text-part-2\r\n"
400                "\r\n"
401                "Some more text here.\r\n"
402                "\r\n"
403                "--inner\r\n"
404                "Content-Type: image/jpeg\r\n"
405                "Content-Disposition: attachment\r\n"
406                "Content-Description: jpeg-1\r\n"
407                "\r\n"
408                "<jpeg data>\r\n"
409                "--inner--");
410   /* No trailing CRLF is _correct_ - see RFC2046 5.1.1 note regarding CRLF
411    * preceding the boundary delimiter line.  An implication of this is that we
412    * must cope with partial lines at the end of the input when recursively
413    * decomposing a multipart message. */
414   vector_init(parts);
415   insist(mime_multipart("--inner\r\n"
416                         "Content-Type: text/plain\r\n"
417                         "Content-Disposition: inline\r\n"
418                         "Content-Description: text-part-2\r\n"
419                         "\r\n"
420                         "Some more text here.\r\n"
421                         "\r\n"
422                         "--inner\r\n"
423                         "Content-Type: image/jpeg\r\n"
424                         "Content-Disposition: attachment\r\n"
425                         "Content-Description: jpeg-1\r\n"
426                         "\r\n"
427                         "<jpeg data>\r\n"
428                         "--inner--",
429                         test_multipart_callback,
430                         "inner",
431                         parts) == 0);
432   check_integer(parts->nvec, 2);
433   check_string(parts->vec[0],
434                "Content-Type: text/plain\r\n"
435                "Content-Disposition: inline\r\n"
436                "Content-Description: text-part-2\r\n"
437                "\r\n"
438                "Some more text here.\r\n");
439   check_string(parts->vec[1],
440                "Content-Type: image/jpeg\r\n"
441                "Content-Disposition: attachment\r\n"
442                "Content-Description: jpeg-1\r\n"
443                "\r\n"
444                "<jpeg data>");
445  
446   /* XXX mime_parse */
447
448   check_string(mime_qp(""), "");
449   check_string(mime_qp("foobar"), "foobar");
450   check_string(mime_qp("foo=20bar"), "foo bar");
451   check_string(mime_qp("x \r\ny"), "x\r\ny");
452   check_string(mime_qp("x=\r\ny"), "xy");
453   check_string(mime_qp("x= \r\ny"), "xy");
454   check_string(mime_qp("x =\r\ny"), "x y");
455   check_string(mime_qp("x = \r\ny"), "x y");
456
457   /* from RFC2045 */
458   check_string(mime_qp("Now's the time =\r\n"
459 "for all folk to come=\r\n"
460 " to the aid of their country."),
461                "Now's the time for all folk to come to the aid of their country.");
462
463 #define check_base64(encoded, decoded) do {                     \
464     check_string(mime_base64(encoded, 0), decoded);             \
465     check_string(mime_to_base64((const uint8_t *)decoded,       \
466                                          (sizeof decoded) - 1), \
467                  encoded);                                      \
468   } while(0)
469     
470   
471   check_base64("",  "");
472   check_base64("BBBB", "\x04\x10\x41");
473   check_base64("////", "\xFF\xFF\xFF");
474   check_base64("//BB", "\xFF\xF0\x41");
475   check_base64("BBBB//BB////",
476              "\x04\x10\x41" "\xFF\xF0\x41" "\xFF\xFF\xFF");
477   check_base64("BBBBBA==",
478                "\x04\x10\x41" "\x04");
479   check_base64("BBBBBBA=",
480                "\x04\x10\x41" "\x04\x10");
481
482   /* Check that decoding handles various kinds of rubbish OK */
483   check_string(mime_base64("B B B B  / / B B / / / /", 0),
484              "\x04\x10\x41" "\xFF\xF0\x41" "\xFF\xFF\xFF");
485   check_string(mime_base64("B\r\nBBB.// B-B//~//", 0),
486                "\x04\x10\x41" "\xFF\xF0\x41" "\xFF\xFF\xFF");
487   check_string(mime_base64("BBBB BB==", 0),
488                "\x04\x10\x41" "\x04");
489   check_string(mime_base64("BBBB BB = =", 0),
490                "\x04\x10\x41" "\x04");
491   check_string(mime_base64("BBBB BBB=", 0),
492                "\x04\x10\x41" "\x04\x10");
493   check_string(mime_base64("BBBB BBB = ", 0),
494                "\x04\x10\x41" "\x04\x10");
495   check_string(mime_base64("BBBB=", 0),
496                "\x04\x10\x41");
497   check_string(mime_base64("BBBBBB==", 0),
498                "\x04\x10\x41" "\x04");
499   check_string(mime_base64("BBBBBBB=", 0),
500                "\x04\x10\x41" "\x04\x10");
501   /* Not actually valid base64 */
502   check_string(mime_base64("BBBBx=", 0),
503                "\x04\x10\x41");
504 }
505
506 static void test_cookies(void) {
507   struct cookiedata cd[1];
508
509   fprintf(stderr, "test_cookies\n");
510
511   /* These are the examples from RFC2109 */
512   insist(!parse_cookie("$Version=\"1\"; Customer=\"WILE_E_COYOTE\"; $Path=\"/acme\"", cd));
513   insist(!strcmp(cd->version, "1"));
514   insist(cd->ncookies = 1);
515   insist(find_cookie(cd, "Customer") == &cd->cookies[0]);
516   check_string(cd->cookies[0].value, "WILE_E_COYOTE");
517   check_string(cd->cookies[0].path, "/acme");
518   insist(cd->cookies[0].domain == 0);
519   insist(!parse_cookie("$Version=\"1\";\n"
520                        "Customer=\"WILE_E_COYOTE\"; $Path=\"/acme\";\n"
521                        "Part_Number=\"Rocket_Launcher_0001\"; $Path=\"/acme\"",
522                        cd));
523   insist(cd->ncookies = 2);
524   insist(find_cookie(cd, "Customer") == &cd->cookies[0]);
525   insist(find_cookie(cd, "Part_Number") == &cd->cookies[1]);
526   check_string(cd->cookies[0].value, "WILE_E_COYOTE");
527   check_string(cd->cookies[0].path, "/acme");
528   insist(cd->cookies[0].domain == 0);
529   check_string(cd->cookies[1].value, "Rocket_Launcher_0001");
530   check_string(cd->cookies[1].path, "/acme");
531   insist(cd->cookies[1].domain == 0);
532   insist(!parse_cookie("$Version=\"1\";\n"
533                        "Customer=\"WILE_E_COYOTE\"; $Path=\"/acme\";\n"
534                        "Part_Number=\"Rocket_Launcher_0001\"; $Path=\"/acme\";\n"
535                        "Shipping=\"FedEx\"; $Path=\"/acme\"",
536                        cd));
537   insist(cd->ncookies = 3);
538   insist(find_cookie(cd, "Customer") == &cd->cookies[0]);
539   insist(find_cookie(cd, "Part_Number") == &cd->cookies[1]);
540   insist(find_cookie(cd, "Shipping") == &cd->cookies[2]);
541   check_string(cd->cookies[0].value, "WILE_E_COYOTE");
542   check_string(cd->cookies[0].path, "/acme");
543   insist(cd->cookies[0].domain == 0);
544   check_string(cd->cookies[1].value, "Rocket_Launcher_0001");
545   check_string(cd->cookies[1].path, "/acme");
546   insist(cd->cookies[1].domain == 0);
547   check_string(cd->cookies[2].value, "FedEx");
548   check_string(cd->cookies[2].path, "/acme");
549   insist(cd->cookies[2].domain == 0);
550 }
551
552 static void test_hex(void) {
553   unsigned n;
554   static const unsigned char h[] = { 0x00, 0xFF, 0x80, 0x7F };
555   uint8_t *u;
556   size_t ul;
557
558   fprintf(stderr, "test_hex\n");
559
560   for(n = 0; n <= UCHAR_MAX; ++n) {
561     if(!isxdigit(n))
562       insist(unhexdigitq(n) == -1);
563   }
564   insist(unhexdigitq('0') == 0);
565   insist(unhexdigitq('1') == 1);
566   insist(unhexdigitq('2') == 2);
567   insist(unhexdigitq('3') == 3);
568   insist(unhexdigitq('4') == 4);
569   insist(unhexdigitq('5') == 5);
570   insist(unhexdigitq('6') == 6);
571   insist(unhexdigitq('7') == 7);
572   insist(unhexdigitq('8') == 8);
573   insist(unhexdigitq('9') == 9);
574   insist(unhexdigitq('a') == 10);
575   insist(unhexdigitq('b') == 11);
576   insist(unhexdigitq('c') == 12);
577   insist(unhexdigitq('d') == 13);
578   insist(unhexdigitq('e') == 14);
579   insist(unhexdigitq('f') == 15);
580   insist(unhexdigitq('A') == 10);
581   insist(unhexdigitq('B') == 11);
582   insist(unhexdigitq('C') == 12);
583   insist(unhexdigitq('D') == 13);
584   insist(unhexdigitq('E') == 14);
585   insist(unhexdigitq('F') == 15);
586   check_string(hex(h, sizeof h), "00ff807f");
587   check_string(hex(0, 0), "");
588   u = unhex("00ff807f", &ul);
589   insist(ul == 4);
590   insist(memcmp(u, h, 4) == 0);
591   u = unhex("00FF807F", &ul);
592   insist(ul == 4);
593   insist(memcmp(u, h, 4) == 0);
594   u = unhex("", &ul);
595   insist(ul == 0);
596   fprintf(stderr, "2 ERROR reports expected {\n");
597   insist(unhex("F", 0) == 0);
598   insist(unhex("az", 0) == 0);
599   fprintf(stderr, "}\n");
600 }
601
602 static void test_casefold(void) {
603   uint32_t c, l;
604   const char *input, *canon_folded, *compat_folded, *canon_expected, *compat_expected;
605
606   fprintf(stderr, "test_casefold\n");
607
608   /* This isn't a very exhaustive test.  Unlike for normalization, there don't
609    * seem to be any public test vectors for these algorithms. */
610   
611   for(c = 1; c < 256; ++c) {
612     input = utf32_to_utf8(&c, 1, 0);
613     canon_folded = utf8_casefold_canon(input, strlen(input), 0);
614     compat_folded = utf8_casefold_compat(input, strlen(input), 0);
615     switch(c) {
616     default:
617       if((c >= 'A' && c <= 'Z')
618          || (c >= 0xC0 && c <= 0xDE && c != 0xD7))
619         l = c ^ 0x20;
620       else
621         l = c;
622       break;
623     case 0xB5:                          /* MICRO SIGN */
624       l = 0x3BC;                        /* GREEK SMALL LETTER MU */
625       break;
626     case 0xDF:                          /* LATIN SMALL LETTER SHARP S */
627       check_string(canon_folded, "ss");
628       check_string(compat_folded, "ss");
629       l = 0;
630       break;
631     }
632     if(l) {
633       uint32_t *d;
634       /* Case-folded data is now normalized */
635       d = utf32_decompose_canon(&l, 1, 0);
636       canon_expected = utf32_to_utf8(d, utf32_len(d), 0);
637       if(strcmp(canon_folded, canon_expected)) {
638         fprintf(stderr, "%s:%d: canon-casefolding %#lx got '%s', expected '%s'\n",
639                 __FILE__, __LINE__, (unsigned long)c,
640                 format(canon_folded), format(canon_expected));
641         count_error();
642       }
643       ++tests;
644       d = utf32_decompose_compat(&l, 1, 0);
645       compat_expected = utf32_to_utf8(d, utf32_len(d), 0);
646       if(strcmp(compat_folded, compat_expected)) {
647         fprintf(stderr, "%s:%d: compat-casefolding %#lx got '%s', expected '%s'\n",
648                 __FILE__, __LINE__, (unsigned long)c,
649                 format(compat_folded), format(compat_expected));
650         count_error();
651       }
652       ++tests;
653     }
654   }
655   check_string(utf8_casefold_canon("", 0, 0), "");
656 }
657
658 struct {
659   const char *in;
660   const char *expect[10];
661 } wtest[] = {
662   /* Empty string */
663   { "", { 0 } },
664   /* Only whitespace and punctuation */
665   { "    ", { 0 } },
666   { " '   ", { 0 } },
667   { " !  ", { 0 } },
668   { " \"\"  ", { 0 } },
669   { " @  ", { 0 } },
670   /* Basics */
671   { "wibble", { "wibble", 0 } },
672   { " wibble", { "wibble", 0 } },
673   { " wibble ", { "wibble", 0 } },
674   { "wibble ", { "wibble", 0 } },
675   { "wibble spong", { "wibble", "spong", 0 } },
676   { " wibble  spong", { "wibble", "spong", 0 } },
677   { " wibble  spong   ", { "wibble", "spong", 0 } },
678   { "wibble   spong  ", { "wibble", "spong", 0 } },
679   { "wibble   spong splat foo zot  ", { "wibble", "spong", "splat", "foo", "zot", 0 } },
680   /* Apostrophes */
681   { "wibble 'spong", { "wibble", "spong", 0 } },
682   { " wibble's", { "wibble's", 0 } },
683   { " wibblespong'   ", { "wibblespong", 0 } },
684   { "wibble   sp''ong  ", { "wibble", "sp", "ong", 0 } },
685 };
686 #define NWTEST (sizeof wtest / sizeof *wtest)
687
688 static void test_words(void) {
689   size_t t, nexpect, ngot, i;
690   int right;
691   
692   fprintf(stderr, "test_words\n");
693   for(t = 0; t < NWTEST; ++t) {
694     char **got = utf8_word_split(wtest[t].in, strlen(wtest[t].in), &ngot, 0);
695
696     for(nexpect = 0; wtest[t].expect[nexpect]; ++nexpect)
697       ;
698     if(nexpect == ngot) {
699       for(i = 0; i < ngot; ++i)
700         if(strcmp(wtest[t].expect[i], got[i]))
701           break;
702       right = i == ngot;
703     } else
704       right = 0;
705     if(!right) {
706       fprintf(stderr, "word split %zu failed\n", t);
707       fprintf(stderr, "input: %s\n", wtest[t].in);
708       fprintf(stderr, "    | %-30s | %-30s\n",
709               "expected", "got");
710       for(i = 0; i < nexpect || i < ngot; ++i) {
711         const char *e = i < nexpect ? wtest[t].expect[i] : "<none>";
712         const char *g = i < ngot ? got[i] : "<none>";
713         fprintf(stderr, " %2zu | %-30s | %-30s\n", i, e, g);
714       }
715       count_error();
716     }
717     ++tests;
718   }
719 }
720
721 /** @brief Less-than comparison function for integer heap */
722 static inline int int_lt(int a, int b) { return a < b; }
723
724 /** @struct iheap
725  * @brief A heap with @c int elements */
726 HEAP_TYPE(iheap, int, int_lt);
727 HEAP_DEFINE(iheap, int, int_lt);
728
729 /** @brief Tests for @ref heap.h */
730 static void test_heap(void) {
731   struct iheap h[1];
732   int n;
733   int last = -1;
734
735   fprintf(stderr, "test_heap\n");
736
737   iheap_init(h);
738   for(n = 0; n < 1000; ++n)
739     iheap_insert(h, random() % 100);
740   for(n = 0; n < 1000; ++n) {
741     const int latest = iheap_remove(h);
742     if(last > latest)
743       fprintf(stderr, "should have %d <= %d\n", last, latest);
744     insist(last <= latest);
745     last = latest;
746   }
747   putchar('\n');
748 }
749
750 /** @brief Open a Unicode test file */
751 static FILE *open_unicode_test(const char *path) {
752   const char *base;
753   FILE *fp;
754   char buffer[1024];
755   int w;
756
757   if((base = strrchr(path, '/')))
758     ++base;
759   else
760     base = path;
761   if(!(fp = fopen(base, "r"))) {
762     snprintf(buffer, sizeof buffer,
763              "wget http://www.unicode.org/Public/5.0.0/ucd/%s", path);
764     if((w = system(buffer)))
765       fatal(0, "%s: %s", buffer, wstat(w));
766     if(chmod(base, 0444) < 0)
767       fatal(errno, "chmod %s", base);
768     if(!(fp = fopen(base, "r")))
769       fatal(errno, "%s", base);
770   }
771   return fp;
772 }
773
774 /** @brief Run breaking tests for utf32_grapheme_boundary() etc */
775 static void breaktest(const char *path,
776                       int (*breakfn)(const uint32_t *, size_t, size_t)) {
777   FILE *fp = open_unicode_test(path);
778   int lineno = 0;
779   char *l, *lp;
780   size_t bn, n;
781   char break_allowed[1024];
782   uint32_t buffer[1024];
783
784   while(!inputline(path, fp, &l, '\n')) {
785     ++lineno;
786     if(l[0] == '#') continue;
787     bn = 0;
788     lp = l;
789     while(*lp) {
790       if(*lp == ' ' || *lp == '\t') {
791         ++lp;
792         continue;
793       }
794       if(*lp == '#')
795         break;
796       if((unsigned char)*lp == 0xC3 && (unsigned char)lp[1] == 0xB7) {
797         /* 00F7 DIVISION SIGN */
798         break_allowed[bn] = 1;
799         lp += 2;
800         continue;
801       }
802       if((unsigned char)*lp == 0xC3 && (unsigned char)lp[1] == 0x97) {
803         /* 00D7 MULTIPLICATION SIGN */
804         break_allowed[bn] = 0;
805         lp += 2;
806         continue;
807       }
808       if(isxdigit((unsigned char)*lp)) {
809         buffer[bn++] = strtoul(lp, &lp, 16);
810         continue;
811       }
812       fatal(0, "%s:%d: evil line: %s", path, lineno, l);
813     }
814     for(n = 0; n <= bn; ++n) {
815       if(breakfn(buffer, bn, n) != break_allowed[n]) {
816         fprintf(stderr,
817                 "%s:%d: offset %zu: mismatch\n"
818                 "%s\n"
819                 "\n",
820                 path, lineno, n, l);
821         count_error();
822       }
823       ++tests;
824     }
825     xfree(l);
826   }
827   fclose(fp);
828 }
829
830 /** @brief Tests for @ref lib/unicode.h */
831 static void test_unicode(void) {
832   FILE *fp;
833   int lineno = 0;
834   char *l, *lp;
835   uint32_t buffer[1024];
836   uint32_t *c[6], *NFD_c[6], *NFKD_c[6], *NFC_c[6], *NFKC_c[6]; /* 1-indexed */
837   int cn, bn;
838
839   fprintf(stderr, "test_unicode\n");
840   fp = open_unicode_test("NormalizationTest.txt");
841   while(!inputline("NormalizationTest.txt", fp, &l, '\n')) {
842     ++lineno;
843     if(*l == '#' || *l == '@')
844       continue;
845     bn = 0;
846     cn = 1;
847     lp = l;
848     c[cn++] = &buffer[bn];
849     while(*lp && *lp != '#') {
850       if(*lp == ' ') {
851         ++lp;
852         continue;
853       }
854       if(*lp == ';') {
855         buffer[bn++] = 0;
856         if(cn == 6)
857           break;
858         c[cn++] = &buffer[bn];
859         ++lp;
860         continue;
861       }
862       buffer[bn++] = strtoul(lp, &lp, 16);
863     }
864     buffer[bn] = 0;
865     assert(cn == 6);
866     for(cn = 1; cn <= 5; ++cn) {
867       NFD_c[cn] = utf32_decompose_canon(c[cn], utf32_len(c[cn]), 0);
868       NFKD_c[cn] = utf32_decompose_compat(c[cn], utf32_len(c[cn]), 0);
869       NFC_c[cn] = utf32_compose_canon(c[cn], utf32_len(c[cn]), 0);
870       NFKC_c[cn] = utf32_compose_compat(c[cn], utf32_len(c[cn]), 0);
871     }
872 #define unt_check(T, A, B) do {                                 \
873     ++tests;                                                    \
874     if(utf32_cmp(c[A], T##_c[B])) {                             \
875       fprintf(stderr,                                           \
876               "NormalizationTest.txt:%d: c%d != "#T"(c%d)\n",   \
877               lineno, A, B);                                    \
878       fprintf(stderr, "      c%d:%s\n",                         \
879               A, format_utf32(c[A]));                           \
880       fprintf(stderr, "      c%d:%s\n",                         \
881               B, format_utf32(c[B]));                           \
882       fprintf(stderr, "%4s(c%d):%s\n",                          \
883               #T, B, format_utf32(T##_c[B]));                   \
884       count_error();                                            \
885     }                                                           \
886   } while(0)
887     unt_check(NFD, 3, 1);
888     unt_check(NFD, 3, 2);
889     unt_check(NFD, 3, 3);
890     unt_check(NFD, 5, 4);
891     unt_check(NFD, 5, 5);
892     unt_check(NFKD, 5, 1);
893     unt_check(NFKD, 5, 2);
894     unt_check(NFKD, 5, 3);
895     unt_check(NFKD, 5, 4);
896     unt_check(NFKD, 5, 5);
897     unt_check(NFC, 2, 1);
898     unt_check(NFC, 2, 2);
899     unt_check(NFC, 2, 3);
900     unt_check(NFC, 4, 4);
901     unt_check(NFC, 4, 5);
902     unt_check(NFKC, 4, 1);
903     unt_check(NFKC, 4, 2);
904     unt_check(NFKC, 4, 3);
905     unt_check(NFKC, 4, 4);
906     unt_check(NFKC, 4, 5);
907     for(cn = 1; cn <= 5; ++cn) {
908       xfree(NFD_c[cn]);
909       xfree(NFKD_c[cn]);
910     }
911     xfree(l);
912   }
913   fclose(fp);
914   breaktest("auxiliary/GraphemeBreakTest.txt", utf32_is_grapheme_boundary);
915   breaktest("auxiliary/WordBreakTest.txt", utf32_is_word_boundary);
916   insist(utf32_combining_class(0x40000) == 0);
917   insist(utf32_combining_class(0xE0000) == 0);
918 }
919
920 static void test_signame(void) {
921   fprintf(stderr, "test_signame\n");
922   insist(find_signal("SIGTERM") == SIGTERM);
923   insist(find_signal("SIGHUP") == SIGHUP);
924   insist(find_signal("SIGINT") == SIGINT);
925   insist(find_signal("SIGQUIT") == SIGQUIT);
926   insist(find_signal("SIGKILL") == SIGKILL);
927   insist(find_signal("SIGYOURMUM") == -1);
928 }
929
930 static void test_cache(void) {
931   const struct cache_type t1 = { 1 }, t2 = { 10 };
932   const char v11[] = "spong", v12[] = "wibble", v2[] = "blat";
933   fprintf(stderr, "test_cache\n");
934   cache_put(&t1, "1_1", v11);
935   cache_put(&t1, "1_2", v12);
936   cache_put(&t2, "2", v2);
937   insist(cache_count() == 3);
938   insist(cache_get(&t2, "2") == v2);
939   insist(cache_get(&t1, "1_1") == v11);
940   insist(cache_get(&t1, "1_2") == v12);
941   insist(cache_get(&t1, "2") == 0);
942   insist(cache_get(&t2, "1_1") == 0);
943   insist(cache_get(&t2, "1_2") == 0);
944   insist(cache_get(&t1, "2") == 0);
945   insist(cache_get(&t2, "1_1") == 0);
946   insist(cache_get(&t2, "1_2") == 0);
947   sleep(2);
948   cache_expire();
949   insist(cache_count() == 1);
950   insist(cache_get(&t1, "1_1") == 0);
951   insist(cache_get(&t1, "1_2") == 0);
952   insist(cache_get(&t2, "2") == v2);
953   cache_clean(0);
954   insist(cache_count() == 0);
955   insist(cache_get(&t2, "2") == 0); 
956 }
957
958 static void test_filepart(void) {
959   fprintf(stderr, "test_filepart\n");
960   check_string(d_dirname("/"), "/");
961   check_string(d_dirname("////"), "/");
962   check_string(d_dirname("/spong"), "/");
963   check_string(d_dirname("////spong"), "/");
964   check_string(d_dirname("/foo/bar"), "/foo");
965   check_string(d_dirname("////foo/////bar"), "////foo");
966   check_string(d_dirname("./bar"), ".");
967   check_string(d_dirname(".//bar"), ".");
968   check_string(d_dirname("."), ".");
969   check_string(d_dirname(".."), ".");
970   check_string(d_dirname("../blat"), "..");
971   check_string(d_dirname("..//blat"), "..");
972   check_string(d_dirname("wibble"), ".");
973   check_string(extension("foo.c"), ".c");
974   check_string(extension(".c"), ".c");
975   check_string(extension("."), ".");
976   check_string(extension("foo"), "");
977   check_string(extension("./foo"), "");
978   check_string(extension("./foo.c"), ".c");
979   check_string(strip_extension("foo.c"), "foo");
980   check_string(strip_extension("foo.mp3"), "foo");
981   check_string(strip_extension("foo.---"), "foo.---");
982   check_string(strip_extension("foo.---xyz"), "foo.---xyz");
983   check_string(strip_extension("foo.bar/wibble.spong"), "foo.bar/wibble");
984 }
985
986 static void test_selection(void) {
987   hash *h;
988   fprintf(stderr, "test_selection\n");
989   insist((h = selection_new()) != 0);
990   selection_set(h, "one", 1);
991   selection_set(h, "two", 1);
992   selection_set(h, "three", 0);
993   selection_set(h, "four", 1);
994   insist(selection_selected(h, "one") == 1);
995   insist(selection_selected(h, "two") == 1);
996   insist(selection_selected(h, "three") == 0);
997   insist(selection_selected(h, "four") == 1);
998   insist(selection_selected(h, "five") == 0);
999   insist(hash_count(h) == 3);
1000   selection_flip(h, "one"); 
1001   selection_flip(h, "three"); 
1002   insist(selection_selected(h, "one") == 0);
1003   insist(selection_selected(h, "three") == 1);
1004   insist(hash_count(h) == 3);
1005   selection_live(h, "one");
1006   selection_live(h, "two");
1007   selection_live(h, "three");
1008   selection_cleanup(h);
1009   insist(selection_selected(h, "one") == 0);
1010   insist(selection_selected(h, "two") == 1);
1011   insist(selection_selected(h, "three") == 1);
1012   insist(selection_selected(h, "four") == 0);
1013   insist(selection_selected(h, "five") == 0);
1014   insist(hash_count(h) == 2);
1015   selection_empty(h);
1016   insist(selection_selected(h, "one") == 0);
1017   insist(selection_selected(h, "two") == 0);
1018   insist(selection_selected(h, "three") == 0);
1019   insist(selection_selected(h, "four") == 0);
1020   insist(selection_selected(h, "five") == 0);
1021   insist(hash_count(h) == 0);
1022 }
1023
1024 static void test_wstat(void) {
1025   pid_t pid;
1026   int w;
1027   
1028   fprintf(stderr, "test_wstat\n");
1029   if(!(pid = xfork())) {
1030     _exit(1);
1031   }
1032   while(waitpid(pid, &w, 0) < 0 && errno == EINTR)
1033     ;
1034   check_string(wstat(w), "exited with status 1");
1035   if(!(pid = xfork())) {
1036     kill(getpid(), SIGTERM);
1037     _exit(-1);
1038   }
1039   while(waitpid(pid, &w, 0) < 0 && errno == EINTR)
1040     ;
1041   check_string_prefix(wstat(w), "terminated by signal 15");
1042 }
1043
1044 static void test_kvp(void) {
1045   struct kvp *k;
1046   size_t n;
1047   
1048   fprintf(stderr, "test_kvp\n");
1049   /* decoding */
1050 #define KVP_URLDECODE(S) kvp_urldecode((S), strlen(S))
1051   insist(KVP_URLDECODE("=%zz") == 0);
1052   insist(KVP_URLDECODE("=%0") == 0);
1053   insist(KVP_URLDECODE("=%0z") == 0);
1054   insist(KVP_URLDECODE("=%%") == 0);
1055   insist(KVP_URLDECODE("==%") == 0);
1056   insist(KVP_URLDECODE("wibble") == 0);
1057   insist(KVP_URLDECODE("") == 0);
1058   insist(KVP_URLDECODE("wibble&") == 0);
1059   insist((k = KVP_URLDECODE("one=bl%61t+foo")) != 0);
1060   check_string(kvp_get(k, "one"), "blat foo");
1061   insist(kvp_get(k, "ONE") == 0);
1062   insist(k->next == 0);
1063   insist((k = KVP_URLDECODE("wibble=splat&bar=spong")) != 0);
1064   check_string(kvp_get(k, "wibble"), "splat");
1065   check_string(kvp_get(k, "bar"), "spong");
1066   insist(kvp_get(k, "ONE") == 0);
1067   insist(k->next->next == 0);
1068   /* encoding */
1069   insist(kvp_set(&k, "bar", "spong") == 0);
1070   insist(kvp_set(&k, "bar", "foo") == 1);
1071   insist(kvp_set(&k, "zog", "%") == 1);
1072   insist(kvp_set(&k, "wibble", 0) == 1);
1073   insist(kvp_set(&k, "wibble", 0) == 0);
1074   check_string(kvp_urlencode(k, 0),
1075                "bar=foo&zog=%25");
1076   check_string(kvp_urlencode(k, &n),
1077                "bar=foo&zog=%25");
1078   insist(n == strlen("bar=foo&zog=%25"));
1079   check_string(urlencodestring("abc% +\n"),
1080                "abc%25%20%2b%0a");
1081 }
1082
1083 static void test_sink(void) {
1084   struct sink *s;
1085   struct dynstr d[1];
1086   FILE *fp;
1087   char *l;
1088   
1089   fprintf(stderr, "test_sink\n");
1090
1091   fp = tmpfile();
1092   assert(fp != 0);
1093   s = sink_stdio("tmpfile", fp);
1094   insist(sink_printf(s, "test: %d\n", 999) == 10);
1095   insist(sink_printf(s, "wibble: %s\n", "foobar") == 15);
1096   rewind(fp);
1097   insist(inputline("tmpfile", fp, &l, '\n') == 0);
1098   check_string(l, "test: 999");
1099   insist(inputline("tmpfile", fp, &l, '\n') == 0);
1100   check_string(l, "wibble: foobar");
1101   insist(inputline("tmpfile", fp, &l, '\n') == -1);
1102   
1103   dynstr_init(d);
1104   s = sink_dynstr(d);
1105   insist(sink_printf(s, "test: %d\n", 999) == 10);
1106   insist(sink_printf(s, "wibble: %s\n", "foobar") == 15);
1107   dynstr_terminate(d);
1108   check_string(d->vec, "test: 999\nwibble: foobar\n");
1109 }
1110
1111 static const char *do_printf(const char *fmt, ...) {
1112   va_list ap;
1113   char *s;
1114   int rc;
1115
1116   va_start(ap, fmt);
1117   rc = byte_vasprintf(&s, fmt, ap);
1118   va_end(ap);
1119   if(rc < 0)
1120     return 0;
1121   return s;
1122 }
1123
1124 static void test_printf(void) {
1125   char c;
1126   short s;
1127   int i;
1128   long l;
1129   long long ll;
1130   intmax_t m;
1131   ssize_t ssz;
1132   ptrdiff_t p;
1133   char *cp;
1134   char buffer[16];
1135   
1136   fprintf(stderr, "test_printf\n");
1137   check_string(do_printf("%d", 999), "999");
1138   check_string(do_printf("%d", -999), "-999");
1139   check_string(do_printf("%i", 999), "999");
1140   check_string(do_printf("%i", -999), "-999");
1141   check_string(do_printf("%u", 999), "999");
1142   check_string(do_printf("%2u", 999), "999");
1143   check_string(do_printf("%10u", 999), "       999");
1144   check_string(do_printf("%-10u", 999), "999       ");
1145   check_string(do_printf("%010u", 999), "0000000999");
1146   check_string(do_printf("%-10d", -999), "-999      ");
1147   check_string(do_printf("%-010d", -999), "-999      "); /* "-" beats "0" */
1148   check_string(do_printf("%66u", 999), "                                                               999");
1149   check_string(do_printf("%o", 999), "1747");
1150   check_string(do_printf("%#o", 999), "01747");
1151   check_string(do_printf("%#o", 0), "0");
1152   check_string(do_printf("%x", 999), "3e7");
1153   check_string(do_printf("%#x", 999), "0x3e7");
1154   check_string(do_printf("%#X", 999), "0X3E7");
1155   check_string(do_printf("%#x", 0), "0");
1156   check_string(do_printf("%hd", (short)999), "999");
1157   check_string(do_printf("%hhd", (short)99), "99");
1158   check_string(do_printf("%ld", 100000L), "100000");
1159   check_string(do_printf("%lld", 10000000000LL), "10000000000");
1160   check_string(do_printf("%qd", 10000000000LL), "10000000000");
1161   check_string(do_printf("%jd", (intmax_t)10000000000LL), "10000000000");
1162   check_string(do_printf("%zd", (ssize_t)2000000000), "2000000000");
1163   check_string(do_printf("%td", (ptrdiff_t)2000000000), "2000000000");
1164   check_string(do_printf("%hu", (short)999), "999");
1165   check_string(do_printf("%hhu", (short)99), "99");
1166   check_string(do_printf("%lu", 100000L), "100000");
1167   check_string(do_printf("%llu", 10000000000LL), "10000000000");
1168   check_string(do_printf("%ju", (uintmax_t)10000000000LL), "10000000000");
1169   check_string(do_printf("%zu", (size_t)2000000000), "2000000000");
1170   check_string(do_printf("%tu", (ptrdiff_t)2000000000), "2000000000");
1171   check_string(do_printf("%p", (void *)0x100), "0x100");
1172   check_string(do_printf("%s", "wibble"), "wibble");
1173   check_string(do_printf("%s-%s", "wibble", "wobble"), "wibble-wobble");
1174   check_string(do_printf("%10s", "wibble"), "    wibble");
1175   check_string(do_printf("%010s", "wibble"), "    wibble"); /* 0 ignored for %s */
1176   check_string(do_printf("%-10s", "wibble"), "wibble    ");
1177   check_string(do_printf("%2s", "wibble"), "wibble");
1178   check_string(do_printf("%.2s", "wibble"), "wi");
1179   check_string(do_printf("%.2s", "w"), "w");
1180   check_string(do_printf("%4.2s", "wibble"), "  wi");
1181   check_string(do_printf("%c", 'a'), "a");
1182   check_string(do_printf("%4c", 'a'), "   a");
1183   check_string(do_printf("%-4c", 'a'), "a   ");
1184   check_string(do_printf("%*c", 0, 'a'), "a");
1185   check_string(do_printf("x%hhny", &c), "xy");
1186   insist(c == 1);
1187   check_string(do_printf("xx%hnyy", &s), "xxyy");
1188   insist(s == 2);
1189   check_string(do_printf("xxx%nyyy", &i), "xxxyyy");
1190   insist(i == 3);
1191   check_string(do_printf("xxxx%lnyyyy", &l), "xxxxyyyy");
1192   insist(l == 4);
1193   check_string(do_printf("xxxxx%llnyyyyy", &ll), "xxxxxyyyyy");
1194   insist(ll == 5);
1195   check_string(do_printf("xxxxxx%jnyyyyyy", &m), "xxxxxxyyyyyy");
1196   insist(m == 6);
1197   check_string(do_printf("xxxxxxx%znyyyyyyy", &ssz), "xxxxxxxyyyyyyy");
1198   insist(ssz == 7);
1199   check_string(do_printf("xxxxxxxx%tnyyyyyyyy", &p), "xxxxxxxxyyyyyyyy");
1200   insist(p == 8);
1201   check_string(do_printf("%*d", 5, 99), "   99");
1202   check_string(do_printf("%*d", -5, 99), "99   ");
1203   check_string(do_printf("%.*d", 5, 99), "00099");
1204   check_string(do_printf("%.*d", -5, 99), "99");
1205   check_string(do_printf("%.0d", 0), "");
1206   check_string(do_printf("%.d", 0), "");
1207   check_string(do_printf("%.d", 0), "");
1208   check_string(do_printf("%%"), "%");
1209   check_string(do_printf("wibble"), "wibble");
1210   insist(do_printf("%") == 0);
1211   insist(do_printf("%=") == 0);
1212   i = byte_asprintf(&cp, "xyzzy %d", 999);
1213   insist(i == 9);
1214   check_string(cp, "xyzzy 999");
1215   i = byte_snprintf(buffer, sizeof buffer, "xyzzy %d", 999);
1216   insist(i == 9);
1217   check_string(buffer, "xyzzy 999");
1218   i = byte_snprintf(buffer, sizeof buffer, "%*d", 32, 99);
1219   insist(i == 32);
1220   check_string(buffer, "               ");
1221   {
1222     /* bizarre workaround for compiler checking of format strings */
1223     char f[] = "xyzzy %";
1224     i = byte_asprintf(&cp, f);
1225     insist(i == -1);
1226   }
1227 }
1228
1229 static void test_basen(void) {
1230   unsigned long v[64];
1231   char buffer[1024];
1232
1233   fprintf(stderr, "test_basen\n");
1234   v[0] = 999;
1235   insist(basen(v, 1, buffer, sizeof buffer, 10) == 0);
1236   check_string(buffer, "999");
1237
1238   v[0] = 1+2*7+3*7*7+4*7*7*7;
1239   insist(basen(v, 1, buffer, sizeof buffer, 7) == 0);
1240   check_string(buffer, "4321");
1241
1242   v[0] = 0x00010203;
1243   v[1] = 0x04050607;
1244   v[2] = 0x08090A0B;
1245   v[3] = 0x0C0D0E0F;
1246   insist(basen(v, 4, buffer, sizeof buffer, 256) == 0);
1247   check_string(buffer, "123456789abcdef");
1248
1249   v[0] = 0x00010203;
1250   v[1] = 0x04050607;
1251   v[2] = 0x08090A0B;
1252   v[3] = 0x0C0D0E0F;
1253   insist(basen(v, 4, buffer, sizeof buffer, 16) == 0);
1254   check_string(buffer, "102030405060708090a0b0c0d0e0f");
1255
1256   v[0] = 0x00010203;
1257   v[1] = 0x04050607;
1258   v[2] = 0x08090A0B;
1259   v[3] = 0x0C0D0E0F;
1260   insist(basen(v, 4, buffer, 10, 16) == -1);
1261 }
1262
1263 static void test_split(void) {
1264   char **v;
1265   int nv;
1266
1267   fprintf(stderr, "test_split\n");
1268   insist(split("\"misquoted", &nv, SPLIT_COMMENTS|SPLIT_QUOTES, 0, 0) == 0);
1269   insist(split("\'misquoted", &nv, SPLIT_COMMENTS|SPLIT_QUOTES, 0, 0) == 0);
1270   insist(split("\'misquoted\\", &nv, SPLIT_COMMENTS|SPLIT_QUOTES, 0, 0) == 0);
1271   insist(split("\'misquoted\\\"", &nv, SPLIT_COMMENTS|SPLIT_QUOTES, 0, 0) == 0);
1272   insist(split("\'mis\\escaped\'", &nv, SPLIT_COMMENTS|SPLIT_QUOTES, 0, 0) == 0);
1273
1274   insist((v = split("", &nv, SPLIT_COMMENTS|SPLIT_QUOTES, 0, 0)));
1275   check_integer(nv, 0);
1276   insist(*v == 0);
1277
1278   insist((v = split("wibble", &nv, SPLIT_COMMENTS|SPLIT_QUOTES, 0, 0)));
1279   check_integer(nv, 1);
1280   check_string(v[0], "wibble");
1281   insist(v[1] == 0);
1282
1283   insist((v = split("   wibble \t\r\n wobble   ", &nv,
1284                     SPLIT_COMMENTS|SPLIT_QUOTES, 0, 0)));
1285   check_integer(nv, 2);
1286   check_string(v[0], "wibble");
1287   check_string(v[1], "wobble");
1288   insist(v[2] == 0);
1289
1290   insist((v = split("wibble wobble #splat", &nv,
1291                     SPLIT_COMMENTS|SPLIT_QUOTES, 0, 0)));
1292   check_integer(nv, 2);
1293   check_string(v[0], "wibble");
1294   check_string(v[1], "wobble");
1295   insist(v[2] == 0);
1296
1297   insist((v = split("\"wibble wobble\" #splat", &nv,
1298                     SPLIT_COMMENTS|SPLIT_QUOTES, 0, 0)));
1299   check_integer(nv, 1);
1300   check_string(v[0], "wibble wobble");
1301   insist(v[1] == 0);
1302
1303   insist((v = split("\"wibble \\\"\\nwobble\"", &nv,
1304                     SPLIT_COMMENTS|SPLIT_QUOTES, 0, 0)));
1305   check_integer(nv, 1);
1306   check_string(v[0], "wibble \"\nwobble");
1307   insist(v[1] == 0);
1308
1309   insist((v = split("\"wibble wobble\" #splat", &nv,
1310                     SPLIT_QUOTES, 0, 0)));
1311   check_integer(nv, 2);
1312   check_string(v[0], "wibble wobble");
1313   check_string(v[1], "#splat");
1314   insist(v[2] == 0);
1315
1316   insist((v = split("\"wibble wobble\" #splat", &nv,
1317                     SPLIT_COMMENTS, 0, 0)));
1318   check_integer(nv, 2);
1319   check_string(v[0], "\"wibble");
1320   check_string(v[1], "wobble\"");
1321   insist(v[2] == 0);
1322
1323   check_string(quoteutf8("wibble"), "wibble");
1324   check_string(quoteutf8("  wibble  "), "\"  wibble  \"");
1325   check_string(quoteutf8("wibble wobble"), "\"wibble wobble\"");
1326   check_string(quoteutf8("wibble\"wobble"), "\"wibble\\\"wobble\"");
1327   check_string(quoteutf8("wibble\nwobble"), "\"wibble\\nwobble\"");
1328   check_string(quoteutf8("wibble\\wobble"), "\"wibble\\\\wobble\"");
1329   check_string(quoteutf8("wibble'wobble"), "\"wibble'wobble\"");
1330 }
1331
1332 static void test_hash(void) {
1333   hash *h;
1334   int i, *ip;
1335   char **keys;
1336
1337   fprintf(stderr, "test_hash\n");
1338   h = hash_new(sizeof(int));
1339   for(i = 0; i < 10000; ++i)
1340     insist(hash_add(h, do_printf("%d", i), &i, HASH_INSERT) == 0);
1341   check_integer(hash_count(h), 10000);
1342   for(i = 0; i < 10000; ++i) {
1343     insist((ip = hash_find(h, do_printf("%d", i))) != 0);
1344     check_integer(*ip, i);
1345     insist(hash_add(h, do_printf("%d", i), &i, HASH_REPLACE) == 0);
1346   }
1347   check_integer(hash_count(h), 10000);
1348   keys = hash_keys(h);
1349   for(i = 0; i < 10000; ++i)
1350     insist(keys[i] != 0);
1351   insist(keys[10000] == 0);
1352   for(i = 0; i < 10000; ++i)
1353     insist(hash_remove(h, do_printf("%d", i)) == 0);
1354   check_integer(hash_count(h), 0);
1355 }
1356
1357 static void test_addr(void) {
1358   struct stringlist a;
1359   const char *s[2];
1360   struct addrinfo *ai;
1361   char *name;
1362   const struct sockaddr_in *sin;
1363
1364   static const struct addrinfo pref = {
1365     AI_PASSIVE,
1366     PF_INET,
1367     SOCK_STREAM,
1368     0,
1369     0,
1370     0,
1371     0,
1372     0
1373   };
1374
1375   printf("test_addr\n");
1376
1377   a.n = 1;
1378   a.s = (char **)s;
1379   s[0] = "smtp";
1380   ai = get_address(&a, &pref, &name);
1381   insist(ai != 0);
1382   check_integer(ai->ai_family, PF_INET);
1383   check_integer(ai->ai_socktype, SOCK_STREAM);
1384   check_integer(ai->ai_protocol, IPPROTO_TCP);
1385   check_integer(ai->ai_addrlen, sizeof(struct sockaddr_in));
1386   sin = (const struct sockaddr_in *)ai->ai_addr;
1387   check_integer(sin->sin_family, AF_INET);
1388   check_integer(sin->sin_addr.s_addr, 0);
1389   check_integer(ntohs(sin->sin_port), 25);
1390   check_string(name, "host * service smtp");
1391
1392   a.n = 2;
1393   s[0] = "localhost";
1394   s[1] = "nntp";
1395   ai = get_address(&a, &pref, &name);
1396   insist(ai != 0);
1397   check_integer(ai->ai_family, PF_INET);
1398   check_integer(ai->ai_socktype, SOCK_STREAM);
1399   check_integer(ai->ai_protocol, IPPROTO_TCP);
1400   check_integer(ai->ai_addrlen, sizeof(struct sockaddr_in));
1401   sin = (const struct sockaddr_in *)ai->ai_addr;
1402   check_integer(sin->sin_family, AF_INET);
1403   check_integer(ntohl(sin->sin_addr.s_addr), 0x7F000001);
1404   check_integer(ntohs(sin->sin_port), 119);
1405   check_string(name, "host localhost service nntp");
1406 }
1407
1408 static void test_url(void) {
1409   struct url p;
1410   
1411   printf("test_url\n");
1412
1413   insist(parse_url("http://www.example.com/example/path", &p) == 0);
1414   check_string(p.scheme, "http");
1415   check_string(p.host, "www.example.com");
1416   insist(p.port == -1);
1417   check_string(p.path, "/example/path");
1418   insist(p.query == 0);
1419
1420   insist(parse_url("https://www.example.com:82/example%2fpath?+query+", &p) == 0);
1421   check_string(p.scheme, "https");
1422   check_string(p.host, "www.example.com");
1423   insist(p.port == 82);
1424   check_string(p.path, "/example/path");
1425   check_string(p.query, "+query+");
1426 }
1427
1428 int main(void) {
1429   mem_init();
1430   fail_first = !!getenv("FAIL_FIRST");
1431   insist('\n' == 0x0A);
1432   insist('\r' == 0x0D);
1433   insist(' ' == 0x20);
1434   insist('0' == 0x30);
1435   insist('9' == 0x39);
1436   insist('A' == 0x41);
1437   insist('Z' == 0x5A);
1438   insist('a' == 0x61);
1439   insist('z' == 0x7A);
1440   /* addr.c */
1441   test_addr();
1442   /* asprintf.c */
1443   /* authhash.c */
1444   /* basen.c */
1445   test_basen();
1446   /* charset.c */
1447   /* client.c */
1448   /* configuration.c */
1449   /* event.c */
1450   /* filepart.c */
1451   test_filepart();
1452   /* fprintf.c */
1453   /* heap.c */
1454   test_heap();
1455   /* hex.c */
1456   test_hex();
1457   /* inputline.c */
1458   /* kvp.c */
1459   test_kvp();
1460   /* log.c */
1461   /* mem.c */
1462   /* mime.c */
1463   test_mime();
1464   test_cookies();
1465   /* mixer.c */
1466   /* plugin.c */
1467   /* printf.c */
1468   test_printf();
1469   /* queue.c */
1470   /* sink.c */
1471   test_sink();
1472   /* snprintf.c */
1473   /* split.c */
1474   test_split();
1475   /* syscalls.c */
1476   /* table.c */
1477   /* unicode.c */
1478   test_unicode();
1479   /* utf8.c */
1480   test_utf8();
1481   /* vector.c */
1482   /* words.c */
1483   test_casefold();
1484   test_words();
1485   /* wstat.c */
1486   test_wstat();
1487   /* signame.c */
1488   test_signame();
1489   /* cache.c */
1490   test_cache();
1491   /* selection.c */
1492   test_selection();
1493   test_hash();
1494   test_url();
1495   fprintf(stderr,  "%d errors out of %d tests\n", errors, tests);
1496   return !!errors;
1497 }
1498   
1499 /*
1500 Local Variables:
1501 c-basic-offset:2
1502 comment-column:40
1503 fill-column:79
1504 indent-tabs-mode:nil
1505 End:
1506 */