forked from servalproject/serval-dna
-
Notifications
You must be signed in to change notification settings - Fork 0
/
http_server.c
2229 lines (2141 loc) · 77.9 KB
/
http_server.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
/*
Serval DNA - HTTP Server
Copyright (C) 2013 Serval Project Inc.
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#include <assert.h>
#include <inttypes.h>
#include <time.h>
#include "serval_types.h"
#include "http_server.h"
#include "sighandlers.h"
#include "conf.h"
#include "log.h"
#include "str.h"
#include "strbuf.h"
#include "strbuf_helpers.h"
#include "net.h"
#include "mem.h"
#define BOUNDARY_STRING_MAXLEN 70 // legislated limit from RFC-1341
/* The (struct http_request).verb field points to one of these static strings, so that a simple
* equality test can be used, eg, (r->verb == HTTP_VERB_GET) instead of a strcmp().
*
* @author Andrew Bettison <andrew@servalproject.com>
*/
const char HTTP_VERB_GET[] = "GET";
const char HTTP_VERB_POST[] = "POST";
const char HTTP_VERB_PUT[] = "PUT";
const char HTTP_VERB_HEAD[] = "HEAD";
const char HTTP_VERB_DELETE[] = "DELETE";
const char HTTP_VERB_TRACE[] = "TRACE";
const char HTTP_VERB_OPTIONS[] = "OPTIONS";
const char HTTP_VERB_CONNECT[] = "CONNECT";
const char HTTP_VERB_PATCH[] = "PATCH";
static struct {
const char *word;
size_t wordlen;
} http_verbs[] = {
#define VERB_ENTRY(NAME) { HTTP_VERB_##NAME, sizeof HTTP_VERB_##NAME - 1 }
VERB_ENTRY(GET),
VERB_ENTRY(POST),
VERB_ENTRY(PUT),
VERB_ENTRY(HEAD),
VERB_ENTRY(DELETE),
VERB_ENTRY(TRACE),
VERB_ENTRY(OPTIONS),
VERB_ENTRY(CONNECT),
VERB_ENTRY(PATCH)
#undef VERB_ENTRY
};
const char CONTENT_TYPE_TEXT[] = "text/plain";
const char CONTENT_TYPE_HTML[] = "text/html";
const char CONTENT_TYPE_JSON[] = "application/json";
const char CONTENT_TYPE_BLOB[] = "application/octet-stream";
static struct profile_total http_server_stats = {
.name = "http_server_poll",
};
#define DEBUG_DUMP_PARSED(r) do { \
if (config.debug.http_server) \
DEBUGF("%s %s HTTP/%u.%u", r->verb ? r->verb : "NULL", alloca_str_toprint(r->path), r->version_major, r->version_minor);\
} while (0)
#define DEBUG_DUMP_PARSER(r) do { \
if (config.debug.http_server) \
DEBUGF("parsed %d %s cursor %d %s end %d remain %"PRIhttp_size_t, \
(int)(r->parsed - r->received), alloca_toprint(-1, r->parsed, r->cursor - r->parsed), \
(int)(r->cursor - r->received), alloca_toprint(50, r->cursor, r->end - r->cursor), \
(int)(r->end - r->received), \
r->request_content_remaining \
); \
} while (0)
static void http_server_poll(struct sched_ent *);
static void http_request_set_idle_timeout(struct http_request *r);
static int http_request_parse_verb(struct http_request *r);
static int http_request_parse_path(struct http_request *r);
static int http_request_parse_http_version(struct http_request *r);
static int http_request_start_parsing_headers(struct http_request *r);
static int http_request_parse_header(struct http_request *r);
static int http_request_start_body(struct http_request *r);
static int http_request_reject_content(struct http_request *r);
static int http_request_parse_body_form_data(struct http_request *r);
static void http_request_start_response(struct http_request *r);
void http_request_init(struct http_request *r, int sockfd)
{
assert(sockfd != -1);
r->request_header.content_length = CONTENT_LENGTH_UNKNOWN;
r->request_content_remaining = CONTENT_LENGTH_UNKNOWN;
r->response.header.content_length = CONTENT_LENGTH_UNKNOWN;
r->response.header.resource_length = CONTENT_LENGTH_UNKNOWN;
r->alarm.stats = &http_server_stats;
r->alarm.function = http_server_poll;
assert(r->idle_timeout >= 0);
if (r->idle_timeout == 0)
r->idle_timeout = 10000; // 10 seconds
r->alarm.poll.fd = sockfd;
r->alarm.poll.events = POLLIN;
r->phase = RECEIVE;
r->reserved = r->buffer;
// Put aside a few bytes for reserving strings, so that the path can be reserved ok.
r->received = r->end = r->parsed = r->cursor = r->buffer + 32;
r->parser = http_request_parse_verb;
watch(&r->alarm);
http_request_set_idle_timeout(r);
}
static void http_request_set_idle_timeout(struct http_request *r)
{
assert(r->phase == RECEIVE || r->phase == TRANSMIT);
r->alarm.alarm = gettime_ms() + r->idle_timeout;
r->alarm.deadline = r->alarm.alarm + 500;
unschedule(&r->alarm);
schedule(&r->alarm);
}
void http_request_free_response_buffer(struct http_request *r)
{
if (r->response_free_buffer) {
if (r->debug_flag && *r->debug_flag)
DEBUGF("Free response buffer of %zu bytes", r->response_buffer_size);
r->response_free_buffer(r->response_buffer);
r->response_free_buffer = NULL;
}
r->response_buffer = NULL;
r->response_buffer_size = 0;
}
int http_request_set_response_bufsize(struct http_request *r, size_t bufsiz)
{
// Don't allocate a new buffer if the existing one contains content.
assert(r->response_buffer_sent == r->response_buffer_length);
const char *const bufe = r->buffer + sizeof r->buffer;
assert(r->reserved < bufe);
size_t rbufsiz = bufe - r->reserved;
if (bufsiz <= rbufsiz) {
http_request_free_response_buffer(r);
r->response_buffer = (char *) r->reserved;
r->response_buffer_size = rbufsiz;
if (r->debug_flag && *r->debug_flag)
DEBUGF("Static response buffer %zu bytes", r->response_buffer_size);
return 0;
}
if (bufsiz != r->response_buffer_size) {
http_request_free_response_buffer(r);
if ((r->response_buffer = emalloc(bufsiz)) == NULL)
return -1;
r->response_free_buffer = free;
r->response_buffer_size = bufsiz;
if (r->debug_flag && *r->debug_flag)
DEBUGF("Allocated response buffer %zu bytes", r->response_buffer_size);
}
assert(r->response_buffer_size >= bufsiz);
assert(r->response_buffer != NULL);
return 0;
}
void http_request_finalise(struct http_request *r)
{
if (r->phase == DONE)
return;
assert(r->phase == RECEIVE || r->phase == TRANSMIT || r->phase == PAUSE);
unschedule(&r->alarm);
if (r->phase != PAUSE)
unwatch(&r->alarm);
close(r->alarm.poll.fd);
r->alarm.poll.fd = -1;
if (r->finalise)
r->finalise(r);
r->finalise = NULL;
http_request_free_response_buffer(r);
r->phase = DONE;
}
struct substring {
const char *start;
const char *end;
};
#define alloca_substring_toprint(sub) alloca_toprint(-1, (sub).start, (sub).end - (sub).start)
const struct substring substring_NULL = { NULL, NULL };
#if 0
static int _matches(struct substring str, const char *text)
{
return strlen(text) == str.end - str.start && memcmp(str.start, text, str.end - str.start) == 0;
}
#endif
static void write_pointer(unsigned char *mem, const void *v)
{
memcpy(mem, &v, sizeof(void*));
}
static void *read_pointer(const unsigned char *mem)
{
void *v;
memcpy(&v, mem, sizeof(void*));
return v;
}
/* Allocate space from the start of the request buffer to hold the given substring plus a
* terminating NUL. Enough bytes must have already been marked as parsed in order to make room,
* otherwise the reservation fails and returns 0. If successful, copies the substring plus a
* terminating NUL into the reserved space, places a pointer to the reserved area into '*resp', and
* returns 1.
*
* Keeps a copy to the pointer 'resp', so that when the reserved area is released, all pointers into
* it can be set to NULL automatically. This provides some safety: if the pointer is accidentally
* dereferenced after the release it will cause a SEGV instead of using a string that has been
* overwritten. It does not protect from using copies of '*resp', which of course will not be have
* been set to NULL by the release.
*
* @author Andrew Bettison <andrew@servalproject.com>
*/
static int _reserve(struct http_request *r, const char **resp, struct substring str)
{
// Reserved string pointer must lie within this http_request struct.
assert((char*)resp >= (char*)r);
assert((char*)resp < (char*)(r + 1));
size_t len = str.end - str.start;
// Substring must contain no NUL chars.
assert(strnchr(str.start, len, '\0') == NULL);
char *reslim = r->buffer + sizeof r->buffer - 1024; // always leave this much unreserved space
assert(r->reserved <= reslim);
size_t siz = sizeof(char**) + len + 1;
if (r->reserved + siz > reslim) {
r->response.result_code = 414;
return 0;
}
if (r->reserved + siz > r->parsed) {
WARNF("Error during HTTP parsing, unparsed content %s would be overwritten by reserving %s",
alloca_toprint(30, r->parsed, r->end - r->parsed),
alloca_substring_toprint(str)
);
r->response.result_code = 500;
return 0;
}
assert(r->reserved + sizeof(char**) <= str.start);
const char ***respp = (const char ***) r->reserved;
char *restr = (char *)(respp + 1);
write_pointer((unsigned char*)respp, resp); // can't use *respp = resp; could cause SIGBUS if not aligned
if (restr != str.start)
memmove(restr, str.start, len);
restr[len] = '\0';
r->reserved += siz;
assert(r->reserved == &restr[len+1]);
if (r->reserved > r->received)
r->received = r->reserved;
assert(r->received <= r->parsed);
*resp = restr;
return 1;
}
/* The same as _reserve(), but takes a NUL-terminated string as a source argument instead of a
* substring.
*
* @author Andrew Bettison <andrew@servalproject.com>
*/
static int _reserve_str(struct http_request *r, const char **resp, const char *str)
{
struct substring sub = { .start = str, .end = str + strlen(str) };
return _reserve(r, resp, sub);
}
/* Release all the strings reserved by _reserve(), returning the space to the request buffer, and
* resetting to NULL all the pointers to reserved strings that were set by _reserve().
*
* @author Andrew Bettison <andrew@servalproject.com>
*/
static void _release_reserved(struct http_request *r)
{
char *res = r->buffer;
while (res < r->reserved) {
assert(res + sizeof(char**) + 1 <= r->reserved);
const char ***respp = (const char ***) res;
char *restr = (char *)(respp + 1);
const char **resp = read_pointer((const unsigned char*)respp); // can't use resp = *respp; could cause SIGBUS if not aligned
assert((const char*)resp >= (const char*)r);
assert((const char*)resp < (const char*)(r + 1));
assert(*resp == restr);
*resp = NULL;
for (res = restr; res < r->reserved && *res; ++res)
;
assert(res < r->reserved);
assert(*res == '\0');
++res;
}
assert(res == r->reserved);
r->reserved = r->buffer;
}
static inline int _end_of_content(struct http_request *r)
{
return r->cursor == r->end && r->request_content_remaining == 0;
}
static inline int _run_out(struct http_request *r)
{
assert(r->cursor <= r->end);
return r->cursor == r->end;
}
static inline int _buffer_full(struct http_request *r)
{
const char *const bufend = r->buffer + sizeof r->buffer;
return r->parsed == r->received && (r->end == bufend || r->request_content_remaining == 0);
}
static inline void _rewind(struct http_request *r)
{
assert(r->parsed >= r->received);
r->cursor = r->parsed;
}
static inline void _commit(struct http_request *r)
{
assert(r->cursor <= r->end);
r->parsed = r->cursor;
}
static inline int _skip_any(struct http_request *r)
{
if (_run_out(r))
return 0;
++r->cursor;
return 1;
}
static inline void _skip_all(struct http_request *r)
{
r->cursor = r->end;
}
static inline int _skip_crlf(struct http_request *r)
{
return !_run_out(r) && *r->cursor == '\r' && ++r->cursor && !_run_out(r) && *r->cursor == '\n' && ++r->cursor;
}
static inline int _skip_to_crlf(struct http_request *r)
{
for (; !_run_out(r); ++r->cursor)
if (r->cursor + 1 < r->end && r->cursor[0] == '\r' && r->cursor[1] == '\n')
return 1;
return 0;
}
static inline void _rewind_optional_cr(struct http_request *r)
{
if (r->cursor > r->parsed && r->cursor[-1] == '\r')
--r->cursor;
}
static inline void _rewind_crlf(struct http_request *r)
{
assert(r->cursor >= r->parsed + 2);
assert(r->cursor[-2] == '\r');
assert(r->cursor[-1] == '\n');
r->cursor -= 2;
}
/* More permissive than _skip_crlf(), this counts NUL characters preceding and between the CR and LF
* as part of the end-of-line sequence and treats the CR as optional. This allows simple manual
* testing using telnet(1).
*/
static inline int _skip_eol(struct http_request *r)
{
unsigned crcount = 0;
for (; !_run_out(r); ++r->cursor) {
switch (*r->cursor) {
case '\0': // ignore any leading NULs (telnet inserts them)
break;
case '\r': // ignore up to one leading CR
if (++crcount > 1)
return 0;
break;
case '\n':
++r->cursor;
return 1;
default:
return 0;
}
}
return 0;
}
/* More permissive than _skip_crlf(), this counts NUL characters preceding and between the CR and LF
* as part of the end-of-line sequence and treats the CR as optional. This allows simple manual
* testing using telnet(1).
*/
static int _skip_to_eol(struct http_request *r)
{
const char *const start = r->cursor;
while (!_run_out(r) && *r->cursor != '\n')
++r->cursor;
if (_run_out(r))
return 0;
// consume preceding NULs (telnet inserts them)
while (r->cursor > start && r->cursor[-1] == '\0')
--r->cursor;
// consume a single preceding CR
if (r->cursor > start && r->cursor[-1] == '\r')
--r->cursor;
// consume any more preceding NULs
while (r->cursor > start && r->cursor[-1] == '\0')
--r->cursor;
return 1;
}
static int _skip_literal(struct http_request *r, const char *literal)
{
while (!_run_out(r) && *literal && *r->cursor == *literal)
++literal, ++r->cursor;
return *literal == '\0';
}
static int _skip_literal_nocase(struct http_request *r, const char *literal)
{
while (!_run_out(r) && *literal && toupper(*r->cursor) == toupper(*literal))
++literal, ++r->cursor;
return *literal == '\0';
}
static int is_http_space(char c)
{
return c == ' ' || c == '\t';
}
static int _skip_optional_space(struct http_request *r)
{
while (!_run_out(r) && is_http_space(*r->cursor))
++r->cursor;
return 1;
}
static inline int _skip_space(struct http_request *r)
{
const char *const start = r->cursor;
_skip_optional_space(r);
return r->cursor > start;
}
static size_t _skip_word_printable(struct http_request *r, struct substring *str)
{
if (_run_out(r) || isspace(*r->cursor) || !isprint(*r->cursor))
return 0;
const char *start = r->cursor;
for (++r->cursor; !_run_out(r) && !isspace(*r->cursor) && isprint(*r->cursor); ++r->cursor)
;
if (_run_out(r))
return 0;
assert(r->cursor > start);
assert(isspace(*r->cursor));
if (str) {
str->start = start;
str->end = r->cursor;
}
return r->cursor - start;
}
static size_t _skip_token(struct http_request *r, struct substring *str)
{
if (_run_out(r) || !is_http_token(*r->cursor))
return 0;
const char *start = r->cursor;
for (++r->cursor; !_run_out(r) && is_http_token(*r->cursor); ++r->cursor)
;
if (_run_out(r))
return 0;
assert(r->cursor > start);
assert(!is_http_token(*r->cursor));
if (str) {
str->start = start;
str->end = r->cursor;
}
return r->cursor - start;
}
static size_t _parse_token(struct http_request *r, char *dst, size_t dstsiz)
{
struct substring str;
size_t len = _skip_token(r, &str);
if (len && dst) {
size_t cpy = len < dstsiz - 1 ? len : dstsiz - 1;
strncpy(dst, str.start, cpy)[cpy] = '\0';
}
return len;
}
static size_t _parse_quoted_string(struct http_request *r, char *dst, size_t dstsiz)
{
assert(r->cursor <= r->end);
if (_run_out(r) || *r->cursor != '"')
return 0;
int slosh = 0;
size_t len = 0;
for (++r->cursor; !_run_out(r); ++r->cursor) {
if (!isprint(*r->cursor))
return 0;
if (slosh) {
if (dst && len < dstsiz - 1)
dst[len] = *r->cursor;
++len;
slosh = 0;
} else if (*r->cursor == '"')
break;
else if (*r->cursor == '\\')
slosh = 1;
else {
if (dst && len < dstsiz - 1)
dst[len] = *r->cursor;
++len;
}
}
if (dst)
dst[len < dstsiz - 1 ? len : dstsiz - 1] = '\0';
if (_run_out(r))
return 0;
assert(*r->cursor == '"');
++r->cursor;
return len;
}
static size_t _parse_token_or_quoted_string(struct http_request *r, char *dst, size_t dstsiz)
{
assert(dstsiz > 0);
if (!_run_out(r) && *r->cursor == '"')
return _parse_quoted_string(r, dst, dstsiz);
return _parse_token(r, dst, dstsiz);
}
static inline int _parse_http_size_t(struct http_request *r, http_size_t *szp)
{
return !_run_out(r) && isdigit(*r->cursor) && str_to_uint64(r->cursor, 10, szp, (const char **)&r->cursor);
}
static inline int _parse_uint32(struct http_request *r, uint32_t *uint32p)
{
return !_run_out(r) && isdigit(*r->cursor) && str_to_uint32(r->cursor, 10, uint32p, (const char **)&r->cursor);
}
static unsigned _parse_ranges(struct http_request *r, struct http_range *range, unsigned nrange)
{
unsigned i = 0;
while (1) {
enum http_range_type type;
http_size_t first = 0, last = 0;
if (_skip_literal(r, "-")) {
if (!_parse_http_size_t(r, &last))
return 0;
type = SUFFIX;
}
else if (_parse_http_size_t(r, &first) && _skip_literal(r, "-")) {
if (_parse_http_size_t(r, &last)) {
if (last < first)
return 0;
type = CLOSED;
} else
type = OPEN;
} else
return 0;
if (i < nrange) {
range[i].type = type;
range[i].first = first;
range[i].last = last;
}
++i;
if (!_skip_literal(r, ","))
break;
_skip_optional_space(r);
}
return i;
}
static int _parse_content_type(struct http_request *r, struct mime_content_type *ct)
{
size_t n = _parse_token(r, ct->type, sizeof ct->type);
if (n == 0)
return 0;
if (n >= sizeof ct->type) {
WARNF("HTTP Content-Type type truncated: %s", alloca_str_toprint(ct->type));
return 0;
}
if (!_skip_literal(r, "/"))
return 0;
n = _parse_token(r, ct->subtype, sizeof ct->subtype);
if (n == 0)
return 0;
if (n >= sizeof ct->subtype) {
WARNF("HTTP Content-Type subtype truncated: %s", alloca_str_toprint(ct->subtype));
return 0;
}
while (_skip_optional_space(r) && _skip_literal(r, ";") && _skip_optional_space(r)) {
char *start = r->cursor;
if (_skip_literal(r, "charset=")) {
size_t n = _parse_token_or_quoted_string(r, ct->charset, sizeof ct->charset);
if (n == 0)
return 0;
if (n >= sizeof ct->charset) {
WARNF("HTTP Content-Type charset truncated: %s", alloca_str_toprint(ct->charset));
return 0;
}
continue;
}
r->cursor = start;
if (_skip_literal(r, "boundary=")) {
size_t n = _parse_token_or_quoted_string(r, ct->multipart_boundary, sizeof ct->multipart_boundary);
if (n == 0)
return 0;
if (n >= sizeof ct->multipart_boundary) {
WARNF("HTTP Content-Type boundary truncated: %s", alloca_str_toprint(ct->multipart_boundary));
return 0;
}
continue;
}
r->cursor = start;
if (_skip_literal(r, "format=")) {
size_t n = _parse_token_or_quoted_string(r, ct->format, sizeof ct->format);
if (n == 0)
return 0;
if (n >= sizeof ct->format) {
WARNF("HTTP Content-Type format truncated: %s", alloca_str_toprint(ct->format));
return 0;
}
continue;
}
r->cursor = start;
struct substring param;
if (_skip_token(r, ¶m) && _skip_literal(r, "=") && _parse_token_or_quoted_string(r, NULL, 0)) {
if (r->debug_flag && *r->debug_flag)
DEBUGF("Skipping HTTP Content-Type parameter: %s", alloca_substring_toprint(param));
continue;
}
WARNF("Malformed HTTP Content-Type: %s", alloca_toprint(50, r->cursor, r->end - r->cursor));
return 0;
}
return 1;
}
static size_t _parse_base64(struct http_request *r, char *bin, size_t binsize)
{
return base64_decode((unsigned char *)bin, binsize, r->cursor, r->end - r->cursor, (const char **)&r->cursor, B64_CONSUME_ALL, is_http_space);
}
static int _parse_authorization_credentials_basic(struct http_request *r, struct http_client_credentials_basic *cred, char *buf, size_t bufsz)
{
size_t n = _parse_base64(r, buf, bufsz - 1); // leave room for NUL terminator on password
assert(n < bufsz); // buffer must be big enough
char *pw = (char *) strnchr(buf, n, ':');
if (pw == NULL)
return 0; // malformed
cred->user = buf;
*pw++ = '\0'; // NUL terminate user
cred->password = pw;
buf[n] = '\0'; // NUL terminate password
return 1;
}
static int _parse_authorization(struct http_request *r, struct http_client_authorization *auth, size_t header_bytes)
{
char *start = r->cursor;
if (_skip_literal(r, "Basic") && _skip_space(r)) {
size_t bufsz = 5 + header_bytes * 3 / 4; // enough for base64 decoding
char buf[bufsz];
if (_parse_authorization_credentials_basic(r, &auth->credentials.basic, buf, bufsz)) {
auth->scheme = BASIC;
_commit(r); // make room for following reservations
if ( !_reserve_str(r, &auth->credentials.basic.user, auth->credentials.basic.user)
|| !_reserve_str(r, &auth->credentials.basic.password, auth->credentials.basic.password)
)
return 0; // error
return 1;
}
if (r->debug_flag && *r->debug_flag)
DEBUGF("Malformed HTTP header: Authorization: %s", alloca_toprint(50, start, header_bytes));
return 0;
}
if (_skip_literal(r, "Digest") && _skip_space(r)) {
if (r->debug_flag && *r->debug_flag)
DEBUG("Ignoring unsupported HTTP Authorization scheme: Digest");
r->cursor += header_bytes;
return 1;
}
struct substring scheme;
if (_skip_token(r, &scheme) && _skip_space(r)) {
if (r->debug_flag && *r->debug_flag)
DEBUGF("Unrecognised HTTP Authorization scheme: %s", alloca_toprint(-1, scheme.start, scheme.end - scheme.start));
return 0;
}
if (r->debug_flag && *r->debug_flag)
DEBUGF("Malformed HTTP Authorization header: %s", alloca_toprint(50, r->parsed, r->end - r->parsed));
return 0;
}
static int _parse_quoted_rfc822_time(struct http_request *r, time_t *timep)
{
char datestr[40];
size_t n = _parse_quoted_string(r, datestr, sizeof datestr);
if (n == 0 || n >= sizeof datestr)
return 0;
// TODO: Move the following code into its own function in str.c
struct tm tm;
bzero(&tm, sizeof tm);
// TODO: Ensure this works in non-English locales, ie, "%a" still accepts "Mon", "Tue" etc. and
// "%b" still accepts "Jan", "Feb" etc.
// TODO: Support symbolic time zones, eg, "UT", "GMT", "UTC", "EST"...
const char *c = strptime(datestr, "%a, %d %b %Y %T ", &tm);
if ((c[0] == '-' || c[0] == '+') && isdigit(c[1]) && isdigit(c[2]) && isdigit(c[3]) && isdigit(c[4]) && c[5] == '\0') {
time_t zone = (c[0] == '-' ? -1 : 1) * ((c[1] - '0') * 600 + (c[2] - '0') * 60 + (c[3] - '0') * 10 + (c[4] - '0'));
const char *tz = getenv("TZ");
if (tz)
tz = alloca_strdup(tz);
setenv("TZ", "", 1);
tzset();
*timep = mktime(&tm) - zone;
if (tz)
setenv("TZ", tz, 1);
else
unsetenv("TZ");
tzset();
return 1;
}
return 0;
}
/* If parsing completes, then sets r->parser to the next parsing function and returns 0. If parsing
* cannot complete due to running out of data, returns 100 without changing r->parser, so this
* function will be called again once more data has been read. Returns a 4nn or 5nn HTTP result
* code if parsing fails. Returns -1 if an unexpected error occurs.
*
* @author Andrew Bettison <andrew@servalproject.com>
*/
static int http_request_parse_verb(struct http_request *r)
{
DEBUG_DUMP_PARSER(r);
_rewind(r);
assert(r->cursor >= r->received);
assert(!_run_out(r));
// Parse verb: GET, PUT, POST, etc.
assert(r->verb == NULL);
unsigned i;
for (i = 0; i < NELS(http_verbs); ++i) {
_rewind(r);
if (_skip_literal(r, http_verbs[i].word) && _skip_literal(r, " ")) {
r->verb = http_verbs[i].word;
break;
}
if (_run_out(r))
return 100; // read more and try again
}
if (r->verb == NULL) {
if (r->debug_flag && *r->debug_flag)
DEBUGF("Malformed HTTP request, invalid verb: %s", alloca_toprint(20, r->cursor, r->end - r->cursor));
return 400;
}
_commit(r);
r->parser = http_request_parse_path;
return 0;
}
/* If parsing completes, then sets r->parser to the next parsing function and returns 0. If parsing
* cannot complete due to running out of data, returns 100 without changing r->parser, so this
* function will be called again once more data has been read. Returns a 4nn or 5nn HTTP result
* code if parsing fails. Returns -1 if an unexpected error occurs.
*
* @author Andrew Bettison <andrew@servalproject.com>
*/
static int http_request_parse_path(struct http_request *r)
{
DEBUG_DUMP_PARSER(r);
// Parse path: word immediately following verb, delimited by spaces.
assert(r->path == NULL);
struct substring path;
if (!(_skip_word_printable(r, &path) && _skip_literal(r, " "))) {
if (_run_out(r))
return 100; // read more and try again
if (r->debug_flag && *r->debug_flag)
DEBUGF("Malformed HTTP %s request at path: %s", r->verb, alloca_toprint(20, r->parsed, r->end - r->parsed));
return 400;
}
_commit(r);
if (!_reserve(r, &r->path, path))
return 0; // error
r->parser = http_request_parse_http_version;
return 0;
}
/* If parsing completes, then sets r->parser to the next parsing function and returns 0. If parsing
* cannot complete due to running out of data, returns 100 without changing r->parser, so this
* function will be called again once more data has been read. Returns a 4nn or 5nn HTTP result
* code if parsing fails. Returns -1 if an unexpected error occurs.
*
* @author Andrew Bettison <andrew@servalproject.com>
*/
static int http_request_parse_http_version(struct http_request *r)
{
DEBUG_DUMP_PARSER(r);
// Parse HTTP version: HTTP/m.n followed by CRLF.
assert(r->version_major == 0);
assert(r->version_minor == 0);
uint32_t major, minor;
if (!( _skip_literal(r, "HTTP/")
&& _parse_uint32(r, &major)
&& major > 0 && major < UINT8_MAX
&& _skip_literal(r, ".")
&& _parse_uint32(r, &minor)
&& minor < UINT8_MAX
&& _skip_eol(r)
)
) {
if (_run_out(r))
return 100; // read more and try again
if (r->debug_flag && *r->debug_flag)
DEBUGF("Malformed HTTP %s request at version: %s", r->verb, alloca_toprint(20, r->parsed, r->end - r->parsed));
return 400;
}
_commit(r);
r->version_major = major;
r->version_minor = minor;
r->parser = http_request_start_parsing_headers;
if (r->handle_first_line)
return r->handle_first_line(r);
return 0; // parsing complete
}
/* Select the header parser. Returns 0 after setting the new parser function. Returns a 4nn or 5nn
* HTTP result code if the request cannot be handled (eg, unsupported HTTP version or invalid path).
*
* @author Andrew Bettison <andrew@servalproject.com>
*/
static int http_request_start_parsing_headers(struct http_request *r)
{
DEBUG_DUMP_PARSER(r);
assert(r->verb != NULL);
assert(r->path != NULL);
assert(r->version_major != 0);
if (r->version_major != 1) {
if (r->debug_flag && *r->debug_flag)
DEBUGF("Unsupported HTTP version: %u.%u", r->version_major, r->version_minor);
return 400;
}
r->parser = http_request_parse_header;
return 0;
}
/* Parse one request header line.
*
* If the end of headers is parsed (blank line), then sets r->parser to the next parsing function
* and returns 0. If a single header line is successfully parsed, returns 0 after advancing
* r->parsed. If parsing cannot complete due to running out of data, returns 0 without changing
* r->parser, so this function will be called again once more data has been read. Returns a 4nn or
* 5nn HTTP result code if parsing fails. Returns -1 if an unexpected error occurs.
*
* @author Andrew Bettison <andrew@servalproject.com>
*/
static int http_request_parse_header(struct http_request *r)
{
DEBUG_DUMP_PARSER(r);
_skip_to_eol(r);
const char *const eol = r->cursor;
_skip_eol(r);
if (eol == r->parsed) { // if EOL is at start of line (ie, blank line)...
_commit(r);
if (r->request_header.content_length != CONTENT_LENGTH_UNKNOWN) {
size_t unparsed = r->end - r->parsed;
if (unparsed > r->request_header.content_length) {
WARNF("HTTP parsing: already read %zu bytes past end of content", (size_t)(unparsed - r->request_header.content_length));
r->request_content_remaining = 0;
}
else
r->request_content_remaining = r->request_header.content_length - unparsed;
}
r->parser = http_request_start_body;
if (r->handle_headers)
return r->handle_headers(r);
return 0;
}
char *const nextline = r->cursor;
_rewind(r);
const char *const sol = r->cursor;
if (_skip_literal_nocase(r, "Content-Length:")) {
if (r->request_header.content_length != CONTENT_LENGTH_UNKNOWN) {
if (r->debug_flag && *r->debug_flag)
DEBUGF("Skipping duplicate HTTP header Content-Length: %s", alloca_toprint(50, sol, r->end - sol));
r->cursor = nextline;
_commit(r);
return 0;
}
_skip_optional_space(r);
http_size_t length;
if (_parse_http_size_t(r, &length) && _skip_optional_space(r) && r->cursor == eol) {
r->cursor = nextline;
_commit(r);
r->request_header.content_length = length;
if (r->debug_flag && *r->debug_flag)
DEBUGF("Parsed HTTP request Content-Length: %"PRIhttp_size_t, r->request_header.content_length);
return 0;
}
goto malformed;
}
_rewind(r);
if (_skip_literal_nocase(r, "Content-Type:")) {
if (r->request_header.content_type.type[0]) {
if (r->debug_flag && *r->debug_flag)
DEBUGF("Skipping duplicate HTTP header Content-Type: %s", alloca_toprint(50, sol, r->end - sol));
r->cursor = nextline;
_commit(r);
return 0;
}
_skip_optional_space(r);
if ( _parse_content_type(r, &r->request_header.content_type)
&& _skip_optional_space(r)
&& r->cursor == eol
) {
r->cursor = nextline;
_commit(r);
if (r->debug_flag && *r->debug_flag)
DEBUGF("Parsed HTTP request Content-type: %s", alloca_mime_content_type(&r->request_header.content_type));
return 0;
}
goto malformed;
}
_rewind(r);
if (_skip_literal_nocase(r, "Range:")) {
if (r->request_header.content_range_count) {
if (r->debug_flag && *r->debug_flag)
DEBUGF("Skipping duplicate HTTP header Range: %s", alloca_toprint(50, sol, r->end - sol));
r->cursor = nextline;
_commit(r);
return 0;
}
_skip_optional_space(r);
unsigned int n;
if ( _skip_literal(r, "bytes=")
&& (n = _parse_ranges(r, r->request_header.content_ranges, NELS(r->request_header.content_ranges)))
&& _skip_optional_space(r)
&& r->cursor == eol
) {
r->cursor = nextline;
_commit(r);
if (n > NELS(r->request_header.content_ranges)) {
if (r->debug_flag && *r->debug_flag)
DEBUGF("HTTP request Range header overflow (%u ranges in set, can only handle %zu): %s",
n, NELS(r->request_header.content_ranges), alloca_toprint(-1, sol, eol - sol));
// In this case ignore the Range: header -- respond with the entire resource.
r->request_header.content_range_count = 0;
} else {
r->request_header.content_range_count = n;
if (r->debug_flag && *r->debug_flag)
DEBUGF("Parsed HTTP request Range: bytes=%s", alloca_http_ranges(r->request_header.content_ranges));
}
return 0;
}
goto malformed;
}
_rewind(r);
if (_skip_literal_nocase(r, "Authorization:")) {
if (r->request_header.authorization.scheme != NOAUTH) {
if (r->debug_flag && *r->debug_flag)
DEBUGF("Skipping duplicate HTTP header Authorization: %s", alloca_toprint(50, sol, r->end - sol));
r->cursor = nextline;
_commit(r);
return 0;
}
_skip_optional_space(r);
if ( _parse_authorization(r, &r->request_header.authorization, eol - r->cursor)
&& _skip_optional_space(r)
&& r->cursor == eol
) {
assert(r->request_header.authorization.scheme != NOAUTH);
r->cursor = nextline;
_commit(r);
return 0;
}
if (r->response.result_code)
return r->response.result_code;
goto malformed;
}
_rewind(r);
if (_skip_literal_nocase(r, "Origin:")) {