-
Notifications
You must be signed in to change notification settings - Fork 80
/
http_server.c
2609 lines (2497 loc) · 92.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 "lang.h" // for FALLTHROUGH
#include "serval_types.h"
#include "http_server.h"
#include "sighandlers.h"
#include "conf.h"
#include "log.h"
#include "debug.h"
#include "str.h"
#include "numeric_str.h"
#include "base64.h"
#include "uri.h"
#include "strbuf.h"
#include "strbuf_helpers.h"
#include "net.h"
#include "mem.h"
#include "version_servald.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
};
int mime_content_types_are_equal(const struct mime_content_type *a, const struct mime_content_type *b) {
return strcmp(a->type, b->type) == 0
&& strcmp(a->subtype, b->subtype) == 0
&& strcmp(a->multipart_boundary, b->multipart_boundary) == 0
&& strcmp(a->charset, b->charset) == 0
&& strcmp(a->format, b->format) == 0;
}
const struct mime_content_type CONTENT_TYPE_FAVICON = { .type = "image", .subtype = "vnd.microsoft.icon" };
const struct mime_content_type CONTENT_TYPE_TEXT = { .type = "text", .subtype = "plain", .charset = "utf-8" };
const struct mime_content_type CONTENT_TYPE_HTML = { .type = "text", .subtype = "html", .charset = "utf-8" };
const struct mime_content_type CONTENT_TYPE_JSON = { .type = "application", .subtype = "json" };
const struct mime_content_type CONTENT_TYPE_BLOB = { .type = "application", .subtype = "octet-stream" };
static struct profile_total http_server_stats = {
.name = "http_server_poll",
};
#define DEBUG_DUMP_PARSED(r) \
DEBUGF(http_server, "%s %s HTTP/%u.%u", r->verb ? r->verb : "NULL", alloca_str_toprint(r->path), r->version_major, r->version_minor)
#define DEBUG_DUMP_PARSER(r) \
DEBUGF(http_server, "parsed=%d %s cursor=%d %s end_decoded=%d end_received=%d %s 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_decoded - r->cursor), \
(int)(r->end_decoded - r->received), \
(int)(r->end_received - r->end_decoded), alloca_toprint(20, r->end_decoded, r->end_received - r->end_decoded), \
r->request_content_remaining \
)
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_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->response.header.minor_version = 1;
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 and query parameters can be
// reserved ok.
r->received = r->decode_ptr = r->end_received = r->end_decoded = r->parsed = r->cursor = r->buffer + sizeof(void*) * (1 + NELS(r->query_parameters));
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) {
IDEBUGF(r->debug, "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;
IDEBUGF(r->debug, "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;
IDEBUGF(r->debug, "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)
{
IN();
if (r->phase == DONE)
RETURNVOID;
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;
OUT();
}
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 a given number of bytes 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, 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, const char *src, size_t len, void (*mover)(char *, const char *, size_t))
{
// Reserved string pointer must lie within this http_request struct.
assert((char*)resp >= (char*)r);
assert((char*)resp < (char*)(r + 1));
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.status_code = 414; // Request-URI Too Long
return 0;
}
if (r->reserved + siz > r->parsed) {
WHYF("Error during HTTP parsing, unparsed content %s would be overwritten by reserving %zu bytes",
alloca_toprint(30, r->parsed, r->end_decoded - r->parsed), len + 1
);
r->response.status_code = 500;
return 0;
}
const char ***respp = (const char ***) r->reserved;
char *restr = (char *)(respp + 1);
mover(restr, src, 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);
// Only store the pointer _after_ the memmove() above, to avoid overwriting part of the source
// string before we copy it, in the case that the source string is located within r->buffer[].
write_pointer((unsigned char*)respp, resp); // can't use *respp = resp; could cause SIGBUS if not aligned
*resp = restr;
return 1;
}
static void _mover_mem(char *dst, const char *src, size_t len)
{
if (dst != src)
memmove(dst, src, len);
}
#if 0
/* Allocate space from the start of the request buffer to hold the given substring plus a
* terminating NUL.
*
* @author Andrew Bettison <andrew@servalproject.com>
*/
static int _reserve_substring(struct http_request *r, const char **resp, struct substring str)
{
size_t len = str.end - str.start;
// Substring must contain no NUL chars.
assert(strnchr(str.start, len, '\0') == NULL);
return _reserve(r, resp, str.start, len, _mover_mem);
}
#endif
/* 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)
{
return _reserve(r, resp, str, strlen(str), _mover_mem);
}
/* The same as _reserve(), but decodes the source bytes using www-form-urlencoding.
*
* @author Andrew Bettison <andrew@servalproject.com>
*/
static void _mover_www_form_uri_decode(char *, const char *, size_t);
static int _reserve_www_form_uriencoded(struct http_request *r, const char **resp, struct substring str)
{
assert(str.end >= str.start);
const char *after = NULL;
size_t len = www_form_uri_decode(NULL, -1, (char *)str.start, str.end - str.start, &after);
assert(len <= (size_t)(str.end - str.start)); // decoded must not be longer than encoded
assert(after == str.end);
return _reserve(r, resp, str.start, len, _mover_www_form_uri_decode);
}
static void _mover_www_form_uri_decode(char *dst, const char *src, size_t len)
{
www_form_uri_decode(dst, len, src, -1, NULL);
}
/* 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 _at_end_of_content(struct http_request *r)
{
return r->cursor == r->end_decoded && r->request_content_remaining == 0;
}
static inline int _run_out_of_decoded_content(struct http_request *r)
{
assert(r->cursor <= r->end_decoded);
return r->cursor == r->end_decoded;
}
/* The input buffer is full if none of it has been parsed yet (so none can be discarded from the
* start) and no more data can be received (because either there is no room for any more data at
* the end or all expected data has already been received). This assumes that the decoder has
* already decoded all available data before this function can be called; ie, any un-decoded data in
* the buffer cannot be decoded yet until more is received (which cannot happen).
*/
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_decoded == 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_decoded);
r->parsed = r->cursor;
}
static inline int _skip_any_char(struct http_request *r)
{
if (_run_out_of_decoded_content(r))
return 0;
++r->cursor;
return 1;
}
static inline int _skip_while(struct http_request *r, int (*predicate)(int))
{
while (!_run_out_of_decoded_content(r) && predicate(*r->cursor))
++r->cursor;
return 1;
}
static inline void _skip_all(struct http_request *r)
{
r->cursor = r->end_decoded;
}
static inline int _skip_crlf(struct http_request *r)
{
return !_run_out_of_decoded_content(r)
&& *r->cursor == '\r'
&& ++r->cursor
&& !_run_out_of_decoded_content(r)
&& *r->cursor == '\n'
&& ++r->cursor;
}
static inline int _skip_to_crlf(struct http_request *r)
{
for (; !_run_out_of_decoded_content(r); ++r->cursor)
if (r->cursor + 1 < r->end_decoded && 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_of_decoded_content(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_of_decoded_content(r) && *r->cursor != '\n')
++r->cursor;
if (_run_out_of_decoded_content(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_of_decoded_content(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_of_decoded_content(r) && *literal && toupper(*r->cursor) == toupper(*literal))
++literal, ++r->cursor;
return *literal == '\0';
}
static int is_http_space(int c)
{
return c == ' ' || c == '\t';
}
static int _skip_optional_space(struct http_request *r)
{
return _skip_while(r, is_http_space);
}
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, char until)
{
const char *start = r->cursor;
if (str)
str->start = str->end = start;
if (_run_out_of_decoded_content(r) || isspace(*r->cursor) || !isprint(*r->cursor) || *r->cursor == until)
return 0;
for (++r->cursor;
!_run_out_of_decoded_content(r) && !isspace(*r->cursor) && isprint(*r->cursor) && *r->cursor != until;
++r->cursor)
;
if (_run_out_of_decoded_content(r))
return 0;
assert(r->cursor > start);
assert(isspace(*r->cursor) || *r->cursor == until);
if (str)
str->end = r->cursor;
return r->cursor - start;
}
static size_t _skip_token(struct http_request *r, struct substring *str)
{
if (_run_out_of_decoded_content(r) || !is_http_token(*r->cursor))
return 0;
const char *start = r->cursor;
for (++r->cursor; !_run_out_of_decoded_content(r) && is_http_token(*r->cursor); ++r->cursor)
;
if (_run_out_of_decoded_content(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_decoded);
if (_run_out_of_decoded_content(r) || *r->cursor != '"')
return 0;
int slosh = 0;
size_t len = 0;
for (++r->cursor; !_run_out_of_decoded_content(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_of_decoded_content(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_of_decoded_content(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_of_decoded_content(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_of_decoded_content(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)) {
IDEBUGF(r->debug, "Skipping HTTP Content-Type parameter: %s", alloca_substring_toprint(param));
continue;
}
WARNF("Malformed HTTP Content-Type: %s", alloca_toprint(50, r->cursor, r->end_decoded - 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_decoded - 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;
}
IDEBUGF(r->debug, "Malformed HTTP header: Authorization: %s", alloca_toprint(50, start, header_bytes));
return 0;
}
if (_skip_literal(r, "Digest") && _skip_space(r)) {
IDEBUG(r->debug, "Ignoring unsupported HTTP Authorization scheme: Digest");
r->cursor += header_bytes;
return 1;
}
struct substring scheme;
if (_skip_token(r, &scheme) && _skip_space(r)) {
IDEBUGF(r->debug, "Unrecognised HTTP Authorization scheme: %s", alloca_toprint(-1, scheme.start, scheme.end - scheme.start));
return 0;
}
IDEBUGF(r->debug, "Malformed HTTP Authorization header: %s", alloca_toprint(50, r->parsed, r->end_decoded - r->parsed));
return 0;
}
static int _parse_origin(struct http_request *r, struct http_origin *origin, size_t header_bytes)
{
char *start = r->cursor;
char *end = start + header_bytes;
bzero(origin, sizeof *origin);
if (_skip_literal(r, "null") && (r->cursor == end || _skip_space(r))) {
origin->null = 1;
return 1;
}
r->cursor = start;
struct substring scheme;
struct substring hostname;
if ( _skip_word_printable(r, &scheme, ':')
&& _skip_literal(r, "://")
&& _skip_word_printable(r, &hostname, '/')
) {
const char *port = hostname.end - 1;
while (port > hostname.start && isdigit(*port))
--port;
if (port >= hostname.start && *port == ':' && port < hostname.end - 1) {
const char *e = NULL;
if (port && port + 1 < r->cursor && str_to_uint16(port + 1, 10, &origin->port, &e)) {
assert(e == r->cursor);
hostname.end = port;
}
}
assert(hostname.end > hostname.start);
strbuf sb = strbuf_local_buf(origin->scheme);
strbuf_ncat(sb, scheme.start, scheme.end - scheme.start);
strbuf sh = strbuf_local_buf(origin->hostname);
strbuf_ncat(sh, hostname.start, hostname.end - hostname.start);
if (strbuf_overrun(sb) || strbuf_overrun(sh)) {
IDEBUGF(r->debug, "Ignoring HTTP Origin with over-long scheme: %s", alloca_toprint(50, start, header_bytes));
r->cursor = end;
return 1;
}
}
_skip_literal(r, "/");
return 1;
}
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_of_decoded_content(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_of_decoded_content(r))
return 100; // read more and try again
}
if (r->verb == NULL) {
IDEBUGF(r->debug, "Malformed HTTP request, invalid verb: %s", alloca_toprint(20, r->cursor, r->end_decoded - 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;
struct {
struct substring name;
struct substring value;
} params[NELS(r->query_parameters)];
unsigned count = 0;
if (_skip_word_printable(r, &path, '?')) {
struct substring param;
while ( count < NELS(params)
&& (_skip_literal(r, "?") || _skip_literal(r, "&"))
&& _skip_word_printable(r, ¶m, '&')
) {
const char *eq = strnchr(param.start, param.end - param.start, '=');
params[count].name.start = param.start;
if (eq) {
params[count].name.end = eq;
params[count].value.start = eq + 1;
params[count].value.end = param.end;
} else {
params[count].name.end = param.end;
params[count].value.start = NULL;
params[count].value.end = NULL;
}
IDEBUGF(r->debug, "Query parameter: %s%s%s",
alloca_substring_toprint(params[count].name),
params[count].value.start ? "=" : "",
params[count].value.start ? alloca_substring_toprint(params[count].value) : ""
);
++count;
}
}
if (!_skip_literal(r, " ")) {
if (_run_out_of_decoded_content(r))
return 100; // read more and try again
if (count == NELS(params))
IDEBUGF(r->debug, "Unsupported HTTP %s request, too many query parameters: %s", r->verb, alloca_toprint(20, r->parsed, r->end_decoded - r->parsed));
else
IDEBUGF(r->debug, "Malformed HTTP %s request at path: %s", r->verb, alloca_toprint(20, r->parsed, r->end_decoded - r->parsed));
return 400;
}
_commit(r);
if (!_reserve_www_form_uriencoded(r, &r->path, path))
return 0; // error
unsigned i;
for (i = 0; i != count; ++i) {
if (!_reserve_www_form_uriencoded(r, &r->query_parameters[i].name, params[i].name))
return 0; // error
if (params[i].value.start && !_reserve_www_form_uriencoded(r, &r->query_parameters[i].value, params[i].value))
return 0; // error
}
r->parser = http_request_parse_http_version;
return 0;
}
const char HTTP_REQUEST_PARAM_NOVALUE[] = "";
const char *http_request_get_query_param(struct http_request *r, const char *name)
{
unsigned i;
for (i = 0; i != NELS(r->query_parameters) && r->query_parameters[i].name; ++i) {
if (strcmp(r->query_parameters[i].name, name) == 0)
return r->query_parameters[i].value ? r->query_parameters[i].value : HTTP_REQUEST_PARAM_NOVALUE;
}
return NULL;
}
/* 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_of_decoded_content(r))
return 100; // read more and try again
IDEBUGF(r->debug, "Malformed HTTP %s request at version: %s", r->verb, alloca_toprint(20, r->parsed, r->end_decoded - 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).
*