-
Notifications
You must be signed in to change notification settings - Fork 237
/
http.cc
1631 lines (1381 loc) · 48.3 KB
/
http.cc
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
/***************************************************************************
* http.c -- HTTP network interaction, parsing, and construction. *
***********************IMPORTANT NMAP LICENSE TERMS************************
* *
* The Nmap Security Scanner is (C) 1996-2021 Insecure.Com LLC ("The Nmap *
* Project"). Nmap is also a registered trademark of the Nmap Project. *
* This program is free software; you may redistribute and/or modify it *
* under the terms of the GNU General Public License as published by the *
* Free Software Foundation; Version 2 ("GPL"), BUT ONLY WITH ALL OF THE *
* CLARIFICATIONS AND EXCEPTIONS DESCRIBED HEREIN. This guarantees your *
* right to use, modify, and redistribute this software under certain *
* conditions. If you wish to embed Nmap technology into proprietary *
* software, we sell alternative licenses (contact [email protected]). *
* Dozens of software vendors already license Nmap technology such as *
* host discovery, port scanning, OS detection, version detection, and *
* the Nmap Scripting Engine. *
* *
* Note that the GPL places important restrictions on "derivative works", *
* yet it does not provide a detailed definition of that term. To avoid *
* misunderstandings, we interpret that term as broadly as copyright law *
* allows. For example, we consider an application to constitute a *
* derivative work for the purpose of this license if it does any of the *
* following with any software or content covered by this license *
* ("Covered Software"): *
* *
* o Integrates source code from Covered Software. *
* *
* o Reads or includes copyrighted data files, such as Nmap's nmap-os-db *
* or nmap-service-probes. *
* *
* o Is designed specifically to execute Covered Software and parse the *
* results (as opposed to typical shell or execution-menu apps, which will *
* execute anything you tell them to). *
* *
* o Includes Covered Software in a proprietary executable installer. The *
* installers produced by InstallShield are an example of this. Including *
* Nmap with other software in compressed or archival form does not *
* trigger this provision, provided appropriate open source decompression *
* or de-archiving software is widely available for no charge. For the *
* purposes of this license, an installer is considered to include Covered *
* Software even if it actually retrieves a copy of Covered Software from *
* another source during runtime (such as by downloading it from the *
* Internet). *
* *
* o Links (statically or dynamically) to a library which does any of the *
* above. *
* *
* o Executes a helper program, module, or script to do any of the above. *
* *
* This list is not exclusive, but is meant to clarify our interpretation *
* of derived works with some common examples. Other people may interpret *
* the plain GPL differently, so we consider this a special exception to *
* the GPL that we apply to Covered Software. Works which meet any of *
* these conditions must conform to all of the terms of this license, *
* particularly including the GPL Section 3 requirements of providing *
* source code and allowing free redistribution of the work as a whole. *
* *
* As another special exception to the GPL terms, the Nmap Project grants *
* permission to link the code of this program with any version of the *
* OpenSSL library which is distributed under a license identical to that *
* listed in the included docs/licenses/OpenSSL.txt file, and distribute *
* linked combinations including the two. *
* *
* The Nmap Project has permission to redistribute Npcap, a packet *
* capturing driver and library for the Microsoft Windows platform. *
* Npcap is a separate work with it's own license rather than this Nmap *
* license. Since the Npcap license does not permit redistribution *
* without special permission, our Nmap Windows binary packages which *
* contain Npcap may not be redistributed without special permission. *
* *
* Any redistribution of Covered Software, including any derived works, *
* must obey and carry forward all of the terms of this license, including *
* obeying all GPL rules and restrictions. For example, source code of *
* the whole work must be provided and free redistribution must be *
* allowed. All GPL references to "this License", are to be treated as *
* including the terms and conditions of this license text as well. *
* *
* Because this license imposes special exceptions to the GPL, Covered *
* Work may not be combined (even as part of a larger work) with plain GPL *
* software. The terms, conditions, and exceptions of this license must *
* be included as well. This license is incompatible with some other open *
* source licenses as well. In some cases we can relicense portions of *
* Nmap or grant special permissions to use it in other open source *
* software. Please contact [email protected] with any such requests. *
* Similarly, we don't incorporate incompatible open source software into *
* Covered Software without special permission from the copyright holders. *
* *
* If you have any questions about the licensing restrictions on using *
* Nmap in other works, we are happy to help. As mentioned above, we also *
* offer an alternative license to integrate Nmap into proprietary *
* applications and appliances. These contracts have been sold to dozens *
* of software vendors, and generally include a perpetual license as well *
* as providing support and updates. They also fund the continued *
* development of Nmap. Please email [email protected] for further *
* information. *
* *
* If you have received a written license agreement or contract for *
* Covered Software stating terms other than these, you may choose to use *
* and redistribute Covered Software under those terms instead of these. *
* *
* Source is provided to this software because we believe users have a *
* right to know exactly what a program is going to do before they run it. *
* This also allows you to audit the software for security holes. *
* *
* Source code also allows you to port Nmap to new platforms, fix bugs, *
* and add new features. You are highly encouraged to send your changes *
* to the [email protected] mailing list for possible incorporation into the *
* main distribution. By sending these changes to Fyodor or one of the *
* Insecure.Org development mailing lists, or checking them into the Nmap *
* source code repository, it is understood (unless you specify *
* otherwise) that you are offering the Nmap Project the unlimited, *
* non-exclusive right to reuse, modify, and relicense the code. Nmap *
* will always be available Open Source, but this is important because *
* the inability to relicense code has caused devastating problems for *
* other Free Software projects (such as KDE and NASM). We also *
* occasionally relicense the code to third parties as discussed above. *
* If you wish to specify special license conditions of your *
* contributions, just say so when you send them. *
* *
* 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 Nmap *
* license file for more details (it's in a COPYING file included with *
* Nmap, and also available from https://svn.nmap.org/nmap/COPYING) *
* *
***************************************************************************/
/* $Id$ */
#include <string.h>
#include "http.h"
#include "errno.h"
/* Limit the size of in-memory data structures to avoid certain denial of
service attacks (those trying to consume all available memory). */
static const int MAX_REQUEST_LINE_LENGTH = 1024;
static const int MAX_STATUS_LINE_LENGTH = 1024;
static const int MAX_HEADER_LENGTH = 1024 * 10;
/* The URI functions have a test program in test/test-uri.c. Run the test after
making any changes and add tests for any new functions. */
void uri_init(struct uri *uri)
{
uri->scheme = NULL;
uri->host = NULL;
uri->port = -1;
uri->path = NULL;
}
void uri_free(struct uri *uri)
{
free(uri->scheme);
free(uri->host);
free(uri->path);
}
static int hex_digit_value(char digit)
{
const char *DIGITS = "0123456789abcdef";
const char *p;
if ((unsigned char) digit == '\0')
return -1;
p = strchr(DIGITS, tolower((int) (unsigned char) digit));
if (p == NULL)
return -1;
return p - DIGITS;
}
/* Case-insensitive string comparison. */
static int str_cmp_i(const char *a, const char *b)
{
while (*a != '\0' && *b != '\0') {
int ca, cb;
ca = tolower((int) (unsigned char) *a);
cb = tolower((int) (unsigned char) *b);
if (ca != cb)
return ca - cb;
a++;
b++;
}
if (*a == '\0' && *b == '\0')
return 0;
else if (*a == '\0')
return -1;
else
return 1;
}
static int str_equal_i(const char *a, const char *b)
{
return str_cmp_i(a, b) == 0;
}
static int lowercase(char *s)
{
char *p;
for (p = s; *p != '\0'; p++)
*p = tolower((int) (unsigned char) *p);
return p - s;
}
/* In-place percent decoding. */
static int percent_decode(char *s)
{
char *p, *q;
/* Skip to the first '%'. If there are no percent escapes, this lets us
return without doing any copying. */
q = s;
while (*q != '\0' && *q != '%')
q++;
p = q;
while (*q != '\0') {
if (*q == '%') {
int c, d;
q++;
c = hex_digit_value(*q);
if (c == -1)
return -1;
q++;
d = hex_digit_value(*q);
if (d == -1)
return -1;
*p++ = c * 16 + d;
q++;
} else {
*p++ = *q++;
}
}
*p = '\0';
return p - s;
}
/* Use these functions because isalpha and isdigit can change their meaning
based on the locale. */
static int is_alpha_char(int c)
{
return c != '\0' && strchr("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ", c) != NULL;
}
static int is_digit_char(int c)
{
return c != '\0' && strchr("0123456789", c) != NULL;
}
/* Get the default port for the given URI scheme, or -1 if unrecognized. */
static int scheme_default_port(const char *scheme)
{
if (str_equal_i(scheme, "http"))
return 80;
return -1;
}
/* Parse a URI string into a struct URI. Any parts of the URI that are absent
will become NULL entries in the structure, except for the port which will be
-1. Returns NULL on error. See RFC 3986, section 3 for syntax. */
struct uri *uri_parse(struct uri *uri, const char *uri_s)
{
const char *p, *q;
uri_init(uri);
/* Scheme, section 3.1. */
p = uri_s;
if (!is_alpha_char(*p))
goto fail;
for (q = p; is_alpha_char(*q) || is_digit_char(*q) || *q == '+' || *q == '-' || *q == '.'; q++)
;
if (*q != ':')
goto fail;
uri->scheme = mkstr(p, q);
/* "An implementation should accept uppercase letters as equivalent to
lowercase in scheme names (e.g., allow "HTTP" as well as "http") for the
sake of robustness..." */
lowercase(uri->scheme);
/* Authority, section 3.2. */
p = q + 1;
if (*p == '/' && *(p + 1) == '/') {
char *authority = NULL;
p += 2;
for (q = p; !(*q == '/' || *q == '?' || *q == '#' || *q == '\0'); q++)
;
authority = mkstr(p, q);
if (uri_parse_authority(uri, authority) == NULL) {
free(authority);
goto fail;
}
free(authority);
p = q;
}
if (uri->port == -1)
uri->port = scheme_default_port(uri->scheme);
/* Path, section 3.3. We include the query and fragment in the path. The
path is also not percent-decoded because we just pass it on to the origin
server. */
q = strchr(p, '\0');
uri->path = mkstr(p, q);
return uri;
fail:
uri_free(uri);
return NULL;
}
/* Parse the authority part of a URI. userinfo (user name and password) are not
supported and will cause an error if present. See RFC 3986, section 3.2.
Returns NULL on error. */
struct uri *uri_parse_authority(struct uri *uri, const char *authority)
{
const char *portsep;
const char *host_start, *host_end;
char *tail;
/* We do not support "user:pass@" userinfo. The proxy has no use for it. */
if (strchr(authority, '@') != NULL)
return NULL;
/* Find the beginning and end of the host. */
host_start = authority;
if (*host_start == '[') {
/* IPv6 address in brackets. */
host_start++;
host_end = strchr(host_start, ']');
if (host_end == NULL)
return NULL;
portsep = host_end + 1;
if (!(*portsep == ':' || *portsep == '\0'))
return NULL;
} else {
portsep = strrchr(authority, ':');
if (portsep == NULL)
portsep = strchr(authority, '\0');
host_end = portsep;
}
/* Get the port number. */
if (*portsep == ':' && *(portsep + 1) != '\0') {
long n;
errno = 0;
n = parse_long(portsep + 1, &tail);
if (errno != 0 || *tail != '\0' || tail == portsep + 1 || n < 1 || n > 65535)
return NULL;
uri->port = n;
} else {
uri->port = -1;
}
/* Get the host. */
uri->host = mkstr(host_start, host_end);
if (percent_decode(uri->host) < 0) {
free(uri->host);
uri->host = NULL;
return NULL;
}
return uri;
}
static void http_header_node_free(struct http_header *node)
{
free(node->name);
free(node->value);
free(node);
}
void http_header_free(struct http_header *header)
{
struct http_header *p, *next;
for (p = header; p != NULL; p = next) {
next = p->next;
http_header_node_free(p);
}
}
/* RFC 2616, section 2.2; see LWS. */
static int is_space_char(int c)
{
return c == ' ' || c == '\t';
}
/* RFC 2616, section 2.2. */
static int is_ctl_char(int c)
{
return (c >= 0 && c <= 31) || c == 127;
}
/* RFC 2616, section 2.2. */
static int is_sep_char(int c)
{
return c != '\0' && strchr("()<>@,;:\\\"/[]?={} \t", c) != NULL;
}
/* RFC 2616, section 2.2. */
static int is_token_char(char c)
{
return !iscntrl((int) (unsigned char) c) && !is_sep_char((int) (unsigned char) c);
}
static int is_crlf(const char *s)
{
return *s == '\n' || (*s == '\r' && *(s + 1) == '\n');
}
static const char *skip_crlf(const char *s)
{
if (*s == '\n')
return s + 1;
else if (*s == '\r' && *(s + 1) == '\n')
return s + 2;
return NULL;
}
static int field_name_equal(const char *a, const char *b)
{
return str_equal_i(a, b);
}
/* Get the value of every header with the given name, separated by commas. If
you only want the first value for header fields that should not be
concatenated in this way, use http_header_get_first. The returned string
must be freed. */
char *http_header_get(const struct http_header *header, const char *name)
{
const struct http_header *p;
char *buf = NULL;
size_t size = 0, offset = 0;
int count;
count = 0;
for (p = header; p != NULL; p = p->next) {
/* RFC 2616, section 4.2: "Multiple message-header fields with the same
field-name MAY be present in a message if and only if the entire
field-value for that header field is defined as a comma-separated
list [i.e., #(values)]. It MUST be possible to combine the multiple
header fields into one "field-name: field-value" pair, without
changing the semantics of the message, by appending each subsequent
field-value to the first, each separated by a comma." */
if (field_name_equal(p->name, name)) {
if (count > 0)
strbuf_append_str(&buf, &size, &offset, ", ");
strbuf_append_str(&buf, &size, &offset, p->value);
count++;
}
}
return buf;
}
const struct http_header *http_header_next(const struct http_header *header,
const struct http_header *p, const char *name)
{
if (p == NULL)
p = header;
else
p = p->next;
for (; p != NULL; p = p->next) {
if (field_name_equal(p->name, name))
return p;
}
return NULL;
}
/* Get the value of the first header with the given name. The returned string
must be freed. */
char *http_header_get_first(const struct http_header *header, const char *name)
{
const struct http_header *p;
p = http_header_next(header, NULL, name);
if (p != NULL)
return strdup(p->value);
return NULL;
}
struct http_header *http_header_set(struct http_header *header, const char *name, const char *value)
{
struct http_header *node, **prev;
header = http_header_remove(header, name);
node = (struct http_header *) safe_malloc(sizeof(*node));
node->name = strdup(name);
node->value = strdup(value);
node->next = NULL;
/* Link it to the end of the list. */
for (prev = &header; *prev != NULL; prev = &(*prev)->next)
;
*prev = node;
return header;
}
/* Read a token from a space-separated string. This only recognizes space as a
separator, so the string must already have had LWS normalized.
http_header_parse does this normalization. */
static const char *read_token(const char *s, char **token)
{
const char *t;
while (*s == ' ')
s++;
t = s;
while (is_token_char(*t))
t++;
if (s == t)
return NULL;
*token = mkstr(s, t);
return t;
}
static const char *read_quoted_string(const char *s, char **quoted_string)
{
char *buf = NULL;
size_t size = 0, offset = 0;
const char *t;
while (is_space_char(*s))
s++;
if (*s != '"')
return NULL;
s++;
t = s;
while (*s != '"') {
/* Get a block of normal characters. */
while (*t != '"' && *t != '\\') {
/* This is qdtext, which is TEXT except for CTL. */
if (is_ctl_char(*t)) {
free(buf);
return NULL;
}
t++;
}
strbuf_append(&buf, &size, &offset, s, t - s);
/* Now possibly handle an escape. */
if (*t == '\\') {
t++;
/* You can only escape a CHAR, octets 0-127. But we disallow 0. */
if (*t <= 0) {
free(buf);
return NULL;
}
strbuf_append(&buf, &size, &offset, t, 1);
t++;
}
s = t;
}
s++;
*quoted_string = buf;
return s;
}
static const char *read_token_or_quoted_string(const char *s, char **token)
{
while (is_space_char(*s))
s++;
if (*s == '"')
return read_quoted_string(s, token);
else
return read_token(s, token);
}
static const char *read_token_list(const char *s, char **tokens[], size_t *n)
{
char *token;
*tokens = NULL;
*n = 0;
for (;;) {
s = read_token(s, &token);
if (s == NULL) {
size_t i;
for (i = 0; i < *n; i++)
free((*tokens)[i]);
free(*tokens);
return NULL;
}
*tokens = (char **) safe_realloc(*tokens, (*n + 1) * sizeof((*tokens)[0]));
(*tokens)[(*n)++] = token;
if (*s != ',')
break;
s++;
}
return s;
}
struct http_header *http_header_remove(struct http_header *header, const char *name)
{
struct http_header *p, *next, **prev;
prev = &header;
for (p = header; p != NULL; p = next) {
next = p->next;
if (field_name_equal(p->name, name)) {
*prev = next;
http_header_node_free(p);
continue;
}
prev = &p->next;
}
return header;
}
/* Removes hop-by-hop headers listed in section 13.5.1 of RFC 2616, and
additionally removes any headers listed in the Connection header as described
in section 14.10. */
int http_header_remove_hop_by_hop(struct http_header **header)
{
static const char *HOP_BY_HOP_HEADERS[] = {
"Connection",
"Keep-Alive",
"Proxy-Authenticate",
"Proxy-Authorization",
"TE",
"Trailers",
"Transfer-Encoding",
"Upgrade",
};
char *connection;
char **connection_tokens;
size_t num_connection_tokens;
unsigned int i;
connection = http_header_get(*header, "Connection");
if (connection != NULL) {
const char *p;
p = read_token_list(connection, &connection_tokens, &num_connection_tokens);
if (p == NULL) {
free(connection);
return 400;
}
if (*p != '\0') {
free(connection);
for (i = 0; i < num_connection_tokens; i++)
free(connection_tokens[i]);
free(connection_tokens);
return 400;
}
free(connection);
} else {
connection_tokens = NULL;
num_connection_tokens = 0;
}
for (i = 0; i < sizeof(HOP_BY_HOP_HEADERS) / sizeof(HOP_BY_HOP_HEADERS[0]); i++)
*header = http_header_remove(*header, HOP_BY_HOP_HEADERS[i]);
for (i = 0; i < num_connection_tokens; i++)
*header = http_header_remove(*header, connection_tokens[i]);
for (i = 0; i < num_connection_tokens; i++)
free(connection_tokens[i]);
free(connection_tokens);
return 0;
}
char *http_header_to_string(const struct http_header *header, size_t *n)
{
const struct http_header *p;
char *buf = NULL;
size_t size = 0, offset = 0;
strbuf_append_str(&buf, &size, &offset, "");
for (p = header; p != NULL; p = p->next)
strbuf_sprintf(&buf, &size, &offset, "%s: %s\r\n", p->name, p->value);
if (n != NULL)
*n = offset;
return buf;
}
void http_request_init(struct http_request *request)
{
request->method = NULL;
uri_init(&request->uri);
request->version = HTTP_UNKNOWN;
request->header = NULL;
request->content_length_set = 0;
request->content_length = 0;
request->bytes_transferred = 0;
}
void http_request_free(struct http_request *request)
{
free(request->method);
uri_free(&request->uri);
http_header_free(request->header);
}
char *http_request_to_string(const struct http_request *request, size_t *n)
{
const char *path;
char *buf = NULL;
size_t size = 0, offset = 0;
/* RFC 2616, section 5.1.2: "the absolute path cannot be empty; if none is
present in the original URI, it MUST be given as "/" (the server
root)." */
path = request->uri.path;
if (path[0] == '\0')
path = "/";
if (request->version == HTTP_09) {
/* HTTP/0.9 doesn't have headers. See
http://www.w3.org/Protocols/HTTP/AsImplemented.html. */
strbuf_sprintf(&buf, &size, &offset, "%s %s\r\n", request->method, path);
} else {
const char *version;
char *header_str;
if (request->version == HTTP_10)
version = " HTTP/1.0";
else
version = " HTTP/1.1";
header_str = http_header_to_string(request->header, NULL);
strbuf_sprintf(&buf, &size, &offset, "%s %s%s\r\n%s\r\n",
request->method, path, version, header_str);
free(header_str);
}
if (n != NULL)
*n = offset;
return buf;
}
void http_response_init(struct http_response *response)
{
response->version = HTTP_UNKNOWN;
response->code = 0;
response->phrase = NULL;
response->header = NULL;
response->content_length_set = 0;
response->content_length = 0;
response->bytes_transferred = 0;
}
void http_response_free(struct http_response *response)
{
free(response->phrase);
http_header_free(response->header);
}
char *http_response_to_string(const struct http_response *response, size_t *n)
{
char *buf = NULL;
size_t size = 0, offset = 0;
if (response->version == HTTP_09) {
/* HTTP/0.9 doesn't have a Status-Line or headers. See
http://www.w3.org/Protocols/HTTP/AsImplemented.html. */
return strdup("");
} else {
const char *version;
char *header_str;
if (response->version == HTTP_10)
version = "HTTP/1.0";
else
version = "HTTP/1.1";
header_str = http_header_to_string(response->header, NULL);
strbuf_sprintf(&buf, &size, &offset, "%s %d %s\r\n%s\r\n",
version, response->code, response->phrase, header_str);
free(header_str);
}
if (n != NULL)
*n = offset;
return buf;
}
int http_read_header(char *buf, int buflen, char **result)
{
char *line = NULL;
char *header;
size_t n = 0;
size_t count;
int blank;
header = NULL;
char *p = buf;
int remaining_len = buflen;
size_t status_len = 0;
http_read_status_line(buf, buflen, NULL, &status_len);
p += status_len;
do {
line = (char *) memchr(p, '\n', remaining_len);
line = line + 1;
if (line == NULL) {
free(header);
if (n >= MAX_HEADER_LENGTH)
/* Request Entity Too Large. */
return 413;
else
return 400;
}
remaining_len = buflen - (line - p);
count = (line - p);
blank = is_crlf(line);
if (n + count >= MAX_HEADER_LENGTH) {
free(header);
/* Request Entity Too Large. */
return 413;
}
header = (char *) safe_realloc(header, n + count + 1);
memcpy(header + n, p, count);
n += count;
p = line;
} while (!blank);
header[n] = '\0';
*result = header;
return 0;
}
static const char *skip_lws(const char *s)
{
for (;;) {
while (is_space_char(*s))
s++;
if (*s == '\n' && is_space_char(*(s + 1)))
s += 1;
else if (*s == '\r' && *(s + 1) == '\n' && is_space_char(*(s + 2)))
s += 2;
else
break;
}
return s;
}
/* See section 4.2 of RFC 2616 for header format. */
int http_parse_header(struct http_header **result, const char *header)
{
const char *p, *q;
size_t value_len, value_offset;
struct http_header *node, **prev;
*result = NULL;
prev = result;
p = header;
while (*p != '\0' && !is_crlf(p)) {
/* Get the field name. */
q = p;
while (*q != '\0' && is_token_char(*q))
q++;
if (*q != ':') {
http_header_free(*result);
return 400;
}
node = (struct http_header *) safe_malloc(sizeof(*node));
node->name = mkstr(p, q);
node->value = NULL;
node->next = NULL;
value_len = 0;
value_offset = 0;
/* Copy the header field value until we hit a CRLF. */
p = q + 1;
p = skip_lws(p);
for (;;) {
q = p;
while (*q != '\0' && !is_space_char(*q) && !is_crlf(q)) {
/* Section 2.2 of RFC 2616 disallows control characters. */
if (iscntrl((int) (unsigned char) *q)) {
http_header_node_free(node);
return 400;
}
q++;
}
strbuf_append(&node->value, &value_len, &value_offset, p, q - p);
p = skip_lws(q);
if (is_crlf(p))
break;
/* Replace LWS with a single space. */
strbuf_append_str(&node->value, &value_len, &value_offset, " ");
}
*prev = node;
prev = &node->next;
p = skip_crlf(p);
}
return 0;
}
static int http_header_get_content_length(const struct http_header *header, int *content_length_set, unsigned long *content_length)
{
char *content_length_s;
char *tail;
int code;
content_length_s = http_header_get_first(header, "Content-Length");
if (content_length_s == NULL) {
*content_length_set = 0;
*content_length = 0;
return 0;
}
code = 0;
errno = 0;
*content_length_set = 1;
*content_length = parse_long(content_length_s, (char **) &tail);
if (errno != 0 || *tail != '\0' || tail == content_length_s)
code = 400;
free(content_length_s);
return code;
}
/* Parse a header and fill in any relevant fields in the request structure. */
int http_request_parse_header(struct http_request *request, const char *header)
{
int code;
code = http_parse_header(&request->header, header);
if (code != 0)
return code;
code = http_header_get_content_length(request->header, &request->content_length_set, &request->content_length);
if (code != 0)
return code;
return 0;
}
/* Parse a header and fill in any relevant fields in the response structure. */
int http_response_parse_header(struct http_response *response, const char *header)
{
int code;
code = http_parse_header(&response->header, header);
if (code != 0)
return code;