-
Notifications
You must be signed in to change notification settings - Fork 43
/
Copy pathchild.c
2274 lines (1926 loc) · 53.2 KB
/
child.c
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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (c) Kristaps Dzonsons <[email protected]>
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include "config.h"
#include <arpa/inet.h>
#include <assert.h>
#include <ctype.h>
#include <errno.h>
#include <inttypes.h>
#include <limits.h>
#if HAVE_MD5
# include <sys/types.h>
# include <md5.h>
#endif
#include <poll.h>
#include <stdarg.h>
#include <stdio.h>
#include <stddef.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include "kcgi.h"
#include "extern.h"
#define MD5Updatec(_ctx, _b, _sz) \
MD5Update((_ctx), (const uint8_t *)(_b), (_sz))
enum mimetype {
MIMETYPE_UNKNOWN,
MIMETYPE_TRANSFER_ENCODING,
MIMETYPE_DISPOSITION,
MIMETYPE_TYPE
};
/*
* For handling HTTP multipart forms.
* This consists of data for a single multipart form entry.
*/
struct mime {
char *disp; /* content disposition */
char *name; /* name of form entry */
size_t namesz; /* size of "name" string */
char *file; /* whether a file was specified */
char *ctype; /* content type */
size_t ctypepos; /* position of ctype in mimes */
char *xcode; /* encoding type */
char *bound; /* form entry boundary */
};
/*
* Both CGI and FastCGI use an environment for their HTTP parameters.
* CGI gets it from the actual environment; FastCGI from a transmitted
* environment.
* We use an abstract representation of those key-value pairs here so
* that we can use the same functions for both.
*/
struct env {
char *key; /* key (e.g., HTTP_HOST) */
size_t keysz;
char *val; /* value (e.g., `foo.com') */
size_t valsz;
};
/*
* Types of FastCGI requests.
* Defined in the FastCGI v1.0 spec, section 8.
*/
enum fcgi_type {
FCGI_BEGIN_REQUEST = 1,
FCGI_ABORT_REQUEST = 2,
FCGI_END_REQUEST = 3,
FCGI_PARAMS = 4,
FCGI_STDIN = 5,
FCGI_STDOUT = 6,
FCGI_STDERR = 7,
FCGI_DATA = 8,
FCGI_GET_VALUES = 9,
FCGI_GET_VALUES_RESULT = 10,
FCGI_UNKNOWN_TYPE = 11,
FCGI__MAX
};
/*
* The FastCGI `FCGI_Header' header layout.
* Defined in the FastCGI v1.0 spec, section 8.
*/
struct fcgi_hdr {
uint8_t version;
uint8_t type;
uint16_t requestId;
uint16_t contentLength;
uint8_t paddingLength;
uint8_t reserved;
};
/*
* The FastCGI `FCGI_BeginRequestBody' header layout.
* Defined in the FastCGI v1.0 spec, section 8.
*/
struct fcgi_bgn {
uint16_t role;
uint8_t flags;
uint8_t res[5];
};
/*
* A buffer of reads from kfcgi_control().
*/
struct fcgi_buf {
size_t sz; /* bytes in buffer */
size_t pos; /* current position (from last read) */
int fd; /* file descriptor */
char *buf; /* buffer itself */
};
/*
* Parameters required to validate fields.
*/
struct parms {
int fd;
const char *const *mimes;
size_t mimesz;
const struct kvalid *keys;
size_t keysz;
enum input type;
};
const char *const kmethods[KMETHOD__MAX] = {
"ACL", /* KMETHOD_ACL */
"CONNECT", /* KMETHOD_CONNECT */
"COPY", /* KMETHOD_COPY */
"DELETE", /* KMETHOD_DELETE */
"GET", /* KMETHOD_GET */
"HEAD", /* KMETHOD_HEAD */
"LOCK", /* KMETHOD_LOCK */
"MKCALENDAR", /* KMETHOD_MKCALENDAR */
"MKCOL", /* KMETHOD_MKCOL */
"MOVE", /* KMETHOD_MOVE */
"OPTIONS", /* KMETHOD_OPTIONS */
"POST", /* KMETHOD_POST */
"PROPFIND", /* KMETHOD_PROPFIND */
"PROPPATCH", /* KMETHOD_PROPPATCH */
"PUT", /* KMETHOD_PUT */
"REPORT", /* KMETHOD_REPORT */
"TRACE", /* KMETHOD_TRACE */
"UNLOCK", /* KMETHOD_UNLOCK */
};
static const char *const krequs[KREQU__MAX] = {
"HTTP_ACCEPT", /* KREQU_ACCEPT */
"HTTP_ACCEPT_CHARSET", /* KREQU_ACCEPT_CHARSET */
"HTTP_ACCEPT_ENCODING", /* KREQU_ACCEPT_ENCODING */
"HTTP_ACCEPT_LANGUAGE", /* KREQU_ACCEPT_LANGUAGE */
"HTTP_ACCESS_CONTROL_REQUEST_HEADERS", /* KREQU_ACCESS_CONTROL_REQUEST_HEADERS */
"HTTP_ACCESS_CONTROL_REQUEST_METHOD", /* KREQU_ACCESS_CONTROL_REQUEST_METHOD */
"HTTP_AUTHORIZATION", /* KREQU_AUTHORIZATION */
"HTTP_DEPTH", /* KREQU_DEPTH */
"HTTP_FROM", /* KREQU_FROM */
"HTTP_HOST", /* KREQU_HOST */
"HTTP_IF", /* KREQU_IF */
"HTTP_IF_MODIFIED_SINCE", /* KREQU_IF_MODIFIED_SINCE */
"HTTP_IF_MATCH", /* KREQU_IF_MATCH */
"HTTP_IF_NONE_MATCH", /* KREQU_IF_NONE_MATCH */
"HTTP_IF_RANGE", /* KREQU_IF_RANGE */
"HTTP_IF_UNMODIFIED_SINCE", /* KREQU_IF_UNMODIFIED_SINCE */
"HTTP_MAX_FORWARDS", /* KREQU_MAX_FORWARDS */
"HTTP_ORIGIN", /* KREQU_ORIGIN */
"HTTP_PROXY_AUTHORIZATION", /* KREQU_PROXY_AUTHORIZATION */
"HTTP_RANGE", /* KREQU_RANGE */
"HTTP_REFERER", /* KREQU_REFERER */
"HTTP_USER_AGENT", /* KREQU_USER_AGENT */
};
static const char *const kauths[KAUTH_UNKNOWN] = {
NULL, /* KAUTH_NONE */
"basic", /* KAUTH_BASIC */
"digest", /* KAUTH_DIGEST */
"bearer", /* KAUTH_BEARER */
};
/*
* Parse the type/subtype field out of a content-type.
* The content-type is defined (among other places) in RFC 822, and is
* either the whole string or up until the ';', which marks the
* beginning of the parameters.
*/
static size_t
str2ctype(const struct parms *pp, const char *ctype)
{
size_t i, sz;
if (NULL == ctype)
return(pp->mimesz);
/* Stop at the content-type parameters. */
sz = strcspn(ctype, ";");
for (i = 0; i < pp->mimesz; i++)
if (sz == strlen(pp->mimes[i]) &&
0 == strncasecmp(pp->mimes[i], ctype, sz))
break;
return(i);
}
/*
* Given a parsed field "key" with value "val" of size "valsz" and MIME
* information "mime", first try to look it up in the array of
* recognised keys ("pp->keys") and optionally validate.
* Then output the type, parse status (key, type, etc.), and values read
* by the parent input() function.
*/
static void
output(const struct parms *pp, char *key,
char *val, size_t valsz, struct mime *mime)
{
size_t i;
ptrdiff_t diff;
char *save;
struct kpair pair;
memset(&pair, 0, sizeof(struct kpair));
pair.key = key;
pair.val = save = val;
pair.valsz = valsz;
pair.file = NULL == mime ? NULL : mime->file;
pair.ctype = NULL == mime ? NULL : mime->ctype;
pair.xcode = NULL == mime ? NULL : mime->xcode;
pair.ctypepos = NULL == mime ? pp->mimesz : mime->ctypepos;
pair.type = KPAIR__MAX;
/*
* Look up the key name in our key table.
* If we find it and it has a validator, then run the validator
* and record the output.
* If we fail, reset the type and clear the results.
* Either way, the keypos parameter is going to be the key
* identifier or keysz if none is found.
*/
for (i = 0; i < pp->keysz; i++) {
if (strcmp(pp->keys[i].name, pair.key))
continue;
if (NULL == pp->keys[i].valid)
break;
if ( ! pp->keys[i].valid(&pair)) {
pair.state = KPAIR_INVALID;
pair.type = KPAIR__MAX;
memset(&pair.parsed, 0, sizeof(union parsed));
} else
pair.state = KPAIR_VALID;
break;
}
pair.keypos = i;
fullwrite(pp->fd, &pp->type, sizeof(enum input));
fullwriteword(pp->fd, pair.key);
fullwrite(pp->fd, &pair.valsz, sizeof(size_t));
fullwrite(pp->fd, pair.val, pair.valsz);
fullwrite(pp->fd, &pair.state, sizeof(enum kpairstate));
fullwrite(pp->fd, &pair.type, sizeof(enum kpairtype));
fullwrite(pp->fd, &pair.keypos, sizeof(size_t));
if (KPAIR_VALID == pair.state)
switch (pair.type) {
case (KPAIR_DOUBLE):
fullwrite(pp->fd,
&pair.parsed.d, sizeof(double));
break;
case (KPAIR_INTEGER):
fullwrite(pp->fd,
&pair.parsed.i, sizeof(int64_t));
break;
case (KPAIR_STRING):
assert(pair.parsed.s >= pair.val);
assert(pair.parsed.s <= pair.val + pair.valsz);
diff = pair.val - pair.parsed.s;
fullwrite(pp->fd, &diff, sizeof(ptrdiff_t));
break;
default:
break;
}
fullwriteword(pp->fd, pair.file);
fullwriteword(pp->fd, pair.ctype);
fullwrite(pp->fd, &pair.ctypepos, sizeof(size_t));
fullwriteword(pp->fd, pair.xcode);
/*
* We can write a new "val" in the validator allocated on the
* heap: if we do, free it here.
*/
if (save != pair.val)
free(pair.val);
}
/*
* Read full stdin request into memory.
* This reads at most "len" bytes and NUL-terminates the results, the
* length of which may be less than "len" and is stored in *szp if not
* NULL.
* Returns the pointer to the data.
* NOTE: we can't use fullread() here because we may not get the total
* number of bytes requested.
* NOTE: "szp" can legit be set to zero.
*/
static char *
scanbuf(size_t len, size_t *szp)
{
ssize_t ssz;
size_t sz;
char *p;
int rc;
struct pollfd pfd;
pfd.fd = STDIN_FILENO;
pfd.events = POLLIN;
/* Allocate the entire buffer here. */
if ((p = kxmalloc(len + 1)) == NULL)
_exit(EXIT_FAILURE);
/*
* Keep reading til we get all the data or the sender stops
* giving us data---whichever comes first.
* Use kutil_warn[x] and _exit to avoid flushing buffers.
*/
for (sz = 0; sz < len; sz += (size_t)ssz) {
if ((rc = poll(&pfd, 1, INFTIM)) < 0) {
kutil_warn(NULL, NULL, "poll");
_exit(EXIT_FAILURE);
} else if (0 == rc) {
kutil_warnx(NULL, NULL, "poll: timeout!?");
ssz = 0;
continue;
}
if (!(pfd.revents & POLLIN))
break;
if ((ssz = read(STDIN_FILENO, p + sz, len - sz)) < 0) {
kutil_warn(NULL, NULL, "read");
_exit(EXIT_FAILURE);
} else if (ssz == 0)
break;
}
if (sz < len)
kutil_warnx(NULL, NULL, "content size mismatch: "
"have %zu while %zu specified", sz, len);
/* ALWAYS NUL-terminate. */
p[sz] = '\0';
if (szp != NULL)
*szp = sz;
return p;
}
/*
* Reset a particular mime component.
* We can get duplicates, so reallocate.
*/
static void
mime_reset(char **dst, const char *src)
{
free(*dst);
if ((*dst = kxstrdup(src)) == NULL)
_exit(EXIT_FAILURE);
}
/*
* Free up all MIME headers.
* We might call this more than once, so make sure that it can be
* invoked again by setting the memory to zero.
*/
static void
mime_free(struct mime *mime)
{
free(mime->disp);
free(mime->name);
free(mime->file);
free(mime->ctype);
free(mime->xcode);
free(mime->bound);
memset(mime, 0, sizeof(struct mime));
}
/*
* Parse out all MIME headers.
* This is defined by RFC 2045.
* This returns TRUE if we've parsed up to (and including) the last
* empty CRLF line, or FALSE if something has gone wrong (e.g., parse
* error, out of memory).
* If FALSE, parsing should stop immediately.
*/
static int
mime_parse(const struct parms *pp, struct mime *mime,
char *buf, size_t len, size_t *pos)
{
char *key, *val, *keyend, *end, *start, *line;
enum mimetype type;
int rc = 0;
mime_free(mime);
while (*pos < len) {
/* Each MIME line ends with a CRLF. */
start = &buf[*pos];
end = memmem(start, len - *pos, "\r\n", 2);
if (end == NULL) {
kutil_warnx(NULL, NULL, "RFC error: "
"MIME header line without CRLF");
return 0;
}
/*
* NUL-terminate to make a nice line.
* Then re-set our starting position.
*/
*end = '\0';
*pos += (end - start) + 2;
/* Empty CRLF line: we're done here! */
if (*start == '\0') {
rc = 1;
break;
}
/*
* Find end of MIME statement name.
* The RFCs disagree on white-space before the colon,
* but as it's allowed in the original RFC 822 and
* obsolete syntax should be supported, we do so here.
*/
key = start;
if ((val = strchr(key, ':')) == NULL) {
kutil_warnx(NULL, NULL, "RFC error: "
"MIME header without colon separator");
return 0;
} else if (key != val) {
keyend = val - 1;
while (keyend >= key && *keyend == ' ')
*keyend-- = '\0';
}
*val++ = '\0';
while (*val == ' ')
val++;
if (*key == '\0')
kutil_warnx(NULL, NULL, "RFC "
"warning: empty MIME header name");
/*
* Set "line" to be at the MIME value subpart, for
* example, "Content-type: text/plain; charset=us-ascii"
* would put us at the parts before "charset".
*/
line = NULL;
if ((line = strchr(val, ';')) != NULL)
*line++ = '\0';
/*
* Allow these specific MIME header statements.
* We'll follow up by parsing specific information from
* the header values, so remember what we parsed.
*/
if (strcasecmp(key, "content-transfer-encoding") == 0) {
mime_reset(&mime->xcode, val);
type = MIMETYPE_TRANSFER_ENCODING;
} else if (strcasecmp(key, "content-disposition") == 0) {
mime_reset(&mime->disp, val);
type = MIMETYPE_DISPOSITION;
} else if (strcasecmp(key, "content-type") == 0) {
mime_reset(&mime->ctype, val);
type = MIMETYPE_TYPE;
} else
type = MIMETYPE_UNKNOWN;
/*
* Process subpart only for content-type and
* content-disposition.
* The rest have no information we want: silently ignore them.
*/
if (type != MIMETYPE_TYPE &&
type != MIMETYPE_DISPOSITION)
continue;
while ((key = line) != NULL) {
while (*key == ' ')
key++;
if (*key == '\0')
break;
/*
* It's not clear whether we're allowed to have
* OWS before the separator, but allow for it
* anyway.
*/
if ((val = strchr(key, '=')) == NULL) {
kutil_warnx(NULL, NULL, "RFC error: "
"MIME header without sub-part "
"separator");
return 0;
} else if (key != val) {
keyend = val - 1;
while (keyend >= key && *keyend == ' ')
*keyend-- = '\0';
}
*val++ = '\0';
if (*key == '\0')
kutil_warnx(NULL, NULL, "RFC warning: "
"empty MIME sub-part name");
/* Quoted string. */
if (*val == '"') {
val++;
line = strchr(val, '"');
if (line == NULL) {
kutil_warnx(NULL, NULL, "RFC "
"error: quoted MIME "
"header sub-part not "
"terminated");
return 0;
}
*line++ = '\0';
/*
* It's unclear as to whether this is
* allowed (white-space before the
* semicolon separator), but let's
* accommodate for it anyway.
*/
while (*line == ' ')
line++;
if (*line == ';')
line++;
} else if ((line = strchr(val, ';')) != NULL)
*line++ = '\0';
/* White-listed sub-commands. */
if (type == MIMETYPE_DISPOSITION) {
if (strcasecmp(key, "filename") == 0)
mime_reset(&mime->file, val);
else if (strcasecmp(key, "name") == 0)
mime_reset(&mime->name, val);
} else if (type == MIMETYPE_TYPE) {
if (strcasecmp(key, "boundary") == 0)
mime_reset(&mime->bound, val);
}
}
}
mime->ctypepos = str2ctype(pp, mime->ctype);
if (!rc)
kutil_warnx(NULL, NULL, "RFC error: unexpected "
"end of file while parsing MIME headers");
return rc;
}
/*
* Parse keys and values separated by newlines.
* I'm not aware of any standard that defines this, but the W3
* guidelines for HTML give a rough idea.
* FIXME: deprecate this.
*/
static void
parse_pairs_text(const struct parms *pp, char *p)
{
char *key, *val;
kutil_warnx(NULL, NULL, "RFC warning: "
"text/plain encoding is deprecated");
while (p != NULL && *p != '\0') {
while (*p == ' ')
p++;
/*
* Key/value pair.
* No value is a warning (not processed).
*/
key = p;
val = NULL;
if (NULL != (p = strchr(p, '='))) {
*p++ = '\0';
val = p;
if ((p = strstr(val, "\r\n")) != NULL) {
*p = '\0';
p += 2;
}
} else {
if ((p = strstr(key, "\r\n")) != NULL) {
*p = '\0';
p += 2;
}
kutil_warnx(NULL, NULL, "RFC warning: "
"key with no value");
continue;
}
if (*key == '\0')
kutil_warnx(NULL, NULL, "RFC warning: "
"zero-length key");
else
output(pp, key, val, strlen(val), NULL);
}
}
/*
* Parse an HTTP message that has a given content-type.
* This happens with, e.g., PUT requests.
* We fake up a "name" for this (it's not really a key-value pair) of an
* empty string, then pass that to the validator and forwarder.
*/
static void
parse_body(const char *ct, const struct parms *pp, char *b, size_t bsz)
{
char name;
struct mime mime;
memset(&mime, 0, sizeof(struct mime));
if ((mime.ctype = kxstrdup(ct)) == NULL)
_exit(EXIT_FAILURE);
mime.ctypepos = str2ctype(pp, mime.ctype);
name = '\0';
output(pp, &name, b, bsz, &mime);
free(mime.ctype);
}
/*
* Parse out key-value pairs from an HTTP cookie.
* These are not URL encoded (at this phase): they're just simple
* key-values "crumbs" with opaque values.
* This is defined by RFC 6265, however, we don't [yet] do the
* quoted-string implementation, nor do we check for accepted
* characters so long as the delimiters aren't used.
*/
static void
parse_pairs(const struct parms *pp, char *p)
{
char *key, *val;
while (p != NULL && *p != '\0') {
while (*p == ' ')
p++;
/*
* Don't allow key-pair without a value.
* Keys shouldn't be zero-length.
*/
key = p;
val = NULL;
if ((p = strchr(p, '=')) != NULL) {
*p++ = '\0';
val = p;
if ((p = strchr(p, ';')) != NULL)
*p++ = '\0';
} else {
if ((p = strchr(key, ';')) != NULL)
p++;
kutil_warnx(NULL, NULL, "RFC error: "
"cookie key pair without value");
continue;
}
/* This is sort-of allowed. */
if (*key == '\0')
kutil_warnx(NULL, NULL, "RFC warning: "
"cookie zero-length key");
else
output(pp, key, val, strlen(val), NULL);
}
}
/*
* Parse out key-value pairs from an HTTP request variable.
* This is either a POST or GET string.
* This MUST be a non-binary (i.e., NUL-terminated) string!
*/
static void
parse_pairs_urlenc(const struct parms *pp, char *p)
{
char *key, *val;
assert(p != NULL);
while (*p != '\0') {
while (*p == ' ')
p++;
key = p;
/*
* Look ahead to either '=' or one of the key-value
* terminators (or the end of the string).
* If we have the equal sign, then we're a key-value
* pair; otherwise, we're a standalone key value.
*/
p += strcspn(p, "=;&");
if (*p == '=') {
*p++ = '\0';
val = p;
p += strcspn(p, ";&");
} else
val = p;
if (*p != '\0')
*p++ = '\0';
/*
* Both the key and the value can be URL encoded, so
* decode those into the character string now.
* If decoding fails, don't decode the given pair, but
* instead move on to the next one after logging the
* failure.
*/
if (*key == '\0')
kutil_warnx(NULL, NULL, "RFC warning: "
"zero-length URL-encoded key");
else if (khttp_urldecode_inplace(key) == KCGI_FORM)
kutil_warnx(NULL, NULL, "RFC warning: "
"malformed key URL-encoding");
else if (khttp_urldecode_inplace(val) == KCGI_FORM)
kutil_warnx(NULL, NULL, "RFC warning: "
"malformed value URL-encoding");
else
output(pp, key, val, strlen(val), NULL);
}
}
/*
* This is described by the "multipart-body" BNF part of RFC 2046,
* section 5.1.1.
* We return TRUE if the parse was ok, FALSE if errors occurred (all
* calling parsers should bail too).
*/
static int
parse_multiform(const struct parms *pp, char *name,
const char *bound, char *buf, size_t len, size_t *pos)
{
struct mime mime;
size_t endpos, bbsz, partsz;
char *ln, *bb;
int rc, first;
/* Define our buffer boundary. */
if ((rc = kxasprintf(&bb, "\r\n--%s", bound)) == -1)
_exit(EXIT_FAILURE);
assert(rc > 0);
bbsz = rc;
rc = 0;
memset(&mime, 0, sizeof(struct mime));
/* Read to the next instance of a buffer boundary. */
for (first = 1; *pos < len; first = 0, *pos = endpos) {
/*
* The (first ? 2 : 0) is because the first prologue
* boundary will not incur an initial CRLF, so our bb is
* past the CRLF and two bytes smaller.
*/
ln = memmem(&buf[*pos], len - *pos,
bb + (first ? 2 : 0),
bbsz - (first ? 2 : 0));
if (ln == NULL) {
kutil_warnx(NULL, NULL, "RFC error: "
"EOF when scanning for boundary");
goto out;
}
/*
* Set "endpos" to point to the beginning of the next
* multipart component, i.e, the end of the boundary
* "bb" string.
* Again, be respectful of whether we should scan after
* the lack of initial CRLF.
*/
endpos = *pos + (ln - &buf[*pos]) +
bbsz - (first ? 2 : 0);
/* Check buffer space. */
if (endpos > len - 2) {
kutil_warnx(NULL, NULL, "RFC error: multipart "
"section writes into trailing CRLF");
goto out;
}
/*
* Terminating boundary has an initial trailing "--".
* If not terminating, must be followed by a CRLF.
* If terminating, RFC 1341 says we can ignore whatever
* comes after the last boundary.
*/
if (memcmp(&buf[endpos], "--", 2)) {
while (endpos < len && buf[endpos] == ' ')
endpos++;
if (endpos > len - 2 ||
memcmp(&buf[endpos], "\r\n", 2)) {
kutil_warnx(NULL, NULL, "RFC error: "
"multipart boundary without "
"CRLF");
goto out;
}
endpos += 2;
} else
endpos = len;
/* First section: jump directly to reprocess. */
if (first)
continue;
/*
* Zero-length part.
* This shouldn't occur, but if it does, it'll screw up
* the MIME parsing (which requires a blank CRLF before
* considering itself finished).
*/
if ((partsz = ln - &buf[*pos]) == 0) {
kutil_warnx(NULL, NULL, "RFC error: "
"zero-length multipart section");
continue;
}
/* We now read our MIME headers, bailing on error. */
if (!mime_parse(pp, &mime, buf, *pos + partsz, pos)) {
kutil_warnx(NULL, NULL, "RFC error: "
"nested error parsing MIME headers");
goto out;
}
/*
* As per RFC 2388, we need a name and disposition.
* Note that multipart/mixed bodies will inherit the
* name of their parent, so the mime.name is ignored.
*/
if (mime.name == NULL && name == NULL) {
kutil_warnx(NULL, NULL,
"RFC error: no MIME name");
continue;
} else if (mime.disp == NULL) {
kutil_warnx(NULL, NULL,
"RFC error: no MIME disposition");
continue;
}
/*
* As per RFC 2045, we default to text/plain.
* We then re-lookup the ctypepos after doing so.
*/
if (mime.ctype == NULL) {
mime.ctype = kxstrdup("text/plain");
if (mime.ctype == NULL)
_exit(EXIT_FAILURE);
mime.ctypepos = str2ctype(pp, mime.ctype);
}
partsz = ln - &buf[*pos];
/*
* Multipart sub-handler.
* We only recognise the multipart/mixed handler.
* This will route into our own function, inheriting the
* current name for content.
*/
if (strcasecmp(mime.ctype, "multipart/mixed") == 0) {
if (mime.bound == NULL) {
kutil_warnx(NULL, NULL, "RFC error: "
"no mixed multipart boundary");
goto out;
}
if (!parse_multiform(pp,
name != NULL ? name : mime.name,
mime.bound, buf, *pos + partsz, pos)) {
kutil_warnx(NULL, NULL, "RFC error: "
"nested error parsing mixed "
"multipart section");
goto out;
}
continue;
}
assert(buf[*pos + partsz] == '\r' ||
buf[*pos + partsz] == '\0');
if (buf[*pos + partsz] != '\0')
buf[*pos + partsz] = '\0';
/* Assign all of our key-value pair data. */
output(pp, name != NULL ? name : mime.name,
&buf[*pos], partsz, &mime);
}
/*
* According to the specification, we can have transport
* padding, a CRLF, then the epilogue.
* But since we don't care about that crap, just pretend that
* everything's fine and exit.
*/
rc = 1;
out:
free(bb);
mime_free(&mime);
return rc;
}
/*
* Parse the boundary from a multipart CONTENT_TYPE and pass it to the
* actual parsing engine.
* This doesn't actually handle any part of the MIME specification.
*/
static void
parse_multi(const struct parms *pp, char *line, char *b, size_t bsz)
{
char *cp;
size_t len = 0;
while (*line == ' ')
line++;
if (*line++ != ';') {
kutil_warnx(NULL, NULL, "RFC error: expected "
"semicolon following multipart declaration");
return;
}
while (*line == ' ')
line++;
/* We absolutely need the boundary marker. */
if (strncmp(line, "boundary", 8)) {
kutil_warnx(NULL, NULL, "RFC error: expected "
"boundary following multipart declaration");
return;
}