Repository navigation
Expand file tree
/
Copy pathcorHttpServer.c
More file actions
1484 lines (1191 loc) · 39.4 KB
/
Copy pathcorHttpServer.c
File metadata and controls
1484 lines (1191 loc) · 39.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//
// FILE corHttpServer.c
//
// AUTHOR Ken Zangelin
//
// Copyright 2026 Seamware
// SPDX-License-Identifier: Apache-2.0
//
// The event loop.
//
// One thread, epoll, edge-triggered. Everything that can block is non-blocking
// and everything that would need a thread per connection needs a state instead.
//
// EDGE-TRIGGERED is the decision the rest of this file answers to. Level
// triggering re-reports a readable socket on every epoll_wait until it is
// drained, which is forgiving; edge triggering reports the TRANSITION once, so
// a handler that reads part of what is available and returns will not be told
// again and the connection stalls until it happens to send more. Hence: every
// accept loops until EAGAIN, every read loops until EAGAIN, and nothing here
// may return early "having done some".
//
// ONE THREAD, and that is not a limitation being apologised for. The broker
// above runs the request off this thread on its own worker pool - see
// corHttpSuspend below - so this loop only ever does I/O, and an I/O loop that
// is single-threaded needs no lock on the connection pool, no atomic on the
// free list, and cannot interleave two responses on one socket.
//
#define _GNU_SOURCE // accept4
#include <errno.h> // errno, EAGAIN, EWOULDBLOCK, EINTR
#include <fcntl.h> // fcntl, O_NONBLOCK
#include <arpa/inet.h> // inet_pton
#include <netinet/in.h> // sockaddr_in, sockaddr_in6, INADDR_ANY
#include <netinet/tcp.h> // TCP_NODELAY
#include <pthread.h> // pthread_mutex_*
#include <stdio.h> // snprintf
#include <stdlib.h> // realloc, free
#include <string.h> // memset, strerror
#include <sys/epoll.h> // epoll_create1, epoll_ctl, epoll_wait
#include <sys/eventfd.h> // eventfd
#include <sys/sendfile.h> // sendfile
#include <sys/socket.h> // socket, bind, listen, accept4, setsockopt
#include <unistd.h> // read, write, close
#include "corBase/corCoLoop.h" // corCoLoopEvent, corCoLoopExpire, corCoLoopTimeoutMs
#include "corHttp/CorHttp.h" // CorHttpServer, CorHttpConn
#include "corHttp/corHttpInternal.h" // Own interface
//
// The resume queue - connections a worker thread has finished with.
//
// A worker cannot touch epoll or the connection's socket: it does not own the
// loop. So it puts the connection here and writes to the eventfd, and the loop
// wakes up and does the writing. The mutex covers the queue only, is held for
// the length of a pointer assignment, and is the single piece of cross-thread
// state in the library.
//
// -----------------------------------------------------------------------------
//
// nonBlocking -
//
static int nonBlocking(int fd)
{
int flags = fcntl(fd, F_GETFL, 0);
if (flags < 0)
return -1;
return fcntl(fd, F_SETFL, flags | O_NONBLOCK);
}
// -----------------------------------------------------------------------------
//
// listener - a bound, listening, non-blocking socket
//
// On every IPv4 interface without a bind address, else on the one address given (a numeric IPv4 or
// IPv6 address - not a host name, which may resolve to more than one, or to the other family).
//
static int listener(unsigned short port, const CorHttpListenOptions* optionsP)
{
const char* bindAddress = (optionsP != NULL) ? optionsP->bindAddress : NULL;
bool reusePort = (optionsP != NULL) ? optionsP->reusePort : false;
struct sockaddr_storage addr;
socklen_t addrLen;
memset(&addr, 0, sizeof(addr));
if ((bindAddress == NULL) || (bindAddress[0] == 0))
{
struct sockaddr_in* in4P = (struct sockaddr_in*) &addr;
in4P->sin_family = AF_INET;
in4P->sin_addr.s_addr = INADDR_ANY;
in4P->sin_port = htons(port);
addrLen = sizeof(struct sockaddr_in);
}
else
{
struct sockaddr_in* in4P = (struct sockaddr_in*) &addr;
struct sockaddr_in6* in6P = (struct sockaddr_in6*) &addr;
if (inet_pton(AF_INET, bindAddress, &in4P->sin_addr) == 1)
{
in4P->sin_family = AF_INET;
in4P->sin_port = htons(port);
addrLen = sizeof(struct sockaddr_in);
}
else if (inet_pton(AF_INET6, bindAddress, &in6P->sin6_addr) == 1)
{
in6P->sin6_family = AF_INET6;
in6P->sin6_port = htons(port);
addrLen = sizeof(struct sockaddr_in6);
}
else
{
errno = EINVAL;
return -1;
}
}
int fd = socket(addr.ss_family, SOCK_STREAM, 0);
if (fd < 0)
return -1;
//
// SO_REUSEADDR so a restart does not have to wait out TIME_WAIT on the
// previous process's sockets. Without it a broker that is restarted inside
// two minutes fails to bind, which in a test suite is every single run.
//
int one = 1;
setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one));
//
// SO_REUSEPORT only when asked for (reusePort): it is what lets MORE THAN ONE
// server hold this port, each with its own listen socket, its own epoll and its
// own thread - the loops of one process (corHttpAcceptShare). It lets a second
// PROCESS of the same user hold the port as well, and the kernel then hashes the
// connections between the two, so without it a second server on a port in use
// fails to bind (EADDRINUSE) instead of silently getting part of the traffic.
//
// A failure to set it is fatal: the caller asked for a shared port and the next
// server's bind would fail instead.
//
if (reusePort == true)
{
#ifdef SO_REUSEPORT
if (setsockopt(fd, SOL_SOCKET, SO_REUSEPORT, &one, sizeof(one)) < 0)
{
close(fd);
return -1;
}
#else
close(fd);
errno = ENOPROTOOPT;
return -1;
#endif
}
if (bind(fd, (struct sockaddr*) &addr, addrLen) < 0)
{
close(fd);
return -1;
}
//
// SOMAXCONN rather than a number of our own: the kernel's limit is the one
// that matters and picking a smaller one here would only cap it.
//
if (listen(fd, SOMAXCONN) < 0)
{
close(fd);
return -1;
}
if (nonBlocking(fd) < 0)
{
close(fd);
return -1;
}
return fd;
}
// -----------------------------------------------------------------------------
//
// epollSet - add or modify a connection's interest set
//
static int epollSet(CorHttpServer* serverP, CorHttpConn* connP, uint32_t events, int op)
{
struct epoll_event ev;
memset(&ev, 0, sizeof(ev));
ev.events = events | EPOLLET;
ev.data.ptr = connP;
return epoll_ctl(serverP->epollFd, op, connP->fd, &ev);
}
// -----------------------------------------------------------------------------
//
// requestDone - tell the caller its request is over
//
// Guarded on userData rather than on a flag of its own: userData is the ONLY
// thing the caller has hung on the connection, so "there is something to free"
// and "userData is set" are the same question. The callback clears it, which is
// also what makes this idempotent - a response that completes and a connection
// that is then closed both come through here, and the second finds nothing.
//
static void requestDone(CorHttpServer* serverP, CorHttpConn* connP)
{
if ((serverP->doneCb != NULL) && (connP->userData != NULL))
serverP->doneCb(connP);
}
// -----------------------------------------------------------------------------
//
// connClose -
//
static void connClose(CorHttpServer* serverP, CorHttpConn* connP)
{
//
// Before the connection goes back to the pool, not after: the callback may
// still want to read the request it was given, and every slice of it points
// into a read buffer this connection is about to hand to the next client.
//
requestDone(serverP, connP);
if (connP->fd != -1)
epoll_ctl(serverP->epollFd, EPOLL_CTL_DEL, connP->fd, NULL);
corHttpConnPut(serverP, connP);
}
// -----------------------------------------------------------------------------
//
// connTake - an accepted socket becomes a connection of this loop
//
static void connTake(CorHttpServer* serverP, int fd)
{
//
// TCP_NODELAY: responses are small and complete, and Nagle would hold the
// last partial segment waiting for more that is never coming - up to 40 ms
// added to a response that was ready.
//
int one = 1;
setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &one, sizeof(one));
CorHttpConn* connP = corHttpConnGet(serverP, fd);
if (connP == NULL)
{
//
// Pool exhausted. Closing immediately is the honest answer: accepting it
// to hold it in a queue would trade a refused connection for a hung one,
// and the client cannot tell the difference until it times out.
//
close(fd);
return;
}
if (epollSet(serverP, connP, EPOLLIN, EPOLL_CTL_ADD) < 0)
connClose(serverP, connP);
}
// -----------------------------------------------------------------------------
//
// acceptAll - drain the listen backlog
//
// Loops until EAGAIN because the listener is edge-triggered too: two
// connections arriving between wakeups produce ONE event, and an accept loop
// that took a single connection would leave the second waiting for a third to
// arrive before it was noticed.
//
static void acceptAll(CorHttpServer* serverP)
{
while (true)
{
int fd = accept4(serverP->listenFd, NULL, NULL, SOCK_NONBLOCK);
if (fd < 0)
{
if ((errno == EAGAIN) || (errno == EWOULDBLOCK))
break;
if (errno == EINTR)
continue;
break;
}
connTake(serverP, fd);
}
}
// -----------------------------------------------------------------------------
//
// acceptDeal - the accepting loop of a group: each new connection to the next loop in turn
//
static void acceptDeal(CorHttpServer* serverP)
{
while (true)
{
int fd = accept4(serverP->listenFd, NULL, NULL, SOCK_NONBLOCK);
if (fd < 0)
{
if (errno == EINTR)
continue;
break; // EAGAIN: the backlog is drained
}
CorHttpServer* toP = &serverP->acceptV[serverP->acceptNext];
serverP->acceptNext = (serverP->acceptNext + 1) % serverP->acceptN;
if (toP == serverP)
{
connTake(serverP, fd);
continue;
}
pthread_mutex_lock(&toP->handMutex);
if (toP->handCount == toP->handSize)
{
int size = (toP->handSize == 0) ? 64 : toP->handSize * 2;
int* v = realloc(toP->handV, size * sizeof(int));
if (v == NULL)
{
pthread_mutex_unlock(&toP->handMutex);
close(fd);
continue;
}
toP->handV = v;
toP->handSize = size;
}
toP->handV[toP->handCount++] = fd;
pthread_mutex_unlock(&toP->handMutex);
uint64_t one = 1;
ssize_t ignored = write(toP->handFd, &one, sizeof(one));
(void) ignored;
}
}
// -----------------------------------------------------------------------------
//
// handDrain - the connections the accepting loop dealt to this one
//
static void handDrain(CorHttpServer* serverP)
{
uint64_t counter;
ssize_t ignored = read(serverP->handFd, &counter, sizeof(counter));
(void) ignored;
while (true)
{
int fd = -1;
pthread_mutex_lock(&serverP->handMutex);
if (serverP->handCount > 0)
fd = serverP->handV[--serverP->handCount];
pthread_mutex_unlock(&serverP->handMutex);
if (fd < 0)
return;
connTake(serverP, fd);
}
}
// -----------------------------------------------------------------------------
//
// readAll - drain the socket into the connection buffer
//
static CorHttpStatus readAll(CorHttpServer* serverP, CorHttpConn* connP)
{
while (true)
{
int room = connP->bufSize - connP->bufUsed - 1; // -1: the parser's terminator
if (room < 1024)
{
CorHttpStatus s = corHttpConnBufGrow(serverP, connP, 1024);
if (s != CorHttpOk)
return s;
room = connP->bufSize - connP->bufUsed - 1;
}
ssize_t n = read(connP->fd, connP->buf + connP->bufUsed, room);
if (n < 0)
{
if ((errno == EAGAIN) || (errno == EWOULDBLOCK))
return CorHttpOk; // drained; what we have is all there is for now
if (errno == EINTR)
continue;
return CorHttpError;
}
if (n == 0)
return CorHttpClosed;
connP->bufUsed += n;
}
}
// -----------------------------------------------------------------------------
//
// writeAll - push out the rendered response, or as much as the socket takes
//
// Returns CorHttpAgain when the socket filled up. The caller then arms EPOLLOUT
// and comes back; writePos is the whole of the state that has to survive.
//
static CorHttpStatus writeAll(CorHttpConn* connP)
{
while (connP->writePos < connP->writeLen)
{
ssize_t n = write(connP->fd, connP->writeBuf + connP->writePos, connP->writeLen - connP->writePos);
if (n < 0)
{
if ((errno == EAGAIN) || (errno == EWOULDBLOCK))
return CorHttpAgain;
if (errno == EINTR)
continue;
return CorHttpError;
}
connP->writePos += n;
}
return CorHttpOk;
}
// -----------------------------------------------------------------------------
//
// upgradeHand - the 101 is written: the socket leaves this server, to the caller's upgrade callback
//
// The bytes the client sent behind the request are copied out first - they live in the read buffer,
// which goes back to the pool with the connection. The connection is put back with fd -1, so it is
// not closed: the socket is the callback's now.
//
static void upgradeHand(CorHttpServer* serverP, CorHttpConn* connP)
{
CorHttpUpgradeCb cb = connP->upgradeCb;
void* cls = connP->upgradeCls;
int fd = connP->fd;
int extraLen = connP->bufUsed - connP->requestEnd;
char* extra = NULL;
if (extraLen > 0)
{
extra = (char*) malloc(extraLen);
if (extra != NULL)
memcpy(extra, &connP->buf[connP->requestEnd], extraLen);
else
extraLen = 0;
}
else
extraLen = 0;
requestDone(serverP, connP);
epoll_ctl(serverP->epollFd, EPOLL_CTL_DEL, fd, NULL);
connP->fd = -1;
corHttpConnPut(serverP, connP);
cb(fd, extra, extraLen, cls);
free(extra);
}
// -----------------------------------------------------------------------------
//
// corHttpUpgrade -
//
void corHttpUpgrade(CorHttpConn* connP, CorHttpUpgradeCb cb, void* cls)
{
connP->upgradeCb = cb;
connP->upgradeCls = cls;
}
static void responseDone(CorHttpServer* serverP, CorHttpConn* connP);
// -----------------------------------------------------------------------------
//
// chunkFrame - the next bytes of a stream in the write buffer, framed: "<hex length>\r\n<bytes>\r\n",
// and the terminating "0\r\n\r\n" behind them when the writer has ended. Raw for an HTTP/1.0 client.
//
static bool chunkFrame(CorHttpConn* connP, CorHttpStream* sP, char* data, int len, bool last)
{
int size = len + 32;
free(connP->writeBuf);
connP->writeBuf = (char*) malloc(size);
connP->writeLen = 0;
connP->writePos = 0;
if (connP->writeBuf == NULL)
return false;
char* p = connP->writeBuf;
if (len > 0)
{
if (sP->chunked == true)
p += snprintf(p, 16, "%x\r\n", len);
memcpy(p, data, len);
p += len;
if (sP->chunked == true)
{
*p++ = '\r';
*p++ = '\n';
}
}
if ((last == true) && (sP->chunked == true))
{
memcpy(p, "0\r\n\r\n", 5);
p += 5;
}
connP->writeLen = (int) (p - connP->writeBuf);
return true;
}
// -----------------------------------------------------------------------------
//
// bodyPump - a file or a stream body, after its headers: as much as the socket takes
//
// true: the body is complete - the response is over, as an in-memory one is when its buffer is out.
// false: waiting (for the socket - EPOLLOUT is armed - or for the stream's writer, whose next write
// wakes the loop), or the connection was closed.
//
static bool bodyPump(CorHttpServer* serverP, CorHttpConn* connP)
{
while (true)
{
CorHttpStatus s = writeAll(connP);
if (s == CorHttpAgain)
{
epollSet(serverP, connP, EPOLLIN | EPOLLOUT, EPOLL_CTL_MOD);
return false;
}
if (s != CorHttpOk)
{
connClose(serverP, connP);
return false;
}
connP->lastActivity = corHttpNowMs();
if (connP->fileFd != -1)
{
while (connP->fileLeft > 0)
{
off_t off = (off_t) connP->fileOffset;
size_t want = (connP->fileLeft > (1 << 30)) ? (1 << 30) : (size_t) connP->fileLeft;
ssize_t n = sendfile(connP->fd, connP->fileFd, &off, want);
if (n < 0)
{
if ((errno == EAGAIN) || (errno == EWOULDBLOCK))
{
epollSet(serverP, connP, EPOLLIN | EPOLLOUT, EPOLL_CTL_MOD);
return false;
}
if (errno == EINTR)
continue;
connClose(serverP, connP);
return false;
}
if (n == 0)
{
//
// The file is shorter than the Content-Length already sent: nothing can make the response
// right - the client sees the connection close before the length it was promised
//
connClose(serverP, connP);
return false;
}
connP->fileOffset += n;
connP->fileLeft -= n;
connP->lastActivity = corHttpNowMs();
}
corHttpBodyRelease(connP);
return true;
}
CorHttpStream* sP = connP->streamP;
if (sP == NULL)
return true; // no body of its own (HEAD), or done
if (sP->lastQueued == true)
{
corHttpBodyRelease(connP); // the terminating chunk is out
return true;
}
int len;
bool ended;
bool overflow;
char* data = corHttpStreamTake(sP, &len, &ended, &overflow);
if (overflow == true)
{
free(data);
connClose(serverP, connP); // the client fell too far behind
return false;
}
if ((len == 0) && (ended == false))
{
free(data);
return false; // the writer's next write wakes the loop
}
bool ok = chunkFrame(connP, sP, data, len, ended);
free(data);
if (ok == false)
{
connClose(serverP, connP);
return false;
}
sP->lastQueued = ended;
}
}
// -----------------------------------------------------------------------------
//
// streamDrain - the streams whose writers wrote or ended: their connections written to
//
static void streamDrain(CorHttpServer* serverP)
{
pthread_mutex_lock(&serverP->resumeMutex);
CorHttpStream* sP = serverP->streamHead;
serverP->streamHead = NULL;
pthread_mutex_unlock(&serverP->resumeMutex);
while (sP != NULL)
{
CorHttpStream* nextP = sP->next;
pthread_mutex_lock(&sP->mutex);
sP->queued = false;
sP->next = NULL;
pthread_mutex_unlock(&sP->mutex);
//
// The connection, if it is still this stream's and its headers are rendered (a stream started by a
// suspended request waits for corHttpResume). The rest of the body follows the response's own path.
//
CorHttpConn* connP = sP->connP;
if ((connP != NULL) && (sP->started == true) && (connP->state == COR_HTTP_CONN_WRITING) && (connP->streamP == sP))
{
if (bodyPump(serverP, connP) == true)
responseDone(serverP, connP);
}
corHttpStreamUnref(sP); // the queue's reference
sP = nextP;
}
}
// -----------------------------------------------------------------------------
//
// responseSend - render and write, and decide what happens to the connection
//
static void responseSend(CorHttpServer* serverP, CorHttpConn* connP)
{
if (corHttpResponseRender(connP) != CorHttpOk)
{
connClose(serverP, connP);
return;
}
CorHttpStatus s = writeAll(connP);
if (s == CorHttpAgain)
{
connP->state = COR_HTTP_CONN_WRITING;
epollSet(serverP, connP, EPOLLIN | EPOLLOUT, EPOLL_CTL_MOD);
return;
}
if (s != CorHttpOk)
{
connClose(serverP, connP);
return;
}
//
// A file or a stream: the headers are out, the body follows as the socket takes it - or, for a stream,
// as its writer writes it
//
if ((connP->fileFd != -1) || (connP->streamP != NULL))
{
connP->state = COR_HTTP_CONN_WRITING;
if (bodyPump(serverP, connP) == false)
return;
}
responseDone(serverP, connP);
}
// -----------------------------------------------------------------------------
//
// responseDone - the whole response is out: the next request on the connection, or close it
//
static void responseDone(CorHttpServer* serverP, CorHttpConn* connP)
{
connP->requests++;
connP->lastActivity = corHttpNowMs();
if (connP->upgradeCb != NULL)
{
upgradeHand(serverP, connP);
return;
}
requestDone(serverP, connP);
if ((connP->keepAlive == false) || (serverP->keepAliveTimeout == 0))
{
connClose(serverP, connP);
return;
}
corHttpConnReset(connP);
connP->state = COR_HTTP_CONN_READING;
epollSet(serverP, connP, EPOLLIN, EPOLL_CTL_MOD);
}
// -----------------------------------------------------------------------------
//
// errorSend - answer without troubling the caller
//
// For the failures the engine itself detects: a request it cannot parse, or one
// bigger than the cap. The caller's callback never sees these, because there is
// nothing coherent to hand it.
//
static void errorSend(CorHttpServer* serverP, CorHttpConn* connP, int statusCode)
{
connP->respHeaders = 0;
connP->respBody = NULL;
connP->respBodyLen = 0;
connP->keepAlive = false; // the stream is out of sync; do not reuse it
corHttpResponseStatus(connP, statusCode);
responseSend(serverP, connP);
}
// -----------------------------------------------------------------------------
//
// requestReady - a whole request has arrived; hand it over
//
static void requestReady(CorHttpServer* serverP, CorHttpConn* connP)
{
CorHttpStatus s = corHttpParse(connP);
if (s == CorHttpAgain)
{
//
// Once per request, not once per read: a client that asked for it is told
// to go ahead, and telling it twice would put a second interim response on
// the wire for a body already on its way.
//
if ((connP->expectContinue == true) && (connP->continueSent == false))
{
connP->continueSent = true;
corHttpContinueSend(connP);
}
return; // wait for the rest of it
}
if (s == CorHttpTooLarge)
{
errorSend(serverP, connP, 413);
return;
}
if (s != CorHttpOk)
{
errorSend(serverP, connP, 400);
return;
}
if (connP->headersTruncated)
{
errorSend(serverP, connP, 431);
return;
}
connP->statusCode = 0;
connP->inCallback = true;
serverP->requestCb(connP);
connP->inCallback = false;
//
// A callback that suspended has taken ownership: a worker thread will answer,
// and this loop must not touch the connection again until it comes back
// through the resume queue.
//
if (connP->state == COR_HTTP_CONN_IDLE)
return;
responseSend(serverP, connP);
}
// -----------------------------------------------------------------------------
//
// corHttpSuspend - the callback is handing this request to another thread
//
// Called from INSIDE the callback. The connection stops being the loop's
// business: no epoll interest, no timeout sweep, no reuse - until
// corHttpResume() puts it back.
//
// "No epoll interest" is a DELETE and not merely a state change. Left armed,
// the fd still reports EPOLLHUP the moment the client hangs up - and this loop
// would then close a connection a worker thread is still holding, returning it
// to the pool to be handed to the next client while the worker writes its
// answer into it. A client that gives up on a slow request is not a rare
// event; it is what a timeout looks like.
//
void corHttpSuspend(CorHttpConn* connP)
{
CorHttpServer* serverP = connP->serverP;
if ((serverP != NULL) && (connP->fd != -1))
epoll_ctl(serverP->epollFd, EPOLL_CTL_DEL, connP->fd, NULL);
connP->state = COR_HTTP_CONN_IDLE;
}
// -----------------------------------------------------------------------------
//
// corHttpResume - a worker has finished; the response is ready to go out
//
// Safe from any thread, and the only function here that is. It touches the
// queue and the eventfd and nothing else - in particular it does NOT write to
// the socket, because that is the loop's, and two threads writing one response
// is how a broker interleaves two answers on one connection.
//
void corHttpResume(CorHttpConn* connP)
{
CorHttpServer* serverP = connP->serverP; // the loop that owns this connection
pthread_mutex_lock(&serverP->resumeMutex);
connP->next = serverP->resumeHead;
serverP->resumeHead = connP;
pthread_mutex_unlock(&serverP->resumeMutex);
if (serverP->resumeFd != -1)
{
uint64_t one = 1;
ssize_t ignored = write(serverP->resumeFd, &one, sizeof(one));
(void) ignored; // a full counter means the loop is already awake
}
}
// -----------------------------------------------------------------------------
//
// corHttpResumeHere - the response is ready, and this IS the loop's thread: send it now
//
// What resumeDrain does for a connection a worker handed back, without the queue and the eventfd -
// for a request that ran as a coroutine of this loop.
//
void corHttpResumeHere(CorHttpConn* connP)
{
CorHttpServer* serverP = connP->serverP;
connP->state = COR_HTTP_CONN_WRITING;
epollSet(serverP, connP, EPOLLIN, EPOLL_CTL_ADD); // ADD: corHttpSuspend removed it
//
// Still inside the callback - a coroutine that finished without ever waiting: requestReady sends the
// response when the callback returns, as for any answer given there. Sent here as well, it went out
// twice - the second an empty one, which a keep-alive client took for its next request's answer.
//
if (connP->inCallback == true)
return;
responseSend(serverP, connP);
}
// -----------------------------------------------------------------------------
//
// resumeDrain - send the responses the workers finished with
//
static void resumeDrain(CorHttpServer* serverP)
{
uint64_t counter;
ssize_t ignored = read(serverP->resumeFd, &counter, sizeof(counter));
(void) ignored;
pthread_mutex_lock(&serverP->resumeMutex);
CorHttpConn* connP = serverP->resumeHead;
serverP->resumeHead = NULL;
pthread_mutex_unlock(&serverP->resumeMutex);
while (connP != NULL)
{
CorHttpConn* nextP = connP->next;
connP->next = NULL;
connP->state = COR_HTTP_CONN_WRITING;
//
// ADD and not MOD: corHttpSuspend removed this fd from the event set, so
// there is no interest to modify. responseSend may need EPOLLOUT if the
// answer does not fit the socket buffer, and that MOD needs a registration
// to modify.
//
epollSet(serverP, connP, EPOLLIN, EPOLL_CTL_ADD);
responseSend(serverP, connP);
connP = nextP;
}
streamDrain(serverP); // the same eventfd wakes the loop for the streams
}
// -----------------------------------------------------------------------------
//
// sinkRead - read what the client sent while its response's body is being written, and drop it
//
// Not into the read buffer: the request the response answers is still there, and a caller may read it