rfc822: new module.
[ccan] / ccan / rfc822 / test / run-bad-header-name.c
1 #include <ccan/foreach/foreach.h>
2 #include <ccan/failtest/failtest_override.h>
3 #include <ccan/failtest/failtest.h>
4 #include <ccan/tap/tap.h>
5 #include <stdlib.h>
6 #include <string.h>
7
8 #define CCAN_RFC822_DEBUG
9
10 #include <ccan/rfc822/rfc822.h>
11
12 #include <ccan/rfc822/rfc822.c>
13
14 #include "testdata.h"
15 #include "helper.h"
16
17 #define NAME_TEMPLATE           "X-Bad-Header"
18 #define NAME_TEMPLATE_LEN       (strlen(NAME_TEMPLATE))
19
20 const char bad_name_template[] =
21         NAME_TEMPLATE ": This is a good header that will become bad\n";
22
23 static bool bad_name(const char *buf, char c)
24 {
25         struct rfc822_msg *msg;
26         struct rfc822_header *hdr;
27         enum rfc822_header_errors errs;
28         struct bytestring hname;
29
30         msg = rfc822_start(NULL, buf, strlen(buf));
31
32         allocation_failure_check();
33
34         hdr = rfc822_first_header(msg);
35         ok1(hdr);
36
37         allocation_failure_check();
38
39         errs = rfc822_header_errors(msg, hdr);
40
41         allocation_failure_check();
42
43         ok1(!(errs & ~RFC822_HDR_BAD_NAME));
44
45         /* Check raw_name still works properly */
46         hname = rfc822_header_raw_name(msg, hdr);
47
48         allocation_failure_check();
49
50         ok1(hname.ptr && hname.len == NAME_TEMPLATE_LEN);
51         ok1((hname.ptr[0] == c) &&
52             (memcmp(hname.ptr + 1, NAME_TEMPLATE + 1, NAME_TEMPLATE_LEN - 1) == 0));
53
54         rfc822_free(msg);
55
56         allocation_failure_check();
57
58         return !!(errs & RFC822_HDR_BAD_NAME);
59 }
60
61 int main(int argc, char *argv[])
62 {
63         char c;
64
65         failtest_setup(argc, argv);
66
67         plan_tests(5 * (1 + 3 + 4));
68
69         ok1(!bad_name(bad_name_template, bad_name_template[0]));
70
71         /* Good characters */
72         foreach_int(c, 'a', 'Z', '3') {
73                 char *tmp = strdup(bad_name_template);
74
75                 tmp[0] = c;
76
77                 ok1(!bad_name(tmp, c));
78
79                 free(tmp);
80         }
81
82         /* Bad characters */
83         foreach_int(c, ' ', '\t', '\b', '\x80') {
84                 char *tmp = strdup(bad_name_template);
85
86                 tmp[0] = c;
87
88                 ok1(bad_name(tmp, c));
89
90                 free(tmp);
91         }
92
93         /* This exits depending on whether all tests passed */
94         failtest_exit(exit_status());
95 }