Remove a superfluous "break" that caused a compile warning on IRIX
[mod_fastcgi.git] / mod_fastcgi.c
blob949b2f20a1d6fa4cde5bd25272ae59e69df88fdf
1 /*
2 * mod_fastcgi.c --
4 * Apache server module for FastCGI.
6 * $Id: mod_fastcgi.c,v 1.154 2003/10/30 00:59:21 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 default:
676 flag = 0;
677 break;
679 p++;
682 /* Return (to be called later when we have more data)
683 * if we don't have an entire header. */
684 if (flag < 2)
685 return NULL;
688 * Parse all the headers.
690 fr->parseHeader = SCAN_CGI_FINISHED;
691 hasContentType = hasStatus = hasLocation = FALSE;
692 next = (char *)fr->header->elts;
693 for(;;) {
694 next = get_header_line(name = next, TRUE);
695 if (*name == '\0') {
696 break;
698 if ((p = strchr(name, ':')) == NULL) {
699 goto BadHeader;
701 value = p + 1;
702 while (p != name && isspace((unsigned char)*(p - 1))) {
703 p--;
705 if (p == name) {
706 goto BadHeader;
708 *p = '\0';
709 if (strpbrk(name, " \t") != NULL) {
710 *p = ' ';
711 goto BadHeader;
713 while (isspace((unsigned char)*value)) {
714 value++;
717 if (strcasecmp(name, "Status") == 0) {
718 int statusValue = strtol(value, NULL, 10);
720 if (hasStatus) {
721 goto DuplicateNotAllowed;
723 if (statusValue < 0) {
724 fr->parseHeader = SCAN_CGI_BAD_HEADER;
725 return ap_psprintf(r->pool, "invalid Status '%s'", value);
727 hasStatus = TRUE;
728 r->status = statusValue;
729 r->status_line = ap_pstrdup(r->pool, value);
730 continue;
733 if (fr->role == FCGI_RESPONDER) {
734 if (strcasecmp(name, "Content-type") == 0) {
735 if (hasContentType) {
736 goto DuplicateNotAllowed;
738 hasContentType = TRUE;
739 r->content_type = ap_pstrdup(r->pool, value);
740 continue;
743 if (strcasecmp(name, "Location") == 0) {
744 if (hasLocation) {
745 goto DuplicateNotAllowed;
747 hasLocation = TRUE;
748 ap_table_set(r->headers_out, "Location", value);
749 continue;
752 /* If the script wants them merged, it can do it */
753 ap_table_add(r->err_headers_out, name, value);
754 continue;
756 else {
757 ap_table_add(fr->authHeaders, name, value);
761 if (fr->role != FCGI_RESPONDER)
762 return NULL;
765 * Who responds, this handler or Apache?
767 if (hasLocation) {
768 const char *location = ap_table_get(r->headers_out, "Location");
770 * Based on internal redirect handling in mod_cgi.c...
772 * If a script wants to produce its own Redirect
773 * body, it now has to explicitly *say* "Status: 302"
775 if (r->status == 200) {
776 if(location[0] == '/') {
778 * Location is an relative path. This handler will
779 * consume all script output, then have Apache perform an
780 * internal redirect.
782 fr->parseHeader = SCAN_CGI_INT_REDIRECT;
783 return NULL;
784 } else {
786 * Location is an absolute URL. If the script didn't
787 * produce a Content-type header, this handler will
788 * consume all script output and then have Apache generate
789 * its standard redirect response. Otherwise this handler
790 * will transmit the script's response.
792 fr->parseHeader = SCAN_CGI_SRV_REDIRECT;
793 return NULL;
798 * We're responding. Send headers, buffer excess script output.
800 ap_send_http_header(r);
802 /* We need to reinstate our timeout, send_http_header() kill()s it */
803 ap_hard_timeout("FastCGI request processing", r);
805 if (r->header_only) {
806 /* we've got all we want from the server */
807 close_connection_to_fs(fr);
808 fr->exitStatusSet = 1;
809 fcgi_buf_reset(fr->clientOutputBuffer);
810 fcgi_buf_reset(fr->serverOutputBuffer);
811 return NULL;
814 len = fr->header->nelts - (next - fr->header->elts);
816 ASSERT(len >= 0);
817 ASSERT(BufferLength(fr->clientOutputBuffer) == 0);
819 if (BufferFree(fr->clientOutputBuffer) < len) {
820 fr->clientOutputBuffer = fcgi_buf_new(r->pool, len);
823 ASSERT(BufferFree(fr->clientOutputBuffer) >= len);
825 if (len > 0) {
826 int sent;
827 sent = fcgi_buf_add_block(fr->clientOutputBuffer, next, len);
828 ASSERT(sent == len);
831 return NULL;
833 BadHeader:
834 /* Log first line of a multi-line header */
835 if ((p = strpbrk(name, "\r\n")) != NULL)
836 *p = '\0';
837 fr->parseHeader = SCAN_CGI_BAD_HEADER;
838 return ap_psprintf(r->pool, "malformed header '%s'", name);
840 DuplicateNotAllowed:
841 fr->parseHeader = SCAN_CGI_BAD_HEADER;
842 return ap_psprintf(r->pool, "duplicate header '%s'", name);
846 * Read from the client filling both the FastCGI server buffer and the
847 * client buffer with the hopes of buffering the client data before
848 * making the connect() to the FastCGI server. This prevents slow
849 * clients from keeping the FastCGI server in processing longer than is
850 * necessary.
852 static int read_from_client_n_queue(fcgi_request *fr)
854 char *end;
855 int count;
856 long int countRead;
858 while (BufferFree(fr->clientInputBuffer) > 0 || BufferFree(fr->serverOutputBuffer) > 0) {
859 fcgi_protocol_queue_client_buffer(fr);
861 if (fr->expectingClientContent <= 0)
862 return OK;
864 fcgi_buf_get_free_block_info(fr->clientInputBuffer, &end, &count);
865 if (count == 0)
866 return OK;
868 if ((countRead = ap_get_client_block(fr->r, end, count)) < 0)
870 /* set the header scan state to done to prevent logging an error
871 * - hokey approach - probably should be using a unique value */
872 fr->parseHeader = SCAN_CGI_FINISHED;
873 return -1;
876 if (countRead == 0) {
877 fr->expectingClientContent = 0;
879 else {
880 fcgi_buf_add_update(fr->clientInputBuffer, countRead);
881 ap_reset_timeout(fr->r);
884 return OK;
887 static int write_to_client(fcgi_request *fr)
889 char *begin;
890 int count;
891 int rv;
892 #ifdef APACHE2
893 apr_bucket * bkt;
894 apr_bucket_brigade * bde;
895 apr_bucket_alloc_t * const bkt_alloc = fr->r->connection->bucket_alloc;
896 #endif
898 fcgi_buf_get_block_info(fr->clientOutputBuffer, &begin, &count);
899 if (count == 0)
900 return OK;
902 /* If fewer than count bytes are written, an error occured.
903 * ap_bwrite() typically forces a flushed write to the client, this
904 * effectively results in a block (and short packets) - it should
905 * be fixed, but I didn't win much support for the idea on new-httpd.
906 * So, without patching Apache, the best way to deal with this is
907 * to size the fcgi_bufs to hold all of the script output (within
908 * reason) so the script can be released from having to wait around
909 * for the transmission to the client to complete. */
911 #ifdef APACHE2
913 bde = apr_brigade_create(fr->r->pool, bkt_alloc);
914 bkt = apr_bucket_transient_create(begin, count, bkt_alloc);
915 APR_BRIGADE_INSERT_TAIL(bde, bkt);
917 if (fr->fs ? fr->fs->flush : dynamicFlush)
919 bkt = apr_bucket_flush_create(bkt_alloc);
920 APR_BRIGADE_INSERT_TAIL(bde, bkt);
923 rv = ap_pass_brigade(fr->r->output_filters, bde);
925 #elif defined(RUSSIAN_APACHE)
927 rv = (ap_rwrite(begin, count, fr->r) != count);
929 #else
931 rv = (ap_bwrite(fr->r->connection->client, begin, count) != count);
933 #endif
935 if (rv)
937 ap_log_rerror(FCGI_LOG_INFO_NOERRNO, fr->r,
938 "FastCGI: client stopped connection before send body completed");
939 return -1;
942 #ifndef APACHE2
944 ap_reset_timeout(fr->r);
946 /* Don't bother with a wrapped buffer, limiting exposure to slow
947 * clients. The BUFF routines don't allow a writev from above,
948 * and don't always memcpy to minimize small write()s, this should
949 * be fixed, but I didn't win much support for the idea on
950 * new-httpd - I'll have to _prove_ its a problem first.. */
952 /* The default behaviour used to be to flush with every write, but this
953 * can tie up the FastCGI server longer than is necessary so its an option now */
955 if (fr->fs ? fr->fs->flush : dynamicFlush)
957 #ifdef RUSSIAN_APACHE
958 rv = ap_rflush(fr->r);
959 #else
960 rv = ap_bflush(fr->r->connection->client);
961 #endif
963 if (rv)
965 ap_log_rerror(FCGI_LOG_INFO_NOERRNO, fr->r,
966 "FastCGI: client stopped connection before send body completed");
967 return -1;
970 ap_reset_timeout(fr->r);
973 #endif /* !APACHE2 */
975 fcgi_buf_toss(fr->clientOutputBuffer, count);
976 return OK;
979 static void
980 get_request_identity(request_rec * const r,
981 uid_t * const uid,
982 gid_t * const gid)
984 #if defined(WIN32)
985 *uid = (uid_t) 0;
986 *gid = (gid_t) 0;
987 #elif defined(APACHE2)
988 ap_unix_identity_t * identity = ap_run_get_suexec_identity(r);
989 if (identity)
991 *uid = identity->uid;
992 *gid = identity->gid;
994 else
996 *uid = 0;
997 *gid = 0;
999 #else
1000 *uid = r->server->server_uid;
1001 *gid = r->server->server_gid;
1002 #endif
1005 /*******************************************************************************
1006 * Determine the user and group the wrapper should be called with.
1007 * Based on code in Apache's create_argv_cmd() (util_script.c).
1009 static void set_uid_n_gid(request_rec *r, const char **user, const char **group)
1011 if (fcgi_wrapper == NULL) {
1012 *user = "-";
1013 *group = "-";
1014 return;
1017 if (strncmp("/~", r->uri, 2) == 0) {
1018 /* its a user dir uri, just send the ~user, and leave it to the PM */
1019 char *end = strchr(r->uri + 2, '/');
1021 if (end)
1022 *user = memcpy(ap_pcalloc(r->pool, end - r->uri), r->uri + 1, end - r->uri - 1);
1023 else
1024 *user = ap_pstrdup(r->pool, r->uri + 1);
1025 *group = "-";
1027 else {
1028 uid_t uid;
1029 gid_t gid;
1031 get_request_identity(r, &uid, &gid);
1033 *user = ap_psprintf(r->pool, "%ld", (long) uid);
1034 *group = ap_psprintf(r->pool, "%ld", (long) gid);
1038 static void send_request_complete(fcgi_request *fr)
1040 if (fr->completeTime.tv_sec)
1042 struct timeval qtime, rtime;
1044 timersub(&fr->queueTime, &fr->startTime, &qtime);
1045 timersub(&fr->completeTime, &fr->queueTime, &rtime);
1047 send_to_pm(FCGI_REQUEST_COMPLETE_JOB, fr->fs_path,
1048 fr->user, fr->group,
1049 qtime.tv_sec * 1000000 + qtime.tv_usec,
1050 rtime.tv_sec * 1000000 + rtime.tv_usec);
1055 /*******************************************************************************
1056 * Connect to the FastCGI server.
1058 static int open_connection_to_fs(fcgi_request *fr)
1060 struct timeval tval;
1061 fd_set write_fds, read_fds;
1062 int status;
1063 request_rec * const r = fr->r;
1064 pool * const rp = r->pool;
1065 const char *socket_path = NULL;
1066 struct sockaddr *socket_addr = NULL;
1067 int socket_addr_len = 0;
1068 #ifndef WIN32
1069 const char *err = NULL;
1070 #endif
1072 /* Create the connection point */
1073 if (fr->dynamic)
1075 socket_path = fcgi_util_socket_hash_filename(rp, fr->fs_path, fr->user, fr->group);
1076 socket_path = fcgi_util_socket_make_path_absolute(rp, socket_path, 1);
1078 #ifndef WIN32
1079 err = fcgi_util_socket_make_domain_addr(rp, (struct sockaddr_un **)&socket_addr,
1080 &socket_addr_len, socket_path);
1081 if (err) {
1082 ap_log_rerror(FCGI_LOG_ERR, r,
1083 "FastCGI: failed to connect to (dynamic) server \"%s\": "
1084 "%s", fr->fs_path, err);
1085 return FCGI_FAILED;
1087 #endif
1089 else
1091 #ifdef WIN32
1092 if (fr->fs->dest_addr != NULL) {
1093 socket_addr = fr->fs->dest_addr;
1095 else if (fr->fs->socket_addr) {
1096 socket_addr = fr->fs->socket_addr;
1098 else {
1099 socket_path = fr->fs->socket_path;
1101 #else
1102 socket_addr = fr->fs->socket_addr;
1103 #endif
1104 socket_addr_len = fr->fs->socket_addr_len;
1107 if (fr->dynamic)
1109 #ifdef WIN32
1110 if (fr->fs && fr->fs->restartTime)
1111 #else
1112 struct stat sock_stat;
1114 if (stat(socket_path, &sock_stat) == 0)
1115 #endif
1117 // It exists
1118 if (dynamicAutoUpdate)
1120 struct stat app_stat;
1122 /* TODO: follow sym links */
1124 if (stat(fr->fs_path, &app_stat) == 0)
1126 #ifdef WIN32
1127 if (fr->fs->startTime < app_stat.st_mtime)
1128 #else
1129 if (sock_stat.st_mtime < app_stat.st_mtime)
1130 #endif
1132 #ifndef WIN32
1133 struct timeval tv = {1, 0};
1134 #endif
1136 * There's a newer one, request a restart.
1138 send_to_pm(FCGI_SERVER_RESTART_JOB, fr->fs_path, fr->user, fr->group, 0, 0);
1140 #ifdef WIN32
1141 Sleep(1000);
1142 #else
1143 /* Avoid sleep/alarm interactions */
1144 ap_select(0, NULL, NULL, NULL, &tv);
1145 #endif
1150 else
1152 int i;
1154 send_to_pm(FCGI_SERVER_START_JOB, fr->fs_path, fr->user, fr->group, 0, 0);
1156 /* wait until it looks like its running - this shouldn't take
1157 * very long at all - the exception is when the sockets are
1158 * removed out from under a running application - the loop
1159 * limit addresses this (preventing spinning) */
1161 for (i = 10; i > 0; i--)
1163 #ifdef WIN32
1164 Sleep(500);
1166 fr->fs = fcgi_util_fs_get_by_id(fr->fs_path, 0, 0);
1168 if (fr->fs && fr->fs->restartTime)
1169 #else
1170 struct timeval tv = {0, 500000};
1172 /* Avoid sleep/alarm interactions */
1173 ap_select(0, NULL, NULL, NULL, &tv);
1175 if (stat(socket_path, &sock_stat) == 0)
1176 #endif
1178 break;
1182 if (i <= 0)
1184 ap_log_rerror(FCGI_LOG_ALERT, r,
1185 "FastCGI: failed to connect to (dynamic) server \"%s\": "
1186 "something is seriously wrong, any chance the "
1187 "socket/named_pipe directory was removed?, see the "
1188 "FastCgiIpcDir directive", fr->fs_path);
1189 return FCGI_FAILED;
1194 #ifdef WIN32
1195 if (socket_path)
1197 BOOL ready;
1198 DWORD connect_time;
1199 int rv;
1200 HANDLE wait_npipe_mutex;
1201 DWORD interval;
1202 DWORD max_connect_time = FCGI_NAMED_PIPE_CONNECT_TIMEOUT;
1204 fr->using_npipe_io = TRUE;
1206 if (fr->dynamic)
1208 interval = dynamicPleaseStartDelay * 1000;
1210 if (dynamicAppConnectTimeout) {
1211 max_connect_time = dynamicAppConnectTimeout;
1214 else
1216 interval = FCGI_NAMED_PIPE_CONNECT_TIMEOUT * 1000;
1218 if (fr->fs->appConnectTimeout) {
1219 max_connect_time = fr->fs->appConnectTimeout;
1223 fcgi_util_ticks(&fr->startTime);
1226 // xxx this handle should live somewhere (see CloseHandle()s below too)
1227 char * wait_npipe_mutex_name, * cp;
1228 wait_npipe_mutex_name = cp = ap_pstrdup(rp, socket_path);
1229 while ((cp = strchr(cp, '\\'))) *cp = '/';
1231 wait_npipe_mutex = CreateMutex(NULL, FALSE, wait_npipe_mutex_name);
1234 if (wait_npipe_mutex == NULL)
1236 ap_log_rerror(FCGI_LOG_ERR, r,
1237 "FastCGI: failed to connect to server \"%s\": "
1238 "can't create the WaitNamedPipe mutex", fr->fs_path);
1239 return FCGI_FAILED;
1242 SetLastError(ERROR_SUCCESS);
1244 rv = WaitForSingleObject(wait_npipe_mutex, max_connect_time * 1000);
1246 if (rv == WAIT_TIMEOUT || rv == WAIT_FAILED)
1248 if (fr->dynamic)
1250 send_to_pm(FCGI_REQUEST_TIMEOUT_JOB, fr->fs_path, fr->user, fr->group, 0, 0);
1252 ap_log_rerror(FCGI_LOG_ERR_NOERRNO, r,
1253 "FastCGI: failed to connect to server \"%s\": "
1254 "wait for a npipe instance failed", fr->fs_path);
1255 FCGIDBG3("interval=%d, max_connect_time=%d", interval, max_connect_time);
1256 CloseHandle(wait_npipe_mutex);
1257 return FCGI_FAILED;
1260 fcgi_util_ticks(&fr->queueTime);
1262 connect_time = fr->queueTime.tv_sec - fr->startTime.tv_sec;
1264 if (fr->dynamic)
1266 if (connect_time >= interval)
1268 send_to_pm(FCGI_REQUEST_TIMEOUT_JOB, fr->fs_path, fr->user, fr->group, 0, 0);
1269 FCGIDBG4("connect_time=%d, interval=%d, max_connect_time=%d", connect_time, interval, max_connect_time);
1271 if (max_connect_time - connect_time < interval)
1273 interval = max_connect_time - connect_time;
1276 else
1278 interval -= connect_time * 1000;
1281 for (;;)
1283 ready = WaitNamedPipe(socket_path, interval);
1285 if (ready)
1287 fr->fd = (SOCKET) CreateFile(socket_path,
1288 GENERIC_READ | GENERIC_WRITE,
1289 FILE_SHARE_READ | FILE_SHARE_WRITE,
1290 NULL, // no security attributes
1291 OPEN_EXISTING, // opens existing pipe
1292 FILE_FLAG_OVERLAPPED,
1293 NULL); // no template file
1295 if (fr->fd != (SOCKET) INVALID_HANDLE_VALUE)
1297 ReleaseMutex(wait_npipe_mutex);
1298 CloseHandle(wait_npipe_mutex);
1299 fcgi_util_ticks(&fr->queueTime);
1300 FCGIDBG2("got npipe connect: %s", fr->fs_path);
1301 return FCGI_OK;
1304 if (GetLastError() != ERROR_PIPE_BUSY
1305 && GetLastError() != ERROR_FILE_NOT_FOUND)
1307 ap_log_rerror(FCGI_LOG_ERR, r,
1308 "FastCGI: failed to connect to server \"%s\": "
1309 "CreateFile() failed", fr->fs_path);
1310 break;
1313 FCGIDBG2("missed npipe connect: %s", fr->fs_path);
1316 if (fr->dynamic)
1318 send_to_pm(FCGI_REQUEST_TIMEOUT_JOB, fr->fs_path, fr->user, fr->group, 0, 0);
1321 fcgi_util_ticks(&fr->queueTime);
1323 connect_time = fr->queueTime.tv_sec - fr->startTime.tv_sec;
1325 FCGIDBG5("interval=%d, max_connect_time=%d, connect_time=%d, ready=%d", interval, max_connect_time, connect_time, ready);
1327 if (connect_time >= max_connect_time)
1329 ap_log_rerror(FCGI_LOG_ERR, r,
1330 "FastCGI: failed to connect to server \"%s\": "
1331 "CreateFile()/WaitNamedPipe() timed out", fr->fs_path);
1332 break;
1336 ReleaseMutex(wait_npipe_mutex);
1337 CloseHandle(wait_npipe_mutex);
1338 fr->fd = INVALID_SOCKET;
1339 return FCGI_FAILED;
1342 #endif
1344 /* Create the socket */
1345 fr->fd = socket(socket_addr->sa_family, SOCK_STREAM, 0);
1347 #ifdef WIN32
1348 if (fr->fd == INVALID_SOCKET) {
1349 errno = WSAGetLastError(); // Not sure this is going to work as expected
1350 #else
1351 if (fr->fd < 0) {
1352 #endif
1353 ap_log_rerror(FCGI_LOG_ERR_ERRNO, r,
1354 "FastCGI: failed to connect to server \"%s\": "
1355 "socket() failed", fr->fs_path);
1356 return FCGI_FAILED;
1359 #ifndef WIN32
1360 if (fr->fd >= FD_SETSIZE) {
1361 ap_log_rerror(FCGI_LOG_ERR, r,
1362 "FastCGI: failed to connect to server \"%s\": "
1363 "socket file descriptor (%u) is larger than "
1364 "FD_SETSIZE (%u), you probably need to rebuild Apache with a "
1365 "larger FD_SETSIZE", fr->fs_path, fr->fd, FD_SETSIZE);
1366 return FCGI_FAILED;
1368 #endif
1370 /* If appConnectTimeout is non-zero, setup do a non-blocking connect */
1371 if ((fr->dynamic && dynamicAppConnectTimeout) || (!fr->dynamic && fr->fs->appConnectTimeout)) {
1372 set_nonblocking(fr, TRUE);
1375 if (fr->dynamic) {
1376 fcgi_util_ticks(&fr->startTime);
1379 /* Connect */
1380 if (connect(fr->fd, (struct sockaddr *)socket_addr, socket_addr_len) == 0)
1381 goto ConnectionComplete;
1383 #ifdef WIN32
1385 errno = WSAGetLastError();
1386 if (errno != WSAEWOULDBLOCK) {
1387 ap_log_rerror(FCGI_LOG_ERR_ERRNO, r,
1388 "FastCGI: failed to connect to server \"%s\": "
1389 "connect() failed", fr->fs_path);
1390 return FCGI_FAILED;
1393 #else
1395 /* ECONNREFUSED means the listen queue is full (or there isn't one).
1396 * With dynamic I can at least make sure the PM knows this is occuring */
1397 if (fr->dynamic && errno == ECONNREFUSED) {
1398 /* @@@ This might be better as some other "kind" of message */
1399 send_to_pm(FCGI_REQUEST_TIMEOUT_JOB, fr->fs_path, fr->user, fr->group, 0, 0);
1401 errno = ECONNREFUSED;
1404 if (errno != EINPROGRESS) {
1405 ap_log_rerror(FCGI_LOG_ERR, r,
1406 "FastCGI: failed to connect to server \"%s\": "
1407 "connect() failed", fr->fs_path);
1408 return FCGI_FAILED;
1411 #endif
1413 /* The connect() is non-blocking */
1415 errno = 0;
1417 if (fr->dynamic) {
1418 do {
1419 FD_ZERO(&write_fds);
1420 FD_SET(fr->fd, &write_fds);
1421 read_fds = write_fds;
1422 tval.tv_sec = dynamicPleaseStartDelay;
1423 tval.tv_usec = 0;
1425 status = ap_select((fr->fd+1), &read_fds, &write_fds, NULL, &tval);
1426 if (status < 0)
1427 break;
1429 fcgi_util_ticks(&fr->queueTime);
1431 if (status > 0)
1432 break;
1434 /* select() timed out */
1435 send_to_pm(FCGI_REQUEST_TIMEOUT_JOB, fr->fs_path, fr->user, fr->group, 0, 0);
1436 } while ((fr->queueTime.tv_sec - fr->startTime.tv_sec) < (int)dynamicAppConnectTimeout);
1438 /* XXX These can be moved down when dynamic vars live is a struct */
1439 if (status == 0) {
1440 ap_log_rerror(FCGI_LOG_ERR_NOERRNO, r,
1441 "FastCGI: failed to connect to server \"%s\": "
1442 "connect() timed out (appConnTimeout=%dsec)",
1443 fr->fs_path, dynamicAppConnectTimeout);
1444 return FCGI_FAILED;
1446 } /* dynamic */
1447 else {
1448 tval.tv_sec = fr->fs->appConnectTimeout;
1449 tval.tv_usec = 0;
1450 FD_ZERO(&write_fds);
1451 FD_SET(fr->fd, &write_fds);
1452 read_fds = write_fds;
1454 status = ap_select((fr->fd+1), &read_fds, &write_fds, NULL, &tval);
1456 if (status == 0) {
1457 ap_log_rerror(FCGI_LOG_ERR_NOERRNO, r,
1458 "FastCGI: failed to connect to server \"%s\": "
1459 "connect() timed out (appConnTimeout=%dsec)",
1460 fr->fs_path, dynamicAppConnectTimeout);
1461 return FCGI_FAILED;
1463 } /* !dynamic */
1465 if (status < 0) {
1466 #ifdef WIN32
1467 errno = WSAGetLastError();
1468 #endif
1469 ap_log_rerror(FCGI_LOG_ERR_ERRNO, r,
1470 "FastCGI: failed to connect to server \"%s\": "
1471 "select() failed", fr->fs_path);
1472 return FCGI_FAILED;
1475 if (FD_ISSET(fr->fd, &write_fds) || FD_ISSET(fr->fd, &read_fds)) {
1476 int error = 0;
1477 NET_SIZE_T len = sizeof(error);
1479 if (getsockopt(fr->fd, SOL_SOCKET, SO_ERROR, (char *)&error, &len) < 0) {
1480 /* Solaris pending error */
1481 #ifdef WIN32
1482 errno = WSAGetLastError();
1483 #endif
1484 ap_log_rerror(FCGI_LOG_ERR_ERRNO, r,
1485 "FastCGI: failed to connect to server \"%s\": "
1486 "select() failed (Solaris pending error)", fr->fs_path);
1487 return FCGI_FAILED;
1490 if (error != 0) {
1491 /* Berkeley-derived pending error */
1492 errno = error;
1493 ap_log_rerror(FCGI_LOG_ERR_ERRNO, r,
1494 "FastCGI: failed to connect to server \"%s\": "
1495 "select() failed (pending error)", fr->fs_path);
1496 return FCGI_FAILED;
1499 else {
1500 #ifdef WIN32
1501 errno = WSAGetLastError();
1502 #endif
1503 ap_log_rerror(FCGI_LOG_ERR_ERRNO, r,
1504 "FastCGI: failed to connect to server \"%s\": "
1505 "select() error - THIS CAN'T HAPPEN!", fr->fs_path);
1506 return FCGI_FAILED;
1509 ConnectionComplete:
1510 /* Return to blocking mode if it was set up */
1511 if ((fr->dynamic && dynamicAppConnectTimeout) || (!fr->dynamic && fr->fs->appConnectTimeout)) {
1512 set_nonblocking(fr, FALSE);
1515 #ifdef TCP_NODELAY
1516 if (socket_addr->sa_family == AF_INET) {
1517 /* We shouldn't be sending small packets and there's no application
1518 * level ack of the data we send, so disable Nagle */
1519 int set = 1;
1520 setsockopt(fr->fd, IPPROTO_TCP, TCP_NODELAY, (char *)&set, sizeof(set));
1522 #endif
1524 return FCGI_OK;
1527 static void sink_client_data(fcgi_request *fr)
1529 char *base;
1530 int size;
1532 fcgi_buf_reset(fr->clientInputBuffer);
1533 fcgi_buf_get_free_block_info(fr->clientInputBuffer, &base, &size);
1534 while (ap_get_client_block(fr->r, base, size) > 0);
1537 static apcb_t cleanup(void *data)
1539 fcgi_request * const fr = (fcgi_request *) data;
1541 if (fr == NULL) return APCB_OK;
1543 /* its more than likely already run, but... */
1544 close_connection_to_fs(fr);
1546 send_request_complete(fr);
1548 if (fr->fs_stderr_len) {
1549 ap_log_rerror(FCGI_LOG_ERR_NOERRNO, fr->r,
1550 "FastCGI: server \"%s\" stderr: %s", fr->fs_path, fr->fs_stderr);
1553 return APCB_OK;
1556 #ifdef WIN32
1557 static int npipe_io(fcgi_request * const fr)
1559 request_rec * const r = fr->r;
1560 enum
1562 STATE_ENV_SEND,
1563 STATE_CLIENT_RECV,
1564 STATE_SERVER_SEND,
1565 STATE_SERVER_RECV,
1566 STATE_CLIENT_SEND,
1567 STATE_ERROR
1569 state = STATE_ENV_SEND;
1570 env_status env_status;
1571 int client_recv;
1572 int dynamic_first_recv = fr->dynamic;
1573 int idle_timeout = fr->dynamic ? dynamic_idle_timeout : fr->fs->idle_timeout;
1574 int send_pending = 0;
1575 int recv_pending = 0;
1576 int client_send = 0;
1577 int rv;
1578 OVERLAPPED rov = { 0 };
1579 OVERLAPPED sov = { 0 };
1580 HANDLE events[2];
1581 struct timeval timeout;
1582 struct timeval dynamic_last_io_time = {0, 0};
1583 int did_io = 1;
1584 pool * const rp = r->pool;
1585 int is_connected = 0;
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 (! is_connected)
1655 if (open_connection_to_fs(fr) != FCGI_OK)
1657 ap_kill_timeout(r);
1658 return HTTP_INTERNAL_SERVER_ERROR;
1661 is_connected = 1;
1664 if (! send_pending && BufferLength(fr->serverOutputBuffer))
1666 Buffer * b = fr->serverOutputBuffer;
1667 DWORD sent, len;
1669 len = min(b->length, b->data + b->size - b->begin);
1671 if (WriteFile((HANDLE) fr->fd, b->begin, len, &sent, &sov))
1673 /* sov.hEvent is set */
1674 fcgi_buf_removed(b, sent);
1676 else if (GetLastError() == ERROR_IO_PENDING)
1678 send_pending = 1;
1680 else
1682 ap_log_rerror(FCGI_LOG_ERR, r, "FastCGI: comm with server "
1683 "\"%s\" aborted: WriteFile() failed", fr->fs_path);
1684 state = STATE_ERROR;
1685 break;
1689 /* fall through */
1691 case STATE_SERVER_RECV:
1694 * Only get more data when the serverInputBuffer is empty.
1695 * Otherwise we may already have the END_REQUEST buffered
1696 * (but not processed) and a read on a closed named pipe
1697 * results in an error that is normally abnormal.
1699 if (! recv_pending && BufferLength(fr->serverInputBuffer) == 0)
1701 Buffer * b = fr->serverInputBuffer;
1702 DWORD rcvd, len;
1704 len = min(b->size - b->length, b->data + b->size - b->end);
1706 if (ReadFile((HANDLE) fr->fd, b->end, len, &rcvd, &rov))
1708 fcgi_buf_added(b, rcvd);
1709 recv_count += rcvd;
1710 ResetEvent(rov.hEvent);
1711 if (dynamic_first_recv)
1713 dynamic_first_recv = 0;
1716 else if (GetLastError() == ERROR_IO_PENDING)
1718 recv_pending = 1;
1720 else if (GetLastError() == ERROR_HANDLE_EOF)
1722 fr->keepReadingFromFcgiApp = FALSE;
1723 state = STATE_CLIENT_SEND;
1724 ResetEvent(rov.hEvent);
1725 break;
1727 else if (GetLastError() == ERROR_NO_DATA)
1729 break;
1731 else
1733 ap_log_rerror(FCGI_LOG_ERR, r, "FastCGI: comm with server "
1734 "\"%s\" aborted: ReadFile() failed", fr->fs_path);
1735 state = STATE_ERROR;
1736 break;
1740 /* fall through */
1742 case STATE_CLIENT_SEND:
1744 if (client_send || ! BufferFree(fr->clientOutputBuffer))
1746 if (write_to_client(fr))
1748 state = STATE_ERROR;
1749 break;
1752 client_send = 0;
1755 break;
1757 default:
1759 ASSERT(0);
1762 if (state == STATE_ERROR)
1764 break;
1767 /* setup the io timeout */
1769 if (BufferLength(fr->clientOutputBuffer))
1771 /* don't let client data sit too long, it might be a push */
1772 timeout.tv_sec = 0;
1773 timeout.tv_usec = 100000;
1775 else if (dynamic_first_recv)
1777 int delay;
1778 struct timeval qwait;
1780 fcgi_util_ticks(&fr->queueTime);
1782 if (did_io)
1784 /* a send() succeeded last pass */
1785 dynamic_last_io_time = fr->queueTime;
1787 else
1789 /* timed out last pass */
1790 struct timeval idle_time;
1792 timersub(&fr->queueTime, &dynamic_last_io_time, &idle_time);
1794 if (idle_time.tv_sec > idle_timeout)
1796 send_to_pm(FCGI_REQUEST_TIMEOUT_JOB, fr->fs_path, fr->user, fr->group, 0, 0);
1797 ap_log_rerror(FCGI_LOG_ERR_NOERRNO, r, "FastCGI: comm "
1798 "with (dynamic) server \"%s\" aborted: (first read) "
1799 "idle timeout (%d sec)", fr->fs_path, idle_timeout);
1800 state = STATE_ERROR;
1801 break;
1805 timersub(&fr->queueTime, &fr->startTime, &qwait);
1807 delay = dynamic_first_recv * dynamicPleaseStartDelay;
1809 if (qwait.tv_sec < delay)
1811 timeout.tv_sec = delay;
1812 timeout.tv_usec = 100000; /* fudge for select() slop */
1813 timersub(&timeout, &qwait, &timeout);
1815 else
1817 /* Killed time somewhere.. client read? */
1818 send_to_pm(FCGI_REQUEST_TIMEOUT_JOB, fr->fs_path, fr->user, fr->group, 0, 0);
1819 dynamic_first_recv = qwait.tv_sec / dynamicPleaseStartDelay + 1;
1820 timeout.tv_sec = dynamic_first_recv * dynamicPleaseStartDelay;
1821 timeout.tv_usec = 100000; /* fudge for select() slop */
1822 timersub(&timeout, &qwait, &timeout);
1825 else
1827 timeout.tv_sec = idle_timeout;
1828 timeout.tv_usec = 0;
1831 /* require a pended recv otherwise the app can deadlock */
1832 if (recv_pending)
1834 msec_timeout = timeout.tv_sec * 1000 + timeout.tv_usec / 1000;
1836 rv = WaitForMultipleObjects(2, events, FALSE, msec_timeout);
1838 if (rv == WAIT_TIMEOUT)
1840 did_io = 0;
1842 if (BufferLength(fr->clientOutputBuffer))
1844 client_send = 1;
1846 else if (dynamic_first_recv)
1848 struct timeval qwait;
1850 fcgi_util_ticks(&fr->queueTime);
1851 timersub(&fr->queueTime, &fr->startTime, &qwait);
1853 send_to_pm(FCGI_REQUEST_TIMEOUT_JOB, fr->fs_path, fr->user, fr->group, 0, 0);
1855 dynamic_first_recv = qwait.tv_sec / dynamicPleaseStartDelay + 1;
1857 else
1859 ap_log_rerror(FCGI_LOG_ERR_NOERRNO, r, "FastCGI: comm with "
1860 "server \"%s\" aborted: idle timeout (%d sec)",
1861 fr->fs_path, idle_timeout);
1862 state = STATE_ERROR;
1863 break;
1866 else
1868 int i = rv - WAIT_OBJECT_0;
1870 did_io = 1;
1872 if (i == 0)
1874 if (send_pending)
1876 DWORD sent;
1878 if (GetOverlappedResult((HANDLE) fr->fd, &sov, &sent, FALSE))
1880 send_pending = 0;
1881 fcgi_buf_removed(fr->serverOutputBuffer, sent);
1883 else
1885 ap_log_rerror(FCGI_LOG_ERR, r, "FastCGI: comm with server "
1886 "\"%s\" aborted: GetOverlappedResult() failed", fr->fs_path);
1887 state = STATE_ERROR;
1888 break;
1892 ResetEvent(sov.hEvent);
1894 else
1896 DWORD rcvd;
1898 ASSERT(i == 1);
1900 recv_pending = 0;
1901 ResetEvent(rov.hEvent);
1903 if (GetOverlappedResult((HANDLE) fr->fd, &rov, &rcvd, FALSE))
1905 fcgi_buf_added(fr->serverInputBuffer, rcvd);
1906 if (dynamic_first_recv)
1908 dynamic_first_recv = 0;
1911 else
1913 ap_log_rerror(FCGI_LOG_ERR, r, "FastCGI: comm with server "
1914 "\"%s\" aborted: GetOverlappedResult() failed", fr->fs_path);
1915 state = STATE_ERROR;
1916 break;
1922 if (fcgi_protocol_dequeue(rp, fr))
1924 state = STATE_ERROR;
1925 break;
1928 if (fr->parseHeader == SCAN_CGI_READING_HEADERS)
1930 const char * err = process_headers(r, fr);
1931 if (err)
1933 ap_log_rerror(FCGI_LOG_ERR_NOERRNO, r,
1934 "FastCGI: comm with server \"%s\" aborted: "
1935 "error parsing headers: %s", fr->fs_path, err);
1936 state = STATE_ERROR;
1937 break;
1941 if (fr->exitStatusSet)
1943 fr->keepReadingFromFcgiApp = FALSE;
1944 state = STATE_CLIENT_SEND;
1945 break;
1949 if (! fr->exitStatusSet || ! fr->eofSent)
1951 CancelIo((HANDLE) fr->fd);
1954 CloseHandle(rov.hEvent);
1955 CloseHandle(sov.hEvent);
1957 return (state == STATE_ERROR);
1959 #endif /* WIN32 */
1961 static int socket_io(fcgi_request * const fr)
1963 enum
1965 STATE_SOCKET_NONE,
1966 STATE_ENV_SEND,
1967 STATE_CLIENT_RECV,
1968 STATE_SERVER_SEND,
1969 STATE_SERVER_RECV,
1970 STATE_CLIENT_SEND,
1971 STATE_ERROR,
1972 STATE_CLIENT_ERROR
1974 state = STATE_ENV_SEND;
1976 request_rec * const r = fr->r;
1978 struct timeval timeout;
1979 struct timeval dynamic_last_io_time = {0, 0};
1980 fd_set read_set;
1981 fd_set write_set;
1982 int nfds = 0;
1983 int select_status = 1;
1984 int idle_timeout;
1985 int rv;
1986 int dynamic_first_recv = fr->dynamic ? 1 : 0;
1987 int client_send = FALSE;
1988 int client_recv = FALSE;
1989 env_status env;
1990 pool *rp = r->pool;
1991 int is_connected = 0;
1993 if (fr->role == FCGI_RESPONDER)
1995 client_recv = (fr->expectingClientContent != 0);
1998 idle_timeout = fr->dynamic ? dynamic_idle_timeout : fr->fs->idle_timeout;
2000 env.envp = NULL;
2002 if (fr->dynamic)
2004 dynamic_last_io_time = fr->startTime;
2006 if (dynamicAppConnectTimeout)
2008 struct timeval qwait;
2009 timersub(&fr->queueTime, &fr->startTime, &qwait);
2010 dynamic_first_recv = qwait.tv_sec / dynamicPleaseStartDelay + 1;
2014 ap_hard_timeout("FastCGI request processing", r);
2016 for (;;)
2018 FD_ZERO(&read_set);
2019 FD_ZERO(&write_set);
2021 switch (state)
2023 case STATE_ENV_SEND:
2025 if (fcgi_protocol_queue_env(r, fr, &env) == 0)
2027 goto SERVER_SEND;
2030 state = STATE_CLIENT_RECV;
2032 /* fall through */
2034 case STATE_CLIENT_RECV:
2036 if (read_from_client_n_queue(fr))
2038 state = STATE_CLIENT_ERROR;
2039 break;
2042 if (fr->eofSent)
2044 state = STATE_SERVER_SEND;
2047 /* fall through */
2049 SERVER_SEND:
2051 case STATE_SERVER_SEND:
2053 if (! is_connected)
2055 if (open_connection_to_fs(fr) != FCGI_OK)
2057 ap_kill_timeout(r);
2058 return HTTP_INTERNAL_SERVER_ERROR;
2061 set_nonblocking(fr, TRUE);
2062 is_connected = 1;
2063 nfds = fr->fd + 1;
2066 if (BufferLength(fr->serverOutputBuffer))
2068 FD_SET(fr->fd, &write_set);
2070 else
2072 ASSERT(fr->eofSent);
2073 state = STATE_SERVER_RECV;
2076 /* fall through */
2078 case STATE_SERVER_RECV:
2080 FD_SET(fr->fd, &read_set);
2082 /* fall through */
2084 case STATE_CLIENT_SEND:
2086 if (client_send || ! BufferFree(fr->clientOutputBuffer))
2088 if (write_to_client(fr))
2090 state = STATE_CLIENT_ERROR;
2091 break;
2094 client_send = 0;
2097 break;
2099 case STATE_ERROR:
2100 case STATE_CLIENT_ERROR:
2102 break;
2104 default:
2106 ASSERT(0);
2109 if (state == STATE_CLIENT_ERROR || state == STATE_ERROR)
2111 break;
2114 /* setup the io timeout */
2116 if (BufferLength(fr->clientOutputBuffer))
2118 /* don't let client data sit too long, it might be a push */
2119 timeout.tv_sec = 0;
2120 timeout.tv_usec = 100000;
2122 else if (dynamic_first_recv)
2124 int delay;
2125 struct timeval qwait;
2127 fcgi_util_ticks(&fr->queueTime);
2129 if (select_status)
2131 /* a send() succeeded last pass */
2132 dynamic_last_io_time = fr->queueTime;
2134 else
2136 /* timed out last pass */
2137 struct timeval idle_time;
2139 timersub(&fr->queueTime, &dynamic_last_io_time, &idle_time);
2141 if (idle_time.tv_sec > idle_timeout)
2143 send_to_pm(FCGI_REQUEST_TIMEOUT_JOB, fr->fs_path, fr->user, fr->group, 0, 0);
2144 ap_log_rerror(FCGI_LOG_ERR_NOERRNO, r, "FastCGI: comm "
2145 "with (dynamic) server \"%s\" aborted: (first read) "
2146 "idle timeout (%d sec)", fr->fs_path, idle_timeout);
2147 state = STATE_ERROR;
2148 break;
2152 timersub(&fr->queueTime, &fr->startTime, &qwait);
2154 delay = dynamic_first_recv * dynamicPleaseStartDelay;
2156 FCGIDBG5("qwait=%ld.%06ld delay=%d first_recv=%d", qwait.tv_sec, qwait.tv_usec, delay, dynamic_first_recv);
2158 if (qwait.tv_sec < delay)
2160 timeout.tv_sec = delay;
2161 timeout.tv_usec = 100000; /* fudge for select() slop */
2162 timersub(&timeout, &qwait, &timeout);
2164 else
2166 /* Killed time somewhere.. client read? */
2167 send_to_pm(FCGI_REQUEST_TIMEOUT_JOB, fr->fs_path, fr->user, fr->group, 0, 0);
2168 dynamic_first_recv = qwait.tv_sec / dynamicPleaseStartDelay + 1;
2169 timeout.tv_sec = dynamic_first_recv * dynamicPleaseStartDelay;
2170 timeout.tv_usec = 100000; /* fudge for select() slop */
2171 timersub(&timeout, &qwait, &timeout);
2174 else
2176 timeout.tv_sec = idle_timeout;
2177 timeout.tv_usec = 0;
2180 /* wait on the socket */
2181 select_status = ap_select(nfds, &read_set, &write_set, NULL, &timeout);
2183 if (select_status < 0)
2185 ap_log_rerror(FCGI_LOG_ERR_ERRNO, r, "FastCGI: comm with server "
2186 "\"%s\" aborted: select() failed", fr->fs_path);
2187 state = STATE_ERROR;
2188 break;
2191 if (select_status == 0)
2193 /* select() timeout */
2195 if (BufferLength(fr->clientOutputBuffer))
2197 if (fr->role == FCGI_RESPONDER)
2199 client_send = TRUE;
2202 else if (dynamic_first_recv)
2204 struct timeval qwait;
2206 fcgi_util_ticks(&fr->queueTime);
2207 timersub(&fr->queueTime, &fr->startTime, &qwait);
2209 send_to_pm(FCGI_REQUEST_TIMEOUT_JOB, fr->fs_path, fr->user, fr->group, 0, 0);
2211 dynamic_first_recv = qwait.tv_sec / dynamicPleaseStartDelay + 1;
2212 continue;
2214 else
2216 ap_log_rerror(FCGI_LOG_ERR_NOERRNO, r, "FastCGI: comm with "
2217 "server \"%s\" aborted: idle timeout (%d sec)",
2218 fr->fs_path, idle_timeout);
2219 state = STATE_ERROR;
2223 if (FD_ISSET(fr->fd, &write_set))
2225 /* send to the server */
2227 rv = fcgi_buf_socket_send(fr->serverOutputBuffer, fr->fd);
2229 if (rv < 0)
2231 ap_log_rerror(FCGI_LOG_ERR, r, "FastCGI: comm with server "
2232 "\"%s\" aborted: write failed", fr->fs_path);
2233 state = STATE_ERROR;
2234 break;
2238 if (FD_ISSET(fr->fd, &read_set))
2240 /* recv from the server */
2242 if (dynamic_first_recv)
2244 dynamic_first_recv = 0;
2245 fcgi_util_ticks(&fr->queueTime);
2248 rv = fcgi_buf_socket_recv(fr->serverInputBuffer, fr->fd);
2250 if (rv < 0)
2252 ap_log_rerror(FCGI_LOG_ERR, r, "FastCGI: comm with server "
2253 "\"%s\" aborted: read failed", fr->fs_path);
2254 state = STATE_ERROR;
2255 break;
2258 if (rv == 0)
2260 fr->keepReadingFromFcgiApp = FALSE;
2261 state = STATE_CLIENT_SEND;
2262 break;
2266 if (fcgi_protocol_dequeue(rp, fr))
2268 state = STATE_ERROR;
2269 break;
2272 if (fr->parseHeader == SCAN_CGI_READING_HEADERS)
2274 const char * err = process_headers(r, fr);
2275 if (err)
2277 ap_log_rerror(FCGI_LOG_ERR_NOERRNO, r,
2278 "FastCGI: comm with server \"%s\" aborted: "
2279 "error parsing headers: %s", fr->fs_path, err);
2280 state = STATE_ERROR;
2281 break;
2285 if (fr->exitStatusSet)
2287 fr->keepReadingFromFcgiApp = FALSE;
2288 state = STATE_CLIENT_SEND;
2289 break;
2293 return (state == STATE_ERROR);
2297 /*----------------------------------------------------------------------
2298 * This is the core routine for moving data between the FastCGI
2299 * application and the Web server's client.
2301 static int do_work(request_rec * const r, fcgi_request * const fr)
2303 int rv;
2304 pool *rp = r->pool;
2306 fcgi_protocol_queue_begin_request(fr);
2308 if (fr->role == FCGI_RESPONDER)
2310 rv = ap_setup_client_block(r, REQUEST_CHUNKED_ERROR);
2311 if (rv != OK)
2313 ap_kill_timeout(r);
2314 return rv;
2317 fr->expectingClientContent = ap_should_client_block(r);
2320 ap_block_alarms();
2321 ap_register_cleanup(rp, (void *)fr, cleanup, ap_null_cleanup);
2322 ap_unblock_alarms();
2324 #ifdef WIN32
2325 if (fr->using_npipe_io)
2327 rv = npipe_io(fr);
2329 else
2330 #endif
2332 rv = socket_io(fr);
2335 /* comm with the server is done */
2336 close_connection_to_fs(fr);
2338 if (fr->role == FCGI_RESPONDER)
2340 sink_client_data(fr);
2343 while (rv == 0 && (BufferLength(fr->serverInputBuffer) || BufferLength(fr->clientOutputBuffer)))
2345 if (fcgi_protocol_dequeue(rp, fr))
2347 rv = HTTP_INTERNAL_SERVER_ERROR;
2350 if (fr->parseHeader == SCAN_CGI_READING_HEADERS)
2352 const char * err = process_headers(r, fr);
2353 if (err)
2355 ap_log_rerror(FCGI_LOG_ERR_NOERRNO, r,
2356 "FastCGI: comm with server \"%s\" aborted: "
2357 "error parsing headers: %s", fr->fs_path, err);
2358 rv = HTTP_INTERNAL_SERVER_ERROR;
2362 if (fr->role == FCGI_RESPONDER)
2364 if (write_to_client(fr))
2366 break;
2369 else
2371 fcgi_buf_reset(fr->clientOutputBuffer);
2375 switch (fr->parseHeader)
2377 case SCAN_CGI_FINISHED:
2379 if (fr->role == FCGI_RESPONDER)
2381 /* RUSSIAN_APACHE requires rflush() over bflush() */
2382 ap_rflush(r);
2383 #ifndef APACHE2
2384 ap_bgetopt(r->connection->client, BO_BYTECT, &r->bytes_sent);
2385 #endif
2388 /* fall through */
2390 case SCAN_CGI_INT_REDIRECT:
2391 case SCAN_CGI_SRV_REDIRECT:
2393 break;
2395 case SCAN_CGI_READING_HEADERS:
2397 ap_log_rerror(FCGI_LOG_ERR_NOERRNO, r, "FastCGI: incomplete headers "
2398 "(%d bytes) received from server \"%s\"", fr->header->nelts, fr->fs_path);
2400 /* fall through */
2402 case SCAN_CGI_BAD_HEADER:
2404 rv = HTTP_INTERNAL_SERVER_ERROR;
2405 break;
2407 default:
2409 ASSERT(0);
2410 rv = HTTP_INTERNAL_SERVER_ERROR;
2413 ap_kill_timeout(r);
2414 return rv;
2417 static int
2418 create_fcgi_request(request_rec * const r,
2419 const char * const path,
2420 fcgi_request ** const frP)
2422 const char *fs_path;
2423 pool * const p = r->pool;
2424 fcgi_server *fs;
2425 fcgi_request * const fr = (fcgi_request *)ap_pcalloc(p, sizeof(fcgi_request));
2426 uid_t uid;
2427 gid_t gid;
2429 fs_path = path ? path : r->filename;
2431 get_request_identity(r, &uid, &gid);
2433 fs = fcgi_util_fs_get_by_id(fs_path, uid, gid);
2435 if (fs == NULL)
2437 const char * err;
2438 struct stat *my_finfo;
2440 /* dynamic? */
2442 #ifndef APACHE2
2443 if (path == NULL)
2445 /* AP2: its bogus that we don't make use of r->finfo, but
2446 * its an apr_finfo_t and there is no apr_os_finfo_get() */
2448 my_finfo = &r->finfo;
2450 else
2451 #endif
2453 my_finfo = (struct stat *) ap_palloc(p, sizeof(struct stat));
2455 if (stat(fs_path, my_finfo) < 0)
2457 ap_log_rerror(FCGI_LOG_ERR_ERRNO, r,
2458 "FastCGI: stat() of \"%s\" failed", fs_path);
2459 return HTTP_NOT_FOUND;
2463 err = fcgi_util_fs_is_path_ok(p, fs_path, my_finfo);
2464 if (err)
2466 ap_log_rerror(FCGI_LOG_ERR_NOERRNO, r,
2467 "FastCGI: invalid (dynamic) server \"%s\": %s", fs_path, err);
2468 return HTTP_FORBIDDEN;
2472 fr->serverInputBuffer = fcgi_buf_new(p, SERVER_BUFSIZE);
2473 fr->serverOutputBuffer = fcgi_buf_new(p, SERVER_BUFSIZE);
2474 fr->clientInputBuffer = fcgi_buf_new(p, SERVER_BUFSIZE);
2475 fr->clientOutputBuffer = fcgi_buf_new(p, SERVER_BUFSIZE);
2476 fr->erBufPtr = fcgi_buf_new(p, sizeof(FCGI_EndRequestBody) + 1);
2477 fr->gotHeader = FALSE;
2478 fr->parseHeader = SCAN_CGI_READING_HEADERS;
2479 fr->header = ap_make_array(p, 1, 1);
2480 fr->fs_stderr = NULL;
2481 fr->r = r;
2482 fr->readingEndRequestBody = FALSE;
2483 fr->exitStatus = 0;
2484 fr->exitStatusSet = FALSE;
2485 fr->requestId = 1; /* anything but zero is OK here */
2486 fr->eofSent = FALSE;
2487 fr->role = FCGI_RESPONDER;
2488 fr->expectingClientContent = FALSE;
2489 fr->keepReadingFromFcgiApp = TRUE;
2490 fr->fs = fs;
2491 fr->fs_path = fs_path;
2492 fr->authHeaders = ap_make_table(p, 10);
2493 #ifdef WIN32
2494 fr->fd = INVALID_SOCKET;
2495 fr->dynamic = ((fs == NULL) || (fs->directive == APP_CLASS_DYNAMIC)) ? TRUE : FALSE;
2496 fr->using_npipe_io = (! fr->dynamic && (fs->dest_addr || fs->socket_addr)) ? 0 : 1;
2497 #else
2498 fr->dynamic = (fs == NULL) ? TRUE : FALSE;
2499 fr->fd = -1;
2500 #endif
2502 set_uid_n_gid(r, &fr->user, &fr->group);
2504 *frP = fr;
2506 return OK;
2510 *----------------------------------------------------------------------
2512 * handler --
2514 * This routine gets called for a request that corresponds to
2515 * a FastCGI connection. It performs the request synchronously.
2517 * Results:
2518 * Final status of request: OK or NOT_FOUND or HTTP_INTERNAL_SERVER_ERROR.
2520 * Side effects:
2521 * Request performed.
2523 *----------------------------------------------------------------------
2526 /* Stolen from mod_cgi.c..
2527 * KLUDGE --- for back-combatibility, we don't have to check ExecCGI
2528 * in ScriptAliased directories, which means we need to know if this
2529 * request came through ScriptAlias or not... so the Alias module
2530 * leaves a note for us.
2532 static int apache_is_scriptaliased(request_rec *r)
2534 const char *t = ap_table_get(r->notes, "alias-forced-type");
2535 return t && (!strcasecmp(t, "cgi-script"));
2538 /* If a script wants to produce its own Redirect body, it now
2539 * has to explicitly *say* "Status: 302". If it wants to use
2540 * Apache redirects say "Status: 200". See process_headers().
2542 static int post_process_for_redirects(request_rec * const r,
2543 const fcgi_request * const fr)
2545 switch(fr->parseHeader) {
2546 case SCAN_CGI_INT_REDIRECT:
2548 /* @@@ There are still differences between the handling in
2549 * mod_cgi and mod_fastcgi. This needs to be revisited.
2551 /* We already read the message body (if any), so don't allow
2552 * the redirected request to think it has one. We can ignore
2553 * Transfer-Encoding, since we used REQUEST_CHUNKED_ERROR.
2555 r->method = "GET";
2556 r->method_number = M_GET;
2557 ap_table_unset(r->headers_in, "Content-length");
2559 ap_internal_redirect_handler(ap_table_get(r->headers_out, "Location"), r);
2560 return OK;
2562 case SCAN_CGI_SRV_REDIRECT:
2563 return HTTP_MOVED_TEMPORARILY;
2565 default:
2566 return OK;
2570 /******************************************************************************
2571 * Process fastcgi-script requests. Based on mod_cgi::cgi_handler().
2573 static int content_handler(request_rec *r)
2575 fcgi_request *fr = NULL;
2576 int ret;
2578 #ifdef APACHE2
2579 if (strcmp(r->handler, FASTCGI_HANDLER_NAME))
2580 return DECLINED;
2581 #endif
2583 /* Setup a new FastCGI request */
2584 ret = create_fcgi_request(r, NULL, &fr);
2585 if (ret)
2587 return ret;
2590 /* If its a dynamic invocation, make sure scripts are OK here */
2591 if (fr->dynamic && ! (ap_allow_options(r) & OPT_EXECCGI)
2592 && ! apache_is_scriptaliased(r))
2594 ap_log_rerror(FCGI_LOG_ERR_NOERRNO, r,
2595 "FastCGI: \"ExecCGI Option\" is off in this directory: %s", r->uri);
2596 return HTTP_FORBIDDEN;
2599 /* Process the fastcgi-script request */
2600 if ((ret = do_work(r, fr)) != OK)
2601 return ret;
2603 /* Special case redirects */
2604 ret = post_process_for_redirects(r, fr);
2606 return ret;
2610 static int post_process_auth_passed_header(table *t, const char *key, const char * const val)
2612 if (strncasecmp(key, "Variable-", 9) == 0)
2613 key += 9;
2615 ap_table_setn(t, key, val);
2616 return 1;
2619 static int post_process_auth_passed_compat_header(table *t, const char *key, const char * const val)
2621 if (strncasecmp(key, "Variable-", 9) == 0)
2622 ap_table_setn(t, key + 9, val);
2624 return 1;
2627 static int post_process_auth_failed_header(table * const t, const char * const key, const char * const val)
2629 ap_table_setn(t, key, val);
2630 return 1;
2633 static void post_process_auth(fcgi_request * const fr, const int passed)
2635 request_rec * const r = fr->r;
2637 /* Restore the saved subprocess_env because we muddied ours up */
2638 r->subprocess_env = fr->saved_subprocess_env;
2640 if (passed) {
2641 if (fr->auth_compat) {
2642 ap_table_do((int (*)(void *, const char *, const char *))post_process_auth_passed_compat_header,
2643 (void *)r->subprocess_env, fr->authHeaders, NULL);
2645 else {
2646 ap_table_do((int (*)(void *, const char *, const char *))post_process_auth_passed_header,
2647 (void *)r->subprocess_env, fr->authHeaders, NULL);
2650 else {
2651 ap_table_do((int (*)(void *, const char *, const char *))post_process_auth_failed_header,
2652 (void *)r->err_headers_out, fr->authHeaders, NULL);
2655 /* @@@ Restore these.. its a hack until I rewrite the header handling */
2656 r->status = HTTP_OK;
2657 r->status_line = NULL;
2660 static int check_user_authentication(request_rec *r)
2662 int res, authenticated = 0;
2663 const char *password;
2664 fcgi_request *fr;
2665 const fcgi_dir_config * const dir_config =
2666 (const fcgi_dir_config *)ap_get_module_config(r->per_dir_config, &fastcgi_module);
2668 if (dir_config->authenticator == NULL)
2669 return DECLINED;
2671 /* Get the user password */
2672 if ((res = ap_get_basic_auth_pw(r, &password)) != OK)
2673 return res;
2675 res = create_fcgi_request(r, dir_config->authenticator, &fr);
2676 if (res)
2678 return res;
2681 /* Save the existing subprocess_env, because we're gonna muddy it up */
2682 fr->saved_subprocess_env = ap_copy_table(r->pool, r->subprocess_env);
2684 ap_table_setn(r->subprocess_env, "REMOTE_PASSWD", password);
2685 ap_table_setn(r->subprocess_env, "FCGI_APACHE_ROLE", "AUTHENTICATOR");
2687 /* The FastCGI Protocol doesn't differentiate authentication */
2688 fr->role = FCGI_AUTHORIZER;
2690 /* Do we need compatibility mode? */
2691 fr->auth_compat = (dir_config->authenticator_options & FCGI_COMPAT);
2693 if ((res = do_work(r, fr)) != OK)
2694 goto AuthenticationFailed;
2696 authenticated = (r->status == 200);
2697 post_process_auth(fr, authenticated);
2699 /* A redirect shouldn't be allowed during the authentication phase */
2700 if (ap_table_get(r->headers_out, "Location") != NULL) {
2701 ap_log_rerror(FCGI_LOG_ERR_NOERRNO, r,
2702 "FastCGI: FastCgiAuthenticator \"%s\" redirected (not allowed)",
2703 dir_config->authenticator);
2704 goto AuthenticationFailed;
2707 if (authenticated)
2708 return OK;
2710 AuthenticationFailed:
2711 if (!(dir_config->authenticator_options & FCGI_AUTHORITATIVE))
2712 return DECLINED;
2714 /* @@@ Probably should support custom_responses */
2715 ap_note_basic_auth_failure(r);
2716 ap_log_rerror(FCGI_LOG_ERR_NOERRNO, r,
2717 "FastCGI: authentication failed for user \"%s\": %s",
2718 #ifdef APACHE2
2719 r->user, r->uri);
2720 #else
2721 r->connection->user, r->uri);
2722 #endif
2724 return (res == OK) ? HTTP_UNAUTHORIZED : res;
2727 static int check_user_authorization(request_rec *r)
2729 int res, authorized = 0;
2730 fcgi_request *fr;
2731 const fcgi_dir_config * const dir_config =
2732 (const fcgi_dir_config *)ap_get_module_config(r->per_dir_config, &fastcgi_module);
2734 if (dir_config->authorizer == NULL)
2735 return DECLINED;
2737 /* @@@ We should probably honor the existing parameters to the require directive
2738 * as well as allow the definition of new ones (or use the basename of the
2739 * FastCGI server and pass the rest of the directive line), but for now keep
2740 * it simple. */
2742 res = create_fcgi_request(r, dir_config->authorizer, &fr);
2743 if (res)
2745 return res;
2748 /* Save the existing subprocess_env, because we're gonna muddy it up */
2749 fr->saved_subprocess_env = ap_copy_table(r->pool, r->subprocess_env);
2751 ap_table_setn(r->subprocess_env, "FCGI_APACHE_ROLE", "AUTHORIZER");
2753 fr->role = FCGI_AUTHORIZER;
2755 /* Do we need compatibility mode? */
2756 fr->auth_compat = (dir_config->authorizer_options & FCGI_COMPAT);
2758 if ((res = do_work(r, fr)) != OK)
2759 goto AuthorizationFailed;
2761 authorized = (r->status == 200);
2762 post_process_auth(fr, authorized);
2764 /* A redirect shouldn't be allowed during the authorization phase */
2765 if (ap_table_get(r->headers_out, "Location") != NULL) {
2766 ap_log_rerror(FCGI_LOG_ERR_NOERRNO, r,
2767 "FastCGI: FastCgiAuthorizer \"%s\" redirected (not allowed)",
2768 dir_config->authorizer);
2769 goto AuthorizationFailed;
2772 if (authorized)
2773 return OK;
2775 AuthorizationFailed:
2776 if (!(dir_config->authorizer_options & FCGI_AUTHORITATIVE))
2777 return DECLINED;
2779 /* @@@ Probably should support custom_responses */
2780 ap_note_basic_auth_failure(r);
2781 ap_log_rerror(FCGI_LOG_ERR_NOERRNO, r,
2782 "FastCGI: authorization failed for user \"%s\": %s",
2783 #ifdef APACHE2
2784 r->user, r->uri);
2785 #else
2786 r->connection->user, r->uri);
2787 #endif
2789 return (res == OK) ? HTTP_UNAUTHORIZED : res;
2792 static int check_access(request_rec *r)
2794 int res, access_allowed = 0;
2795 fcgi_request *fr;
2796 const fcgi_dir_config * const dir_config =
2797 (fcgi_dir_config *)ap_get_module_config(r->per_dir_config, &fastcgi_module);
2799 if (dir_config == NULL || dir_config->access_checker == NULL)
2800 return DECLINED;
2802 res = create_fcgi_request(r, dir_config->access_checker, &fr);
2803 if (res)
2805 return res;
2808 /* Save the existing subprocess_env, because we're gonna muddy it up */
2809 fr->saved_subprocess_env = ap_copy_table(r->pool, r->subprocess_env);
2811 ap_table_setn(r->subprocess_env, "FCGI_APACHE_ROLE", "ACCESS_CHECKER");
2813 /* The FastCGI Protocol doesn't differentiate access control */
2814 fr->role = FCGI_AUTHORIZER;
2816 /* Do we need compatibility mode? */
2817 fr->auth_compat = (dir_config->access_checker_options & FCGI_COMPAT);
2819 if ((res = do_work(r, fr)) != OK)
2820 goto AccessFailed;
2822 access_allowed = (r->status == 200);
2823 post_process_auth(fr, access_allowed);
2825 /* A redirect shouldn't be allowed during the access check phase */
2826 if (ap_table_get(r->headers_out, "Location") != NULL) {
2827 ap_log_rerror(FCGI_LOG_ERR_NOERRNO, r,
2828 "FastCGI: FastCgiAccessChecker \"%s\" redirected (not allowed)",
2829 dir_config->access_checker);
2830 goto AccessFailed;
2833 if (access_allowed)
2834 return OK;
2836 AccessFailed:
2837 if (!(dir_config->access_checker_options & FCGI_AUTHORITATIVE))
2838 return DECLINED;
2840 /* @@@ Probably should support custom_responses */
2841 ap_log_rerror(FCGI_LOG_ERR_NOERRNO, r, "FastCGI: access denied: %s", r->uri);
2842 return (res == OK) ? HTTP_FORBIDDEN : res;
2845 static int
2846 fixups(request_rec * r)
2848 uid_t uid;
2849 gid_t gid;
2851 get_request_identity(r, &uid, &gid);
2853 if (fcgi_util_fs_get_by_id(r->filename, uid, gid))
2855 r->handler = FASTCGI_HANDLER_NAME;
2856 return OK;
2859 return DECLINED;
2862 #ifndef APACHE2
2864 # define AP_INIT_RAW_ARGS(directive, func, mconfig, where, help) \
2865 { directive, func, mconfig, where, RAW_ARGS, help }
2866 # define AP_INIT_TAKE1(directive, func, mconfig, where, help) \
2867 { directive, func, mconfig, where, TAKE1, help }
2868 # define AP_INIT_TAKE12(directive, func, mconfig, where, help) \
2869 { directive, func, mconfig, where, TAKE12, help }
2870 # define AP_INIT_FLAG(directive, func, mconfig, where, help) \
2871 { directive, func, mconfig, where, FLAG, help }
2873 #endif
2875 static const command_rec fastcgi_cmds[] =
2877 AP_INIT_RAW_ARGS("AppClass", fcgi_config_new_static_server, NULL, RSRC_CONF, NULL),
2878 AP_INIT_RAW_ARGS("FastCgiServer", fcgi_config_new_static_server, NULL, RSRC_CONF, NULL),
2880 AP_INIT_RAW_ARGS("ExternalAppClass", fcgi_config_new_external_server, NULL, RSRC_CONF, NULL),
2881 AP_INIT_RAW_ARGS("FastCgiExternalServer", fcgi_config_new_external_server, NULL, RSRC_CONF, NULL),
2883 AP_INIT_TAKE1("FastCgiIpcDir", fcgi_config_set_socket_dir, NULL, RSRC_CONF, NULL),
2885 AP_INIT_TAKE1("FastCgiSuexec", fcgi_config_set_wrapper, NULL, RSRC_CONF, NULL),
2886 AP_INIT_TAKE1("FastCgiWrapper", fcgi_config_set_wrapper, NULL, RSRC_CONF, NULL),
2888 AP_INIT_RAW_ARGS("FCGIConfig", fcgi_config_set_config, NULL, RSRC_CONF, NULL),
2889 AP_INIT_RAW_ARGS("FastCgiConfig", fcgi_config_set_config, NULL, RSRC_CONF, NULL),
2891 AP_INIT_TAKE12("FastCgiAuthenticator", fcgi_config_new_auth_server,
2892 (void *)FCGI_AUTH_TYPE_AUTHENTICATOR, ACCESS_CONF,
2893 "a fastcgi-script path (absolute or relative to ServerRoot) followed by an optional -compat"),
2894 AP_INIT_FLAG("FastCgiAuthenticatorAuthoritative", fcgi_config_set_authoritative_slot,
2895 (void *)XtOffsetOf(fcgi_dir_config, authenticator_options), ACCESS_CONF,
2896 "Set to 'off' to allow authentication to be passed along to lower modules upon failure"),
2898 AP_INIT_TAKE12("FastCgiAuthorizer", fcgi_config_new_auth_server,
2899 (void *)FCGI_AUTH_TYPE_AUTHORIZER, ACCESS_CONF,
2900 "a fastcgi-script path (absolute or relative to ServerRoot) followed by an optional -compat"),
2901 AP_INIT_FLAG("FastCgiAuthorizerAuthoritative", fcgi_config_set_authoritative_slot,
2902 (void *)XtOffsetOf(fcgi_dir_config, authorizer_options), ACCESS_CONF,
2903 "Set to 'off' to allow authorization to be passed along to lower modules upon failure"),
2905 AP_INIT_TAKE12("FastCgiAccessChecker", fcgi_config_new_auth_server,
2906 (void *)FCGI_AUTH_TYPE_ACCESS_CHECKER, ACCESS_CONF,
2907 "a fastcgi-script path (absolute or relative to ServerRoot) followed by an optional -compat"),
2908 AP_INIT_FLAG("FastCgiAccessCheckerAuthoritative", fcgi_config_set_authoritative_slot,
2909 (void *)XtOffsetOf(fcgi_dir_config, access_checker_options), ACCESS_CONF,
2910 "Set to 'off' to allow access control to be passed along to lower modules upon failure"),
2911 { NULL }
2914 #ifdef APACHE2
2916 static void register_hooks(apr_pool_t * p)
2918 // ap_hook_pre_config(x_pre_config, NULL, NULL, APR_HOOK_MIDDLE);
2919 ap_hook_post_config(init_module, NULL, NULL, APR_HOOK_MIDDLE);
2920 ap_hook_child_init(fcgi_child_init, NULL, NULL, APR_HOOK_MIDDLE);
2921 ap_hook_handler(content_handler, NULL, NULL, APR_HOOK_MIDDLE);
2922 ap_hook_check_user_id(check_user_authentication, NULL, NULL, APR_HOOK_MIDDLE);
2923 ap_hook_access_checker(check_access, NULL, NULL, APR_HOOK_MIDDLE);
2924 ap_hook_auth_checker(check_user_authorization, NULL, NULL, APR_HOOK_MIDDLE);
2925 ap_hook_fixups(fixups, NULL, NULL, APR_HOOK_MIDDLE);
2928 module AP_MODULE_DECLARE_DATA fastcgi_module =
2930 STANDARD20_MODULE_STUFF,
2931 fcgi_config_create_dir_config, /* per-directory config creator */
2932 NULL, /* dir config merger */
2933 NULL, /* server config creator */
2934 NULL, /* server config merger */
2935 fastcgi_cmds, /* command table */
2936 register_hooks, /* set up other request processing hooks */
2939 #else /* !APACHE2 */
2941 handler_rec fastcgi_handlers[] = {
2942 { FCGI_MAGIC_TYPE, content_handler },
2943 { FASTCGI_HANDLER_NAME, content_handler },
2944 { NULL }
2947 module MODULE_VAR_EXPORT fastcgi_module = {
2948 STANDARD_MODULE_STUFF,
2949 init_module, /* initializer */
2950 fcgi_config_create_dir_config, /* per-dir config creator */
2951 NULL, /* per-dir config merger (default: override) */
2952 NULL, /* per-server config creator */
2953 NULL, /* per-server config merger (default: override) */
2954 fastcgi_cmds, /* command table */
2955 fastcgi_handlers, /* [9] content handlers */
2956 NULL, /* [2] URI-to-filename translation */
2957 check_user_authentication, /* [5] authenticate user_id */
2958 check_user_authorization, /* [6] authorize user_id */
2959 check_access, /* [4] check access (based on src & http headers) */
2960 NULL, /* [7] check/set MIME type */
2961 fixups, /* [8] fixups */
2962 NULL, /* [10] logger */
2963 NULL, /* [3] header-parser */
2964 fcgi_child_init, /* process initialization */
2965 #ifdef WIN32
2966 fcgi_child_exit, /* process exit/cleanup */
2967 #else
2968 NULL,
2969 #endif
2970 NULL /* [1] post read-request handling */
2973 #endif /* !APACHE2 */