1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "http.h"
static int fail_resize;
void *
fields_realloc(void *p, size_t n)
{
return fail_resize ? NULL : realloc(p, n);
}
static void
pair(struct kpair *p, const char *key, const char *value)
{
p->key = strdup(key);
p->val = strdup(value);
p->valsz = strlen(value);
p->file = strdup("fixture.png");
p->ctype = strdup("application/octet-stream");
p->xcode = strdup("binary");
assert(p->key && p->val && p->file && p->ctype && p->xcode);
}
static void
exercise(int fail)
{
static const char *const names[] = { "file", "json", "scope" };
struct kreq r;
struct kpair *file;
size_t i;
char key[64];
memset(&r, 0, sizeof(r));
r.fieldsz = 10006;
r.fields = calloc(r.fieldsz, sizeof(*r.fields));
r.cookiesz = 1000;
r.cookies = calloc(r.cookiesz, sizeof(*r.cookies));
assert(r.fields && r.cookies);
for (i = 0; i < 10000; i++) {
snprintf(key, sizeof(key), "unused-%zu", i);
pair(&r.fields[i], key, "ignored");
}
pair(&r.fields[10000], "json", "first");
pair(&r.fields[10001], "json", "second");
pair(&r.fields[10002], "file", "PDF");
r.fields[10002].val[1] = '\0';
pair(&r.fields[10003], "scope", "");
pair(&r.fields[10004], "scope", "all");
pair(&r.fields[10005], "file", "wrong duplicate");
for (i = 0; i < r.cookiesz; i++)
pair(&r.cookies[i], "identity-is-not-a-cookie", "ignored");
/* Never move a mapped request's storage out from under kcgi's maps. */
r.keysz = 1;
assert(http_keep_fields(&r, names, 3) == -1);
assert(r.fieldsz == 10006 && r.cookiesz == 1000);
r.keysz = 0;
fail_resize = fail;
assert(http_keep_fields(&r, names, 3) == (fail ? -1 : 0));
assert(r.fieldsz == 3 && r.cookiesz == 0 && r.cookies == NULL);
assert(strcmp(http_field_str(&r, "json"), "first") == 0);
assert(strcmp(http_field_str(&r, "scope"), "") == 0);
file = http_field(&r, "file");
assert(file && file->valsz == 3 && memcmp(file->val, "P\0F", 3) == 0);
assert(strcmp(file->file, "fixture.png") == 0);
assert(http_field_str(&r, "file") == NULL);
assert(http_field(&r, "unused-0") == NULL);
assert(file->next == NULL);
fail_resize = 0;
if (!fail) {
assert(http_keep_fields(&r, names, 3) == 0);
assert(r.fieldsz == 3);
}
/* Exercise the real library destructor after moving/removing its pairs. */
khttp_child_free(&r);
memset(&r, 0, sizeof(r));
r.fieldsz = 1;
r.fields = calloc(1, sizeof(*r.fields));
assert(r.fields);
pair(r.fields, "unknown", "ignored");
assert(http_keep_fields(&r, names, 3) == 0);
assert(r.fields == NULL && r.fieldsz == 0);
khttp_child_free(&r);
}
int
main(void)
{
exercise(0);
exercise(1);
puts("request fields: bounded retention, first values, binary files, cookies and failed shrink passed");
return 0;
}