-
-
Notifications
You must be signed in to change notification settings - Fork 5
/
httpc.c
1764 lines (1640 loc) · 53.9 KB
/
httpc.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
#define HTTPC_PROGRAM "Embeddable HTTP 1.0/1.1 client"
#define HTTPC_LICENSE "The Unlicense (public domain)"
#define HTTPC_AUTHOR "Richard James Howe"
#define HTTPC_EMAIL "[email protected]"
#define HTTPC_REPO "https://github.com/howerj/httpc"
#ifndef HTTPC_VERSION
#define HTTPC_VERSION "0.0.0" /* defined by build system */
#endif
#include "httpc.h"
#define LOCALELY_API static inline
#define LOCALELY_EXTERN LOCALELY_API
#define LOCALELY_IMPLEMENTATION
#include "localely.h" /* used because isX and toupper are locale dependent and thus suck */
#include <assert.h>
#include <string.h>
#include <stdint.h>
#include <limits.h>
#ifndef HTTPC_STACK_BUFFER_SIZE /* buffers allocated on the stack, responsible for some arbitrary limits as well. */
#define HTTPC_STACK_BUFFER_SIZE (128ul)
#endif
#ifndef HTTPC_TESTS_ON /* Build in tests to the program */
#define HTTPC_TESTS_ON (1u)
#endif
#ifndef HTTPC_GROW /* Allow data structures to grow */
#define HTTPC_GROW (1u)
#endif
#ifndef HTTPC_LOGGING /* 0 == logging disabled, 1 == logging on */
#define HTTPC_LOGGING (1u)
#endif
#ifndef HTTPC_CONNECTION_ATTEMPTS /* default maximum number of connection attempts */
#define HTTPC_CONNECTION_ATTEMPTS (3u)
#endif
#ifndef HTTPC_REDIRECT_MAX /* default maximum number of HTTP redirects */
#define HTTPC_REDIRECT_MAX (3u)
#endif
#ifndef HTTPC_MAX_HEADER /* maximum size for the header; 0 == infinite length allowed */
#define HTTPC_MAX_HEADER (8192ul)
#endif
#ifndef HTTPC_ALLOW_ANY_RESPONSE_STRING /* Allow any response string, e.g. instead of requiring "200 ok", "200 beep boop" would be fine */
#define HTTPC_ALLOW_ANY_RESPONSE_STRING (0)
#endif
#define USED(X) ((void)(X)) /* warning suppression: variable is used conditionally */
#define UNUSED(X) ((void)(X)) /* warning suppression: variable is unused in function */
#define MAX(X, Y) ((X) > (Y) ? (X) : (Y))
#define MIN(X, Y) ((X) < (Y) ? (X) : (Y))
#define BUILD_BUG_ON(condition) ((void)sizeof(char[1 - 2*!!(condition)]))
#define implies(P, Q) assert(!(P) || (Q))
#define NELEMS(X) ((sizeof(X) / sizeof((X)[0])))
typedef struct {
unsigned char stack[HTTPC_STACK_BUFFER_SIZE]; /* small temporary buffer */
unsigned char *buffer; /* either points to buf or is allocated */
size_t allocated, used; /* number of bytes allocates, number of byte actually used */
} httpc_buffer_t; /* growable buffer, also used for memory optimization reasons */
typedef struct {
char *buffer;
size_t length, used;
} httpc_buffer_cb_t; /* used in PUT/POST/GET to memory functions */
typedef struct {
int code;
const char *value;
} httpc_response_string_t;
typedef unsigned long httpc_length_t;
struct httpc {
httpc_options_t *os; /* operating system dependent functions for socket, TLS/SLL and allocation. */
httpc_buffer_t b0, burl; /* buffers for temporary values, heavily reused, be careful! */
httpc_callback snd, /* callback for sending payload, called repeatedly to generate output in chunks */
rcv; /* callback for receiving payload, called piecemeal to on chunks of input */
void *snd_param, /* parameter given to the "snd" callback */
*rcv_param; /* parameter given to the "rcv" callback */
/* These strings point into 'url', which has been modified from the
* original URL to contain a bunch of NUL terminated strings where the
* delimiters were */
char *domain, /* parsed: domain or IPv4/IPv6 */
*userpass, /* parsed: username/password used for basic authentication */
*path, /* parsed: file path */
*url; /* full URL to be parsed */
unsigned short port; /* port to talk on, parsed out at the same time as domain, userpass, path and URL. */
void *socket; /* socket used to talk to the server (might actually be an SSL/TLS handle). */
httpc_length_t position, /* file position */
length, /* length of file, if known */
max; /* maximum read in */
int state, /* HTTPC contains a state-machine, the state of which is encoded here. */
status; /* HTTP return code status */
unsigned long start_ms, /* Start time of operation */
current_ms, /* Current time, used within exponential back-off operation */
end_ms; /* End time of operation */
unsigned retries, /* number of times to connection retried */
redirects; /* number of times to redirected */
unsigned retries_max, /* maximum number of times to retry */
redirects_max; /* maximum number of times to redirect */
unsigned v1, v2; /* HTTP version (1.0 or 1.1) */
unsigned use_ssl :1, /* if set then SSL should be used on the connection */
fatal :1, /* if set then something has gone fatally wrong */
accept_ranges :1, /* if set then the server accepts ranges */
identity :1, /* 1 == identity encoded, 0 == chunked */
redirect :1, /* if set then a redirect is going on */
length_set :1, /* has length been set on a PUT/POST? */
open :1, /* is the file handle open? */
keep_alive :1, /* does the server support keep-alive? */
progress :1; /* are we making progress? */
};
static inline void httpc_reverse_string(char * const r, const size_t length) {
assert(r);
const size_t last = length - 1;
for (size_t i = 0; i < length / 2ul; i++) {
const size_t t = r[i];
r[i] = r[last - i];
r[last - i] = t;
}
}
static unsigned httpc_num_to_str(char b[64 + 1], unsigned long u, const unsigned long base) {
assert(b);
assert(base >= 2 && base <= 36);
unsigned i = 0;
do {
const unsigned long q = u % base;
const unsigned long r = u / base;
b[i++] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"[q];
assert(i < 64u);
u = r;
} while (u);
b[i] = '\0';
httpc_reverse_string(b, i);
return i;
}
static int httpc_kill(httpc_t *h) {
assert(h);
h->fatal = 1;
return HTTPC_ERROR;
}
static int httpc_is_dead(httpc_t *h) {
assert(h);
return h->fatal;
}
static int httpc_is_yield_on(httpc_t *h) {
assert(h);
return !!(h->os->flags & HTTPC_OPT_NON_BLOCKING);
}
static int httpc_is_reuse(httpc_t *h) {
assert(h);
return !!(h->os->flags & HTTPC_OPT_REUSE);
}
#ifdef __GNUC__
static int httpc_log_fmt(httpc_t *h, const char *fmt, ...) __attribute__ ((format (printf, 2, 3)));
static int httpc_log_line(httpc_t *h, const char *type, int die, int ret, const unsigned line, const char *fmt, ...) __attribute__ ((format (printf, 6, 7)));
#endif
static int httpc_log_fmt(httpc_t *h, const char *fmt, ...) {
assert(fmt);
assert(h);
assert(h->os);
httpc_options_t *os = h->os;
assert(os->logger);
va_list ap;
va_start(ap, fmt);
const int r = os->logger(os, os->logfile, fmt, ap);
va_end(ap);
if (r < 0)
(void)httpc_kill(h);
return r;
}
static int httpc_log_line(httpc_t *h, const char *type, int die, int ret, const unsigned line, const char *fmt, ...) {
assert(h);
assert(fmt);
httpc_options_t *os = h->os;
if (os->flags & HTTPC_OPT_LOGGING_ON) {
assert(os->logger);
assert(type);
if (httpc_log_fmt(h, "%s:%u ", type, line) < 0)
return HTTPC_ERROR;
va_list ap;
va_start(ap, fmt);
if (os->logger(os, os->logfile, fmt, ap) < 0)
(void)httpc_kill(h);
va_end(ap);
if (httpc_log_fmt(h, "\n") < 0)
return HTTPC_ERROR;
}
if (die)
return httpc_kill(h);
return httpc_is_dead(h) ? HTTPC_ERROR : ret;
}
#if HTTPC_LOGGING == 0
static inline int httpc_rcode(const int c) { return c; } /* suppresses warnings */
#define debug(H, ...) httpc_rcode(HTTPC_OK)
#define info(H, ...) httpc_rcode(HTTPC_OK)
#define error(H, ...) httpc_rcode(HTTPC_ERROR)
#define fatal(H, ...) httpc_kill((H))
#else
#define debug(H, ...) httpc_log_line((H), "debug", 0, HTTPC_OK, __LINE__, __VA_ARGS__)
#define info(H, ...) httpc_log_line((H), "info", 0, HTTPC_OK, __LINE__, __VA_ARGS__)
#define error(H, ...) httpc_log_line((H), "error", 0, HTTPC_ERROR, __LINE__, __VA_ARGS__)
#define fatal(H, ...) httpc_log_line((H), "fatal", 1, HTTPC_ERROR, __LINE__, __VA_ARGS__)
#endif
static void *httpc_malloc(httpc_t *h, const size_t size) {
assert(h);
assert(h->os->allocator);
if (httpc_is_dead(h))
return NULL;
void *r = h->os->allocator(h->os->arena, NULL, 0, size);
if (!r) {
(void)httpc_kill(h);
(void)debug(h, "malloc %ld failed", (long)size);
return NULL;
}
void *m = memset(r, 0, size);
(void)debug(h, "malloc %p/%ld", m, (long)size);
return m;
}
static void *httpc_realloc(httpc_t *h, void *pointer, const size_t size) {
assert(h);
assert(h->os->allocator);
(void)debug(h, "%s %p/%ld", size > 0 ? "realloc" : "free", pointer, (long)size);
if (httpc_is_dead(h) && size > 0)
return NULL;
void *r = h->os->allocator(h->os->arena, pointer, 0, size);
if (r == NULL && size != 0)
(void)httpc_kill(h);
return r;
}
static int httpc_free(httpc_t *h, void *pointer) {
assert(h);
assert(h->os->allocator);
(void)debug(h, "free %p", pointer);
(void)h->os->allocator(h->os->arena, pointer, 0, 0);
return HTTPC_OK;
}
static int httpc_network_read(httpc_t *h, unsigned char *bytes, size_t *length) {
assert(h);
assert(bytes);
assert(length);
const int r = h->os->read(h->os, h->socket, bytes, length);
if (r < 0 || (r != HTTPC_OK && r != HTTPC_YIELD))
return error(h, "network read error %d", r);
if (r == HTTPC_YIELD)
return fatal(h, httpc_is_yield_on(h) ? "yield not implemented" : "yielding when yield option not set");
return r;
}
static int httpc_network_write(httpc_t *h, const unsigned char *bytes, size_t length) {
assert(h);
assert(bytes);
if (length == 0)
return HTTPC_OK;
size_t l = length;
const int r = h->os->write(h->os, h->socket, bytes, &l);
if (l != length)
return error(h, "network write incomplete");
if (r < 0 || (r != HTTPC_OK && r != HTTPC_YIELD))
return error(h, "network write error %d", r);
if (r == HTTPC_YIELD)
return fatal(h, httpc_is_yield_on(h) ? "yield not implemented" : "yielding when yield option not set");
return r;
}
static int httpc_read_char(httpc_t *h) {
assert(h);
size_t length = 1;
unsigned char x = 0;
if (httpc_network_read(h, &x, &length) < 0)
return -1;
if (length != 1)
return -1;
return x;
}
static int buffer_free(httpc_t *h, httpc_buffer_t *s) {
assert(h);
assert(s);
if (s->buffer != s->stack) {
const int r = httpc_free(h, s->buffer);
s->buffer = NULL; /* prevent double free */
s->allocated = 0;
return r;
}
return HTTPC_OK; /* pointer == buffer, no need to free */
}
static int httpc_buffer(httpc_t *h, httpc_buffer_t *s, size_t needed) { /* dynamically growable buffer */
assert(h);
assert(s);
if (s->buffer == NULL) { /* take care of initialization */
s->buffer = s->stack;
s->used = 0;
s->allocated = sizeof (s->stack);
memset(s->stack, 0, sizeof s->stack);
}
if (needed <= s->allocated) /* we could free here if we only need stack buffer */
return HTTPC_OK;
if (HTTPC_GROW == 0)
return fatal(h, "buffer not allowed to grow");
if (s->buffer == s->stack) {
if (!(s->buffer = httpc_malloc(h, needed)))
return fatal(h, "allocation failed");
s->allocated = needed;
memcpy(s->buffer, s->stack, sizeof s->stack);
return HTTPC_OK;
}
unsigned char *old = s->buffer;
if ((s->buffer = httpc_realloc(h, s->buffer, needed)) == NULL) {
(void)httpc_free(h, old);
return fatal(h, "reallocation failed");
}
s->allocated = needed;
return HTTPC_OK;
}
static int httpc_buffer_add_string(httpc_t *h, httpc_buffer_t *b, const char *s) {
assert(h);
assert(b);
assert(s);
if (httpc_is_dead(h))
return HTTPC_ERROR;
const size_t l = strlen(s);
const size_t newsz = l + b->used + !(b->used);
if (httpc_buffer(h, b, newsz) < 0)
return HTTPC_ERROR;
memcpy(b->buffer + b->used - !!(b->used), s, l);
b->used = newsz;
b->buffer[b->used - 1] = '\0';
return HTTPC_OK;
}
/* Modified from: <https://stackoverflow.com/questions/342409>.
*
* This function should be added to the API, along with many others
* within this library. However it would need reworking slightly,
* perhaps to work on raw buffers only. We would also need to add
* a base-64 decode, as it would be odd to have one function without
* the other. */
static int httpc_buffer_add_base64(httpc_t *h, httpc_buffer_t *out, const unsigned char *in, const size_t input_length) {
assert(h);
assert(in);
assert(out);
/* assert(shake_it_all_about); */
const size_t encoded_length = 4ull * ((input_length + 2ull) / 3ull);
const size_t needs = 1u + encoded_length + out->used;
assert(needs > encoded_length);
assert(encoded_length > input_length);
if (needs < encoded_length)
return -1;
if (httpc_buffer(h, out, needs) < 0)
return -1;
size_t j = out->used - (out->used != 0);
for (size_t i = 0; i < input_length;) {
static const char encoding_table[] = {
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P',
'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f',
'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v',
'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/'
};
const uint32_t octet_a = i < input_length ? (unsigned char)in[i++] : 0;
const uint32_t octet_b = i < input_length ? (unsigned char)in[i++] : 0;
const uint32_t octet_c = i < input_length ? (unsigned char)in[i++] : 0;
const uint32_t triple = (octet_a << 0x10) + (octet_b << 0x08) + octet_c;
assert(j < (out->allocated - 4));
out->buffer[j++] = encoding_table[(triple >> (3 * 6)) & 0x3F];
out->buffer[j++] = encoding_table[(triple >> (2 * 6)) & 0x3F];
out->buffer[j++] = encoding_table[(triple >> (1 * 6)) & 0x3F];
out->buffer[j++] = encoding_table[(triple >> (0 * 6)) & 0x3F];
}
static const int mod_table[] = { 0, 2, 1, };
for (int i = 0; i < mod_table[input_length % 3]; i++)
out->buffer[j - 1u - i] = '=';
assert(j < out->allocated);
out->buffer[j] = '\0';
out->used = j;
return 0;
}
static inline int httpc_character_to_number(int ch) {
ch = C_toupper(ch);
static const char m[] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
for (int d = 0; d < (int)(sizeof (m) - 1); d++)
if (ch == m[d])
return d;
return -1;
}
static int httpc_string_to_number(const char *s, httpc_length_t *out, const size_t max, unsigned long base) {
assert(s);
assert(out);
assert(max < SIZE_MAX);
httpc_length_t result = 0;
int ch = s[0];
*out = 0;
if (!ch)
return -1;
size_t j = 0;
for (j = 0; j < max && (ch = s[j]); j++) {
const int digit = httpc_character_to_number(ch);
if (digit < 0)
return -1;
const httpc_length_t n = (httpc_length_t)digit + (result * (httpc_length_t)base);
if (n < result) /* overflow */
return -1;
result = n;
}
if (ch && j < max)
return -1;
*out = result;
return 0;
}
static int httpc_scan_number(const char *s, httpc_length_t *out, unsigned long base) {
assert(s);
assert(out);
while (C_isspace(*s))
s++;
return httpc_string_to_number(s, out, 64, base);
}
/* URL Format is (roughly):
*
* (http/https '://')? (user-info '@')? host (':' port)? ('/' path ('?' query)* ('#' fragment)?)
*
* The 'user-info' format is:
*
* username ':' password
*
* Must ensure invalid characters are not present in path/domain/parsed-out-contents such
* as spaces.
*
* The 'url' string is modified by putting in NUL terminating
* characters where the separators were.
*
* With a few modifications (such as accepting a struct for the various fields)
* this could be added to the API. */
static int httpc_parse_url(httpc_t *h, const char *url) {
assert(h);
assert(url);
if (httpc_is_dead(h))
return HTTPC_ERROR;
h->url = NULL;
const size_t l = strlen(url);
if (httpc_buffer(h, &h->burl, l + 2) < 0)
return HTTPC_ERROR;
h->url = (char*)h->burl.buffer;
memcpy(h->url, url, l + 1);
h->port = 80;
h->use_ssl = 0;
int ch = 0;
size_t i = 0, j = 0;
char *u = h->url;
for (;(ch = u[i]); i++)
if (!C_isspace(ch))
break;
if (!ch) {
error(h, "invalid URL: %s", url);
goto fail;
}
const char http[] = "http://", https[] = "https://";
if (l > sizeof http && !memcmp(&u[i], http, sizeof(http) - 1ul)) {
i += sizeof(http) - 1ul;
} else if (l > sizeof https && !memcmp(&u[i], https, sizeof(https) - 1ul)) {
h->use_ssl = 1u;
h->port = 443;
i += sizeof(https) - 1ul;
}
char *usr = memchr(&u[i], '@', l - i);
if (usr) {
h->userpass = &u[i];
i = (usr - u) + 1ul;
*usr = '\0';
if (!strchr(h->userpass, ':')) {
error(h, "user-pass contains no ':': %s", h->userpass);
goto fail;
}
}
h->domain = &u[i];
for (j = i;(ch = u[j]);j++)
if (ch == ':' || ch == '/')
break;
if (j == i)
goto fail;
if (ch == '/') {
memmove(&u[j + 1], &u[j], strlen(&u[j]) + 1);
u[j] = '\0';
}
if (!strlen(h->domain))
goto fail;
if (ch == ':') {
u[j] = '\0';
httpc_length_t port = 0;
for (i = j + 1; (ch = u[i]); i++)
if (!C_isdigit(ch))
break;
if (httpc_string_to_number(&u[j + 1], &port, i - (j + 1), 10) < 0) {
error(h, "invalid port number");
goto fail;
}
h->port = port;
j = i - 1;
}
h->path = &u[j + 1];
h->path = h->path[0] ? h->path : "/";
info(h, "domain: %s", h->domain);
info(h, "port: %d", h->port);
info(h, "SSL: %s", h->use_ssl ? "true" : "false");
if (h->userpass)
info(h, "user/pass: %s", h->userpass);
info(h, "path %s", h->path ? h->path : "/");
return HTTPC_OK;
fail:
h->url = NULL;
return HTTPC_ERROR;
}
enum { HTTPC_GET, HTTPC_HEAD, HTTPC_PUT, HTTPC_POST, HTTPC_DELETE, HTTPC_TRACE, HTTPC_OPTIONS, };
static const char *httpc_op_to_str(int op) {
switch (op) {
case HTTPC_GET: return "GET ";
case HTTPC_HEAD: return "HEAD ";
case HTTPC_PUT: return "PUT ";
case HTTPC_POST: return "POST ";
case HTTPC_DELETE: return "DELETE ";
case HTTPC_TRACE: return "TRACE ";
case HTTPC_OPTIONS: return "OPTIONS ";
}
return NULL;
}
/* This allows us to be a bit more liberal in what we accept */
static inline int httpc_case_insensitive_compare(const char *a, const char *b, const size_t length) {
assert(a);
assert(b);
assert(length < SIZE_MAX);
for (size_t i = 0; i < length ; i++) {
const int ach = C_tolower(a[i]);
const int bch = C_tolower(b[i]);
const int diff = ach - bch;
if (!ach || diff)
return diff;
}
return 0;
}
static const char *httpc_case_insensitive_search(const char *haystack, const char *needle) {
assert(haystack);
assert(needle);
const size_t needle_length = strlen(needle);
for (; *haystack; haystack++)
if (0 == httpc_case_insensitive_compare(haystack, needle, needle_length))
return haystack;
return NULL;
}
static int httpc_request_send_header(httpc_t *h, httpc_buffer_t *b0, int op) {
assert(h);
assert(b0);
implies(h->os->argc, h->os->argv);
if (httpc_is_dead(h))
return HTTPC_ERROR;
const char *operation = httpc_op_to_str(op);
if (!operation)
return fatal(h, "unknown operation '%d'", op);
b0->used = 0;
if (httpc_buffer_add_string(h, b0, operation) < 0)
goto fail;
if (httpc_buffer_add_string(h, b0, h->path ? h->path : "/") < 0)
goto fail;
if (h->os->flags & HTTPC_OPT_HTTP_1_0) {
if (httpc_buffer_add_string(h, b0, " HTTP/1.0\r\nHost: ") < 0)
goto fail;
} else {
if (httpc_buffer_add_string(h, b0, " HTTP/1.1\r\nHost: ") < 0)
goto fail;
}
if (httpc_buffer_add_string(h, b0, h->domain) < 0)
goto fail;
if (httpc_buffer_add_string(h, b0, "\r\n") < 0)
goto fail;
if (op == HTTPC_GET && !(h->os->flags & HTTPC_OPT_HTTP_1_0) && h->position && h->accept_ranges) {
char range[64 + 1] = { 0, };
if (httpc_buffer_add_string(h, b0, "Range: bytes=") < 0)
goto fail;
httpc_num_to_str(range, h->position, 10);
if (httpc_buffer_add_string(h, b0, range) < 0)
goto fail;
if (httpc_buffer_add_string(h, b0, "-\r\n") < 0)
goto fail;
}
if (op == HTTPC_PUT || op == HTTPC_POST) {
const char field[] = "Content-Length:";
size_t field_len= sizeof(field) - 1;
for (int i = 0; i < h->os->argc; i++) {
const char *line = h->os->argv[i];
if (httpc_case_insensitive_compare(field, line, field_len) == 0){
if (httpc_scan_number(&line[field_len], &h->length, 10) == 0){
h->length_set = 1;
}
break;
}
}
if (h->length_set == 0) {
if (httpc_buffer_add_string(h, b0, "Transfer-Encoding: chunked\r\n") < 0)
goto fail;
}
}
if (httpc_is_reuse(h)) {
if (httpc_buffer_add_string(h, b0, "Connection: keep-alive\r\n") < 0)
goto fail;
} else {
if (httpc_buffer_add_string(h, b0, "Connection: close\r\n") < 0)
goto fail;
}
if (httpc_buffer_add_string(h, b0, "Accept-Encoding: identity\r\n") < 0)
goto fail;
if (h->userpass) {
const size_t upl = strlen(h->userpass);
if (httpc_buffer_add_string(h, b0, "Authorization: Basic ") < 0)
goto fail;
if (httpc_buffer_add_base64(h, b0, (uint8_t*)h->userpass, upl) < 0) {
error(h, "base64 encoding fail");
goto fail;
}
if (httpc_buffer_add_string(h, b0, "\r\n") < 0)
goto fail;
}
/* N.B. We could split up the writes by instead calling 'httpc_network_write' instead
* of 'httpc_buffer_add_string' if we wanted. It has some advantages. */
assert(b0->used > 0u);
if (httpc_network_write(h, b0->buffer, b0->used - 1u) < 0)
goto fail;
for (int i = 0; i < h->os->argc; i++) {
const char *line = h->os->argv[i];
size_t l = 0;
for (l = 0; line[l]; l++)
if (line[l] == '\r' || line[l] == '\n')
return fatal(h, "invalid custom header field (illegal chars present)");
if (httpc_network_write(h, (unsigned char *)line, l) < 0)
goto fail;
debug(h, "custom header '%s' added", line);
if (httpc_network_write(h, (unsigned char *)"\r\n", 2) < 0)
goto fail;
}
if (httpc_network_write(h, (unsigned char *)"\r\n", 2) < 0)
goto fail;
return info(h, "%s request complete", operation);
fail:
return error(h, "send GET header failed");
}
static int httpc_backoff(httpc_t *h) {
/* N.B. Instead of Xms, we could use the round trip time as estimated by the
* connection time as an initial guess as per RFC 2616 */
if (httpc_is_dead(h))
return HTTPC_ERROR;
const unsigned long exponen = MIN(h->retries, 16u);
const unsigned long backoff = 500ul * (1ul << exponen);
const unsigned long limited = MIN(1000ul * 10ul * 1ul, backoff);
if (httpc_is_yield_on(h)) {
unsigned long now_ms = 0;
if (h->os->time(h->os, &now_ms) < 0)
return fatal(h, "unable to get time");
if ((now_ms - h->current_ms) > limited)
return HTTPC_OK;
return HTTPC_YIELD;
}
info(h, "backing off for %lu ms, retried %u", limited, (h->retries));
return h->os->sleep(h->os, limited);
}
/* N.B. We could add in a callback to handle unknown fields, however we would
* need to add infrastructure so an external user could meaningfully interact
* with the library internals, which would be too invasive. */
static int httpc_parse_response_field(httpc_t *h, char *line, size_t length) {
assert(h);
assert(line);
if (httpc_is_dead(h))
return HTTPC_ERROR;
if (length == 0)
return HTTPC_OK;
line[length - 1] = '\0';
#define X_MACRO_FIELDS \
X("Transfer-Encoding:", FLD_TRANSFER_ENCODING) \
X("Content-Length:", FLD_CONTENT_LENGTH)\
X("Accept-Ranges:", FLD_ACCEPT_RANGES)\
X("Connection:", FLD_CONNECTION)\
X("Location:", FLD_REDIRECT)
enum {
#define X(STR, ENUM) ENUM,
X_MACRO_FIELDS
#undef X
};
static const struct field {
const char *name;
size_t length;
int type;
} fields[] = {
#define X(STR, ENUM) { .name = STR, .length = sizeof (STR) - 1, .type = ENUM },
X_MACRO_FIELDS
#undef X
};
const size_t field_length = sizeof (fields) / sizeof (fields[0]);
for (size_t i = 0; i < field_length; i++) {
const struct field *fld = &fields[i];
if (fld->length > length)
continue;
if (httpc_case_insensitive_compare(fld->name, line, fld->length))
continue;
/* N.B. Using 'httpc_case_insensitive_search' is a little too liberal in our input handling */
switch (fld->type) {
case FLD_ACCEPT_RANGES:
if (httpc_case_insensitive_search(line, "bytes")) {
h->accept_ranges = !(h->os->flags & HTTPC_OPT_HTTP_1_0);
return info(h, "Accept-Ranges: bytes");
}
if (httpc_case_insensitive_search(line, "none")) {
h->accept_ranges = 0;
return info(h, "Accept-Ranges: none");
}
return error(h, "unknown accept ranges field: %s", line);
case FLD_TRANSFER_ENCODING:
if (strchr(line, ','))
return error(h, "Transfer encoding too complex, cannot handle it: %s", line);
if (httpc_case_insensitive_search(line, "identity")) {
h->identity = 1;
h->position = 0;
return info(h, "identity transfer encoding");
}
if (httpc_case_insensitive_search(line, "chunked")) { /* chunky monkey setting */
h->identity = 0;
return info(h, "chunked transfer encoding");
}
return error(h, "cannot handle transfer encoding: %s", line);
case FLD_CONNECTION:
if (httpc_case_insensitive_search(line, "close")) {
h->keep_alive = 0;
return info(h, "connection close mandatory");
}
if (httpc_case_insensitive_search(line, "keep-alive")) {
h->keep_alive = 1;
return info(h, "connection may be kept alive");
}
return error(h, "unknown connection type");
case FLD_CONTENT_LENGTH:
if (httpc_scan_number(&line[fld->length], &h->length, 10) < 0)
return error(h, "invalid content length: %s", line);
h->length_set = 1;
return info(h, "Content Length: %lu", (unsigned long)h->length);
case FLD_REDIRECT:
if (h->os->response >= 300 && h->os->response < 399) {
if (h->redirects++ > h->redirects_max)
return error(h, "redirect count exceed max (%u)", (unsigned)h->redirects_max);
size_t k = 0, j = 0;
for (k = fld->length; C_isspace(line[k]); k++)
;
j = k;
for (k = fld->length; !C_isspace(line[k]) && line[k]; k++)
;
line[k] = '\0';
if (httpc_parse_url(h, &line[j]) < 0)
return fatal(h, "redirect failed");
h->redirect = 1;
return info(h, "redirecting request");
}
return fatal(h, "invalid redirect");
default:
return fatal(h, "invalid state");
}
}
return info(h, "unknown field: %s", line);
}
static int httpc_read_until_line_end(httpc_t *h, httpc_buffer_t *b, size_t *length) {
assert(h);
assert(b);
assert(length);
size_t olength = *length;
*length = 0;
if (olength == 0)
return fatal(h, "expected length > 0");
if (httpc_is_dead(h))
return HTTPC_ERROR;
b->buffer[olength - 1] = '\0';
for (size_t i = 0; i < (olength - 1ul); i++) {
const int ch = httpc_read_char(h);
if (ch < 0) {
assert(i < olength);
b->buffer[i] = '\0';
return error(h, "unexpected EOF");
}
if (ch == '\n' || ch == '\r') { /* accept either "\n" or "\r\n" */
if (ch != '\n' && httpc_read_char(h) != '\n')
return error(h, "Got '\\r' with no '\\n'");
assert(i < olength);
b->buffer[i] = '\0';
*length = i;
return HTTPC_OK;
}
assert(i < olength);
b->buffer[i] = ch;
if ((i + 1ul) >= (olength - 1ul)) {
const size_t newsz = olength * 2ul;
if (newsz < olength) /* overflow */
return HTTPC_ERROR;
if (httpc_buffer(h, b, newsz) < 0)
return HTTPC_ERROR;
olength = newsz;
}
}
return fatal(h, "buffer too small");
}
/* N.B. We should check for end of string here (which can include white-space) */
static int httpc_response_string_matches(const httpc_response_string_t *m, const char *string) {
assert(m);
assert(string);
const size_t elen = strlen(m->value), slen = strlen(string);
if (slen < elen)
return 0;
return 0 == httpc_case_insensitive_compare(m->value, string, slen);
}
static int httpc_parse_response_header_start_line(httpc_t *h, char *line, const size_t length) {
assert(h);
const char v1_0[] = "HTTP/1.0 ", v1_1[] = "HTTP/1.1 ";
size_t i = 0, j = 0;
httpc_options_t *os = h->os;
assert(length >= 1);
if (length < sizeof (v1_0) && length < sizeof (v1_1))
return error(h, "start line too small");
if (!httpc_case_insensitive_compare(line, v1_0, sizeof (v1_0) - 1)) {
h->v1 = 1;
h->v2 = 0;
i += sizeof (v1_0) - 1;
} else if (!httpc_case_insensitive_compare(line, v1_1, sizeof (v1_1) - 1)) {
h->v1 = 1;
h->v2 = 1;
i += sizeof (v1_1) - 1;
} else {
return error(h, "unknown HTTP protocol/version: %s", line);
}
while (C_isspace(line[i]))
i++;
j = i;
while (C_isdigit(line[j]))
j++;
httpc_length_t resp = 0;
if (httpc_string_to_number((const char *)&line[i], &resp, j - i, 10) < 0)
return error(h, "invalid response number: %s", line);
os->response = resp;
while (C_isspace(line[j]))
j++;
if(j >= length)
return error(h, "bounds exceeded");
char *ok = &line[j];
ok[length - 1u] = '\0';
/* For handling redirections: <https://developer.mozilla.org/en-US/docs/Web/HTTP/Redirections> */
if (os->response < 200 || os->response > 399)
return error(h, "invalid response number: %u", os->response);
if (os->response >= 200 && os->response <= 299) {
if (HTTPC_ALLOW_ANY_RESPONSE_STRING)
return HTTPC_OK;
static const httpc_response_string_t resps[] = {
{ 200, "OK", }, /* Default response, always allowed */
{ 201, "Created", },
{ 202, "Accepted", },
{ 204, "No Content", },
{ 206, "Partial Content", },
{ 218, "This is fine", },
};
int found = 0;
for (size_t i = 0; i < NELEMS(resps); i++) {
const httpc_response_string_t *m = &resps[i];
if (httpc_response_string_matches(m, ok) && m->code == os->response) {
found = 1;
break;
}
}
if (!found) {
httpc_response_string_t okay = { os->response, "OK", };
found = httpc_response_string_matches(&okay, ok);
}
if (!found)
return error(h, "unexpected HTTP response: %s", ok);
}
return HTTPC_OK;
}
static int httpc_parse_response_header(httpc_t *h, httpc_buffer_t *b0) {
assert(h);
assert(b0);
if (httpc_is_dead(h))
return HTTPC_ERROR;
size_t length = 0, hlen = 0;
httpc_options_t *os = h->os;
h->v1 = 0;
h->v2 = 0;
os->response = 0;
h->length = 0;
h->identity = 1;
h->length_set = 0;
h->keep_alive = !(os->flags & HTTPC_OPT_HTTP_1_0);
h->accept_ranges = !(os->flags & HTTPC_OPT_HTTP_1_0);
b0->used = 0;
length = b0->allocated;
if (httpc_read_until_line_end(h, b0, &length) < 0)
return error(h, "protocol error (could not read first line)");
hlen += length;
info(h, "HEADER: %s/%lu", b0->buffer, (unsigned long)length);
if (httpc_parse_response_header_start_line(h, (char*)b0->buffer, length) < 0)
return error(h, "start line parse failed");
for (; hlen < HTTPC_MAX_HEADER; hlen += length) {
length = b0->allocated;
if (httpc_read_until_line_end(h, b0, &length) < 0)
return error(h, "invalid header: %s", b0->buffer);
if (length == 0)
break;
if (httpc_parse_response_field(h, (char*)b0->buffer, b0->allocated) < 0)
return error(h, "error parsing response line");
if ((hlen + length) < hlen)
return fatal(h, "overflow in length");
}
return info(h, "header done");
}
static int httpc_execute_rcv_callback(httpc_t *h, const unsigned char *buf, const size_t length) {
assert(h);
assert(buf);
if (h->rcv == NULL) /* null operation */
return HTTPC_OK;
if ((h->position + length) < h->max) /* discard previous data run */
return HTTPC_OK;
const size_t diff = (h->position + length) - h->max;
assert(diff <= length);
const int r = h->rcv(h->rcv_param, (unsigned char*)buf, diff, h->max);
if (r == HTTPC_YIELD)
return fatal(h, "yield not supported here");
if (r < 0)
return fatal(h, "rcv callback failed");
return HTTPC_OK;
}
static int httpc_parse_response_body_identity(httpc_t *h, httpc_buffer_t *b0) {
assert(h);
assert(h->identity);
assert(b0);
if (httpc_is_dead(h))
return HTTPC_ERROR;
b0->used = 0;
for (;;) {
size_t length = b0->allocated;
if (httpc_network_read(h, b0->buffer, &length) < 0)
return error(h, "read error");