-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy pathFeersum.xs
3209 lines (2787 loc) · 89.6 KB
/
Feersum.xs
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
#include "EVAPI.h"
#define PERL_NO_GET_CONTEXT
#include "ppport.h"
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/socket.h>
#include <errno.h>
#include <ctype.h>
#include <netinet/ip.h>
#include <netinet/tcp.h>
#include <sys/uio.h>
#include <time.h>
#include "picohttpparser-git/picohttpparser.c"
///////////////////////////////////////////////////////////////
// "Compile Time Options" - See Feersum.pm POD for information
#define MAX_HEADERS 64
#define MAX_HEADER_NAME_LEN 128
#define MAX_BODY_LEN 2147483647
#define READ_BUFSZ 4096
#define READ_INIT_FACTOR 2
#define READ_GROW_FACTOR 8
#define READ_TIMEOUT 5.0
#define AUTOCORK_WRITES 1
#define KEEPALIVE_CONNECTION 0
#define DATE_HEADER 1
// may be lower for your platform (e.g. Solaris is 16). See POD.
#define FEERSUM_IOMATRIX_SIZE 64
// auto-detected in Makefile.PL by perl versions and ithread usage; override
// that here. See POD for details.
#if 0
# undef FEERSUM_STEAL
#endif
///////////////////////////////////////////////////////////////
#ifdef __GNUC__
# define likely(x) __builtin_expect(!!(x), 1)
# define unlikely(x) __builtin_expect(!!(x), 0)
#else
# define likely(x) (x)
# define unlikely(x) (x)
#endif
#ifndef HAS_ACCEPT4
#ifdef __GLIBC_PREREQ
#if __GLIBC_PREREQ(2, 10)
// accept4 is available
#define HAS_ACCEPT4 1
#endif
#endif
#endif
#ifndef HAS_ACCEPT4
#ifdef __NR_accept4
#define HAS_ACCEPT4 1
#endif
#endif
#ifndef CRLF
#define CRLF "\015\012"
#endif
#define CRLFx2 CRLF CRLF
// make darwin, solaris and bsd happy:
#ifndef SOL_TCP
#define SOL_TCP IPPROTO_TCP
#endif
// Wish-list: %z formats for perl sprintf. Would make compiling a lot less
// noisy for systems that warn size_t and STRLEN are incompatible with
// %d/%u/%x.
#if Size_t_size == LONGSIZE
# define Sz_f "l"
# define Sz_t long
#elif Size_t_size == 8 && defined HAS_QUAD && QUADKIND == QUAD_IS_LONG_LONG
# define Sz_f "ll"
# define Sz_t long long
#else
// hope "int" works.
# define Sz_f ""
# define Sz_t int
#endif
#define Sz_uf Sz_f"u"
#define Sz_xf Sz_f"x"
#define Ssz_df Sz_f"d"
#define Sz unsigned Sz_t
#define Ssz Sz_t
#define WARN_PREFIX "Feersum: "
#ifndef DEBUG
#ifndef __inline
#define __inline
#endif
#define INLINE_UNLESS_DEBUG __inline
#else
#define INLINE_UNLESS_DEBUG
#endif
#define trouble(f_, ...) warn(WARN_PREFIX f_, ##__VA_ARGS__);
#ifdef DEBUG
#define trace(f_, ...) warn("%s:%-4d [%d] " f_, __FILE__, __LINE__, (int)getpid(), ##__VA_ARGS__)
#else
#define trace(...)
#endif
#if DEBUG >= 2
#define trace2(f_, ...) trace(f_, ##__VA_ARGS__)
#else
#define trace2(...)
#endif
#if DEBUG >= 3
#define trace3(f_, ...) trace(f_, ##__VA_ARGS__)
#else
#define trace3(...)
#endif
#include "rinq.c"
// Check FEERSUM_IOMATRIX_SIZE against what's actually usable on this
// platform. See Feersum.pm for an explanation
#if defined(IOV_MAX) && FEERSUM_IOMATRIX_SIZE > IOV_MAX
# undef FEERSUM_IOMATRIX_SIZE
# define FEERSUM_IOMATRIX_SIZE IOV_MAX
#elif defined(UIO_MAXIOV) && FEERSUM_IOMATRIX_SIZE > UIO_MAXIOV
# undef FEERSUM_IOMATRIX_SIZE
# define FEERSUM_IOMATRIX_SIZE UIO_MAXIOV
#endif
struct iomatrix {
unsigned offset;
unsigned count;
struct iovec iov[FEERSUM_IOMATRIX_SIZE];
SV *sv[FEERSUM_IOMATRIX_SIZE];
};
struct feer_req {
SV *buf;
const char* method;
size_t method_len;
const char* uri;
size_t uri_len;
int minor_version;
size_t num_headers;
struct phr_header headers[MAX_HEADERS];
SV* path;
SV* query;
SV* addr;
SV* port;
};
enum feer_respond_state {
RESPOND_NOT_STARTED = 0,
RESPOND_NORMAL = 1,
RESPOND_STREAMING = 2,
RESPOND_SHUTDOWN = 3
};
#define RESPOND_STR(_n,_s) do { \
switch(_n) { \
case RESPOND_NOT_STARTED: _s = "NOT_STARTED(0)"; break; \
case RESPOND_NORMAL: _s = "NORMAL(1)"; break; \
case RESPOND_STREAMING: _s = "STREAMING(2)"; break; \
case RESPOND_SHUTDOWN: _s = "SHUTDOWN(4)"; break; \
} \
} while (0)
enum feer_receive_state {
RECEIVE_WAIT = 0,
RECEIVE_HEADERS = 1,
RECEIVE_BODY = 2,
RECEIVE_STREAMING = 3,
RECEIVE_SHUTDOWN = 4
};
#define RECEIVE_STR(_n,_s) do { \
switch(_n) { \
case RECEIVE_WAIT: _s = "WAIT(0)"; break; \
case RECEIVE_HEADERS: _s = "HEADERS(1)"; break; \
case RECEIVE_BODY: _s = "BODY(2)"; break; \
case RECEIVE_STREAMING: _s = "STREAMING(3)"; break; \
case RECEIVE_SHUTDOWN: _s = "SHUTDOWN(4)"; break; \
} \
} while (0)
struct feer_conn {
SV *self;
int fd;
struct sockaddr *sa;
struct ev_io read_ev_io;
struct ev_io write_ev_io;
struct ev_timer read_ev_timer;
SV *rbuf;
struct rinq *wbuf_rinq;
SV *poll_write_cb;
SV *ext_guard;
struct feer_req *req;
ssize_t expected_cl;
ssize_t received_cl;
enum feer_respond_state responding;
enum feer_receive_state receiving;
bool is_keepalive;
int reqs;
unsigned int in_callback;
unsigned int is_http11:1;
unsigned int poll_write_cb_is_io_handle:1;
unsigned int auto_cl:1;
};
enum feer_header_norm_style {
HEADER_NORM_SKIP = 0,
HEADER_NORM_UPCASE_DASH = 1,
HEADER_NORM_LOCASE_DASH = 2,
HEADER_NORM_UPCASE = 3,
HEADER_NORM_LOCASE = 4
};
typedef struct feer_conn feer_conn_handle; // for typemap
#define dCONN struct feer_conn *c = (struct feer_conn *)w->data
#define IsArrayRef(_x) (SvROK(_x) && SvTYPE(SvRV(_x)) == SVt_PVAV)
#define IsCodeRef(_x) (SvROK(_x) && SvTYPE(SvRV(_x)) == SVt_PVCV)
static SV* feersum_env_method(pTHX_ struct feer_req *r);
static SV* feersum_env_uri(pTHX_ struct feer_req *r);
static SV* feersum_env_protocol(pTHX_ struct feer_req *r);
static void feersum_set_path_and_query(pTHX_ struct feer_req *r);
static void feersum_set_remote_info(pTHX_ struct feer_req *r, struct sockaddr *sa);
static HV* feersum_env(pTHX_ struct feer_conn *c);
static SV* feersum_env_path(pTHX_ struct feer_req *r);
static SV* feersum_env_query(pTHX_ struct feer_req *r);
static HV* feersum_env_headers(pTHX_ struct feer_req *r, int norm);
static SV* feersum_env_header(pTHX_ struct feer_req *r, SV* name);
static SV* feersum_env_addr(pTHX_ struct feer_conn *c);
static SV* feersum_env_port(pTHX_ struct feer_conn *c);
static ssize_t feersum_env_content_length(pTHX_ struct feer_conn *c);
static SV* feersum_env_io(pTHX_ struct feer_conn *c);
static void feersum_start_response
(pTHX_ struct feer_conn *c, SV *message, AV *headers, int streaming);
static size_t feersum_write_whole_body (pTHX_ struct feer_conn *c, SV *body);
static void feersum_handle_psgi_response(
pTHX_ struct feer_conn *c, SV *ret, bool can_recurse);
static bool feersum_set_keepalive (pTHX_ struct feer_conn *c, bool is_keepalive);
static int feersum_close_handle(pTHX_ struct feer_conn *c, bool is_writer);
static SV* feersum_conn_guard(pTHX_ struct feer_conn *c, SV *guard);
static void start_read_watcher(struct feer_conn *c);
static void stop_read_watcher(struct feer_conn *c);
static void restart_read_timer(struct feer_conn *c);
static void stop_read_timer(struct feer_conn *c);
static void start_write_watcher(struct feer_conn *c);
static void stop_write_watcher(struct feer_conn *c);
static void try_conn_write(EV_P_ struct ev_io *w, int revents);
static void try_conn_read(EV_P_ struct ev_io *w, int revents);
static void conn_read_timeout(EV_P_ struct ev_timer *w, int revents);
static bool process_request_headers(struct feer_conn *c, int body_offset);
static void sched_request_callback(struct feer_conn *c);
static void call_died (pTHX_ struct feer_conn *c, const char *cb_type);
static void call_request_callback(struct feer_conn *c);
static void call_poll_callback (struct feer_conn *c, bool is_write);
static void pump_io_handle (struct feer_conn *c, SV *io);
static void conn_write_ready (struct feer_conn *c);
static void respond_with_server_error(struct feer_conn *c, const char *msg, STRLEN msg_len, int code);
static void update_wbuf_placeholder(struct feer_conn *c, SV *sv, struct iovec *iov);
static STRLEN add_sv_to_wbuf (struct feer_conn *c, SV *sv);
static STRLEN add_const_to_wbuf (struct feer_conn *c, const char *str, size_t str_len);
#define add_crlf_to_wbuf(c) add_const_to_wbuf(c,CRLF,2)
static void finish_wbuf (struct feer_conn *c);
static void add_chunk_sv_to_wbuf (struct feer_conn *c, SV *sv);
static void add_placeholder_to_wbuf (struct feer_conn *c, SV **sv, struct iovec **iov_ref);
static void uri_decode_sv (SV *sv);
static bool str_eq(const char *a, int a_len, const char *b, int b_len);
static bool str_case_eq(const char *a, int a_len, const char *b, int b_len);
static SV* fetch_av_normal (pTHX_ AV *av, I32 i);
static const char *http_code_to_msg (int code);
static int prep_socket (int fd, int is_tcp);
static HV *feer_stash, *feer_conn_stash;
static HV *feer_conn_reader_stash = NULL, *feer_conn_writer_stash = NULL;
static MGVTBL psgix_io_vtbl;
static SV *request_cb_cv = NULL;
static bool request_cb_is_psgi = 0;
static SV *shutdown_cb_cv = NULL;
static bool shutting_down = 0;
static int active_conns = 0;
static double read_timeout = READ_TIMEOUT;
static unsigned int max_connection_reqs = 0;
static SV *feer_server_name = NULL;
static SV *feer_server_port = NULL;
static bool is_tcp = 1;
static bool is_keepalive = KEEPALIVE_CONNECTION;
static ev_io accept_w;
static ev_prepare ep;
static ev_check ec;
struct ev_idle ei;
static struct rinq *request_ready_rinq = NULL;
static AV *psgi_ver;
static SV *psgi_serv10, *psgi_serv11, *crlf_sv;
// TODO: make this thread-local if and when there are multiple C threads:
struct ev_loop *feersum_ev_loop = NULL;
static HV *feersum_tmpl_env = NULL;
#define DATE_HEADER_LENGTH 37 // "Date: Thu, 01 Jan 1970 00:00:00 GMT\015\012"
static const char *const DAYS[] = {"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"};
static const char *const MONTHS[] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun",
"Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};
static char DATE_BUF[DATE_HEADER_LENGTH+1] = "Date: The, 01 Jan 1970 00:00:00 GMT\015\012";
static time_t LAST_GENERATED_TIME = 0;
static INLINE_UNLESS_DEBUG void uint_to_str(unsigned int value, char *str) {
str[0] = (value / 10) + '0';
str[1] = (value % 10) + '0';
}
static INLINE_UNLESS_DEBUG void uint_to_str_4digits(unsigned int value, char *str) {
str[0] = (value / 1000) + '0';
str[1] = (value / 100) % 10 + '0';
str[2] = (value / 10) % 10 + '0';
str[3] = value % 10 + '0';
}
INLINE_UNLESS_DEBUG
static void generate_date_header(void) {
time_t now = time(NULL);
if (now == LAST_GENERATED_TIME) return;
LAST_GENERATED_TIME = now;
struct tm *tm = gmtime(&now);
const char *day = DAYS[tm->tm_wday];
DATE_BUF[6] = day[0];
DATE_BUF[7] = day[1];
DATE_BUF[8] = day[2];
uint_to_str(tm->tm_mday, DATE_BUF + 11);
const char *month = MONTHS[tm->tm_mon];
DATE_BUF[14] = month[0];
DATE_BUF[15] = month[1];
DATE_BUF[16] = month[2];
uint_to_str_4digits(tm->tm_year + 1900, DATE_BUF + 18);
uint_to_str(tm->tm_hour, DATE_BUF + 23);
uint_to_str(tm->tm_min, DATE_BUF + 26);
uint_to_str(tm->tm_sec, DATE_BUF + 29);
}
INLINE_UNLESS_DEBUG
static SV*
fetch_av_normal (pTHX_ AV *av, I32 i)
{
SV **elt = av_fetch(av, i, 0);
if (elt == NULL) return NULL;
SV *sv = *elt;
// copy to remove magic
if (unlikely(SvMAGICAL(sv))) sv = sv_2mortal(newSVsv(sv));
if (unlikely(!SvOK(sv))) return NULL;
// usually array ref elems aren't RVs (for PSGI anyway)
if (unlikely(SvROK(sv))) sv = SvRV(sv);
return sv;
}
INLINE_UNLESS_DEBUG
static struct iomatrix *
next_iomatrix (struct feer_conn *c)
{
bool add_iomatrix = 0;
struct iomatrix *m;
if (!c->wbuf_rinq) {
trace3("next_iomatrix(%d): head\n", c->fd);
add_iomatrix = 1;
}
else {
// get the tail-end struct
m = (struct iomatrix *)c->wbuf_rinq->prev->ref;
trace3("next_iomatrix(%d): tail, count=%d, offset=%d\n",
c->fd, m->count, m->offset);
if (m->count >= FEERSUM_IOMATRIX_SIZE) {
add_iomatrix = 1;
}
}
if (add_iomatrix) {
trace3("next_iomatrix(%d): malloc\n", c->fd);
Newx(m,1,struct iomatrix);
Poison(m,1,struct iomatrix);
m->offset = m->count = 0;
rinq_push(&c->wbuf_rinq, m);
}
trace3("next_iomatrix(%d): end, count=%d, offset=%d\n",
c->fd, m->count, m->offset);
return m;
}
INLINE_UNLESS_DEBUG
static STRLEN
add_sv_to_wbuf(struct feer_conn *c, SV *sv)
{
struct iomatrix *m = next_iomatrix(c);
int idx = m->count++;
STRLEN cur;
if (unlikely(SvMAGICAL(sv))) {
sv = newSVsv(sv); // copy to force it to be normal.
}
else if (unlikely(SvPADTMP(sv))) {
// PADTMPs have their PVs re-used, so we can't simply keep a
// reference. TEMPs maybe behave in a similar way and are potentially
// stealable. If not stealing, we must make a copy.
#ifdef FEERSUM_STEAL
if (SvFLAGS(sv) == (SVs_PADTMP|SVf_POK|SVp_POK)) {
trace3("STEALING\n");
SV *theif = newSV(0);
sv_upgrade(theif, SVt_PV);
SvPV_set(theif, SvPVX(sv));
SvLEN_set(theif, SvLEN(sv));
SvCUR_set(theif, SvCUR(sv));
// make the temp null
(void)SvOK_off(sv);
SvPV_set(sv, NULL);
SvLEN_set(sv, 0);
SvCUR_set(sv, 0);
SvFLAGS(theif) |= SVf_READONLY|SVf_POK|SVp_POK;
sv = theif;
}
else {
sv = newSVsv(sv);
}
#else
sv = newSVsv(sv);
#endif
}
else {
sv = SvREFCNT_inc(sv);
}
m->iov[idx].iov_base = SvPV(sv, cur);
m->iov[idx].iov_len = cur;
m->sv[idx] = sv;
return cur;
}
INLINE_UNLESS_DEBUG
static STRLEN
add_const_to_wbuf(struct feer_conn *c, const char *str, size_t str_len)
{
struct iomatrix *m = next_iomatrix(c);
int idx = m->count++;
m->iov[idx].iov_base = (void*)str;
m->iov[idx].iov_len = str_len;
m->sv[idx] = NULL;
return str_len;
}
INLINE_UNLESS_DEBUG
static void
add_placeholder_to_wbuf(struct feer_conn *c, SV **sv, struct iovec **iov_ref)
{
struct iomatrix *m = next_iomatrix(c);
int idx = m->count++;
*sv = newSV(31);
SvPOK_on(*sv);
m->sv[idx] = *sv;
*iov_ref = &m->iov[idx];
}
INLINE_UNLESS_DEBUG
static void
finish_wbuf(struct feer_conn *c)
{
if (!c->is_http11) return; // nothing required
add_const_to_wbuf(c, "0\r\n\r\n", 5); // terminating chunk
}
INLINE_UNLESS_DEBUG
static void
update_wbuf_placeholder(struct feer_conn *c, SV *sv, struct iovec *iov)
{
STRLEN cur;
// can't pass iov_len for cur; incompatible pointer type on some systems:
iov->iov_base = SvPV(sv,cur);
iov->iov_len = cur;
}
static void
add_chunk_sv_to_wbuf(struct feer_conn *c, SV *sv)
{
SV *chunk;
struct iovec *chunk_iov;
add_placeholder_to_wbuf(c, &chunk, &chunk_iov);
STRLEN cur = add_sv_to_wbuf(c, sv);
add_crlf_to_wbuf(c);
sv_setpvf(chunk, "%"Sz_xf CRLF, (Sz)cur);
update_wbuf_placeholder(c, chunk, chunk_iov);
}
static const char *
http_code_to_msg (int code) {
// http://en.wikipedia.org/wiki/List_of_HTTP_status_codes
switch (code) {
case 100: return "Continue";
case 101: return "Switching Protocols";
case 102: return "Processing"; // RFC 2518
case 200: return "OK";
case 201: return "Created";
case 202: return "Accepted";
case 203: return "Non Authoritative Information";
case 204: return "No Content";
case 205: return "Reset Content";
case 206: return "Partial Content";
case 207: return "Multi-Status"; // RFC 4918 (WebDav)
case 300: return "Multiple Choices";
case 301: return "Moved Permanently";
case 302: return "Found";
case 303: return "See Other";
case 304: return "Not Modified";
case 305: return "Use Proxy";
case 307: return "Temporary Redirect";
case 400: return "Bad Request";
case 401: return "Unauthorized";
case 402: return "Payment Required";
case 403: return "Forbidden";
case 404: return "Not Found";
case 405: return "Method Not Allowed";
case 406: return "Not Acceptable";
case 407: return "Proxy Authentication Required";
case 408: return "Request Timeout";
case 409: return "Conflict";
case 410: return "Gone";
case 411: return "Length Required";
case 412: return "Precondition Failed";
case 413: return "Request Entity Too Large";
case 414: return "Request URI Too Long";
case 415: return "Unsupported Media Type";
case 416: return "Requested Range Not Satisfiable";
case 417: return "Expectation Failed";
case 418: return "I'm a teapot";
case 421: return "Too Many Connections"; // Microsoft?
case 422: return "Unprocessable Entity"; // RFC 4918
case 423: return "Locked"; // RFC 4918
case 424: return "Failed Dependency"; // RFC 4918
case 425: return "Unordered Collection"; // RFC 3648
case 426: return "Upgrade Required"; // RFC 2817
case 449: return "Retry With"; // Microsoft
case 450: return "Blocked by Parental Controls"; // Microsoft
case 500: return "Internal Server Error";
case 501: return "Not Implemented";
case 502: return "Bad Gateway";
case 503: return "Service Unavailable";
case 504: return "Gateway Timeout";
case 505: return "HTTP Version Not Supported";
case 506: return "Variant Also Negotiates"; // RFC 2295
case 507: return "Insufficient Storage"; // RFC 4918
case 509: return "Bandwidth Limit Exceeded"; // Apache mod
case 510: return "Not Extended"; // RFC 2774
case 530: return "User access denied"; // ??
default: break;
}
// default to the Nxx group names in RFC 2616
if (100 <= code && code <= 199) {
return "Informational";
}
else if (200 <= code && code <= 299) {
return "Success";
}
else if (300 <= code && code <= 399) {
return "Redirection";
}
else if (400 <= code && code <= 499) {
return "Client Error";
}
else {
return "Error";
}
}
static int
prep_socket(int fd, int is_tcp)
{
#ifdef HAS_ACCEPT4
int flags = 1;
#else
int flags;
// make it non-blocking
flags = O_NONBLOCK;
if (unlikely(fcntl(fd, F_SETFL, flags) < 0))
return -1;
flags = 1;
#endif
if (likely(is_tcp)) {
// flush writes immediately
if (unlikely(setsockopt(fd, SOL_TCP, TCP_NODELAY, &flags, sizeof(int))))
return -1;
}
// handle URG data inline
if (unlikely(setsockopt(fd, SOL_SOCKET, SO_OOBINLINE, &flags, sizeof(int))))
return -1;
// disable lingering
struct linger linger = { .l_onoff = 0, .l_linger = 0 };
if (unlikely(setsockopt(fd, SOL_SOCKET, SO_LINGER, &linger, sizeof(linger))))
return -1;
return 0;
}
INLINE_UNLESS_DEBUG static void
safe_close_conn(struct feer_conn *c, const char *where)
{
if (unlikely(c->fd < 0))
return;
// make it blocking
fcntl(c->fd, F_SETFL, 0);
if (unlikely(close(c->fd)))
perror(where);
c->fd = -1;
}
static struct feer_conn *
new_feer_conn (EV_P_ int conn_fd, struct sockaddr *sa)
{
SV *self = newSV(0);
SvUPGRADE(self, SVt_PVMG); // ensures sv_bless doesn't reallocate
SvGROW(self, sizeof(struct feer_conn));
SvPOK_only(self);
SvIOK_on(self);
SvIV_set(self,conn_fd);
struct feer_conn *c = (struct feer_conn *)SvPVX(self);
Zero(c, 1, struct feer_conn);
c->self = self;
c->fd = conn_fd;
c->sa = sa;
c->responding = RESPOND_NOT_STARTED;
c->receiving = RECEIVE_HEADERS;
c->is_keepalive = 0;
c->reqs = 0;
ev_io_init(&c->read_ev_io, try_conn_read, conn_fd, EV_READ);
c->read_ev_io.data = (void *)c;
ev_init(&c->read_ev_timer, conn_read_timeout);
c->read_ev_timer.data = (void *)c;
trace3("made conn fd=%d self=%p, c=%p, cur=%"Sz_uf", len=%"Sz_uf"\n",
c->fd, self, c, (Sz)SvCUR(self), (Sz)SvLEN(self));
SV *rv = newRV_inc(c->self);
sv_bless(rv, feer_conn_stash); // so DESTROY can get called on read errors
SvREFCNT_dec(rv);
SvREADONLY_on(self); // turn off later for blessing
active_conns++;
return c;
}
// for use in the typemap:
INLINE_UNLESS_DEBUG
static struct feer_conn *
sv_2feer_conn (SV *rv)
{
if (unlikely(!sv_isa(rv,"Feersum::Connection")))
croak("object is not of type Feersum::Connection");
return (struct feer_conn *)SvPVX(SvRV(rv));
}
INLINE_UNLESS_DEBUG
static SV*
feer_conn_2sv (struct feer_conn *c)
{
return newRV_inc(c->self);
}
static feer_conn_handle *
sv_2feer_conn_handle (SV *rv, bool can_croak)
{
trace3("sv 2 conn_handle\n");
if (unlikely(!SvROK(rv))) croak("Expected a reference");
// do not allow subclassing
SV *sv = SvRV(rv);
if (likely(
sv_isobject(rv) &&
(SvSTASH(sv) == feer_conn_writer_stash ||
SvSTASH(sv) == feer_conn_reader_stash)
)) {
UV uv = SvUV(sv);
if (uv == 0) {
if (can_croak) croak("Operation not allowed: Handle is closed.");
return NULL;
}
return INT2PTR(feer_conn_handle*,uv);
}
if (can_croak)
croak("Expected a Feersum::Connection::Writer or ::Reader object");
return NULL;
}
static SV *
new_feer_conn_handle (pTHX_ struct feer_conn *c, bool is_writer)
{
SV *sv;
SvREFCNT_inc_void_NN(c->self);
sv = newRV_noinc(newSVuv(PTR2UV(c)));
sv_bless(sv, is_writer ? feer_conn_writer_stash : feer_conn_reader_stash);
return sv;
}
#if DEBUG
# define change_responding_state(c, _to) do { \
enum feer_respond_state __to = (_to); \
enum feer_respond_state __from = c->responding; \
const char *_from_str, *_to_str; \
if (likely(__from != __to)) { \
RESPOND_STR(c->responding, _from_str); \
RESPOND_STR(__to, _to_str); \
trace2("==> responding state %d: %s to %s\n", \
c->fd,_from_str,_to_str); \
c->responding = __to; \
} \
} while (0)
# define change_receiving_state(c, _to) do { \
enum feer_receive_state __to = (_to); \
enum feer_receive_state __from = c->receiving; \
const char *_from_str, *_to_str; \
if (likely(__from != __to)) { \
RECEIVE_STR(c->receiving, _from_str); \
RECEIVE_STR(__to, _to_str); \
trace2("==> receiving state %d: %s to %s\n", \
c->fd,_from_str,_to_str); \
c->receiving = __to; \
} \
} while (0)
#else
# define change_responding_state(c, _to) c->responding = _to
# define change_receiving_state(c, _to) c->receiving = _to
#endif
INLINE_UNLESS_DEBUG static void
start_read_watcher(struct feer_conn *c) {
if (unlikely(ev_is_active(&c->read_ev_io)))
return;
trace("start read watcher %d\n",c->fd);
ev_io_start(feersum_ev_loop, &c->read_ev_io);
SvREFCNT_inc_void_NN(c->self);
}
INLINE_UNLESS_DEBUG static void
stop_read_watcher(struct feer_conn *c) {
if (unlikely(!ev_is_active(&c->read_ev_io)))
return;
trace("stop read watcher %d\n",c->fd);
ev_io_stop(feersum_ev_loop, &c->read_ev_io);
SvREFCNT_dec(c->self);
}
INLINE_UNLESS_DEBUG static void
restart_read_timer(struct feer_conn *c) {
if (likely(!ev_is_active(&c->read_ev_timer))) {
trace("restart read timer %d\n",c->fd);
c->read_ev_timer.repeat = read_timeout;
SvREFCNT_inc_void_NN(c->self);
}
ev_timer_again(feersum_ev_loop, &c->read_ev_timer);
}
INLINE_UNLESS_DEBUG static void
stop_read_timer(struct feer_conn *c) {
if (unlikely(!ev_is_active(&c->read_ev_timer)))
return;
trace("stop read timer %d\n",c->fd);
ev_timer_stop(feersum_ev_loop, &c->read_ev_timer);
SvREFCNT_dec(c->self);
}
INLINE_UNLESS_DEBUG static void
start_write_watcher(struct feer_conn *c) {
if (unlikely(ev_is_active(&c->write_ev_io)))
return;
trace("start write watcher %d\n",c->fd);
ev_io_start(feersum_ev_loop, &c->write_ev_io);
SvREFCNT_inc_void_NN(c->self);
}
INLINE_UNLESS_DEBUG static void
stop_write_watcher(struct feer_conn *c) {
if (unlikely(!ev_is_active(&c->write_ev_io)))
return;
trace("stop write watcher %d\n",c->fd);
ev_io_stop(feersum_ev_loop, &c->write_ev_io);
SvREFCNT_dec(c->self);
}
static void
process_request_ready_rinq (void)
{
while (request_ready_rinq) {
struct feer_conn *c =
(struct feer_conn *)rinq_shift(&request_ready_rinq);
//trace("rinq shifted c=%p, head=%p\n", c, request_ready_rinq);
call_request_callback(c);
if (likely(c->wbuf_rinq)) {
// this was deferred until after the perl callback
conn_write_ready(c);
}
SvREFCNT_dec(c->self); // for the rinq
}
}
static void
prepare_cb (EV_P_ ev_prepare *w, int revents)
{
if (unlikely(revents & EV_ERROR)) {
trouble("EV error in prepare, revents=0x%08x\n", revents);
ev_break(EV_A, EVBREAK_ALL);
return;
}
if (!ev_is_active(&accept_w) && !shutting_down) {
ev_io_start(EV_A, &accept_w);
}
ev_prepare_stop(EV_A, w);
}
static void
check_cb (EV_P_ ev_check *w, int revents)
{
if (unlikely(revents & EV_ERROR)) {
trouble("EV error in check, revents=0x%08x\n", revents);
ev_break(EV_A, EVBREAK_ALL);
return;
}
trace3("check! head=%p\n", request_ready_rinq);
if (request_ready_rinq)
process_request_ready_rinq();
}
static void
idle_cb (EV_P_ ev_idle *w, int revents)
{
if (unlikely(revents & EV_ERROR)) {
trouble("EV error in idle, revents=0x%08x\n", revents);
ev_break(EV_A, EVBREAK_ALL);
return;
}
trace3("idle! head=%p\n", request_ready_rinq);
if (request_ready_rinq)
process_request_ready_rinq();
ev_idle_stop(EV_A, w);
}
static void
try_conn_write(EV_P_ struct ev_io *w, int revents)
{
dCONN;
int i;
struct iomatrix *m;
SvREFCNT_inc_void_NN(c->self);
// if it's marked writeable EV suggests we simply try write to it.
// Otherwise it is stopped and we should ditch this connection.
if (unlikely(revents & EV_ERROR && !(revents & EV_WRITE))) {
trace("EV error on write, fd=%d revents=0x%08x\n", w->fd, revents);
change_responding_state(c, RESPOND_SHUTDOWN);
goto try_write_finished;
}
if (unlikely(!c->wbuf_rinq)) {
if (unlikely(c->responding >= RESPOND_SHUTDOWN))
goto try_write_finished;
if (!c->poll_write_cb) {
// no callback and no data: wait for app to push to us.
if (c->responding == RESPOND_STREAMING)
goto try_write_paused;
trace("tried to write with an empty buffer %d resp=%d\n",w->fd,c->responding);
change_responding_state(c, RESPOND_SHUTDOWN);
goto try_write_finished;
}
if (c->poll_write_cb_is_io_handle)
pump_io_handle(c, c->poll_write_cb);
else
call_poll_callback(c, 1);
// callback didn't write anything:
if (unlikely(!c->wbuf_rinq)) goto try_write_again;
}
try_write_again_immediately:
m = (struct iomatrix *)c->wbuf_rinq->ref;
#if DEBUG >= 2
warn("going to write to %d:\n",c->fd);
for (i=0; i < m->count; i++) {
fprintf(stderr,"%.*s",
(int)m->iov[i].iov_len, (char*)m->iov[i].iov_base);
}
#endif
trace("going to write %d off=%d count=%d\n", w->fd, m->offset, m->count);
errno = 0;
ssize_t wrote = writev(w->fd, &m->iov[m->offset], m->count - m->offset);
trace("wrote %"Ssz_df" bytes to %d, errno=%d\n", (Ssz)wrote, w->fd, errno);
if (unlikely(wrote <= 0)) {
if (unlikely(wrote == 0))
goto try_write_again;
if (likely(errno == EAGAIN || errno == EINTR))
goto try_write_again;
perror("Feersum try_conn_write");
change_responding_state(c, RESPOND_SHUTDOWN);
goto try_write_finished;
}
bool consume = 1;
for (i = m->offset; i < m->count && consume; i++) {
struct iovec *v = &m->iov[i];
if (unlikely(v->iov_len > wrote)) {
trace3("offset vector %d base=%p len=%"Sz_uf"\n",
w->fd, v->iov_base, (Sz)v->iov_len);
v->iov_base += wrote;
v->iov_len -= wrote;
// don't consume any more:
consume = 0;
}
else {
trace3("consume vector %d base=%p len=%"Sz_uf" sv=%p\n",
w->fd, v->iov_base, (Sz)v->iov_len, m->sv[i]);
wrote -= v->iov_len;
m->offset++;
if (m->sv[i]) {
SvREFCNT_dec(m->sv[i]);
m->sv[i] = NULL;
}
}
}
if (likely(m->offset >= m->count)) {
trace2("all done with iomatrix %d state=%d\n",w->fd,c->responding);
rinq_shift(&c->wbuf_rinq);
Safefree(m);
if (!c->wbuf_rinq)
goto try_write_finished;
trace2("write again immediately %d state=%d\n",w->fd,c->responding);
goto try_write_again_immediately;
}
// else, fallthrough:
trace2("write fallthrough %d state=%d\n",w->fd,c->responding);
try_write_again:
trace("write again %d state=%d\n",w->fd,c->responding);
start_write_watcher(c);
goto try_write_cleanup;
try_write_finished: