prevent module init from running twice under AP2/*nix
[mod_fastcgi.git] / mod_fastcgi.c
blobbb26ea88cd77b274cfaa128497e626cdb46bc6b6
1 /*
2 * mod_fastcgi.c --
4 * Apache server module for FastCGI.
6 * $Id: mod_fastcgi.c,v 1.144 2002/10/19 02:09:29 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 #ifndef timersub
75 #define timersub(a, b, result) \
76 do { \
77 (result)->tv_sec = (a)->tv_sec - (b)->tv_sec; \
78 (result)->tv_usec = (a)->tv_usec - (b)->tv_usec; \
79 if ((result)->tv_usec < 0) { \
80 --(result)->tv_sec; \
81 (result)->tv_usec += 1000000; \
82 } \
83 } while (0)
84 #endif
87 * Global variables
90 pool *fcgi_config_pool; /* the config pool */
91 server_rec *fcgi_apache_main_server;
93 const char *fcgi_wrapper = NULL; /* wrapper path */
94 uid_t fcgi_user_id; /* the run uid of Apache & PM */
95 gid_t fcgi_group_id; /* the run gid of Apache & PM */
97 fcgi_server *fcgi_servers = NULL; /* AppClasses */
99 char *fcgi_socket_dir = NULL; /* default FastCgiIpcDir */
101 char *fcgi_dynamic_dir = NULL; /* directory for the dynamic
102 * fastcgi apps' sockets */
104 #ifdef WIN32
106 #pragma warning( disable : 4706 4100 4127)
107 fcgi_pm_job *fcgi_dynamic_mbox = NULL;
108 HANDLE *fcgi_dynamic_mbox_mutex = NULL;
109 HANDLE fcgi_pm_thread = INVALID_HANDLE_VALUE;
111 #else
113 int fcgi_pm_pipe[2] = { -1, -1 };
114 pid_t fcgi_pm_pid = -1;
116 #endif
118 char *fcgi_empty_env = NULL;
120 u_int dynamicMaxProcs = FCGI_DEFAULT_MAX_PROCS;
121 int dynamicMinProcs = FCGI_DEFAULT_MIN_PROCS;
122 int dynamicMaxClassProcs = FCGI_DEFAULT_MAX_CLASS_PROCS;
123 u_int dynamicKillInterval = FCGI_DEFAULT_KILL_INTERVAL;
124 u_int dynamicUpdateInterval = FCGI_DEFAULT_UPDATE_INTERVAL;
125 float dynamicGain = FCGI_DEFAULT_GAIN;
126 int dynamicThreshold1 = FCGI_DEFAULT_THRESHOLD_1;
127 int dynamicThresholdN = FCGI_DEFAULT_THRESHOLD_N;
128 u_int dynamicPleaseStartDelay = FCGI_DEFAULT_START_PROCESS_DELAY;
129 u_int dynamicAppConnectTimeout = FCGI_DEFAULT_APP_CONN_TIMEOUT;
130 char **dynamicEnvp = &fcgi_empty_env;
131 u_int dynamicProcessSlack = FCGI_DEFAULT_PROCESS_SLACK;
132 int dynamicAutoRestart = FCGI_DEFAULT_RESTART_DYNAMIC;
133 int dynamicAutoUpdate = FCGI_DEFAULT_AUTOUPDATE;
134 int dynamicFlush = FCGI_FLUSH;
135 u_int dynamicListenQueueDepth = FCGI_DEFAULT_LISTEN_Q;
136 u_int dynamicInitStartDelay = DEFAULT_INIT_START_DELAY;
137 u_int dynamicRestartDelay = FCGI_DEFAULT_RESTART_DELAY;
138 array_header *dynamic_pass_headers = NULL;
139 u_int dynamic_idle_timeout = FCGI_DEFAULT_IDLE_TIMEOUT;
141 /*******************************************************************************
142 * Construct a message and write it to the pm_pipe.
144 static void send_to_pm(const char id, const char * const fs_path,
145 const char *user, const char * const group, const unsigned long q_usec,
146 const unsigned long req_usec)
148 #ifdef WIN32
149 fcgi_pm_job *job = NULL;
151 if (!(job = (fcgi_pm_job *) malloc(sizeof(fcgi_pm_job))))
152 return;
153 #else
154 static int failed_count = 0;
155 int buflen = 0;
156 char buf[FCGI_MAX_MSG_LEN];
157 #endif
159 if (strlen(fs_path) > FCGI_MAXPATH) {
160 ap_log_error(FCGI_LOG_ERR_NOERRNO, fcgi_apache_main_server,
161 "FastCGI: the path \"%s\" is too long (>%d) for a dynamic server", fs_path, FCGI_MAXPATH);
162 return;
165 switch(id) {
167 case FCGI_SERVER_START_JOB:
168 case FCGI_SERVER_RESTART_JOB:
169 #ifdef WIN32
170 job->id = id;
171 job->fs_path = strdup(fs_path);
172 job->user = strdup(user);
173 job->group = strdup(group);
174 job->qsec = 0L;
175 job->start_time = 0L;
176 #else
177 buflen = sprintf(buf, "%c %s %s %s*", id, fs_path, user, group);
178 #endif
179 break;
181 case FCGI_REQUEST_TIMEOUT_JOB:
182 #ifdef WIN32
183 job->id = id;
184 job->fs_path = strdup(fs_path);
185 job->user = strdup(user);
186 job->group = strdup(group);
187 job->qsec = 0L;
188 job->start_time = 0L;
189 #else
190 buflen = sprintf(buf, "%c %s %s %s*", id, fs_path, user, group);
191 #endif
192 break;
194 case FCGI_REQUEST_COMPLETE_JOB:
195 #ifdef WIN32
196 job->id = id;
197 job->fs_path = strdup(fs_path);
198 job->qsec = q_usec;
199 job->start_time = req_usec;
200 job->user = strdup(user);
201 job->group = strdup(group);
202 #else
203 buflen = sprintf(buf, "%c %s %s %s %lu %lu*", id, fs_path, user, group, q_usec, req_usec);
204 #endif
205 break;
208 #ifdef WIN32
209 if (fcgi_pm_add_job(job)) return;
211 SetEvent(fcgi_event_handles[MBOX_EVENT]);
212 #else
213 ap_assert(buflen <= FCGI_MAX_MSG_LEN);
215 /* There is no apache flag or function that can be used to id
216 * restart/shutdown pending so ignore the first few failures as
217 * once it breaks it will stay broke */
218 if (write(fcgi_pm_pipe[1], (const void *)buf, buflen) != buflen
219 && failed_count++ > 10)
221 ap_log_error(FCGI_LOG_WARN, fcgi_apache_main_server,
222 "FastCGI: write() to PM failed (ignore if a restart or shutdown is pending)");
224 #endif
228 *----------------------------------------------------------------------
230 * init_module
232 * An Apache module initializer, called by the Apache core
233 * after reading the server config.
235 * Start the process manager no matter what, since there may be a
236 * request for dynamic FastCGI applications without any being
237 * configured as static applications. Also, check for the existence
238 * and create if necessary a subdirectory into which all dynamic
239 * sockets will go.
241 *----------------------------------------------------------------------
243 #ifdef APACHE2
244 static apcb_t init_module(apr_pool_t * p, apr_pool_t * plog,
245 apr_pool_t * tp, server_rec * s)
246 #else
247 static apcb_t init_module(server_rec *s, pool *p)
248 #endif
250 #ifndef WIN32
251 const char *err;
252 #endif
254 /* Register to reset to default values when the config pool is cleaned */
255 ap_block_alarms();
256 ap_register_cleanup(p, NULL, fcgi_config_reset_globals, ap_null_cleanup);
257 ap_unblock_alarms();
259 #ifdef APACHE2
260 ap_add_version_component(p, "mod_fastcgi/" MOD_FASTCGI_VERSION);
261 #else
262 ap_add_version_component("mod_fastcgi/" MOD_FASTCGI_VERSION);
263 #endif
265 fcgi_config_set_fcgi_uid_n_gid(1);
267 /* keep these handy */
268 fcgi_config_pool = p;
269 fcgi_apache_main_server = s;
271 #ifdef WIN32
272 if (fcgi_socket_dir == NULL)
273 fcgi_socket_dir = DEFAULT_SOCK_DIR;
274 fcgi_dynamic_dir = ap_pstrcat(p, fcgi_socket_dir, "dynamic", NULL);
275 #else
277 if (fcgi_socket_dir == NULL)
278 fcgi_socket_dir = ap_server_root_relative(p, DEFAULT_SOCK_DIR);
280 /* Create Unix/Domain socket directory */
281 if ((err = fcgi_config_make_dir(p, fcgi_socket_dir)))
282 ap_log_error(FCGI_LOG_ERR, s, "FastCGI: %s", err);
284 /* Create Dynamic directory */
285 if ((err = fcgi_config_make_dynamic_dir(p, 1)))
286 ap_log_error(FCGI_LOG_ERR, s, "FastCGI: %s", err);
288 /* Spawn the PM only once. Under Unix, Apache calls init() routines
289 * twice, once before detach() and once after. Win32 doesn't detach.
290 * Under DSO, DSO modules are unloaded between the two init() calls.
291 * Under Unix, the -X switch causes two calls to init() but no detach
292 * (but all subprocesses are wacked so the PM is toasted anyway)! */
294 #ifdef APACHE2
296 void * first_pass;
297 apr_pool_userdata_get(&first_pass, "mod_fastcgi", s->process->pool);
298 if (first_pass == NULL)
300 apr_pool_userdata_set((const void *)1, "mod_fastcgi",
301 apr_pool_cleanup_null, s->process->pool);
302 return APCB_OK;
305 #else /* !APACHE2 */
307 if (ap_standalone && ap_restart_time == 0)
308 return;
310 #endif
312 /* Create the pipe for comm with the PM */
313 if (pipe(fcgi_pm_pipe) < 0) {
314 ap_log_error(FCGI_LOG_ERR, s, "FastCGI: pipe() failed");
317 /* Start the Process Manager */
319 #ifdef APACHE2
321 apr_proc_t * proc = apr_palloc(p, sizeof(*proc));
322 apr_status_t rv;
324 rv = apr_proc_fork(proc, tp);
326 if (rv == APR_INCHILD)
328 /* child */
329 fcgi_pm_main(NULL);
330 exit(1);
332 else if (rv != APR_INPARENT)
334 return rv;
337 /* parent */
339 apr_pool_note_subprocess(p, proc, APR_KILL_ONLY_ONCE);
341 #else /* !APACHE2 */
343 fcgi_pm_pid = ap_spawn_child(p, fcgi_pm_main, NULL, kill_only_once, NULL, NULL, NULL);
344 if (fcgi_pm_pid <= 0) {
345 ap_log_error(FCGI_LOG_ALERT, s,
346 "FastCGI: can't start the process manager, spawn_child() failed");
349 #endif /* !APACHE2 */
351 close(fcgi_pm_pipe[0]);
353 #endif /* !WIN32 */
355 return APCB_OK;
358 #ifdef APACHE2
359 static apcb_t fcgi_child_exit(void * dc)
360 #else
361 static apcb_t fcgi_child_exit(server_rec *dc0, pool *dc1)
362 #endif
364 #ifdef WIN32
365 /* Signal the PM thread to exit*/
366 SetEvent(fcgi_event_handles[TERM_EVENT]);
368 /* Waiting on pm thread to exit */
369 WaitForSingleObject(fcgi_pm_thread, INFINITE);
370 #endif
372 return APCB_OK;
375 #ifdef APACHE2
376 static void fcgi_child_init(apr_pool_t * p, server_rec * dc)
377 #else
378 static void fcgi_child_init(server_rec *dc, pool *p)
379 #endif
381 #ifdef WIN32
382 /* Create the MBOX, TERM, and WAKE event handlers */
383 fcgi_event_handles[0] = CreateEvent(NULL, FALSE, FALSE, NULL);
384 if (fcgi_event_handles[0] == NULL) {
385 ap_log_error(FCGI_LOG_ALERT, fcgi_apache_main_server,
386 "FastCGI: CreateEvent() failed");
388 fcgi_event_handles[1] = CreateEvent(NULL, FALSE, FALSE, NULL);
389 if (fcgi_event_handles[1] == NULL) {
390 ap_log_error(FCGI_LOG_ALERT, fcgi_apache_main_server,
391 "FastCGI: CreateEvent() failed");
393 fcgi_event_handles[2] = CreateEvent(NULL, FALSE, FALSE, NULL);
394 if (fcgi_event_handles[2] == NULL) {
395 ap_log_error(FCGI_LOG_ALERT, fcgi_apache_main_server,
396 "FastCGI: CreateEvent() failed");
399 /* Create the mbox mutex (PM - request threads) */
400 fcgi_dynamic_mbox_mutex = CreateMutex(NULL, FALSE, NULL);
401 if (fcgi_dynamic_mbox_mutex == NULL) {
402 ap_log_error(FCGI_LOG_ALERT, fcgi_apache_main_server,
403 "FastCGI: CreateMutex() failed");
406 /* Spawn of the process manager thread */
407 fcgi_pm_thread = (HANDLE) _beginthread(fcgi_pm_main, 0, NULL);
408 if (fcgi_pm_thread == (HANDLE) -1) {
409 ap_log_error(FCGI_LOG_ALERT, fcgi_apache_main_server,
410 "_beginthread() failed to spawn the process manager");
413 #ifdef APACHE2
414 apr_pool_cleanup_register(p, NULL, fcgi_child_exit, fcgi_child_exit);
415 #endif
416 #endif
420 *----------------------------------------------------------------------
422 * get_header_line --
424 * Terminate a line: scan to the next newline, scan back to the
425 * first non-space character and store a terminating zero. Return
426 * the next character past the end of the newline.
428 * If the end of the string is reached, ASSERT!
430 * If the FIRST character(s) in the line are '\n' or "\r\n", the
431 * first character is replaced with a NULL and next character
432 * past the newline is returned. NOTE: this condition supercedes
433 * the processing of RFC-822 continuation lines.
435 * If continuation is set to 'TRUE', then it parses a (possible)
436 * sequence of RFC-822 continuation lines.
438 * Results:
439 * As above.
441 * Side effects:
442 * Termination byte stored in string.
444 *----------------------------------------------------------------------
446 static char *get_header_line(char *start, int continuation)
448 char *p = start;
449 char *end = start;
451 if(p[0] == '\r' && p[1] == '\n') { /* If EOL in 1st 2 chars */
452 p++; /* point to \n and stop */
453 } else if(*p != '\n') {
454 if(continuation) {
455 while(*p != '\0') {
456 if(*p == '\n' && p[1] != ' ' && p[1] != '\t')
457 break;
458 p++;
460 } else {
461 while(*p != '\0' && *p != '\n') {
462 p++;
467 ap_assert(*p != '\0');
468 end = p;
469 end++;
472 * Trim any trailing whitespace.
474 while(isspace((unsigned char)p[-1]) && p > start) {
475 p--;
478 *p = '\0';
479 return end;
482 #ifdef WIN32
484 static int set_nonblocking(const fcgi_request * fr, int nonblocking)
486 if (fr->using_npipe_io)
488 if (nonblocking)
490 DWORD mode = PIPE_NOWAIT | PIPE_READMODE_BYTE;
491 if (SetNamedPipeHandleState((HANDLE) fr->fd, &mode, NULL, NULL) == 0)
493 ap_log_rerror(FCGI_LOG_ERR, fr->r,
494 "FastCGI: SetNamedPipeHandleState() failed");
495 return -1;
499 else
501 unsigned long ioctl_arg = (nonblocking) ? 1 : 0;
502 if (ioctlsocket(fr->fd, FIONBIO, &ioctl_arg) != 0)
504 errno = WSAGetLastError();
505 ap_log_rerror(FCGI_LOG_ERR_ERRNO, fr->r,
506 "FastCGI: ioctlsocket() failed");
507 return -1;
511 return 0;
514 #else
516 static int set_nonblocking(const fcgi_request * fr, int nonblocking)
518 int nb_flag = 0;
519 int fd_flags = fcntl(fr->fd, F_GETFL, 0);
521 if (fd_flags < 0) return -1;
523 #if defined(O_NONBLOCK)
524 nb_flag = O_NONBLOCK;
525 #elif defined(O_NDELAY)
526 nb_flag = O_NDELAY;
527 #elif defined(FNDELAY)
528 nb_flag = FNDELAY;
529 #else
530 #error "TODO - don't read from app until all data from client is posted."
531 #endif
533 fd_flags = (nonblocking) ? (fd_flags | nb_flag) : (fd_flags & ~nb_flag);
535 return fcntl(fr->fd, F_SETFL, fd_flags);
538 #endif
540 /*******************************************************************************
541 * Close the connection to the FastCGI server. This is normally called by
542 * do_work(), but may also be called as in request pool cleanup.
544 static void close_connection_to_fs(fcgi_request *fr)
546 #ifdef WIN32
548 if (fr->fd != INVALID_SOCKET)
550 set_nonblocking(fr, FALSE);
552 if (fr->using_npipe_io)
554 CloseHandle((HANDLE) fr->fd);
556 else
558 /* abort the connection entirely */
559 struct linger linger = {0, 0};
560 setsockopt(fr->fd, SOL_SOCKET, SO_LINGER, (void *) &linger, sizeof(linger));
561 closesocket(fr->fd);
564 fr->fd = INVALID_SOCKET;
566 #else /* ! WIN32 */
568 if (fr->fd >= 0)
570 struct linger linger = {0, 0};
571 set_nonblocking(fr, FALSE);
572 /* abort the connection entirely */
573 setsockopt(fr->fd, SOL_SOCKET, SO_LINGER, &linger, sizeof(linger));
574 close(fr->fd);
575 fr->fd = -1;
577 #endif /* ! WIN32 */
579 if (fr->dynamic && fr->keepReadingFromFcgiApp == FALSE)
581 /* XXX FCGI_REQUEST_COMPLETE_JOB is only sent for requests which complete
582 * normally WRT the fcgi app. There is no data sent for
583 * connect() timeouts or requests which complete abnormally.
584 * KillDynamicProcs() and RemoveRecords() need to be looked at
585 * to be sure they can reasonably handle these cases before
586 * sending these sort of stats - theres some funk in there.
588 if (fcgi_util_ticks(&fr->completeTime) < 0)
590 /* there's no point to aborting the request, just log it */
591 ap_log_error(FCGI_LOG_ERR, fr->r->server, "FastCGI: can't get time of day");
599 *----------------------------------------------------------------------
601 * process_headers --
603 * Call with r->parseHeader == SCAN_CGI_READING_HEADERS
604 * and initial script output in fr->header.
606 * If the initial script output does not include the header
607 * terminator ("\r\n\r\n") process_headers returns with no side
608 * effects, to be called again when more script output
609 * has been appended to fr->header.
611 * If the initial script output includes the header terminator,
612 * process_headers parses the headers and determines whether or
613 * not the remaining script output will be sent to the client.
614 * If so, process_headers sends the HTTP response headers to the
615 * client and copies any non-header script output to the output
616 * buffer reqOutbuf.
618 * Results:
619 * none.
621 * Side effects:
622 * May set r->parseHeader to:
623 * SCAN_CGI_FINISHED -- headers parsed, returning script response
624 * SCAN_CGI_BAD_HEADER -- malformed header from script
625 * SCAN_CGI_INT_REDIRECT -- handler should perform internal redirect
626 * SCAN_CGI_SRV_REDIRECT -- handler should return REDIRECT
628 *----------------------------------------------------------------------
631 static const char *process_headers(request_rec *r, fcgi_request *fr)
633 char *p, *next, *name, *value;
634 int len, flag;
635 int hasContentType, hasStatus, hasLocation;
637 ap_assert(fr->parseHeader == SCAN_CGI_READING_HEADERS);
639 if (fr->header == NULL)
640 return NULL;
643 * Do we have the entire header? Scan for the blank line that
644 * terminates the header.
646 p = (char *)fr->header->elts;
647 len = fr->header->nelts;
648 flag = 0;
649 while(len-- && flag < 2) {
650 switch(*p) {
651 case '\r':
652 break;
653 case '\n':
654 flag++;
655 break;
656 case '\0':
657 case '\v':
658 case '\f':
659 name = "Invalid Character";
660 goto BadHeader;
661 break;
662 default:
663 flag = 0;
664 break;
666 p++;
669 /* Return (to be called later when we have more data)
670 * if we don't have an entire header. */
671 if (flag < 2)
672 return NULL;
675 * Parse all the headers.
677 fr->parseHeader = SCAN_CGI_FINISHED;
678 hasContentType = hasStatus = hasLocation = FALSE;
679 next = (char *)fr->header->elts;
680 for(;;) {
681 next = get_header_line(name = next, TRUE);
682 if (*name == '\0') {
683 break;
685 if ((p = strchr(name, ':')) == NULL) {
686 goto BadHeader;
688 value = p + 1;
689 while (p != name && isspace((unsigned char)*(p - 1))) {
690 p--;
692 if (p == name) {
693 goto BadHeader;
695 *p = '\0';
696 if (strpbrk(name, " \t") != NULL) {
697 *p = ' ';
698 goto BadHeader;
700 while (isspace((unsigned char)*value)) {
701 value++;
704 if (strcasecmp(name, "Status") == 0) {
705 int statusValue = strtol(value, NULL, 10);
707 if (hasStatus) {
708 goto DuplicateNotAllowed;
710 if (statusValue < 0) {
711 fr->parseHeader = SCAN_CGI_BAD_HEADER;
712 return ap_psprintf(r->pool, "invalid Status '%s'", value);
714 hasStatus = TRUE;
715 r->status = statusValue;
716 r->status_line = ap_pstrdup(r->pool, value);
717 continue;
720 if (fr->role == FCGI_RESPONDER) {
721 if (strcasecmp(name, "Content-type") == 0) {
722 if (hasContentType) {
723 goto DuplicateNotAllowed;
725 hasContentType = TRUE;
726 r->content_type = ap_pstrdup(r->pool, value);
727 continue;
730 if (strcasecmp(name, "Location") == 0) {
731 if (hasLocation) {
732 goto DuplicateNotAllowed;
734 hasLocation = TRUE;
735 ap_table_set(r->headers_out, "Location", value);
736 continue;
739 /* If the script wants them merged, it can do it */
740 ap_table_add(r->err_headers_out, name, value);
741 continue;
743 else {
744 ap_table_add(fr->authHeaders, name, value);
748 if (fr->role != FCGI_RESPONDER)
749 return NULL;
752 * Who responds, this handler or Apache?
754 if (hasLocation) {
755 const char *location = ap_table_get(r->headers_out, "Location");
757 * Based on internal redirect handling in mod_cgi.c...
759 * If a script wants to produce its own Redirect
760 * body, it now has to explicitly *say* "Status: 302"
762 if (r->status == 200) {
763 if(location[0] == '/') {
765 * Location is an relative path. This handler will
766 * consume all script output, then have Apache perform an
767 * internal redirect.
769 fr->parseHeader = SCAN_CGI_INT_REDIRECT;
770 return NULL;
771 } else {
773 * Location is an absolute URL. If the script didn't
774 * produce a Content-type header, this handler will
775 * consume all script output and then have Apache generate
776 * its standard redirect response. Otherwise this handler
777 * will transmit the script's response.
779 fr->parseHeader = SCAN_CGI_SRV_REDIRECT;
780 return NULL;
785 * We're responding. Send headers, buffer excess script output.
787 ap_send_http_header(r);
789 /* We need to reinstate our timeout, send_http_header() kill()s it */
790 ap_hard_timeout("FastCGI request processing", r);
792 if (r->header_only) {
793 /* we've got all we want from the server */
794 close_connection_to_fs(fr);
795 fr->exitStatusSet = 1;
796 fcgi_buf_reset(fr->clientOutputBuffer);
797 fcgi_buf_reset(fr->serverOutputBuffer);
798 return NULL;
801 len = fr->header->nelts - (next - fr->header->elts);
802 ap_assert(len >= 0);
803 ap_assert(BufferLength(fr->clientOutputBuffer) == 0);
804 if (BufferFree(fr->clientOutputBuffer) < len) {
805 fr->clientOutputBuffer = fcgi_buf_new(r->pool, len);
807 ap_assert(BufferFree(fr->clientOutputBuffer) >= len);
808 if (len > 0) {
809 int sent = fcgi_buf_add_block(fr->clientOutputBuffer, next, len);
810 ap_assert(sent == len);
812 return NULL;
814 BadHeader:
815 /* Log first line of a multi-line header */
816 if ((p = strpbrk(name, "\r\n")) != NULL)
817 *p = '\0';
818 fr->parseHeader = SCAN_CGI_BAD_HEADER;
819 return ap_psprintf(r->pool, "malformed header '%s'", name);
821 DuplicateNotAllowed:
822 fr->parseHeader = SCAN_CGI_BAD_HEADER;
823 return ap_psprintf(r->pool, "duplicate header '%s'", name);
827 * Read from the client filling both the FastCGI server buffer and the
828 * client buffer with the hopes of buffering the client data before
829 * making the connect() to the FastCGI server. This prevents slow
830 * clients from keeping the FastCGI server in processing longer than is
831 * necessary.
833 static int read_from_client_n_queue(fcgi_request *fr)
835 char *end;
836 int count;
837 long int countRead;
839 while (BufferFree(fr->clientInputBuffer) > 0 || BufferFree(fr->serverOutputBuffer) > 0) {
840 fcgi_protocol_queue_client_buffer(fr);
842 if (fr->expectingClientContent <= 0)
843 return OK;
845 fcgi_buf_get_free_block_info(fr->clientInputBuffer, &end, &count);
846 if (count == 0)
847 return OK;
849 if ((countRead = ap_get_client_block(fr->r, end, count)) < 0)
850 return -1;
852 if (countRead == 0) {
853 fr->expectingClientContent = 0;
855 else {
856 fcgi_buf_add_update(fr->clientInputBuffer, countRead);
857 ap_reset_timeout(fr->r);
860 return OK;
863 static int write_to_client(fcgi_request *fr)
865 char *begin;
866 int count;
867 int rv;
868 #ifdef APACHE2
869 apr_bucket * bkt;
870 apr_bucket_brigade * bde;
871 apr_bucket_alloc_t * const bkt_alloc = fr->r->connection->bucket_alloc;
872 #endif
874 fcgi_buf_get_block_info(fr->clientOutputBuffer, &begin, &count);
875 if (count == 0)
876 return OK;
878 /* If fewer than count bytes are written, an error occured.
879 * ap_bwrite() typically forces a flushed write to the client, this
880 * effectively results in a block (and short packets) - it should
881 * be fixed, but I didn't win much support for the idea on new-httpd.
882 * So, without patching Apache, the best way to deal with this is
883 * to size the fcgi_bufs to hold all of the script output (within
884 * reason) so the script can be released from having to wait around
885 * for the transmission to the client to complete. */
887 #ifdef APACHE2
889 bde = apr_brigade_create(fr->r->pool, bkt_alloc);
890 bkt = apr_bucket_transient_create(begin, count, bkt_alloc);
891 APR_BRIGADE_INSERT_TAIL(bde, bkt);
893 if (fr->fs ? fr->fs->flush : dynamicFlush)
895 bkt = apr_bucket_flush_create(bkt_alloc);
896 APR_BRIGADE_INSERT_TAIL(bde, bkt);
899 rv = ap_pass_brigade(fr->r->output_filters, bde);
901 #elif defined(RUSSIAN_APACHE)
903 rv = (ap_rwrite(begin, count, fr->r) != count);
905 #else
907 rv = (ap_bwrite(fr->r->connection->client, begin, count) != count);
909 #endif
911 if (rv)
913 ap_log_rerror(FCGI_LOG_INFO_NOERRNO, fr->r,
914 "FastCGI: client stopped connection before send body completed");
915 return -1;
918 #ifndef APACHE2
920 ap_reset_timeout(fr->r);
922 /* Don't bother with a wrapped buffer, limiting exposure to slow
923 * clients. The BUFF routines don't allow a writev from above,
924 * and don't always memcpy to minimize small write()s, this should
925 * be fixed, but I didn't win much support for the idea on
926 * new-httpd - I'll have to _prove_ its a problem first.. */
928 /* The default behaviour used to be to flush with every write, but this
929 * can tie up the FastCGI server longer than is necessary so its an option now */
931 if (fr->fs ? fr->fs->flush : dynamicFlush)
933 #ifdef RUSSIAN_APACHE
934 rv = ap_rflush(fr->r);
935 #else
936 rv = ap_bflush(fr->r->connection->client);
937 #endif
939 if (rv)
941 ap_log_rerror(FCGI_LOG_INFO_NOERRNO, fr->r,
942 "FastCGI: client stopped connection before send body completed");
943 return -1;
946 ap_reset_timeout(fr->r);
949 #endif /* !APACHE2 */
951 fcgi_buf_toss(fr->clientOutputBuffer, count);
952 return OK;
955 /*******************************************************************************
956 * Determine the user and group the wrapper should be called with.
957 * Based on code in Apache's create_argv_cmd() (util_script.c).
959 static void set_uid_n_gid(request_rec *r, const char **user, const char **group)
961 if (fcgi_wrapper == NULL) {
962 *user = "-";
963 *group = "-";
964 return;
967 if (strncmp("/~", r->uri, 2) == 0) {
968 /* its a user dir uri, just send the ~user, and leave it to the PM */
969 char *end = strchr(r->uri + 2, '/');
971 if (end)
972 *user = memcpy(ap_pcalloc(r->pool, end - r->uri), r->uri + 1, end - r->uri - 1);
973 else
974 *user = ap_pstrdup(r->pool, r->uri + 1);
975 *group = "-";
977 else {
978 *user = ap_psprintf(r->pool, "%ld", (long) fcgi_util_get_server_uid(r->server));
979 *group = ap_psprintf(r->pool, "%ld", (long) fcgi_util_get_server_gid(r->server));
983 static void send_request_complete(fcgi_request *fr)
985 if (fr->completeTime.tv_sec)
987 struct timeval qtime, rtime;
989 timersub(&fr->queueTime, &fr->startTime, &qtime);
990 timersub(&fr->completeTime, &fr->queueTime, &rtime);
992 send_to_pm(FCGI_REQUEST_COMPLETE_JOB, fr->fs_path,
993 fr->user, fr->group,
994 qtime.tv_sec * 1000000 + qtime.tv_usec,
995 rtime.tv_sec * 1000000 + rtime.tv_usec);
1000 /*******************************************************************************
1001 * Connect to the FastCGI server.
1003 static int open_connection_to_fs(fcgi_request *fr)
1005 struct timeval tval;
1006 fd_set write_fds, read_fds;
1007 int status;
1008 request_rec * const r = fr->r;
1009 pool * const rp = r->pool;
1010 const char *socket_path = NULL;
1011 struct sockaddr *socket_addr = NULL;
1012 int socket_addr_len = 0;
1013 #ifndef WIN32
1014 const char *err = NULL;
1015 #endif
1017 /* Create the connection point */
1018 if (fr->dynamic)
1020 socket_path = fcgi_util_socket_hash_filename(rp, fr->fs_path, fr->user, fr->group);
1021 socket_path = fcgi_util_socket_make_path_absolute(rp, socket_path, 1);
1023 #ifndef WIN32
1024 err = fcgi_util_socket_make_domain_addr(rp, (struct sockaddr_un **)&socket_addr,
1025 &socket_addr_len, socket_path);
1026 if (err) {
1027 ap_log_rerror(FCGI_LOG_ERR, r,
1028 "FastCGI: failed to connect to (dynamic) server \"%s\": "
1029 "%s", fr->fs_path, err);
1030 return FCGI_FAILED;
1032 #endif
1034 else
1036 #ifdef WIN32
1037 if (fr->fs->dest_addr != NULL) {
1038 socket_addr = fr->fs->dest_addr;
1040 else if (fr->fs->socket_addr) {
1041 socket_addr = fr->fs->socket_addr;
1043 else {
1044 socket_path = fr->fs->socket_path;
1046 #else
1047 socket_addr = fr->fs->socket_addr;
1048 #endif
1049 socket_addr_len = fr->fs->socket_addr_len;
1052 if (fr->dynamic)
1054 #ifdef WIN32
1055 if (fr->fs && fr->fs->restartTime)
1056 #else
1057 struct stat sock_stat;
1059 if (stat(socket_path, &sock_stat) == 0)
1060 #endif
1062 // It exists
1063 if (dynamicAutoUpdate)
1065 struct stat app_stat;
1067 /* TODO: follow sym links */
1069 if (stat(fr->fs_path, &app_stat) == 0)
1071 #ifdef WIN32
1072 if (fr->fs->startTime < app_stat.st_mtime)
1073 #else
1074 if (sock_stat.st_mtime < app_stat.st_mtime)
1075 #endif
1077 #ifndef WIN32
1078 struct timeval tv = {1, 0};
1079 #endif
1081 * There's a newer one, request a restart.
1083 send_to_pm(FCGI_SERVER_RESTART_JOB, fr->fs_path, fr->user, fr->group, 0, 0);
1085 #ifdef WIN32
1086 Sleep(1000);
1087 #else
1088 /* Avoid sleep/alarm interactions */
1089 ap_select(0, NULL, NULL, NULL, &tv);
1090 #endif
1095 else
1097 int i;
1099 send_to_pm(FCGI_SERVER_START_JOB, fr->fs_path, fr->user, fr->group, 0, 0);
1101 /* wait until it looks like its running - this shouldn't take
1102 * very long at all - the exception is when the sockets are
1103 * removed out from under a running application - the loop
1104 * limit addresses this (preventing spinning) */
1106 for (i = 10; i > 0; i--)
1108 #ifdef WIN32
1109 Sleep(500);
1111 fr->fs = fcgi_util_fs_get_by_id(fr->fs_path, 0, 0);
1113 if (fr->fs && fr->fs->restartTime)
1114 #else
1115 struct timeval tv = {0, 500000};
1117 /* Avoid sleep/alarm interactions */
1118 ap_select(0, NULL, NULL, NULL, &tv);
1120 if (stat(socket_path, &sock_stat) == 0)
1121 #endif
1123 break;
1127 if (i <= 0)
1129 ap_log_rerror(FCGI_LOG_ALERT, r,
1130 "FastCGI: failed to connect to (dynamic) server \"%s\": "
1131 "something is seriously wrong, any chance the "
1132 "socket/named_pipe directory was removed?, see the "
1133 "FastCgiIpcDir directive", fr->fs_path);
1134 return FCGI_FAILED;
1139 #ifdef WIN32
1140 if (socket_path)
1142 BOOL ready;
1143 DWORD connect_time;
1144 int rv;
1145 HANDLE wait_npipe_mutex;
1146 DWORD interval;
1147 DWORD max_connect_time = FCGI_NAMED_PIPE_CONNECT_TIMEOUT;
1149 fr->using_npipe_io = TRUE;
1151 if (fr->dynamic)
1153 interval = dynamicPleaseStartDelay * 1000;
1155 if (dynamicAppConnectTimeout) {
1156 max_connect_time = dynamicAppConnectTimeout;
1159 else
1161 interval = FCGI_NAMED_PIPE_CONNECT_TIMEOUT * 1000;
1163 if (fr->fs->appConnectTimeout) {
1164 max_connect_time = fr->fs->appConnectTimeout;
1168 fcgi_util_ticks(&fr->startTime);
1171 // xxx this handle should live somewhere (see CloseHandle()s below too)
1172 char * wait_npipe_mutex_name, * cp;
1173 wait_npipe_mutex_name = cp = ap_pstrdup(rp, socket_path);
1174 while ((cp = strchr(cp, '\\'))) *cp = '/';
1176 wait_npipe_mutex = CreateMutex(NULL, FALSE, wait_npipe_mutex_name);
1179 if (wait_npipe_mutex == NULL)
1181 ap_log_rerror(FCGI_LOG_ERR, r,
1182 "FastCGI: failed to connect to server \"%s\": "
1183 "can't create the WaitNamedPipe mutex", fr->fs_path);
1184 return FCGI_FAILED;
1187 SetLastError(ERROR_SUCCESS);
1189 rv = WaitForSingleObject(wait_npipe_mutex, max_connect_time * 1000);
1191 if (rv == WAIT_TIMEOUT || rv == WAIT_FAILED)
1193 if (fr->dynamic)
1195 send_to_pm(FCGI_REQUEST_TIMEOUT_JOB, fr->fs_path, fr->user, fr->group, 0, 0);
1197 ap_log_rerror(FCGI_LOG_ERR_NOERRNO, r,
1198 "FastCGI: failed to connect to server \"%s\": "
1199 "wait for a npipe instance failed", fr->fs_path);
1200 FCGIDBG3("interval=%d, max_connect_time=%d", interval, max_connect_time);
1201 CloseHandle(wait_npipe_mutex);
1202 return FCGI_FAILED;
1205 fcgi_util_ticks(&fr->queueTime);
1207 connect_time = fr->queueTime.tv_sec - fr->startTime.tv_sec;
1209 if (fr->dynamic)
1211 if (connect_time >= interval)
1213 send_to_pm(FCGI_REQUEST_TIMEOUT_JOB, fr->fs_path, fr->user, fr->group, 0, 0);
1214 FCGIDBG4("connect_time=%d, interval=%d, max_connect_time=%d", connect_time, interval, max_connect_time);
1216 if (max_connect_time - connect_time < interval)
1218 interval = max_connect_time - connect_time;
1221 else
1223 interval -= connect_time * 1000;
1226 for (;;)
1228 ready = WaitNamedPipe(socket_path, interval);
1230 if (ready)
1232 fr->fd = (SOCKET) CreateFile(socket_path,
1233 GENERIC_READ | GENERIC_WRITE,
1234 FILE_SHARE_READ | FILE_SHARE_WRITE,
1235 NULL, // no security attributes
1236 OPEN_EXISTING, // opens existing pipe
1237 FILE_FLAG_OVERLAPPED,
1238 NULL); // no template file
1240 if (fr->fd != (SOCKET) INVALID_HANDLE_VALUE)
1242 ReleaseMutex(wait_npipe_mutex);
1243 CloseHandle(wait_npipe_mutex);
1244 fcgi_util_ticks(&fr->queueTime);
1245 FCGIDBG2("got npipe connect: %s", fr->fs_path);
1246 return FCGI_OK;
1249 if (GetLastError() != ERROR_PIPE_BUSY
1250 && GetLastError() != ERROR_FILE_NOT_FOUND)
1252 ap_log_rerror(FCGI_LOG_ERR, r,
1253 "FastCGI: failed to connect to server \"%s\": "
1254 "CreateFile() failed", fr->fs_path);
1255 break;
1258 FCGIDBG2("missed npipe connect: %s", fr->fs_path);
1261 if (fr->dynamic)
1263 send_to_pm(FCGI_REQUEST_TIMEOUT_JOB, fr->fs_path, fr->user, fr->group, 0, 0);
1266 fcgi_util_ticks(&fr->queueTime);
1268 connect_time = fr->queueTime.tv_sec - fr->startTime.tv_sec;
1270 FCGIDBG5("interval=%d, max_connect_time=%d, connect_time=%d, ready=%d", interval, max_connect_time, connect_time, ready);
1272 if (connect_time >= max_connect_time)
1274 ap_log_rerror(FCGI_LOG_ERR, r,
1275 "FastCGI: failed to connect to server \"%s\": "
1276 "CreateFile()/WaitNamedPipe() timed out", fr->fs_path);
1277 break;
1281 ReleaseMutex(wait_npipe_mutex);
1282 CloseHandle(wait_npipe_mutex);
1283 fr->fd = INVALID_SOCKET;
1284 return FCGI_FAILED;
1287 #endif
1289 /* Create the socket */
1290 fr->fd = socket(socket_addr->sa_family, SOCK_STREAM, 0);
1292 #ifdef WIN32
1293 if (fr->fd == INVALID_SOCKET) {
1294 errno = WSAGetLastError(); // Not sure this is going to work as expected
1295 #else
1296 if (fr->fd < 0) {
1297 #endif
1298 ap_log_rerror(FCGI_LOG_ERR_ERRNO, r,
1299 "FastCGI: failed to connect to server \"%s\": "
1300 "socket() failed", fr->fs_path);
1301 return FCGI_FAILED;
1304 #ifndef WIN32
1305 if (fr->fd >= FD_SETSIZE) {
1306 ap_log_rerror(FCGI_LOG_ERR, r,
1307 "FastCGI: failed to connect to server \"%s\": "
1308 "socket file descriptor (%u) is larger than "
1309 "FD_SETSIZE (%u), you probably need to rebuild Apache with a "
1310 "larger FD_SETSIZE", fr->fs_path, fr->fd, FD_SETSIZE);
1311 return FCGI_FAILED;
1313 #endif
1315 /* If appConnectTimeout is non-zero, setup do a non-blocking connect */
1316 if ((fr->dynamic && dynamicAppConnectTimeout) || (!fr->dynamic && fr->fs->appConnectTimeout)) {
1317 set_nonblocking(fr, TRUE);
1320 if (fr->dynamic) {
1321 fcgi_util_ticks(&fr->startTime);
1324 /* Connect */
1325 if (connect(fr->fd, (struct sockaddr *)socket_addr, socket_addr_len) == 0)
1326 goto ConnectionComplete;
1328 #ifdef WIN32
1330 errno = WSAGetLastError();
1331 if (errno != WSAEWOULDBLOCK) {
1332 ap_log_rerror(FCGI_LOG_ERR_ERRNO, r,
1333 "FastCGI: failed to connect to server \"%s\": "
1334 "connect() failed", fr->fs_path);
1335 return FCGI_FAILED;
1338 #else
1340 /* ECONNREFUSED means the listen queue is full (or there isn't one).
1341 * With dynamic I can at least make sure the PM knows this is occuring */
1342 if (fr->dynamic && errno == ECONNREFUSED) {
1343 /* @@@ This might be better as some other "kind" of message */
1344 send_to_pm(FCGI_REQUEST_TIMEOUT_JOB, fr->fs_path, fr->user, fr->group, 0, 0);
1346 errno = ECONNREFUSED;
1349 if (errno != EINPROGRESS) {
1350 ap_log_rerror(FCGI_LOG_ERR, r,
1351 "FastCGI: failed to connect to server \"%s\": "
1352 "connect() failed", fr->fs_path);
1353 return FCGI_FAILED;
1356 #endif
1358 /* The connect() is non-blocking */
1360 errno = 0;
1362 if (fr->dynamic) {
1363 do {
1364 FD_ZERO(&write_fds);
1365 FD_SET(fr->fd, &write_fds);
1366 read_fds = write_fds;
1367 tval.tv_sec = dynamicPleaseStartDelay;
1368 tval.tv_usec = 0;
1370 status = ap_select((fr->fd+1), &read_fds, &write_fds, NULL, &tval);
1371 if (status < 0)
1372 break;
1374 fcgi_util_ticks(&fr->queueTime);
1376 if (status > 0)
1377 break;
1379 /* select() timed out */
1380 send_to_pm(FCGI_REQUEST_TIMEOUT_JOB, fr->fs_path, fr->user, fr->group, 0, 0);
1381 } while ((fr->queueTime.tv_sec - fr->startTime.tv_sec) < (int)dynamicAppConnectTimeout);
1383 /* XXX These can be moved down when dynamic vars live is a struct */
1384 if (status == 0) {
1385 ap_log_rerror(FCGI_LOG_ERR_NOERRNO, r,
1386 "FastCGI: failed to connect to server \"%s\": "
1387 "connect() timed out (appConnTimeout=%dsec)",
1388 fr->fs_path, dynamicAppConnectTimeout);
1389 return FCGI_FAILED;
1391 } /* dynamic */
1392 else {
1393 tval.tv_sec = fr->fs->appConnectTimeout;
1394 tval.tv_usec = 0;
1395 FD_ZERO(&write_fds);
1396 FD_SET(fr->fd, &write_fds);
1397 read_fds = write_fds;
1399 status = ap_select((fr->fd+1), &read_fds, &write_fds, NULL, &tval);
1401 if (status == 0) {
1402 ap_log_rerror(FCGI_LOG_ERR_NOERRNO, r,
1403 "FastCGI: failed to connect to server \"%s\": "
1404 "connect() timed out (appConnTimeout=%dsec)",
1405 fr->fs_path, dynamicAppConnectTimeout);
1406 return FCGI_FAILED;
1408 } /* !dynamic */
1410 if (status < 0) {
1411 #ifdef WIN32
1412 errno = WSAGetLastError();
1413 #endif
1414 ap_log_rerror(FCGI_LOG_ERR_ERRNO, r,
1415 "FastCGI: failed to connect to server \"%s\": "
1416 "select() failed", fr->fs_path);
1417 return FCGI_FAILED;
1420 if (FD_ISSET(fr->fd, &write_fds) || FD_ISSET(fr->fd, &read_fds)) {
1421 int error = 0;
1422 NET_SIZE_T len = sizeof(error);
1424 if (getsockopt(fr->fd, SOL_SOCKET, SO_ERROR, (char *)&error, &len) < 0) {
1425 /* Solaris pending error */
1426 #ifdef WIN32
1427 errno = WSAGetLastError();
1428 #endif
1429 ap_log_rerror(FCGI_LOG_ERR_ERRNO, r,
1430 "FastCGI: failed to connect to server \"%s\": "
1431 "select() failed (Solaris pending error)", fr->fs_path);
1432 return FCGI_FAILED;
1435 if (error != 0) {
1436 /* Berkeley-derived pending error */
1437 errno = error;
1438 ap_log_rerror(FCGI_LOG_ERR_ERRNO, r,
1439 "FastCGI: failed to connect to server \"%s\": "
1440 "select() failed (pending error)", fr->fs_path);
1441 return FCGI_FAILED;
1444 else {
1445 #ifdef WIN32
1446 errno = WSAGetLastError();
1447 #endif
1448 ap_log_rerror(FCGI_LOG_ERR_ERRNO, r,
1449 "FastCGI: failed to connect to server \"%s\": "
1450 "select() error - THIS CAN'T HAPPEN!", fr->fs_path);
1451 return FCGI_FAILED;
1454 ConnectionComplete:
1455 /* Return to blocking mode if it was set up */
1456 if ((fr->dynamic && dynamicAppConnectTimeout) || (!fr->dynamic && fr->fs->appConnectTimeout)) {
1457 set_nonblocking(fr, FALSE);
1460 #ifdef TCP_NODELAY
1461 if (socket_addr->sa_family == AF_INET) {
1462 /* We shouldn't be sending small packets and there's no application
1463 * level ack of the data we send, so disable Nagle */
1464 int set = 1;
1465 setsockopt(fr->fd, IPPROTO_TCP, TCP_NODELAY, (char *)&set, sizeof(set));
1467 #endif
1469 return FCGI_OK;
1472 static void sink_client_data(fcgi_request *fr)
1474 char *base;
1475 int size;
1477 fcgi_buf_reset(fr->clientInputBuffer);
1478 fcgi_buf_get_free_block_info(fr->clientInputBuffer, &base, &size);
1479 while (ap_get_client_block(fr->r, base, size) > 0);
1482 static apcb_t cleanup(void *data)
1484 fcgi_request * const fr = (fcgi_request *) data;
1486 if (fr == NULL) return APCB_OK;
1488 /* its more than likely already run, but... */
1489 close_connection_to_fs(fr);
1491 send_request_complete(fr);
1493 if (fr->fs_stderr_len) {
1494 ap_log_rerror(FCGI_LOG_ERR_NOERRNO, fr->r,
1495 "FastCGI: server \"%s\" stderr: %s", fr->fs_path, fr->fs_stderr);
1498 return APCB_OK;
1501 #ifdef WIN32
1502 static int npipe_io(fcgi_request * const fr)
1504 request_rec * const r = fr->r;
1505 enum
1507 STATE_ENV_SEND,
1508 STATE_CLIENT_RECV,
1509 STATE_SERVER_SEND,
1510 STATE_SERVER_RECV,
1511 STATE_CLIENT_SEND,
1512 STATE_CLIENT_ERROR,
1513 STATE_ERROR
1515 state = STATE_ENV_SEND;
1516 env_status env_status;
1517 int client_recv;
1518 int dynamic_first_recv = fr->dynamic;
1519 int idle_timeout = fr->dynamic ? dynamic_idle_timeout : fr->fs->idle_timeout;
1520 int send_pending = 0;
1521 int recv_pending = 0;
1522 int client_send = 0;
1523 int rv;
1524 OVERLAPPED rov = { 0 };
1525 OVERLAPPED sov = { 0 };
1526 HANDLE events[2];
1527 struct timeval timeout;
1528 struct timeval dynamic_last_io_time = {0, 0};
1529 int did_io = 1;
1530 pool * const rp = r->pool;
1532 DWORD recv_count = 0;
1534 if (fr->role == FCGI_RESPONDER)
1536 client_recv = (fr->expectingClientContent != 0);
1539 idle_timeout = fr->dynamic ? dynamic_idle_timeout : fr->fs->idle_timeout;
1541 env_status.envp = NULL;
1543 events[0] = CreateEvent(NULL, TRUE, FALSE, NULL);
1544 events[1] = CreateEvent(NULL, TRUE, FALSE, NULL);
1545 sov.hEvent = events[0];
1546 rov.hEvent = events[1];
1548 if (fr->dynamic)
1550 dynamic_last_io_time = fr->startTime;
1552 if (dynamicAppConnectTimeout)
1554 struct timeval qwait;
1555 timersub(&fr->queueTime, &fr->startTime, &qwait);
1556 dynamic_first_recv = qwait.tv_sec / dynamicPleaseStartDelay + 1;
1560 ap_hard_timeout("FastCGI request processing", r);
1562 while (state != STATE_CLIENT_SEND)
1564 DWORD msec_timeout;
1566 switch (state)
1568 case STATE_ENV_SEND:
1570 if (fcgi_protocol_queue_env(r, fr, &env_status) == 0)
1572 goto SERVER_SEND;
1575 state = STATE_CLIENT_RECV;
1577 /* fall through */
1579 case STATE_CLIENT_RECV:
1581 if (read_from_client_n_queue(fr) != OK)
1583 state = STATE_CLIENT_ERROR;
1584 break;
1587 if (fr->eofSent)
1589 state = STATE_SERVER_SEND;
1592 /* fall through */
1594 SERVER_SEND:
1596 case STATE_SERVER_SEND:
1598 if (! send_pending && BufferLength(fr->serverOutputBuffer))
1600 Buffer * b = fr->serverOutputBuffer;
1601 DWORD sent, len;
1603 len = min(b->length, b->data + b->size - b->begin);
1605 if (WriteFile((HANDLE) fr->fd, b->begin, len, &sent, &sov))
1607 fcgi_buf_removed(b, sent);
1608 ResetEvent(sov.hEvent);
1610 else if (GetLastError() == ERROR_IO_PENDING)
1612 send_pending = 1;
1614 else
1616 ap_log_rerror(FCGI_LOG_ERR, r, "FastCGI: comm with server "
1617 "\"%s\" aborted: WriteFile() failed", fr->fs_path);
1618 state = STATE_ERROR;
1619 break;
1623 /* fall through */
1625 case STATE_SERVER_RECV:
1628 * Only get more data when the serverInputBuffer is empty.
1629 * Otherwise we may already have the END_REQUEST buffered
1630 * (but not processed) and a read on a closed named pipe
1631 * results in an error that is normally abnormal.
1633 if (! recv_pending && BufferLength(fr->serverInputBuffer) == 0)
1635 Buffer * b = fr->serverInputBuffer;
1636 DWORD rcvd, len;
1638 len = min(b->size - b->length, b->data + b->size - b->end);
1640 if (ReadFile((HANDLE) fr->fd, b->end, len, &rcvd, &rov))
1642 fcgi_buf_added(b, rcvd);
1643 recv_count += rcvd;
1644 ResetEvent(rov.hEvent);
1645 if (dynamic_first_recv)
1647 dynamic_first_recv = 0;
1650 else if (GetLastError() == ERROR_IO_PENDING)
1652 recv_pending = 1;
1654 else if (GetLastError() == ERROR_HANDLE_EOF)
1656 fr->keepReadingFromFcgiApp = FALSE;
1657 state = STATE_CLIENT_SEND;
1658 ResetEvent(rov.hEvent);
1659 break;
1661 else if (GetLastError() == ERROR_NO_DATA)
1663 break;
1665 else
1667 ap_log_rerror(FCGI_LOG_ERR, r, "FastCGI: comm with server "
1668 "\"%s\" aborted: ReadFile() failed", fr->fs_path);
1669 state = STATE_ERROR;
1670 break;
1674 /* fall through */
1676 case STATE_CLIENT_SEND:
1678 if (client_send || ! BufferFree(fr->clientOutputBuffer))
1680 if (write_to_client(fr))
1682 state = STATE_CLIENT_ERROR;
1683 break;
1686 client_send = 0;
1689 break;
1691 default:
1693 ap_assert(0);
1696 if (state == STATE_CLIENT_ERROR || state == STATE_ERROR)
1698 break;
1701 /* setup the io timeout */
1703 if (BufferLength(fr->clientOutputBuffer))
1705 /* don't let client data sit too long, it might be a push */
1706 timeout.tv_sec = 0;
1707 timeout.tv_usec = 100000;
1709 else if (dynamic_first_recv)
1711 int delay;
1712 struct timeval qwait;
1714 fcgi_util_ticks(&fr->queueTime);
1716 if (did_io)
1718 /* a send() succeeded last pass */
1719 dynamic_last_io_time = fr->queueTime;
1721 else
1723 /* timed out last pass */
1724 struct timeval idle_time;
1726 timersub(&fr->queueTime, &dynamic_last_io_time, &idle_time);
1728 if (idle_time.tv_sec > idle_timeout)
1730 send_to_pm(FCGI_REQUEST_TIMEOUT_JOB, fr->fs_path, fr->user, fr->group, 0, 0);
1731 ap_log_rerror(FCGI_LOG_ERR_NOERRNO, r, "FastCGI: comm "
1732 "with (dynamic) server \"%s\" aborted: (first read) "
1733 "idle timeout (%d sec)", fr->fs_path, idle_timeout);
1734 state = STATE_ERROR;
1735 break;
1739 timersub(&fr->queueTime, &fr->startTime, &qwait);
1741 delay = dynamic_first_recv * dynamicPleaseStartDelay;
1743 if (qwait.tv_sec < delay)
1745 timeout.tv_sec = delay;
1746 timeout.tv_usec = 100000; /* fudge for select() slop */
1747 timersub(&timeout, &qwait, &timeout);
1749 else
1751 /* Killed time somewhere.. client read? */
1752 send_to_pm(FCGI_REQUEST_TIMEOUT_JOB, fr->fs_path, fr->user, fr->group, 0, 0);
1753 dynamic_first_recv = qwait.tv_sec / dynamicPleaseStartDelay + 1;
1754 timeout.tv_sec = dynamic_first_recv * dynamicPleaseStartDelay;
1755 timeout.tv_usec = 100000; /* fudge for select() slop */
1756 timersub(&timeout, &qwait, &timeout);
1759 else
1761 timeout.tv_sec = idle_timeout;
1762 timeout.tv_usec = 0;
1765 /* require a pended recv otherwise the app can deadlock */
1766 if (recv_pending)
1768 msec_timeout = timeout.tv_sec * 1000 + timeout.tv_usec / 1000;
1770 rv = WaitForMultipleObjects(2, events, FALSE, msec_timeout);
1772 if (rv == WAIT_TIMEOUT)
1774 did_io = 0;
1776 if (BufferLength(fr->clientOutputBuffer))
1778 client_send = 1;
1780 else if (dynamic_first_recv)
1782 struct timeval qwait;
1784 fcgi_util_ticks(&fr->queueTime);
1785 timersub(&fr->queueTime, &fr->startTime, &qwait);
1787 send_to_pm(FCGI_REQUEST_TIMEOUT_JOB, fr->fs_path, fr->user, fr->group, 0, 0);
1789 dynamic_first_recv = qwait.tv_sec / dynamicPleaseStartDelay + 1;
1791 else
1793 ap_log_rerror(FCGI_LOG_ERR_NOERRNO, r, "FastCGI: comm with "
1794 "server \"%s\" aborted: idle timeout (%d sec)",
1795 fr->fs_path, idle_timeout);
1796 state = STATE_ERROR;
1797 break;
1800 else
1802 int i = rv - WAIT_OBJECT_0;
1804 did_io = 1;
1806 if (i == 0)
1808 DWORD sent;
1810 if (GetOverlappedResult((HANDLE) fr->fd, &sov, &sent, FALSE))
1812 send_pending = 0;
1813 ResetEvent(sov.hEvent);
1814 fcgi_buf_removed(fr->serverOutputBuffer, sent);
1816 else
1818 ap_log_rerror(FCGI_LOG_ERR, r, "FastCGI: comm with server "
1819 "\"%s\" aborted: GetOverlappedResult() failed", fr->fs_path);
1820 state = STATE_ERROR;
1821 break;
1824 else
1826 DWORD rcvd;
1828 ap_assert(i == 1);
1830 recv_pending = 0;
1831 ResetEvent(rov.hEvent);
1833 if (GetOverlappedResult((HANDLE) fr->fd, &rov, &rcvd, FALSE))
1835 fcgi_buf_added(fr->serverInputBuffer, rcvd);
1836 if (dynamic_first_recv)
1838 dynamic_first_recv = 0;
1841 else
1843 ap_log_rerror(FCGI_LOG_ERR, r, "FastCGI: comm with server "
1844 "\"%s\" aborted: GetOverlappedResult() failed", fr->fs_path);
1845 state = STATE_ERROR;
1846 break;
1852 if (fcgi_protocol_dequeue(rp, fr))
1854 state = STATE_ERROR;
1855 break;
1858 if (fr->parseHeader == SCAN_CGI_READING_HEADERS)
1860 const char * err = process_headers(r, fr);
1861 if (err)
1863 ap_log_rerror(FCGI_LOG_ERR_NOERRNO, r,
1864 "FastCGI: comm with server \"%s\" aborted: "
1865 "error parsing headers: %s", fr->fs_path, err);
1866 state = STATE_ERROR;
1867 break;
1871 if (fr->exitStatusSet)
1873 fr->keepReadingFromFcgiApp = FALSE;
1874 state = STATE_CLIENT_SEND;
1875 break;
1879 if (! fr->exitStatusSet || ! fr->eofSent)
1881 CancelIo((HANDLE) fr->fd);
1884 CloseHandle(rov.hEvent);
1885 CloseHandle(sov.hEvent);
1887 return (state == STATE_ERROR);
1889 #endif /* WIN32 */
1891 static int socket_io(fcgi_request * const fr)
1893 enum
1895 STATE_SOCKET_NONE,
1896 STATE_ENV_SEND,
1897 STATE_CLIENT_RECV,
1898 STATE_SERVER_SEND,
1899 STATE_SERVER_RECV,
1900 STATE_CLIENT_SEND,
1901 STATE_ERROR,
1902 STATE_CLIENT_ERROR
1904 state = STATE_ENV_SEND;
1906 request_rec * const r = fr->r;
1908 struct timeval timeout;
1909 struct timeval dynamic_last_io_time = {0, 0};
1910 fd_set read_set;
1911 fd_set write_set;
1912 int nfds = fr->fd + 1;
1913 int select_status = 1;
1914 int idle_timeout;
1915 int rv;
1916 int dynamic_first_recv = fr->dynamic ? 1 : 0;
1917 int client_send = FALSE;
1918 int client_recv = FALSE;
1919 env_status env;
1920 pool *rp = r->pool;
1922 if (fr->role == FCGI_RESPONDER)
1924 client_recv = (fr->expectingClientContent != 0);
1927 idle_timeout = fr->dynamic ? dynamic_idle_timeout : fr->fs->idle_timeout;
1929 env.envp = NULL;
1931 if (fr->dynamic)
1933 dynamic_last_io_time = fr->startTime;
1935 if (dynamicAppConnectTimeout)
1937 struct timeval qwait;
1938 timersub(&fr->queueTime, &fr->startTime, &qwait);
1939 dynamic_first_recv = qwait.tv_sec / dynamicPleaseStartDelay + 1;
1943 ap_hard_timeout("FastCGI request processing", r);
1945 set_nonblocking(fr, TRUE);
1947 for (;;)
1949 FD_ZERO(&read_set);
1950 FD_ZERO(&write_set);
1952 switch (state)
1954 case STATE_ENV_SEND:
1956 if (fcgi_protocol_queue_env(r, fr, &env) == 0)
1958 goto SERVER_SEND;
1961 state = STATE_CLIENT_RECV;
1963 /* fall through */
1965 case STATE_CLIENT_RECV:
1967 if (read_from_client_n_queue(fr))
1969 state = STATE_CLIENT_ERROR;
1970 break;
1973 if (fr->eofSent)
1975 state = STATE_SERVER_SEND;
1978 /* fall through */
1980 SERVER_SEND:
1982 case STATE_SERVER_SEND:
1984 if (BufferLength(fr->serverOutputBuffer))
1986 FD_SET(fr->fd, &write_set);
1988 else
1990 ap_assert(fr->eofSent);
1991 state = STATE_SERVER_RECV;
1994 /* fall through */
1996 case STATE_SERVER_RECV:
1998 FD_SET(fr->fd, &read_set);
2000 /* fall through */
2002 case STATE_CLIENT_SEND:
2004 if (client_send || ! BufferFree(fr->clientOutputBuffer))
2006 if (write_to_client(fr))
2008 state = STATE_CLIENT_ERROR;
2009 break;
2012 client_send = 0;
2015 break;
2017 case STATE_ERROR:
2018 case STATE_CLIENT_ERROR:
2020 break;
2022 default:
2024 ap_assert(0);
2027 if (state == STATE_CLIENT_ERROR || state == STATE_ERROR)
2029 break;
2032 /* setup the io timeout */
2034 if (BufferLength(fr->clientOutputBuffer))
2036 /* don't let client data sit too long, it might be a push */
2037 timeout.tv_sec = 0;
2038 timeout.tv_usec = 100000;
2040 else if (dynamic_first_recv)
2042 int delay;
2043 struct timeval qwait;
2045 fcgi_util_ticks(&fr->queueTime);
2047 if (select_status)
2049 /* a send() succeeded last pass */
2050 dynamic_last_io_time = fr->queueTime;
2052 else
2054 /* timed out last pass */
2055 struct timeval idle_time;
2057 timersub(&fr->queueTime, &dynamic_last_io_time, &idle_time);
2059 if (idle_time.tv_sec > idle_timeout)
2061 send_to_pm(FCGI_REQUEST_TIMEOUT_JOB, fr->fs_path, fr->user, fr->group, 0, 0);
2062 ap_log_rerror(FCGI_LOG_ERR_NOERRNO, r, "FastCGI: comm "
2063 "with (dynamic) server \"%s\" aborted: (first read) "
2064 "idle timeout (%d sec)", fr->fs_path, idle_timeout);
2065 state = STATE_ERROR;
2066 break;
2070 timersub(&fr->queueTime, &fr->startTime, &qwait);
2072 delay = dynamic_first_recv * dynamicPleaseStartDelay;
2074 FCGIDBG5("qwait=%ld.%06ld delay=%d first_recv=%d", qwait.tv_sec, qwait.tv_usec, delay, dynamic_first_recv);
2076 if (qwait.tv_sec < delay)
2078 timeout.tv_sec = delay;
2079 timeout.tv_usec = 100000; /* fudge for select() slop */
2080 timersub(&timeout, &qwait, &timeout);
2082 else
2084 /* Killed time somewhere.. client read? */
2085 send_to_pm(FCGI_REQUEST_TIMEOUT_JOB, fr->fs_path, fr->user, fr->group, 0, 0);
2086 dynamic_first_recv = qwait.tv_sec / dynamicPleaseStartDelay + 1;
2087 timeout.tv_sec = dynamic_first_recv * dynamicPleaseStartDelay;
2088 timeout.tv_usec = 100000; /* fudge for select() slop */
2089 timersub(&timeout, &qwait, &timeout);
2092 else
2094 timeout.tv_sec = idle_timeout;
2095 timeout.tv_usec = 0;
2098 /* wait on the socket */
2099 select_status = ap_select(nfds, &read_set, &write_set, NULL, &timeout);
2101 if (select_status < 0)
2103 ap_log_rerror(FCGI_LOG_ERR_ERRNO, r, "FastCGI: comm with server "
2104 "\"%s\" aborted: select() failed", fr->fs_path);
2105 state = STATE_ERROR;
2106 break;
2109 if (select_status == 0)
2111 /* select() timeout */
2113 if (BufferLength(fr->clientOutputBuffer))
2115 if (fr->role == FCGI_RESPONDER)
2117 client_send = TRUE;
2120 else if (dynamic_first_recv)
2122 struct timeval qwait;
2124 fcgi_util_ticks(&fr->queueTime);
2125 timersub(&fr->queueTime, &fr->startTime, &qwait);
2127 send_to_pm(FCGI_REQUEST_TIMEOUT_JOB, fr->fs_path, fr->user, fr->group, 0, 0);
2129 dynamic_first_recv = qwait.tv_sec / dynamicPleaseStartDelay + 1;
2130 continue;
2132 else
2134 ap_log_rerror(FCGI_LOG_ERR_NOERRNO, r, "FastCGI: comm with "
2135 "server \"%s\" aborted: idle timeout (%d sec)",
2136 fr->fs_path, idle_timeout);
2137 state = STATE_ERROR;
2141 if (FD_ISSET(fr->fd, &write_set))
2143 /* send to the server */
2145 rv = fcgi_buf_socket_send(fr->serverOutputBuffer, fr->fd);
2147 if (rv < 0)
2149 ap_log_rerror(FCGI_LOG_ERR, r, "FastCGI: comm with server "
2150 "\"%s\" aborted: write failed", fr->fs_path);
2151 state = STATE_ERROR;
2152 break;
2156 if (FD_ISSET(fr->fd, &read_set))
2158 /* recv from the server */
2160 if (dynamic_first_recv)
2162 dynamic_first_recv = 0;
2163 fcgi_util_ticks(&fr->queueTime);
2166 rv = fcgi_buf_socket_recv(fr->serverInputBuffer, fr->fd);
2168 if (rv < 0)
2170 ap_log_rerror(FCGI_LOG_ERR, r, "FastCGI: comm with server "
2171 "\"%s\" aborted: read failed", fr->fs_path);
2172 state = STATE_ERROR;
2173 break;
2176 if (rv == 0)
2178 fr->keepReadingFromFcgiApp = FALSE;
2179 state = STATE_CLIENT_SEND;
2180 break;
2184 if (fcgi_protocol_dequeue(rp, fr))
2186 state = STATE_ERROR;
2187 break;
2190 if (fr->parseHeader == SCAN_CGI_READING_HEADERS)
2192 const char * err = process_headers(r, fr);
2193 if (err)
2195 ap_log_rerror(FCGI_LOG_ERR_NOERRNO, r,
2196 "FastCGI: comm with server \"%s\" aborted: "
2197 "error parsing headers: %s", fr->fs_path, err);
2198 state = STATE_ERROR;
2199 break;
2203 if (fr->exitStatusSet)
2205 fr->keepReadingFromFcgiApp = FALSE;
2206 state = STATE_CLIENT_SEND;
2207 break;
2211 return (state == STATE_ERROR);
2215 /*----------------------------------------------------------------------
2216 * This is the core routine for moving data between the FastCGI
2217 * application and the Web server's client.
2219 static int do_work(request_rec * const r, fcgi_request * const fr)
2221 int rv;
2222 pool *rp = r->pool;
2224 fcgi_protocol_queue_begin_request(fr);
2226 if (fr->role == FCGI_RESPONDER)
2228 rv = ap_setup_client_block(r, REQUEST_CHUNKED_ERROR);
2229 if (rv != OK)
2231 ap_kill_timeout(r);
2232 return rv;
2235 fr->expectingClientContent = ap_should_client_block(r);
2238 ap_block_alarms();
2239 ap_register_cleanup(rp, (void *)fr, cleanup, ap_null_cleanup);
2240 ap_unblock_alarms();
2242 ap_hard_timeout("connect() to FastCGI server", r);
2244 /* Connect to the FastCGI Application */
2245 if (open_connection_to_fs(fr) != FCGI_OK)
2247 ap_kill_timeout(r);
2248 return HTTP_INTERNAL_SERVER_ERROR;
2251 #ifdef WIN32
2252 if (fr->using_npipe_io)
2254 rv = npipe_io(fr);
2256 else
2257 #endif
2259 rv = socket_io(fr);
2262 /* comm with the server is done */
2263 close_connection_to_fs(fr);
2265 if (fr->role == FCGI_RESPONDER)
2267 sink_client_data(fr);
2270 while (rv == 0 && BufferLength(fr->serverInputBuffer) || BufferLength(fr->clientOutputBuffer))
2272 if (fcgi_protocol_dequeue(rp, fr))
2274 rv = HTTP_INTERNAL_SERVER_ERROR;
2277 if (fr->parseHeader == SCAN_CGI_READING_HEADERS)
2279 const char * err = process_headers(r, fr);
2280 if (err)
2282 ap_log_rerror(FCGI_LOG_ERR_NOERRNO, r,
2283 "FastCGI: comm with server \"%s\" aborted: "
2284 "error parsing headers: %s", fr->fs_path, err);
2285 rv = HTTP_INTERNAL_SERVER_ERROR;
2289 if (fr->role == FCGI_RESPONDER)
2291 if (write_to_client(fr))
2293 break;
2296 else
2298 fcgi_buf_reset(fr->clientOutputBuffer);
2302 switch (fr->parseHeader)
2304 case SCAN_CGI_FINISHED:
2306 if (fr->role == FCGI_RESPONDER)
2308 /* RUSSIAN_APACHE requires rflush() over bflush() */
2309 ap_rflush(r);
2310 #ifndef APACHE2
2311 ap_bgetopt(r->connection->client, BO_BYTECT, &r->bytes_sent);
2312 #endif
2315 /* fall through */
2317 case SCAN_CGI_INT_REDIRECT:
2318 case SCAN_CGI_SRV_REDIRECT:
2320 break;
2322 case SCAN_CGI_READING_HEADERS:
2324 ap_log_rerror(FCGI_LOG_ERR_NOERRNO, r, "FastCGI: incomplete headers "
2325 "(%d bytes) received from server \"%s\"", fr->header->nelts, fr->fs_path);
2327 /* fall through */
2329 case SCAN_CGI_BAD_HEADER:
2331 rv = HTTP_INTERNAL_SERVER_ERROR;
2332 break;
2334 default:
2336 ap_assert(0);
2337 rv = HTTP_INTERNAL_SERVER_ERROR;
2340 ap_kill_timeout(r);
2341 return rv;
2344 static fcgi_request *create_fcgi_request(request_rec * const r, const char *path)
2346 const char *fs_path;
2347 pool * const p = r->pool;
2348 fcgi_server *fs;
2349 fcgi_request * const fr = (fcgi_request *)ap_pcalloc(p, sizeof(fcgi_request));
2351 fs_path = path ? path : r->filename;
2353 fs = fcgi_util_fs_get_by_id(fs_path, fcgi_util_get_server_uid(r->server),
2354 fcgi_util_get_server_gid(r->server));
2355 if (fs == NULL)
2357 const char * err;
2358 struct stat *my_finfo;
2360 /* dynamic? */
2362 #ifndef APACHE2
2363 if (path == NULL)
2365 /* AP2: its bogus that we don't make use of r->finfo, but
2366 * its an apr_finfo_t and there is no apr_os_finfo_get() */
2368 my_finfo = &r->finfo;
2370 else
2371 #endif
2373 my_finfo = (struct stat *) ap_palloc(p, sizeof(struct stat));
2375 if (stat(fs_path, my_finfo) < 0)
2377 ap_log_rerror(FCGI_LOG_ERR_ERRNO, r,
2378 "FastCGI: stat() of \"%s\" failed", fs_path);
2379 return NULL;
2383 err = fcgi_util_fs_is_path_ok(p, fs_path, my_finfo);
2385 if (err)
2387 ap_log_rerror(FCGI_LOG_ERR_NOERRNO, r,
2388 "FastCGI: invalid (dynamic) server \"%s\": %s", fs_path, err);
2389 return NULL;
2393 fr->serverInputBuffer = fcgi_buf_new(p, SERVER_BUFSIZE);
2394 fr->serverOutputBuffer = fcgi_buf_new(p, SERVER_BUFSIZE);
2395 fr->clientInputBuffer = fcgi_buf_new(p, SERVER_BUFSIZE);
2396 fr->clientOutputBuffer = fcgi_buf_new(p, SERVER_BUFSIZE);
2397 fr->erBufPtr = fcgi_buf_new(p, sizeof(FCGI_EndRequestBody) + 1);
2398 fr->gotHeader = FALSE;
2399 fr->parseHeader = SCAN_CGI_READING_HEADERS;
2400 fr->header = ap_make_array(p, 1, 1);
2401 fr->fs_stderr = NULL;
2402 fr->r = r;
2403 fr->readingEndRequestBody = FALSE;
2404 fr->exitStatus = 0;
2405 fr->exitStatusSet = FALSE;
2406 fr->requestId = 1; /* anything but zero is OK here */
2407 fr->eofSent = FALSE;
2408 fr->role = FCGI_RESPONDER;
2409 fr->expectingClientContent = FALSE;
2410 fr->keepReadingFromFcgiApp = TRUE;
2411 fr->fs = fs;
2412 fr->fs_path = fs_path;
2413 fr->authHeaders = ap_make_table(p, 10);
2414 #ifdef WIN32
2415 fr->fd = INVALID_SOCKET;
2416 fr->dynamic = ((fs == NULL) || (fs->directive == APP_CLASS_DYNAMIC)) ? TRUE : FALSE;
2417 fr->using_npipe_io = FALSE;
2418 #else
2419 fr->dynamic = (fs == NULL) ? TRUE : FALSE;
2420 fr->fd = -1;
2421 #endif
2423 set_uid_n_gid(r, &fr->user, &fr->group);
2425 return fr;
2429 *----------------------------------------------------------------------
2431 * handler --
2433 * This routine gets called for a request that corresponds to
2434 * a FastCGI connection. It performs the request synchronously.
2436 * Results:
2437 * Final status of request: OK or NOT_FOUND or HTTP_INTERNAL_SERVER_ERROR.
2439 * Side effects:
2440 * Request performed.
2442 *----------------------------------------------------------------------
2445 /* Stolen from mod_cgi.c..
2446 * KLUDGE --- for back-combatibility, we don't have to check ExecCGI
2447 * in ScriptAliased directories, which means we need to know if this
2448 * request came through ScriptAlias or not... so the Alias module
2449 * leaves a note for us.
2451 static int apache_is_scriptaliased(request_rec *r)
2453 const char *t = ap_table_get(r->notes, "alias-forced-type");
2454 return t && (!strcasecmp(t, "cgi-script"));
2457 /* If a script wants to produce its own Redirect body, it now
2458 * has to explicitly *say* "Status: 302". If it wants to use
2459 * Apache redirects say "Status: 200". See process_headers().
2461 static int post_process_for_redirects(request_rec * const r,
2462 const fcgi_request * const fr)
2464 switch(fr->parseHeader) {
2465 case SCAN_CGI_INT_REDIRECT:
2467 /* @@@ There are still differences between the handling in
2468 * mod_cgi and mod_fastcgi. This needs to be revisited.
2470 /* We already read the message body (if any), so don't allow
2471 * the redirected request to think it has one. We can ignore
2472 * Transfer-Encoding, since we used REQUEST_CHUNKED_ERROR.
2474 r->method = "GET";
2475 r->method_number = M_GET;
2476 ap_table_unset(r->headers_in, "Content-length");
2478 ap_internal_redirect_handler(ap_table_get(r->headers_out, "Location"), r);
2479 return OK;
2481 case SCAN_CGI_SRV_REDIRECT:
2482 return HTTP_MOVED_TEMPORARILY;
2484 default:
2485 return OK;
2489 /******************************************************************************
2490 * Process fastcgi-script requests. Based on mod_cgi::cgi_handler().
2492 static int content_handler(request_rec *r)
2494 fcgi_request *fr = NULL;
2495 int ret;
2497 #ifdef APACHE2
2498 if (strcmp(r->handler, FASTCGI_HANDLER_NAME))
2499 return DECLINED;
2500 #endif
2502 /* Setup a new FastCGI request */
2503 if ((fr = create_fcgi_request(r, NULL)) == NULL)
2504 return HTTP_INTERNAL_SERVER_ERROR;
2506 /* If its a dynamic invocation, make sure scripts are OK here */
2507 if (fr->dynamic && !(ap_allow_options(r) & OPT_EXECCGI) && !apache_is_scriptaliased(r)) {
2508 ap_log_rerror(FCGI_LOG_ERR_NOERRNO, r,
2509 "FastCGI: \"ExecCGI Option\" is off in this directory: %s", r->uri);
2510 return HTTP_INTERNAL_SERVER_ERROR;
2513 /* Process the fastcgi-script request */
2514 if ((ret = do_work(r, fr)) != OK)
2515 return ret;
2517 /* Special case redirects */
2518 ret = post_process_for_redirects(r, fr);
2520 return ret;
2524 static int post_process_auth_passed_header(table *t, const char *key, const char * const val)
2526 if (strncasecmp(key, "Variable-", 9) == 0)
2527 key += 9;
2529 ap_table_setn(t, key, val);
2530 return 1;
2533 static int post_process_auth_passed_compat_header(table *t, const char *key, const char * const val)
2535 if (strncasecmp(key, "Variable-", 9) == 0)
2536 ap_table_setn(t, key + 9, val);
2538 return 1;
2541 static int post_process_auth_failed_header(table * const t, const char * const key, const char * const val)
2543 ap_table_setn(t, key, val);
2544 return 1;
2547 static void post_process_auth(fcgi_request * const fr, const int passed)
2549 request_rec * const r = fr->r;
2551 /* Restore the saved subprocess_env because we muddied ours up */
2552 r->subprocess_env = fr->saved_subprocess_env;
2554 if (passed) {
2555 if (fr->auth_compat) {
2556 ap_table_do((int (*)(void *, const char *, const char *))post_process_auth_passed_compat_header,
2557 (void *)r->subprocess_env, fr->authHeaders, NULL);
2559 else {
2560 ap_table_do((int (*)(void *, const char *, const char *))post_process_auth_passed_header,
2561 (void *)r->subprocess_env, fr->authHeaders, NULL);
2564 else {
2565 ap_table_do((int (*)(void *, const char *, const char *))post_process_auth_failed_header,
2566 (void *)r->err_headers_out, fr->authHeaders, NULL);
2569 /* @@@ Restore these.. its a hack until I rewrite the header handling */
2570 r->status = HTTP_OK;
2571 r->status_line = NULL;
2574 static int check_user_authentication(request_rec *r)
2576 int res, authenticated = 0;
2577 const char *password;
2578 fcgi_request *fr;
2579 const fcgi_dir_config * const dir_config =
2580 (const fcgi_dir_config *)ap_get_module_config(r->per_dir_config, &fastcgi_module);
2582 if (dir_config->authenticator == NULL)
2583 return DECLINED;
2585 /* Get the user password */
2586 if ((res = ap_get_basic_auth_pw(r, &password)) != OK)
2587 return res;
2589 if ((fr = create_fcgi_request(r, dir_config->authenticator)) == NULL)
2590 return HTTP_INTERNAL_SERVER_ERROR;
2592 /* Save the existing subprocess_env, because we're gonna muddy it up */
2593 fr->saved_subprocess_env = ap_copy_table(r->pool, r->subprocess_env);
2595 ap_table_setn(r->subprocess_env, "REMOTE_PASSWD", password);
2596 ap_table_setn(r->subprocess_env, "FCGI_APACHE_ROLE", "AUTHENTICATOR");
2598 /* The FastCGI Protocol doesn't differentiate authentication */
2599 fr->role = FCGI_AUTHORIZER;
2601 /* Do we need compatibility mode? */
2602 fr->auth_compat = (dir_config->authenticator_options & FCGI_COMPAT);
2604 if ((res = do_work(r, fr)) != OK)
2605 goto AuthenticationFailed;
2607 authenticated = (r->status == 200);
2608 post_process_auth(fr, authenticated);
2610 /* A redirect shouldn't be allowed during the authentication phase */
2611 if (ap_table_get(r->headers_out, "Location") != NULL) {
2612 ap_log_rerror(FCGI_LOG_ERR_NOERRNO, r,
2613 "FastCGI: FastCgiAuthenticator \"%s\" redirected (not allowed)",
2614 dir_config->authenticator);
2615 goto AuthenticationFailed;
2618 if (authenticated)
2619 return OK;
2621 AuthenticationFailed:
2622 if (!(dir_config->authenticator_options & FCGI_AUTHORITATIVE))
2623 return DECLINED;
2625 /* @@@ Probably should support custom_responses */
2626 ap_note_basic_auth_failure(r);
2627 ap_log_rerror(FCGI_LOG_ERR_NOERRNO, r,
2628 "FastCGI: authentication failed for user \"%s\": %s",
2629 #ifdef APACHE2
2630 r->user, r->uri);
2631 #else
2632 r->connection->user, r->uri);
2633 #endif
2635 return (res == OK) ? HTTP_UNAUTHORIZED : res;
2638 static int check_user_authorization(request_rec *r)
2640 int res, authorized = 0;
2641 fcgi_request *fr;
2642 const fcgi_dir_config * const dir_config =
2643 (const fcgi_dir_config *)ap_get_module_config(r->per_dir_config, &fastcgi_module);
2645 if (dir_config->authorizer == NULL)
2646 return DECLINED;
2648 /* @@@ We should probably honor the existing parameters to the require directive
2649 * as well as allow the definition of new ones (or use the basename of the
2650 * FastCGI server and pass the rest of the directive line), but for now keep
2651 * it simple. */
2653 if ((fr = create_fcgi_request(r, dir_config->authorizer)) == NULL)
2654 return HTTP_INTERNAL_SERVER_ERROR;
2656 /* Save the existing subprocess_env, because we're gonna muddy it up */
2657 fr->saved_subprocess_env = ap_copy_table(r->pool, r->subprocess_env);
2659 ap_table_setn(r->subprocess_env, "FCGI_APACHE_ROLE", "AUTHORIZER");
2661 fr->role = FCGI_AUTHORIZER;
2663 /* Do we need compatibility mode? */
2664 fr->auth_compat = (dir_config->authorizer_options & FCGI_COMPAT);
2666 if ((res = do_work(r, fr)) != OK)
2667 goto AuthorizationFailed;
2669 authorized = (r->status == 200);
2670 post_process_auth(fr, authorized);
2672 /* A redirect shouldn't be allowed during the authorization phase */
2673 if (ap_table_get(r->headers_out, "Location") != NULL) {
2674 ap_log_rerror(FCGI_LOG_ERR_NOERRNO, r,
2675 "FastCGI: FastCgiAuthorizer \"%s\" redirected (not allowed)",
2676 dir_config->authorizer);
2677 goto AuthorizationFailed;
2680 if (authorized)
2681 return OK;
2683 AuthorizationFailed:
2684 if (!(dir_config->authorizer_options & FCGI_AUTHORITATIVE))
2685 return DECLINED;
2687 /* @@@ Probably should support custom_responses */
2688 ap_note_basic_auth_failure(r);
2689 ap_log_rerror(FCGI_LOG_ERR_NOERRNO, r,
2690 "FastCGI: authorization failed for user \"%s\": %s",
2691 #ifdef APACHE2
2692 r->user, r->uri);
2693 #else
2694 r->connection->user, r->uri);
2695 #endif
2697 return (res == OK) ? HTTP_UNAUTHORIZED : res;
2700 static int check_access(request_rec *r)
2702 int res, access_allowed = 0;
2703 fcgi_request *fr;
2704 const fcgi_dir_config * const dir_config =
2705 (fcgi_dir_config *)ap_get_module_config(r->per_dir_config, &fastcgi_module);
2707 if (dir_config == NULL || dir_config->access_checker == NULL)
2708 return DECLINED;
2710 if ((fr = create_fcgi_request(r, dir_config->access_checker)) == NULL)
2711 return HTTP_INTERNAL_SERVER_ERROR;
2713 /* Save the existing subprocess_env, because we're gonna muddy it up */
2714 fr->saved_subprocess_env = ap_copy_table(r->pool, r->subprocess_env);
2716 ap_table_setn(r->subprocess_env, "FCGI_APACHE_ROLE", "ACCESS_CHECKER");
2718 /* The FastCGI Protocol doesn't differentiate access control */
2719 fr->role = FCGI_AUTHORIZER;
2721 /* Do we need compatibility mode? */
2722 fr->auth_compat = (dir_config->access_checker_options & FCGI_COMPAT);
2724 if ((res = do_work(r, fr)) != OK)
2725 goto AccessFailed;
2727 access_allowed = (r->status == 200);
2728 post_process_auth(fr, access_allowed);
2730 /* A redirect shouldn't be allowed during the access check phase */
2731 if (ap_table_get(r->headers_out, "Location") != NULL) {
2732 ap_log_rerror(FCGI_LOG_ERR_NOERRNO, r,
2733 "FastCGI: FastCgiAccessChecker \"%s\" redirected (not allowed)",
2734 dir_config->access_checker);
2735 goto AccessFailed;
2738 if (access_allowed)
2739 return OK;
2741 AccessFailed:
2742 if (!(dir_config->access_checker_options & FCGI_AUTHORITATIVE))
2743 return DECLINED;
2745 /* @@@ Probably should support custom_responses */
2746 ap_log_rerror(FCGI_LOG_ERR_NOERRNO, r, "FastCGI: access denied: %s", r->uri);
2747 return (res == OK) ? HTTP_FORBIDDEN : res;
2750 static int
2751 fixups(request_rec * r)
2753 if (fcgi_util_fs_get_by_id(r->filename,
2754 fcgi_util_get_server_uid(r->server),
2755 fcgi_util_get_server_gid(r->server)))
2757 r->handler = FASTCGI_HANDLER_NAME;
2758 return OK;
2761 return DECLINED;
2764 #ifndef APACHE2
2766 # define AP_INIT_RAW_ARGS(directive, func, mconfig, where, help) \
2767 { directive, func, mconfig, where, RAW_ARGS, help }
2768 # define AP_INIT_TAKE1(directive, func, mconfig, where, help) \
2769 { directive, func, mconfig, where, TAKE1, help }
2770 # define AP_INIT_TAKE12(directive, func, mconfig, where, help) \
2771 { directive, func, mconfig, where, TAKE12, help }
2772 # define AP_INIT_FLAG(directive, func, mconfig, where, help) \
2773 { directive, func, mconfig, where, FLAG, help }
2775 #endif
2777 static const command_rec fastcgi_cmds[] =
2779 AP_INIT_RAW_ARGS("AppClass", fcgi_config_new_static_server, NULL, RSRC_CONF, NULL),
2780 AP_INIT_RAW_ARGS("FastCgiServer", fcgi_config_new_static_server, NULL, RSRC_CONF, NULL),
2782 AP_INIT_RAW_ARGS("ExternalAppClass", fcgi_config_new_external_server, NULL, RSRC_CONF, NULL),
2783 AP_INIT_RAW_ARGS("FastCgiExternalServer", fcgi_config_new_external_server, NULL, RSRC_CONF, NULL),
2785 AP_INIT_TAKE1("FastCgiIpcDir", fcgi_config_set_socket_dir, NULL, RSRC_CONF, NULL),
2787 AP_INIT_TAKE1("FastCgiSuexec", fcgi_config_set_wrapper, NULL, RSRC_CONF, NULL),
2788 AP_INIT_TAKE1("FastCgiWrapper", fcgi_config_set_wrapper, NULL, RSRC_CONF, NULL),
2790 AP_INIT_RAW_ARGS("FCGIConfig", fcgi_config_set_config, NULL, RSRC_CONF, NULL),
2791 AP_INIT_RAW_ARGS("FastCgiConfig", fcgi_config_set_config, NULL, RSRC_CONF, NULL),
2793 AP_INIT_TAKE12("FastCgiAuthenticator", fcgi_config_new_auth_server,
2794 (void *)FCGI_AUTH_TYPE_AUTHENTICATOR, ACCESS_CONF,
2795 "a fastcgi-script path (absolute or relative to ServerRoot) followed by an optional -compat"),
2796 AP_INIT_FLAG("FastCgiAuthenticatorAuthoritative", fcgi_config_set_authoritative_slot,
2797 (void *)XtOffsetOf(fcgi_dir_config, authenticator_options), ACCESS_CONF,
2798 "Set to 'off' to allow authentication to be passed along to lower modules upon failure"),
2800 AP_INIT_TAKE12("FastCgiAuthorizer", fcgi_config_new_auth_server,
2801 (void *)FCGI_AUTH_TYPE_AUTHORIZER, ACCESS_CONF,
2802 "a fastcgi-script path (absolute or relative to ServerRoot) followed by an optional -compat"),
2803 AP_INIT_FLAG("FastCgiAuthorizerAuthoritative", fcgi_config_set_authoritative_slot,
2804 (void *)XtOffsetOf(fcgi_dir_config, authorizer_options), ACCESS_CONF,
2805 "Set to 'off' to allow authorization to be passed along to lower modules upon failure"),
2807 AP_INIT_TAKE12("FastCgiAccessChecker", fcgi_config_new_auth_server,
2808 (void *)FCGI_AUTH_TYPE_ACCESS_CHECKER, ACCESS_CONF,
2809 "a fastcgi-script path (absolute or relative to ServerRoot) followed by an optional -compat"),
2810 AP_INIT_FLAG("FastCgiAccessCheckerAuthoritative", fcgi_config_set_authoritative_slot,
2811 (void *)XtOffsetOf(fcgi_dir_config, access_checker_options), ACCESS_CONF,
2812 "Set to 'off' to allow access control to be passed along to lower modules upon failure"),
2813 { NULL }
2816 #ifdef APACHE2
2818 static void register_hooks(apr_pool_t * p)
2820 // ap_hook_pre_config(x_pre_config, NULL, NULL, APR_HOOK_MIDDLE);
2821 ap_hook_post_config(init_module, NULL, NULL, APR_HOOK_MIDDLE);
2822 ap_hook_child_init(fcgi_child_init, NULL, NULL, APR_HOOK_MIDDLE);
2823 ap_hook_handler(content_handler, NULL, NULL, APR_HOOK_MIDDLE);
2824 ap_hook_check_user_id(check_user_authentication, NULL, NULL, APR_HOOK_MIDDLE);
2825 ap_hook_access_checker(check_access, NULL, NULL, APR_HOOK_MIDDLE);
2826 ap_hook_auth_checker(check_user_authorization, NULL, NULL, APR_HOOK_MIDDLE);
2827 ap_hook_fixups(fixups, NULL, NULL, APR_HOOK_MIDDLE);
2830 module AP_MODULE_DECLARE_DATA fastcgi_module =
2832 STANDARD20_MODULE_STUFF,
2833 fcgi_config_create_dir_config, /* per-directory config creator */
2834 NULL, /* dir config merger */
2835 NULL, /* server config creator */
2836 NULL, /* server config merger */
2837 fastcgi_cmds, /* command table */
2838 register_hooks, /* set up other request processing hooks */
2841 #else /* !APACHE2 */
2843 handler_rec fastcgi_handlers[] = {
2844 { FCGI_MAGIC_TYPE, content_handler },
2845 { FASTCGI_HANDLER_NAME, content_handler },
2846 { NULL }
2849 module MODULE_VAR_EXPORT fastcgi_module = {
2850 STANDARD_MODULE_STUFF,
2851 init_module, /* initializer */
2852 fcgi_config_create_dir_config, /* per-dir config creator */
2853 NULL, /* per-dir config merger (default: override) */
2854 NULL, /* per-server config creator */
2855 NULL, /* per-server config merger (default: override) */
2856 fastcgi_cmds, /* command table */
2857 fastcgi_handlers, /* [9] content handlers */
2858 NULL, /* [2] URI-to-filename translation */
2859 check_user_authentication, /* [5] authenticate user_id */
2860 check_user_authorization, /* [6] authorize user_id */
2861 check_access, /* [4] check access (based on src & http headers) */
2862 NULL, /* [7] check/set MIME type */
2863 fixups, /* [8] fixups */
2864 NULL, /* [10] logger */
2865 NULL, /* [3] header-parser */
2866 fcgi_child_init, /* process initialization */
2867 fcgi_child_exit, /* process exit/cleanup */
2868 NULL /* [1] post read-request handling */
2871 #endif /* !APACHE2 */