forked from phusion/passenger
-
Notifications
You must be signed in to change notification settings - Fork 0
/
RequestHandler.h
2141 lines (1832 loc) · 68.1 KB
/
RequestHandler.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Phusion Passenger - http://www.modrails.com/
* Copyright (c) 2011, 2012 Phusion
*
* "Phusion Passenger" is a trademark of Hongli Lai & Ninh Bui.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
/*
STAGES
Accept connect password
|
\|/
Read header
|
\|/
+------+------+
| |
| |
\|/ |
Buffer |
request |
body |
| |
| |
\|/ |
Checkout <-------+
session
|
|
\|/
Send header
to app
|
|
\|/
Send request
body to app
OVERVIEW OF I/O CHANNELS, PIPES AND WATCHERS
OPTIONAL: appOutputWatcher
clientBodyBuffer (o)
| |
+----------+ | +-----------+ | +---------------+
| | ------ clientInput -----> | Request | ----------------> | |
| Client | fd | Handler | session | Application |
| | <--- clientOutputPipe --- | | <--- appInput --- | |
+----------+ | +-----------+ +---------------+
|
(o)
clientOutputWatcher
*/
#ifndef _PASSENGER_REQUEST_HANDLER_H_
#define _PASSENGER_REQUEST_HANDLER_H_
#include <boost/shared_ptr.hpp>
#include <boost/weak_ptr.hpp>
#include <boost/make_shared.hpp>
#include <ev++.h>
#if defined(__GLIBCXX__) || defined(__APPLE__)
#include <cxxabi.h>
#define CXX_ABI_API_AVAILABLE
#endif
#include <sys/types.h>
#include <arpa/inet.h>
#include <sys/un.h>
#include <typeinfo>
#include <cassert>
#include <cctype>
#include <Logging.h>
#include <EventedBufferedInput.h>
#include <MessageReadersWriters.h>
#include <Constants.h>
#include <HttpConstants.h>
#include <UnionStation.h>
#include <ApplicationPool2/Pool.h>
#include <Utils/StrIntUtils.h>
#include <Utils/IOUtils.h>
#include <Utils/HttpHeaderBufferer.h>
#include <Utils/Template.h>
#include <Utils/Timer.h>
#include <Utils/Dechunker.h>
#include <agents/HelperAgent/AgentOptions.h>
#include <agents/HelperAgent/FileBackedPipe.h>
#include <agents/HelperAgent/ScgiRequestParser.h>
namespace Passenger {
using namespace std;
using namespace boost;
using namespace oxt;
using namespace ApplicationPool2;
class RequestHandler;
#define RH_WARN(client, x) P_WARN("[Client " << client->name() << "] " << x)
#define RH_DEBUG(client, x) P_DEBUG("[Client " << client->name() << "] " << x)
#define RH_TRACE(client, level, x) P_TRACE(level, "[Client " << client->name() << "] " << x)
class Client: public enable_shared_from_this<Client> {
private:
struct ev_loop *getLoop() const;
const SafeLibevPtr &getSafeLibev() const;
unsigned int getConnectPasswordTimeout(const RequestHandler *handler) const;
static size_t onClientInputData(const EventedBufferedInputPtr &source, const StaticString &data);
static void onClientInputError(const EventedBufferedInputPtr &source, const char *message, int errnoCode);
static void onClientBodyBufferData(const FileBackedPipePtr &source,
const char *data, size_t size,
const FileBackedPipe::ConsumeCallback &callback);
static void onClientBodyBufferEnd(const FileBackedPipePtr &source);
static void onClientBodyBufferError(const FileBackedPipePtr &source, int errorCode);
static void onClientBodyBufferCommit(const FileBackedPipePtr &source);
static void onClientOutputPipeData(const FileBackedPipePtr &source,
const char *data, size_t size,
const FileBackedPipe::ConsumeCallback &callback);
static void onClientOutputPipeEnd(const FileBackedPipePtr &source);
static void onClientOutputPipeError(const FileBackedPipePtr &source, int errorCode);
static void onClientOutputPipeCommit(const FileBackedPipePtr &source);
void onClientOutputWritable(ev::io &io, int revents);
static size_t onAppInputData(const EventedBufferedInputPtr &source, const StaticString &data);
static void onAppInputChunk(const char *data, size_t size, void *userData);
static void onAppInputError(const EventedBufferedInputPtr &source, const char *message, int errnoCode);
void onAppOutputWritable(ev::io &io, int revents);
void onTimeout(ev::timer &timer, int revents);
static const char *boolStr(bool val) {
static const char *strs[] = { "false", "true" };
return strs[val];
}
void resetPrimitiveFields() {
requestHandler = NULL;
state = DISCONNECTED;
backgroundOperations = 0;
requestBodyIsBuffered = false;
freeBufferedConnectPassword();
connectedAt = 0;
contentLength = 0;
clientBodyAlreadyRead = 0;
checkoutSessionAfterCommit = false;
sessionCheckedOut = false;
sessionCheckoutTry = 0;
responseHeaderSeen = false;
chunkedResponse = false;
appRoot.clear();
}
void freeScopeLogs() {
endScopeLog(&scopeLogs.requestProxying, false);
endScopeLog(&scopeLogs.getFromPool, false);
endScopeLog(&scopeLogs.bufferingRequestBody, false);
endScopeLog(&scopeLogs.requestProcessing, false);
}
public:
/** Back reference to the RequestHandler that this Client is associated with.
* NULL when this Client is not in the pool or is disconnected. */
RequestHandler *requestHandler;
/** File descriptor of the client socket. Is empty when this Client is not
* in the pool or is disconnected. */
FileDescriptor fd;
/** The last associated file descriptor number is stored here. It is not
* cleared after disassociating. Its only purpose is to make logging calls
* like RH_DEBUG() print the correct client name after disconnect() is called.
* Do not use this value for anything else as it may not refer to a valid
* file descriptor. */
int fdnum;
/***** Client <-> RequestHandler I/O channels, pipes and watchers *****/
/** Client input channel. */
EventedBufferedInputPtr clientInput;
/** If request body buffering is turned on, it will be buffered into this FileBackedPipe. */
FileBackedPipePtr clientBodyBuffer;
/** Client output pipe. */
FileBackedPipePtr clientOutputPipe;
/** Client output channel watcher. */
ev::io clientOutputWatcher;
/***** RequestHandler <-> Application I/O channels, pipes and watchers *****/
/** Application input channel. */
EventedBufferedInputPtr appInput;
string appOutputBuffer;
/** Application output channel watcher. */
ev::io appOutputWatcher;
/***** State variables *****/
enum {
BEGIN_READING_CONNECT_PASSWORD,
STILL_READING_CONNECT_PASSWORD,
READING_HEADER,
BUFFERING_REQUEST_BODY,
CHECKING_OUT_SESSION,
SENDING_HEADER_TO_APP,
FORWARDING_BODY_TO_APP,
// Special states
WRITING_SIMPLE_RESPONSE,
DISCONNECTED
} state;
/* How many background operations are currently in progress, e.g.
* an asyncGet() or bodyBuffer.add(). If the client is disconnected
* while this flag is true, then the Client object is not reassociateable
* in order to give the completion callbacks a chance to cancel properly.
*/
unsigned int backgroundOperations;
struct {
char *data;
unsigned int alreadyRead;
} bufferedConnectPassword;
// Used for enforcing the connection timeout.
ev::timer timeoutTimer;
ev_tstamp connectedAt;
long long contentLength;
unsigned long long clientBodyAlreadyRead;
Options options;
ScgiRequestParser scgiParser;
SessionPtr session;
string appRoot;
struct {
UnionStation::ScopeLog
*requestProcessing,
*bufferingRequestBody,
*getFromPool,
*requestProxying;
} scopeLogs;
unsigned int sessionCheckoutTry;
bool requestBodyIsBuffered;
bool sessionCheckedOut;
bool checkoutSessionAfterCommit;
bool responseHeaderSeen;
bool chunkedResponse;
HttpHeaderBufferer responseHeaderBufferer;
Dechunker responseDechunker;
Client() {
fdnum = -1;
clientInput = make_shared< EventedBufferedInput<> >();
clientInput->onData = onClientInputData;
clientInput->onError = onClientInputError;
clientInput->userData = this;
clientBodyBuffer = make_shared<FileBackedPipe>("/tmp");
clientBodyBuffer->userData = this;
clientBodyBuffer->onData = onClientBodyBufferData;
clientBodyBuffer->onEnd = onClientBodyBufferEnd;
clientBodyBuffer->onError = onClientBodyBufferError;
clientBodyBuffer->onCommit = onClientBodyBufferCommit;
clientOutputPipe = make_shared<FileBackedPipe>("/tmp");
clientOutputPipe->userData = this;
clientOutputPipe->onData = onClientOutputPipeData;
clientOutputPipe->onEnd = onClientOutputPipeEnd;
clientOutputPipe->onError = onClientOutputPipeError;
clientOutputPipe->onCommit = onClientOutputPipeCommit;
clientOutputWatcher.set<Client, &Client::onClientOutputWritable>(this);
appInput = make_shared< EventedBufferedInput<> >();
appInput->onData = onAppInputData;
appInput->onError = onAppInputError;
appInput->userData = this;
appOutputWatcher.set<Client, &Client::onAppOutputWritable>(this);
timeoutTimer.set<Client, &Client::onTimeout>(this);
responseDechunker.onData = onAppInputChunk;
responseDechunker.userData = this;
bufferedConnectPassword.data = NULL;
bufferedConnectPassword.alreadyRead = 0;
memset(&scopeLogs, 0, sizeof(scopeLogs));
resetPrimitiveFields();
}
~Client() {
if (requestHandler != NULL) {
discard();
}
clientInput->userData = NULL;
clientBodyBuffer->userData = NULL;
clientOutputPipe->userData = NULL;
appInput->userData = NULL;
freeBufferedConnectPassword();
freeScopeLogs();
}
void associate(RequestHandler *handler, const FileDescriptor &_fd) {
assert(requestHandler == NULL);
requestHandler = handler;
fd = _fd;
fdnum = _fd;
state = BEGIN_READING_CONNECT_PASSWORD;
connectedAt = ev_time();
clientInput->reset(getSafeLibev().get(), _fd);
clientInput->start();
clientBodyBuffer->reset(getSafeLibev());
clientOutputPipe->reset(getSafeLibev());
clientOutputPipe->start();
clientOutputWatcher.set(getLoop());
clientOutputWatcher.set(_fd, ev::WRITE);
// appOutputWatcher is initialized in initiateSession.
timeoutTimer.set(getLoop());
timeoutTimer.start(getConnectPasswordTimeout(handler) / 1000.0, 0.0);
}
void disassociate() {
assert(requestHandler != NULL);
resetPrimitiveFields();
fd = FileDescriptor();
clientInput->reset(NULL, FileDescriptor());
clientBodyBuffer->reset();
clientOutputPipe->reset();
clientOutputWatcher.stop();
appInput->reset(NULL, FileDescriptor());
appOutputBuffer.resize(0);
appOutputWatcher.stop();
timeoutTimer.stop();
scgiParser.reset();
session.reset();
responseHeaderBufferer.reset();
responseDechunker.reset();
freeScopeLogs();
}
void discard() {
assert(requestHandler != NULL);
resetPrimitiveFields();
fd = FileDescriptor();
clientInput->stop();
clientBodyBuffer->reset();
clientOutputPipe->reset();
clientOutputWatcher.stop();
appInput->stop();
appOutputWatcher.stop();
timeoutTimer.stop();
freeScopeLogs();
}
bool reassociateable() const {
return requestHandler == NULL
&& backgroundOperations == 0
&& clientInput->resetable()
&& clientBodyBuffer->resetable()
&& clientOutputPipe->resetable()
&& appInput->resetable();
}
string name() const {
if (fdnum == -1) {
return "(null)";
} else {
return toString(fdnum);
}
}
bool connected() const {
return requestHandler != NULL;
}
const char *getStateName() const {
switch (state) {
case BEGIN_READING_CONNECT_PASSWORD:
return "BEGIN_READING_CONNECT_PASSWORD";
case STILL_READING_CONNECT_PASSWORD:
return "STILL_READING_CONNECT_PASSWORD";
case READING_HEADER:
return "READING_HEADER";
case BUFFERING_REQUEST_BODY:
return "BUFFERING_REQUEST_BODY";
case CHECKING_OUT_SESSION:
return "CHECKING_OUT_SESSION";
case SENDING_HEADER_TO_APP:
return "SENDING_HEADER_TO_APP";
case FORWARDING_BODY_TO_APP:
return "FORWARDING_BODY_TO_APP";
case WRITING_SIMPLE_RESPONSE:
return "WRITING_SIMPLE_RESPONSE";
case DISCONNECTED:
return "DISCONNECTED";
default:
return "UNKNOWN";
}
}
void freeBufferedConnectPassword() {
if (bufferedConnectPassword.data != NULL) {
free(bufferedConnectPassword.data);
bufferedConnectPassword.data = NULL;
bufferedConnectPassword.alreadyRead = 0;
}
}
bool shouldHalfCloseWrite() const {
return session->getProtocol() == "session";
}
bool useUnionStation() const {
return options.logger != NULL;
}
UnionStation::LoggerPtr getLogger() const {
return options.logger;
}
void beginScopeLog(UnionStation::ScopeLog **scopeLog, const char *name) {
if (options.logger != NULL) {
*scopeLog = new UnionStation::ScopeLog(options.logger, name);
}
}
void endScopeLog(UnionStation::ScopeLog **scopeLog, bool success = true) {
if (success && *scopeLog != NULL) {
(*scopeLog)->success();
}
delete *scopeLog;
*scopeLog = NULL;
}
void logMessage(const StaticString &message) {
options.logger->message(message);
}
void verifyInvariants() const {
assert((requestHandler == NULL) == (fd == -1));
assert((requestHandler == NULL) == (state == DISCONNECTED));
}
template<typename Stream>
void inspect(Stream &stream) const {
const char *indent = " ";
time_t the_time;
struct tm the_tm;
char timestr[60];
the_time = (time_t) connectedAt;
localtime_r(&the_time, &the_tm);
strftime(timestr, sizeof(timestr) - 1, "%F %H:%M:%S", &the_tm);
stream << indent << "host = " << (scgiParser.getHeader("HTTP_HOST").empty() ? "(empty)" : scgiParser.getHeader("HTTP_HOST")) << "\n";
stream << indent << "uri = " << (scgiParser.getHeader("REQUEST_URI").empty() ? "(empty)" : scgiParser.getHeader("REQUEST_URI")) << "\n";
stream << indent << "connected at = " << timestr << " (" << (unsigned long long) (ev_time() - connectedAt) << " sec ago)\n";
stream << indent << "state = " << getStateName() << "\n";
if (session == NULL) {
stream << indent << "session = NULL\n";
} else {
stream << indent << "session pid = " << session->getPid() << "\n";
stream << indent << "session gupid = " << session->getGupid() << "\n";
stream << indent << "session initiated = " << boolStr(session->initiated()) << "\n";
}
stream
<< indent << "requestBodyIsBuffered = " << boolStr(requestBodyIsBuffered) << "\n"
<< indent << "contentLength = " << contentLength << "\n"
<< indent << "clientBodyAlreadyRead = " << clientBodyAlreadyRead << "\n"
<< indent << "clientInput = " << clientInput.get() << " " << clientInput->inspect() << "\n"
<< indent << "clientInput started = " << boolStr(clientInput->isStarted()) << "\n"
<< indent << "clientBodyBuffer started = " << boolStr(clientBodyBuffer->isStarted()) << "\n"
<< indent << "clientBodyBuffer reachedEnd = " << boolStr(clientBodyBuffer->reachedEnd()) << "\n"
<< indent << "clientOutputPipe started = " << boolStr(clientOutputPipe->isStarted()) << "\n"
<< indent << "clientOutputPipe reachedEnd = " << boolStr(clientOutputPipe->reachedEnd()) << "\n"
<< indent << "clientOutputWatcher active = " << boolStr(clientOutputWatcher.is_active()) << "\n"
<< indent << "appInput = " << appInput.get() << " " << appInput->inspect() << "\n"
<< indent << "appInput started = " << boolStr(appInput->isStarted()) << "\n"
<< indent << "appInput reachedEnd = " << boolStr(appInput->endReached()) << "\n"
<< indent << "responseHeaderSeen = " << boolStr(responseHeaderSeen) << "\n"
<< indent << "useUnionStation = " << boolStr(useUnionStation()) << "\n"
;
}
};
typedef shared_ptr<Client> ClientPtr;
class RequestHandler {
private:
friend class Client;
typedef UnionStation::LoggerFactory LoggerFactory;
typedef UnionStation::LoggerFactoryPtr LoggerFactoryPtr;
typedef UnionStation::LoggerPtr LoggerPtr;
const SafeLibevPtr libev;
FileDescriptor requestSocket;
PoolPtr pool;
const AgentOptions &options;
const ResourceLocator resourceLocator;
LoggerFactoryPtr loggerFactory;
ev::io requestSocketWatcher;
ev::timer resumeSocketWatcherTimer;
HashMap<int, ClientPtr> clients;
Timer inactivityTimer;
bool accept4Available;
void disconnect(const ClientPtr &client) {
// Prevent Client object from being destroyed until we're done.
ClientPtr reference = client;
clients.erase(client->fd);
client->discard();
client->verifyInvariants();
RH_DEBUG(client, "Disconnected; new client count = " << clients.size());
if (clients.empty()) {
inactivityTimer.start();
}
}
void disconnectWithError(const ClientPtr &client, const StaticString &message) {
RH_WARN(client, "Disconnecting with error: " << message);
if (client->useUnionStation()) {
client->logMessage("Disconnecting with error: " + message);
}
disconnect(client);
}
void disconnectWithClientSocketWriteError(const ClientPtr &client, int e) {
stringstream message;
message << "client socket write error: ";
message << strerror(e);
message << " (errno=" << e << ")";
disconnectWithError(client, message.str());
}
void disconnectWithAppSocketWriteError(const ClientPtr &client, int e) {
stringstream message;
message << "app socket write error: ";
message << strerror(e);
message << " (errno=" << e << ")";
disconnectWithError(client, message.str());
}
void disconnectWithWarning(const ClientPtr &client, const StaticString &message) {
P_DEBUG("Disconnected client " << client->name() << " with warning: " << message);
disconnect(client);
}
// GDB helper function, implemented in .cpp file to prevent inlining.
Client *getClientPointer(const ClientPtr &client);
void getInactivityTime(unsigned long long *result) const {
*result = inactivityTimer.elapsed();
}
static bool getBoolOption(const ClientPtr &client, const StaticString &name, bool defaultValue = false) {
ScgiRequestParser::const_iterator it = client->scgiParser.getHeaderIterator(name);
if (it != client->scgiParser.end()) {
return it->second == "true";
} else {
return defaultValue;
}
}
static long long getLongLongOption(const ClientPtr &client, const StaticString &name, long long defaultValue = -1) {
ScgiRequestParser::const_iterator it = client->scgiParser.getHeaderIterator(name);
if (it != client->scgiParser.end()) {
long long result = stringToULL(it->second);
// The client may send a malicious integer, so check for this.
if (result < 0) {
return defaultValue;
} else {
return result;
}
} else {
return defaultValue;
}
}
void writeErrorResponse(const ClientPtr &client, const StaticString &message, const SpawnException *e = NULL) {
assert(client->state < Client::FORWARDING_BODY_TO_APP);
client->state = Client::WRITING_SIMPLE_RESPONSE;
string templatesDir = resourceLocator.getResourcesDir() + "/templates";
string data;
if (getBoolOption(client, "PASSENGER_FRIENDLY_ERROR_PAGES", true)) {
string cssFile = templatesDir + "/error_layout.css";
string errorLayoutFile = templatesDir + "/error_layout.html.template";
string generalErrorFile =
(e != NULL && e->isHTML())
? templatesDir + "/general_error_with_html.html.template"
: templatesDir + "/general_error.html.template";
string css = readAll(cssFile);
StringMap<StaticString> params;
params.set("CSS", css);
params.set("APP_ROOT", client->options.appRoot);
params.set("RUBY", client->options.ruby);
params.set("ENVIRONMENT", client->options.environment);
params.set("MESSAGE", message);
params.set("IS_RUBY_APP",
(client->options.appType == "classic-rails" || client->options.appType == "rack")
? "true" : "false");
if (e != NULL) {
params.set("TITLE", "Web application could not be started");
// Store all SpawnException annotations into 'params',
// but convert its name to uppercase.
const map<string, string> &annotations = e->getAnnotations();
map<string, string>::const_iterator it, end = annotations.end();
for (it = annotations.begin(); it != end; it++) {
string name = it->first;
for (string::size_type i = 0; i < name.size(); i++) {
name[i] = toupper(name[i]);
}
params.set(name, it->second);
}
} else {
params.set("TITLE", "Internal server error");
}
string content = Template::apply(readAll(generalErrorFile), params);
params.set("CONTENT", content);
data = Template::apply(readAll(errorLayoutFile), params);
} else {
data = readAll(templatesDir + "/undisclosed_error.html.template");
}
stringstream str;
if (getBoolOption(client, "PASSENGER_STATUS_LINE", true)) {
str << "HTTP/1.1 500 Internal Server Error\r\n";
}
str << "Status: 500 Internal Server Error\r\n";
str << "Content-Length: " << data.size() << "\r\n";
str << "Content-Type: text/html; charset=UTF-8\r\n";
str << "Cache-Control: no-cache, no-store, must-revalidate\r\n";
str << "\r\n";
const string &header = str.str();
client->clientOutputPipe->write(header.data(), header.size());
client->clientOutputPipe->write(data.data(), data.size());
client->clientOutputPipe->end();
}
/*****************************************************
* COMPONENT: appInput -> clientOutputPipe plumbing
*
* The following code receives data from appInput,
* possibly modifies it, and forwards it to
* clientOutputPipe.
*****************************************************/
struct Header {
StaticString key;
StaticString value;
Header() { }
Header(const StaticString &_key, const StaticString &_value)
: key(_key),
value(_value)
{ }
bool empty() const {
return key.empty();
}
const char *begin() const {
return key.data();
}
const char *end() const {
return value.data() + value.size() + sizeof("\r\n") - 1;
}
size_t size() const {
return end() - begin();
}
};
/** Given a substring containing the start of the header value,
* extracts the substring that contains a single header value.
*
* const char *data =
* "Status: 200 OK\r\n"
* "Foo: bar\r\n";
* extractHeaderValue(data + strlen("Status:"), strlen(data) - strlen("Status:"));
* // "200 OK"
*/
static StaticString extractHeaderValue(const char *data, size_t size) {
const char *start = data;
const char *end = data + size;
const char *terminator;
while (start < end && *start == ' ') {
start++;
}
terminator = (const char *) memchr(start, '\r', end - start);
if (terminator == NULL) {
return StaticString();
} else {
return StaticString(start, terminator - start);
}
}
static Header lookupHeader(const StaticString &headerData, const StaticString &name) {
string::size_type searchStart = 0;
while (searchStart < headerData.size()) {
string::size_type pos = headerData.find(name, searchStart);
if (OXT_UNLIKELY(pos == string::npos)) {
return Header();
} else if ((pos == 0 || headerData[pos - 1] == '\n')
&& headerData.size() > pos + name.size()
&& headerData[pos + name.size()] == ':')
{
StaticString value = extractHeaderValue(
headerData.data() + pos + name.size() + 1,
headerData.size() - pos - name.size() - 1);
return Header(headerData.substr(pos, name.size()), value);
} else {
searchStart = pos + name.size() + 1;
}
}
return Header();
}
static Header lookupHeader(const StaticString &headerData, const StaticString &name,
const StaticString &name2)
{
Header header = lookupHeader(headerData, name);
if (header.empty()) {
header = lookupHeader(headerData, name2);
}
return header;
}
bool addStatusHeaderFromStatusLine(const ClientPtr &client, string &headerData) {
string::size_type begin = headerData.find(' ');
string::size_type end = headerData.find("\r\n");
if (begin != string::npos && end != string::npos) {
StaticString status(headerData.data() + begin, end - begin);
headerData.append("Status: ");
headerData.append(status);
headerData.append("\r\n");
return true;
} else {
disconnectWithError(client, "application sent malformed response: the HTTP status line is invalid.");
return false;
}
}
static bool addReasonPhrase(string &headerData, const Header &status) {
if (status.value.find(' ') == string::npos) {
int statusCode = stringToInt(status.value);
const char *statusCodeAndReasonPhrase = getStatusCodeAndReasonPhrase(statusCode);
char newStatus[100];
char *pos = newStatus;
const char *end = newStatus + sizeof(newStatus);
pos = appendData(pos, end, "Status: ");
if (statusCodeAndReasonPhrase == NULL) {
pos = appendData(pos, end, toString(statusCode));
pos = appendData(pos, end, " Unknown Reason-Phrase\r\n");
} else {
pos = appendData(pos, end, statusCodeAndReasonPhrase);
pos = appendData(pos, end, "\r\n");
}
headerData.replace(status.begin() - headerData.data(), status.size(),
newStatus, pos - newStatus);
return true;
} else {
return false;
}
}
bool removeStatusLine(const ClientPtr &client, string &headerData) {
string::size_type end = headerData.find("\r\n");
if (end != string::npos) {
headerData.erase(0, end + 2);
return true;
} else {
disconnectWithError(client, "application sent malformed response: the HTTP status line is invalid.");
return false;
}
}
static void addStatusLineFromStatusHeader(string &headerData, const Header &status) {
char statusLine[100];
char *pos = statusLine;
const char *end = statusLine + sizeof(statusLine);
pos = appendData(pos, end, "HTTP/1.1 ");
pos = appendData(pos, end, status.value);
pos = appendData(pos, end, "\r\n");
headerData.insert(0, statusLine, pos - statusLine);
}
static void removeHeader(string &headerData, const Header &header) {
headerData.erase(header.begin() - headerData.data(), header.size());
}
/*
* Given a full header, possibly modify the header and send it to the clientOutputPipe.
*/
bool processResponseHeader(const ClientPtr &client,
const StaticString &origHeaderData)
{
string headerData;
headerData.reserve(origHeaderData.size() + 100);
// Strip trailing CRLF.
headerData.append(origHeaderData.data(), origHeaderData.size() - 2);
if (startsWith(headerData, "HTTP/1.")) {
Header status = lookupHeader(headerData, "Status", "status");
if (status.empty()) {
// Add status header if necessary.
if (!addStatusHeaderFromStatusLine(client, headerData)) {
return false;
}
} else {
// Add reason phrase to existing status header if necessary.
addReasonPhrase(headerData, status);
}
// Remove status line if necesary.
if (!getBoolOption(client, "PASSENGER_STATUS_LINE", true)) {
if (!removeStatusLine(client, headerData)) {
return false;
}
}
} else {
Header status = lookupHeader(headerData, "Status", "status");
if (!status.empty()) {
// Add reason phrase to status header if necessary.
if (addReasonPhrase(headerData, status)) {
status = lookupHeader(headerData, "Status", "status");
}
// Add status line if necessary.
if (getBoolOption(client, "PASSENGER_STATUS_LINE", true)) {
addStatusLineFromStatusHeader(headerData, status);
}
} else {
disconnectWithError(client, "application sent malformed response: it didn't send an HTTP status line or a Status header.");
return false;
}
}
// Process chunked transfer encoding.
Header transferEncoding = lookupHeader(headerData, "Transfer-Encoding", "transfer-encoding");
if (!transferEncoding.empty() && transferEncoding.value == "chunked") {
P_TRACE(3, "Response with chunked transfer encoding detected.");
client->chunkedResponse = true;
removeHeader(headerData, transferEncoding);
}
// Add X-Powered-By.
if (getBoolOption(client, "PASSENGER_SHOW_VERSION_IN_HEADER", true)) {
headerData.append("X-Powered-By: Phusion Passenger " PASSENGER_VERSION "\r\n");
} else {
headerData.append("X-Powered-By: Phusion Passenger\r\n");
}
// Detect out of band work request
Header oobw = lookupHeader(headerData, "X-Passenger-Request-OOB-Work", "x-passenger-request-oob-work");
if (!oobw.empty()) {
P_TRACE(3, "Response with oobw detected.");
if (client->session != NULL) {
client->session->requestOOBW();
}
removeHeader(headerData, oobw);
}
headerData.append("\r\n");
writeToClientOutputPipe(client, headerData);
return true;
}
void writeToClientOutputPipe(const ClientPtr &client, const StaticString &data) {
bool wasCommittingToDisk = client->clientOutputPipe->isCommittingToDisk();
bool nowCommittingToDisk = !client->clientOutputPipe->write(data.data(), data.size());
if (!wasCommittingToDisk && nowCommittingToDisk) {
RH_TRACE(client, 3, "Buffering response data to disk; temporarily stopping application socket.");
client->backgroundOperations++;
// If the data comes from writeErrorResponse(), then appInput is not available.
if (client->session != NULL && client->session->initiated()) {
client->appInput->stop();
}
}
}
size_t onAppInputData(const ClientPtr &client, const StaticString &data) {
if (!client->connected()) {
return 0;
}
if (!data.empty()) {
RH_TRACE(client, 3, "Application sent data: \"" << cEscapeString(data) << "\"");
// Buffer the application response until we've encountered the end of the header.
if (!client->responseHeaderSeen) {
size_t consumed = client->responseHeaderBufferer.feed(data.data(), data.size());
if (!client->responseHeaderBufferer.acceptingInput()) {
if (client->responseHeaderBufferer.hasError()) {
disconnectWithError(client, "application response format error (invalid header)");
} else {
// Now that we have a full header, do something with it.
client->responseHeaderSeen = true;
StaticString header = client->responseHeaderBufferer.getData();
if (processResponseHeader(client, header)) {
return consumed;
} else {
assert(!client->connected());
}
}
}
// The header has already been processed so forward it
// directly to clientOutputPipe, possibly through a
// dechunker first.
} else if (client->chunkedResponse) {
client->responseDechunker.feed(data.data(), data.size());
} else {
onAppInputChunk(client, data);
}
return data.size();
} else {
onAppInputEof(client);
return 0;
}
}
void onAppInputChunk(const ClientPtr &client, const StaticString &data) {
writeToClientOutputPipe(client, data);
}
void onAppInputEof(const ClientPtr &client) {
if (!client->connected()) {
return;
}
RH_DEBUG(client, "Application sent EOF");
client->endScopeLog(&client->scopeLogs.requestProxying);
client->clientOutputPipe->end();
}
void onAppInputError(const ClientPtr &client, const char *message, int errorCode) {
if (!client->connected()) {