-
Notifications
You must be signed in to change notification settings - Fork 2
/
cepresso.h
1949 lines (1678 loc) · 62.6 KB
/
cepresso.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
/*
* Copyright (c) 2022 XXIV
*
* 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.
*/
#ifndef __LIB_CEPRESSO_H__
#define __LIB_CEPRESSO_H__
#ifndef SO_REUSEPORT
#define SO_REUSEPORT 15
#endif
// * * * * * * * * * * * * * * * * * "httpserver.h" * * * * * * * * * * * * * * * * *
// 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 *));
// 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_server_set_userdata(struct http_server_s *server, void *data);
// 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. By default it will listen on all interface. For the second variant
// provide the IP address of the interface to listen on, or NULL for any.
int http_server_listen(struct http_server_s *server);
int http_server_listen_addr(struct http_server_s *server, const char *ipaddr);
// 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. By default it will
// listen on all interface. For the second variant provide the IP address of
// the interface to listen on, or NULL for any.
int http_server_listen_poll(struct http_server_s *server);
int http_server_listen_addr_poll(struct http_server_s *server, const char *ipaddr);
// 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 1 if the flag is set and false otherwise. The flags that can be
// queried are listed below
int http_request_has_flag(struct http_request_s *request, int flag);
// This flag will be set when the request body is chunked or the body is too
// large to fit in memory are once. This means that the http_request_read_chunk
// function must be used to read the body piece by piece.
#define HTTP_FLG_STREAMED 0x1
// 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 that was set with http_request_set_userdata.
void *http_request_userdata(struct http_request_s *request);
// Retrieve the opaque data pointer that was set with http_server_set_userdata.
void *http_request_server_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 or the body is too big to fit in
// memory all at once you cannot read the body in the typical way. Instead you
// need to call this function to read one chunk at a time. To check if the
// request requires this type of reading you can call the http_request_has_flag
// function to check if the HTTP_FLG_STREAMED flag is set. To read a streamed body
// 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);
#define http_request_read_body http_request_read_chunk
#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>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <netinet/in.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 1024
#define HTTP_REQUEST_TIMEOUT 20
#define HTTP_KEEP_ALIVE_TIMEOUT 120
#define HTTP_MAX_TOKEN_LENGTH 8192 // 8kb
#define HTTP_MAX_TOTAL_EST_MEM_USAGE 4294967296 // 4gb
#define HTTP_MAX_REQUEST_BUF_SIZE 8388608 // 8mb
#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)
// stream flags
#define HS_SF_CONSUMED 0x1
// parser flags
#define HS_PF_IN_CONTENT_LEN 0x1
#define HS_PF_IN_TRANSFER_ENC 0x2
#define HS_PF_CHUNKED 0x4
#define HS_PF_CKEND 0x8
#define HS_PF_REQ_END 0x10
// http session states
#define HTTP_SESSION_INIT 0
#define HTTP_SESSION_READ 1
#define HTTP_SESSION_WRITE 2
#define HTTP_SESSION_NOP 3
// http session flags
#define HTTP_END_SESSION 0x2
#define HTTP_AUTOMATIC 0x8
#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 {
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 {
char *buf;
int64_t total_bytes;
int32_t capacity;
int32_t length;
int32_t index;
int32_t anchor;
http_token_t token;
uint8_t flags;
} hs_stream_t;
typedef struct {
int64_t content_length;
int64_t body_consumed;
int16_t match_index;
int16_t header_count;
int8_t state;
int8_t meta;
} http_parser_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;
hs_stream_t stream;
http_parser_t parser;
int state;
int socket;
int timeout;
struct http_server_s *server;
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
int64_t memused;
int socket;
int port;
int loop;
int timerfd;
socklen_t len;
void (*request_handler)(http_request_t *);
struct sockaddr_in addr;
void *data;
char date[32];
} 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;
// enums
enum hs_token {
HS_TOK_NONE, HS_TOK_METHOD, HS_TOK_TARGET, HS_TOK_VERSION,
HS_TOK_HEADER_KEY, HS_TOK_HEADER_VAL, HS_TOK_CHUNK_BODY, HS_TOK_BODY,
HS_TOK_BODY_STREAM, HS_TOK_REQ_END, HS_TOK_EOF, HS_TOK_ERROR
};
enum hs_state {
ST, MT, MS, TR, TS, VN, RR, RN, HK, HS, HV, HR, HE,
ER, HN, BD, CS, CB, CE, CR, CN, CD, C1, C2, BR, HS_STATE_LEN
};
enum hs_char_type {
HS_SPC, HS_NL, HS_CR, HS_COLN, HS_TAB, HS_SCOLN,
HS_DIGIT, HS_HEX, HS_ALPHA, HS_TCHAR, HS_VCHAR, HS_ETC, HS_CHAR_TYPE_LEN
};
enum hs_meta_state {
M_WFK, M_ANY, M_MTE, M_MCL, M_CLV, M_MCK, M_SML, M_CHK, M_BIG, M_ZER, M_CSZ,
M_CBD, M_LST, M_STR, M_SEN, M_BDY, M_END, M_ERR
};
enum hs_meta_type {
HS_META_NOT_CONTENT_LEN, HS_META_NOT_TRANSFER_ENC, HS_META_END_KEY,
HS_META_END_VALUE, HS_META_END_HEADERS, HS_META_LARGE_BODY,
HS_META_TYPE_LEN
};
#define HS_META_NOT_CHUNKED 0
#define HS_META_NON_ZERO 0
#define HS_META_END_CHK_SIZE 1
#define HS_META_END_CHUNK 2
#define HS_META_NEXT 0
// 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_process_tokens(http_request_t *request);
#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", "", "", "", "", ""
"", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", ""
};
static int const hs_transitions[] = {
// A-Z G-Z
// spc \n \r : \t ; 0-9 a-f g-z tch vch etc
/* ST start */ BR, BR, BR, BR, BR, BR, BR, MT, MT, MT, BR, BR,
/* MT method */ MS, BR, BR, BR, BR, BR, MT, MT, MT, MT, BR, BR,
/* MS methodsp */ BR, BR, BR, BR, BR, BR, TR, TR, TR, TR, TR, BR,
/* TR target */ TS, BR, BR, TR, BR, TR, TR, TR, TR, TR, TR, BR,
/* TS targetsp */ BR, BR, BR, BR, BR, BR, VN, VN, VN, VN, VN, BR,
/* VN version */ BR, BR, RR, BR, BR, BR, VN, VN, VN, VN, VN, BR,
/* RR rl \r */ BR, RN, BR, BR, BR, BR, BR, BR, BR, BR, BR, BR,
/* RN rl \n */ BR, BR, BR, BR, BR, BR, HK, HK, HK, HK, BR, BR,
/* HK headkey */ BR, BR, BR, HS, BR, BR, HK, HK, HK, HK, BR, BR,
/* HS headspc */ HS, HS, HS, HV, HS, HV, HV, HV, HV, HV, HV, BR,
/* HV headval */ HV, BR, HR, HV, HV, HV, HV, HV, HV, HV, HV, BR,
/* HR head\r */ BR, HE, BR, BR, BR, BR, BR, BR, BR, BR, BR, BR,
/* HE head\n */ BR, BR, ER, BR, BR, BR, HK, HK, HK, HK, BR, BR,
/* ER hend\r */ BR, HN, BR, BR, BR, BR, BR, BR, BR, BR, BR, BR,
/* HN hend\n */ BD, BD, BD, BD, BD, BD, BD, BD, BD, BD, BD, BD,
/* BD body */ BD, BD, BD, BD, BD, BD, BD, BD, BD, BD, BD, BD,
/* CS chksz */ BR, BR, CR, BR, BR, CE, CS, CS, BR, BR, BR, BR,
/* CB chkbd */ CB, CB, CB, CB, CB, CB, CB, CB, CB, CB, CB, CB,
/* CE chkext */ BR, BR, CR, CE, CE, CE, CE, CE, CE, CE, CE, BR,
/* CR chksz\r */ BR, CN, BR, BR, BR, BR, BR, BR, BR, BR, BR, BR,
/* CN chksz\n */ CB, CB, CB, CB, CB, CB, CB, CB, CB, CB, CB, CB,
/* CD chkend */ BR, BR, C1, BR, BR, BR, BR, BR, BR, BR, BR, BR,
/* C1 chkend\r */ BR, C2, BR, BR, BR, BR, BR, BR, BR, BR, BR, BR,
/* C2 chkend\n */ BR, BR, BR, BR, BR, BR, CS, CS, BR, BR, BR, BR
};
static int const hs_meta_transitions[] = {
// no chk
// not cl not te endkey endval end h toobig
/* WFK wait */ M_WFK, M_WFK, M_WFK, M_ANY, M_END, M_ERR,
/* ANY matchkey */ M_MTE, M_MCL, M_WFK, M_ERR, M_END, M_ERR,
/* MTE matchte */ M_MTE, M_WFK, M_MCK, M_ERR, M_ERR, M_ERR,
/* MCL matchcl */ M_WFK, M_MCL, M_CLV, M_ERR, M_ERR, M_ERR,
/* CLV clvalue */ M_ERR, M_ERR, M_ERR, M_SML, M_ERR, M_ERR,
/* MCK matchchk */ M_WFK, M_ERR, M_ERR, M_CHK, M_ERR, M_ERR,
/* SML smallbdy */ M_SML, M_SML, M_SML, M_SML, M_BDY, M_BIG,
/* CHK chunkbdy */ M_CHK, M_CHK, M_CHK, M_CHK, M_ZER, M_ERR,
/* BIG bigbody */ M_BIG, M_BIG, M_BIG, M_BIG, M_STR, M_ERR,
// *** chunked body ***
// nonzer endsz endchk
/* ZER zerochk */ M_CSZ, M_LST, M_ERR, M_ERR, M_ERR, M_ERR,
/* CSZ chksize */ M_CSZ, M_CBD, M_ERR, M_ERR, M_ERR, M_ERR,
/* CBD readchk */ M_CBD, M_CBD, M_ZER, M_ERR, M_ERR, M_ERR,
/* LST lastchk */ M_LST, M_END, M_END, M_ERR, M_ERR, M_ERR,
// *** streamed body ***
// next
/* STR readstr */ M_SEN, M_ERR, M_ERR, M_ERR, M_ERR, M_ERR,
/* SEN strend */ M_END, M_ERR, M_ERR, M_ERR, M_ERR, M_ERR,
// *** small body ***
// next
/* BDY readbody */ M_END, M_ERR, M_ERR, M_ERR, M_ERR, M_ERR,
/* END reqend */ M_WFK, M_ERR, M_ERR, M_ERR, M_ERR, M_ERR
};
static int const hs_ctype[] = {
HS_ETC, HS_ETC, HS_ETC, HS_ETC, HS_ETC, HS_ETC, HS_ETC,
HS_ETC, HS_ETC, HS_TAB, HS_NL, HS_ETC, HS_ETC, HS_CR,
HS_ETC, HS_ETC, HS_ETC, HS_ETC, HS_ETC, HS_ETC, HS_ETC,
HS_ETC, HS_ETC, HS_ETC, HS_ETC, HS_ETC, HS_ETC, HS_ETC,
HS_ETC, HS_ETC, HS_ETC, HS_ETC, HS_SPC, HS_TCHAR, HS_VCHAR,
HS_TCHAR, HS_TCHAR, HS_TCHAR, HS_TCHAR, HS_TCHAR, HS_VCHAR, HS_VCHAR,
HS_TCHAR, HS_TCHAR, HS_TCHAR, HS_TCHAR, HS_TCHAR, HS_VCHAR, HS_DIGIT,
HS_DIGIT, HS_DIGIT, HS_DIGIT, HS_DIGIT, HS_DIGIT, HS_DIGIT, HS_DIGIT,
HS_DIGIT, HS_DIGIT, HS_COLN, HS_SCOLN, HS_VCHAR, HS_VCHAR, HS_VCHAR,
HS_VCHAR, HS_VCHAR, HS_HEX, HS_HEX, HS_HEX, HS_HEX, HS_HEX,
HS_HEX, HS_ALPHA, HS_ALPHA, HS_ALPHA, HS_ALPHA, HS_ALPHA, HS_ALPHA,
HS_ALPHA, HS_ALPHA, HS_ALPHA, HS_ALPHA, HS_ALPHA, HS_ALPHA, HS_ALPHA,
HS_ALPHA, HS_ALPHA, HS_ALPHA, HS_ALPHA, HS_ALPHA, HS_ALPHA, HS_ALPHA,
HS_VCHAR, HS_VCHAR, HS_VCHAR, HS_TCHAR, HS_TCHAR, HS_TCHAR, HS_HEX,
HS_HEX, HS_HEX, HS_HEX, HS_HEX, HS_HEX, HS_ALPHA, HS_ALPHA,
HS_ALPHA, HS_ALPHA, HS_ALPHA, HS_ALPHA, HS_ALPHA, HS_ALPHA, HS_ALPHA,
HS_ALPHA, HS_ALPHA, HS_ALPHA, HS_ALPHA, HS_ALPHA, HS_ALPHA, HS_ALPHA,
HS_ALPHA, HS_ALPHA, HS_ALPHA, HS_ALPHA, HS_VCHAR, HS_TCHAR, HS_VCHAR,
HS_TCHAR, HS_ETC
};
static int const hs_token_start_states[] = {
//ST MT MS TR TS VN RR RN HK
0, HS_TOK_METHOD, 0, HS_TOK_TARGET, 0, HS_TOK_VERSION, 0, 0, HS_TOK_HEADER_KEY,
//HS HV HR HE ER HN BD CS CB CE CR CN
0, HS_TOK_HEADER_VAL, 0, 0, 0, 0, HS_TOK_BODY, 0, HS_TOK_CHUNK_BODY, 0, 0, 0,
//CD C1 C2
0, 0, 0,
};
// *** input stream ***
int hs_stream_read_socket(hs_stream_t *stream, int socket, int64_t *memused) {
if (stream->index < stream->length) return 1;
if (!stream->buf) {
*memused += HTTP_REQUEST_BUF_SIZE;
stream->buf = (char *) calloc(1, HTTP_REQUEST_BUF_SIZE);
assert(stream->buf != NULL);
stream->capacity = HTTP_REQUEST_BUF_SIZE;
}
int bytes;
do {
bytes = read(
socket,
stream->buf + stream->length,
stream->capacity - stream->length
);
if (bytes > 0) {
stream->length += bytes;
stream->total_bytes += bytes;
}
if (
stream->length == stream->capacity &&
stream->capacity != HTTP_MAX_REQUEST_BUF_SIZE
) {
*memused -= stream->capacity;
stream->capacity *= 2;
if (stream->capacity > HTTP_MAX_REQUEST_BUF_SIZE) {
stream->capacity = HTTP_MAX_REQUEST_BUF_SIZE;
}
*memused += stream->capacity;
stream->buf = (char *) realloc(stream->buf, stream->capacity);
assert(stream->buf != NULL);
}
} while (bytes > 0 && stream->capacity < HTTP_MAX_REQUEST_BUF_SIZE);
return bytes == 0 ? 0 : 1;
}
int hs_stream_next(hs_stream_t *stream, char *c) {
HTTP_FLAG_CLEAR(stream->flags, HS_SF_CONSUMED);
if (stream->index >= stream->length) return 0;
*c = stream->buf[stream->index];
return 1;
}
void hs_stream_consume(hs_stream_t *stream) {
if (HTTP_FLAG_CHECK(stream->flags, HS_SF_CONSUMED)) return;
HTTP_FLAG_SET(stream->flags, HS_SF_CONSUMED);
stream->index++;
int new_len = stream->token.len + 1;
stream->token.len = stream->token.type == 0 ? 0 : new_len;
}
void hs_stream_begin_token(hs_stream_t *stream, int token_type) {
stream->token.index = stream->index;
stream->token.type = token_type;
}
int hs_stream_jump(hs_stream_t *stream, int offset) {
HTTP_FLAG_SET(stream->flags, HS_SF_CONSUMED);
if (stream->index + offset > stream->length) return 0;
stream->index += offset;
int new_len = stream->token.len + offset;
stream->token.len = stream->token.type == 0 ? 0 : new_len;
return 1;
}
int hs_stream_jumpall(hs_stream_t *stream) {
int offset = stream->length - stream->index;
stream->index += offset;
int new_len = stream->token.len + offset;
HTTP_FLAG_SET(stream->flags, HS_SF_CONSUMED);
stream->token.len = stream->token.type == 0 ? 0 : new_len;
return offset;
}
void hs_stream_anchor(hs_stream_t *stream) {
stream->anchor = stream->index;
}
http_token_t hs_stream_emit(hs_stream_t *stream) {
http_token_t token = stream->token;
http_token_t none = {0, 0, 0};
stream->token = none;
return token;
}
http_token_t hs_stream_current_token(hs_stream_t *stream) {
return stream->token;
}
int hs_stream_can_contain(hs_stream_t *stream, int64_t size) {
return HTTP_MAX_REQUEST_BUF_SIZE - stream->index + 1 >= size;
}
void hs_stream_shift(hs_stream_t *stream) {
if (stream->token.index == stream->anchor) return;
if (stream->token.len > 0) {
char *dst = stream->buf + stream->anchor;
char const *src = stream->buf + stream->token.index;
int bytes = stream->length - stream->token.index;
memcpy(dst, src, bytes);
}
stream->token.index = stream->anchor;
stream->index = stream->token.len + stream->anchor;
stream->length = stream->anchor + stream->token.len;
}
// *** http parser ***
void hs_trigger_meta(http_parser_t *parser, int event) {
int to = hs_meta_transitions[parser->meta * HS_META_TYPE_LEN + event];
parser->meta = to;
}
#define HS_MATCH(str, meta) \
in_bounds = parser->match_index < (int)sizeof(str) - 1; \
m = in_bounds ? str[parser->match_index] : m; \
low = c >= 'A' && c <= 'Z' ? c + 32 : c; \
if (low != m) hs_trigger_meta(parser, meta);
http_token_t hs_transition_action(
http_parser_t *parser,
hs_stream_t *stream,
char c,
int8_t from,
int8_t to
) {
http_token_t emitted = {0, 0, 0};
if (from == HN) {
hs_stream_anchor(stream);
}
if (from != to) {
int type = hs_token_start_states[to];
if (type != HS_TOK_NONE) hs_stream_begin_token(stream, type);
if (from == CS) hs_trigger_meta(parser, HS_META_END_CHK_SIZE);
if (to == HK) {
parser->header_count++;
if (parser->header_count > HTTP_MAX_HEADER_COUNT) {
emitted.type = HS_TOK_ERROR;
}
} else if (to == HS) {
hs_trigger_meta(parser, HS_META_END_KEY);
emitted = hs_stream_emit(stream);
}
parser->match_index = 0;
}
char low, m = '\0';
int in_bounds = 0;
int body_left = 0;
switch (to) {
case MS:
case TS:
emitted = hs_stream_emit(stream);
break;
case RR:
case HR:
hs_trigger_meta(parser, HS_META_END_VALUE);
emitted = hs_stream_emit(stream);
break;
case HK:
HS_MATCH("transfer-encoding", HS_META_NOT_TRANSFER_ENC)
HS_MATCH("content-length", HS_META_NOT_CONTENT_LEN)
parser->match_index++;
break;
case HV:
if (parser->meta == M_MCK) {
HS_MATCH("chunked", HS_META_NOT_CHUNKED)
parser->match_index++;
} else if (parser->meta == M_CLV) {
parser->content_length *= 10;
parser->content_length += c - '0';
}
break;
case HN:
if (parser->meta == M_SML && !hs_stream_can_contain(stream, parser->content_length)) {
hs_trigger_meta(parser, HS_META_LARGE_BODY);
}
if (parser->meta == M_BIG || parser->meta == M_CHK) {
emitted.type = HS_TOK_BODY_STREAM;
}
//if (parser->meta == M_CHK) parser->state = CS;
hs_trigger_meta(parser, HS_META_END_HEADERS);
if (parser->content_length == 0 && parser->meta == M_BDY) parser->meta = M_END;
if (parser->meta == M_END) {
emitted.type = HS_TOK_BODY;
}
break;
case CS:
if (c != '0') hs_trigger_meta(parser, HS_META_NON_ZERO);
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 CB:
case BD:
if (parser->meta == M_STR) hs_stream_begin_token(stream, HS_TOK_CHUNK_BODY);
body_left = parser->content_length - parser->body_consumed;
if (hs_stream_jump(stream, body_left)) {
emitted = hs_stream_emit(stream);
hs_trigger_meta(parser, HS_META_NEXT);
if (to == CB) parser->state = CD;
parser->content_length = 0;
parser->body_consumed = 0;
} else {
parser->body_consumed += hs_stream_jumpall(stream);
if (parser->meta == M_STR) {
emitted = hs_stream_emit(stream);
hs_stream_shift(stream);
}
}
break;
case C2:
hs_trigger_meta(parser, HS_META_END_CHUNK);
break;
case BR:
emitted.type = HS_TOK_ERROR;
break;
}
return emitted;
}
http_token_t hs_meta_emit(http_parser_t *parser) {
http_token_t token = {0, 0, 0};
switch (parser->meta) {
case M_SEN:
token.type = HS_TOK_CHUNK_BODY;
hs_trigger_meta(parser, HS_META_NEXT);
break;
case M_END:
token.type = HS_TOK_REQ_END;
memset(parser, 0, sizeof(http_parser_t));
break;
}
return token;
}
http_token_t http_parse(http_parser_t *parser, hs_stream_t *stream) {
char c = 0;
http_token_t token = hs_meta_emit(parser);
if (token.type != HS_TOK_NONE) return token;
while (hs_stream_next(stream, &c)) {
int type = c < 0 ? HS_ETC : hs_ctype[(int) c];
int to = hs_transitions[parser->state * HS_CHAR_TYPE_LEN + type];
if (parser->meta == M_ZER && parser->state == HN && to == BD) {
to = CS;
}
int from = parser->state;
parser->state = to;
http_token_t emitted = hs_transition_action(parser, stream, c, from, to);
hs_stream_consume(stream);
if (emitted.type != HS_TOK_NONE) return emitted;
}
if (parser->state == CB) hs_stream_shift(stream);
token = hs_meta_emit(parser);
http_token_t current = hs_stream_current_token(stream);
if (
current.type != HS_TOK_CHUNK_BODY &&
current.type != HS_TOK_BODY &&
current.len > HTTP_MAX_TOKEN_LENGTH
) {
token.type = HS_TOK_ERROR;
}
return token;
}
// *** 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, const char *ipaddr, int port) {
addr->sin_family = AF_INET;
if (ipaddr == NULL) {
addr->sin_addr.s_addr = INADDR_ANY;
} else {
addr->sin_addr.s_addr = inet_addr(ipaddr);
}
addr->sin_port = htons(port);
int rc = bind(s, (struct sockaddr *) addr, sizeof(struct sockaddr_in));
if (rc < 0) {
exit(1);
}
}
int hs_write_client_socket(http_request_t *session) {
int bytes = write(
session->socket,
session->stream.buf + session->stream.total_bytes,
session->stream.length - session->stream.total_bytes
);
if (bytes > 0) session->stream.total_bytes += bytes;
return errno == EPIPE ? 0 : 1;
}
void hs_free_buffer(http_request_t *session) {
if (session->stream.buf) {
free(session->stream.buf);
session->server->memused -= session->stream.capacity;
session->stream.buf = NULL;
}
}
void hs_init_session(http_request_t *session) {
session->flags = HTTP_AUTOMATIC;
session->parser = (http_parser_t) {};
session->stream = (hs_stream_t) {};
if (session->tokens.buf) {
free(session->tokens.buf);
session->tokens.buf = NULL;
}
http_token_dyn_init(&session->tokens, 32);
}
void hs_end_session(http_request_t *session) {
hs_delete_events(session);
close(session->socket);
hs_free_buffer(session);
free(session->tokens.buf);
session->tokens.buf = NULL;
free(session);
}
void hs_reset_timeout(http_request_t *request, int time) {
request->timeout = time;