/
http.c
2506 lines (2103 loc) · 70.5 KB
/
http.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright(c) 2012 Tim Ruehsen
*
* This file is part of libmget.
*
* Libmget is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Libmget 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 Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with libmget. If not, see <http://www.gnu.org/licenses/>.
*
*
* HTTP routines
*
* Changelog
* 25.04.2012 Tim Ruehsen created
* 26.10.2012 added Cookie support (RFC 6265)
*
* Resources:
* RFC 2616
* RFC 6265
*
*/
#if HAVE_CONFIG_H
# include <config.h>
#endif
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <time.h>
#include <errno.h>
#if WITH_ZLIB
//#include <zlib.h>
#endif
#ifdef WITH_LIBNGHTTP2
#include <nghttp2/nghttp2.h>
#endif
#ifdef __WIN32
# include <winsock2.h>
#else
# ifdef __VMS
# include "vms_ip.h"
# else /* def __VMS */
// # include <netdb.h>
# endif /* def __VMS [else] */
# include <sys/socket.h>
# include <netinet/in.h>
#ifndef __BEOS__
# include <arpa/inet.h>
#endif
#endif
#include <libmget.h>
#include "private.h"
#define HTTP_CTYPE_SEPERATOR (1<<0)
#define _http_isseperator(c) (http_ctype[(unsigned char)(c)]&HTTP_CTYPE_SEPERATOR)
static const unsigned char
http_ctype[256] = {
['('] = HTTP_CTYPE_SEPERATOR,
[')'] = HTTP_CTYPE_SEPERATOR,
['<'] = HTTP_CTYPE_SEPERATOR,
['>'] = HTTP_CTYPE_SEPERATOR,
['@'] = HTTP_CTYPE_SEPERATOR,
[','] = HTTP_CTYPE_SEPERATOR,
[';'] = HTTP_CTYPE_SEPERATOR,
[':'] = HTTP_CTYPE_SEPERATOR,
['\\'] = HTTP_CTYPE_SEPERATOR,
['\"'] = HTTP_CTYPE_SEPERATOR,
['/'] = HTTP_CTYPE_SEPERATOR,
['['] = HTTP_CTYPE_SEPERATOR,
[']'] = HTTP_CTYPE_SEPERATOR,
['?'] = HTTP_CTYPE_SEPERATOR,
['='] = HTTP_CTYPE_SEPERATOR,
['{'] = HTTP_CTYPE_SEPERATOR,
['}'] = HTTP_CTYPE_SEPERATOR,
[' '] = HTTP_CTYPE_SEPERATOR,
['\t'] = HTTP_CTYPE_SEPERATOR
};
static mget_vector_t
*http_proxies,
*https_proxies;
int mget_http_isseperator(char c)
{
// return strchr("()<>@,;:\\\"/[]?={} \t", c) != NULL;
return _http_isseperator(c);
}
// TEXT = <any OCTET except CTLs, but including LWS>
//int http_istext(char c)
//{
// return (c>=32 && c<=126) || c=='\r' || c=='\n' || c=='\t';
//}
// token = 1*<any CHAR except CTLs or separators>
int mget_http_istoken(char c)
{
return c > 32 && c <= 126 && !_http_isseperator(c);
}
const char *mget_http_parse_token(const char *s, const char **token)
{
const char *p;
for (p = s; mget_http_istoken(*s); s++);
*token = strndup(p, s - p);
return s;
}
// quoted-string = ( <"> *(qdtext | quoted-pair ) <"> )
// qdtext = <any TEXT except <">>
// quoted-pair = "\" CHAR
// TEXT = <any OCTET except CTLs, but including LWS>
// CTL = <any US-ASCII control character (octets 0 - 31) and DEL (127)>
// LWS = [CRLF] 1*( SP | HT )
const char *mget_http_parse_quoted_string(const char *s, const char **qstring)
{
if (*s == '\"') {
const char *p = ++s;
// relaxed scanning
while (*s) {
if (*s == '\"') break;
else if (*s == '\\' && s[1]) {
s += 2;
} else
s++;
}
*qstring = strndup(p, s - p);
if (*s == '\"') s++;
} else
*qstring = NULL;
return s;
}
// generic-param = token [ EQUAL gen-value ]
// gen-value = token / host / quoted-string
const char *mget_http_parse_param(const char *s, const char **param, const char **value)
{
const char *p;
*param = *value = NULL;
while (isblank(*s)) s++;
if (*s == ';') {
s++;
while (isblank(*s)) s++;
}
if (!*s) return s;
for (p = s; mget_http_istoken(*s); s++);
*param = strndup(p, s - p);
while (isblank(*s)) s++;
if (*s && *s++ == '=') {
while (isblank(*s)) s++;
if (*s == '\"') {
s = mget_http_parse_quoted_string(s, value);
} else {
s = mget_http_parse_token(s, value);
}
}
return s;
}
// message-header = field-name ":" [ field-value ]
// field-name = token
// field-value = *( field-content | LWS )
// field-content = <the OCTETs making up the field-value
// and consisting of either *TEXT or combinations
// of token, separators, and quoted-string>
const char *mget_http_parse_name(const char *s, const char **name)
{
while (isblank(*s)) s++;
s = mget_http_parse_token(s, name);
while (*s && *s != ':') s++;
return *s == ':' ? s + 1 : s;
}
const char *mget_parse_name_fixed(const char *s, const char **name, size_t *namelen)
{
while (isblank(*s)) s++;
*name = s;
while (mget_http_istoken(*s))
s++;
*namelen = s - *name;
while (*s && *s != ':') s++;
return *s == ':' ? s + 1 : s;
}
static int G_GNUC_MGET_NONNULL_ALL compare_param(mget_http_header_param_t *p1, mget_http_header_param_t *p2)
{
return mget_strcasecmp_ascii(p1->name, p2->name);
}
void mget_http_add_param(mget_vector_t **params, mget_http_header_param_t *param)
{
if (!*params) *params = mget_vector_create(4, 4, (int(*)(const void *, const void *))compare_param);
mget_vector_add(*params, param, sizeof(*param));
}
/*
Link = "Link" ":" #link-value
link-value = "<" URI-Reference ">" *( ";" link-param )
link-param = ( ( "rel" "=" relation-types )
| ( "anchor" "=" <"> URI-Reference <"> )
| ( "rev" "=" relation-types )
| ( "hreflang" "=" Language-Tag )
| ( "media" "=" ( MediaDesc | ( <"> MediaDesc <"> ) ) )
| ( "title" "=" quoted-string )
| ( "title*" "=" ext-value )
| ( "type" "=" ( media-type | quoted-mt ) )
| ( link-extension ) )
link-extension = ( parmname [ "=" ( ptoken | quoted-string ) ] )
| ( ext-name-star "=" ext-value )
ext-name-star = parmname "*" ; reserved for RFC2231-profiled
; extensions. Whitespace NOT
; allowed in between.
ptoken = 1*ptokenchar
ptokenchar = "!" | "#" | "$" | "%" | "&" | "'" | "("
| ")" | "*" | "+" | "-" | "." | "/" | DIGIT
| ":" | "<" | "=" | ">" | "?" | "@" | ALPHA
| "[" | "]" | "^" | "_" | "`" | "{" | "|"
| "}" | "~"
media-type = type-name "/" subtype-name
quoted-mt = <"> media-type <">
relation-types = relation-type
| <"> relation-type *( 1*SP relation-type ) <">
relation-type = reg-rel-type | ext-rel-type
reg-rel-type = LOALPHA *( LOALPHA | DIGIT | "." | "-" )
ext-rel-type = URI
*/
const char *mget_http_parse_link(const char *s, mget_http_link_t *link)
{
memset(link, 0, sizeof(*link));
while (isblank(*s)) s++;
if (*s == '<') {
// URI reference as of RFC 3987 (if relative, resolve as of RFC 3986)
const char *p = s + 1;
if ((s = strchr(p, '>')) != NULL) {
const char *name = NULL, *value = NULL;
link->uri = strndup(p, s - p);
s++;
while (isblank(*s)) s++;
while (*s == ';') {
s = mget_http_parse_param(s, &name, &value);
if (name && value) {
if (!mget_strcasecmp_ascii(name, "rel")) {
if (!mget_strcasecmp_ascii(value, "describedby"))
link->rel = link_rel_describedby;
else if (!mget_strcasecmp_ascii(value, "duplicate"))
link->rel = link_rel_duplicate;
} else if (!mget_strcasecmp_ascii(name, "pri")) {
link->pri = atoi(value);
} else if (!mget_strcasecmp_ascii(name, "type")) {
link->type = value;
value = NULL;
}
// http_add_param(&link->params,¶m);
while (isblank(*s)) s++;
}
xfree(name);
xfree(value);
}
// if (!msg->contacts) msg->contacts=vec_create(1,1,NULL);
// vec_add(msg->contacts,&contact,sizeof(contact));
while (*s && !isblank(*s)) s++;
}
}
return s;
}
// from RFC 3230:
// Digest = "Digest" ":" #(instance-digest)
// instance-digest = digest-algorithm "=" <encoded digest output>
// digest-algorithm = token
const char *mget_http_parse_digest(const char *s, mget_http_digest_t *digest)
{
const char *p;
memset(digest, 0, sizeof(*digest));
while (isblank(*s)) s++;
s = mget_http_parse_token(s, &digest->algorithm);
while (isblank(*s)) s++;
if (*s == '=') {
s++;
while (isblank(*s)) s++;
if (*s == '\"') {
s = mget_http_parse_quoted_string(s, &digest->encoded_digest);
} else {
for (p = s; *s && !isblank(*s) && *s != ',' && *s != ';'; s++);
digest->encoded_digest = strndup(p, s - p);
}
}
while (*s && !isblank(*s)) s++;
return s;
}
// RFC 2617:
// challenge = auth-scheme 1*SP 1#auth-param
// auth-scheme = token
// auth-param = token "=" ( token | quoted-string )
const char *mget_http_parse_challenge(const char *s, mget_http_challenge_t *challenge)
{
const char *old;
memset(challenge, 0, sizeof(*challenge));
while (isblank(*s)) s++;
s = mget_http_parse_token(s, &challenge->auth_scheme);
if (*s == ' ')
s++; // Auth scheme must have a space at the end of the token
else {
// parse/syntax error
xfree(challenge->auth_scheme);
return s;
}
mget_http_header_param_t param;
do {
old = s;
s = mget_http_parse_param(s, ¶m.name, ¶m.value);
if (param.name) {
if (*param.name && !param.value) {
xfree(param.name);
return old; // a new scheme detected
}
if (!param.value) {
xfree(param.name);
continue;
}
if (!challenge->params)
challenge->params = mget_stringmap_create_nocase(8);
mget_stringmap_put_noalloc(challenge->params, param.name, param.value);
}
while (isblank(*s)) s++;
if (*s != ',') break;
else if (*s) s++;
} while (*s);
return s;
}
const char *mget_http_parse_challenges(const char *s, mget_vector_t *challenges)
{
mget_http_challenge_t challenge;
while (*s) {
s = mget_http_parse_challenge(s, &challenge);
if (challenge.auth_scheme) {
mget_vector_add(challenges, &challenge, sizeof(challenge));
}
}
return s;
}
const char *mget_http_parse_location(const char *s, const char **location)
{
const char *p;
while (isblank(*s)) s++;
for (p = s; *s && !isblank(*s); s++);
*location = strndup(p, s - p);
return s;
}
// Transfer-Encoding = "Transfer-Encoding" ":" 1#transfer-coding
// transfer-coding = "chunked" | transfer-extension
// transfer-extension = token *( ";" parameter )
// parameter = attribute "=" value
// attribute = token
// value = token | quoted-string
const char *mget_http_parse_transfer_encoding(const char *s, char *transfer_encoding)
{
while (isblank(*s)) s++;
if (!mget_strcasecmp_ascii(s, "identity"))
*transfer_encoding = transfer_encoding_identity;
else
*transfer_encoding = transfer_encoding_chunked;
while (mget_http_istoken(*s)) s++;
return s;
}
// Content-Type = "Content-Type" ":" media-type
// media-type = type "/" subtype *( ";" parameter )
// type = token
// subtype = token
// example: Content-Type: text/html; charset=ISO-8859-4
const char *mget_http_parse_content_type(const char *s, const char **content_type, const char **charset)
{
mget_http_header_param_t param;
const char *p;
while (isblank(*s)) s++;
for (p = s; *s && (mget_http_istoken(*s) || *s == '/'); s++);
if (content_type)
*content_type = strndup(p, s - p);
if (charset) {
*charset = NULL;
while (*s) {
s=mget_http_parse_param(s, ¶m.name, ¶m.value);
if (!mget_strcasecmp_ascii("charset", param.name)) {
xfree(param.name);
*charset = param.value;
break;
}
xfree(param.name);
xfree(param.value);
}
}
return s;
}
// RFC 2183
//
// disposition := "Content-Disposition" ":" disposition-type *(";" disposition-parm)
// disposition-type := "inline" / "attachment" / extension-token ; values are not case-sensitive
// disposition-parm := filename-parm / creation-date-parm / modification-date-parm
// / read-date-parm / size-parm / parameter
// filename-parm := "filename" "=" value
// creation-date-parm := "creation-date" "=" quoted-date-time
// modification-date-parm := "modification-date" "=" quoted-date-time
// read-date-parm := "read-date" "=" quoted-date-time
// size-parm := "size" "=" 1*DIGIT
// quoted-date-time := quoted-string
// ; contents MUST be an RFC 822 `date-time'
// ; numeric timezones (+HHMM or -HHMM) MUST be used
const char *mget_http_parse_content_disposition(const char *s, const char **filename)
{
mget_http_header_param_t param;
char *p;
if (filename) {
*filename = NULL;
while (*s) {
s = mget_http_parse_param(s, ¶m.name, ¶m.value);
if (param.value && !mget_strcasecmp_ascii("filename", param.name)) {
// just take the last path part as filename
if (!*filename) {
if ((p = strpbrk(param.value,"/\\"))) {
p = strdup(p + 1);
} else {
p = (char *) param.value;
param.value = NULL;
}
mget_percent_unescape(p);
if (!mget_str_is_valid_utf8(p)) {
// if it is not UTF-8, assume ISO-8859-1
// see http://stackoverflow.com/questions/93551/how-to-encode-the-filename-parameter-of-content-disposition-header-in-http
*filename = mget_str_to_utf8(p, "iso-8859-1");
xfree(p);
} else {
*filename = p;
p = NULL;
}
}
} else if (param.value && !mget_strcasecmp_ascii("filename*", param.name)) {
// RFC5987
// ext-value = charset "'" [ language ] "'" value-chars
// ; like RFC 2231's <extended-initial-value>
// ; (see [RFC2231], Section 7)
// charset = "UTF-8" / "ISO-8859-1" / mime-charset
// mime-charset = 1*mime-charsetc
// mime-charsetc = ALPHA / DIGIT
// / "!" / "#" / "$" / "%" / "&"
// / "+" / "-" / "^" / "_" / "`"
// / "{" / "}" / "~"
// ; as <mime-charset> in Section 2.3 of [RFC2978]
// ; except that the single quote is not included
// ; SHOULD be registered in the IANA charset registry
// language = <Language-Tag, defined in [RFC5646], Section 2.1>
// value-chars = *( pct-encoded / attr-char )
// pct-encoded = "%" HEXDIG HEXDIG
// ; see [RFC3986], Section 2.1
// attr-char = ALPHA / DIGIT
// / "!" / "#" / "$" / "&" / "+" / "-" / "."
// / "^" / "_" / "`" / "|" / "~"
// ; token except ( "*" / "'" / "%" )
if ((p = strchr(param.value, '\''))) {
const char *charset = param.value;
const char *language = p + 1;
*p = 0;
if ((p = strchr(language, '\''))) {
*p++ = 0;
if (*p) {
mget_percent_unescape(p);
if (mget_str_needs_encoding(p))
*filename = mget_str_to_utf8(p, charset);
else
*filename = strdup(p);
// just take the last path part as filename
if ((p = strpbrk(*filename, "/\\"))) {
p = strdup(p + 1);
xfree(*filename);
*filename = p;
}
xfree(param.name);
xfree(param.value);
break; // stop looping, we found the final filename
}
}
}
}
xfree(param.name);
xfree(param.value);
}
}
return s;
}
// RFC 6797
//
// Strict-Transport-Security = "Strict-Transport-Security" ":" [ directive ] *( ";" [ directive ] )
// directive = directive-name [ "=" directive-value ]
// directive-name = token
// directive-value = token | quoted-string
const char *mget_http_parse_strict_transport_security(const char *s, time_t *maxage, char *include_subdomains)
{
mget_http_header_param_t param;
*maxage = 0;
*include_subdomains = 0;
while (*s) {
s = mget_http_parse_param(s, ¶m.name, ¶m.value);
if (param.value) {
if (!mget_strcasecmp_ascii(param.name, "max-age")) {
long offset = atol(param.value);
if (offset > 0)
*maxage = time(NULL) + offset;
else
*maxage = 0; // keep 0 as a special value: remove entry from HSTS database
}
} else {
if (!mget_strcasecmp_ascii(param.name, "includeSubDomains")) {
*include_subdomains = 1;
}
}
xfree(param.name);
xfree(param.value);
}
return s;
}
// Content-Encoding = "Content-Encoding" ":" 1#content-coding
const char *mget_http_parse_content_encoding(const char *s, char *content_encoding)
{
while (isblank(*s)) s++;
if (!mget_strcasecmp_ascii(s, "gzip") || !mget_strcasecmp_ascii(s, "x-gzip"))
*content_encoding = mget_content_encoding_gzip;
else if (!mget_strcasecmp_ascii(s, "deflate"))
*content_encoding = mget_content_encoding_deflate;
else if (!mget_strcasecmp_ascii(s, "bzip2"))
*content_encoding = mget_content_encoding_bzip2;
else if (!mget_strcasecmp_ascii(s, "xz") || !mget_strcasecmp_ascii(s, "lzma") || !mget_strcasecmp_ascii(s, "x-lzma"))
// 'xz' is the tag currently understood by Firefox (2.1.2014)
// 'lzma' / 'x-lzma' are the tags currently understood by ELinks
*content_encoding = mget_content_encoding_lzma;
else
*content_encoding = mget_content_encoding_identity;
while (mget_http_istoken(*s)) s++;
return s;
}
const char *mget_http_parse_connection(const char *s, char *keep_alive)
{
while (isblank(*s)) s++;
if (!mget_strcasecmp_ascii(s, "keep-alive"))
*keep_alive = 1;
else
*keep_alive = 0;
while (mget_http_istoken(*s)) s++;
return s;
}
const char *mget_http_parse_etag(const char *s, const char **etag)
{
const char *p;
while (isblank(*s)) s++;
for (p = s; *s && !isblank(*s); s++);
*etag = strndup(p, s - p);
return s;
}
/*
// returns GMT/UTC time as an integer of format YYYYMMDDHHMMSS
// this makes us independant from size of time_t - work around possible year 2038 problems
static long long NONNULL_ALL parse_rfc1123_date(const char *s)
{
// we simply can't use strptime() since it requires us to setlocale()
// which is not thread-safe !!!
static const char *mnames[12] = {
"Jan", "Feb", "Mar","Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
};
static int days_per_month[12] = {
31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31
};
int day, mon = 0, year, hour, min, sec, leap, it;
char mname[4] = "";
if (sscanf(s, " %*[a-zA-Z], %02d %3s %4d %2d:%2d:%2d", &day, mname, &year, &hour, &min, &sec) >= 6) {
// RFC 822 / 1123: Wed, 09 Jun 2021 10:18:14 GMT
}
else if (sscanf(s, " %*[a-zA-Z], %2d-%3s-%4d %2d:%2d:%2d", &day, mname, &year, &hour, &min, &sec) >= 6) {
// RFC 850 / 1036 or Netscape: Wednesday, 09-Jun-21 10:18:14 or Wed, 09-Jun-2021 10:18:14
}
else if (sscanf(s, " %*[a-zA-Z], %3s %2d %2d:%2d:%2d %4d", mname, &day, &hour, &min, &sec, &year) >= 6) {
// ANSI C's asctime(): Wed Jun 09 10:18:14 2021
} else {
err_printf(_("Failed to parse date '%s'\n"), s);
return 0; // return as session cookie
}
if (*mname) {
for (it = 0; it < countof(mnames); it++) {
if (!mget_strcasecmp_ascii(mname, mnames[it])) {
mon = it + 1;
break;
}
}
}
if (year < 70 && year >= 0) year += 2000;
else if (year >= 70 && year <= 99) year += 1900;
if (mon == 2 && year % 4 == 0 && (year % 100 != 0 || year % 400 == 0))
leap = 1;
else
leap = 0;
// we don't handle leap seconds
if (year < 1601 || mon < 1 || mon > 12 || day < 1 || (day > days_per_month[mon - 1] + leap) ||
hour < 0 || hour > 23 || min < 0 || min > 60 || sec < 0 || sec > 60)
{
err_printf(_("Failed to parse date '%s'\n"), s);
return 0; // return as session cookie
}
return(((((long long)year*100 + mon)*100 + day)*100 + hour)*100 + min)*100 + sec;
}
*/
// copied this routine from
// http://ftp.netbsd.org/pub/pkgsrc/current/pkgsrc/pkgtools/libnbcompat/files/timegm.c
static int leap_days(int y1, int y2)
{
y1--;
y2--;
return (y2/4 - y1/4) - (y2/100 - y1/100) + (y2/400 - y1/400);
}
/*
RFC 2616, 3.3.1 Full Date
HTTP-date = rfc1123-date | rfc850-date | asctime-date
rfc1123-date = wkday "," SP date1 SP time SP "GMT"
rfc850-date = weekday "," SP date2 SP time SP "GMT"
asctime-date = wkday SP date3 SP time SP 4DIGIT
date1 = 2DIGIT SP month SP 4DIGIT
; day month year (e.g., 02 Jun 1982)
date2 = 2DIGIT "-" month "-" 2DIGIT
; day-month-year (e.g., 02-Jun-82)
date3 = month SP ( 2DIGIT | ( SP 1DIGIT ))
; month day (e.g., Jun 2)
time = 2DIGIT ":" 2DIGIT ":" 2DIGIT
; 00:00:00 - 23:59:59
wkday = "Mon" | "Tue" | "Wed"
| "Thu" | "Fri" | "Sat" | "Sun"
weekday = "Monday" | "Tuesday" | "Wednesday"
| "Thursday" | "Friday" | "Saturday" | "Sunday"
month = "Jan" | "Feb" | "Mar" | "Apr"
| "May" | "Jun" | "Jul" | "Aug"
| "Sep" | "Oct" | "Nov" | "Dec"
*/
time_t mget_http_parse_full_date(const char *s)
{
// we simply can't use strptime() since it requires us to setlocale()
// which is not thread-safe !!!
static const char *mnames[12] = {
"Jan", "Feb", "Mar","Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
};
static int days_per_month[12] = {
31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31
};
// cumulated number of days until beginning of month for non-leap years
static const int sum_of_days[12] = {
0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334
};
int day, mon = 0, year, hour, min, sec, leap_month, leap_year, days;
char mname[4] = "";
if (sscanf(s, " %*[a-zA-Z], %02d %3s %4d %2d:%2d:%2d", &day, mname, &year, &hour, &min, &sec) >= 6) {
// RFC 822 / 1123: Wed, 09 Jun 2021 10:18:14 GMT
}
else if (sscanf(s, " %*[a-zA-Z], %2d-%3s-%4d %2d:%2d:%2d", &day, mname, &year, &hour, &min, &sec) >= 6) {
// RFC 850 / 1036 or Netscape: Wednesday, 09-Jun-21 10:18:14 or Wed, 09-Jun-2021 10:18:14
}
else if (sscanf(s, " %*[a-zA-Z] %3s %2d %2d:%2d:%2d %4d", mname, &day, &hour, &min, &sec, &year) >= 6) {
// ANSI C's asctime(): Wed Jun 09 10:18:14 2021
} else {
error_printf(_("Failed to parse date '%s'\n"), s);
return 0; // return as session cookie
}
if (*mname) {
unsigned it;
for (it = 0; it < countof(mnames); it++) {
if (!mget_strcasecmp_ascii(mname, mnames[it])) {
mon = it + 1;
break;
}
}
}
if (year < 70 && year >= 0) year += 2000;
else if (year >= 70 && year <= 99) year += 1900;
if (year < 1970) year = 1970;
// we don't handle leap seconds
leap_year = year % 4 == 0 && (year % 100 != 0 || year % 400 == 0);
leap_month = (mon == 2 && leap_year);
if (mon < 1 || mon > 12 || day < 1 || (day > days_per_month[mon - 1] + leap_month) ||
hour < 0 || hour > 23 || min < 0 || min > 60 || sec < 0 || sec > 60)
{
error_printf(_("Failed to parse date '%s'\n"), s);
return 0; // return as session cookie
}
// calculate time_t from GMT/UTC time values
days = 365 * (year - 1970) + leap_days(1970, year);
days += sum_of_days[mon - 1] + (mon > 2 && leap_year);
days += day - 1;
return (((time_t)days * 24 + hour) * 60 + min) * 60 + sec;
}
char *mget_http_print_date(time_t t, char *buf, size_t bufsize)
{
static const char *dnames[7] = {
"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"
};
static const char *mnames[12] = {
"Jan", "Feb", "Mar","Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
};
struct tm tm;
if (!bufsize)
return buf;
if (gmtime_r(&t, &tm)) {
snprintf(buf, bufsize, "%s, %02d %s %d %02d:%02d:%02d GMT",
dnames[tm.tm_wday],tm.tm_mday,mnames[tm.tm_mon],tm.tm_year+1900,
tm.tm_hour, tm.tm_min, tm.tm_sec);
} else
*buf = 0;
return buf;
}
// adjust time (t) by number of seconds (n)
/*
static long long adjust_time(long long t, int n)
{
static int days_per_month[12] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
int day, mon, year, hour, min, sec, leap;
sec = t % 100;
min = (t /= 100) % 100;
hour = (t /= 100) % 100;
day = (t /= 100) % 100;
mon = (t /= 100) % 100;
year = t / 100;
sec += n;
if (n >= 0) {
if (sec >= 60) {
min += sec / 60;
sec %= 60;
}
if (min >= 60) {
hour += min / 60;
min %= 60;
}
if (hour >= 24) {
day += hour / 24;
hour %= 24;
}
while (1) {
if (mon == 2 && year % 4 == 0 && (year % 100 != 0 || year % 400 == 0))
leap = 1;
else
leap = 0;
if (day > days_per_month[mon - 1] + leap) {
day -= (days_per_month[mon - 1] + leap);
mon++;
if (mon > 12) {
mon = 1;
year++;
}
} else break;
}
} else { // n<0
if (sec < 0) {
min += (sec - 59) / 60;
sec = 59 + (sec + 1) % 60;
}
if (min < 0) {
hour += (min - 59) / 60;
min = 59 + (min + 1) % 60;
}
if (hour < 0) {
day += (hour - 23) / 24;
hour = 23 + (hour + 1) % 24;
}
for (;;) {
if (day <= 0) {
if (--mon < 1) {
mon = 12;
year--;
}
if (mon == 2 && year % 4 == 0 && (year % 100 != 0 || year % 400 == 0))
leap = 1;
else
leap = 0;
day += (days_per_month[mon - 1] + leap);
} else break;
}
}
return (((((long long)year*100 + mon)*100 + day)*100 + hour)*100 + min)*100 + sec;
}
// return current GMT/UTC
static long long get_current_time(void)
{
time_t t = time(NULL);
struct tm tm;
gmtime_r(&t, &tm);
return (((((long long)(tm.tm_year + 1900)*100 + tm.tm_mon + 1)*100 + tm.tm_mday)*100 + tm.tm_hour)*100 + tm.tm_min)*100 + tm.tm_sec;
}
*/
/*
RFC 6265
set-cookie-header = "Set-Cookie:" SP set-cookie-string
set-cookie-string = cookie-pair *( ";" SP cookie-av )
cookie-pair = cookie-name "=" cookie-value
cookie-name = token
cookie-value = *cookie-octet / ( DQUOTE *cookie-octet DQUOTE )
cookie-octet = %x21 / %x23-2B / %x2D-3A / %x3C-5B / %x5D-7E
; US-ASCII characters excluding CTLs,
; whitespace DQUOTE, comma, semicolon,
; and backslash
token = <token, defined in [RFC2616], Section 2.2>
cookie-av = expires-av / max-age-av / domain-av /
path-av / secure-av / httponly-av /
extension-av
expires-av = "Expires=" sane-cookie-date
sane-cookie-date = <rfc1123-date, defined in [RFC2616], Section 3.3.1>
max-age-av = "Max-Age=" non-zero-digit *DIGIT
; In practice, both expires-av and max-age-av
; are limited to dates representable by the
; user agent.
non-zero-digit = %x31-39
; digits 1 through 9
domain-av = "Domain=" domain-value
domain-value = <subdomain>
; defined in [RFC1034], Section 3.5, as
; enhanced by [RFC1123], Section 2.1
path-av = "Path=" path-value
path-value = <any CHAR except CTLs or ";">
secure-av = "Secure"
httponly-av = "HttpOnly"
extension-av = <any CHAR except CTLs or ";">
*/
const char *mget_http_parse_setcookie(const char *s, mget_cookie_t *cookie)
{
const char *name, *p;
int allocated_cookie = (cookie == NULL);
cookie = mget_cookie_init(cookie);
while (isspace(*s)) s++;
s = mget_http_parse_token(s, &cookie->name);
while (isspace(*s)) s++;
if (cookie->name && *cookie->name && *s == '=') {
// *cookie-octet / ( DQUOTE *cookie-octet DQUOTE )
for (s++; isspace(*s);) s++;
if (*s == '\"')
s++;