-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathmod_fastcgi.c
3061 lines (2556 loc) · 90.1 KB
/
mod_fastcgi.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* mod_fastcgi.c --
*
* Apache server module for FastCGI.
*
* $Id: mod_fastcgi.c,v 1.169 2008/11/09 14:31:03 robs Exp $
*
* Copyright (c) 1995-1996 Open Market, Inc.
*
* See the file "LICENSE.TERMS" for information on usage and redistribution
* of this file, and for a DISCLAIMER OF ALL WARRANTIES.
*
*
* Patches for Apache-1.1 provided by
* Ralf S. Engelschall
*
* Patches for Linux provided by
* Scott Langley
*
* Patches for suexec handling by
* Brian Grossman <[email protected]> and
* Rob Saccoccio <[email protected]>
*/
/*
* Module design notes.
*
* 1. Restart cleanup.
*
* mod_fastcgi spawns several processes: one process manager process
* and several application processes. None of these processes
* handle SIGHUP, so they just go away when the Web server performs
* a restart (as Apache does every time it starts.)
*
* In order to allow the process manager to properly cleanup the
* running fastcgi processes (without being disturbed by Apache),
* an intermediate process was introduced. The diagram is as follows;
*
* ApacheWS --> MiddleProc --> ProcMgr --> FCGI processes
*
* On a restart, ApacheWS sends a SIGKILL to MiddleProc and then
* collects it via waitpid(). The ProcMgr periodically checks for
* its parent (via getppid()) and if it does not have one, as in
* case when MiddleProc has terminated, ProcMgr issues a SIGTERM
* to all FCGI processes, waitpid()s on them and then exits, so it
* can be collected by init(1). Doing it any other way (short of
* changing Apache API), results either in inconsistent results or
* in generation of zombie processes.
*
* XXX: How does Apache 1.2 implement "gentle" restart
* that does not disrupt current connections? How does
* gentle restart interact with restart cleanup?
*
* 2. Request timeouts.
*
* Earlier versions of this module used ap_soft_timeout() rather than
* ap_hard_timeout() and ate FastCGI server output until it completed.
* This precluded the FastCGI server from having to implement a
* SIGPIPE handler, but meant hanging the application longer than
* necessary. SIGPIPE handler now must be installed in ALL FastCGI
* applications. The handler should abort further processing and go
* back into the accept() loop.
*
* Although using ap_soft_timeout() is better than ap_hard_timeout()
* we have to be more careful about SIGINT handling and subsequent
* processing, so, for now, make it hard.
*/
#include "fcgi.h"
#ifdef APACHE2
#ifndef WIN32
#include <unistd.h>
#if APR_HAVE_CTYPE_H
#include <ctype.h>
#endif
#include "unixd.h"
#endif
#endif
#ifndef timersub
#define timersub(a, b, result) \
do { \
(result)->tv_sec = (a)->tv_sec - (b)->tv_sec; \
(result)->tv_usec = (a)->tv_usec - (b)->tv_usec; \
if ((result)->tv_usec < 0) { \
--(result)->tv_sec; \
(result)->tv_usec += 1000000; \
} \
} while (0)
#endif
/*
* Global variables
*/
pool *fcgi_config_pool; /* the config pool */
server_rec *fcgi_apache_main_server;
const char *fcgi_wrapper = NULL; /* wrapper path */
uid_t fcgi_user_id; /* the run uid of Apache & PM */
gid_t fcgi_group_id; /* the run gid of Apache & PM */
fcgi_server *fcgi_servers = NULL; /* AppClasses */
char *fcgi_socket_dir = NULL; /* default FastCgiIpcDir */
char *fcgi_dynamic_dir = NULL; /* directory for the dynamic
* fastcgi apps' sockets */
#ifdef WIN32
#pragma warning( disable : 4706 4100 4127)
fcgi_pm_job *fcgi_dynamic_mbox = NULL;
HANDLE *fcgi_dynamic_mbox_mutex = NULL;
HANDLE fcgi_pm_thread = INVALID_HANDLE_VALUE;
#else
int fcgi_pm_pipe[2] = { -1, -1 };
pid_t fcgi_pm_pid = -1;
#endif
char *fcgi_empty_env = NULL;
u_int dynamicMaxProcs = FCGI_DEFAULT_MAX_PROCS;
int dynamicMinProcs = FCGI_DEFAULT_MIN_PROCS;
int dynamicMaxClassProcs = FCGI_DEFAULT_MAX_CLASS_PROCS;
u_int dynamicKillInterval = FCGI_DEFAULT_KILL_INTERVAL;
u_int dynamicUpdateInterval = FCGI_DEFAULT_UPDATE_INTERVAL;
float dynamicGain = FCGI_DEFAULT_GAIN;
int dynamicThreshold1 = FCGI_DEFAULT_THRESHOLD_1;
int dynamicThresholdN = FCGI_DEFAULT_THRESHOLD_N;
u_int dynamicPleaseStartDelay = FCGI_DEFAULT_START_PROCESS_DELAY;
u_int dynamicAppConnectTimeout = FCGI_DEFAULT_APP_CONN_TIMEOUT;
char **dynamicEnvp = &fcgi_empty_env;
u_int dynamicProcessSlack = FCGI_DEFAULT_PROCESS_SLACK;
int dynamicAutoRestart = FCGI_DEFAULT_RESTART_DYNAMIC;
int dynamicAutoUpdate = FCGI_DEFAULT_AUTOUPDATE;
int dynamicFlush = FCGI_FLUSH;
u_int dynamicListenQueueDepth = FCGI_DEFAULT_LISTEN_Q;
u_int dynamicInitStartDelay = DEFAULT_INIT_START_DELAY;
u_int dynamicRestartDelay = FCGI_DEFAULT_RESTART_DELAY;
array_header *dynamic_pass_headers = NULL;
u_int dynamic_idle_timeout = FCGI_DEFAULT_IDLE_TIMEOUT;
int dynamicMinServerLife = FCGI_DEFAULT_MIN_SERVER_LIFE;
#ifdef APLOG_USE_MODULE
APLOG_USE_MODULE(fastcgi);
#endif
/*******************************************************************************
* Construct a message and write it to the pm_pipe.
*/
static void send_to_pm(const char id, const char * const fs_path,
const char *user, const char * const group, const unsigned long q_usec,
const unsigned long req_usec)
{
#ifdef WIN32
fcgi_pm_job *job = NULL;
if (!(job = (fcgi_pm_job *) malloc(sizeof(fcgi_pm_job))))
return;
#else
static int failed_count = 0;
int buflen = 0;
char buf[FCGI_MAX_MSG_LEN];
#endif
if (strlen(fs_path) > FCGI_MAXPATH) {
ap_log_error(FCGI_LOG_ERR_NOERRNO, fcgi_apache_main_server,
"FastCGI: the path \"%s\" is too long (>%d) for a dynamic server", fs_path, FCGI_MAXPATH);
return;
}
switch(id) {
case FCGI_SERVER_START_JOB:
case FCGI_SERVER_RESTART_JOB:
#ifdef WIN32
job->id = id;
job->fs_path = strdup(fs_path);
job->user = strdup(user);
job->group = strdup(group);
job->qsec = 0L;
job->start_time = 0L;
#else
buflen = sprintf(buf, "%c %s %s %s*", id, fs_path, user, group);
#endif
break;
case FCGI_REQUEST_TIMEOUT_JOB:
#ifdef WIN32
job->id = id;
job->fs_path = strdup(fs_path);
job->user = strdup(user);
job->group = strdup(group);
job->qsec = 0L;
job->start_time = 0L;
#else
buflen = sprintf(buf, "%c %s %s %s*", id, fs_path, user, group);
#endif
break;
case FCGI_REQUEST_COMPLETE_JOB:
#ifdef WIN32
job->id = id;
job->fs_path = strdup(fs_path);
job->qsec = q_usec;
job->start_time = req_usec;
job->user = strdup(user);
job->group = strdup(group);
#else
buflen = sprintf(buf, "%c %s %s %s %lu %lu*", id, fs_path, user, group, q_usec, req_usec);
#endif
break;
}
#ifdef WIN32
if (fcgi_pm_add_job(job)) return;
SetEvent(fcgi_event_handles[MBOX_EVENT]);
#else
ASSERT(buflen <= FCGI_MAX_MSG_LEN);
/* There is no apache flag or function that can be used to id
* restart/shutdown pending so ignore the first few failures as
* once it breaks it will stay broke */
if (write(fcgi_pm_pipe[1], (const void *)buf, buflen) != buflen
&& failed_count++ > 10)
{
ap_log_error(FCGI_LOG_WARN, fcgi_apache_main_server,
"FastCGI: write() to PM failed (ignore if a restart or shutdown is pending)");
}
#endif
}
/*
*----------------------------------------------------------------------
*
* init_module
*
* An Apache module initializer, called by the Apache core
* after reading the server config.
*
* Start the process manager no matter what, since there may be a
* request for dynamic FastCGI applications without any being
* configured as static applications. Also, check for the existence
* and create if necessary a subdirectory into which all dynamic
* sockets will go.
*
*----------------------------------------------------------------------
*/
#ifdef APACHE2
static apcb_t init_module(apr_pool_t * p, apr_pool_t * plog,
apr_pool_t * tp, server_rec * s)
#else
static apcb_t init_module(server_rec *s, pool *p)
#endif
{
#ifndef WIN32
const char *err;
#endif
/* Register to reset to default values when the config pool is cleaned */
ap_block_alarms();
ap_register_cleanup(p, NULL, fcgi_config_reset_globals, ap_null_cleanup);
ap_unblock_alarms();
#ifdef APACHE2
ap_add_version_component(p, "mod_fastcgi/" MOD_FASTCGI_VERSION);
#else
ap_add_version_component("mod_fastcgi/" MOD_FASTCGI_VERSION);
#endif
fcgi_config_set_fcgi_uid_n_gid(1);
/* keep these handy */
fcgi_config_pool = p;
fcgi_apache_main_server = s;
#ifdef WIN32
if (fcgi_socket_dir == NULL)
fcgi_socket_dir = DEFAULT_SOCK_DIR;
fcgi_dynamic_dir = ap_pstrcat(p, fcgi_socket_dir, "dynamic", NULL);
#else
if (fcgi_socket_dir == NULL)
fcgi_socket_dir = ap_server_root_relative(p, DEFAULT_SOCK_DIR);
/* Create Unix/Domain socket directory */
if ((err = fcgi_config_make_dir(p, fcgi_socket_dir)))
ap_log_error(FCGI_LOG_ERR, s, "FastCGI: %s", err);
/* Create Dynamic directory */
if ((err = fcgi_config_make_dynamic_dir(p, 1)))
ap_log_error(FCGI_LOG_ERR, s, "FastCGI: %s", err);
/* Spawn the PM only once. Under Unix, Apache calls init() routines
* twice, once before detach() and once after. Win32 doesn't detach.
* Under DSO, DSO modules are unloaded between the two init() calls.
* Under Unix, the -X switch causes two calls to init() but no detach
* (but all subprocesses are wacked so the PM is toasted anyway)! */
#ifdef APACHE2
{
void * first_pass;
apr_pool_userdata_get(&first_pass, "mod_fastcgi", s->process->pool);
if (first_pass == NULL)
{
apr_pool_userdata_set((const void *)1, "mod_fastcgi",
apr_pool_cleanup_null, s->process->pool);
return APCB_OK;
}
}
#else /* !APACHE2 */
if (ap_standalone && ap_restart_time == 0)
return;
#endif
/* Create the pipe for comm with the PM */
if (pipe(fcgi_pm_pipe) < 0) {
ap_log_error(FCGI_LOG_ERR, s, "FastCGI: pipe() failed");
}
/* Start the Process Manager */
#ifdef APACHE2
{
apr_proc_t * proc = apr_palloc(p, sizeof(*proc));
apr_status_t rv;
rv = apr_proc_fork(proc, tp);
if (rv == APR_INCHILD)
{
/* child */
fcgi_pm_main(NULL);
exit(1);
}
else if (rv != APR_INPARENT)
{
return rv;
}
/* parent */
apr_pool_note_subprocess(p, proc, APR_KILL_ONLY_ONCE);
}
#else /* !APACHE2 */
fcgi_pm_pid = ap_spawn_child(p, fcgi_pm_main, NULL, kill_only_once, NULL, NULL, NULL);
if (fcgi_pm_pid <= 0) {
ap_log_error(FCGI_LOG_ALERT, s,
"FastCGI: can't start the process manager, spawn_child() failed");
}
#endif /* !APACHE2 */
close(fcgi_pm_pipe[0]);
#endif /* !WIN32 */
return APCB_OK;
}
#ifdef WIN32
#ifdef APACHE2
static apcb_t fcgi_child_exit(void * dc)
#else
static apcb_t fcgi_child_exit(server_rec *dc0, pool *dc1)
#endif
{
/* Signal the PM thread to exit*/
SetEvent(fcgi_event_handles[TERM_EVENT]);
/* Waiting on pm thread to exit */
WaitForSingleObject(fcgi_pm_thread, INFINITE);
return APCB_OK;
}
#endif /* WIN32 */
#ifdef APACHE2
static void fcgi_child_init(apr_pool_t * p, server_rec * dc)
#else
static void fcgi_child_init(server_rec *dc, pool *p)
#endif
{
#ifdef WIN32
/* Create the MBOX, TERM, and WAKE event handlers */
fcgi_event_handles[0] = CreateEvent(NULL, FALSE, FALSE, NULL);
if (fcgi_event_handles[0] == NULL) {
ap_log_error(FCGI_LOG_ALERT, fcgi_apache_main_server,
"FastCGI: CreateEvent() failed");
}
fcgi_event_handles[1] = CreateEvent(NULL, FALSE, FALSE, NULL);
if (fcgi_event_handles[1] == NULL) {
ap_log_error(FCGI_LOG_ALERT, fcgi_apache_main_server,
"FastCGI: CreateEvent() failed");
}
fcgi_event_handles[2] = CreateEvent(NULL, FALSE, FALSE, NULL);
if (fcgi_event_handles[2] == NULL) {
ap_log_error(FCGI_LOG_ALERT, fcgi_apache_main_server,
"FastCGI: CreateEvent() failed");
}
/* Create the mbox mutex (PM - request threads) */
fcgi_dynamic_mbox_mutex = CreateMutex(NULL, FALSE, NULL);
if (fcgi_dynamic_mbox_mutex == NULL) {
ap_log_error(FCGI_LOG_ALERT, fcgi_apache_main_server,
"FastCGI: CreateMutex() failed");
}
/* Spawn of the process manager thread */
fcgi_pm_thread = (HANDLE) _beginthread(fcgi_pm_main, 0, NULL);
if (fcgi_pm_thread == (HANDLE) -1) {
ap_log_error(FCGI_LOG_ALERT, fcgi_apache_main_server,
"_beginthread() failed to spawn the process manager");
}
#ifdef APACHE2
apr_pool_cleanup_register(p, NULL, fcgi_child_exit, fcgi_child_exit);
#endif
#endif
}
/*
*----------------------------------------------------------------------
*
* get_header_line --
*
* Terminate a line: scan to the next newline, scan back to the
* first non-space character and store a terminating zero. Return
* the next character past the end of the newline.
*
* If the end of the string is reached, ASSERT!
*
* If the FIRST character(s) in the line are '\n' or "\r\n", the
* first character is replaced with a NULL and next character
* past the newline is returned. NOTE: this condition supercedes
* the processing of RFC-822 continuation lines.
*
* If continuation is set to 'TRUE', then it parses a (possible)
* sequence of RFC-822 continuation lines.
*
* Results:
* As above.
*
* Side effects:
* Termination byte stored in string.
*
*----------------------------------------------------------------------
*/
static char *get_header_line(char *start, int continuation)
{
char *p = start;
char *end = start;
if(p[0] == '\r' && p[1] == '\n') { /* If EOL in 1st 2 chars */
p++; /* point to \n and stop */
} else if(*p != '\n') {
if(continuation) {
while(*p != '\0') {
if(*p == '\n' && p[1] != ' ' && p[1] != '\t')
break;
p++;
}
} else {
while(*p != '\0' && *p != '\n') {
p++;
}
}
}
ASSERT(*p != '\0');
end = p;
end++;
/*
* Trim any trailing whitespace.
*/
while(isspace((unsigned char)p[-1]) && p > start) {
p--;
}
*p = '\0';
return end;
}
#ifdef WIN32
static int set_nonblocking(const fcgi_request * fr, int nonblocking)
{
if (fr->using_npipe_io)
{
if (nonblocking)
{
DWORD mode = PIPE_NOWAIT | PIPE_READMODE_BYTE;
if (SetNamedPipeHandleState((HANDLE) fr->fd, &mode, NULL, NULL) == 0)
{
ap_log_rerror(FCGI_LOG_ERR, fr->r,
"FastCGI: SetNamedPipeHandleState() failed");
return -1;
}
}
}
else
{
unsigned long ioctl_arg = (nonblocking) ? 1 : 0;
if (ioctlsocket(fr->fd, FIONBIO, &ioctl_arg) != 0)
{
errno = WSAGetLastError();
ap_log_rerror(FCGI_LOG_ERR_ERRNO, fr->r,
"FastCGI: ioctlsocket() failed");
return -1;
}
}
return 0;
}
#else
static int set_nonblocking(const fcgi_request * fr, int nonblocking)
{
int nb_flag = 0;
int fd_flags = fcntl(fr->fd, F_GETFL, 0);
if (fd_flags < 0) return -1;
#if defined(O_NONBLOCK)
nb_flag = O_NONBLOCK;
#elif defined(O_NDELAY)
nb_flag = O_NDELAY;
#elif defined(FNDELAY)
nb_flag = FNDELAY;
#else
#error "TODO - don't read from app until all data from client is posted."
#endif
fd_flags = (nonblocking) ? (fd_flags | nb_flag) : (fd_flags & ~nb_flag);
return fcntl(fr->fd, F_SETFL, fd_flags);
}
#endif
/*******************************************************************************
* Close the connection to the FastCGI server. This is normally called by
* do_work(), but may also be called as in request pool cleanup.
*/
static void close_connection_to_fs(fcgi_request *fr)
{
#ifdef WIN32
if (fr->fd != INVALID_SOCKET)
{
set_nonblocking(fr, FALSE);
if (fr->using_npipe_io)
{
CloseHandle((HANDLE) fr->fd);
}
else
{
/* abort the connection entirely */
struct linger linger = {0, 0};
setsockopt(fr->fd, SOL_SOCKET, SO_LINGER, (void *) &linger, sizeof(linger));
closesocket(fr->fd);
}
fr->fd = INVALID_SOCKET;
#else /* ! WIN32 */
if (fr->fd >= 0)
{
struct linger linger = {0, 0};
set_nonblocking(fr, FALSE);
/* abort the connection entirely */
setsockopt(fr->fd, SOL_SOCKET, SO_LINGER, &linger, sizeof(linger));
close(fr->fd);
fr->fd = -1;
#endif /* ! WIN32 */
if (fr->dynamic && fr->keepReadingFromFcgiApp == FALSE)
{
/* XXX FCGI_REQUEST_COMPLETE_JOB is only sent for requests which complete
* normally WRT the fcgi app. There is no data sent for
* connect() timeouts or requests which complete abnormally.
* KillDynamicProcs() and RemoveRecords() need to be looked at
* to be sure they can reasonably handle these cases before
* sending these sort of stats - theres some funk in there.
*/
if (fcgi_util_ticks(&fr->completeTime) < 0)
{
/* there's no point to aborting the request, just log it */
ap_log_error(FCGI_LOG_ERR, fr->r->server, "FastCGI: can't get time of day");
}
}
}
}
/*
*----------------------------------------------------------------------
*
* process_headers --
*
* Call with r->parseHeader == SCAN_CGI_READING_HEADERS
* and initial script output in fr->header.
*
* If the initial script output does not include the header
* terminator ("\r\n\r\n") process_headers returns with no side
* effects, to be called again when more script output
* has been appended to fr->header.
*
* If the initial script output includes the header terminator,
* process_headers parses the headers and determines whether or
* not the remaining script output will be sent to the client.
* If so, process_headers sends the HTTP response headers to the
* client and copies any non-header script output to the output
* buffer reqOutbuf.
*
* Results:
* none.
*
* Side effects:
* May set r->parseHeader to:
* SCAN_CGI_FINISHED -- headers parsed, returning script response
* SCAN_CGI_BAD_HEADER -- malformed header from script
* SCAN_CGI_INT_REDIRECT -- handler should perform internal redirect
* SCAN_CGI_SRV_REDIRECT -- handler should return REDIRECT
*
*----------------------------------------------------------------------
*/
static const char *process_headers(request_rec *r, fcgi_request *fr)
{
char *p, *next, *name, *value;
int len, flag;
int hasLocation = FALSE;
ASSERT(fr->parseHeader == SCAN_CGI_READING_HEADERS);
if (fr->header == NULL)
return NULL;
/*
* Do we have the entire header? Scan for the blank line that
* terminates the header.
*/
p = (char *)fr->header->elts;
len = fr->header->nelts;
flag = 0;
while(len-- && flag < 2) {
switch(*p) {
case '\r':
break;
case '\n':
flag++;
break;
case '\0':
case '\v':
case '\f':
name = "Invalid Character";
goto BadHeader;
default:
flag = 0;
break;
}
p++;
}
/* Return (to be called later when we have more data)
* if we don't have an entire header. */
if (flag < 2)
return NULL;
/*
* Parse all the headers.
*/
fr->parseHeader = SCAN_CGI_FINISHED;
next = (char *)fr->header->elts;
for(;;) {
next = get_header_line(name = next, TRUE);
if (*name == '\0') {
break;
}
if ((p = strchr(name, ':')) == NULL) {
goto BadHeader;
}
value = p + 1;
while (p != name && isspace((unsigned char)*(p - 1))) {
p--;
}
if (p == name) {
goto BadHeader;
}
*p = '\0';
if (strpbrk(name, " \t") != NULL) {
*p = ' ';
goto BadHeader;
}
while (isspace((unsigned char)*value)) {
value++;
}
if (strcasecmp(name, "Status") == 0) {
int statusValue = strtol(value, NULL, 10);
if (statusValue < 0) {
fr->parseHeader = SCAN_CGI_BAD_HEADER;
return ap_psprintf(r->pool, "invalid Status '%s'", value);
}
r->status = statusValue;
r->status_line = ap_pstrdup(r->pool, value);
continue;
}
if (fr->role == FCGI_RESPONDER) {
if (strcasecmp(name, "Content-type") == 0) {
#ifdef APACHE2
ap_set_content_type(r, value);
#else
r->content_type = ap_pstrdup(r->pool, value);
#endif
continue;
}
/*
* Special case headers that should not persist on error
* or across redirects, i.e. use headers_out rather than
* err_headers_out.
*/
if (strcasecmp(name, "Location") == 0) {
hasLocation = TRUE;
ap_table_set(r->headers_out, name, value);
continue;
}
if (strcasecmp(name, "Content-Length") == 0) {
ap_table_set(r->headers_out, name, value);
continue;
}
/* If the script wants them merged, it can do it */
ap_table_add(r->err_headers_out, name, value);
continue;
}
else {
ap_table_add(fr->authHeaders, name, value);
}
}
if (fr->role != FCGI_RESPONDER)
return NULL;
/*
* Who responds, this handler or Apache?
*/
if (hasLocation) {
const char *location = ap_table_get(r->headers_out, "Location");
/*
* Based on internal redirect handling in mod_cgi.c...
*
* If a script wants to produce its own Redirect
* body, it now has to explicitly *say* "Status: 302"
*/
if (r->status == 200) {
if(location[0] == '/') {
/*
* Location is an relative path. This handler will
* consume all script output, then have Apache perform an
* internal redirect.
*/
fr->parseHeader = SCAN_CGI_INT_REDIRECT;
return NULL;
} else {
/*
* Location is an absolute URL. If the script didn't
* produce a Content-type header, this handler will
* consume all script output and then have Apache generate
* its standard redirect response. Otherwise this handler
* will transmit the script's response.
*/
fr->parseHeader = SCAN_CGI_SRV_REDIRECT;
return NULL;
}
}
}
/*
* We're responding. Send headers, buffer excess script output.
*/
ap_send_http_header(r);
/* We need to reinstate our timeout, send_http_header() kill()s it */
ap_hard_timeout("FastCGI request processing", r);
if (r->header_only) {
/* we've got all we want from the server */
close_connection_to_fs(fr);
fr->exitStatusSet = 1;
fcgi_buf_reset(fr->clientOutputBuffer);
fcgi_buf_reset(fr->serverOutputBuffer);
return NULL;
}
len = fr->header->nelts - (next - fr->header->elts);
ASSERT(len >= 0);
ASSERT(BufferLength(fr->clientOutputBuffer) == 0);
if (BufferFree(fr->clientOutputBuffer) < len) {
fr->clientOutputBuffer = fcgi_buf_new(r->pool, len);
}
ASSERT(BufferFree(fr->clientOutputBuffer) >= len);
if (len > 0) {
int sent;
sent = fcgi_buf_add_block(fr->clientOutputBuffer, next, len);
ASSERT(sent == len);
}
return NULL;
BadHeader:
/* Log first line of a multi-line header */
if ((p = strpbrk(name, "\r\n")) != NULL)
*p = '\0';
fr->parseHeader = SCAN_CGI_BAD_HEADER;
return ap_psprintf(r->pool, "malformed header '%s'", name);
}
/*
* Read from the client filling both the FastCGI server buffer and the
* client buffer with the hopes of buffering the client data before
* making the connect() to the FastCGI server. This prevents slow
* clients from keeping the FastCGI server in processing longer than is
* necessary.
*/
static int read_from_client_n_queue(fcgi_request *fr)
{
char *end;
int count;
long int countRead;
while (BufferFree(fr->clientInputBuffer) > 0 || BufferFree(fr->serverOutputBuffer) > 0) {
fcgi_protocol_queue_client_buffer(fr);
if (fr->expectingClientContent <= 0)
return OK;
fcgi_buf_get_free_block_info(fr->clientInputBuffer, &end, &count);
if (count == 0)
return OK;
if ((countRead = ap_get_client_block(fr->r, end, count)) < 0)
{
/* set the header scan state to done to prevent logging an error
* - hokey approach - probably should be using a unique value */
fr->parseHeader = SCAN_CGI_FINISHED;
return -1;
}
if (countRead == 0) {
fr->expectingClientContent = 0;
}
else {
fcgi_buf_add_update(fr->clientInputBuffer, countRead);
ap_reset_timeout(fr->r);
}
}
return OK;
}
static int write_to_client(fcgi_request *fr)
{
char *begin;
int count;
int rv;
#ifdef APACHE2
apr_bucket * bkt;
apr_bucket_brigade * bde;
apr_bucket_alloc_t * const bkt_alloc = fr->r->connection->bucket_alloc;
#endif
fcgi_buf_get_block_info(fr->clientOutputBuffer, &begin, &count);
if (count == 0)
return OK;
/* If fewer than count bytes are written, an error occured.
* ap_bwrite() typically forces a flushed write to the client, this
* effectively results in a block (and short packets) - it should
* be fixed, but I didn't win much support for the idea on new-httpd.
* So, without patching Apache, the best way to deal with this is
* to size the fcgi_bufs to hold all of the script output (within
* reason) so the script can be released from having to wait around
* for the transmission to the client to complete. */
#ifdef APACHE2
bde = apr_brigade_create(fr->r->pool, bkt_alloc);
bkt = apr_bucket_transient_create(begin, count, bkt_alloc);
APR_BRIGADE_INSERT_TAIL(bde, bkt);
if (fr->fs ? fr->fs->flush : dynamicFlush)
{
bkt = apr_bucket_flush_create(bkt_alloc);
APR_BRIGADE_INSERT_TAIL(bde, bkt);
}
rv = ap_pass_brigade(fr->r->output_filters, bde);
#elif defined(RUSSIAN_APACHE)
rv = (ap_rwrite(begin, count, fr->r) != count);
#else
rv = (ap_bwrite(fr->r->connection->client, begin, count) != count);
#endif
if (rv || fr->r->connection->aborted) {
ap_log_rerror(FCGI_LOG_INFO_NOERRNO, fr->r,
"FastCGI: client stopped connection before send body completed");
return -1;
}
#ifndef APACHE2
ap_reset_timeout(fr->r);
/* Don't bother with a wrapped buffer, limiting exposure to slow
* clients. The BUFF routines don't allow a writev from above,
* and don't always memcpy to minimize small write()s, this should
* be fixed, but I didn't win much support for the idea on
* new-httpd - I'll have to _prove_ its a problem first.. */
/* The default behaviour used to be to flush with every write, but this
* can tie up the FastCGI server longer than is necessary so its an option now */
if (fr->fs ? fr->fs->flush : dynamicFlush)
{
#ifdef RUSSIAN_APACHE
rv = ap_rflush(fr->r);
#else
rv = ap_bflush(fr->r->connection->client);
#endif
if (rv)
{
ap_log_rerror(FCGI_LOG_INFO_NOERRNO, fr->r,
"FastCGI: client stopped connection before send body completed");
return -1;
}
ap_reset_timeout(fr->r);
}
#endif /* !APACHE2 */
fcgi_buf_toss(fr->clientOutputBuffer, count);
return OK;
}
static void
get_request_identity(request_rec * const r,
uid_t * const uid,
gid_t * const gid)
{
#if defined(WIN32)
*uid = (uid_t) 0;
*gid = (gid_t) 0;
#elif defined(APACHE2)
ap_unix_identity_t * identity = ap_run_get_suexec_identity(r);
if (identity)
{
*uid = identity->uid;
*gid = identity->gid;
}
else
{
*uid = 0;
*gid = 0;