/
Feersum.xs
1500 lines (1290 loc) · 39.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"
#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 "ppport.h"
#include "picohttpparser/picohttpparser.c"
#include "rinq.c"
#ifndef CRLF
#define CRLF "\015\012"
#endif
#define CRLFx2 CRLF CRLF
#define MAX_HEADERS 64
#define MAX_HEADER_NAME_LEN 128
#define MAX_BODY_LENGTH IV_MAX - 1
// Setting this to true will wait for writability before calling write() (will
// try to immediately write otherwise)
#define AUTOCORK_WRITES 1
#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_, ...) trouble(f_, ##__VA_ARGS__)
#else
#define trace(...)
#endif
struct feer_req {
SV *buf;
const char* method;
size_t method_len;
const char* path;
size_t path_len;
int minor_version;
size_t num_headers;
struct phr_header headers[MAX_HEADERS];
};
// enough to hold a 64-bit signed integer (which is 20+1 chars) plus nul
#define CONN_LABEL_LENGTH 24
#define RESPOND_NORMAL 1
#define RESPOND_STREAMING 2
#define RESPOND_SHUTDOWN 3
#define RECEIVE_HEADERS 0
#define RECEIVE_BODY 1
#define RECEIVE_STREAMING 2
#define RECEIVE_SHUTDOWN 3
struct feer_conn {
char label[CONN_LABEL_LENGTH];
SV *self;
int fd;
struct ev_io read_ev_io;
struct ev_io write_ev_io;
struct ev_loop *loop;
SV *rbuf, *wbuf;
struct feer_req *req;
size_t expected_cl;
size_t received_cl;
// SV *drain_cb; // async "done writing" callback
// SV *read_cb; // async "data available" callback
int16_t in_callback;
int16_t responding;
int16_t receiving;
};
typedef struct feer_conn feer_conn_handle; // for typemap
#define dCONN struct feer_conn *c = (struct feer_conn *)w->data
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 bool process_request_headers(struct feer_conn *c, int body_offset);
static void sched_request_callback(struct feer_conn *c);
static void call_request_callback(struct feer_conn *c);
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 add_sv_to_wbuf (struct feer_conn *c, SV *sv, bool chunked);
static void uri_decode_sv (SV *sv);
static void offset_sv(SV *sv, int how_much);
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 const char const *http_code_to_msg (int code);
static int prep_socket (int fd);
static HV *feer_stash, *feer_conn_stash;
static HV *feer_conn_reader_stash = NULL, *feer_conn_writer_stash = NULL;
static SV *request_cb_cv = NULL;
static SV *shutdown_cb_cv = NULL;
static bool shutting_down = 0;
static int active_conns = 0;
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;
static const char const *
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 flags;
struct linger linger = { .l_onoff = 0, .l_linger = 0 };
// make it non-blocking
flags = O_NONBLOCK;
if (fcntl(fd, F_SETFL, flags) < 0)
return -1;
// flush writes immediately
flags = 1;
#if PERL_DARWIN
if (setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &flags, sizeof(int)))
#else
if (setsockopt(fd, SOL_TCP, TCP_NODELAY, &flags, sizeof(int)))
#endif
return -1;
// handle URG data inline
flags = 1;
if (setsockopt(fd, SOL_SOCKET, SO_OOBINLINE, &flags, sizeof(int)))
return -1;
// disable lingering
if (setsockopt(fd, SOL_SOCKET, SO_LINGER, &linger, sizeof(linger)))
return -1;
return 0;
}
static struct feer_conn *
new_feer_conn (EV_P_ int conn_fd)
{
// allocate an SV that can hold the feer_conn PLUS a string for the fd
// so that dumping the SV from interpreter-land
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);
STRLEN label_len = snprintf(
c->label, CONN_LABEL_LENGTH, "%"IVdf, conn_fd);
// make the var readonly and make the visible portion just the fd number
SvCUR_set(self, label_len);
SvREADONLY_on(self); // turn off later for blessing
c->self = self;
c->fd = conn_fd;
if (prep_socket(c->fd)) {
perror("prep_socket");
trace("prep_socket failed for %d", c->fd);
}
c->loop = loop; // from EV_P_
// TODO: these initializations should be Lazy
ev_io_init(&c->read_ev_io, try_conn_read, conn_fd, EV_READ);
c->read_ev_io.data = (void *)c;
ev_io_init(&c->write_ev_io, try_conn_write, conn_fd, EV_WRITE);
c->write_ev_io.data = (void *)c;
#ifdef DEBUG
sv_dump(self);
#endif
trace("made conn fd=%d self=%p, c=%p, cur=%d, len=%d\n",
c->fd, self, c, SvCUR(self), SvLEN(self));
active_conns++;
return c;
}
// for use in the typemap:
INLINE_UNLESS_DEBUG static struct feer_conn *
sv_2feer_conn (SV *rv)
{
if (!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)
{
SV *rv = newRV_inc(c->self);
if (!SvOBJECT(c->self)) {
trace("c->self not yet an object, SvCUR:%d\n",SvCUR(c->self));
SvREADONLY_off(c->self);
// XXX: should this block use newRV_noinc instead?
sv_bless(rv, feer_conn_stash);
SvREADONLY_on(c->self);
}
return rv;
}
INLINE_UNLESS_DEBUG static feer_conn_handle *
sv_2feer_conn_handle (SV *rv, bool can_croak)
{
trace("sv 2 conn_handle\n");
if (!SvROK(rv))
croak("Expected a reference");
// do not allow subclassing
SV *sv = SvRV(rv);
if (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 (struct feer_conn *c, bool is_writer)
{
SV *sv;
SvREFCNT_inc(c->self);
sv = newRV_noinc(newSVuv(PTR2UV(c)));
sv_bless(sv, is_writer ? feer_conn_writer_stash : feer_conn_reader_stash);
return sv;
}
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 (c->wbuf && SvCUR(c->wbuf) > 0) {
// 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)
{
trace("prepare!\n");
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)
{
trace("check! head=%p\n", request_ready_rinq);
process_request_ready_rinq();
}
static void
idle_cb (EV_P_ ev_idle *w, int revents)
{
trace("idle! head=%p\n", 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;
if (!c->wbuf || SvCUR(c->wbuf) == 0) {
trace("tried to write with an empty buffer %d\n",w->fd);
ev_io_stop(EV_A, w);
return;
}
// TODO: handle errors in revents?
trace("going to write %d %ld %p\n",w->fd, SvCUR(c->wbuf), SvPVX(c->wbuf));
STRLEN buflen;
const char *bufptr = SvPV(c->wbuf, buflen);
ssize_t wrote = write(w->fd, bufptr, buflen);
trace("wrote %d bytes to %d\n", wrote, w->fd);
if (wrote == -1) {
if (errno == EAGAIN || errno == EINTR)
goto try_write_again;
perror("try_conn_write");
goto try_write_finished;
}
// check for more work
if (SvCUR(c->wbuf) == wrote) {
trace("All done with %d\n",w->fd);
SvREFCNT_dec(c->wbuf); c->wbuf = NULL;
goto try_write_finished;
}
trace("More work to do %d: cur=%d len=%d ivx=%d\n",w->fd, SvCUR(c->wbuf), SvLEN(c->wbuf), SvIVX(c->wbuf));
// remove written bytes from the front of the string (using the OOK hack)
offset_sv(c->wbuf, wrote);
try_write_again:
trace("write again %d\n",w->fd);
if (!ev_is_active(w)) {
ev_io_start(EV_A, w);
}
return;
try_write_finished:
// TODO: call a drain callback with success/error
ev_io_stop(EV_A, w);
// should always be responding, but just in case
if (!c->responding || c->responding == RESPOND_SHUTDOWN) {
shutdown(c->fd, SHUT_WR);
// sleep(1);
trace("ref dec after write %d\n", c->fd);
// TODO: call a completion callback instead of just GCing
SvREFCNT_dec(c->self);
}
return;
}
static int
try_parse_http(struct feer_conn *c, size_t last_read)
{
struct feer_req *req = c->req;
if (!req) {
req = (struct feer_req *)
calloc(1,sizeof(struct feer_req));
req->num_headers = MAX_HEADERS;
c->req = req;
}
return phr_parse_request(SvPVX(c->rbuf), SvCUR(c->rbuf),
&req->method, &req->method_len,
&req->path, &req->path_len, &req->minor_version,
req->headers, &req->num_headers,
(SvCUR(c->rbuf)-last_read));
}
#define READ_CHUNK 4096
static void
try_conn_read(EV_P_ ev_io *w, int revents)
{
dCONN;
// TODO: handle errors in revents?
if (c->receiving == RECEIVE_SHUTDOWN) {
ev_io_stop(EV_A, w);
return;
}
trace("try read %d\n",w->fd);
if (!c->rbuf) {
trace("init rbuf for %d\n",w->fd);
c->rbuf = newSV(2*READ_CHUNK + 1);
#ifdef DEBUG
sv_dump(c->rbuf);
#endif
}
if (SvLEN(c->rbuf) - SvCUR(c->rbuf) < READ_CHUNK) {
size_t new_len = SvLEN(c->rbuf) + READ_CHUNK;
trace("moar memory %d: %d to %d\n",w->fd, SvLEN(c->rbuf),new_len);
SvGROW(c->rbuf, new_len);
}
char *cur = SvPVX(c->rbuf) + SvCUR(c->rbuf);
ssize_t got_n = read(w->fd, cur, READ_CHUNK);
if (got_n == -1) {
if (errno == EAGAIN || errno == EINTR)
goto try_read_again;
perror("try_conn_read");
goto try_read_error;
}
else if (got_n == 0) {
trace("EOF before complete request: %d\n",w->fd,SvCUR(c->rbuf));
goto try_read_error;
}
trace("read %d %d\n", w->fd, got_n);
SvCUR(c->rbuf) += got_n;
if (c->receiving == RECEIVE_HEADERS) {
int ret = try_parse_http(c, (size_t)got_n);
if (ret == -1) goto try_read_error;
if (ret == -2) goto try_read_again;
if (process_request_headers(c, ret))
goto try_read_again;
else
goto dont_read_again;
}
else if (c->receiving == RECEIVE_BODY) {
c->received_cl += got_n;
if (c->received_cl < c->expected_cl)
goto try_read_again;
// body is complete
sched_request_callback(c);
goto dont_read_again;
}
else {
warn("unknown read state %d %d", w->fd, c->receiving);
}
try_read_error:
trace("try read error %d\n", w->fd);
ev_io_stop(EV_A, w);
c->receiving = RECEIVE_SHUTDOWN;
c->responding = RESPOND_SHUTDOWN;
shutdown(c->fd, SHUT_RDWR);
SvREFCNT_dec(c->self);
return;
dont_read_again:
c->receiving = RECEIVE_SHUTDOWN;
shutdown(c->fd, SHUT_RD); // TODO: respect keep-alive
ev_io_stop(EV_A, w);
return;
try_read_again:
trace("read again %d\n", w->fd);
if (!ev_is_active(w)) {
ev_io_start(EV_A,w);
}
return;
}
static void
accept_cb (EV_P_ ev_io *w, int revents)
{
struct sockaddr_in sa;
socklen_t sl = sizeof(struct sockaddr_in);
trace("accept! revents=0x%08x\n", revents);
if (!(revents & EV_READ))
return;
if (shutting_down) {
// shouldn't get called, but be defensive
close(w->fd);
ev_io_stop(EV_A, w);
return;
}
while (1) {
sl = sizeof(struct sockaddr_in);
int fd = accept(w->fd, (struct sockaddr *)&sa, &sl);
if (fd == -1) break;
// TODO: put the sockaddr in with the conn
struct feer_conn *c = new_feer_conn(EV_A, fd);
// XXX: good idea to read right away?
// try_conn_read(EV_A, &c->read_ev_io, EV_READ);
ev_io_start(EV_A, &c->read_ev_io);
}
}
static void
sched_request_callback (struct feer_conn *c)
{
trace("rinq push: c=%p, head=%p\n", c, request_ready_rinq);
rinq_push(&request_ready_rinq, c);
SvREFCNT_inc(c->self); // for the rinq
if (!ev_is_active(&ei)) {
ev_idle_start(c->loop, &ei);
}
}
static bool
process_request_headers (struct feer_conn *c, int body_offset)
{
int err_code;
const char *err;
struct feer_req *req = c->req;
trace("body follows headers, making new rbuf\n");
bool body_is_required;
c->receiving = RECEIVE_BODY;
if (str_eq("GET", 3, req->method, req->method_len) ||
str_eq("HEAD", 4, req->method, req->method_len) ||
str_eq("DELETE", 6, req->method, req->method_len))
{
// Not supposed to have a body. Additional bytes are either a mistake
// or pipelined requests under HTTP/1.1
// XXX ignore them for now
goto got_it_all;
}
else if (str_eq("PUT", 3, req->method, req->method_len) ||
str_eq("POST", 4, req->method, req->method_len))
{
// MUST have a body
body_is_required = 1;
}
else {
err = "Feersum doesn't support that method yet\n";
err_code = 405;
goto got_bad_request;
}
// a body potentially follows the headers. Let feer_req retain its
// pointers into rbuf and make a new scalar for more body data.
int need = SvCUR(c->rbuf) - body_offset;
char *from = SvPVX(c->rbuf) + body_offset;
SV *new_rbuf = newSV((need > 2*READ_CHUNK) ? need-1 : 2*READ_CHUNK-1);
if (need)
sv_setpvn(new_rbuf, from, need);
req->buf = c->rbuf;
c->rbuf = new_rbuf;
// determine how much we need to read
int i;
size_t expected = 0;
for (i=0; i < req->num_headers; i++) {
struct phr_header *hdr = &req->headers[i];
if (!hdr->name) continue;
// XXX: ignore multiple C-L headers?
if (str_case_eq("content-length", 14, hdr->name, hdr->name_len)) {
int g = grok_number(hdr->value, hdr->value_len, &expected);
if (g == IS_NUMBER_IN_UV) {
if (expected > MAX_BODY_LENGTH) {
err_code = 413;
err = "Content length exceeds maximum\n";
goto got_bad_request;
}
else
goto got_cl;
}
else {
err_code = 400;
err = "invalid content-length\n";
goto got_bad_request;
}
}
// TODO: support "Connection: close" bodies
// TODO: support "Transfer-Encoding: chunked" bodies
}
if (body_is_required) {
// Go the nginx route...
err_code = 411;
err = "Content-Length required\n";
}
else {
// XXX TODO support requests that don't require a body
err_code = 418;
err = "Feersum doesn't know how to handle optional-body requests yet\n";
}
got_bad_request:
respond_with_server_error(c, err, 0, err_code);
return 0;
got_cl:
c->expected_cl = expected;
c->received_cl = SvCUR(c->rbuf);
// don't have enough bytes to schedule immediately?
if (c->expected_cl && c->received_cl < c->expected_cl) {
// TODO: schedule the callback immediately and support a non-blocking
// ->read method.
// sched_request_callback(c);
// c->receiving = RECEIVE_STREAM;
return 1;
}
// fallthrough: have enough bytes
got_it_all:
c->receiving = RECEIVE_SHUTDOWN;
shutdown(c->fd, SHUT_RD);
sched_request_callback(c);
return 0;
}
static void
conn_write_ready (struct feer_conn *c)
{
if (c->in_callback) return; // defer until out of callback
if (!ev_is_active(&c->write_ev_io)) {
#if AUTOCORK_WRITES
ev_io_start(c->loop, &c->write_ev_io);
#else
// attempt a non-blocking write immediately if we're not already
// waiting for writability
try_conn_write(c->loop, &c->write_ev_io, EV_WRITE);
#endif
}
}
static void
offset_sv(SV *sv, int how_much)
{
if (!SvOOK(sv)) {
if (SvTYPE(sv) < SVt_PVIV)
SvUPGRADE(sv, SVt_PVIV);
SvOOK_on(sv);
SvIVX(sv) = 0;
}
SvIVX(sv) += how_much;
SvPVX(sv) += how_much;
SvCUR(sv) -= how_much;
SvLEN(sv) -= how_much;
}
static void
add_sv_to_wbuf (struct feer_conn *c, SV *sv, bool chunked)
{
if (sv == NULL || !SvOK(sv)) {
if (chunked) {
// last-chunk = 1*"0" CRLF CRLF
if (!c->wbuf)
c->wbuf = newSVpv("0" CRLFx2, 5);
else
sv_catpvn(c->wbuf, "0" CRLFx2, 5);
}
return;
}
if (SvUTF8(sv)) {
sv_utf8_encode(sv);
}
if (chunked) {
STRLEN len;
const char *ptr = SvPV(sv, len); // invoke magic if any
if (!c->wbuf) {
// make a buffer that can fit the data plus chunk envelope
STRLEN need = (len > READ_CHUNK) ? len+32 : READ_CHUNK-1;
c->wbuf = newSV(need);
SvPOK_on(c->wbuf);
}
/*
From http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.6.1
chunk-size = [0-9a-f]+
chunk = chunk-size CRLF chunk-data CRLF
*/
sv_catpvf(c->wbuf, "%x" CRLF, len);
sv_catpvn(c->wbuf, ptr, len);
sv_catpvn(c->wbuf, CRLF, 2);
}
else {
if (c->wbuf)
sv_catsv(c->wbuf, sv);
else {
// use newSV+sv_setsv instead of newSVsv so that we can steal the
// buffer if possible
c->wbuf = newSV(0);
sv_setsv(c->wbuf, sv);
}
}
}
static void
respond_with_server_error (struct feer_conn *c, const char *msg, STRLEN msg_len, int err_code)
{
SV *tmp;
if (c->responding) {
trouble("Tried to send server error but already responding!");
return;
}
if (!msg_len) msg_len = strlen(msg);
tmp = newSV(255);
sv_catpvf(tmp, "HTTP/1.1 %d %s" CRLF
"Content-Type: text/plain" CRLF
"Connection: close" CRLF
"Content-Length: %d" CRLFx2,
err_code, http_code_to_msg(err_code), msg_len);
sv_catpvn(tmp, msg, msg_len);
SvTEMP_on(tmp); // so add_sv_to_wbuf can optimize
add_sv_to_wbuf(c,tmp,0);
SvREFCNT_dec(tmp);
shutdown(c->fd, SHUT_RD);
c->responding = RESPOND_SHUTDOWN;
c->receiving = RECEIVE_SHUTDOWN;
conn_write_ready(c);
}
INLINE_UNLESS_DEBUG bool
str_eq(const char *a, int a_len, const char *b, int b_len)
{
if (a_len != b_len) return 0;
if (a == b) return 1;
int i;
for (i=0; i<a_len && i<b_len; i++) {
if (a[i] != b[i]) return 0;
}
return 1;
}
/*
* Compares two strings, assumes that the first string is already lower-cased
*/
INLINE_UNLESS_DEBUG bool
str_case_eq(const char *a, int a_len, const char *b, int b_len)
{
if (a_len != b_len) return 0;
if (a == b) return 1;
int i;
for (i=0; i<a_len && i<b_len; i++) {
if (a[i] != tolower(b[i])) return 0;
}
return 1;
}
INLINE_UNLESS_DEBUG int
hex_decode(const char ch)
{
if ('0' <= ch && ch <= '9')
return ch - '0';
else if ('A' <= ch && ch <= 'F')
return ch - 'A' + 10;
else if ('a' <= ch && ch <= 'f')
return ch - 'a' + 10;
return -1;
}
static void
uri_decode_sv (SV *sv)
{
STRLEN len;
char *ptr, *end, *decoded;
ptr = SvPV(sv, len);
end = SvEND(sv);
while (ptr < end) {
if (*ptr == '%') goto needs_decode;
ptr++;
}
return;
needs_decode:
// Up until ptr have been "decoded" already by virtue of those chars not
// being encoded.
decoded = ptr;
for (; ptr < end; ptr++) {
if (*ptr == '%' && end-ptr >= 2) {
int c1 = hex_decode(ptr[1]);
int c2 = hex_decode(ptr[2]);
if (c1 != -1 && c2 != -1) {
*decoded++ = (c1 << 4) + c2;
ptr += 2;
continue;
}
}
*decoded++ = *ptr;
}
*decoded = '\0'; // play nice with C
ptr = SvPV_nolen(sv);
SvCUR_set(sv, decoded-ptr);
}
void
call_request_callback (struct feer_conn *c)
{
dSP;
SV *sv_self;
c->in_callback++;
sv_self = feer_conn_2sv(c);
trace("request callback c=%p self=%p\n", c, sv_self);
ENTER;
SAVETMPS;
PUSHMARK(SP);
XPUSHs(sv_2mortal(sv_self));
trace("calling request callback, errsv? %d\n", SvTRUE(ERRSV) ? 1 : 0);
PUTBACK;
call_sv(request_cb_cv, G_DISCARD|G_EVAL|G_VOID);
SPAGAIN;
trace("called request callback, errsv? %d\n", SvTRUE(ERRSV) ? 1 : 0);
if (SvTRUE(ERRSV)) {
STRLEN err_len;
char *err = SvPV(ERRSV,err_len);
trace("an error was thrown in the request callback: %.*s\n",err_len,err);
PUSHMARK(SP);
XPUSHs(sv_2mortal(newSVsv(ERRSV)));
PUTBACK;
call_pv("Feersum::DIED", G_DISCARD|G_EVAL|G_VOID|G_KEEPERR);
SPAGAIN;
respond_with_server_error(c,"Request handler exception.\n",0,500);
sv_setsv(ERRSV, &PL_sv_undef);
}
trace("leaving request callback\n");
PUTBACK;
FREETMPS;
LEAVE;
c->in_callback--;
}
MODULE = Feersum PACKAGE = Feersum
PROTOTYPES: ENABLE
void
accept_on_fd(SV *self, int fd)
PPCODE:
{
trace("going to accept on %d\n",fd);
ev_prepare_init(&ep, prepare_cb);
ev_prepare_start(EV_DEFAULT, &ep);
ev_check_init(&ec, check_cb);
ev_check_start(EV_DEFAULT, &ec);
ev_idle_init(&ei, idle_cb);
ev_io_init(&accept_w, accept_cb, fd, EV_READ);
}
void
request_handler(SV *self, SV *cb)
PROTOTYPE: $&
PPCODE:
{
if (!SvROK(cb) || SvTYPE(SvRV(cb)) != SVt_PVCV)
croak("must supply a code reference");
if (request_cb_cv)
SvREFCNT_dec(request_cb_cv);
request_cb_cv = SvRV(cb);
SvREFCNT_inc(request_cb_cv);
trace("assigned request handler %p\n", SvRV(cb));
}
void
graceful_shutdown (SV *self, SV *cb)
PROTOTYPE: $&
PPCODE:
{
if (!SvROK(cb) || SvTYPE(SvRV(cb)) != SVt_PVCV)
croak("must supply a code reference");
if (shutting_down)
croak("already shutting down");
shutdown_cb_cv = SvRV(cb);
SvREFCNT_inc(shutdown_cb_cv);
trace("assigned shutdown handler %p\n", SvRV(cb));
shutting_down = 1;
ev_io_stop(EV_DEFAULT, &accept_w);
close(accept_w.fd);
}
void
DESTROY (SV *self)
PPCODE:
{