Provide a NO_SUEXEC_FOR_AP_USER_N_GROUP macro for building
[mod_fastcgi.git] / mod_fastcgi.c
blob0e418fa3abdc26ee92fe7cdab7222a94937a1edc
1 /*
2 * mod_fastcgi.c --
4 * Apache server module for FastCGI.
6 * $Id: mod_fastcgi.c,v 1.151 2003/02/04 00:29:41 robs Exp $
8 * Copyright (c) 1995-1996 Open Market, Inc.
10 * See the file "LICENSE.TERMS" for information on usage and redistribution
11 * of this file, and for a DISCLAIMER OF ALL WARRANTIES.
14 * Patches for Apache-1.1 provided by
15 * Ralf S. Engelschall
16 * <rse@en.muc.de>
18 * Patches for Linux provided by
19 * Scott Langley
20 * <langles@vote-smart.org>
22 * Patches for suexec handling by
23 * Brian Grossman <brian@SoftHome.net> and
24 * Rob Saccoccio <robs@ipass.net>
28 * Module design notes.
30 * 1. Restart cleanup.
32 * mod_fastcgi spawns several processes: one process manager process
33 * and several application processes. None of these processes
34 * handle SIGHUP, so they just go away when the Web server performs
35 * a restart (as Apache does every time it starts.)
37 * In order to allow the process manager to properly cleanup the
38 * running fastcgi processes (without being disturbed by Apache),
39 * an intermediate process was introduced. The diagram is as follows;
41 * ApacheWS --> MiddleProc --> ProcMgr --> FCGI processes
43 * On a restart, ApacheWS sends a SIGKILL to MiddleProc and then
44 * collects it via waitpid(). The ProcMgr periodically checks for
45 * its parent (via getppid()) and if it does not have one, as in
46 * case when MiddleProc has terminated, ProcMgr issues a SIGTERM
47 * to all FCGI processes, waitpid()s on them and then exits, so it
48 * can be collected by init(1). Doing it any other way (short of
49 * changing Apache API), results either in inconsistent results or
50 * in generation of zombie processes.
52 * XXX: How does Apache 1.2 implement "gentle" restart
53 * that does not disrupt current connections? How does
54 * gentle restart interact with restart cleanup?
56 * 2. Request timeouts.
58 * Earlier versions of this module used ap_soft_timeout() rather than
59 * ap_hard_timeout() and ate FastCGI server output until it completed.
60 * This precluded the FastCGI server from having to implement a
61 * SIGPIPE handler, but meant hanging the application longer than
62 * necessary. SIGPIPE handler now must be installed in ALL FastCGI
63 * applications. The handler should abort further processing and go
64 * back into the accept() loop.
66 * Although using ap_soft_timeout() is better than ap_hard_timeout()
67 * we have to be more careful about SIGINT handling and subsequent
68 * processing, so, for now, make it hard.
72 #include "fcgi.h"
74 #ifdef APACHE2
75 #ifndef WIN32
77 #include <unistd.h>
79 #if APR_HAVE_CTYPE_H
80 #include <ctype.h>
81 #endif
83 #include "unixd.h"
85 #endif
86 #endif
88 #ifndef timersub
89 #define timersub(a, b, result) \
90 do { \
91 (result)->tv_sec = (a)->tv_sec - (b)->tv_sec; \
92 (result)->tv_usec = (a)->tv_usec - (b)->tv_usec; \
93 if ((result)->tv_usec < 0) { \
94 --(result)->tv_sec; \
95 (result)->tv_usec += 1000000; \
96 } \
97 } while (0)
98 #endif
101 * Global variables
104 pool *fcgi_config_pool; /* the config pool */
105 server_rec *fcgi_apache_main_server;
107 const char *fcgi_wrapper = NULL; /* wrapper path */
108 uid_t fcgi_user_id; /* the run uid of Apache & PM */
109 gid_t fcgi_group_id; /* the run gid of Apache & PM */
111 fcgi_server *fcgi_servers = NULL; /* AppClasses */
113 char *fcgi_socket_dir = NULL; /* default FastCgiIpcDir */
115 char *fcgi_dynamic_dir = NULL; /* directory for the dynamic
116 * fastcgi apps' sockets */
118 #ifdef WIN32
120 #pragma warning( disable : 4706 4100 4127)
121 fcgi_pm_job *fcgi_dynamic_mbox = NULL;
122 HANDLE *fcgi_dynamic_mbox_mutex = NULL;
123 HANDLE fcgi_pm_thread = INVALID_HANDLE_VALUE;
125 #else
127 int fcgi_pm_pipe[2] = { -1, -1 };
128 pid_t fcgi_pm_pid = -1;
130 #endif
132 char *fcgi_empty_env = NULL;
134 u_int dynamicMaxProcs = FCGI_DEFAULT_MAX_PROCS;
135 int dynamicMinProcs = FCGI_DEFAULT_MIN_PROCS;
136 int dynamicMaxClassProcs = FCGI_DEFAULT_MAX_CLASS_PROCS;
137 u_int dynamicKillInterval = FCGI_DEFAULT_KILL_INTERVAL;
138 u_int dynamicUpdateInterval = FCGI_DEFAULT_UPDATE_INTERVAL;
139 float dynamicGain = FCGI_DEFAULT_GAIN;
140 int dynamicThreshold1 = FCGI_DEFAULT_THRESHOLD_1;
141 int dynamicThresholdN = FCGI_DEFAULT_THRESHOLD_N;
142 u_int dynamicPleaseStartDelay = FCGI_DEFAULT_START_PROCESS_DELAY;
143 u_int dynamicAppConnectTimeout = FCGI_DEFAULT_APP_CONN_TIMEOUT;
144 char **dynamicEnvp = &fcgi_empty_env;
145 u_int dynamicProcessSlack = FCGI_DEFAULT_PROCESS_SLACK;
146 int dynamicAutoRestart = FCGI_DEFAULT_RESTART_DYNAMIC;
147 int dynamicAutoUpdate = FCGI_DEFAULT_AUTOUPDATE;
148 int dynamicFlush = FCGI_FLUSH;
149 u_int dynamicListenQueueDepth = FCGI_DEFAULT_LISTEN_Q;
150 u_int dynamicInitStartDelay = DEFAULT_INIT_START_DELAY;
151 u_int dynamicRestartDelay = FCGI_DEFAULT_RESTART_DELAY;
152 array_header *dynamic_pass_headers = NULL;
153 u_int dynamic_idle_timeout = FCGI_DEFAULT_IDLE_TIMEOUT;
155 /*******************************************************************************
156 * Construct a message and write it to the pm_pipe.
158 static void send_to_pm(const char id, const char * const fs_path,
159 const char *user, const char * const group, const unsigned long q_usec,
160 const unsigned long req_usec)
162 #ifdef WIN32
163 fcgi_pm_job *job = NULL;
165 if (!(job = (fcgi_pm_job *) malloc(sizeof(fcgi_pm_job))))
166 return;
167 #else
168 static int failed_count = 0;
169 int buflen = 0;
170 char buf[FCGI_MAX_MSG_LEN];
171 #endif
173 if (strlen(fs_path) > FCGI_MAXPATH) {
174 ap_log_error(FCGI_LOG_ERR_NOERRNO, fcgi_apache_main_server,
175 "FastCGI: the path \"%s\" is too long (>%d) for a dynamic server", fs_path, FCGI_MAXPATH);
176 return;
179 switch(id) {
181 case FCGI_SERVER_START_JOB:
182 case FCGI_SERVER_RESTART_JOB:
183 #ifdef WIN32
184 job->id = id;
185 job->fs_path = strdup(fs_path);
186 job->user = strdup(user);
187 job->group = strdup(group);
188 job->qsec = 0L;
189 job->start_time = 0L;
190 #else
191 buflen = sprintf(buf, "%c %s %s %s*", id, fs_path, user, group);
192 #endif
193 break;
195 case FCGI_REQUEST_TIMEOUT_JOB:
196 #ifdef WIN32
197 job->id = id;
198 job->fs_path = strdup(fs_path);
199 job->user = strdup(user);
200 job->group = strdup(group);
201 job->qsec = 0L;
202 job->start_time = 0L;
203 #else
204 buflen = sprintf(buf, "%c %s %s %s*", id, fs_path, user, group);
205 #endif
206 break;
208 case FCGI_REQUEST_COMPLETE_JOB:
209 #ifdef WIN32
210 job->id = id;
211 job->fs_path = strdup(fs_path);
212 job->qsec = q_usec;
213 job->start_time = req_usec;
214 job->user = strdup(user);
215 job->group = strdup(group);
216 #else
217 buflen = sprintf(buf, "%c %s %s %s %lu %lu*", id, fs_path, user, group, q_usec, req_usec);
218 #endif
219 break;
222 #ifdef WIN32
223 if (fcgi_pm_add_job(job)) return;
225 SetEvent(fcgi_event_handles[MBOX_EVENT]);
226 #else
227 ASSERT(buflen <= FCGI_MAX_MSG_LEN);
229 /* There is no apache flag or function that can be used to id
230 * restart/shutdown pending so ignore the first few failures as
231 * once it breaks it will stay broke */
232 if (write(fcgi_pm_pipe[1], (const void *)buf, buflen) != buflen
233 && failed_count++ > 10)
235 ap_log_error(FCGI_LOG_WARN, fcgi_apache_main_server,
236 "FastCGI: write() to PM failed (ignore if a restart or shutdown is pending)");
238 #endif
242 *----------------------------------------------------------------------
244 * init_module
246 * An Apache module initializer, called by the Apache core
247 * after reading the server config.
249 * Start the process manager no matter what, since there may be a
250 * request for dynamic FastCGI applications without any being
251 * configured as static applications. Also, check for the existence
252 * and create if necessary a subdirectory into which all dynamic
253 * sockets will go.
255 *----------------------------------------------------------------------
257 #ifdef APACHE2
258 static apcb_t init_module(apr_pool_t * p, apr_pool_t * plog,
259 apr_pool_t * tp, server_rec * s)
260 #else
261 static apcb_t init_module(server_rec *s, pool *p)
262 #endif
264 #ifndef WIN32
265 const char *err;
266 #endif
268 /* Register to reset to default values when the config pool is cleaned */
269 ap_block_alarms();
270 ap_register_cleanup(p, NULL, fcgi_config_reset_globals, ap_null_cleanup);
271 ap_unblock_alarms();
273 #ifdef APACHE2
274 ap_add_version_component(p, "mod_fastcgi/" MOD_FASTCGI_VERSION);
275 #else
276 ap_add_version_component("mod_fastcgi/" MOD_FASTCGI_VERSION);
277 #endif
279 fcgi_config_set_fcgi_uid_n_gid(1);
281 /* keep these handy */
282 fcgi_config_pool = p;
283 fcgi_apache_main_server = s;
285 #ifdef WIN32
286 if (fcgi_socket_dir == NULL)
287 fcgi_socket_dir = DEFAULT_SOCK_DIR;
288 fcgi_dynamic_dir = ap_pstrcat(p, fcgi_socket_dir, "dynamic", NULL);
289 #else
291 if (fcgi_socket_dir == NULL)
292 fcgi_socket_dir = ap_server_root_relative(p, DEFAULT_SOCK_DIR);
294 /* Create Unix/Domain socket directory */
295 if ((err = fcgi_config_make_dir(p, fcgi_socket_dir)))
296 ap_log_error(FCGI_LOG_ERR, s, "FastCGI: %s", err);
298 /* Create Dynamic directory */
299 if ((err = fcgi_config_make_dynamic_dir(p, 1)))
300 ap_log_error(FCGI_LOG_ERR, s, "FastCGI: %s", err);
302 /* Spawn the PM only once. Under Unix, Apache calls init() routines
303 * twice, once before detach() and once after. Win32 doesn't detach.
304 * Under DSO, DSO modules are unloaded between the two init() calls.
305 * Under Unix, the -X switch causes two calls to init() but no detach
306 * (but all subprocesses are wacked so the PM is toasted anyway)! */
308 #ifdef APACHE2
310 void * first_pass;
311 apr_pool_userdata_get(&first_pass, "mod_fastcgi", s->process->pool);
312 if (first_pass == NULL)
314 apr_pool_userdata_set((const void *)1, "mod_fastcgi",
315 apr_pool_cleanup_null, s->process->pool);
316 return APCB_OK;
319 #else /* !APACHE2 */
321 if (ap_standalone && ap_restart_time == 0)
322 return;
324 #endif
326 /* Create the pipe for comm with the PM */
327 if (pipe(fcgi_pm_pipe) < 0) {
328 ap_log_error(FCGI_LOG_ERR, s, "FastCGI: pipe() failed");
331 /* Start the Process Manager */
333 #ifdef APACHE2
335 apr_proc_t * proc = apr_palloc(p, sizeof(*proc));
336 apr_status_t rv;
338 rv = apr_proc_fork(proc, tp);
340 if (rv == APR_INCHILD)
342 /* child */
343 fcgi_pm_main(NULL);
344 exit(1);
346 else if (rv != APR_INPARENT)
348 return rv;
351 /* parent */
353 apr_pool_note_subprocess(p, proc, APR_KILL_ONLY_ONCE);
355 #else /* !APACHE2 */
357 fcgi_pm_pid = ap_spawn_child(p, fcgi_pm_main, NULL, kill_only_once, NULL, NULL, NULL);
358 if (fcgi_pm_pid <= 0) {
359 ap_log_error(FCGI_LOG_ALERT, s,
360 "FastCGI: can't start the process manager, spawn_child() failed");
363 #endif /* !APACHE2 */
365 close(fcgi_pm_pipe[0]);
367 #endif /* !WIN32 */
369 return APCB_OK;
372 #ifdef WIN32
373 #ifdef APACHE2
374 static apcb_t fcgi_child_exit(void * dc)
375 #else
376 static apcb_t fcgi_child_exit(server_rec *dc0, pool *dc1)
377 #endif
379 /* Signal the PM thread to exit*/
380 SetEvent(fcgi_event_handles[TERM_EVENT]);
382 /* Waiting on pm thread to exit */
383 WaitForSingleObject(fcgi_pm_thread, INFINITE);
385 return APCB_OK;
387 #endif /* WIN32 */
389 #ifdef APACHE2
390 static void fcgi_child_init(apr_pool_t * p, server_rec * dc)
391 #else
392 static void fcgi_child_init(server_rec *dc, pool *p)
393 #endif
395 #ifdef WIN32
396 /* Create the MBOX, TERM, and WAKE event handlers */
397 fcgi_event_handles[0] = CreateEvent(NULL, FALSE, FALSE, NULL);
398 if (fcgi_event_handles[0] == NULL) {
399 ap_log_error(FCGI_LOG_ALERT, fcgi_apache_main_server,
400 "FastCGI: CreateEvent() failed");
402 fcgi_event_handles[1] = CreateEvent(NULL, FALSE, FALSE, NULL);
403 if (fcgi_event_handles[1] == NULL) {
404 ap_log_error(FCGI_LOG_ALERT, fcgi_apache_main_server,
405 "FastCGI: CreateEvent() failed");
407 fcgi_event_handles[2] = CreateEvent(NULL, FALSE, FALSE, NULL);
408 if (fcgi_event_handles[2] == NULL) {
409 ap_log_error(FCGI_LOG_ALERT, fcgi_apache_main_server,
410 "FastCGI: CreateEvent() failed");
413 /* Create the mbox mutex (PM - request threads) */
414 fcgi_dynamic_mbox_mutex = CreateMutex(NULL, FALSE, NULL);
415 if (fcgi_dynamic_mbox_mutex == NULL) {
416 ap_log_error(FCGI_LOG_ALERT, fcgi_apache_main_server,
417 "FastCGI: CreateMutex() failed");
420 /* Spawn of the process manager thread */
421 fcgi_pm_thread = (HANDLE) _beginthread(fcgi_pm_main, 0, NULL);
422 if (fcgi_pm_thread == (HANDLE) -1) {
423 ap_log_error(FCGI_LOG_ALERT, fcgi_apache_main_server,
424 "_beginthread() failed to spawn the process manager");
427 #ifdef APACHE2
428 apr_pool_cleanup_register(p, NULL, fcgi_child_exit, fcgi_child_exit);
429 #endif
430 #endif
434 *----------------------------------------------------------------------
436 * get_header_line --
438 * Terminate a line: scan to the next newline, scan back to the
439 * first non-space character and store a terminating zero. Return
440 * the next character past the end of the newline.
442 * If the end of the string is reached, ASSERT!
444 * If the FIRST character(s) in the line are '\n' or "\r\n", the
445 * first character is replaced with a NULL and next character
446 * past the newline is returned. NOTE: this condition supercedes
447 * the processing of RFC-822 continuation lines.
449 * If continuation is set to 'TRUE', then it parses a (possible)
450 * sequence of RFC-822 continuation lines.
452 * Results:
453 * As above.
455 * Side effects:
456 * Termination byte stored in string.
458 *----------------------------------------------------------------------
460 static char *get_header_line(char *start, int continuation)
462 char *p = start;
463 char *end = start;
465 if(p[0] == '\r' && p[1] == '\n') { /* If EOL in 1st 2 chars */
466 p++; /* point to \n and stop */
467 } else if(*p != '\n') {
468 if(continuation) {
469 while(*p != '\0') {
470 if(*p == '\n' && p[1] != ' ' && p[1] != '\t')
471 break;
472 p++;
474 } else {
475 while(*p != '\0' && *p != '\n') {
476 p++;
481 ASSERT(*p != '\0');
482 end = p;
483 end++;
486 * Trim any trailing whitespace.
488 while(isspace((unsigned char)p[-1]) && p > start) {
489 p--;
492 *p = '\0';
493 return end;
496 #ifdef WIN32
498 static int set_nonblocking(const fcgi_request * fr, int nonblocking)
500 if (fr->using_npipe_io)
502 if (nonblocking)
504 DWORD mode = PIPE_NOWAIT | PIPE_READMODE_BYTE;
505 if (SetNamedPipeHandleState((HANDLE) fr->fd, &mode, NULL, NULL) == 0)
507 ap_log_rerror(FCGI_LOG_ERR, fr->r,
508 "FastCGI: SetNamedPipeHandleState() failed");
509 return -1;
513 else
515 unsigned long ioctl_arg = (nonblocking) ? 1 : 0;
516 if (ioctlsocket(fr->fd, FIONBIO, &ioctl_arg) != 0)
518 errno = WSAGetLastError();
519 ap_log_rerror(FCGI_LOG_ERR_ERRNO, fr->r,
520 "FastCGI: ioctlsocket() failed");
521 return -1;
525 return 0;
528 #else
530 static int set_nonblocking(const fcgi_request * fr, int nonblocking)
532 int nb_flag = 0;
533 int fd_flags = fcntl(fr->fd, F_GETFL, 0);
535 if (fd_flags < 0) return -1;
537 #if defined(O_NONBLOCK)
538 nb_flag = O_NONBLOCK;
539 #elif defined(O_NDELAY)
540 nb_flag = O_NDELAY;
541 #elif defined(FNDELAY)
542 nb_flag = FNDELAY;
543 #else
544 #error "TODO - don't read from app until all data from client is posted."
545 #endif
547 fd_flags = (nonblocking) ? (fd_flags | nb_flag) : (fd_flags & ~nb_flag);
549 return fcntl(fr->fd, F_SETFL, fd_flags);
552 #endif
554 /*******************************************************************************
555 * Close the connection to the FastCGI server. This is normally called by
556 * do_work(), but may also be called as in request pool cleanup.
558 static void close_connection_to_fs(fcgi_request *fr)
560 #ifdef WIN32
562 if (fr->fd != INVALID_SOCKET)
564 set_nonblocking(fr, FALSE);
566 if (fr->using_npipe_io)
568 CloseHandle((HANDLE) fr->fd);
570 else
572 /* abort the connection entirely */
573 struct linger linger = {0, 0};
574 setsockopt(fr->fd, SOL_SOCKET, SO_LINGER, (void *) &linger, sizeof(linger));
575 closesocket(fr->fd);
578 fr->fd = INVALID_SOCKET;
580 #else /* ! WIN32 */
582 if (fr->fd >= 0)
584 struct linger linger = {0, 0};
585 set_nonblocking(fr, FALSE);
586 /* abort the connection entirely */
587 setsockopt(fr->fd, SOL_SOCKET, SO_LINGER, &linger, sizeof(linger));
588 close(fr->fd);
589 fr->fd = -1;
591 #endif /* ! WIN32 */
593 if (fr->dynamic && fr->keepReadingFromFcgiApp == FALSE)
595 /* XXX FCGI_REQUEST_COMPLETE_JOB is only sent for requests which complete
596 * normally WRT the fcgi app. There is no data sent for
597 * connect() timeouts or requests which complete abnormally.
598 * KillDynamicProcs() and RemoveRecords() need to be looked at
599 * to be sure they can reasonably handle these cases before
600 * sending these sort of stats - theres some funk in there.
602 if (fcgi_util_ticks(&fr->completeTime) < 0)
604 /* there's no point to aborting the request, just log it */
605 ap_log_error(FCGI_LOG_ERR, fr->r->server, "FastCGI: can't get time of day");
613 *----------------------------------------------------------------------
615 * process_headers --
617 * Call with r->parseHeader == SCAN_CGI_READING_HEADERS
618 * and initial script output in fr->header.
620 * If the initial script output does not include the header
621 * terminator ("\r\n\r\n") process_headers returns with no side
622 * effects, to be called again when more script output
623 * has been appended to fr->header.
625 * If the initial script output includes the header terminator,
626 * process_headers parses the headers and determines whether or
627 * not the remaining script output will be sent to the client.
628 * If so, process_headers sends the HTTP response headers to the
629 * client and copies any non-header script output to the output
630 * buffer reqOutbuf.
632 * Results:
633 * none.
635 * Side effects:
636 * May set r->parseHeader to:
637 * SCAN_CGI_FINISHED -- headers parsed, returning script response
638 * SCAN_CGI_BAD_HEADER -- malformed header from script
639 * SCAN_CGI_INT_REDIRECT -- handler should perform internal redirect
640 * SCAN_CGI_SRV_REDIRECT -- handler should return REDIRECT
642 *----------------------------------------------------------------------
645 static const char *process_headers(request_rec *r, fcgi_request *fr)
647 char *p, *next, *name, *value;
648 int len, flag;
649 int hasContentType, hasStatus, hasLocation;
651 ASSERT(fr->parseHeader == SCAN_CGI_READING_HEADERS);
653 if (fr->header == NULL)
654 return NULL;
657 * Do we have the entire header? Scan for the blank line that
658 * terminates the header.
660 p = (char *)fr->header->elts;
661 len = fr->header->nelts;
662 flag = 0;
663 while(len-- && flag < 2) {
664 switch(*p) {
665 case '\r':
666 break;
667 case '\n':
668 flag++;
669 break;
670 case '\0':
671 case '\v':
672 case '\f':
673 name = "Invalid Character";
674 goto BadHeader;
675 break;
676 default:
677 flag = 0;
678 break;
680 p++;
683 /* Return (to be called later when we have more data)
684 * if we don't have an entire header. */
685 if (flag < 2)
686 return NULL;
689 * Parse all the headers.
691 fr->parseHeader = SCAN_CGI_FINISHED;
692 hasContentType = hasStatus = hasLocation = FALSE;
693 next = (char *)fr->header->elts;
694 for(;;) {
695 next = get_header_line(name = next, TRUE);
696 if (*name == '\0') {
697 break;
699 if ((p = strchr(name, ':')) == NULL) {
700 goto BadHeader;
702 value = p + 1;
703 while (p != name && isspace((unsigned char)*(p - 1))) {
704 p--;
706 if (p == name) {
707 goto BadHeader;
709 *p = '\0';
710 if (strpbrk(name, " \t") != NULL) {
711 *p = ' ';
712 goto BadHeader;
714 while (isspace((unsigned char)*value)) {
715 value++;
718 if (strcasecmp(name, "Status") == 0) {
719 int statusValue = strtol(value, NULL, 10);
721 if (hasStatus) {
722 goto DuplicateNotAllowed;
724 if (statusValue < 0) {
725 fr->parseHeader = SCAN_CGI_BAD_HEADER;
726 return ap_psprintf(r->pool, "invalid Status '%s'", value);
728 hasStatus = TRUE;
729 r->status = statusValue;
730 r->status_line = ap_pstrdup(r->pool, value);
731 continue;
734 if (fr->role == FCGI_RESPONDER) {
735 if (strcasecmp(name, "Content-type") == 0) {
736 if (hasContentType) {
737 goto DuplicateNotAllowed;
739 hasContentType = TRUE;
740 r->content_type = ap_pstrdup(r->pool, value);
741 continue;
744 if (strcasecmp(name, "Location") == 0) {
745 if (hasLocation) {
746 goto DuplicateNotAllowed;
748 hasLocation = TRUE;
749 ap_table_set(r->headers_out, "Location", value);
750 continue;
753 /* If the script wants them merged, it can do it */
754 ap_table_add(r->err_headers_out, name, value);
755 continue;
757 else {
758 ap_table_add(fr->authHeaders, name, value);
762 if (fr->role != FCGI_RESPONDER)
763 return NULL;
766 * Who responds, this handler or Apache?
768 if (hasLocation) {
769 const char *location = ap_table_get(r->headers_out, "Location");
771 * Based on internal redirect handling in mod_cgi.c...
773 * If a script wants to produce its own Redirect
774 * body, it now has to explicitly *say* "Status: 302"
776 if (r->status == 200) {
777 if(location[0] == '/') {
779 * Location is an relative path. This handler will
780 * consume all script output, then have Apache perform an
781 * internal redirect.
783 fr->parseHeader = SCAN_CGI_INT_REDIRECT;
784 return NULL;
785 } else {
787 * Location is an absolute URL. If the script didn't
788 * produce a Content-type header, this handler will
789 * consume all script output and then have Apache generate
790 * its standard redirect response. Otherwise this handler
791 * will transmit the script's response.
793 fr->parseHeader = SCAN_CGI_SRV_REDIRECT;
794 return NULL;
799 * We're responding. Send headers, buffer excess script output.
801 ap_send_http_header(r);
803 /* We need to reinstate our timeout, send_http_header() kill()s it */
804 ap_hard_timeout("FastCGI request processing", r);
806 if (r->header_only) {
807 /* we've got all we want from the server */
808 close_connection_to_fs(fr);
809 fr->exitStatusSet = 1;
810 fcgi_buf_reset(fr->clientOutputBuffer);
811 fcgi_buf_reset(fr->serverOutputBuffer);
812 return NULL;
815 len = fr->header->nelts - (next - fr->header->elts);
817 ASSERT(len >= 0);
818 ASSERT(BufferLength(fr->clientOutputBuffer) == 0);
820 if (BufferFree(fr->clientOutputBuffer) < len) {
821 fr->clientOutputBuffer = fcgi_buf_new(r->pool, len);
824 ASSERT(BufferFree(fr->clientOutputBuffer) >= len);
826 if (len > 0) {
827 int sent;
828 sent = fcgi_buf_add_block(fr->clientOutputBuffer, next, len);
829 ASSERT(sent == len);
832 return NULL;
834 BadHeader:
835 /* Log first line of a multi-line header */
836 if ((p = strpbrk(name, "\r\n")) != NULL)
837 *p = '\0';
838 fr->parseHeader = SCAN_CGI_BAD_HEADER;
839 return ap_psprintf(r->pool, "malformed header '%s'", name);
841 DuplicateNotAllowed:
842 fr->parseHeader = SCAN_CGI_BAD_HEADER;
843 return ap_psprintf(r->pool, "duplicate header '%s'", name);
847 * Read from the client filling both the FastCGI server buffer and the
848 * client buffer with the hopes of buffering the client data before
849 * making the connect() to the FastCGI server. This prevents slow
850 * clients from keeping the FastCGI server in processing longer than is
851 * necessary.
853 static int read_from_client_n_queue(fcgi_request *fr)
855 char *end;
856 int count;
857 long int countRead;
859 while (BufferFree(fr->clientInputBuffer) > 0 || BufferFree(fr->serverOutputBuffer) > 0) {
860 fcgi_protocol_queue_client_buffer(fr);
862 if (fr->expectingClientContent <= 0)
863 return OK;
865 fcgi_buf_get_free_block_info(fr->clientInputBuffer, &end, &count);
866 if (count == 0)
867 return OK;
869 if ((countRead = ap_get_client_block(fr->r, end, count)) < 0)
871 /* set the header scan state to done to prevent logging an error
872 * - hokey approach - probably should be using a unique value */
873 fr->parseHeader = SCAN_CGI_FINISHED;
874 return -1;
877 if (countRead == 0) {
878 fr->expectingClientContent = 0;
880 else {
881 fcgi_buf_add_update(fr->clientInputBuffer, countRead);
882 ap_reset_timeout(fr->r);
885 return OK;
888 static int write_to_client(fcgi_request *fr)
890 char *begin;
891 int count;
892 int rv;
893 #ifdef APACHE2
894 apr_bucket * bkt;
895 apr_bucket_brigade * bde;
896 apr_bucket_alloc_t * const bkt_alloc = fr->r->connection->bucket_alloc;
897 #endif
899 fcgi_buf_get_block_info(fr->clientOutputBuffer, &begin, &count);
900 if (count == 0)
901 return OK;
903 /* If fewer than count bytes are written, an error occured.
904 * ap_bwrite() typically forces a flushed write to the client, this
905 * effectively results in a block (and short packets) - it should
906 * be fixed, but I didn't win much support for the idea on new-httpd.
907 * So, without patching Apache, the best way to deal with this is
908 * to size the fcgi_bufs to hold all of the script output (within
909 * reason) so the script can be released from having to wait around
910 * for the transmission to the client to complete. */
912 #ifdef APACHE2
914 bde = apr_brigade_create(fr->r->pool, bkt_alloc);
915 bkt = apr_bucket_transient_create(begin, count, bkt_alloc);
916 APR_BRIGADE_INSERT_TAIL(bde, bkt);
918 if (fr->fs ? fr->fs->flush : dynamicFlush)
920 bkt = apr_bucket_flush_create(bkt_alloc);
921 APR_BRIGADE_INSERT_TAIL(bde, bkt);
924 rv = ap_pass_brigade(fr->r->output_filters, bde);
926 #elif defined(RUSSIAN_APACHE)
928 rv = (ap_rwrite(begin, count, fr->r) != count);
930 #else
932 rv = (ap_bwrite(fr->r->connection->client, begin, count) != count);
934 #endif
936 if (rv)
938 ap_log_rerror(FCGI_LOG_INFO_NOERRNO, fr->r,
939 "FastCGI: client stopped connection before send body completed");
940 return -1;
943 #ifndef APACHE2
945 ap_reset_timeout(fr->r);
947 /* Don't bother with a wrapped buffer, limiting exposure to slow
948 * clients. The BUFF routines don't allow a writev from above,
949 * and don't always memcpy to minimize small write()s, this should
950 * be fixed, but I didn't win much support for the idea on
951 * new-httpd - I'll have to _prove_ its a problem first.. */
953 /* The default behaviour used to be to flush with every write, but this
954 * can tie up the FastCGI server longer than is necessary so its an option now */
956 if (fr->fs ? fr->fs->flush : dynamicFlush)
958 #ifdef RUSSIAN_APACHE
959 rv = ap_rflush(fr->r);
960 #else
961 rv = ap_bflush(fr->r->connection->client);
962 #endif
964 if (rv)
966 ap_log_rerror(FCGI_LOG_INFO_NOERRNO, fr->r,
967 "FastCGI: client stopped connection before send body completed");
968 return -1;
971 ap_reset_timeout(fr->r);
974 #endif /* !APACHE2 */
976 fcgi_buf_toss(fr->clientOutputBuffer, count);
977 return OK;
980 static void
981 get_request_identity(request_rec * const r,
982 uid_t * const uid,
983 gid_t * const gid)
985 #if defined(WIN32)
986 *uid = (uid_t) 0;
987 *gid = (gid_t) 0;
988 #elif defined(APACHE2)
989 ap_unix_identity_t * identity = ap_run_get_suexec_identity(r);
990 if (identity)
992 *uid = identity->uid;
993 *gid = identity->gid;
995 else
997 *uid = 0;
998 *gid = 0;
1000 #else
1001 *uid = r->server->server_uid;
1002 *gid = r->server->server_gid;
1003 #endif
1006 /*******************************************************************************
1007 * Determine the user and group the wrapper should be called with.
1008 * Based on code in Apache's create_argv_cmd() (util_script.c).
1010 static void set_uid_n_gid(request_rec *r, const char **user, const char **group)
1012 if (fcgi_wrapper == NULL) {
1013 *user = "-";
1014 *group = "-";
1015 return;
1018 if (strncmp("/~", r->uri, 2) == 0) {
1019 /* its a user dir uri, just send the ~user, and leave it to the PM */
1020 char *end = strchr(r->uri + 2, '/');
1022 if (end)
1023 *user = memcpy(ap_pcalloc(r->pool, end - r->uri), r->uri + 1, end - r->uri - 1);
1024 else
1025 *user = ap_pstrdup(r->pool, r->uri + 1);
1026 *group = "-";
1028 else {
1029 uid_t uid;
1030 gid_t gid;
1032 get_request_identity(r, &uid, &gid);
1034 *user = ap_psprintf(r->pool, "%ld", (long) uid);
1035 *group = ap_psprintf(r->pool, "%ld", (long) gid);
1039 static void send_request_complete(fcgi_request *fr)
1041 if (fr->completeTime.tv_sec)
1043 struct timeval qtime, rtime;
1045 timersub(&fr->queueTime, &fr->startTime, &qtime);
1046 timersub(&fr->completeTime, &fr->queueTime, &rtime);
1048 send_to_pm(FCGI_REQUEST_COMPLETE_JOB, fr->fs_path,
1049 fr->user, fr->group,
1050 qtime.tv_sec * 1000000 + qtime.tv_usec,
1051 rtime.tv_sec * 1000000 + rtime.tv_usec);
1056 /*******************************************************************************
1057 * Connect to the FastCGI server.
1059 static int open_connection_to_fs(fcgi_request *fr)
1061 struct timeval tval;
1062 fd_set write_fds, read_fds;
1063 int status;
1064 request_rec * const r = fr->r;
1065 pool * const rp = r->pool;
1066 const char *socket_path = NULL;
1067 struct sockaddr *socket_addr = NULL;
1068 int socket_addr_len = 0;
1069 #ifndef WIN32
1070 const char *err = NULL;
1071 #endif
1073 /* Create the connection point */
1074 if (fr->dynamic)
1076 socket_path = fcgi_util_socket_hash_filename(rp, fr->fs_path, fr->user, fr->group);
1077 socket_path = fcgi_util_socket_make_path_absolute(rp, socket_path, 1);
1079 #ifndef WIN32
1080 err = fcgi_util_socket_make_domain_addr(rp, (struct sockaddr_un **)&socket_addr,
1081 &socket_addr_len, socket_path);
1082 if (err) {
1083 ap_log_rerror(FCGI_LOG_ERR, r,
1084 "FastCGI: failed to connect to (dynamic) server \"%s\": "
1085 "%s", fr->fs_path, err);
1086 return FCGI_FAILED;
1088 #endif
1090 else
1092 #ifdef WIN32
1093 if (fr->fs->dest_addr != NULL) {
1094 socket_addr = fr->fs->dest_addr;
1096 else if (fr->fs->socket_addr) {
1097 socket_addr = fr->fs->socket_addr;
1099 else {
1100 socket_path = fr->fs->socket_path;
1102 #else
1103 socket_addr = fr->fs->socket_addr;
1104 #endif
1105 socket_addr_len = fr->fs->socket_addr_len;
1108 if (fr->dynamic)
1110 #ifdef WIN32
1111 if (fr->fs && fr->fs->restartTime)
1112 #else
1113 struct stat sock_stat;
1115 if (stat(socket_path, &sock_stat) == 0)
1116 #endif
1118 // It exists
1119 if (dynamicAutoUpdate)
1121 struct stat app_stat;
1123 /* TODO: follow sym links */
1125 if (stat(fr->fs_path, &app_stat) == 0)
1127 #ifdef WIN32
1128 if (fr->fs->startTime < app_stat.st_mtime)
1129 #else
1130 if (sock_stat.st_mtime < app_stat.st_mtime)
1131 #endif
1133 #ifndef WIN32
1134 struct timeval tv = {1, 0};
1135 #endif
1137 * There's a newer one, request a restart.
1139 send_to_pm(FCGI_SERVER_RESTART_JOB, fr->fs_path, fr->user, fr->group, 0, 0);
1141 #ifdef WIN32
1142 Sleep(1000);
1143 #else
1144 /* Avoid sleep/alarm interactions */
1145 ap_select(0, NULL, NULL, NULL, &tv);
1146 #endif
1151 else
1153 int i;
1155 send_to_pm(FCGI_SERVER_START_JOB, fr->fs_path, fr->user, fr->group, 0, 0);
1157 /* wait until it looks like its running - this shouldn't take
1158 * very long at all - the exception is when the sockets are
1159 * removed out from under a running application - the loop
1160 * limit addresses this (preventing spinning) */
1162 for (i = 10; i > 0; i--)
1164 #ifdef WIN32
1165 Sleep(500);
1167 fr->fs = fcgi_util_fs_get_by_id(fr->fs_path, 0, 0);
1169 if (fr->fs && fr->fs->restartTime)
1170 #else
1171 struct timeval tv = {0, 500000};
1173 /* Avoid sleep/alarm interactions */
1174 ap_select(0, NULL, NULL, NULL, &tv);
1176 if (stat(socket_path, &sock_stat) == 0)
1177 #endif
1179 break;
1183 if (i <= 0)
1185 ap_log_rerror(FCGI_LOG_ALERT, r,
1186 "FastCGI: failed to connect to (dynamic) server \"%s\": "
1187 "something is seriously wrong, any chance the "
1188 "socket/named_pipe directory was removed?, see the "
1189 "FastCgiIpcDir directive", fr->fs_path);
1190 return FCGI_FAILED;
1195 #ifdef WIN32
1196 if (socket_path)
1198 BOOL ready;
1199 DWORD connect_time;
1200 int rv;
1201 HANDLE wait_npipe_mutex;
1202 DWORD interval;
1203 DWORD max_connect_time = FCGI_NAMED_PIPE_CONNECT_TIMEOUT;
1205 fr->using_npipe_io = TRUE;
1207 if (fr->dynamic)
1209 interval = dynamicPleaseStartDelay * 1000;
1211 if (dynamicAppConnectTimeout) {
1212 max_connect_time = dynamicAppConnectTimeout;
1215 else
1217 interval = FCGI_NAMED_PIPE_CONNECT_TIMEOUT * 1000;
1219 if (fr->fs->appConnectTimeout) {
1220 max_connect_time = fr->fs->appConnectTimeout;
1224 fcgi_util_ticks(&fr->startTime);
1227 // xxx this handle should live somewhere (see CloseHandle()s below too)
1228 char * wait_npipe_mutex_name, * cp;
1229 wait_npipe_mutex_name = cp = ap_pstrdup(rp, socket_path);
1230 while ((cp = strchr(cp, '\\'))) *cp = '/';
1232 wait_npipe_mutex = CreateMutex(NULL, FALSE, wait_npipe_mutex_name);
1235 if (wait_npipe_mutex == NULL)
1237 ap_log_rerror(FCGI_LOG_ERR, r,
1238 "FastCGI: failed to connect to server \"%s\": "
1239 "can't create the WaitNamedPipe mutex", fr->fs_path);
1240 return FCGI_FAILED;
1243 SetLastError(ERROR_SUCCESS);
1245 rv = WaitForSingleObject(wait_npipe_mutex, max_connect_time * 1000);
1247 if (rv == WAIT_TIMEOUT || rv == WAIT_FAILED)
1249 if (fr->dynamic)
1251 send_to_pm(FCGI_REQUEST_TIMEOUT_JOB, fr->fs_path, fr->user, fr->group, 0, 0);
1253 ap_log_rerror(FCGI_LOG_ERR_NOERRNO, r,
1254 "FastCGI: failed to connect to server \"%s\": "
1255 "wait for a npipe instance failed", fr->fs_path);
1256 FCGIDBG3("interval=%d, max_connect_time=%d", interval, max_connect_time);
1257 CloseHandle(wait_npipe_mutex);
1258 return FCGI_FAILED;
1261 fcgi_util_ticks(&fr->queueTime);
1263 connect_time = fr->queueTime.tv_sec - fr->startTime.tv_sec;
1265 if (fr->dynamic)
1267 if (connect_time >= interval)
1269 send_to_pm(FCGI_REQUEST_TIMEOUT_JOB, fr->fs_path, fr->user, fr->group, 0, 0);
1270 FCGIDBG4("connect_time=%d, interval=%d, max_connect_time=%d", connect_time, interval, max_connect_time);
1272 if (max_connect_time - connect_time < interval)
1274 interval = max_connect_time - connect_time;
1277 else
1279 interval -= connect_time * 1000;
1282 for (;;)
1284 ready = WaitNamedPipe(socket_path, interval);
1286 if (ready)
1288 fr->fd = (SOCKET) CreateFile(socket_path,
1289 GENERIC_READ | GENERIC_WRITE,
1290 FILE_SHARE_READ | FILE_SHARE_WRITE,
1291 NULL, // no security attributes
1292 OPEN_EXISTING, // opens existing pipe
1293 FILE_FLAG_OVERLAPPED,
1294 NULL); // no template file
1296 if (fr->fd != (SOCKET) INVALID_HANDLE_VALUE)
1298 ReleaseMutex(wait_npipe_mutex);
1299 CloseHandle(wait_npipe_mutex);
1300 fcgi_util_ticks(&fr->queueTime);
1301 FCGIDBG2("got npipe connect: %s", fr->fs_path);
1302 return FCGI_OK;
1305 if (GetLastError() != ERROR_PIPE_BUSY
1306 && GetLastError() != ERROR_FILE_NOT_FOUND)
1308 ap_log_rerror(FCGI_LOG_ERR, r,
1309 "FastCGI: failed to connect to server \"%s\": "
1310 "CreateFile() failed", fr->fs_path);
1311 break;
1314 FCGIDBG2("missed npipe connect: %s", fr->fs_path);
1317 if (fr->dynamic)
1319 send_to_pm(FCGI_REQUEST_TIMEOUT_JOB, fr->fs_path, fr->user, fr->group, 0, 0);
1322 fcgi_util_ticks(&fr->queueTime);
1324 connect_time = fr->queueTime.tv_sec - fr->startTime.tv_sec;
1326 FCGIDBG5("interval=%d, max_connect_time=%d, connect_time=%d, ready=%d", interval, max_connect_time, connect_time, ready);
1328 if (connect_time >= max_connect_time)
1330 ap_log_rerror(FCGI_LOG_ERR, r,
1331 "FastCGI: failed to connect to server \"%s\": "
1332 "CreateFile()/WaitNamedPipe() timed out", fr->fs_path);
1333 break;
1337 ReleaseMutex(wait_npipe_mutex);
1338 CloseHandle(wait_npipe_mutex);
1339 fr->fd = INVALID_SOCKET;
1340 return FCGI_FAILED;
1343 #endif
1345 /* Create the socket */
1346 fr->fd = socket(socket_addr->sa_family, SOCK_STREAM, 0);
1348 #ifdef WIN32
1349 if (fr->fd == INVALID_SOCKET) {
1350 errno = WSAGetLastError(); // Not sure this is going to work as expected
1351 #else
1352 if (fr->fd < 0) {
1353 #endif
1354 ap_log_rerror(FCGI_LOG_ERR_ERRNO, r,
1355 "FastCGI: failed to connect to server \"%s\": "
1356 "socket() failed", fr->fs_path);
1357 return FCGI_FAILED;
1360 #ifndef WIN32
1361 if (fr->fd >= FD_SETSIZE) {
1362 ap_log_rerror(FCGI_LOG_ERR, r,
1363 "FastCGI: failed to connect to server \"%s\": "
1364 "socket file descriptor (%u) is larger than "
1365 "FD_SETSIZE (%u), you probably need to rebuild Apache with a "
1366 "larger FD_SETSIZE", fr->fs_path, fr->fd, FD_SETSIZE);
1367 return FCGI_FAILED;
1369 #endif
1371 /* If appConnectTimeout is non-zero, setup do a non-blocking connect */
1372 if ((fr->dynamic && dynamicAppConnectTimeout) || (!fr->dynamic && fr->fs->appConnectTimeout)) {
1373 set_nonblocking(fr, TRUE);
1376 if (fr->dynamic) {
1377 fcgi_util_ticks(&fr->startTime);
1380 /* Connect */
1381 if (connect(fr->fd, (struct sockaddr *)socket_addr, socket_addr_len) == 0)
1382 goto ConnectionComplete;
1384 #ifdef WIN32
1386 errno = WSAGetLastError();
1387 if (errno != WSAEWOULDBLOCK) {
1388 ap_log_rerror(FCGI_LOG_ERR_ERRNO, r,
1389 "FastCGI: failed to connect to server \"%s\": "
1390 "connect() failed", fr->fs_path);
1391 return FCGI_FAILED;
1394 #else
1396 /* ECONNREFUSED means the listen queue is full (or there isn't one).
1397 * With dynamic I can at least make sure the PM knows this is occuring */
1398 if (fr->dynamic && errno == ECONNREFUSED) {
1399 /* @@@ This might be better as some other "kind" of message */
1400 send_to_pm(FCGI_REQUEST_TIMEOUT_JOB, fr->fs_path, fr->user, fr->group, 0, 0);
1402 errno = ECONNREFUSED;
1405 if (errno != EINPROGRESS) {
1406 ap_log_rerror(FCGI_LOG_ERR, r,
1407 "FastCGI: failed to connect to server \"%s\": "
1408 "connect() failed", fr->fs_path);
1409 return FCGI_FAILED;
1412 #endif
1414 /* The connect() is non-blocking */
1416 errno = 0;
1418 if (fr->dynamic) {
1419 do {
1420 FD_ZERO(&write_fds);
1421 FD_SET(fr->fd, &write_fds);
1422 read_fds = write_fds;
1423 tval.tv_sec = dynamicPleaseStartDelay;
1424 tval.tv_usec = 0;
1426 status = ap_select((fr->fd+1), &read_fds, &write_fds, NULL, &tval);
1427 if (status < 0)
1428 break;
1430 fcgi_util_ticks(&fr->queueTime);
1432 if (status > 0)
1433 break;
1435 /* select() timed out */
1436 send_to_pm(FCGI_REQUEST_TIMEOUT_JOB, fr->fs_path, fr->user, fr->group, 0, 0);
1437 } while ((fr->queueTime.tv_sec - fr->startTime.tv_sec) < (int)dynamicAppConnectTimeout);
1439 /* XXX These can be moved down when dynamic vars live is a struct */
1440 if (status == 0) {
1441 ap_log_rerror(FCGI_LOG_ERR_NOERRNO, r,
1442 "FastCGI: failed to connect to server \"%s\": "
1443 "connect() timed out (appConnTimeout=%dsec)",
1444 fr->fs_path, dynamicAppConnectTimeout);
1445 return FCGI_FAILED;
1447 } /* dynamic */
1448 else {
1449 tval.tv_sec = fr->fs->appConnectTimeout;
1450 tval.tv_usec = 0;
1451 FD_ZERO(&write_fds);
1452 FD_SET(fr->fd, &write_fds);
1453 read_fds = write_fds;
1455 status = ap_select((fr->fd+1), &read_fds, &write_fds, NULL, &tval);
1457 if (status == 0) {
1458 ap_log_rerror(FCGI_LOG_ERR_NOERRNO, r,
1459 "FastCGI: failed to connect to server \"%s\": "
1460 "connect() timed out (appConnTimeout=%dsec)",
1461 fr->fs_path, dynamicAppConnectTimeout);
1462 return FCGI_FAILED;
1464 } /* !dynamic */
1466 if (status < 0) {
1467 #ifdef WIN32
1468 errno = WSAGetLastError();
1469 #endif
1470 ap_log_rerror(FCGI_LOG_ERR_ERRNO, r,
1471 "FastCGI: failed to connect to server \"%s\": "
1472 "select() failed", fr->fs_path);
1473 return FCGI_FAILED;
1476 if (FD_ISSET(fr->fd, &write_fds) || FD_ISSET(fr->fd, &read_fds)) {
1477 int error = 0;
1478 NET_SIZE_T len = sizeof(error);
1480 if (getsockopt(fr->fd, SOL_SOCKET, SO_ERROR, (char *)&error, &len) < 0) {
1481 /* Solaris pending error */
1482 #ifdef WIN32
1483 errno = WSAGetLastError();
1484 #endif
1485 ap_log_rerror(FCGI_LOG_ERR_ERRNO, r,
1486 "FastCGI: failed to connect to server \"%s\": "
1487 "select() failed (Solaris pending error)", fr->fs_path);
1488 return FCGI_FAILED;
1491 if (error != 0) {
1492 /* Berkeley-derived pending error */
1493 errno = error;
1494 ap_log_rerror(FCGI_LOG_ERR_ERRNO, r,
1495 "FastCGI: failed to connect to server \"%s\": "
1496 "select() failed (pending error)", fr->fs_path);
1497 return FCGI_FAILED;
1500 else {
1501 #ifdef WIN32
1502 errno = WSAGetLastError();
1503 #endif
1504 ap_log_rerror(FCGI_LOG_ERR_ERRNO, r,
1505 "FastCGI: failed to connect to server \"%s\": "
1506 "select() error - THIS CAN'T HAPPEN!", fr->fs_path);
1507 return FCGI_FAILED;
1510 ConnectionComplete:
1511 /* Return to blocking mode if it was set up */
1512 if ((fr->dynamic && dynamicAppConnectTimeout) || (!fr->dynamic && fr->fs->appConnectTimeout)) {
1513 set_nonblocking(fr, FALSE);
1516 #ifdef TCP_NODELAY
1517 if (socket_addr->sa_family == AF_INET) {
1518 /* We shouldn't be sending small packets and there's no application
1519 * level ack of the data we send, so disable Nagle */
1520 int set = 1;
1521 setsockopt(fr->fd, IPPROTO_TCP, TCP_NODELAY, (char *)&set, sizeof(set));
1523 #endif
1525 return FCGI_OK;
1528 static void sink_client_data(fcgi_request *fr)
1530 char *base;
1531 int size;
1533 fcgi_buf_reset(fr->clientInputBuffer);
1534 fcgi_buf_get_free_block_info(fr->clientInputBuffer, &base, &size);
1535 while (ap_get_client_block(fr->r, base, size) > 0);
1538 static apcb_t cleanup(void *data)
1540 fcgi_request * const fr = (fcgi_request *) data;
1542 if (fr == NULL) return APCB_OK;
1544 /* its more than likely already run, but... */
1545 close_connection_to_fs(fr);
1547 send_request_complete(fr);
1549 if (fr->fs_stderr_len) {
1550 ap_log_rerror(FCGI_LOG_ERR_NOERRNO, fr->r,
1551 "FastCGI: server \"%s\" stderr: %s", fr->fs_path, fr->fs_stderr);
1554 return APCB_OK;
1557 #ifdef WIN32
1558 static int npipe_io(fcgi_request * const fr)
1560 request_rec * const r = fr->r;
1561 enum
1563 STATE_ENV_SEND,
1564 STATE_CLIENT_RECV,
1565 STATE_SERVER_SEND,
1566 STATE_SERVER_RECV,
1567 STATE_CLIENT_SEND,
1568 STATE_ERROR
1570 state = STATE_ENV_SEND;
1571 env_status env_status;
1572 int client_recv;
1573 int dynamic_first_recv = fr->dynamic;
1574 int idle_timeout = fr->dynamic ? dynamic_idle_timeout : fr->fs->idle_timeout;
1575 int send_pending = 0;
1576 int recv_pending = 0;
1577 int client_send = 0;
1578 int rv;
1579 OVERLAPPED rov = { 0 };
1580 OVERLAPPED sov = { 0 };
1581 HANDLE events[2];
1582 struct timeval timeout;
1583 struct timeval dynamic_last_io_time = {0, 0};
1584 int did_io = 1;
1585 pool * const rp = r->pool;
1587 DWORD recv_count = 0;
1589 if (fr->role == FCGI_RESPONDER)
1591 client_recv = (fr->expectingClientContent != 0);
1594 idle_timeout = fr->dynamic ? dynamic_idle_timeout : fr->fs->idle_timeout;
1596 env_status.envp = NULL;
1598 events[0] = CreateEvent(NULL, TRUE, FALSE, NULL);
1599 events[1] = CreateEvent(NULL, TRUE, FALSE, NULL);
1600 sov.hEvent = events[0];
1601 rov.hEvent = events[1];
1603 if (fr->dynamic)
1605 dynamic_last_io_time = fr->startTime;
1607 if (dynamicAppConnectTimeout)
1609 struct timeval qwait;
1610 timersub(&fr->queueTime, &fr->startTime, &qwait);
1611 dynamic_first_recv = qwait.tv_sec / dynamicPleaseStartDelay + 1;
1615 ap_hard_timeout("FastCGI request processing", r);
1617 while (state != STATE_CLIENT_SEND)
1619 DWORD msec_timeout;
1621 switch (state)
1623 case STATE_ENV_SEND:
1625 if (fcgi_protocol_queue_env(r, fr, &env_status) == 0)
1627 goto SERVER_SEND;
1630 state = STATE_CLIENT_RECV;
1632 /* fall through */
1634 case STATE_CLIENT_RECV:
1636 if (read_from_client_n_queue(fr) != OK)
1638 state = STATE_ERROR;
1639 break;
1642 if (fr->eofSent)
1644 state = STATE_SERVER_SEND;
1647 /* fall through */
1649 SERVER_SEND:
1651 case STATE_SERVER_SEND:
1653 if (! send_pending && BufferLength(fr->serverOutputBuffer))
1655 Buffer * b = fr->serverOutputBuffer;
1656 DWORD sent, len;
1658 len = min(b->length, b->data + b->size - b->begin);
1660 if (WriteFile((HANDLE) fr->fd, b->begin, len, &sent, &sov))
1662 /* sov.hEvent is set */
1663 fcgi_buf_removed(b, sent);
1665 else if (GetLastError() == ERROR_IO_PENDING)
1667 send_pending = 1;
1669 else
1671 ap_log_rerror(FCGI_LOG_ERR, r, "FastCGI: comm with server "
1672 "\"%s\" aborted: WriteFile() failed", fr->fs_path);
1673 state = STATE_ERROR;
1674 break;
1678 /* fall through */
1680 case STATE_SERVER_RECV:
1683 * Only get more data when the serverInputBuffer is empty.
1684 * Otherwise we may already have the END_REQUEST buffered
1685 * (but not processed) and a read on a closed named pipe
1686 * results in an error that is normally abnormal.
1688 if (! recv_pending && BufferLength(fr->serverInputBuffer) == 0)
1690 Buffer * b = fr->serverInputBuffer;
1691 DWORD rcvd, len;
1693 len = min(b->size - b->length, b->data + b->size - b->end);
1695 if (ReadFile((HANDLE) fr->fd, b->end, len, &rcvd, &rov))
1697 fcgi_buf_added(b, rcvd);
1698 recv_count += rcvd;
1699 ResetEvent(rov.hEvent);
1700 if (dynamic_first_recv)
1702 dynamic_first_recv = 0;
1705 else if (GetLastError() == ERROR_IO_PENDING)
1707 recv_pending = 1;
1709 else if (GetLastError() == ERROR_HANDLE_EOF)
1711 fr->keepReadingFromFcgiApp = FALSE;
1712 state = STATE_CLIENT_SEND;
1713 ResetEvent(rov.hEvent);
1714 break;
1716 else if (GetLastError() == ERROR_NO_DATA)
1718 break;
1720 else
1722 ap_log_rerror(FCGI_LOG_ERR, r, "FastCGI: comm with server "
1723 "\"%s\" aborted: ReadFile() failed", fr->fs_path);
1724 state = STATE_ERROR;
1725 break;
1729 /* fall through */
1731 case STATE_CLIENT_SEND:
1733 if (client_send || ! BufferFree(fr->clientOutputBuffer))
1735 if (write_to_client(fr))
1737 state = STATE_ERROR;
1738 break;
1741 client_send = 0;
1744 break;
1746 default:
1748 ASSERT(0);
1751 if (state == STATE_ERROR)
1753 break;
1756 /* setup the io timeout */
1758 if (BufferLength(fr->clientOutputBuffer))
1760 /* don't let client data sit too long, it might be a push */
1761 timeout.tv_sec = 0;
1762 timeout.tv_usec = 100000;
1764 else if (dynamic_first_recv)
1766 int delay;
1767 struct timeval qwait;
1769 fcgi_util_ticks(&fr->queueTime);
1771 if (did_io)
1773 /* a send() succeeded last pass */
1774 dynamic_last_io_time = fr->queueTime;
1776 else
1778 /* timed out last pass */
1779 struct timeval idle_time;
1781 timersub(&fr->queueTime, &dynamic_last_io_time, &idle_time);
1783 if (idle_time.tv_sec > idle_timeout)
1785 send_to_pm(FCGI_REQUEST_TIMEOUT_JOB, fr->fs_path, fr->user, fr->group, 0, 0);
1786 ap_log_rerror(FCGI_LOG_ERR_NOERRNO, r, "FastCGI: comm "
1787 "with (dynamic) server \"%s\" aborted: (first read) "
1788 "idle timeout (%d sec)", fr->fs_path, idle_timeout);
1789 state = STATE_ERROR;
1790 break;
1794 timersub(&fr->queueTime, &fr->startTime, &qwait);
1796 delay = dynamic_first_recv * dynamicPleaseStartDelay;
1798 if (qwait.tv_sec < delay)
1800 timeout.tv_sec = delay;
1801 timeout.tv_usec = 100000; /* fudge for select() slop */
1802 timersub(&timeout, &qwait, &timeout);
1804 else
1806 /* Killed time somewhere.. client read? */
1807 send_to_pm(FCGI_REQUEST_TIMEOUT_JOB, fr->fs_path, fr->user, fr->group, 0, 0);
1808 dynamic_first_recv = qwait.tv_sec / dynamicPleaseStartDelay + 1;
1809 timeout.tv_sec = dynamic_first_recv * dynamicPleaseStartDelay;
1810 timeout.tv_usec = 100000; /* fudge for select() slop */
1811 timersub(&timeout, &qwait, &timeout);
1814 else
1816 timeout.tv_sec = idle_timeout;
1817 timeout.tv_usec = 0;
1820 /* require a pended recv otherwise the app can deadlock */
1821 if (recv_pending)
1823 msec_timeout = timeout.tv_sec * 1000 + timeout.tv_usec / 1000;
1825 rv = WaitForMultipleObjects(2, events, FALSE, msec_timeout);
1827 if (rv == WAIT_TIMEOUT)
1829 did_io = 0;
1831 if (BufferLength(fr->clientOutputBuffer))
1833 client_send = 1;
1835 else if (dynamic_first_recv)
1837 struct timeval qwait;
1839 fcgi_util_ticks(&fr->queueTime);
1840 timersub(&fr->queueTime, &fr->startTime, &qwait);
1842 send_to_pm(FCGI_REQUEST_TIMEOUT_JOB, fr->fs_path, fr->user, fr->group, 0, 0);
1844 dynamic_first_recv = qwait.tv_sec / dynamicPleaseStartDelay + 1;
1846 else
1848 ap_log_rerror(FCGI_LOG_ERR_NOERRNO, r, "FastCGI: comm with "
1849 "server \"%s\" aborted: idle timeout (%d sec)",
1850 fr->fs_path, idle_timeout);
1851 state = STATE_ERROR;
1852 break;
1855 else
1857 int i = rv - WAIT_OBJECT_0;
1859 did_io = 1;
1861 if (i == 0)
1863 if (send_pending)
1865 DWORD sent;
1867 if (GetOverlappedResult((HANDLE) fr->fd, &sov, &sent, FALSE))
1869 send_pending = 0;
1870 fcgi_buf_removed(fr->serverOutputBuffer, sent);
1872 else
1874 ap_log_rerror(FCGI_LOG_ERR, r, "FastCGI: comm with server "
1875 "\"%s\" aborted: GetOverlappedResult() failed", fr->fs_path);
1876 state = STATE_ERROR;
1877 break;
1881 ResetEvent(sov.hEvent);
1883 else
1885 DWORD rcvd;
1887 ASSERT(i == 1);
1889 recv_pending = 0;
1890 ResetEvent(rov.hEvent);
1892 if (GetOverlappedResult((HANDLE) fr->fd, &rov, &rcvd, FALSE))
1894 fcgi_buf_added(fr->serverInputBuffer, rcvd);
1895 if (dynamic_first_recv)
1897 dynamic_first_recv = 0;
1900 else
1902 ap_log_rerror(FCGI_LOG_ERR, r, "FastCGI: comm with server "
1903 "\"%s\" aborted: GetOverlappedResult() failed", fr->fs_path);
1904 state = STATE_ERROR;
1905 break;
1911 if (fcgi_protocol_dequeue(rp, fr))
1913 state = STATE_ERROR;
1914 break;
1917 if (fr->parseHeader == SCAN_CGI_READING_HEADERS)
1919 const char * err = process_headers(r, fr);
1920 if (err)
1922 ap_log_rerror(FCGI_LOG_ERR_NOERRNO, r,
1923 "FastCGI: comm with server \"%s\" aborted: "
1924 "error parsing headers: %s", fr->fs_path, err);
1925 state = STATE_ERROR;
1926 break;
1930 if (fr->exitStatusSet)
1932 fr->keepReadingFromFcgiApp = FALSE;
1933 state = STATE_CLIENT_SEND;
1934 break;
1938 if (! fr->exitStatusSet || ! fr->eofSent)
1940 CancelIo((HANDLE) fr->fd);
1943 CloseHandle(rov.hEvent);
1944 CloseHandle(sov.hEvent);
1946 return (state == STATE_ERROR);
1948 #endif /* WIN32 */
1950 static int socket_io(fcgi_request * const fr)
1952 enum
1954 STATE_SOCKET_NONE,
1955 STATE_ENV_SEND,
1956 STATE_CLIENT_RECV,
1957 STATE_SERVER_SEND,
1958 STATE_SERVER_RECV,
1959 STATE_CLIENT_SEND,
1960 STATE_ERROR,
1961 STATE_CLIENT_ERROR
1963 state = STATE_ENV_SEND;
1965 request_rec * const r = fr->r;
1967 struct timeval timeout;
1968 struct timeval dynamic_last_io_time = {0, 0};
1969 fd_set read_set;
1970 fd_set write_set;
1971 int nfds = fr->fd + 1;
1972 int select_status = 1;
1973 int idle_timeout;
1974 int rv;
1975 int dynamic_first_recv = fr->dynamic ? 1 : 0;
1976 int client_send = FALSE;
1977 int client_recv = FALSE;
1978 env_status env;
1979 pool *rp = r->pool;
1981 if (fr->role == FCGI_RESPONDER)
1983 client_recv = (fr->expectingClientContent != 0);
1986 idle_timeout = fr->dynamic ? dynamic_idle_timeout : fr->fs->idle_timeout;
1988 env.envp = NULL;
1990 if (fr->dynamic)
1992 dynamic_last_io_time = fr->startTime;
1994 if (dynamicAppConnectTimeout)
1996 struct timeval qwait;
1997 timersub(&fr->queueTime, &fr->startTime, &qwait);
1998 dynamic_first_recv = qwait.tv_sec / dynamicPleaseStartDelay + 1;
2002 ap_hard_timeout("FastCGI request processing", r);
2004 set_nonblocking(fr, TRUE);
2006 for (;;)
2008 FD_ZERO(&read_set);
2009 FD_ZERO(&write_set);
2011 switch (state)
2013 case STATE_ENV_SEND:
2015 if (fcgi_protocol_queue_env(r, fr, &env) == 0)
2017 goto SERVER_SEND;
2020 state = STATE_CLIENT_RECV;
2022 /* fall through */
2024 case STATE_CLIENT_RECV:
2026 if (read_from_client_n_queue(fr))
2028 state = STATE_CLIENT_ERROR;
2029 break;
2032 if (fr->eofSent)
2034 state = STATE_SERVER_SEND;
2037 /* fall through */
2039 SERVER_SEND:
2041 case STATE_SERVER_SEND:
2043 if (BufferLength(fr->serverOutputBuffer))
2045 FD_SET(fr->fd, &write_set);
2047 else
2049 ASSERT(fr->eofSent);
2050 state = STATE_SERVER_RECV;
2053 /* fall through */
2055 case STATE_SERVER_RECV:
2057 FD_SET(fr->fd, &read_set);
2059 /* fall through */
2061 case STATE_CLIENT_SEND:
2063 if (client_send || ! BufferFree(fr->clientOutputBuffer))
2065 if (write_to_client(fr))
2067 state = STATE_CLIENT_ERROR;
2068 break;
2071 client_send = 0;
2074 break;
2076 case STATE_ERROR:
2077 case STATE_CLIENT_ERROR:
2079 break;
2081 default:
2083 ASSERT(0);
2086 if (state == STATE_CLIENT_ERROR || state == STATE_ERROR)
2088 break;
2091 /* setup the io timeout */
2093 if (BufferLength(fr->clientOutputBuffer))
2095 /* don't let client data sit too long, it might be a push */
2096 timeout.tv_sec = 0;
2097 timeout.tv_usec = 100000;
2099 else if (dynamic_first_recv)
2101 int delay;
2102 struct timeval qwait;
2104 fcgi_util_ticks(&fr->queueTime);
2106 if (select_status)
2108 /* a send() succeeded last pass */
2109 dynamic_last_io_time = fr->queueTime;
2111 else
2113 /* timed out last pass */
2114 struct timeval idle_time;
2116 timersub(&fr->queueTime, &dynamic_last_io_time, &idle_time);
2118 if (idle_time.tv_sec > idle_timeout)
2120 send_to_pm(FCGI_REQUEST_TIMEOUT_JOB, fr->fs_path, fr->user, fr->group, 0, 0);
2121 ap_log_rerror(FCGI_LOG_ERR_NOERRNO, r, "FastCGI: comm "
2122 "with (dynamic) server \"%s\" aborted: (first read) "
2123 "idle timeout (%d sec)", fr->fs_path, idle_timeout);
2124 state = STATE_ERROR;
2125 break;
2129 timersub(&fr->queueTime, &fr->startTime, &qwait);
2131 delay = dynamic_first_recv * dynamicPleaseStartDelay;
2133 FCGIDBG5("qwait=%ld.%06ld delay=%d first_recv=%d", qwait.tv_sec, qwait.tv_usec, delay, dynamic_first_recv);
2135 if (qwait.tv_sec < delay)
2137 timeout.tv_sec = delay;
2138 timeout.tv_usec = 100000; /* fudge for select() slop */
2139 timersub(&timeout, &qwait, &timeout);
2141 else
2143 /* Killed time somewhere.. client read? */
2144 send_to_pm(FCGI_REQUEST_TIMEOUT_JOB, fr->fs_path, fr->user, fr->group, 0, 0);
2145 dynamic_first_recv = qwait.tv_sec / dynamicPleaseStartDelay + 1;
2146 timeout.tv_sec = dynamic_first_recv * dynamicPleaseStartDelay;
2147 timeout.tv_usec = 100000; /* fudge for select() slop */
2148 timersub(&timeout, &qwait, &timeout);
2151 else
2153 timeout.tv_sec = idle_timeout;
2154 timeout.tv_usec = 0;
2157 /* wait on the socket */
2158 select_status = ap_select(nfds, &read_set, &write_set, NULL, &timeout);
2160 if (select_status < 0)
2162 ap_log_rerror(FCGI_LOG_ERR_ERRNO, r, "FastCGI: comm with server "
2163 "\"%s\" aborted: select() failed", fr->fs_path);
2164 state = STATE_ERROR;
2165 break;
2168 if (select_status == 0)
2170 /* select() timeout */
2172 if (BufferLength(fr->clientOutputBuffer))
2174 if (fr->role == FCGI_RESPONDER)
2176 client_send = TRUE;
2179 else if (dynamic_first_recv)
2181 struct timeval qwait;
2183 fcgi_util_ticks(&fr->queueTime);
2184 timersub(&fr->queueTime, &fr->startTime, &qwait);
2186 send_to_pm(FCGI_REQUEST_TIMEOUT_JOB, fr->fs_path, fr->user, fr->group, 0, 0);
2188 dynamic_first_recv = qwait.tv_sec / dynamicPleaseStartDelay + 1;
2189 continue;
2191 else
2193 ap_log_rerror(FCGI_LOG_ERR_NOERRNO, r, "FastCGI: comm with "
2194 "server \"%s\" aborted: idle timeout (%d sec)",
2195 fr->fs_path, idle_timeout);
2196 state = STATE_ERROR;
2200 if (FD_ISSET(fr->fd, &write_set))
2202 /* send to the server */
2204 rv = fcgi_buf_socket_send(fr->serverOutputBuffer, fr->fd);
2206 if (rv < 0)
2208 ap_log_rerror(FCGI_LOG_ERR, r, "FastCGI: comm with server "
2209 "\"%s\" aborted: write failed", fr->fs_path);
2210 state = STATE_ERROR;
2211 break;
2215 if (FD_ISSET(fr->fd, &read_set))
2217 /* recv from the server */
2219 if (dynamic_first_recv)
2221 dynamic_first_recv = 0;
2222 fcgi_util_ticks(&fr->queueTime);
2225 rv = fcgi_buf_socket_recv(fr->serverInputBuffer, fr->fd);
2227 if (rv < 0)
2229 ap_log_rerror(FCGI_LOG_ERR, r, "FastCGI: comm with server "
2230 "\"%s\" aborted: read failed", fr->fs_path);
2231 state = STATE_ERROR;
2232 break;
2235 if (rv == 0)
2237 fr->keepReadingFromFcgiApp = FALSE;
2238 state = STATE_CLIENT_SEND;
2239 break;
2243 if (fcgi_protocol_dequeue(rp, fr))
2245 state = STATE_ERROR;
2246 break;
2249 if (fr->parseHeader == SCAN_CGI_READING_HEADERS)
2251 const char * err = process_headers(r, fr);
2252 if (err)
2254 ap_log_rerror(FCGI_LOG_ERR_NOERRNO, r,
2255 "FastCGI: comm with server \"%s\" aborted: "
2256 "error parsing headers: %s", fr->fs_path, err);
2257 state = STATE_ERROR;
2258 break;
2262 if (fr->exitStatusSet)
2264 fr->keepReadingFromFcgiApp = FALSE;
2265 state = STATE_CLIENT_SEND;
2266 break;
2270 return (state == STATE_ERROR);
2274 /*----------------------------------------------------------------------
2275 * This is the core routine for moving data between the FastCGI
2276 * application and the Web server's client.
2278 static int do_work(request_rec * const r, fcgi_request * const fr)
2280 int rv;
2281 pool *rp = r->pool;
2283 fcgi_protocol_queue_begin_request(fr);
2285 if (fr->role == FCGI_RESPONDER)
2287 rv = ap_setup_client_block(r, REQUEST_CHUNKED_ERROR);
2288 if (rv != OK)
2290 ap_kill_timeout(r);
2291 return rv;
2294 fr->expectingClientContent = ap_should_client_block(r);
2297 ap_block_alarms();
2298 ap_register_cleanup(rp, (void *)fr, cleanup, ap_null_cleanup);
2299 ap_unblock_alarms();
2301 ap_hard_timeout("connect() to FastCGI server", r);
2303 /* Connect to the FastCGI Application */
2304 if (open_connection_to_fs(fr) != FCGI_OK)
2306 ap_kill_timeout(r);
2307 return HTTP_INTERNAL_SERVER_ERROR;
2310 #ifdef WIN32
2311 if (fr->using_npipe_io)
2313 rv = npipe_io(fr);
2315 else
2316 #endif
2318 rv = socket_io(fr);
2321 /* comm with the server is done */
2322 close_connection_to_fs(fr);
2324 if (fr->role == FCGI_RESPONDER)
2326 sink_client_data(fr);
2329 while (rv == 0 && (BufferLength(fr->serverInputBuffer) || BufferLength(fr->clientOutputBuffer)))
2331 if (fcgi_protocol_dequeue(rp, fr))
2333 rv = HTTP_INTERNAL_SERVER_ERROR;
2336 if (fr->parseHeader == SCAN_CGI_READING_HEADERS)
2338 const char * err = process_headers(r, fr);
2339 if (err)
2341 ap_log_rerror(FCGI_LOG_ERR_NOERRNO, r,
2342 "FastCGI: comm with server \"%s\" aborted: "
2343 "error parsing headers: %s", fr->fs_path, err);
2344 rv = HTTP_INTERNAL_SERVER_ERROR;
2348 if (fr->role == FCGI_RESPONDER)
2350 if (write_to_client(fr))
2352 break;
2355 else
2357 fcgi_buf_reset(fr->clientOutputBuffer);
2361 switch (fr->parseHeader)
2363 case SCAN_CGI_FINISHED:
2365 if (fr->role == FCGI_RESPONDER)
2367 /* RUSSIAN_APACHE requires rflush() over bflush() */
2368 ap_rflush(r);
2369 #ifndef APACHE2
2370 ap_bgetopt(r->connection->client, BO_BYTECT, &r->bytes_sent);
2371 #endif
2374 /* fall through */
2376 case SCAN_CGI_INT_REDIRECT:
2377 case SCAN_CGI_SRV_REDIRECT:
2379 break;
2381 case SCAN_CGI_READING_HEADERS:
2383 ap_log_rerror(FCGI_LOG_ERR_NOERRNO, r, "FastCGI: incomplete headers "
2384 "(%d bytes) received from server \"%s\"", fr->header->nelts, fr->fs_path);
2386 /* fall through */
2388 case SCAN_CGI_BAD_HEADER:
2390 rv = HTTP_INTERNAL_SERVER_ERROR;
2391 break;
2393 default:
2395 ASSERT(0);
2396 rv = HTTP_INTERNAL_SERVER_ERROR;
2399 ap_kill_timeout(r);
2400 return rv;
2403 static int
2404 create_fcgi_request(request_rec * const r,
2405 const char * const path,
2406 fcgi_request ** const frP)
2408 const char *fs_path;
2409 pool * const p = r->pool;
2410 fcgi_server *fs;
2411 fcgi_request * const fr = (fcgi_request *)ap_pcalloc(p, sizeof(fcgi_request));
2412 uid_t uid;
2413 gid_t gid;
2415 fs_path = path ? path : r->filename;
2417 get_request_identity(r, &uid, &gid);
2419 fs = fcgi_util_fs_get_by_id(fs_path, uid, gid);
2421 if (fs == NULL)
2423 const char * err;
2424 struct stat *my_finfo;
2426 /* dynamic? */
2428 #ifndef APACHE2
2429 if (path == NULL)
2431 /* AP2: its bogus that we don't make use of r->finfo, but
2432 * its an apr_finfo_t and there is no apr_os_finfo_get() */
2434 my_finfo = &r->finfo;
2436 else
2437 #endif
2439 my_finfo = (struct stat *) ap_palloc(p, sizeof(struct stat));
2441 if (stat(fs_path, my_finfo) < 0)
2443 ap_log_rerror(FCGI_LOG_ERR_ERRNO, r,
2444 "FastCGI: stat() of \"%s\" failed", fs_path);
2445 return HTTP_NOT_FOUND;
2449 err = fcgi_util_fs_is_path_ok(p, fs_path, my_finfo);
2450 if (err)
2452 ap_log_rerror(FCGI_LOG_ERR_NOERRNO, r,
2453 "FastCGI: invalid (dynamic) server \"%s\": %s", fs_path, err);
2454 return HTTP_FORBIDDEN;
2458 fr->serverInputBuffer = fcgi_buf_new(p, SERVER_BUFSIZE);
2459 fr->serverOutputBuffer = fcgi_buf_new(p, SERVER_BUFSIZE);
2460 fr->clientInputBuffer = fcgi_buf_new(p, SERVER_BUFSIZE);
2461 fr->clientOutputBuffer = fcgi_buf_new(p, SERVER_BUFSIZE);
2462 fr->erBufPtr = fcgi_buf_new(p, sizeof(FCGI_EndRequestBody) + 1);
2463 fr->gotHeader = FALSE;
2464 fr->parseHeader = SCAN_CGI_READING_HEADERS;
2465 fr->header = ap_make_array(p, 1, 1);
2466 fr->fs_stderr = NULL;
2467 fr->r = r;
2468 fr->readingEndRequestBody = FALSE;
2469 fr->exitStatus = 0;
2470 fr->exitStatusSet = FALSE;
2471 fr->requestId = 1; /* anything but zero is OK here */
2472 fr->eofSent = FALSE;
2473 fr->role = FCGI_RESPONDER;
2474 fr->expectingClientContent = FALSE;
2475 fr->keepReadingFromFcgiApp = TRUE;
2476 fr->fs = fs;
2477 fr->fs_path = fs_path;
2478 fr->authHeaders = ap_make_table(p, 10);
2479 #ifdef WIN32
2480 fr->fd = INVALID_SOCKET;
2481 fr->dynamic = ((fs == NULL) || (fs->directive == APP_CLASS_DYNAMIC)) ? TRUE : FALSE;
2482 fr->using_npipe_io = FALSE;
2483 #else
2484 fr->dynamic = (fs == NULL) ? TRUE : FALSE;
2485 fr->fd = -1;
2486 #endif
2488 set_uid_n_gid(r, &fr->user, &fr->group);
2490 *frP = fr;
2492 return OK;
2496 *----------------------------------------------------------------------
2498 * handler --
2500 * This routine gets called for a request that corresponds to
2501 * a FastCGI connection. It performs the request synchronously.
2503 * Results:
2504 * Final status of request: OK or NOT_FOUND or HTTP_INTERNAL_SERVER_ERROR.
2506 * Side effects:
2507 * Request performed.
2509 *----------------------------------------------------------------------
2512 /* Stolen from mod_cgi.c..
2513 * KLUDGE --- for back-combatibility, we don't have to check ExecCGI
2514 * in ScriptAliased directories, which means we need to know if this
2515 * request came through ScriptAlias or not... so the Alias module
2516 * leaves a note for us.
2518 static int apache_is_scriptaliased(request_rec *r)
2520 const char *t = ap_table_get(r->notes, "alias-forced-type");
2521 return t && (!strcasecmp(t, "cgi-script"));
2524 /* If a script wants to produce its own Redirect body, it now
2525 * has to explicitly *say* "Status: 302". If it wants to use
2526 * Apache redirects say "Status: 200". See process_headers().
2528 static int post_process_for_redirects(request_rec * const r,
2529 const fcgi_request * const fr)
2531 switch(fr->parseHeader) {
2532 case SCAN_CGI_INT_REDIRECT:
2534 /* @@@ There are still differences between the handling in
2535 * mod_cgi and mod_fastcgi. This needs to be revisited.
2537 /* We already read the message body (if any), so don't allow
2538 * the redirected request to think it has one. We can ignore
2539 * Transfer-Encoding, since we used REQUEST_CHUNKED_ERROR.
2541 r->method = "GET";
2542 r->method_number = M_GET;
2543 ap_table_unset(r->headers_in, "Content-length");
2545 ap_internal_redirect_handler(ap_table_get(r->headers_out, "Location"), r);
2546 return OK;
2548 case SCAN_CGI_SRV_REDIRECT:
2549 return HTTP_MOVED_TEMPORARILY;
2551 default:
2552 return OK;
2556 /******************************************************************************
2557 * Process fastcgi-script requests. Based on mod_cgi::cgi_handler().
2559 static int content_handler(request_rec *r)
2561 fcgi_request *fr = NULL;
2562 int ret;
2564 #ifdef APACHE2
2565 if (strcmp(r->handler, FASTCGI_HANDLER_NAME))
2566 return DECLINED;
2567 #endif
2569 /* Setup a new FastCGI request */
2570 ret = create_fcgi_request(r, NULL, &fr);
2571 if (ret)
2573 return ret;
2576 /* If its a dynamic invocation, make sure scripts are OK here */
2577 if (fr->dynamic && ! (ap_allow_options(r) & OPT_EXECCGI)
2578 && ! apache_is_scriptaliased(r))
2580 ap_log_rerror(FCGI_LOG_ERR_NOERRNO, r,
2581 "FastCGI: \"ExecCGI Option\" is off in this directory: %s", r->uri);
2582 return HTTP_FORBIDDEN;
2585 /* Process the fastcgi-script request */
2586 if ((ret = do_work(r, fr)) != OK)
2587 return ret;
2589 /* Special case redirects */
2590 ret = post_process_for_redirects(r, fr);
2592 return ret;
2596 static int post_process_auth_passed_header(table *t, const char *key, const char * const val)
2598 if (strncasecmp(key, "Variable-", 9) == 0)
2599 key += 9;
2601 ap_table_setn(t, key, val);
2602 return 1;
2605 static int post_process_auth_passed_compat_header(table *t, const char *key, const char * const val)
2607 if (strncasecmp(key, "Variable-", 9) == 0)
2608 ap_table_setn(t, key + 9, val);
2610 return 1;
2613 static int post_process_auth_failed_header(table * const t, const char * const key, const char * const val)
2615 ap_table_setn(t, key, val);
2616 return 1;
2619 static void post_process_auth(fcgi_request * const fr, const int passed)
2621 request_rec * const r = fr->r;
2623 /* Restore the saved subprocess_env because we muddied ours up */
2624 r->subprocess_env = fr->saved_subprocess_env;
2626 if (passed) {
2627 if (fr->auth_compat) {
2628 ap_table_do((int (*)(void *, const char *, const char *))post_process_auth_passed_compat_header,
2629 (void *)r->subprocess_env, fr->authHeaders, NULL);
2631 else {
2632 ap_table_do((int (*)(void *, const char *, const char *))post_process_auth_passed_header,
2633 (void *)r->subprocess_env, fr->authHeaders, NULL);
2636 else {
2637 ap_table_do((int (*)(void *, const char *, const char *))post_process_auth_failed_header,
2638 (void *)r->err_headers_out, fr->authHeaders, NULL);
2641 /* @@@ Restore these.. its a hack until I rewrite the header handling */
2642 r->status = HTTP_OK;
2643 r->status_line = NULL;
2646 static int check_user_authentication(request_rec *r)
2648 int res, authenticated = 0;
2649 const char *password;
2650 fcgi_request *fr;
2651 const fcgi_dir_config * const dir_config =
2652 (const fcgi_dir_config *)ap_get_module_config(r->per_dir_config, &fastcgi_module);
2654 if (dir_config->authenticator == NULL)
2655 return DECLINED;
2657 /* Get the user password */
2658 if ((res = ap_get_basic_auth_pw(r, &password)) != OK)
2659 return res;
2661 res = create_fcgi_request(r, dir_config->authenticator, &fr);
2662 if (res)
2664 return res;
2667 /* Save the existing subprocess_env, because we're gonna muddy it up */
2668 fr->saved_subprocess_env = ap_copy_table(r->pool, r->subprocess_env);
2670 ap_table_setn(r->subprocess_env, "REMOTE_PASSWD", password);
2671 ap_table_setn(r->subprocess_env, "FCGI_APACHE_ROLE", "AUTHENTICATOR");
2673 /* The FastCGI Protocol doesn't differentiate authentication */
2674 fr->role = FCGI_AUTHORIZER;
2676 /* Do we need compatibility mode? */
2677 fr->auth_compat = (dir_config->authenticator_options & FCGI_COMPAT);
2679 if ((res = do_work(r, fr)) != OK)
2680 goto AuthenticationFailed;
2682 authenticated = (r->status == 200);
2683 post_process_auth(fr, authenticated);
2685 /* A redirect shouldn't be allowed during the authentication phase */
2686 if (ap_table_get(r->headers_out, "Location") != NULL) {
2687 ap_log_rerror(FCGI_LOG_ERR_NOERRNO, r,
2688 "FastCGI: FastCgiAuthenticator \"%s\" redirected (not allowed)",
2689 dir_config->authenticator);
2690 goto AuthenticationFailed;
2693 if (authenticated)
2694 return OK;
2696 AuthenticationFailed:
2697 if (!(dir_config->authenticator_options & FCGI_AUTHORITATIVE))
2698 return DECLINED;
2700 /* @@@ Probably should support custom_responses */
2701 ap_note_basic_auth_failure(r);
2702 ap_log_rerror(FCGI_LOG_ERR_NOERRNO, r,
2703 "FastCGI: authentication failed for user \"%s\": %s",
2704 #ifdef APACHE2
2705 r->user, r->uri);
2706 #else
2707 r->connection->user, r->uri);
2708 #endif
2710 return (res == OK) ? HTTP_UNAUTHORIZED : res;
2713 static int check_user_authorization(request_rec *r)
2715 int res, authorized = 0;
2716 fcgi_request *fr;
2717 const fcgi_dir_config * const dir_config =
2718 (const fcgi_dir_config *)ap_get_module_config(r->per_dir_config, &fastcgi_module);
2720 if (dir_config->authorizer == NULL)
2721 return DECLINED;
2723 /* @@@ We should probably honor the existing parameters to the require directive
2724 * as well as allow the definition of new ones (or use the basename of the
2725 * FastCGI server and pass the rest of the directive line), but for now keep
2726 * it simple. */
2728 res = create_fcgi_request(r, dir_config->authorizer, &fr);
2729 if (res)
2731 return res;
2734 /* Save the existing subprocess_env, because we're gonna muddy it up */
2735 fr->saved_subprocess_env = ap_copy_table(r->pool, r->subprocess_env);
2737 ap_table_setn(r->subprocess_env, "FCGI_APACHE_ROLE", "AUTHORIZER");
2739 fr->role = FCGI_AUTHORIZER;
2741 /* Do we need compatibility mode? */
2742 fr->auth_compat = (dir_config->authorizer_options & FCGI_COMPAT);
2744 if ((res = do_work(r, fr)) != OK)
2745 goto AuthorizationFailed;
2747 authorized = (r->status == 200);
2748 post_process_auth(fr, authorized);
2750 /* A redirect shouldn't be allowed during the authorization phase */
2751 if (ap_table_get(r->headers_out, "Location") != NULL) {
2752 ap_log_rerror(FCGI_LOG_ERR_NOERRNO, r,
2753 "FastCGI: FastCgiAuthorizer \"%s\" redirected (not allowed)",
2754 dir_config->authorizer);
2755 goto AuthorizationFailed;
2758 if (authorized)
2759 return OK;
2761 AuthorizationFailed:
2762 if (!(dir_config->authorizer_options & FCGI_AUTHORITATIVE))
2763 return DECLINED;
2765 /* @@@ Probably should support custom_responses */
2766 ap_note_basic_auth_failure(r);
2767 ap_log_rerror(FCGI_LOG_ERR_NOERRNO, r,
2768 "FastCGI: authorization failed for user \"%s\": %s",
2769 #ifdef APACHE2
2770 r->user, r->uri);
2771 #else
2772 r->connection->user, r->uri);
2773 #endif
2775 return (res == OK) ? HTTP_UNAUTHORIZED : res;
2778 static int check_access(request_rec *r)
2780 int res, access_allowed = 0;
2781 fcgi_request *fr;
2782 const fcgi_dir_config * const dir_config =
2783 (fcgi_dir_config *)ap_get_module_config(r->per_dir_config, &fastcgi_module);
2785 if (dir_config == NULL || dir_config->access_checker == NULL)
2786 return DECLINED;
2788 res = create_fcgi_request(r, dir_config->access_checker, &fr);
2789 if (res)
2791 return res;
2794 /* Save the existing subprocess_env, because we're gonna muddy it up */
2795 fr->saved_subprocess_env = ap_copy_table(r->pool, r->subprocess_env);
2797 ap_table_setn(r->subprocess_env, "FCGI_APACHE_ROLE", "ACCESS_CHECKER");
2799 /* The FastCGI Protocol doesn't differentiate access control */
2800 fr->role = FCGI_AUTHORIZER;
2802 /* Do we need compatibility mode? */
2803 fr->auth_compat = (dir_config->access_checker_options & FCGI_COMPAT);
2805 if ((res = do_work(r, fr)) != OK)
2806 goto AccessFailed;
2808 access_allowed = (r->status == 200);
2809 post_process_auth(fr, access_allowed);
2811 /* A redirect shouldn't be allowed during the access check phase */
2812 if (ap_table_get(r->headers_out, "Location") != NULL) {
2813 ap_log_rerror(FCGI_LOG_ERR_NOERRNO, r,
2814 "FastCGI: FastCgiAccessChecker \"%s\" redirected (not allowed)",
2815 dir_config->access_checker);
2816 goto AccessFailed;
2819 if (access_allowed)
2820 return OK;
2822 AccessFailed:
2823 if (!(dir_config->access_checker_options & FCGI_AUTHORITATIVE))
2824 return DECLINED;
2826 /* @@@ Probably should support custom_responses */
2827 ap_log_rerror(FCGI_LOG_ERR_NOERRNO, r, "FastCGI: access denied: %s", r->uri);
2828 return (res == OK) ? HTTP_FORBIDDEN : res;
2831 static int
2832 fixups(request_rec * r)
2834 uid_t uid;
2835 gid_t gid;
2837 get_request_identity(r, &uid, &gid);
2839 if (fcgi_util_fs_get_by_id(r->filename, uid, gid))
2841 r->handler = FASTCGI_HANDLER_NAME;
2842 return OK;
2845 return DECLINED;
2848 #ifndef APACHE2
2850 # define AP_INIT_RAW_ARGS(directive, func, mconfig, where, help) \
2851 { directive, func, mconfig, where, RAW_ARGS, help }
2852 # define AP_INIT_TAKE1(directive, func, mconfig, where, help) \
2853 { directive, func, mconfig, where, TAKE1, help }
2854 # define AP_INIT_TAKE12(directive, func, mconfig, where, help) \
2855 { directive, func, mconfig, where, TAKE12, help }
2856 # define AP_INIT_FLAG(directive, func, mconfig, where, help) \
2857 { directive, func, mconfig, where, FLAG, help }
2859 #endif
2861 static const command_rec fastcgi_cmds[] =
2863 AP_INIT_RAW_ARGS("AppClass", fcgi_config_new_static_server, NULL, RSRC_CONF, NULL),
2864 AP_INIT_RAW_ARGS("FastCgiServer", fcgi_config_new_static_server, NULL, RSRC_CONF, NULL),
2866 AP_INIT_RAW_ARGS("ExternalAppClass", fcgi_config_new_external_server, NULL, RSRC_CONF, NULL),
2867 AP_INIT_RAW_ARGS("FastCgiExternalServer", fcgi_config_new_external_server, NULL, RSRC_CONF, NULL),
2869 AP_INIT_TAKE1("FastCgiIpcDir", fcgi_config_set_socket_dir, NULL, RSRC_CONF, NULL),
2871 AP_INIT_TAKE1("FastCgiSuexec", fcgi_config_set_wrapper, NULL, RSRC_CONF, NULL),
2872 AP_INIT_TAKE1("FastCgiWrapper", fcgi_config_set_wrapper, NULL, RSRC_CONF, NULL),
2874 AP_INIT_RAW_ARGS("FCGIConfig", fcgi_config_set_config, NULL, RSRC_CONF, NULL),
2875 AP_INIT_RAW_ARGS("FastCgiConfig", fcgi_config_set_config, NULL, RSRC_CONF, NULL),
2877 AP_INIT_TAKE12("FastCgiAuthenticator", fcgi_config_new_auth_server,
2878 (void *)FCGI_AUTH_TYPE_AUTHENTICATOR, ACCESS_CONF,
2879 "a fastcgi-script path (absolute or relative to ServerRoot) followed by an optional -compat"),
2880 AP_INIT_FLAG("FastCgiAuthenticatorAuthoritative", fcgi_config_set_authoritative_slot,
2881 (void *)XtOffsetOf(fcgi_dir_config, authenticator_options), ACCESS_CONF,
2882 "Set to 'off' to allow authentication to be passed along to lower modules upon failure"),
2884 AP_INIT_TAKE12("FastCgiAuthorizer", fcgi_config_new_auth_server,
2885 (void *)FCGI_AUTH_TYPE_AUTHORIZER, ACCESS_CONF,
2886 "a fastcgi-script path (absolute or relative to ServerRoot) followed by an optional -compat"),
2887 AP_INIT_FLAG("FastCgiAuthorizerAuthoritative", fcgi_config_set_authoritative_slot,
2888 (void *)XtOffsetOf(fcgi_dir_config, authorizer_options), ACCESS_CONF,
2889 "Set to 'off' to allow authorization to be passed along to lower modules upon failure"),
2891 AP_INIT_TAKE12("FastCgiAccessChecker", fcgi_config_new_auth_server,
2892 (void *)FCGI_AUTH_TYPE_ACCESS_CHECKER, ACCESS_CONF,
2893 "a fastcgi-script path (absolute or relative to ServerRoot) followed by an optional -compat"),
2894 AP_INIT_FLAG("FastCgiAccessCheckerAuthoritative", fcgi_config_set_authoritative_slot,
2895 (void *)XtOffsetOf(fcgi_dir_config, access_checker_options), ACCESS_CONF,
2896 "Set to 'off' to allow access control to be passed along to lower modules upon failure"),
2897 { NULL }
2900 #ifdef APACHE2
2902 static void register_hooks(apr_pool_t * p)
2904 // ap_hook_pre_config(x_pre_config, NULL, NULL, APR_HOOK_MIDDLE);
2905 ap_hook_post_config(init_module, NULL, NULL, APR_HOOK_MIDDLE);
2906 ap_hook_child_init(fcgi_child_init, NULL, NULL, APR_HOOK_MIDDLE);
2907 ap_hook_handler(content_handler, NULL, NULL, APR_HOOK_MIDDLE);
2908 ap_hook_check_user_id(check_user_authentication, NULL, NULL, APR_HOOK_MIDDLE);
2909 ap_hook_access_checker(check_access, NULL, NULL, APR_HOOK_MIDDLE);
2910 ap_hook_auth_checker(check_user_authorization, NULL, NULL, APR_HOOK_MIDDLE);
2911 ap_hook_fixups(fixups, NULL, NULL, APR_HOOK_MIDDLE);
2914 module AP_MODULE_DECLARE_DATA fastcgi_module =
2916 STANDARD20_MODULE_STUFF,
2917 fcgi_config_create_dir_config, /* per-directory config creator */
2918 NULL, /* dir config merger */
2919 NULL, /* server config creator */
2920 NULL, /* server config merger */
2921 fastcgi_cmds, /* command table */
2922 register_hooks, /* set up other request processing hooks */
2925 #else /* !APACHE2 */
2927 handler_rec fastcgi_handlers[] = {
2928 { FCGI_MAGIC_TYPE, content_handler },
2929 { FASTCGI_HANDLER_NAME, content_handler },
2930 { NULL }
2933 module MODULE_VAR_EXPORT fastcgi_module = {
2934 STANDARD_MODULE_STUFF,
2935 init_module, /* initializer */
2936 fcgi_config_create_dir_config, /* per-dir config creator */
2937 NULL, /* per-dir config merger (default: override) */
2938 NULL, /* per-server config creator */
2939 NULL, /* per-server config merger (default: override) */
2940 fastcgi_cmds, /* command table */
2941 fastcgi_handlers, /* [9] content handlers */
2942 NULL, /* [2] URI-to-filename translation */
2943 check_user_authentication, /* [5] authenticate user_id */
2944 check_user_authorization, /* [6] authorize user_id */
2945 check_access, /* [4] check access (based on src & http headers) */
2946 NULL, /* [7] check/set MIME type */
2947 fixups, /* [8] fixups */
2948 NULL, /* [10] logger */
2949 NULL, /* [3] header-parser */
2950 fcgi_child_init, /* process initialization */
2951 #ifdef WIN32
2952 fcgi_child_exit, /* process exit/cleanup */
2953 #else
2954 NULL,
2955 #endif
2956 NULL /* [1] post read-request handling */
2959 #endif /* !APACHE2 */