-
Notifications
You must be signed in to change notification settings - Fork 4
/
iwn_http_server.c
2674 lines (2394 loc) · 78.3 KB
/
iwn_http_server.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* HTTP protocol parser is based on https://github.com/jeremycw/httpserver.h MIT code.
*/
#include "iwn_http_server_internal.h"
#include "iwn_poller_adapter.h"
#include "iwn_url.h"
#include "iwn_scheduler.h"
#include "poller/iwn_direct_poller_adapter.h"
#include "ssl/iwn_brssl_poller_adapter.h"
#include <iowow/iwlog.h>
#include <iowow/iwutils.h>
#include <iowow/iwpool.h>
#include <iowow/iwxstr.h>
#include <arpa/inet.h>
#include <assert.h>
#include <stdatomic.h>
#include <ctype.h>
#include <errno.h>
#include <fcntl.h>
#include <inttypes.h>
#include <netdb.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
#include <pthread.h>
#include <stdatomic.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <sys/un.h>
#include <sys/file.h>
#include <time.h>
#include <unistd.h>
struct server {
struct iwn_http_server server;
struct iwn_http_server_spec spec;
long stime; ///< Server time second since epoch.
int fd;
int refs;
pthread_mutex_t mtx;
pthread_mutex_t mtx_ssl;
struct iwpool *pool;
char stime_text[32]; ///< Formatted as: `%a, %d %b %Y %T GMT`
volatile bool https;
};
struct token {
int index;
int len;
int type;
};
struct tokens_buf {
struct token *buf;
ssize_t capacity;
ssize_t size;
};
struct stream {
char *buf;
void (*buf_free)(void*);
struct token token;
ssize_t bytes_total;
ssize_t capacity;
ssize_t length;
ssize_t index;
ssize_t anchor;
uint8_t flags;
};
struct parser {
ssize_t content_length;
ssize_t body_consumed;
int16_t match_index;
int16_t header_count;
int8_t state;
int8_t meta;
};
struct header {
char *name;
char *value;
struct header *next;
};
struct response {
struct header *headers;
struct iwpool *pool;
const char *body;
void (*body_free)(void*);
size_t body_len;
int code;
};
struct proxy {
iwrc rc; ///< Not zero if proxy connection failed
struct iwxstr *from_endpoint_buf; ///< proxy <- proxied endpoint buffer
struct iwxstr *to_endpoint_buf; ///< proxy -> proxied endpoint buffer
const char *url_raw;
struct iwn_pairs headers; ///< Extra headers to add to the proxied request
struct iwn_url url;
pthread_mutex_t mtx;
size_t channel_buf_max_size; ///< Max size of intemediate data buffer for read/write proxy channels.
/// Default: 1048576(1MB)
uint32_t timeout_connect_sec; ///< Socket connect timeout in seconds.
uint32_t timeout_data_sec; ///< Socket data events timeout in seconds.
volatile int fd;
volatile int fd_timeout;
volatile bool connected;
volatile bool disconnected;
};
struct client {
struct iwn_http_req request;
struct iwn_poller *poller;
iwn_http_server_chunk_handler chunk_cb;
struct iwpool *pool;
iwn_on_poller_adapter_event injected_poller_evh;
struct server *server;
struct tokens_buf tokens;
struct stream stream;
struct parser parser;
struct response response;
struct proxy proxy;
struct sockaddr_storage sockaddr;
// Web-framework implementation hooks (do not use these in app)
// TODO: Review it
void *_ws_data;
void *_wf_data;
void (*_wf_on_request_dispose)(struct iwn_http_req*);
void (*_wf_on_response_headers_write)(struct iwn_http_req*);
atomic_int refs;
int fd;
uint8_t state; ///< HTTP_SESSION_{INIT,READ,WRITE,NOP}
uint8_t flags; ///< HTTP_END_SESSION,HTTP_AUTOMATIC,HTTP_CHUNKED_RESPONSE
char ip[46]; ///< Client ip address
};
// stream flags
#define HS_SF_CONSUMED 0x01U
// parser flags
#define HS_PF_IN_CONTENT_LEN 0x01U
#define HS_PF_IN_TRANSFER_ENC 0x02U
#define HS_PF_CHUNKED 0x04U
#define HS_PF_CKEND 0x08U
#define HS_PF_REQ_END 0x10U
// 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_KEEP_ALIVE 0x01U
#define HTTP_STREAMED 0x02U
#define HTTP_END_SESSION 0x04U
#define HTTP_AUTOMATIC 0x08U
#define HTTP_CHUNKED_RESPONSE 0x10U
#define HTTP_STREAM_RESPONSE 0x20U
#define HTTP_UPGRADE 0x40U
#define HTTP_HAS_CONTENT_LEN 0x80U
// http version indicators
#define HTTP_1_0 0
#define HTTP_1_1 1
#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
// uncrustify:off
enum token_e {
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 char_type_e {
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 meta_state_e {
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 meta_type_e {
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
};
enum state_e {
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
};
static const int8_t _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 const int8_t _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 const int8_t _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 int8_t const _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 BR
0, 0, 0, 0
};
static char const *_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", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", ""
};
// uncrustify:on
static iwrc _server_ref(struct server *server, struct server **out);
static void _server_unref(struct server *server);
static int64_t _proxy_client_on_ready(struct iwn_poller_adapter *pa, void *user_data, uint32_t events);
static void _noop_free(void *ptr) {
;
}
static void _server_time(struct server *server, char out_buf[32]) {
static_assert(sizeof(server->stime_text) == 32, "sizeof(server->stime) == 32");
time_t rawtime;
time(&rawtime);
pthread_mutex_lock(&server->mtx);
if (server->stime != rawtime) {
server->stime = rawtime;
struct tm *timeinfo = gmtime(&rawtime);
if (timeinfo) {
strftime(server->stime_text, sizeof(server->stime_text), "%a, %d %b %Y %T %Z", timeinfo);
} else {
out_buf[0] = '\0';
}
}
memcpy(out_buf, server->stime_text, sizeof(server->stime_text));
pthread_mutex_unlock(&server->mtx);
}
IW_INLINE void _stream_free_buffer(struct client *client) {
if (IW_UNLIKELY(client->stream.buf_free)) {
client->stream.buf_free(client->stream.buf);
} else {
free(client->stream.buf);
}
memset(&client->stream, 0, sizeof(client->stream));
}
IW_INLINE void _tokens_free_buffer(struct client *client) {
free(client->tokens.buf);
memset(&client->tokens, 0, sizeof(client->tokens));
}
IW_INLINE void _request_data_free(struct client *client) {
if (client->request.on_request_dispose) {
client->request.on_request_dispose(&client->request);
client->request.on_request_dispose = 0;
}
if (client->_wf_on_request_dispose) {
client->_wf_on_request_dispose(&client->request);
client->_wf_on_request_dispose = 0;
}
client->_wf_data = 0;
client->_ws_data = 0;
client->request.user_data = 0;
client->request.user_flags = 0;
}
static bool _stream_next(struct stream *stream, char *c) {
stream->flags &= ~HS_SF_CONSUMED;
if (stream->index >= stream->length) {
return false;
}
*c = stream->buf[stream->index];
return true;
}
static void _stream_consume(struct stream *stream) {
if (stream->flags & HS_SF_CONSUMED) {
return;
}
stream->flags |= HS_SF_CONSUMED;
stream->index++;
int nlen = stream->token.len + 1;
stream->token.len = stream->token.type ? nlen : 0;
}
static void _stream_shift(struct stream *stream) {
if (stream->token.index == stream->anchor) {
return;
}
if (stream->token.len > 0) {
char *dst = stream->buf + stream->anchor;
char *src = stream->buf + stream->token.index;
ssize_t bytes = stream->length - stream->token.index;
memcpy(dst, src, bytes);
}
stream->token.index = stream->anchor;
stream->index = stream->anchor + stream->token.len;
stream->length = stream->index;
}
IW_INLINE void _stream_anchor(struct stream *stream) {
stream->anchor = stream->index;
}
IW_INLINE void _stream_begin_token(struct stream *stream, int token_type) {
stream->token.type = token_type;
stream->token.index = stream->index;
}
IW_INLINE struct token _stream_emit(struct stream *stream) {
struct token token = stream->token;
memset(&stream->token, 0, sizeof(stream->token));
return token;
}
IW_INLINE bool _stream_can_contain(struct client *client, int64_t size) {
return client->server->spec.request_buf_max_size - client->stream.index + 1 >= size;
}
static bool _stream_jump(struct stream *stream, int offset) {
stream->flags |= HS_SF_CONSUMED;
if (stream->index + offset > stream->length) {
return false;
}
stream->index += offset;
int nlen = stream->token.len + offset;
stream->token.len = stream->token.type == 0 ? 0 : nlen;
return true;
}
static ssize_t _stream_jumpall(struct stream *stream) {
stream->flags |= HS_SF_CONSUMED;
ssize_t offset = stream->length - stream->index;
stream->index += offset;
int nlen = (int) (stream->token.len + offset);
stream->token.len = stream->token.type == 0 ? 0 : nlen;
return offset;
}
///////////////////////////////////////////////////////////////////////////
// Client //
///////////////////////////////////////////////////////////////////////////
IW_INLINE void _response_body_free(struct response *response) {
if (response->body) {
if (response->body_free) {
response->body_free((void*) response->body);
response->body_free = 0;
}
response->body = 0;
}
}
IW_INLINE void _response_free(struct client *client) {
struct response *response = &client->response;
if (response->pool) {
iwpool_destroy(response->pool);
response->pool = 0;
}
_response_body_free(response);
response->headers = 0;
response->code = 200;
}
static bool _client_response_error(struct client *client, int code, char *response) {
return iwn_http_response_write(&client->request, code, "text/plain", response, -1);
}
static void _client_reset(struct client *client) {
_request_data_free(client);
_stream_free_buffer(client);
_tokens_free_buffer(client);
_response_free(client);
}
static void _proxy_destroy(struct client *client) {
struct proxy *proxy = &client->proxy;
pthread_mutex_destroy(&proxy->mtx);
iwxstr_destroy(proxy->from_endpoint_buf);
iwxstr_destroy(proxy->to_endpoint_buf);
memset(&client->proxy, 0, sizeof(client->proxy));
}
static void _client_destroy(struct client *client) {
if (client) {
if (client->injected_poller_evh == _proxy_client_on_ready) {
_proxy_destroy(client);
}
_client_reset(client);
if (client->server) {
_server_unref(client->server);
}
pthread_mutex_destroy(&client->request.user_mtx);
iwpool_destroy(client->pool);
}
}
static void _client_unref(struct client *client) {
if (--client->refs == 0) {
_client_destroy(client);
}
}
static iwrc _client_init(struct client *client) {
iwrc rc = 0;
_client_reset(client);
client->flags = HTTP_AUTOMATIC;
memset(&client->parser, 0, sizeof(client->parser));
client->chunk_cb = 0;
client->tokens.capacity = 32;
client->tokens.size = 0;
client->tokens.buf = malloc(sizeof(client->tokens.buf[0]) * client->tokens.capacity);
if (!client->tokens.buf) {
client->tokens.capacity = 0;
rc = iwrc_set_errno(IW_ERROR_ALLOC, errno);
goto finish;
}
if (client->server->spec.request_timeout_sec > 0) {
iwn_poller_set_timeout(client->server->spec.poller, client->fd, client->server->spec.request_timeout_sec);
}
finish:
return rc;
}
IW_INLINE bool _client_write_bytes(struct client *client) {
struct iwn_poller_adapter *pa = client->request.poller_adapter;
struct stream *stream = &client->stream;
if (stream->length > stream->bytes_total) {
ssize_t bytes = pa->write(pa,
(uint8_t*) stream->buf + stream->bytes_total,
stream->length - stream->bytes_total);
if (bytes > 0) {
stream->bytes_total += bytes;
}
return errno != EPIPE;
} else {
return true;
}
}
static void _client_write(struct client *client) {
iwrc rc = 0;
struct stream *stream = &client->stream;
struct iwn_poller_adapter *pa = client->request.poller_adapter;
again:
if (!_client_write_bytes(client)) {
client->flags |= HTTP_END_SESSION;
return;
}
if (stream->bytes_total != stream->length || pa->has_pending_write_bytes(pa)) {
rc = pa->arm(pa, IWN_POLLOUT);
} else if (client->flags & (HTTP_CHUNKED_RESPONSE | HTTP_STREAM_RESPONSE)) {
_stream_free_buffer(client);
if (client->server->spec.request_timeout_sec > 0) {
iwn_poller_set_timeout(client->server->spec.poller, client->fd, client->server->spec.request_timeout_sec);
}
bool again = false;
if (!client->chunk_cb || !client->chunk_cb((void*) client, &again)) {
client->flags |= HTTP_END_SESSION;
} else if (again) {
goto again;
}
} else {
bool (*on_response_completed)(struct iwn_http_req*) = client->request.on_response_completed;
if (IW_UNLIKELY(on_response_completed)) {
client->request.on_response_completed = 0;
if (!on_response_completed(&client->request)) {
client->flags |= HTTP_END_SESSION;
}
} else if (client->flags & HTTP_KEEP_ALIVE) {
client->state = HTTP_SESSION_INIT;
if (client->server->spec.request_timeout_keepalive_sec > 0) {
iwn_poller_set_timeout(client->server->spec.poller, client->fd,
client->server->spec.request_timeout_keepalive_sec);
}
} else {
client->flags |= HTTP_END_SESSION;
}
}
if (rc) {
iwlog_ecode_error3(rc);
client->flags |= HTTP_END_SESSION;
}
}
static bool _client_read_bytes(struct client *client) {
struct iwn_poller_adapter *pa = client->request.poller_adapter;
struct stream *stream = &client->stream;
struct server *server = client->server;
if (stream->index < stream->length) {
return true;
}
if (!stream->buf) {
stream->length = 0;
stream->capacity = 0;
stream->buf = malloc(server->spec.request_buf_size + 1 /* \0 */);
if (!stream->buf) {
return false;
}
stream->capacity = server->spec.request_buf_size;
}
ssize_t bytes;
do {
bytes = pa->read(pa, (uint8_t*) stream->buf + stream->length, stream->capacity - stream->length);
if (bytes > 0) {
stream->length += bytes;
stream->bytes_total += bytes;
}
if (stream->length == stream->capacity) {
if (stream->capacity != server->spec.request_buf_max_size) {
ssize_t ncap = stream->capacity * 2;
if (ncap > server->spec.request_buf_max_size) {
ncap = server->spec.request_buf_max_size;
}
char *nbuf = realloc(stream->buf, ncap + 1 /* \0 */);
if (!nbuf) {
bytes = 0;
break;
}
stream->capacity = ncap;
stream->buf = nbuf;
} else {
break;
}
}
} while (bytes > 0);
return bytes != 0;
}
IW_INLINE void _meta_trigger(struct parser *parser, int event) {
int8_t to = _meta_transitions[parser->meta * HS_META_TYPE_LEN + event];
parser->meta = to;
}
struct token _meta_emit_token(struct parser *parser) {
struct token token = { 0 };
switch (parser->meta) {
case M_SEN:
token.type = HS_TOK_CHUNK_BODY;
_meta_trigger(parser, HS_META_NEXT);
break;
case M_END:
token.type = HS_TOK_REQ_END;
memset(parser, 0, sizeof(*parser));
break;
}
return token;
}
struct token _transition(struct client *client, char c, int8_t from, int8_t to) {
struct server *server = client->server;
struct parser *parser = &client->parser;
struct stream *stream = &client->stream;
struct token emitted = { 0 };
if (from == HN) {
_stream_anchor(stream);
}
if (from != to) {
int8_t type = _token_start_states[to];
if (type != HS_TOK_NONE) {
_stream_begin_token(stream, type);
}
if (from == CS) {
_meta_trigger(parser, HS_META_END_CHK_SIZE);
}
if (to == HK) {
++parser->header_count;
if (parser->header_count > server->spec.request_max_headers_count) {
emitted.type = HS_TOK_ERROR;
}
} else if (to == HS) {
_meta_trigger(parser, HS_META_END_KEY);
emitted = _stream_emit(stream);
}
parser->match_index = 0;
}
char low, m = '\0';
int in_bounds = 0;
ssize_t body_left = 0;
#define 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) _meta_trigger(parser, meta__)
switch (to) {
case MS:
case TS:
emitted = _stream_emit(stream);
break;
case RR:
case HR:
_meta_trigger(parser, HS_META_END_VALUE);
emitted = _stream_emit(stream);
break;
case HK:
MATCH("transfer-encoding", HS_META_NOT_TRANSFER_ENC);
MATCH("content-length", HS_META_NOT_CONTENT_LEN);
parser->match_index++;
break;
case HV:
if (parser->meta == M_MCK) {
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 && !_stream_can_contain(client, parser->content_length)) {
_meta_trigger(parser, HS_META_LARGE_BODY);
}
if (parser->meta == M_BIG || parser->meta == M_CHK) {
emitted.type = HS_TOK_BODY_STREAM;
}
_meta_trigger(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') {
_meta_trigger(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) {
_stream_begin_token(stream, HS_TOK_CHUNK_BODY);
}
body_left = parser->content_length - parser->body_consumed;
if (_stream_jump(stream, body_left)) {
emitted = _stream_emit(stream);
_meta_trigger(parser, HS_META_NEXT);
if (to == CB) {
parser->state = CD;
}
parser->content_length = 0;
parser->body_consumed = 0;
} else {
parser->body_consumed += _stream_jumpall(stream);
if (parser->meta == M_STR) {
emitted = _stream_emit(stream);
_stream_shift(stream);
}
}
break;
case C2:
_meta_trigger(parser, HS_META_END_CHUNK);
break;
case BR:
emitted.type = HS_TOK_ERROR;
break;
}
#undef MATCH
return emitted;
}
static iwrc _fd_make_non_blocking(int fd) {
int rci, flags;
while ((flags = fcntl(fd, F_GETFL, 0)) == -1 && errno == EINTR);
if (flags == -1) {
return iwrc_set_errno(IW_ERROR_ERRNO, errno);
}
while ((rci = fcntl(fd, F_SETFL, flags | O_NONBLOCK | O_CLOEXEC)) == -1 && errno == EINTR);
if (rci == -1) {
return iwrc_set_errno(IW_ERROR_ERRNO, errno);
}
return 0;
}
static void _proxy_connect_check_timeout(void *d) {
struct client *client = d;
if (client) {
struct proxy *proxy = &client->proxy;
proxy->fd_timeout = -1;
if (!proxy->connected) {
iwlog_warn("Proxy | Connection timeout %s on timeout %u sec", proxy->url_raw, proxy->timeout_connect_sec);
int fd = proxy->fd;
if (fd > -1) {
iwn_poller_remove(client->poller, fd);
}
}
_client_unref(client);
}
}
static void _proxy_connect_check_cancel(void *d) {
struct client *client = d;
if (client) {
client->proxy.fd_timeout = -1;
}
}
static void _proxy_endpoint_on_dispose(const struct iwn_poller_task *t) {
struct client *client = t->user_data;
if (client) {
client->proxy.connected = false;
client->proxy.disconnected = true;
client->proxy.fd = -1;
int fd = client->fd;
if (fd > -1) { // Flush rest of buffers if any
iwn_poller_arm_events(t->poller, fd, IWN_POLLOUT);
}
fd = client->proxy.fd_timeout;
if (fd > -1) { // Close timeout checker
iwn_poller_remove(t->poller, fd);
}
_client_unref(client);
}
}
static iwrc _proxy_to_endpoint_write_lk(struct client *client) {
iwrc rc = 0;
struct proxy *proxy = &client->proxy;
while (iwxstr_size(proxy->to_endpoint_buf)) {
ssize_t rci = write(proxy->fd, iwxstr_ptr(proxy->to_endpoint_buf), iwxstr_size(proxy->to_endpoint_buf));
if (rci == -1) {
if (errno == EINTR) {
continue;
} else if (errno == EAGAIN || errno == EWOULDBLOCK) {
break;
}
rc = iwrc_set_errno(IW_ERROR_IO_ERRNO, errno);
break;
} else if (rci == 0) {
rc = IW_ERROR_EOF;
break;
}
iwxstr_shift(proxy->to_endpoint_buf, rci);
}
return rc;
}
static iwrc _proxy_from_endpoint_read_lk(struct client *client) {
iwrc rc = 0;
while (!rc) {
char buf[1024];
ssize_t rci = read(client->proxy.fd, buf, sizeof(buf));
if (rci == -1) {
if (errno == EINTR) {
continue;
} else if (errno == EAGAIN || errno == EWOULDBLOCK) {
break;
}
rc = iwrc_set_errno(IW_ERROR_IO_ERRNO, errno);
break;
} else if (rci == 0) {
rc = IW_ERROR_EOF;
break;
}
rc = iwxstr_cat(client->proxy.from_endpoint_buf, buf, rci);
}
return rc;
}
static int64_t _proxy_endpoint_on_ready(const struct iwn_poller_task *t, uint32_t events) {
iwrc rc = 0;
uint32_t arm_client = 0;
uint32_t ret = IWN_POLLET;
struct client *client = t->user_data;
struct proxy *proxy = &client->proxy;
if (!proxy->connected) {
struct sockaddr_storage sa = { 0 };
socklen_t sa_len = sizeof(sa);
if (getpeername(t->fd, (void*) &sa, &sa_len) == 0) {
proxy->connected = true;
arm_client |= IWN_POLLIN;
ret |= IWN_POLLOUT;
} else {
char ch;
proxy->fd = -1;
if (read(proxy->fd, &ch, 1) == -1) {
proxy->rc = iwrc_set_errno(IW_ERROR_IO_ERRNO, errno);
iwlog_ecode_error(proxy->rc, "Proxy | Connection to the proxy endpoint: %s failed", proxy->url_raw);
}
int fd = proxy->fd_timeout;
if (fd > -1) { // Cancel connection timeout watcher
iwn_poller_remove(t->poller, fd);
}
return -1;
}
}
if (events & IWN_POLLIN) {
pthread_mutex_lock(&proxy->mtx);
rc = _proxy_from_endpoint_read_lk(client);
pthread_mutex_unlock(&proxy->mtx);
RCGO(rc, finish);
}
if (events & IWN_POLLOUT) {
pthread_mutex_lock(&proxy->mtx);
rc = _proxy_to_endpoint_write_lk(client);
pthread_mutex_unlock(&proxy->mtx);
RCGO(rc, finish);
}
pthread_mutex_lock(&proxy->mtx);
if (iwxstr_size(proxy->from_endpoint_buf)) {