Skip to content
Navigation Menu
{{ message }}
forked from jeremycw/httpserver.h
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhttpserver.h
More file actions
1703 lines (1522 loc) · 54.3 KB
/
httpserver.h
File metadata and controls
1703 lines (1522 loc) · 54.3 KB
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
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
*
* MIT License
*
* Copyright (c) 2019 Jeremy Williams
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
*
* httpserver.h (0.6.0)
*
* Description:
*
* A single header C library for building non-blocking event driven HTTP
* servers
*
* Usage:
*
* Do this:
* #define HTTPSERVER_IMPL
* before you include this file in *one* C or C++ file to create the
* implementation.
*
* // i.e. it should look like this:
* #include ...
* #include ...
* #include ...
* #define HTTPSERVER_IMPL
* #include "httpserver.h"
*
* There are some #defines that can be configured. This must be done in the
* same file that you define HTTPSERVER_IMPL These defines have default values
* and will need to be #undef'd and redefined to configure them.
*
* HTTP_REQUEST_BUF_SIZE - default 1024 - The initial size in bytes of the
* read buffer for the request. This buffer grows automatically if it's
* capacity is reached but it certain environments it may be optimal to
* change this value.
*
* HTTP_RESPONSE_BUF_SIZE - default 512 - Same as above except for the
* response buffer.
*
* HTTP_REQUEST_TIMEOUT - default 20 - The amount of seconds the request will
* wait for activity on the socket before closing. This only applies mid
* request. For the amount of time to hold onto keep-alive connections see
* below.
*
* HTTP_KEEP_ALIVE_TIMEOUT - default 120 - The amount of seconds to keep a
* connection alive a keep-alive request has completed.
*
* HTTP_MAX_CONTENT_LENGTH - default 8388608 (8MB) - The max size in bytes
* of the request content length. It should be noted that the request body
* will be fully read into memory so while this could be redefined to a
* value as large as INT_MAX it will allocate a lot of memory. I would
* reccommend using chunked encoding for large requests.
*
* HTTP_MAX_TOTAL_EST_MEM_USAGE - default 4294967296 (4GB) - This is the
* amount of read/write buffer space that is allowed to be allocated across
* all requests before new requests will get 503 responses.
*
* HTTP_MAX_TOKEN_LENGTH - default 8192 (8KB) - This is the max size of any
* non body http tokens. i.e: header names, header values, url length, etc.
*
* For more details see the documentation of the interface and the example
* below.
*
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
#ifndef HTTPSERVER_H
#define HTTPSERVER_H
#ifdef __cplusplus
extern "C" {
#endif
// String type used to read the request details. The char pointer is NOT null
// terminated.
struct http_string_s {
char const * buf;
int len;
};
struct http_server_s;
struct http_request_s;
struct http_response_s;
// Returns the event loop id that the server is running on. This will be an
// epoll fd when running on Linux or a kqueue on BSD. This can be used to
// listen for activity on sockets, etc. The only caveat is that the user data
// must be set to a struct where the first member is the function pointer to
// a callback that will handle the event. i.e:
//
// For kevent:
//
// struct foo {
// void (*handler)(struct kevent*);
// ...
// }
//
// // Set ev.udata to a foo pointer when registering the event.
//
// For epoll:
//
// struct foo {
// void (*handler)(struct epoll_event*);
// ...
// }
//
// // Set ev.data.ptr to a foo pointer when registering the event.
int http_server_loop(struct http_server_s* server);
// Allocates and initializes the http server. Takes a port and a function
// pointer that is called to process requests.
struct http_server_s* http_server_init(int port, void (*handler)(struct http_request_s*));
// Starts the event loop and the server listening. During normal operation this
// function will not return. Return value is the error code if the server fails
// to start.
int http_server_listen(struct http_server_s* server);
// Use this listen call in place of the one above when you want to integrate
// an http server into an existing application that has a loop already and you
// want to use the polling functionality instead. This works well for
// applications like games that have a constant update loop.
int http_server_listen_poll(struct http_server_s* server);
// Call this function in your update loop. It will trigger the request handler
// once if there is a request ready. Returns 1 if a request was handled and 0
// if no requests were handled. It should be called in a loop until it returns
// 0.
int http_server_poll(struct http_server_s* server);
// Returns the request method as it was read from the HTTP request line.
struct http_string_s http_request_method(struct http_request_s* request);
// Returns the full request target (url) as it was read from the HTTP request
// line.
struct http_string_s http_request_target(struct http_request_s* request);
// Returns the request body. If no request body was sent buf and len of the
// string will be set to 0.
struct http_string_s http_request_body(struct http_request_s* request);
// Returns the request header value for the given header key. The key is case
// insensitive.
struct http_string_s http_request_header(struct http_request_s* request, char const * key);
// Procedure used to iterate over all the request headers. iter should be
// initialized to zero before calling. Each call will set key and val to the
// key and value of the next header. Returns 0 when there are no more headers.
int http_request_iterate_headers(
struct http_request_s* request,
struct http_string_s* key,
struct http_string_s* val,
int* iter
);
// Retrieve the opaque data pointer.
void* http_request_userdata(struct http_request_s* request);
// Stores a pointer for future retrieval. This is not used by the library in
// any way and is strictly for you, the application programmer to make use
// of.
void http_request_set_userdata(struct http_request_s* request, void* data);
#define HTTP_KEEP_ALIVE 1
#define HTTP_CLOSE 0
// By default the server will inspect the Connection header and the HTTP
// version to determine whether the connection should be kept alive or not.
// Use this function to override that behaviour to force the connection to
// keep-alive or close by passing in the HTTP_KEEP_ALIVE or HTTP_CLOSE
// directives respectively. This may provide a minor performance improvement
// in cases where you control client and server and want to always close or
// keep the connection alive.
void http_request_connection(struct http_request_s* request, int directive);
// When reading in the HTTP request the server allocates a buffer to store
// the request details such as the headers, method, body, etc. By default this
// memory will be freed when http_respond is called. This function lets you
// free that memory before the http_respond call. This can be useful if you
// have requests that take a long time to complete and you don't require the
// request data. Accessing any http_string_s's will be invalid after this call.
void http_request_free_buffer(struct http_request_s* request);
// Allocates an http response. This memory will be freed when http_respond is
// called.
struct http_response_s* http_response_init();
// Set the response status. Accepts values between 100 and 599 inclusive. Any
// other value will map to 500.
void http_response_status(struct http_response_s* response, int status);
// Set a response header. Takes two null terminated strings.
void http_response_header(struct http_response_s* response, char const * key, char const * value);
// Set the response body. The caller is responsible for freeing any memory that
// may have been allocated for the body. It is safe to free this memory AFTER
// http_respond has been called.
void http_response_body(struct http_response_s* response, char const * body, int length);
// Starts writing the response to the client. Any memory allocated for the
// response body or response headers is safe to free after this call.
void http_respond(struct http_request_s* request, struct http_response_s* response);
// Writes a chunk to the client. The notify_done callback will be called when
// the write is complete. This call consumes the response so a new response
// will need to be initialized for each chunk. The response status of the
// request will be the response status that is set when http_respond_chunk is
// called the first time. Any headers set for the first call will be sent as
// the response headers. Headers set for subsequent calls will be ignored.
void http_respond_chunk(
struct http_request_s* request,
struct http_response_s* response,
void (*notify_done)(struct http_request_s*)
);
// Ends the chunked response. Any headers set before this call will be included
// as what the HTTP spec refers to as 'trailers' which are essentially more
// response headers.
void http_respond_chunk_end(struct http_request_s* request, struct http_response_s* response);
// If a request has Transfer-Encoding: chunked you cannot read the body in the
// typical way. Instead you need to call this function to read one chunk at a
// time. You pass a callback that will be called when the chunk is ready. When
// the callback is called you can use `http_request_chunk` to get the current
// chunk. When done with that chunk call this function again to request the
// next chunk. If the chunk has size 0 then the request body has been completely
// read and you can now respond.
void http_request_read_chunk(
struct http_request_s* request,
void (*chunk_cb)(struct http_request_s*)
);
// Returns the current chunk of the request body. This chunk is only valid until
// the next call to `http_request_read_chunk`.
struct http_string_s http_request_chunk(struct http_request_s* request);
#ifdef __cplusplus
}
#endif
// Minimal example usage.
#ifdef HTTPSERVER_EXAMPLE
#define RESPONSE "Hello, World!"
void handle_request(struct http_request_s* request) {
struct http_response_s* response = http_response_init();
http_response_status(response, 200);
http_response_header(response, "Content-Type", "text/plain");
http_response_body(response, RESPONSE, sizeof(RESPONSE) - 1);
http_respond(request, response);
}
int main() {
struct http_server_s* server = http_server_init(8080, handle_request);
http_server_listen(server);
}
#endif
#endif
#ifdef HTTPSERVER_IMPL
#ifndef HTTPSERVER_IMPL_ONCE
#define HTTPSERVER_IMPL_ONCE
#ifdef __linux__
#define EPOLL
#define _POSIX_C_SOURCE 199309L
#else
#define KQUEUE
#endif
#include <time.h>
#include <stdlib.h>
#include <stdio.h>
#include <fcntl.h>
#include <errno.h>
#include <netdb.h>
#include <unistd.h>
#include <string.h>
#include <stdarg.h>
#include <signal.h>
#include <limits.h>
#include <assert.h>
#ifdef KQUEUE
#include <sys/event.h>
#else
#include <sys/epoll.h>
#include <sys/timerfd.h>
#endif
// *** macro definitions
// Application configurable
#define HTTP_REQUEST_BUF_SIZE 1024
#define HTTP_RESPONSE_BUF_SIZE 512
#define HTTP_REQUEST_TIMEOUT 20
#define HTTP_KEEP_ALIVE_TIMEOUT 120
#define HTTP_MAX_CONTENT_LENGTH 8388608 // 8mb
#define HTTP_MAX_TOKEN_LENGTH 8192 // 8kb
#define HTTP_MAX_TOTAL_EST_MEM_USAGE 4294967296 // 4gb
#define HTTP_MAX_HEADER_COUNT 127
#define HTTP_FLAG_SET(var, flag) var |= flag
#define HTTP_FLAG_CLEAR(var, flag) var &= ~flag
#define HTTP_FLAG_CHECK(var, flag) (var & flag)
// token types / parser states
#define HTTP_METHOD 0
#define HTTP_TARGET 1
#define HTTP_VERSION 2
#define HTTP_HEADER_KEY 3
#define HTTP_HEADER_VALUE 4
#define HTTP_HEADER_END 5
#define HTTP_NONE 6
#define HTTP_BODY 7
#define HTTP_PARSE_ERROR 13
// error sub types
#define HTTP_ERR_PAYLOAD_TOO_LARGE 0
#define HTTP_ERR_BAD_REQUEST 1
// chunked token types / parser state
#define HTTP_CHUNK_SIZE 8
#define HTTP_CHUNK_EXTN 9
#define HTTP_CHUNK_BODY 10
#define HTTP_CHUNK_BODY_END 11
#define HTTP_CHUNK_BODY_PARTIAL 12
// parser flags
#define HS_PF_TRANSFER_ENCODING 0x1
#define HS_PF_CONTENT_LENGTH 0x2
#define HS_PF_CHUNKED 0x4
// parser sub states
#define HTTP_LWS 2
#define HTTP_CR 3
#define HTTP_CRLF 4
// parser comparisons
#define HS_CONTENT_LENGTH_LOW "content-length"
#define HS_CONTENT_LENGTH_UP "CONTENT-LENGTH"
#define HS_TRANSFER_ENCODING_LOW "transfer-encoding"
#define HS_TRANSFER_ENCODING_UP "TRANSFER-ENCODING"
#define HS_CHUNKED_LOW "chunked"
#define HS_CHUNKED_UP "CHUNKED"
// parser sentinel lengths
#define HTTP_CHUNKED_LEN -1
// http session states
#define HTTP_SESSION_INIT 0
#define HTTP_SESSION_READ_HEADERS 1
#define HTTP_SESSION_READ_BODY 2
#define HTTP_SESSION_WRITE 3
#define HTTP_SESSION_READ_CHUNK 4
#define HTTP_SESSION_NOP 5
// http session flags
#define HTTP_RESPONSE_READY 0x4
#define HTTP_AUTOMATIC 0x8
#define HTTP_RESPONSE_PAUSED 0x10
#define HTTP_CHUNKED_RESPONSE 0x20
// http version indicators
#define HTTP_1_0 0
#define HTTP_1_1 1
// *** declarations ***
// structs
typedef struct {
int index;
int len;
int type;
} http_token_t;
typedef struct {
int content_length;
int len;
int token_start_index;
int start;
int body_start_index;
char header_count;
char content_length_i;
char transfer_encoding_i;
char flags;
char state;
char sub_state;
} http_parser_t;
typedef struct {
http_token_t* buf;
int capacity;
int size;
} http_token_dyn_t;
#ifdef EPOLL
typedef void (*epoll_cb_t)(struct epoll_event*);
#endif
typedef struct http_ev_cb_s {
#ifdef KQUEUE
void (*handler)(struct kevent* ev);
#else
epoll_cb_t handler;
#endif
} ev_cb_t;
typedef struct http_request_s {
#ifdef KQUEUE
void (*handler)(struct kevent* ev);
#else
epoll_cb_t handler;
epoll_cb_t timer_handler;
int timerfd;
#endif
void (*chunk_cb)(struct http_request_s*);
void* data;
http_parser_t parser;
int state;
int socket;
char* buf;
int bytes;
int written;
int capacity;
int timeout;
struct http_server_s* server;
http_token_t token;
http_token_dyn_t tokens;
char flags;
} http_request_t;
typedef struct http_server_s {
#ifdef KQUEUE
void (*handler)(struct kevent* ev);
#else
epoll_cb_t handler;
epoll_cb_t timer_handler;
#endif
long memused;
int socket;
int port;
int loop;
int timerfd;
socklen_t len;
void (*request_handler)(http_request_t*);
struct sockaddr_in addr;
char* date;
} http_server_t;
typedef struct http_header_s {
char const * key;
char const * value;
struct http_header_s* next;
} http_header_t;
typedef struct http_response_s {
http_header_t* headers;
char const * body;
int content_length;
int status;
} http_response_t;
typedef struct http_string_s http_string_t;
// prototypes
void hs_add_server_sock_events(struct http_server_s* serv);
void hs_server_init(struct http_server_s* serv);
void hs_delete_events(struct http_request_s* request);
void hs_add_events(struct http_request_s* request);
void hs_add_write_event(struct http_request_s* request);
void hs_exec_response_handler(http_request_t* request, void (*handler)(http_request_t*));
#ifdef KQUEUE
void hs_server_listen_cb(struct kevent* ev);
void hs_session_io_cb(struct kevent* ev);
#else
void hs_server_listen_cb(struct epoll_event* ev);
void hs_session_io_cb(struct epoll_event* ev);
void hs_server_timer_cb(struct epoll_event* ev);
void hs_request_timer_cb(struct epoll_event* ev);
#endif
// constants
char const * hs_status_text[] = {
"", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "",
//100s
"Continue", "Switching Protocols", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "",
//200s
"OK", "Created", "Accepted", "Non-Authoritative Information", "No Content",
"Reset Content", "Partial Content", "", "", "",
"", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "",
//300s
"Multiple Choices", "Moved Permanently", "Found", "See Other", "Not Modified",
"Use Proxy", "", "Temporary Redirect", "", "",
"", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "",
//400s
"Bad Request", "Unauthorized", "Payment Required", "Forbidden", "Not Found",
"Method Not Allowed", "Not Acceptable", "Proxy Authentication Required",
"Request Timeout", "Conflict",
"Gone", "Length Required", "", "Payload Too Large", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "",
//500s
"Internal Server Error", "Not Implemented", "Bad Gateway", "Service Unavailable",
"Gateway Timeout", "", "", "", "", ""
"", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", ""
};
// *** http parser ***
#define HS_P_MATCH_HEADER(up, low, i) \
if ((c == up[(int)i] || c == low[(int)i]) && i < (char)(sizeof(up) - 1)) i++;
http_token_t hs_parse_error(http_parser_t* parser, int subtype) {
parser->len = 0;
parser->state = HTTP_PARSE_ERROR;
http_token_t token;
token.index = subtype;
token.type = HTTP_PARSE_ERROR;
return token;
}
http_token_t http_parse(http_parser_t* parser, char* input, int n) {
for (int i = parser->start; i < n; ++i, parser->start = i + 1, parser->len++) {
char c = input[i];
switch (parser->state) {
case HTTP_METHOD:
if (c == ' ') {
http_token_t token;
token.index = parser->token_start_index;
token.type = parser->state;
token.len = parser->len;
parser->state = HTTP_TARGET;
parser->len = 0;
parser->token_start_index = i + 1;
return token;
}
break;
case HTTP_TARGET:
if (c == ' ') {
http_token_t token;
token.index = parser->token_start_index;
token.type = parser->state;
token.len = parser->len;
parser->state = HTTP_VERSION;
parser->token_start_index = i + 1;
parser->len = 0;
return token;
}
break;
case HTTP_VERSION:
if (c == '\r') {
parser->sub_state = HTTP_CR;
http_token_t token;
token.index = parser->token_start_index;
token.type = HTTP_VERSION;
token.len = parser->len;
return token;
} else if (parser->sub_state == HTTP_CR && c == '\n') {
parser->sub_state = 0;
parser->len = 0;
parser->token_start_index = i + 1;
parser->state = HTTP_HEADER_KEY;
}
break;
case HTTP_HEADER_KEY:
if (c == ':') {
parser->state = HTTP_HEADER_VALUE;
parser->sub_state = HTTP_LWS;
if (parser->len == parser->content_length_i + 1) {
HTTP_FLAG_SET(parser->flags, HS_PF_CONTENT_LENGTH);
} else if (parser->len == parser->transfer_encoding_i + 1) {
HTTP_FLAG_SET(parser->flags, HS_PF_TRANSFER_ENCODING);
}
parser->content_length_i = 0;
parser->transfer_encoding_i = 0;
http_token_t token;
token.index = parser->token_start_index;
token.type = HTTP_HEADER_KEY;
token.len = parser->len - 1;
return token;
}
HS_P_MATCH_HEADER(
HS_CONTENT_LENGTH_UP,
HS_CONTENT_LENGTH_LOW,
parser->content_length_i
)
HS_P_MATCH_HEADER(
HS_TRANSFER_ENCODING_UP,
HS_TRANSFER_ENCODING_LOW,
parser->transfer_encoding_i
)
break;
case HTTP_HEADER_VALUE:
if (parser->sub_state == HTTP_LWS && (c == ' ' || c == '\t' || c == '\r' || c == '\n')) {
continue;
} else if (parser->sub_state == HTTP_LWS) {
parser->sub_state = 0;
parser->len = 0;
parser->token_start_index = i;
if (HTTP_FLAG_CHECK(parser->flags, HS_PF_CONTENT_LENGTH)) {
parser->content_length *= 10;
parser->content_length += c - '0';
} else if (HTTP_FLAG_CHECK(parser->flags, HS_PF_TRANSFER_ENCODING)) {
HS_P_MATCH_HEADER(HS_CHUNKED_UP, HS_CHUNKED_LOW, parser->transfer_encoding_i)
}
} else if (parser->sub_state != HTTP_LWS && c == '\r') {
parser->sub_state = HTTP_CR;
parser->state = HTTP_HEADER_END;
HTTP_FLAG_CLEAR(parser->flags, HS_PF_TRANSFER_ENCODING);
HTTP_FLAG_CLEAR(parser->flags, HS_PF_CONTENT_LENGTH);
if (parser->len == parser->transfer_encoding_i) {
HTTP_FLAG_SET(parser->flags, HS_PF_CHUNKED);
}
parser->transfer_encoding_i = 0;
if (parser->header_count == HTTP_MAX_HEADER_COUNT) {
return hs_parse_error(parser, HTTP_ERR_BAD_REQUEST);
}
parser->header_count++;
http_token_t token;
token.index = parser->token_start_index;
token.type = HTTP_HEADER_VALUE;
token.len = parser->len;
return token;
} else if (HTTP_FLAG_CHECK(parser->flags, HS_PF_CONTENT_LENGTH)) {
int64_t new_content_length = parser->content_length * 10l;
new_content_length += c - '0';
if (new_content_length > HTTP_MAX_CONTENT_LENGTH) {
return hs_parse_error(parser, HTTP_ERR_PAYLOAD_TOO_LARGE);
} else {
parser->content_length = (int)new_content_length;
}
} else if (HTTP_FLAG_CHECK(parser->flags, HS_PF_TRANSFER_ENCODING)) {
HS_P_MATCH_HEADER(HS_CHUNKED_UP, HS_CHUNKED_LOW, parser->transfer_encoding_i)
}
break;
case HTTP_HEADER_END:
if (parser->sub_state == 0 && c == '\r') {
parser->sub_state = HTTP_CR;
} else if (parser->sub_state == HTTP_CR && c == '\n') {
parser->sub_state = HTTP_CRLF;
} else if (parser->sub_state == HTTP_CRLF && c == '\r') {
parser->sub_state = 0;
parser->state = HTTP_BODY;
http_token_t token;
token.index = i + 2;
parser->body_start_index = token.index;
token.type = HTTP_BODY;
if (HTTP_FLAG_CHECK(parser->flags, HS_PF_CHUNKED)) {
token.len = HTTP_CHUNKED_LEN;
} else {
token.len = parser->content_length;
}
parser->start++;
return token;
} else if (parser->sub_state == HTTP_CRLF && c != '\r') {
parser->sub_state = 0;
parser->len = 0;
parser->token_start_index = i;
i--;
parser->state = HTTP_HEADER_KEY;
}
break;
}
if (parser->len >= HTTP_MAX_TOKEN_LENGTH && parser->state != HTTP_BODY) {
return hs_parse_error(parser, HTTP_ERR_BAD_REQUEST);
}
}
http_token_t token = { 0, 0, 0 };
token.type = HTTP_NONE;
return token;
}
// When we detect that the full chunk exists in the read buffer we can
// immediately emit the HTTP_CHUNK_BODY token and skip reading forward to the
// end of the chunk
http_token_t http_gen_body_token(http_parser_t* parser) {
http_token_t token;
token.index = parser->token_start_index;
token.type = HTTP_CHUNK_BODY;
token.len = parser->content_length;
parser->start = parser->token_start_index + parser->content_length;
parser->len = parser->content_length;
parser->state = HTTP_CHUNK_BODY_END;
return token;
}
http_token_t http_chunk_parse(http_request_t* request, char* input, int n) {
http_parser_t* parser = &request->parser;
for (int i = parser->start; i < n; ++i, parser->start = i + 1, parser->len++) {
char c = input[i];
int remaining = n - (i + 1);
switch (parser->state) {
case HTTP_CHUNK_SIZE:
if (c == ';') {
parser->state = HTTP_CHUNK_EXTN;
} else if (c == '\n') {
parser->token_start_index = i + 1;
parser->len = 0;
if (remaining >= parser->content_length) {
// Full chunk exists in buffer
return http_gen_body_token(parser);
}
parser->state = HTTP_CHUNK_BODY;
} else if (c == '\r') {
break;
} else if (c >= 'A' && c <= 'F') {
parser->content_length *= 0x10;
parser->content_length += c - 55;
} else if (c >= 'a' && c <= 'f') {
parser->content_length *= 0x10;
parser->content_length += c - 87;
} else if (c >= '0' && c <= '9') {
parser->content_length *= 0x10;
parser->content_length += c - '0';
}
break;
case HTTP_CHUNK_EXTN:
if (c == '\n') {
if (remaining >= parser->content_length) {
// Full chunk exists in buffer
parser->token_start_index = i + 1;
return http_gen_body_token(parser);
}
parser->token_start_index = i + 1;
parser->state = HTTP_CHUNK_BODY;
}
break;
case HTTP_CHUNK_BODY:
if (remaining >= parser->content_length) {
// The remaining portion of the chunk exists in the read buffer
return http_gen_body_token(parser);
}
break;
case HTTP_CHUNK_BODY_END:
if (c == '\n') {
parser->state = HTTP_CHUNK_SIZE;
parser->content_length = 0;
parser->len = 0;
parser->token_start_index = i + 1;
}
break;
}
}
// This code is reached when we come to the end of our read buffer and no
// token has been emitted during this call. If we are part way through parsing
// a token at the end of the buffer or the next token would require us to grow
// the buffer then we want to reset the parser to overwrite old chunks so that
// we don't need to grow the buffer.
if (parser->token_start_index != parser->body_start_index) {
// Next time, start parsing as if the current token has been shifted to the
// start of the http body.
parser->start = parser->body_start_index + parser->len - 1;
int tsi = parser->token_start_index;
parser->token_start_index = parser->body_start_index;
// This will make the next read overwrite the old bytes
request->bytes = parser->start;
// If parser->len is 1 then there is no current partial token. This is kind
// of ugly because len gets incremented in the for loop before we get here
// so we need to check for 1 instead of 0
if (parser->len > 1) {
char* dst = input + parser->body_start_index;
char const* src = input + tsi;
// Copy partial token to beginning of body
memcpy(dst, src, n - tsi);
}
}
http_token_t token = { 0, 0, 0 };
token.type = HTTP_NONE;
return token;
}
void http_parse_start_chunk_mode(http_parser_t* parser) {
parser->token_start_index = parser->start;
parser->content_length = 0;
parser->state = HTTP_CHUNK_SIZE;
}
// *** http server ***
void http_token_dyn_push(http_token_dyn_t* dyn, http_token_t a) {
if (dyn->size == dyn->capacity) {
dyn->capacity *= 2;
dyn->buf = (http_token_t*)realloc(dyn->buf, dyn->capacity * sizeof(http_token_t));
assert(dyn->buf != NULL);
}
dyn->buf[dyn->size] = a;
dyn->size++;
}
void http_token_dyn_init(http_token_dyn_t* dyn, int capacity) {
dyn->buf = (http_token_t*)malloc(sizeof(http_token_t) * capacity);
assert(dyn->buf != NULL);
dyn->size = 0;
dyn->capacity = capacity;
}
void hs_bind_localhost(int s, struct sockaddr_in* addr, int port) {
addr->sin_family = AF_INET;
addr->sin_addr.s_addr = INADDR_ANY;
addr->sin_port = htons(port);
int rc = bind(s, (struct sockaddr *)addr, sizeof(struct sockaddr_in));;
if (rc < 0) {
exit(1);
}
}
int hs_read_client_socket(http_request_t* session) {
if (!session->buf) {
session->server->memused += HTTP_REQUEST_BUF_SIZE;
session->buf = (char*)calloc(1, HTTP_REQUEST_BUF_SIZE);
assert(session->buf != NULL);
session->capacity = HTTP_REQUEST_BUF_SIZE;
http_token_dyn_init(&session->tokens, 32);
}
int bytes;
do {
bytes = read(
session->socket,
session->buf + session->bytes,
session->capacity - session->bytes
);
if (bytes > 0) session->bytes += bytes;
if (session->bytes == session->capacity) {
session->server->memused -= session->capacity;
session->capacity *= 2;
session->server->memused += session->capacity;
session->buf = (char*)realloc(session->buf, session->capacity);
assert(session->buf != NULL);
}
} while (bytes > 0);
return bytes == 0 ? 0 : 1;
}
int hs_write_client_socket(http_request_t* session) {
int bytes = write(
session->socket,
session->buf + session->written,
session->bytes - session->written
);
if (bytes > 0) session->written += bytes;
return errno == EPIPE ? 0 : 1;
}
void hs_free_buffer(http_request_t* session) {
if (session->buf) {
free(session->buf);
session->server->memused -= session->capacity;
session->buf = NULL;
free(session->tokens.buf);
session->tokens.buf = NULL;
}
}
void hs_parse_tokens(http_request_t* session) {
http_token_t token;
int chunk_start = 0;
do {
token = http_parse(&session->parser, session->buf, session->bytes);
if (token.type != HTTP_NONE) {
session->token = token;
http_token_dyn_push(&session->tokens, token);
}
chunk_start = token.type == HTTP_BODY && token.len == HTTP_CHUNKED_LEN;
} while (token.type != HTTP_NONE && !chunk_start);
}
void hs_init_session(http_request_t* session) {
session->flags = 0;
session->flags |= HTTP_AUTOMATIC;
session->parser = (http_parser_t){ };
session->bytes = 0;
session->written = 0;
session->buf = NULL;
session->token.len = 0;
session->token.index = 0;
session->token.type = HTTP_NONE;
}
int hs_parsing_headers(http_request_t* request) {
return request->token.type != HTTP_BODY;
}
int hs_reading_body(http_request_t* request) {
if (
request->token.type != HTTP_BODY ||
request->token.len == 0 ||
request->token.len == HTTP_CHUNKED_LEN
) {
return 0;
}
int size = request->token.index + request->token.len;
return request->bytes < size;
}
void hs_end_session(http_request_t* session) {
hs_delete_events(session);
close(session->socket);
hs_free_buffer(session);
free(session);
}
void hs_reset_timeout(http_request_t* request, int time) {
request->timeout = time;
}
void hs_write_response(http_request_t* request) {
if (!hs_write_client_socket(request)) { return hs_end_session(request); }
if (request->written != request->bytes) {
// All bytes of the body were not written and we need to wait until the
You can’t perform that action at this time.
