-
Notifications
You must be signed in to change notification settings - Fork 6
/
431 http handle.h
3057 lines (2781 loc) · 117 KB
/
431 http handle.h
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
/* ************************************************************************* */
#if !defined(FIO_INCLUDE_FILE) /* Dev test - ignore line */
#define FIO___DEV___ /* Development inclusion - ignore line */
#define FIO_HTTP_HANDLE /* Development inclusion - ignore line */
#define FIO_STR /* Development inclusion - ignore line */
#include "./include.h" /* Development inclusion - ignore line */
#endif /* Development inclusion - ignore line */
/* *****************************************************************************
An HTTP connection Handle helper
See also:
https://www.rfc-editor.org/rfc/rfc9110.html
Copyright and License: see header file (000 copyright.h) or top of file
***************************************************************************** */
#if defined(FIO_HTTP_HANDLE) && !defined(H___FIO_HTTP_HANDLE___H) && \
!defined(FIO___RECURSIVE_INCLUDE)
#define H___FIO_HTTP_HANDLE___H
/* *****************************************************************************
HTTP Handle Settings
***************************************************************************** */
#ifndef FIO_HTTP_EXACT_LOGGING
/**
* By default, facil.io logs the HTTP request cycle using a fuzzy starting and
* ending point for the time stamp.
*
* The fuzzy timestamp includes delays that aren't related to the HTTP request
* and may ignore time passed due to timestamp caching.
*
* On the other hand, `FIO_HTTP_EXACT_LOGGING` collects exact time stamps to
* measure the time it took to process the HTTP request (excluding time spent
* reading / writing the data from the network).
*
* Due to the preference to err on the side of higher performance, fuzzy
* time-stamping is the default.
*/
#define FIO_HTTP_EXACT_LOGGING 0
#ifndef H___FIO_SERVER___H
#undef FIO_HTTP_EXACT_LOGGING
#define FIO_HTTP_EXACT_LOGGING 1
#endif
#endif
#ifndef FIO_HTTP_BODY_RAM_LIMIT
/**
* The HTTP handle automatically switches between RAM storage and file storage
* once the HTTP body (payload) reaches a certain size. This control this point
* of transition
*/
#define FIO_HTTP_BODY_RAM_LIMIT (1 << 17)
#endif
#ifndef FIO_HTTP_CACHE_LIMIT
/** Each of the HTTP String Caches will be limited to this String count. */
#define FIO_HTTP_CACHE_LIMIT 0 /* ((1UL << 6) + (1UL << 5)) */
#endif
#ifndef FIO_HTTP_CACHE_STR_MAX_LEN
/** The HTTP handle will avoid caching strings longer than this value. */
#define FIO_HTTP_CACHE_STR_MAX_LEN (1 << 12)
#endif
#ifndef FIO_HTTP_CACHE_USES_MUTEX
/** The HTTP cache will use a mutex to allow headers to be set concurrently. */
#define FIO_HTTP_CACHE_USES_MUTEX 1
#endif
#ifndef FIO_HTTP_CACHE_STATIC
/** Adds a static cache for common HTTP header names. */
#define FIO_HTTP_CACHE_STATIC 1
#endif
#ifndef FIO_HTTP_DEFAULT_INDEX_FILENAME
/** The default file name when a static file response points to a folder. */
#define FIO_HTTP_DEFAULT_INDEX_FILENAME "index.html"
#endif
#ifndef FIO_HTTP_STATIC_FILE_COMPLETION
#define FIO_HTTP_STATIC_FILE_COMPLETION 1
#endif
/* *****************************************************************************
HTTP Handle Type
***************************************************************************** */
/**
* The HTTP Handle type.
*
* Note that the type is NOT designed to be thread-safe.
*/
typedef struct fio_http_s fio_http_s;
/**
* The HTTP Controller points to all the callbacks required by the HTTP Handler.
*
* This allows the HTTP Handler to be somewhat protocol agnostic.
*
* Note: if the controller callbacks aren't thread-safe, than the `http_write`
* function MUST NOT be called from any thread except the thread that the
* controller is expecting.
*/
typedef struct fio_http_controller_s fio_http_controller_s;
/* *****************************************************************************
Constructor / Destructor
***************************************************************************** */
/** Create a new fio_http_s handle. */
SFUNC fio_http_s *fio_http_new(void);
/** Reduces an fio_http_s handle's reference count or frees it. */
SFUNC void fio_http_free(fio_http_s *);
/** Increases an fio_http_s handle's reference count. */
SFUNC fio_http_s *fio_http_dup(fio_http_s *);
/** Destroyed the HTTP handle object, freeing all allocated resources. */
SFUNC fio_http_s *fio_http_destroy(fio_http_s *h);
/** Collects an updated timestamp for logging purposes. */
SFUNC void fio_http_start_time_set(fio_http_s *);
/* *****************************************************************************
Opaque User and Controller Data
***************************************************************************** */
/** Gets the opaque user pointer associated with the HTTP handle. */
FIO_IFUNC void *fio_http_udata(fio_http_s *);
/** Sets the opaque user pointer associated with the HTTP handle. */
FIO_IFUNC void *fio_http_udata_set(fio_http_s *, void *);
/** Gets the second opaque user pointer associated with the HTTP handle. */
FIO_IFUNC void *fio_http_udata2(fio_http_s *);
/** Sets a second opaque user pointer associated with the HTTP handle. */
FIO_IFUNC void *fio_http_udata2_set(fio_http_s *, void *);
/** Gets the HTTP Controller associated with the HTTP handle. */
FIO_IFUNC fio_http_controller_s *fio_http_controller(fio_http_s *h);
/** Gets the HTTP Controller associated with the HTTP handle. */
FIO_IFUNC fio_http_controller_s *fio_http_controller_set(
fio_http_s *h,
fio_http_controller_s *controller);
/** Returns the existing controller data (`void *` pointer). */
FIO_IFUNC void *fio_http_cdata(fio_http_s *h);
/** Sets a new controller data (`void *` pointer). */
FIO_IFUNC void *fio_http_cdata_set(fio_http_s *h, void *cdata);
/* *****************************************************************************
Data associated with the Request (usually set by the HTTP protocol)
***************************************************************************** */
/** Gets the status associated with the HTTP handle (response). */
SFUNC size_t fio_http_status(fio_http_s *);
/** Sets the status associated with the HTTP handle (response). */
SFUNC size_t fio_http_status_set(fio_http_s *, size_t status);
/** Gets the method information associated with the HTTP handle. */
SFUNC fio_str_info_s fio_http_method(fio_http_s *);
/** Sets the method information associated with the HTTP handle. */
SFUNC fio_str_info_s fio_http_method_set(fio_http_s *, fio_str_info_s);
/** Gets the path information associated with the HTTP handle. */
SFUNC fio_str_info_s fio_http_path(fio_http_s *);
/** Sets the path information associated with the HTTP handle. */
SFUNC fio_str_info_s fio_http_path_set(fio_http_s *, fio_str_info_s);
/** Gets the query information associated with the HTTP handle. */
SFUNC fio_str_info_s fio_http_query(fio_http_s *);
/** Sets the query information associated with the HTTP handle. */
SFUNC fio_str_info_s fio_http_query_set(fio_http_s *, fio_str_info_s);
/** Gets the version information associated with the HTTP handle. */
SFUNC fio_str_info_s fio_http_version(fio_http_s *);
/** Sets the version information associated with the HTTP handle. */
SFUNC fio_str_info_s fio_http_version_set(fio_http_s *, fio_str_info_s);
/**
* Gets the header information associated with the HTTP handle.
*
* Since more than a single value may be associated with a header name, the
* index may be used to collect subsequent values.
*
* An empty value is returned if no header value is available (or index is
* exceeded).
*/
SFUNC fio_str_info_s fio_http_request_header(fio_http_s *,
fio_str_info_s name,
size_t index);
/** Sets the header information associated with the HTTP handle. */
SFUNC fio_str_info_s fio_http_request_header_set(fio_http_s *,
fio_str_info_s name,
fio_str_info_s value);
/** Sets the header information associated with the HTTP handle. */
SFUNC fio_str_info_s
fio_http_request_header_set_if_missing(fio_http_s *,
fio_str_info_s name,
fio_str_info_s value);
/** Adds to the header information associated with the HTTP handle. */
SFUNC fio_str_info_s fio_http_request_header_add(fio_http_s *,
fio_str_info_s name,
fio_str_info_s value);
/**
* Iterates through all request headers (except cookies!).
*
* A non-zero return will stop iteration.
* */
SFUNC size_t fio_http_request_header_each(fio_http_s *,
int (*callback)(fio_http_s *,
fio_str_info_s name,
fio_str_info_s value,
void *udata),
void *udata);
/** Gets the body (payload) length associated with the HTTP handle. */
SFUNC size_t fio_http_body_length(fio_http_s *);
/** Adjusts the body's reading position. Negative values start at the end. */
SFUNC size_t fio_http_body_seek(fio_http_s *, ssize_t pos);
/** Reads up to `length` of data from the body, returns nothing on EOF. */
SFUNC fio_str_info_s fio_http_body_read(fio_http_s *, size_t length);
/**
* Reads from the body until finding `token`, reaching `limit` or EOF.
*
* Note: `limit` is ignored if the
*/
SFUNC fio_str_info_s fio_http_body_read_until(fio_http_s *,
char token,
size_t limit);
/** Allocates a body (payload) of (at least) the `expected_length`. */
SFUNC void fio_http_body_expect(fio_http_s *, size_t expected_length);
/** Writes `data` to the body (payload) associated with the HTTP handle. */
SFUNC void fio_http_body_write(fio_http_s *, const void *data, size_t len);
/* *****************************************************************************
Cookies
***************************************************************************** */
/**
* Possible values for the `same_site` property in the cookie settings.
*
* See: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie
*/
typedef enum fio_http_cookie_same_site_e {
/** allow the browser to dictate this property */
FIO_HTTP_COOKIE_SAME_SITE_BROWSER_DEFAULT = 0,
/** The browser sends the cookie with cross-site and same-site requests. */
FIO_HTTP_COOKIE_SAME_SITE_NONE,
/**
* The cookie is withheld on cross-site sub-requests.
*
* The cookie is sent when a user navigates to the URL from an external
* site.
*/
FIO_HTTP_COOKIE_SAME_SITE_LAX,
/** The browser sends the cookie only for same-site requests. */
FIO_HTTP_COOKIE_SAME_SITE_STRICT,
} fio_http_cookie_same_site_e;
/**
* This is a helper for setting cookie data.
*
* This struct is used together with the `fio_http_cookie_set` macro. i.e.:
*
* fio_http_set_cookie(h,
* .name = "my_cookie",
* .value = "data");
*
*/
typedef struct fio_http_cookie_args_s {
/** The cookie's name. */
fio_str_info_s name;
/** The cookie's value (leave blank to delete cookie). */
fio_str_info_s value;
/** The cookie's domain (optional). */
fio_str_info_s domain;
/** The cookie's path (optional). */
fio_str_info_s path;
/** Max Age (how long should the cookie persist), in seconds (0 == session).*/
int max_age;
/** SameSite value. */
fio_http_cookie_same_site_e same_site;
/** Limit cookie to secure connections.*/
unsigned secure : 1;
/** Limit cookie to HTTP (intended to prevent JavaScript access/hijacking).*/
unsigned http_only : 1;
} fio_http_cookie_args_s;
/**
* Sets a response cookie.
*
* Returns -1 on error and 0 on success.
*
* Note: Long cookie names and long cookie values will be considered a security
* violation and an error will be returned. Many browsers and proxies impose
* limits on headers and cookies, cookies often limited to 4Kb in total for both
* name and value.
*/
SFUNC int fio_http_cookie_set(fio_http_s *h, fio_http_cookie_args_s);
#ifndef __cplusplus
/** Named arguments helper. See fio_http_cookie_args_s for details. */
#define fio_http_cookie_set(http___handle, ...) \
fio_http_cookie_set((http___handle), (fio_http_cookie_args_s){__VA_ARGS__})
#endif
/** Returns a cookie value (either received of newly set), if any. */
SFUNC fio_str_info_s fio_http_cookie(fio_http_s *,
const char *name,
size_t name_len);
/** Iterates through all cookies. A non-zero return will stop iteration. */
SFUNC size_t fio_http_cookie_each(fio_http_s *,
int (*callback)(fio_http_s *,
fio_str_info_s name,
fio_str_info_s value,
void *udata),
void *udata);
/**
* Iterates through all response set cookies.
*
* A non-zero return value from the callback will stop iteration.
*/
SFUNC size_t
fio_http_set_cookie_each(fio_http_s *h,
int (*callback)(fio_http_s *,
fio_str_info_s set_cookie_header,
fio_str_info_s value,
void *udata),
void *udata);
/* *****************************************************************************
Responding to an HTTP event.
***************************************************************************** */
/** Returns true if the HTTP handle's response was sent. */
SFUNC int fio_http_is_finished(fio_http_s *);
/** Returns true if the HTTP handle's response is streaming. */
SFUNC int fio_http_is_streaming(fio_http_s *);
/** Returns true if the HTTP connection was (or should have been) upgraded. */
SFUNC int fio_http_is_upgraded(fio_http_s *h);
/** Returns true if the HTTP handle establishes a WebSocket Upgrade. */
SFUNC int fio_http_is_websocket(fio_http_s *);
/** Returns true if the HTTP handle establishes an EventSource connection. */
SFUNC int fio_http_is_sse(fio_http_s *);
/**
* Gets the header information associated with the HTTP handle.
*
* Since more than a single value may be associated with a header name, the
* index may be used to collect subsequent values.
*
* An empty value is returned if no header value is available (or index is
* exceeded).
*
* If the response headers were already sent, the returned value is always
* empty.
*/
SFUNC fio_str_info_s fio_http_response_header(fio_http_s *,
fio_str_info_s name,
size_t index);
/**
* Sets the header information associated with the HTTP handle.
*
* If the response headers were already sent, the returned value is always
* empty.
*/
SFUNC fio_str_info_s fio_http_response_header_set(fio_http_s *,
fio_str_info_s name,
fio_str_info_s value);
/**
* Sets the header information associated with the HTTP handle.
*
* If the response headers were already sent, the returned value is always
* empty.
*/
SFUNC fio_str_info_s
fio_http_response_header_set_if_missing(fio_http_s *,
fio_str_info_s name,
fio_str_info_s value);
/**
* Adds to the header information associated with the HTTP handle.
*
* If the response headers were already sent, the returned value is always
* empty.
*/
SFUNC fio_str_info_s fio_http_response_header_add(fio_http_s *,
fio_str_info_s name,
fio_str_info_s value);
/**
* Iterates through all response headers (except cookies!).
*
* A non-zero return will stop iteration.
* */
SFUNC size_t fio_http_response_header_each(fio_http_s *,
int (*callback)(fio_http_s *,
fio_str_info_s name,
fio_str_info_s value,
void *udata),
void *udata);
/** Arguments for the fio_http_write function. */
typedef struct fio_http_write_args_s {
/** The data to be written. */
const void *buf;
/** The length of the data to be written. */
size_t len;
/** The offset at which writing should begin. */
size_t offset;
/** If streaming a file, set this value. The file is always closed. */
int fd;
/** If the data is a buffer, this callback may be set to free it once sent. */
void (*dealloc)(void *);
/** If the data is a buffer / a file - should it be copied? */
int copy;
/**
* If `finish` is set, this data marks the end of the response.
*
* Otherwise the response will stream the data.
*/
int finish;
} fio_http_write_args_s;
/**
* Writes `data` to the response body associated with the HTTP handle after
* sending all headers (no further headers may be sent).
*/
SFUNC void fio_http_write(fio_http_s *, fio_http_write_args_s args);
/** Named arguments helper. See fio_http_write and fio_http_write_args_s. */
#define fio_http_write(http_handle, ...) \
fio_http_write(http_handle, (fio_http_write_args_s){__VA_ARGS__})
#define fio_http_finish(http_handle) fio_http_write(http_handle, .finish = 1)
/* *****************************************************************************
WebSocket / SSE Helpers
***************************************************************************** */
/** Returns non-zero if request headers ask for a WebSockets Upgrade.*/
SFUNC int fio_http_websockets_requested(fio_http_s *);
/** Sets response data to agree to a WebSockets Upgrade.*/
SFUNC void fio_http_upgrade_websockets(fio_http_s *);
/** Sets request data to request a WebSockets Upgrade.*/
SFUNC void fio_http_websockets_set_request(fio_http_s *);
/** Returns non-zero if request headers ask for an EventSource (SSE) Upgrade.*/
SFUNC int fio_http_sse_requested(fio_http_s *);
/** Sets response data to agree to an EventSource (SSE) Upgrade.*/
SFUNC void fio_http_upgrade_sse(fio_http_s *);
/** Sets request data to request an EventSource (SSE) Upgrade.*/
SFUNC void fio_http_sse_set_request(fio_http_s *);
/* *****************************************************************************
MIME File Type Helpers - NOT thread safe!
***************************************************************************** */
/** Registers a Mime-Type to be associated with the file extension. */
SFUNC int fio_http_mimetype_register(char *file_ext,
size_t file_ext_len,
fio_str_info_s mime_type);
/** Finds the Mime-Type associated with the file extension (if registered). */
SFUNC fio_str_info_s fio_http_mimetype(char *file_ext, size_t file_ext_len);
/* *****************************************************************************
HTTP Body Parsing Helpers (TODO!)
***************************************************************************** */
/* *****************************************************************************
Header Parsing Helpers
***************************************************************************** */
/**
* Copies all header data, from possibly an array of identical response headers,
* resulting in a parsed format outputted to `buf_parsed`.
*
* Returns 0 on success or -1 on error (i.e., `buf_parsed.capa` wasn't enough
* for the parsed output).
*
* Note that the parsed output isn't readable as a string, but is designed to
* work with the `FIO_HTTP_PARSED_HEADER_EACH` and
* `FIO_HTTP_HEADER_VALUE_EACH_PROPERTY` property.
*
* See also `fio_http_response_header_parse`.
*/
SFUNC int fio_http_response_header_parse(fio_http_s *h,
fio_str_info_s *buf_parsed,
fio_str_info_s header_name);
/**
* Copies all header data, from possibly an array of identical response headers,
* resulting in a parsed format outputted to `buf_parsed`.
*
* Returns 0 on success or -1 on error (i.e., `buf_parsed.capa` wasn't enough
* for the parsed output).
*
* Note that the parsed output isn't readable as a string, but is designed to
* work with the `FIO_HTTP_PARSED_HEADER_EACH` and
* `FIO_HTTP_HEADER_VALUE_EACH_PROPERTY` property.
*
* i.e.:
*
* ```c
* FIO_STR_INFO_TMP_VAR(buf, 1023); // tmp buffer for the parsed output
* fio_http_s *h = fio_http_new(); // using a mock HTTP handle
* fio_http_request_header_add(
* h,
* FIO_STR_INFO2("accept", 6),
* FIO_STR_INFO1("text/html, application/json;q=0.9; d=500, image/png"));
* fio_http_request_header_add(h,
* FIO_STR_INFO2("accept", 6),
* FIO_STR_INFO1("text/yaml"));
* FIO_ASSERT( // in production do NOT assert, but route to error instead!
* !fio_http_request_header_parse(h, &buf, FIO_STR_INFO2("accept", 6)),
* "parse returned error!");
* FIO_HTTP_PARSED_HEADER_EACH(buf, value) {
* printf("* processing value (%zu bytes): %s\n", value.len, value.buf);
* FIO_HTTP_HEADER_VALUE_EACH_PROPERTY(value, prop) {
* printf("* for value %s: (%zu,%zu bytes) %s = %s\n",
* value.buf,
* prop.name.len,
* prop.value.len,
* prop.name.buf,
* prop.value.buf);
* }
* }
* ```
*/
SFUNC int fio_http_request_header_parse(fio_http_s *h,
fio_str_info_s *buf_parsed,
fio_str_info_s header_name);
/**
* Parses header for multiple values and properties and iterates over all
* values.
*
* This MACRO will allocate 2048 bytes on the stack for parsing the header
* values and properties, if more space is necessary dig deeper.
*
* Use FIO_HTTP_HEADER_VALUE_EACH_PROPERTY to iterate over a value's properties.
*/
#define FIO_HTTP_HEADER_EACH_VALUE(/* fio_http_s */ http_handle, \
/* int / bool */ is_request, \
/* fio_str_info_s */ header_name, \
/* chosen var named */ value) \
for (char fio___buf__##value##__[2048], /* allocate buffer on stack */ \
*fio___buf__##value##_ptr = NULL; \
!fio___buf__##value##_ptr; \
fio___buf__##value##_ptr = fio___buf__##value##__) \
for (fio_str_info_s fio___buf__##value##__str = /* declare buffer var */ \
FIO_STR_INFO3(fio___buf__##value##__, 0, 2048); \
fio___buf__##value##__str.buf == fio___buf__##value##__; \
fio___buf__##value##__str.buf = fio___buf__##value##__ + 1) \
if (!((is_request ? fio_http_request_header_parse \
: fio_http_response_header_parse)( \
http_handle, /* parse headers */ \
&fio___buf__##value##__str, \
header_name))) \
FIO_HTTP_PARSED_HEADER_EACH(fio___buf__##value##__str, value) /* loop \
*/
/** Iterated through the properties associated with a parsed header values. */
#define FIO_HTTP_HEADER_VALUE_EACH_PROPERTY(/* fio_str_info_s */ value, \
/* chosen var named */ property)
/** Used internally to iterate over a parsed header buffer. */
#define FIO_HTTP_PARSED_HEADER_EACH(/* fio_str_info_s */ buf_parsed, \
/* chosen var named */ value)
/* *****************************************************************************
General Helpers
***************************************************************************** */
/** Sends the requested error message and finishes the response. */
SFUNC void fio_http_send_error_response(fio_http_s *h, size_t status);
/** Returns true (1) if the ETag response matches an if-none-match request. */
SFUNC int fio_http_etag_is_match(fio_http_s *h);
/**
* Attempts to send a static file from the `root` folder. On success the
* response is complete and 0 is returned. Otherwise returns -1.
*/
SFUNC int fio_http_static_file_response(fio_http_s *h,
fio_str_info_s root_folder,
fio_str_info_s file_name,
size_t max_age);
/** Returns a human readable string related to the HTTP status number. */
SFUNC fio_str_info_s fio_http_status2str(size_t status);
/** Logs an HTTP (response) to STDOUT. */
SFUNC void fio_http_write_log(fio_http_s *h, fio_buf_info_s peer_addr);
/* *****************************************************************************
The HTTP Controller
***************************************************************************** */
/**
* The HTTP Controller manages all the callbacks required by the HTTP Handler in
* order for HTTP responses and requests to be sent.
*/
struct fio_http_controller_s {
/* MUST be initialized to zero, used internally by the HTTP Handle. */
uintptr_t private_flags;
/** Called when an HTTP handle is freed. */
void (*on_destroyed)(fio_http_s *h);
/** Informs the controller that request / response headers must be sent. */
void (*send_headers)(fio_http_s *h);
/** called by the HTTP handle for each body chunk (or to finish a response. */
void (*write_body)(fio_http_s *h, fio_http_write_args_s args);
/** called once a request / response had finished */
void (*on_finish)(fio_http_s *h);
};
/* *****************************************************************************
HTTP Handle Implementation - inlined static functions
***************************************************************************** */
#define FIO___HTTP_GETSET_PTR(type, name, index_, pre_set_code) \
/** Used internally to set / get the propecrty at its known pointer index. \
*/ \
FIO_IFUNC type *fio_http_##name(fio_http_s *h) { \
return ((type **)h)[index_]; \
} \
/** Used internally to set / get the propercty at its known pointer index. \
*/ \
FIO_IFUNC type *fio_http_##name##_set(fio_http_s *h, type *ptr) { \
pre_set_code; \
return (((type **)h)[index_] = ptr); \
}
SFUNC fio_http_controller_s *fio___http_controller_validate(
fio_http_controller_s *c);
/* Create fio_http_udata_(get|set) functions */
FIO___HTTP_GETSET_PTR(void, udata, 0, (void)0)
/* Create fio_http_pdata_(get|set) functions */
FIO___HTTP_GETSET_PTR(void, udata2, 1, (void)0)
/* Create fio_http_cdata_(get|set) functions */
FIO___HTTP_GETSET_PTR(void, cdata, 2, (void)0)
/* Create fio_http_controller_(get|set) functions */
FIO___HTTP_GETSET_PTR(fio_http_controller_s,
controller,
3,
ptr = fio___http_controller_validate(ptr))
#undef FIO___HTTP_GETSET_PTR
/*
REMEMBER:
========
All memory allocations should use:
* FIO_MEM_REALLOC_(ptr, old_size, new_size, copy_len)
* FIO_MEM_FREE_(ptr, size)
*/
/* *****************************************************************************
Header Parsing Helpers - inlined helpers
***************************************************************************** */
#define FIO___HTTP_PARSED_HEADER_VALUE 0
#define FIO___HTTP_PARSED_HEADER_PROPERTY_BLOCK_LEN 1
#define FIO___HTTP_PARSED_HEADER_PROPERTY_DATA 2
typedef struct {
fio_str_info_s name;
fio_str_info_s value;
} fio___http_header_property_s;
/**
* Assumes a Buffer of bytes containing length info and string data as such:
* [ NUL byte - 1 byte at head of format ]
* repeat
* [ 2 byte info: (type | (len << 2)) ]
* [ Optional 2 byte info: (len << 2) (if type was 1)]
* [ String of `len` bytes][ NUL byte (not counted in `len`)]
*/
FIO_IFUNC fio_str_info_s fio___http_parsed_headers_next(fio_str_info_s value) {
for (;;) {
const size_t coded = (size_t)fio_buf2u16u(value.buf + value.len + 1U);
if (!coded)
return (value = (fio_str_info_s){0});
const size_t block_len = coded >> 2;
value.buf += value.len + 3;
value.len = block_len;
if (!(coded & 3))
return value;
value.buf -= 3; /* reposition to read NUL + value rather than text start */
}
}
FIO_IFUNC fio___http_header_property_s
fio___http_parsed_property_next(fio___http_header_property_s property) {
for (;;) {
size_t coded =
(size_t)fio_buf2u16u(property.value.buf + property.value.len + 1);
if (!(coded & 3))
return (property = (fio___http_header_property_s){{0}, {0}});
if ((coded & 3) == FIO___HTTP_PARSED_HEADER_PROPERTY_BLOCK_LEN) {
property.value.buf += 2;
coded = (size_t)fio_buf2u16u(property.value.buf + property.value.len + 1);
}
if ((coded & 3) != 2)
return (property = (fio___http_header_property_s){{0}, {0}});
coded >>= 2;
property.name.buf = property.value.buf + property.value.len + 3;
property.name.len = coded;
coded = (size_t)fio_buf2u16u(property.name.buf + property.name.len + 1);
FIO_ASSERT_DEBUG((coded & 3) == 2,
"header property value parsing format error");
property.value.buf = property.name.buf + property.name.len + 3;
property.value.len = coded >> 2;
return property;
}
}
#undef FIO_HTTP_PARSED_HEADER_EACH
#define FIO_HTTP_PARSED_HEADER_EACH(buf_parsed, value) \
for (fio_str_info_s value = \
fio___http_parsed_headers_next(FIO_STR_INFO2(buf_parsed.buf, 0)); \
value.len; \
value = fio___http_parsed_headers_next(value))
#undef FIO_HTTP_HEADER_VALUE_EACH_PROPERTY
#define FIO_HTTP_HEADER_VALUE_EACH_PROPERTY(value_, property) \
for (fio___http_header_property_s property = \
fio___http_parsed_property_next( \
(fio___http_header_property_s){.value = value_}); \
property.name.len; \
property = fio___http_parsed_property_next(property))
/* *****************************************************************************
HTTP Handle Implementation - possibly externed functions.
***************************************************************************** */
#if defined(FIO_EXTERN_COMPLETE) || !defined(FIO_EXTERN)
/* *****************************************************************************
Helpers - memory allocation & logging time collection
***************************************************************************** */
FIO___LEAK_COUNTER_DEF(http___keystr_allocator)
FIO_SFUNC void fio___http_keystr_free(void *ptr, size_t len) {
FIO_MEM_FREE_(ptr, len);
if (ptr)
FIO___LEAK_COUNTER_ON_FREE(http___keystr_allocator);
(void)len; /* if unused */
}
FIO_SFUNC void *fio___http_keystr_alloc(size_t capa) {
FIO___LEAK_COUNTER_ON_ALLOC(http___keystr_allocator);
return FIO_MEM_REALLOC_(NULL, 0, capa, 0);
}
#if FIO_HTTP_EXACT_LOGGING
#define FIO___HTTP_TIME_DIV 1000000
#define FIO___HTTP_TIME_UNIT "us"
FIO_IFUNC int64_t fio_http_get_timestump(void) {
return fio_time2micro(fio_time_real());
}
#else
#define FIO___HTTP_TIME_DIV 1000
#define FIO___HTTP_TIME_UNIT "ms"
int64_t fio_srv_last_tick(void);
FIO_IFUNC int64_t fio_http_get_timestump(void) {
return (int64_t)fio_srv_last_tick();
}
#endif
FIO_SFUNC fio_str_info_s fio_http_date(uint64_t now_in_seconds) {
static char date_buf[128];
static size_t date_len;
static uint64_t date_buf_val;
if (date_buf_val == now_in_seconds)
return FIO_STR_INFO2(date_buf, date_len);
date_len = fio_time2rfc7231(date_buf, now_in_seconds);
date_buf[date_len] = 0;
date_buf_val = now_in_seconds;
return FIO_STR_INFO2(date_buf, date_len);
}
#define FIO___RECURSIVE_INCLUDE 1
/* *****************************************************************************
String Cache
***************************************************************************** */
#define FIO_MAP_NAME fio___http_str_cache
#define FIO_MAP_LRU FIO_HTTP_CACHE_LIMIT
#define FIO_MAP_KEY_BSTR
#include FIO_INCLUDE_FILE
static struct {
fio___http_str_cache_s cache;
FIO___LOCK_TYPE lock;
} FIO___HTTP_STRING_CACHE[2] = {{.lock = FIO___LOCK_INIT},
{.lock = FIO___LOCK_INIT}};
#define FIO___HTTP_STR_CACHE_COOKIE 0
#define FIO___HTTP_STR_CACHE_VALUE 1
#if FIO_HTTP_CACHE_STATIC
#define FIO___HTTP_STATIC_CACHE_MASK 127
#define FIO___HTTP_STATIC_CACHE_FOLD 22
#define FIO___HTTP_STATIC_CACHE_STEP 1
#define FIO___HTTP_STATIC_CACHE_STEP_LIMIT 3
static struct {
fio___bstr_meta_s meta;
char str[32];
} FIO___HTTP_STATIC_CACHE[] = {
#define FIO___HTTP_STATIC_CACHE_SET(s) \
{ .meta = {.ref = 3, .len = (uint32_t)(sizeof(s) - 1)}, .str = s }
FIO___HTTP_STATIC_CACHE_SET("a-im"),
FIO___HTTP_STATIC_CACHE_SET("accept"),
FIO___HTTP_STATIC_CACHE_SET("accept-charset"),
FIO___HTTP_STATIC_CACHE_SET("accept-datetime"),
FIO___HTTP_STATIC_CACHE_SET("accept-encoding"),
FIO___HTTP_STATIC_CACHE_SET("accept-language"),
FIO___HTTP_STATIC_CACHE_SET("accept-ranges"),
FIO___HTTP_STATIC_CACHE_SET("access-control-allow-origin"),
FIO___HTTP_STATIC_CACHE_SET("access-control-request-headers"),
FIO___HTTP_STATIC_CACHE_SET("access-control-request-method"),
FIO___HTTP_STATIC_CACHE_SET("age"),
FIO___HTTP_STATIC_CACHE_SET("allow"),
FIO___HTTP_STATIC_CACHE_SET("authorization"),
FIO___HTTP_STATIC_CACHE_SET("cache-control"),
FIO___HTTP_STATIC_CACHE_SET("connection"),
FIO___HTTP_STATIC_CACHE_SET("content-disposition"),
FIO___HTTP_STATIC_CACHE_SET("content-encoding"),
FIO___HTTP_STATIC_CACHE_SET("content-language"),
FIO___HTTP_STATIC_CACHE_SET("content-length"),
FIO___HTTP_STATIC_CACHE_SET("content-location"),
FIO___HTTP_STATIC_CACHE_SET("content-range"),
FIO___HTTP_STATIC_CACHE_SET("content-type"),
FIO___HTTP_STATIC_CACHE_SET("cookie"),
FIO___HTTP_STATIC_CACHE_SET("date"),
FIO___HTTP_STATIC_CACHE_SET("dnt"),
FIO___HTTP_STATIC_CACHE_SET("etag"),
FIO___HTTP_STATIC_CACHE_SET("expect"),
FIO___HTTP_STATIC_CACHE_SET("expires"),
FIO___HTTP_STATIC_CACHE_SET("forwarded"),
FIO___HTTP_STATIC_CACHE_SET("from"),
FIO___HTTP_STATIC_CACHE_SET("host"),
FIO___HTTP_STATIC_CACHE_SET("if-match"),
FIO___HTTP_STATIC_CACHE_SET("if-modified-since"),
FIO___HTTP_STATIC_CACHE_SET("if-none-match"),
FIO___HTTP_STATIC_CACHE_SET("if-range"),
FIO___HTTP_STATIC_CACHE_SET("if-unmodified-since"),
FIO___HTTP_STATIC_CACHE_SET("last-modified"),
FIO___HTTP_STATIC_CACHE_SET("link"),
FIO___HTTP_STATIC_CACHE_SET("location"),
FIO___HTTP_STATIC_CACHE_SET("max-forwards"),
FIO___HTTP_STATIC_CACHE_SET("origin"),
FIO___HTTP_STATIC_CACHE_SET("pragma"),
FIO___HTTP_STATIC_CACHE_SET("proxy-authenticate"),
FIO___HTTP_STATIC_CACHE_SET("proxy-authorization"),
FIO___HTTP_STATIC_CACHE_SET("range"),
FIO___HTTP_STATIC_CACHE_SET("referer"),
FIO___HTTP_STATIC_CACHE_SET("refresh"),
FIO___HTTP_STATIC_CACHE_SET("retry-after"),
FIO___HTTP_STATIC_CACHE_SET("sec-ch-ua"),
FIO___HTTP_STATIC_CACHE_SET("sec-ch-ua-mobile"),
FIO___HTTP_STATIC_CACHE_SET("sec-ch-ua-platform"),
FIO___HTTP_STATIC_CACHE_SET("sec-fetch-dest"),
FIO___HTTP_STATIC_CACHE_SET("sec-fetch-mode"),
FIO___HTTP_STATIC_CACHE_SET("sec-fetch-site"),
FIO___HTTP_STATIC_CACHE_SET("sec-fetch-user"),
FIO___HTTP_STATIC_CACHE_SET("server"),
FIO___HTTP_STATIC_CACHE_SET("set-cookie"),
FIO___HTTP_STATIC_CACHE_SET("strict-transport-security"),
FIO___HTTP_STATIC_CACHE_SET("te"),
FIO___HTTP_STATIC_CACHE_SET("transfer-encoding"),
FIO___HTTP_STATIC_CACHE_SET("upgrade"),
FIO___HTTP_STATIC_CACHE_SET("upgrade-insecure-requests"),
FIO___HTTP_STATIC_CACHE_SET("user-agent"),
FIO___HTTP_STATIC_CACHE_SET("vary"),
FIO___HTTP_STATIC_CACHE_SET("via"),
FIO___HTTP_STATIC_CACHE_SET("warning"),
FIO___HTTP_STATIC_CACHE_SET("www-authenticate"),
FIO___HTTP_STATIC_CACHE_SET("x-csrf-token"),
FIO___HTTP_STATIC_CACHE_SET("x-forwarded-for"),
FIO___HTTP_STATIC_CACHE_SET("x-forwarded-host"),
FIO___HTTP_STATIC_CACHE_SET("x-forwarded-proto"),
FIO___HTTP_STATIC_CACHE_SET("x-requested-with"),
{{0}}};
static uint16_t FIO___HTTP_STATIC_CACHE_IMAP[FIO___HTTP_STATIC_CACHE_MASK + 1] =
{0};
static void fio___http_str_cached_init(void) {
FIO_MEMSET(FIO___HTTP_STATIC_CACHE_IMAP,
0,
(FIO___HTTP_STATIC_CACHE_MASK + 1) *
sizeof(FIO___HTTP_STATIC_CACHE_IMAP[0]));
for (size_t i = 0; FIO___HTTP_STATIC_CACHE[i].meta.ref; ++i) {
uint64_t hash = fio_stable_hash(FIO___HTTP_STATIC_CACHE[i].str,
FIO___HTTP_STATIC_CACHE[i].meta.len,
0); /* use stable hash (change resilient) */
hash ^= hash >> FIO___HTTP_STATIC_CACHE_FOLD;
size_t protection = 0;
while (FIO___HTTP_STATIC_CACHE_IMAP[hash & FIO___HTTP_STATIC_CACHE_MASK]) {
FIO_ASSERT(
(FIO___HTTP_STATIC_CACHE_IMAP[hash & FIO___HTTP_STATIC_CACHE_MASK] &
0xFF80) != (hash & 0xFF80),
"full collision for HTTP static hash (%zu == %zu!",
(size_t)(hash & FIO___HTTP_STATIC_CACHE_MASK),
i);
hash += hash >> FIO___HTTP_STATIC_CACHE_STEP;
FIO_ASSERT((protection++) < FIO___HTTP_STATIC_CACHE_STEP_LIMIT,
"HTTP static cache collision overflow @ %zu (%s)",
i,
FIO___HTTP_STATIC_CACHE[i].str);
}
FIO___HTTP_STATIC_CACHE_IMAP[hash & FIO___HTTP_STATIC_CACHE_MASK] =
(hash & 0xFF80) | i;
}
}
static char *fio___http_str_cached_static(char *str, size_t len) {
uint64_t hash =
fio_stable_hash(str, len, 0); /* use stable hash (change resilient) */
hash ^= hash >> FIO___HTTP_STATIC_CACHE_FOLD;
for (size_t attempts = 0; attempts < FIO___HTTP_STATIC_CACHE_STEP_LIMIT;
++attempts) {
if ((FIO___HTTP_STATIC_CACHE_IMAP[hash & FIO___HTTP_STATIC_CACHE_MASK] &
0xFF80) == (hash & 0xFF80))
break;
hash += hash >> FIO___HTTP_STATIC_CACHE_STEP;
}
size_t pos =
FIO___HTTP_STATIC_CACHE_IMAP[hash & FIO___HTTP_STATIC_CACHE_MASK] &
0x007F;
if (FIO___HTTP_STATIC_CACHE[pos].meta.len == len &&
!FIO_MEMCMP(str, FIO___HTTP_STATIC_CACHE[pos].str, len)) {
return FIO___HTTP_STATIC_CACHE[pos].str;
}
return NULL;
}
#undef FIO___HTTP_STATIC_CACHE_MASK
#undef FIO___HTTP_STATIC_CACHE_FOLD
#undef FIO___HTTP_STATIC_CACHE_STEP
#undef FIO___HTTP_STATIC_CACHE_STEP_LIMIT
#else
#define fio___http_str_cached_init() (void)0
#endif /* FIO_HTTP_CACHE_STATIC */
FIO_IFUNC char *fio___http_str_cached_inner(size_t group,
uint64_t hash,
fio_str_info_s s) {
#if !FIO_HTTP_CACHE_LIMIT
return fio_bstr_write(NULL, s.buf, s.len);
#endif
fio_str_info_s cached;
hash ^= (uint64_t)(uintptr_t)fio_http_new;
#if FIO_HTTP_CACHE_USES_MUTEX
FIO___LOCK_LOCK(FIO___HTTP_STRING_CACHE[group].lock);
#endif
cached =
fio___http_str_cache_set_if_missing(&FIO___HTTP_STRING_CACHE[group].cache,
hash,