Eliminate the logging of "incomplete headers (0 bytes) received from
[mod_fastcgi.git] / mod_fastcgi.c
blob380e050dd77411c7bbeef4664639cdf80333fd3d
1 /*
2 * mod_fastcgi.c --
4 * Apache server module for FastCGI.
6 * $Id: mod_fastcgi.c,v 1.147 2002/12/05 03:02:05 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 #endif
84 #endif
86 #ifndef timersub
87 #define timersub(a, b, result) \
88 do { \
89 (result)->tv_sec = (a)->tv_sec - (b)->tv_sec; \
90 (result)->tv_usec = (a)->tv_usec - (b)->tv_usec; \
91 if ((result)->tv_usec < 0) { \
92 --(result)->tv_sec; \
93 (result)->tv_usec += 1000000; \
94 } \
95 } while (0)
96 #endif
99 * Global variables
102 pool *fcgi_config_pool; /* the config pool */
103 server_rec *fcgi_apache_main_server;
105 const char *fcgi_wrapper = NULL; /* wrapper path */
106 uid_t fcgi_user_id; /* the run uid of Apache & PM */
107 gid_t fcgi_group_id; /* the run gid of Apache & PM */
109 fcgi_server *fcgi_servers = NULL; /* AppClasses */
111 char *fcgi_socket_dir = NULL; /* default FastCgiIpcDir */
113 char *fcgi_dynamic_dir = NULL; /* directory for the dynamic
114 * fastcgi apps' sockets */
116 #ifdef WIN32
118 #pragma warning( disable : 4706 4100 4127)
119 fcgi_pm_job *fcgi_dynamic_mbox = NULL;
120 HANDLE *fcgi_dynamic_mbox_mutex = NULL;
121 HANDLE fcgi_pm_thread = INVALID_HANDLE_VALUE;
123 #else
125 int fcgi_pm_pipe[2] = { -1, -1 };
126 pid_t fcgi_pm_pid = -1;
128 #endif
130 char *fcgi_empty_env = NULL;
132 u_int dynamicMaxProcs = FCGI_DEFAULT_MAX_PROCS;
133 int dynamicMinProcs = FCGI_DEFAULT_MIN_PROCS;
134 int dynamicMaxClassProcs = FCGI_DEFAULT_MAX_CLASS_PROCS;
135 u_int dynamicKillInterval = FCGI_DEFAULT_KILL_INTERVAL;
136 u_int dynamicUpdateInterval = FCGI_DEFAULT_UPDATE_INTERVAL;
137 float dynamicGain = FCGI_DEFAULT_GAIN;
138 int dynamicThreshold1 = FCGI_DEFAULT_THRESHOLD_1;
139 int dynamicThresholdN = FCGI_DEFAULT_THRESHOLD_N;
140 u_int dynamicPleaseStartDelay = FCGI_DEFAULT_START_PROCESS_DELAY;
141 u_int dynamicAppConnectTimeout = FCGI_DEFAULT_APP_CONN_TIMEOUT;
142 char **dynamicEnvp = &fcgi_empty_env;
143 u_int dynamicProcessSlack = FCGI_DEFAULT_PROCESS_SLACK;
144 int dynamicAutoRestart = FCGI_DEFAULT_RESTART_DYNAMIC;
145 int dynamicAutoUpdate = FCGI_DEFAULT_AUTOUPDATE;
146 int dynamicFlush = FCGI_FLUSH;
147 u_int dynamicListenQueueDepth = FCGI_DEFAULT_LISTEN_Q;
148 u_int dynamicInitStartDelay = DEFAULT_INIT_START_DELAY;
149 u_int dynamicRestartDelay = FCGI_DEFAULT_RESTART_DELAY;
150 array_header *dynamic_pass_headers = NULL;
151 u_int dynamic_idle_timeout = FCGI_DEFAULT_IDLE_TIMEOUT;
153 /*******************************************************************************
154 * Construct a message and write it to the pm_pipe.
156 static void send_to_pm(const char id, const char * const fs_path,
157 const char *user, const char * const group, const unsigned long q_usec,
158 const unsigned long req_usec)
160 #ifdef WIN32
161 fcgi_pm_job *job = NULL;
163 if (!(job = (fcgi_pm_job *) malloc(sizeof(fcgi_pm_job))))
164 return;
165 #else
166 static int failed_count = 0;
167 int buflen = 0;
168 char buf[FCGI_MAX_MSG_LEN];
169 #endif
171 if (strlen(fs_path) > FCGI_MAXPATH) {
172 ap_log_error(FCGI_LOG_ERR_NOERRNO, fcgi_apache_main_server,
173 "FastCGI: the path \"%s\" is too long (>%d) for a dynamic server", fs_path, FCGI_MAXPATH);
174 return;
177 switch(id) {
179 case FCGI_SERVER_START_JOB:
180 case FCGI_SERVER_RESTART_JOB:
181 #ifdef WIN32
182 job->id = id;
183 job->fs_path = strdup(fs_path);
184 job->user = strdup(user);
185 job->group = strdup(group);
186 job->qsec = 0L;
187 job->start_time = 0L;
188 #else
189 buflen = sprintf(buf, "%c %s %s %s*", id, fs_path, user, group);
190 #endif
191 break;
193 case FCGI_REQUEST_TIMEOUT_JOB:
194 #ifdef WIN32
195 job->id = id;
196 job->fs_path = strdup(fs_path);
197 job->user = strdup(user);
198 job->group = strdup(group);
199 job->qsec = 0L;
200 job->start_time = 0L;
201 #else
202 buflen = sprintf(buf, "%c %s %s %s*", id, fs_path, user, group);
203 #endif
204 break;
206 case FCGI_REQUEST_COMPLETE_JOB:
207 #ifdef WIN32
208 job->id = id;
209 job->fs_path = strdup(fs_path);
210 job->qsec = q_usec;
211 job->start_time = req_usec;
212 job->user = strdup(user);
213 job->group = strdup(group);
214 #else
215 buflen = sprintf(buf, "%c %s %s %s %lu %lu*", id, fs_path, user, group, q_usec, req_usec);
216 #endif
217 break;
220 #ifdef WIN32
221 if (fcgi_pm_add_job(job)) return;
223 SetEvent(fcgi_event_handles[MBOX_EVENT]);
224 #else
225 ap_assert(buflen <= FCGI_MAX_MSG_LEN);
227 /* There is no apache flag or function that can be used to id
228 * restart/shutdown pending so ignore the first few failures as
229 * once it breaks it will stay broke */
230 if (write(fcgi_pm_pipe[1], (const void *)buf, buflen) != buflen
231 && failed_count++ > 10)
233 ap_log_error(FCGI_LOG_WARN, fcgi_apache_main_server,
234 "FastCGI: write() to PM failed (ignore if a restart or shutdown is pending)");
236 #endif
240 *----------------------------------------------------------------------
242 * init_module
244 * An Apache module initializer, called by the Apache core
245 * after reading the server config.
247 * Start the process manager no matter what, since there may be a
248 * request for dynamic FastCGI applications without any being
249 * configured as static applications. Also, check for the existence
250 * and create if necessary a subdirectory into which all dynamic
251 * sockets will go.
253 *----------------------------------------------------------------------
255 #ifdef APACHE2
256 static apcb_t init_module(apr_pool_t * p, apr_pool_t * plog,
257 apr_pool_t * tp, server_rec * s)
258 #else
259 static apcb_t init_module(server_rec *s, pool *p)
260 #endif
262 #ifndef WIN32
263 const char *err;
264 #endif
266 /* Register to reset to default values when the config pool is cleaned */
267 ap_block_alarms();
268 ap_register_cleanup(p, NULL, fcgi_config_reset_globals, ap_null_cleanup);
269 ap_unblock_alarms();
271 #ifdef APACHE2
272 ap_add_version_component(p, "mod_fastcgi/" MOD_FASTCGI_VERSION);
273 #else
274 ap_add_version_component("mod_fastcgi/" MOD_FASTCGI_VERSION);
275 #endif
277 fcgi_config_set_fcgi_uid_n_gid(1);
279 /* keep these handy */
280 fcgi_config_pool = p;
281 fcgi_apache_main_server = s;
283 #ifdef WIN32
284 if (fcgi_socket_dir == NULL)
285 fcgi_socket_dir = DEFAULT_SOCK_DIR;
286 fcgi_dynamic_dir = ap_pstrcat(p, fcgi_socket_dir, "dynamic", NULL);
287 #else
289 if (fcgi_socket_dir == NULL)
290 fcgi_socket_dir = ap_server_root_relative(p, DEFAULT_SOCK_DIR);
292 /* Create Unix/Domain socket directory */
293 if ((err = fcgi_config_make_dir(p, fcgi_socket_dir)))
294 ap_log_error(FCGI_LOG_ERR, s, "FastCGI: %s", err);
296 /* Create Dynamic directory */
297 if ((err = fcgi_config_make_dynamic_dir(p, 1)))
298 ap_log_error(FCGI_LOG_ERR, s, "FastCGI: %s", err);
300 /* Spawn the PM only once. Under Unix, Apache calls init() routines
301 * twice, once before detach() and once after. Win32 doesn't detach.
302 * Under DSO, DSO modules are unloaded between the two init() calls.
303 * Under Unix, the -X switch causes two calls to init() but no detach
304 * (but all subprocesses are wacked so the PM is toasted anyway)! */
306 #ifdef APACHE2
308 void * first_pass;
309 apr_pool_userdata_get(&first_pass, "mod_fastcgi", s->process->pool);
310 if (first_pass == NULL)
312 apr_pool_userdata_set((const void *)1, "mod_fastcgi",
313 apr_pool_cleanup_null, s->process->pool);
314 return APCB_OK;
317 #else /* !APACHE2 */
319 if (ap_standalone && ap_restart_time == 0)
320 return;
322 #endif
324 /* Create the pipe for comm with the PM */
325 if (pipe(fcgi_pm_pipe) < 0) {
326 ap_log_error(FCGI_LOG_ERR, s, "FastCGI: pipe() failed");
329 /* Start the Process Manager */
331 #ifdef APACHE2
333 apr_proc_t * proc = apr_palloc(p, sizeof(*proc));
334 apr_status_t rv;
336 rv = apr_proc_fork(proc, tp);
338 if (rv == APR_INCHILD)
340 /* child */
341 fcgi_pm_main(NULL);
342 exit(1);
344 else if (rv != APR_INPARENT)
346 return rv;
349 /* parent */
351 apr_pool_note_subprocess(p, proc, APR_KILL_ONLY_ONCE);
353 #else /* !APACHE2 */
355 fcgi_pm_pid = ap_spawn_child(p, fcgi_pm_main, NULL, kill_only_once, NULL, NULL, NULL);
356 if (fcgi_pm_pid <= 0) {
357 ap_log_error(FCGI_LOG_ALERT, s,
358 "FastCGI: can't start the process manager, spawn_child() failed");
361 #endif /* !APACHE2 */
363 close(fcgi_pm_pipe[0]);
365 #endif /* !WIN32 */
367 return APCB_OK;
370 #ifdef WIN32
371 #ifdef APACHE2
372 static apcb_t fcgi_child_exit(void * dc)
373 #else
374 static apcb_t fcgi_child_exit(server_rec *dc0, pool *dc1)
375 #endif
377 /* Signal the PM thread to exit*/
378 SetEvent(fcgi_event_handles[TERM_EVENT]);
380 /* Waiting on pm thread to exit */
381 WaitForSingleObject(fcgi_pm_thread, INFINITE);
383 return APCB_OK;
385 #endif /* WIN32 */
387 #ifdef APACHE2
388 static void fcgi_child_init(apr_pool_t * p, server_rec * dc)
389 #else
390 static void fcgi_child_init(server_rec *dc, pool *p)
391 #endif
393 #ifdef WIN32
394 /* Create the MBOX, TERM, and WAKE event handlers */
395 fcgi_event_handles[0] = CreateEvent(NULL, FALSE, FALSE, NULL);
396 if (fcgi_event_handles[0] == NULL) {
397 ap_log_error(FCGI_LOG_ALERT, fcgi_apache_main_server,
398 "FastCGI: CreateEvent() failed");
400 fcgi_event_handles[1] = CreateEvent(NULL, FALSE, FALSE, NULL);
401 if (fcgi_event_handles[1] == NULL) {
402 ap_log_error(FCGI_LOG_ALERT, fcgi_apache_main_server,
403 "FastCGI: CreateEvent() failed");
405 fcgi_event_handles[2] = CreateEvent(NULL, FALSE, FALSE, NULL);
406 if (fcgi_event_handles[2] == NULL) {
407 ap_log_error(FCGI_LOG_ALERT, fcgi_apache_main_server,
408 "FastCGI: CreateEvent() failed");
411 /* Create the mbox mutex (PM - request threads) */
412 fcgi_dynamic_mbox_mutex = CreateMutex(NULL, FALSE, NULL);
413 if (fcgi_dynamic_mbox_mutex == NULL) {
414 ap_log_error(FCGI_LOG_ALERT, fcgi_apache_main_server,
415 "FastCGI: CreateMutex() failed");
418 /* Spawn of the process manager thread */
419 fcgi_pm_thread = (HANDLE) _beginthread(fcgi_pm_main, 0, NULL);
420 if (fcgi_pm_thread == (HANDLE) -1) {
421 ap_log_error(FCGI_LOG_ALERT, fcgi_apache_main_server,
422 "_beginthread() failed to spawn the process manager");
425 #ifdef APACHE2
426 apr_pool_cleanup_register(p, NULL, fcgi_child_exit, fcgi_child_exit);
427 #endif
428 #endif
432 *----------------------------------------------------------------------
434 * get_header_line --
436 * Terminate a line: scan to the next newline, scan back to the
437 * first non-space character and store a terminating zero. Return
438 * the next character past the end of the newline.
440 * If the end of the string is reached, ASSERT!
442 * If the FIRST character(s) in the line are '\n' or "\r\n", the
443 * first character is replaced with a NULL and next character
444 * past the newline is returned. NOTE: this condition supercedes
445 * the processing of RFC-822 continuation lines.
447 * If continuation is set to 'TRUE', then it parses a (possible)
448 * sequence of RFC-822 continuation lines.
450 * Results:
451 * As above.
453 * Side effects:
454 * Termination byte stored in string.
456 *----------------------------------------------------------------------
458 static char *get_header_line(char *start, int continuation)
460 char *p = start;
461 char *end = start;
463 if(p[0] == '\r' && p[1] == '\n') { /* If EOL in 1st 2 chars */
464 p++; /* point to \n and stop */
465 } else if(*p != '\n') {
466 if(continuation) {
467 while(*p != '\0') {
468 if(*p == '\n' && p[1] != ' ' && p[1] != '\t')
469 break;
470 p++;
472 } else {
473 while(*p != '\0' && *p != '\n') {
474 p++;
479 ap_assert(*p != '\0');
480 end = p;
481 end++;
484 * Trim any trailing whitespace.
486 while(isspace((unsigned char)p[-1]) && p > start) {
487 p--;
490 *p = '\0';
491 return end;
494 #ifdef WIN32
496 static int set_nonblocking(const fcgi_request * fr, int nonblocking)
498 if (fr->using_npipe_io)
500 if (nonblocking)
502 DWORD mode = PIPE_NOWAIT | PIPE_READMODE_BYTE;
503 if (SetNamedPipeHandleState((HANDLE) fr->fd, &mode, NULL, NULL) == 0)
505 ap_log_rerror(FCGI_LOG_ERR, fr->r,
506 "FastCGI: SetNamedPipeHandleState() failed");
507 return -1;
511 else
513 unsigned long ioctl_arg = (nonblocking) ? 1 : 0;
514 if (ioctlsocket(fr->fd, FIONBIO, &ioctl_arg) != 0)
516 errno = WSAGetLastError();
517 ap_log_rerror(FCGI_LOG_ERR_ERRNO, fr->r,
518 "FastCGI: ioctlsocket() failed");
519 return -1;
523 return 0;
526 #else
528 static int set_nonblocking(const fcgi_request * fr, int nonblocking)
530 int nb_flag = 0;
531 int fd_flags = fcntl(fr->fd, F_GETFL, 0);
533 if (fd_flags < 0) return -1;
535 #if defined(O_NONBLOCK)
536 nb_flag = O_NONBLOCK;
537 #elif defined(O_NDELAY)
538 nb_flag = O_NDELAY;
539 #elif defined(FNDELAY)
540 nb_flag = FNDELAY;
541 #else
542 #error "TODO - don't read from app until all data from client is posted."
543 #endif
545 fd_flags = (nonblocking) ? (fd_flags | nb_flag) : (fd_flags & ~nb_flag);
547 return fcntl(fr->fd, F_SETFL, fd_flags);
550 #endif
552 /*******************************************************************************
553 * Close the connection to the FastCGI server. This is normally called by
554 * do_work(), but may also be called as in request pool cleanup.
556 static void close_connection_to_fs(fcgi_request *fr)
558 #ifdef WIN32
560 if (fr->fd != INVALID_SOCKET)
562 set_nonblocking(fr, FALSE);
564 if (fr->using_npipe_io)
566 CloseHandle((HANDLE) fr->fd);
568 else
570 /* abort the connection entirely */
571 struct linger linger = {0, 0};
572 setsockopt(fr->fd, SOL_SOCKET, SO_LINGER, (void *) &linger, sizeof(linger));
573 closesocket(fr->fd);
576 fr->fd = INVALID_SOCKET;
578 #else /* ! WIN32 */
580 if (fr->fd >= 0)
582 struct linger linger = {0, 0};
583 set_nonblocking(fr, FALSE);
584 /* abort the connection entirely */
585 setsockopt(fr->fd, SOL_SOCKET, SO_LINGER, &linger, sizeof(linger));
586 close(fr->fd);
587 fr->fd = -1;
589 #endif /* ! WIN32 */
591 if (fr->dynamic && fr->keepReadingFromFcgiApp == FALSE)
593 /* XXX FCGI_REQUEST_COMPLETE_JOB is only sent for requests which complete
594 * normally WRT the fcgi app. There is no data sent for
595 * connect() timeouts or requests which complete abnormally.
596 * KillDynamicProcs() and RemoveRecords() need to be looked at
597 * to be sure they can reasonably handle these cases before
598 * sending these sort of stats - theres some funk in there.
600 if (fcgi_util_ticks(&fr->completeTime) < 0)
602 /* there's no point to aborting the request, just log it */
603 ap_log_error(FCGI_LOG_ERR, fr->r->server, "FastCGI: can't get time of day");
611 *----------------------------------------------------------------------
613 * process_headers --
615 * Call with r->parseHeader == SCAN_CGI_READING_HEADERS
616 * and initial script output in fr->header.
618 * If the initial script output does not include the header
619 * terminator ("\r\n\r\n") process_headers returns with no side
620 * effects, to be called again when more script output
621 * has been appended to fr->header.
623 * If the initial script output includes the header terminator,
624 * process_headers parses the headers and determines whether or
625 * not the remaining script output will be sent to the client.
626 * If so, process_headers sends the HTTP response headers to the
627 * client and copies any non-header script output to the output
628 * buffer reqOutbuf.
630 * Results:
631 * none.
633 * Side effects:
634 * May set r->parseHeader to:
635 * SCAN_CGI_FINISHED -- headers parsed, returning script response
636 * SCAN_CGI_BAD_HEADER -- malformed header from script
637 * SCAN_CGI_INT_REDIRECT -- handler should perform internal redirect
638 * SCAN_CGI_SRV_REDIRECT -- handler should return REDIRECT
640 *----------------------------------------------------------------------
643 static const char *process_headers(request_rec *r, fcgi_request *fr)
645 char *p, *next, *name, *value;
646 int len, flag;
647 int hasContentType, hasStatus, hasLocation;
649 ap_assert(fr->parseHeader == SCAN_CGI_READING_HEADERS);
651 if (fr->header == NULL)
652 return NULL;
655 * Do we have the entire header? Scan for the blank line that
656 * terminates the header.
658 p = (char *)fr->header->elts;
659 len = fr->header->nelts;
660 flag = 0;
661 while(len-- && flag < 2) {
662 switch(*p) {
663 case '\r':
664 break;
665 case '\n':
666 flag++;
667 break;
668 case '\0':
669 case '\v':
670 case '\f':
671 name = "Invalid Character";
672 goto BadHeader;
673 break;
674 default:
675 flag = 0;
676 break;
678 p++;
681 /* Return (to be called later when we have more data)
682 * if we don't have an entire header. */
683 if (flag < 2)
684 return NULL;
687 * Parse all the headers.
689 fr->parseHeader = SCAN_CGI_FINISHED;
690 hasContentType = hasStatus = hasLocation = FALSE;
691 next = (char *)fr->header->elts;
692 for(;;) {
693 next = get_header_line(name = next, TRUE);
694 if (*name == '\0') {
695 break;
697 if ((p = strchr(name, ':')) == NULL) {
698 goto BadHeader;
700 value = p + 1;
701 while (p != name && isspace((unsigned char)*(p - 1))) {
702 p--;
704 if (p == name) {
705 goto BadHeader;
707 *p = '\0';
708 if (strpbrk(name, " \t") != NULL) {
709 *p = ' ';
710 goto BadHeader;
712 while (isspace((unsigned char)*value)) {
713 value++;
716 if (strcasecmp(name, "Status") == 0) {
717 int statusValue = strtol(value, NULL, 10);
719 if (hasStatus) {
720 goto DuplicateNotAllowed;
722 if (statusValue < 0) {
723 fr->parseHeader = SCAN_CGI_BAD_HEADER;
724 return ap_psprintf(r->pool, "invalid Status '%s'", value);
726 hasStatus = TRUE;
727 r->status = statusValue;
728 r->status_line = ap_pstrdup(r->pool, value);
729 continue;
732 if (fr->role == FCGI_RESPONDER) {
733 if (strcasecmp(name, "Content-type") == 0) {
734 if (hasContentType) {
735 goto DuplicateNotAllowed;
737 hasContentType = TRUE;
738 r->content_type = ap_pstrdup(r->pool, value);
739 continue;
742 if (strcasecmp(name, "Location") == 0) {
743 if (hasLocation) {
744 goto DuplicateNotAllowed;
746 hasLocation = TRUE;
747 ap_table_set(r->headers_out, "Location", value);
748 continue;
751 /* If the script wants them merged, it can do it */
752 ap_table_add(r->err_headers_out, name, value);
753 continue;
755 else {
756 ap_table_add(fr->authHeaders, name, value);
760 if (fr->role != FCGI_RESPONDER)
761 return NULL;
764 * Who responds, this handler or Apache?
766 if (hasLocation) {
767 const char *location = ap_table_get(r->headers_out, "Location");
769 * Based on internal redirect handling in mod_cgi.c...
771 * If a script wants to produce its own Redirect
772 * body, it now has to explicitly *say* "Status: 302"
774 if (r->status == 200) {
775 if(location[0] == '/') {
777 * Location is an relative path. This handler will
778 * consume all script output, then have Apache perform an
779 * internal redirect.
781 fr->parseHeader = SCAN_CGI_INT_REDIRECT;
782 return NULL;
783 } else {
785 * Location is an absolute URL. If the script didn't
786 * produce a Content-type header, this handler will
787 * consume all script output and then have Apache generate
788 * its standard redirect response. Otherwise this handler
789 * will transmit the script's response.
791 fr->parseHeader = SCAN_CGI_SRV_REDIRECT;
792 return NULL;
797 * We're responding. Send headers, buffer excess script output.
799 ap_send_http_header(r);
801 /* We need to reinstate our timeout, send_http_header() kill()s it */
802 ap_hard_timeout("FastCGI request processing", r);
804 if (r->header_only) {
805 /* we've got all we want from the server */
806 close_connection_to_fs(fr);
807 fr->exitStatusSet = 1;
808 fcgi_buf_reset(fr->clientOutputBuffer);
809 fcgi_buf_reset(fr->serverOutputBuffer);
810 return NULL;
813 len = fr->header->nelts - (next - fr->header->elts);
814 ap_assert(len >= 0);
815 ap_assert(BufferLength(fr->clientOutputBuffer) == 0);
816 if (BufferFree(fr->clientOutputBuffer) < len) {
817 fr->clientOutputBuffer = fcgi_buf_new(r->pool, len);
819 ap_assert(BufferFree(fr->clientOutputBuffer) >= len);
820 if (len > 0) {
821 int sent = fcgi_buf_add_block(fr->clientOutputBuffer, next, len);
822 ap_assert(sent == len);
824 return NULL;
826 BadHeader:
827 /* Log first line of a multi-line header */
828 if ((p = strpbrk(name, "\r\n")) != NULL)
829 *p = '\0';
830 fr->parseHeader = SCAN_CGI_BAD_HEADER;
831 return ap_psprintf(r->pool, "malformed header '%s'", name);
833 DuplicateNotAllowed:
834 fr->parseHeader = SCAN_CGI_BAD_HEADER;
835 return ap_psprintf(r->pool, "duplicate header '%s'", name);
839 * Read from the client filling both the FastCGI server buffer and the
840 * client buffer with the hopes of buffering the client data before
841 * making the connect() to the FastCGI server. This prevents slow
842 * clients from keeping the FastCGI server in processing longer than is
843 * necessary.
845 static int read_from_client_n_queue(fcgi_request *fr)
847 char *end;
848 int count;
849 long int countRead;
851 while (BufferFree(fr->clientInputBuffer) > 0 || BufferFree(fr->serverOutputBuffer) > 0) {
852 fcgi_protocol_queue_client_buffer(fr);
854 if (fr->expectingClientContent <= 0)
855 return OK;
857 fcgi_buf_get_free_block_info(fr->clientInputBuffer, &end, &count);
858 if (count == 0)
859 return OK;
861 if ((countRead = ap_get_client_block(fr->r, end, count)) < 0)
863 /* set the header scan state to done to prevent logging an error
864 * - hokey approach - probably should be using a unique value */
865 fr->parseHeader = SCAN_CGI_FINISHED;
866 return -1;
869 if (countRead == 0) {
870 fr->expectingClientContent = 0;
872 else {
873 fcgi_buf_add_update(fr->clientInputBuffer, countRead);
874 ap_reset_timeout(fr->r);
877 return OK;
880 static int write_to_client(fcgi_request *fr)
882 char *begin;
883 int count;
884 int rv;
885 #ifdef APACHE2
886 apr_bucket * bkt;
887 apr_bucket_brigade * bde;
888 apr_bucket_alloc_t * const bkt_alloc = fr->r->connection->bucket_alloc;
889 #endif
891 fcgi_buf_get_block_info(fr->clientOutputBuffer, &begin, &count);
892 if (count == 0)
893 return OK;
895 /* If fewer than count bytes are written, an error occured.
896 * ap_bwrite() typically forces a flushed write to the client, this
897 * effectively results in a block (and short packets) - it should
898 * be fixed, but I didn't win much support for the idea on new-httpd.
899 * So, without patching Apache, the best way to deal with this is
900 * to size the fcgi_bufs to hold all of the script output (within
901 * reason) so the script can be released from having to wait around
902 * for the transmission to the client to complete. */
904 #ifdef APACHE2
906 bde = apr_brigade_create(fr->r->pool, bkt_alloc);
907 bkt = apr_bucket_transient_create(begin, count, bkt_alloc);
908 APR_BRIGADE_INSERT_TAIL(bde, bkt);
910 if (fr->fs ? fr->fs->flush : dynamicFlush)
912 bkt = apr_bucket_flush_create(bkt_alloc);
913 APR_BRIGADE_INSERT_TAIL(bde, bkt);
916 rv = ap_pass_brigade(fr->r->output_filters, bde);
918 #elif defined(RUSSIAN_APACHE)
920 rv = (ap_rwrite(begin, count, fr->r) != count);
922 #else
924 rv = (ap_bwrite(fr->r->connection->client, begin, count) != count);
926 #endif
928 if (rv)
930 ap_log_rerror(FCGI_LOG_INFO_NOERRNO, fr->r,
931 "FastCGI: client stopped connection before send body completed");
932 return -1;
935 #ifndef APACHE2
937 ap_reset_timeout(fr->r);
939 /* Don't bother with a wrapped buffer, limiting exposure to slow
940 * clients. The BUFF routines don't allow a writev from above,
941 * and don't always memcpy to minimize small write()s, this should
942 * be fixed, but I didn't win much support for the idea on
943 * new-httpd - I'll have to _prove_ its a problem first.. */
945 /* The default behaviour used to be to flush with every write, but this
946 * can tie up the FastCGI server longer than is necessary so its an option now */
948 if (fr->fs ? fr->fs->flush : dynamicFlush)
950 #ifdef RUSSIAN_APACHE
951 rv = ap_rflush(fr->r);
952 #else
953 rv = ap_bflush(fr->r->connection->client);
954 #endif
956 if (rv)
958 ap_log_rerror(FCGI_LOG_INFO_NOERRNO, fr->r,
959 "FastCGI: client stopped connection before send body completed");
960 return -1;
963 ap_reset_timeout(fr->r);
966 #endif /* !APACHE2 */
968 fcgi_buf_toss(fr->clientOutputBuffer, count);
969 return OK;
972 /*******************************************************************************
973 * Determine the user and group the wrapper should be called with.
974 * Based on code in Apache's create_argv_cmd() (util_script.c).
976 static void set_uid_n_gid(request_rec *r, const char **user, const char **group)
978 if (fcgi_wrapper == NULL) {
979 *user = "-";
980 *group = "-";
981 return;
984 if (strncmp("/~", r->uri, 2) == 0) {
985 /* its a user dir uri, just send the ~user, and leave it to the PM */
986 char *end = strchr(r->uri + 2, '/');
988 if (end)
989 *user = memcpy(ap_pcalloc(r->pool, end - r->uri), r->uri + 1, end - r->uri - 1);
990 else
991 *user = ap_pstrdup(r->pool, r->uri + 1);
992 *group = "-";
994 else {
995 *user = ap_psprintf(r->pool, "%ld", (long) fcgi_util_get_server_uid(r->server));
996 *group = ap_psprintf(r->pool, "%ld", (long) fcgi_util_get_server_gid(r->server));
1000 static void send_request_complete(fcgi_request *fr)
1002 if (fr->completeTime.tv_sec)
1004 struct timeval qtime, rtime;
1006 timersub(&fr->queueTime, &fr->startTime, &qtime);
1007 timersub(&fr->completeTime, &fr->queueTime, &rtime);
1009 send_to_pm(FCGI_REQUEST_COMPLETE_JOB, fr->fs_path,
1010 fr->user, fr->group,
1011 qtime.tv_sec * 1000000 + qtime.tv_usec,
1012 rtime.tv_sec * 1000000 + rtime.tv_usec);
1017 /*******************************************************************************
1018 * Connect to the FastCGI server.
1020 static int open_connection_to_fs(fcgi_request *fr)
1022 struct timeval tval;
1023 fd_set write_fds, read_fds;
1024 int status;
1025 request_rec * const r = fr->r;
1026 pool * const rp = r->pool;
1027 const char *socket_path = NULL;
1028 struct sockaddr *socket_addr = NULL;
1029 int socket_addr_len = 0;
1030 #ifndef WIN32
1031 const char *err = NULL;
1032 #endif
1034 /* Create the connection point */
1035 if (fr->dynamic)
1037 socket_path = fcgi_util_socket_hash_filename(rp, fr->fs_path, fr->user, fr->group);
1038 socket_path = fcgi_util_socket_make_path_absolute(rp, socket_path, 1);
1040 #ifndef WIN32
1041 err = fcgi_util_socket_make_domain_addr(rp, (struct sockaddr_un **)&socket_addr,
1042 &socket_addr_len, socket_path);
1043 if (err) {
1044 ap_log_rerror(FCGI_LOG_ERR, r,
1045 "FastCGI: failed to connect to (dynamic) server \"%s\": "
1046 "%s", fr->fs_path, err);
1047 return FCGI_FAILED;
1049 #endif
1051 else
1053 #ifdef WIN32
1054 if (fr->fs->dest_addr != NULL) {
1055 socket_addr = fr->fs->dest_addr;
1057 else if (fr->fs->socket_addr) {
1058 socket_addr = fr->fs->socket_addr;
1060 else {
1061 socket_path = fr->fs->socket_path;
1063 #else
1064 socket_addr = fr->fs->socket_addr;
1065 #endif
1066 socket_addr_len = fr->fs->socket_addr_len;
1069 if (fr->dynamic)
1071 #ifdef WIN32
1072 if (fr->fs && fr->fs->restartTime)
1073 #else
1074 struct stat sock_stat;
1076 if (stat(socket_path, &sock_stat) == 0)
1077 #endif
1079 // It exists
1080 if (dynamicAutoUpdate)
1082 struct stat app_stat;
1084 /* TODO: follow sym links */
1086 if (stat(fr->fs_path, &app_stat) == 0)
1088 #ifdef WIN32
1089 if (fr->fs->startTime < app_stat.st_mtime)
1090 #else
1091 if (sock_stat.st_mtime < app_stat.st_mtime)
1092 #endif
1094 #ifndef WIN32
1095 struct timeval tv = {1, 0};
1096 #endif
1098 * There's a newer one, request a restart.
1100 send_to_pm(FCGI_SERVER_RESTART_JOB, fr->fs_path, fr->user, fr->group, 0, 0);
1102 #ifdef WIN32
1103 Sleep(1000);
1104 #else
1105 /* Avoid sleep/alarm interactions */
1106 ap_select(0, NULL, NULL, NULL, &tv);
1107 #endif
1112 else
1114 int i;
1116 send_to_pm(FCGI_SERVER_START_JOB, fr->fs_path, fr->user, fr->group, 0, 0);
1118 /* wait until it looks like its running - this shouldn't take
1119 * very long at all - the exception is when the sockets are
1120 * removed out from under a running application - the loop
1121 * limit addresses this (preventing spinning) */
1123 for (i = 10; i > 0; i--)
1125 #ifdef WIN32
1126 Sleep(500);
1128 fr->fs = fcgi_util_fs_get_by_id(fr->fs_path, 0, 0);
1130 if (fr->fs && fr->fs->restartTime)
1131 #else
1132 struct timeval tv = {0, 500000};
1134 /* Avoid sleep/alarm interactions */
1135 ap_select(0, NULL, NULL, NULL, &tv);
1137 if (stat(socket_path, &sock_stat) == 0)
1138 #endif
1140 break;
1144 if (i <= 0)
1146 ap_log_rerror(FCGI_LOG_ALERT, r,
1147 "FastCGI: failed to connect to (dynamic) server \"%s\": "
1148 "something is seriously wrong, any chance the "
1149 "socket/named_pipe directory was removed?, see the "
1150 "FastCgiIpcDir directive", fr->fs_path);
1151 return FCGI_FAILED;
1156 #ifdef WIN32
1157 if (socket_path)
1159 BOOL ready;
1160 DWORD connect_time;
1161 int rv;
1162 HANDLE wait_npipe_mutex;
1163 DWORD interval;
1164 DWORD max_connect_time = FCGI_NAMED_PIPE_CONNECT_TIMEOUT;
1166 fr->using_npipe_io = TRUE;
1168 if (fr->dynamic)
1170 interval = dynamicPleaseStartDelay * 1000;
1172 if (dynamicAppConnectTimeout) {
1173 max_connect_time = dynamicAppConnectTimeout;
1176 else
1178 interval = FCGI_NAMED_PIPE_CONNECT_TIMEOUT * 1000;
1180 if (fr->fs->appConnectTimeout) {
1181 max_connect_time = fr->fs->appConnectTimeout;
1185 fcgi_util_ticks(&fr->startTime);
1188 // xxx this handle should live somewhere (see CloseHandle()s below too)
1189 char * wait_npipe_mutex_name, * cp;
1190 wait_npipe_mutex_name = cp = ap_pstrdup(rp, socket_path);
1191 while ((cp = strchr(cp, '\\'))) *cp = '/';
1193 wait_npipe_mutex = CreateMutex(NULL, FALSE, wait_npipe_mutex_name);
1196 if (wait_npipe_mutex == NULL)
1198 ap_log_rerror(FCGI_LOG_ERR, r,
1199 "FastCGI: failed to connect to server \"%s\": "
1200 "can't create the WaitNamedPipe mutex", fr->fs_path);
1201 return FCGI_FAILED;
1204 SetLastError(ERROR_SUCCESS);
1206 rv = WaitForSingleObject(wait_npipe_mutex, max_connect_time * 1000);
1208 if (rv == WAIT_TIMEOUT || rv == WAIT_FAILED)
1210 if (fr->dynamic)
1212 send_to_pm(FCGI_REQUEST_TIMEOUT_JOB, fr->fs_path, fr->user, fr->group, 0, 0);
1214 ap_log_rerror(FCGI_LOG_ERR_NOERRNO, r,
1215 "FastCGI: failed to connect to server \"%s\": "
1216 "wait for a npipe instance failed", fr->fs_path);
1217 FCGIDBG3("interval=%d, max_connect_time=%d", interval, max_connect_time);
1218 CloseHandle(wait_npipe_mutex);
1219 return FCGI_FAILED;
1222 fcgi_util_ticks(&fr->queueTime);
1224 connect_time = fr->queueTime.tv_sec - fr->startTime.tv_sec;
1226 if (fr->dynamic)
1228 if (connect_time >= interval)
1230 send_to_pm(FCGI_REQUEST_TIMEOUT_JOB, fr->fs_path, fr->user, fr->group, 0, 0);
1231 FCGIDBG4("connect_time=%d, interval=%d, max_connect_time=%d", connect_time, interval, max_connect_time);
1233 if (max_connect_time - connect_time < interval)
1235 interval = max_connect_time - connect_time;
1238 else
1240 interval -= connect_time * 1000;
1243 for (;;)
1245 ready = WaitNamedPipe(socket_path, interval);
1247 if (ready)
1249 fr->fd = (SOCKET) CreateFile(socket_path,
1250 GENERIC_READ | GENERIC_WRITE,
1251 FILE_SHARE_READ | FILE_SHARE_WRITE,
1252 NULL, // no security attributes
1253 OPEN_EXISTING, // opens existing pipe
1254 FILE_FLAG_OVERLAPPED,
1255 NULL); // no template file
1257 if (fr->fd != (SOCKET) INVALID_HANDLE_VALUE)
1259 ReleaseMutex(wait_npipe_mutex);
1260 CloseHandle(wait_npipe_mutex);
1261 fcgi_util_ticks(&fr->queueTime);
1262 FCGIDBG2("got npipe connect: %s", fr->fs_path);
1263 return FCGI_OK;
1266 if (GetLastError() != ERROR_PIPE_BUSY
1267 && GetLastError() != ERROR_FILE_NOT_FOUND)
1269 ap_log_rerror(FCGI_LOG_ERR, r,
1270 "FastCGI: failed to connect to server \"%s\": "
1271 "CreateFile() failed", fr->fs_path);
1272 break;
1275 FCGIDBG2("missed npipe connect: %s", fr->fs_path);
1278 if (fr->dynamic)
1280 send_to_pm(FCGI_REQUEST_TIMEOUT_JOB, fr->fs_path, fr->user, fr->group, 0, 0);
1283 fcgi_util_ticks(&fr->queueTime);
1285 connect_time = fr->queueTime.tv_sec - fr->startTime.tv_sec;
1287 FCGIDBG5("interval=%d, max_connect_time=%d, connect_time=%d, ready=%d", interval, max_connect_time, connect_time, ready);
1289 if (connect_time >= max_connect_time)
1291 ap_log_rerror(FCGI_LOG_ERR, r,
1292 "FastCGI: failed to connect to server \"%s\": "
1293 "CreateFile()/WaitNamedPipe() timed out", fr->fs_path);
1294 break;
1298 ReleaseMutex(wait_npipe_mutex);
1299 CloseHandle(wait_npipe_mutex);
1300 fr->fd = INVALID_SOCKET;
1301 return FCGI_FAILED;
1304 #endif
1306 /* Create the socket */
1307 fr->fd = socket(socket_addr->sa_family, SOCK_STREAM, 0);
1309 #ifdef WIN32
1310 if (fr->fd == INVALID_SOCKET) {
1311 errno = WSAGetLastError(); // Not sure this is going to work as expected
1312 #else
1313 if (fr->fd < 0) {
1314 #endif
1315 ap_log_rerror(FCGI_LOG_ERR_ERRNO, r,
1316 "FastCGI: failed to connect to server \"%s\": "
1317 "socket() failed", fr->fs_path);
1318 return FCGI_FAILED;
1321 #ifndef WIN32
1322 if (fr->fd >= FD_SETSIZE) {
1323 ap_log_rerror(FCGI_LOG_ERR, r,
1324 "FastCGI: failed to connect to server \"%s\": "
1325 "socket file descriptor (%u) is larger than "
1326 "FD_SETSIZE (%u), you probably need to rebuild Apache with a "
1327 "larger FD_SETSIZE", fr->fs_path, fr->fd, FD_SETSIZE);
1328 return FCGI_FAILED;
1330 #endif
1332 /* If appConnectTimeout is non-zero, setup do a non-blocking connect */
1333 if ((fr->dynamic && dynamicAppConnectTimeout) || (!fr->dynamic && fr->fs->appConnectTimeout)) {
1334 set_nonblocking(fr, TRUE);
1337 if (fr->dynamic) {
1338 fcgi_util_ticks(&fr->startTime);
1341 /* Connect */
1342 if (connect(fr->fd, (struct sockaddr *)socket_addr, socket_addr_len) == 0)
1343 goto ConnectionComplete;
1345 #ifdef WIN32
1347 errno = WSAGetLastError();
1348 if (errno != WSAEWOULDBLOCK) {
1349 ap_log_rerror(FCGI_LOG_ERR_ERRNO, r,
1350 "FastCGI: failed to connect to server \"%s\": "
1351 "connect() failed", fr->fs_path);
1352 return FCGI_FAILED;
1355 #else
1357 /* ECONNREFUSED means the listen queue is full (or there isn't one).
1358 * With dynamic I can at least make sure the PM knows this is occuring */
1359 if (fr->dynamic && errno == ECONNREFUSED) {
1360 /* @@@ This might be better as some other "kind" of message */
1361 send_to_pm(FCGI_REQUEST_TIMEOUT_JOB, fr->fs_path, fr->user, fr->group, 0, 0);
1363 errno = ECONNREFUSED;
1366 if (errno != EINPROGRESS) {
1367 ap_log_rerror(FCGI_LOG_ERR, r,
1368 "FastCGI: failed to connect to server \"%s\": "
1369 "connect() failed", fr->fs_path);
1370 return FCGI_FAILED;
1373 #endif
1375 /* The connect() is non-blocking */
1377 errno = 0;
1379 if (fr->dynamic) {
1380 do {
1381 FD_ZERO(&write_fds);
1382 FD_SET(fr->fd, &write_fds);
1383 read_fds = write_fds;
1384 tval.tv_sec = dynamicPleaseStartDelay;
1385 tval.tv_usec = 0;
1387 status = ap_select((fr->fd+1), &read_fds, &write_fds, NULL, &tval);
1388 if (status < 0)
1389 break;
1391 fcgi_util_ticks(&fr->queueTime);
1393 if (status > 0)
1394 break;
1396 /* select() timed out */
1397 send_to_pm(FCGI_REQUEST_TIMEOUT_JOB, fr->fs_path, fr->user, fr->group, 0, 0);
1398 } while ((fr->queueTime.tv_sec - fr->startTime.tv_sec) < (int)dynamicAppConnectTimeout);
1400 /* XXX These can be moved down when dynamic vars live is a struct */
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 */
1409 else {
1410 tval.tv_sec = fr->fs->appConnectTimeout;
1411 tval.tv_usec = 0;
1412 FD_ZERO(&write_fds);
1413 FD_SET(fr->fd, &write_fds);
1414 read_fds = write_fds;
1416 status = ap_select((fr->fd+1), &read_fds, &write_fds, NULL, &tval);
1418 if (status == 0) {
1419 ap_log_rerror(FCGI_LOG_ERR_NOERRNO, r,
1420 "FastCGI: failed to connect to server \"%s\": "
1421 "connect() timed out (appConnTimeout=%dsec)",
1422 fr->fs_path, dynamicAppConnectTimeout);
1423 return FCGI_FAILED;
1425 } /* !dynamic */
1427 if (status < 0) {
1428 #ifdef WIN32
1429 errno = WSAGetLastError();
1430 #endif
1431 ap_log_rerror(FCGI_LOG_ERR_ERRNO, r,
1432 "FastCGI: failed to connect to server \"%s\": "
1433 "select() failed", fr->fs_path);
1434 return FCGI_FAILED;
1437 if (FD_ISSET(fr->fd, &write_fds) || FD_ISSET(fr->fd, &read_fds)) {
1438 int error = 0;
1439 NET_SIZE_T len = sizeof(error);
1441 if (getsockopt(fr->fd, SOL_SOCKET, SO_ERROR, (char *)&error, &len) < 0) {
1442 /* Solaris pending error */
1443 #ifdef WIN32
1444 errno = WSAGetLastError();
1445 #endif
1446 ap_log_rerror(FCGI_LOG_ERR_ERRNO, r,
1447 "FastCGI: failed to connect to server \"%s\": "
1448 "select() failed (Solaris pending error)", fr->fs_path);
1449 return FCGI_FAILED;
1452 if (error != 0) {
1453 /* Berkeley-derived pending error */
1454 errno = error;
1455 ap_log_rerror(FCGI_LOG_ERR_ERRNO, r,
1456 "FastCGI: failed to connect to server \"%s\": "
1457 "select() failed (pending error)", fr->fs_path);
1458 return FCGI_FAILED;
1461 else {
1462 #ifdef WIN32
1463 errno = WSAGetLastError();
1464 #endif
1465 ap_log_rerror(FCGI_LOG_ERR_ERRNO, r,
1466 "FastCGI: failed to connect to server \"%s\": "
1467 "select() error - THIS CAN'T HAPPEN!", fr->fs_path);
1468 return FCGI_FAILED;
1471 ConnectionComplete:
1472 /* Return to blocking mode if it was set up */
1473 if ((fr->dynamic && dynamicAppConnectTimeout) || (!fr->dynamic && fr->fs->appConnectTimeout)) {
1474 set_nonblocking(fr, FALSE);
1477 #ifdef TCP_NODELAY
1478 if (socket_addr->sa_family == AF_INET) {
1479 /* We shouldn't be sending small packets and there's no application
1480 * level ack of the data we send, so disable Nagle */
1481 int set = 1;
1482 setsockopt(fr->fd, IPPROTO_TCP, TCP_NODELAY, (char *)&set, sizeof(set));
1484 #endif
1486 return FCGI_OK;
1489 static void sink_client_data(fcgi_request *fr)
1491 char *base;
1492 int size;
1494 fcgi_buf_reset(fr->clientInputBuffer);
1495 fcgi_buf_get_free_block_info(fr->clientInputBuffer, &base, &size);
1496 while (ap_get_client_block(fr->r, base, size) > 0);
1499 static apcb_t cleanup(void *data)
1501 fcgi_request * const fr = (fcgi_request *) data;
1503 if (fr == NULL) return APCB_OK;
1505 /* its more than likely already run, but... */
1506 close_connection_to_fs(fr);
1508 send_request_complete(fr);
1510 if (fr->fs_stderr_len) {
1511 ap_log_rerror(FCGI_LOG_ERR_NOERRNO, fr->r,
1512 "FastCGI: server \"%s\" stderr: %s", fr->fs_path, fr->fs_stderr);
1515 return APCB_OK;
1518 #ifdef WIN32
1519 static int npipe_io(fcgi_request * const fr)
1521 request_rec * const r = fr->r;
1522 enum
1524 STATE_ENV_SEND,
1525 STATE_CLIENT_RECV,
1526 STATE_SERVER_SEND,
1527 STATE_SERVER_RECV,
1528 STATE_CLIENT_SEND,
1529 STATE_ERROR
1531 state = STATE_ENV_SEND;
1532 env_status env_status;
1533 int client_recv;
1534 int dynamic_first_recv = fr->dynamic;
1535 int idle_timeout = fr->dynamic ? dynamic_idle_timeout : fr->fs->idle_timeout;
1536 int send_pending = 0;
1537 int recv_pending = 0;
1538 int client_send = 0;
1539 int rv;
1540 OVERLAPPED rov = { 0 };
1541 OVERLAPPED sov = { 0 };
1542 HANDLE events[2];
1543 struct timeval timeout;
1544 struct timeval dynamic_last_io_time = {0, 0};
1545 int did_io = 1;
1546 pool * const rp = r->pool;
1548 DWORD recv_count = 0;
1550 if (fr->role == FCGI_RESPONDER)
1552 client_recv = (fr->expectingClientContent != 0);
1555 idle_timeout = fr->dynamic ? dynamic_idle_timeout : fr->fs->idle_timeout;
1557 env_status.envp = NULL;
1559 events[0] = CreateEvent(NULL, TRUE, FALSE, NULL);
1560 events[1] = CreateEvent(NULL, TRUE, FALSE, NULL);
1561 sov.hEvent = events[0];
1562 rov.hEvent = events[1];
1564 if (fr->dynamic)
1566 dynamic_last_io_time = fr->startTime;
1568 if (dynamicAppConnectTimeout)
1570 struct timeval qwait;
1571 timersub(&fr->queueTime, &fr->startTime, &qwait);
1572 dynamic_first_recv = qwait.tv_sec / dynamicPleaseStartDelay + 1;
1576 ap_hard_timeout("FastCGI request processing", r);
1578 while (state != STATE_CLIENT_SEND)
1580 DWORD msec_timeout;
1582 switch (state)
1584 case STATE_ENV_SEND:
1586 if (fcgi_protocol_queue_env(r, fr, &env_status) == 0)
1588 goto SERVER_SEND;
1591 state = STATE_CLIENT_RECV;
1593 /* fall through */
1595 case STATE_CLIENT_RECV:
1597 if (read_from_client_n_queue(fr) != OK)
1599 state = STATE_ERROR;
1600 break;
1603 if (fr->eofSent)
1605 state = STATE_SERVER_SEND;
1608 /* fall through */
1610 SERVER_SEND:
1612 case STATE_SERVER_SEND:
1614 if (! send_pending && BufferLength(fr->serverOutputBuffer))
1616 Buffer * b = fr->serverOutputBuffer;
1617 DWORD sent, len;
1619 len = min(b->length, b->data + b->size - b->begin);
1621 if (WriteFile((HANDLE) fr->fd, b->begin, len, &sent, &sov))
1623 /* sov.hEvent is set */
1624 fcgi_buf_removed(b, sent);
1626 else if (GetLastError() == ERROR_IO_PENDING)
1628 send_pending = 1;
1630 else
1632 ap_log_rerror(FCGI_LOG_ERR, r, "FastCGI: comm with server "
1633 "\"%s\" aborted: WriteFile() failed", fr->fs_path);
1634 state = STATE_ERROR;
1635 break;
1639 /* fall through */
1641 case STATE_SERVER_RECV:
1644 * Only get more data when the serverInputBuffer is empty.
1645 * Otherwise we may already have the END_REQUEST buffered
1646 * (but not processed) and a read on a closed named pipe
1647 * results in an error that is normally abnormal.
1649 if (! recv_pending && BufferLength(fr->serverInputBuffer) == 0)
1651 Buffer * b = fr->serverInputBuffer;
1652 DWORD rcvd, len;
1654 len = min(b->size - b->length, b->data + b->size - b->end);
1656 if (ReadFile((HANDLE) fr->fd, b->end, len, &rcvd, &rov))
1658 fcgi_buf_added(b, rcvd);
1659 recv_count += rcvd;
1660 ResetEvent(rov.hEvent);
1661 if (dynamic_first_recv)
1663 dynamic_first_recv = 0;
1666 else if (GetLastError() == ERROR_IO_PENDING)
1668 recv_pending = 1;
1670 else if (GetLastError() == ERROR_HANDLE_EOF)
1672 fr->keepReadingFromFcgiApp = FALSE;
1673 state = STATE_CLIENT_SEND;
1674 ResetEvent(rov.hEvent);
1675 break;
1677 else if (GetLastError() == ERROR_NO_DATA)
1679 break;
1681 else
1683 ap_log_rerror(FCGI_LOG_ERR, r, "FastCGI: comm with server "
1684 "\"%s\" aborted: ReadFile() failed", fr->fs_path);
1685 state = STATE_ERROR;
1686 break;
1690 /* fall through */
1692 case STATE_CLIENT_SEND:
1694 if (client_send || ! BufferFree(fr->clientOutputBuffer))
1696 if (write_to_client(fr))
1698 state = STATE_ERROR;
1699 break;
1702 client_send = 0;
1705 break;
1707 default:
1709 ap_assert(0);
1712 if (state == STATE_ERROR)
1714 break;
1717 /* setup the io timeout */
1719 if (BufferLength(fr->clientOutputBuffer))
1721 /* don't let client data sit too long, it might be a push */
1722 timeout.tv_sec = 0;
1723 timeout.tv_usec = 100000;
1725 else if (dynamic_first_recv)
1727 int delay;
1728 struct timeval qwait;
1730 fcgi_util_ticks(&fr->queueTime);
1732 if (did_io)
1734 /* a send() succeeded last pass */
1735 dynamic_last_io_time = fr->queueTime;
1737 else
1739 /* timed out last pass */
1740 struct timeval idle_time;
1742 timersub(&fr->queueTime, &dynamic_last_io_time, &idle_time);
1744 if (idle_time.tv_sec > idle_timeout)
1746 send_to_pm(FCGI_REQUEST_TIMEOUT_JOB, fr->fs_path, fr->user, fr->group, 0, 0);
1747 ap_log_rerror(FCGI_LOG_ERR_NOERRNO, r, "FastCGI: comm "
1748 "with (dynamic) server \"%s\" aborted: (first read) "
1749 "idle timeout (%d sec)", fr->fs_path, idle_timeout);
1750 state = STATE_ERROR;
1751 break;
1755 timersub(&fr->queueTime, &fr->startTime, &qwait);
1757 delay = dynamic_first_recv * dynamicPleaseStartDelay;
1759 if (qwait.tv_sec < delay)
1761 timeout.tv_sec = delay;
1762 timeout.tv_usec = 100000; /* fudge for select() slop */
1763 timersub(&timeout, &qwait, &timeout);
1765 else
1767 /* Killed time somewhere.. client read? */
1768 send_to_pm(FCGI_REQUEST_TIMEOUT_JOB, fr->fs_path, fr->user, fr->group, 0, 0);
1769 dynamic_first_recv = qwait.tv_sec / dynamicPleaseStartDelay + 1;
1770 timeout.tv_sec = dynamic_first_recv * dynamicPleaseStartDelay;
1771 timeout.tv_usec = 100000; /* fudge for select() slop */
1772 timersub(&timeout, &qwait, &timeout);
1775 else
1777 timeout.tv_sec = idle_timeout;
1778 timeout.tv_usec = 0;
1781 /* require a pended recv otherwise the app can deadlock */
1782 if (recv_pending)
1784 msec_timeout = timeout.tv_sec * 1000 + timeout.tv_usec / 1000;
1786 rv = WaitForMultipleObjects(2, events, FALSE, msec_timeout);
1788 if (rv == WAIT_TIMEOUT)
1790 did_io = 0;
1792 if (BufferLength(fr->clientOutputBuffer))
1794 client_send = 1;
1796 else if (dynamic_first_recv)
1798 struct timeval qwait;
1800 fcgi_util_ticks(&fr->queueTime);
1801 timersub(&fr->queueTime, &fr->startTime, &qwait);
1803 send_to_pm(FCGI_REQUEST_TIMEOUT_JOB, fr->fs_path, fr->user, fr->group, 0, 0);
1805 dynamic_first_recv = qwait.tv_sec / dynamicPleaseStartDelay + 1;
1807 else
1809 ap_log_rerror(FCGI_LOG_ERR_NOERRNO, r, "FastCGI: comm with "
1810 "server \"%s\" aborted: idle timeout (%d sec)",
1811 fr->fs_path, idle_timeout);
1812 state = STATE_ERROR;
1813 break;
1816 else
1818 int i = rv - WAIT_OBJECT_0;
1820 did_io = 1;
1822 if (i == 0)
1824 if (send_pending)
1826 DWORD sent;
1828 if (GetOverlappedResult((HANDLE) fr->fd, &sov, &sent, FALSE))
1830 send_pending = 0;
1831 fcgi_buf_removed(fr->serverOutputBuffer, sent);
1833 else
1835 ap_log_rerror(FCGI_LOG_ERR, r, "FastCGI: comm with server "
1836 "\"%s\" aborted: GetOverlappedResult() failed", fr->fs_path);
1837 state = STATE_ERROR;
1838 break;
1842 ResetEvent(sov.hEvent);
1844 else
1846 DWORD rcvd;
1848 ap_assert(i == 1);
1850 recv_pending = 0;
1851 ResetEvent(rov.hEvent);
1853 if (GetOverlappedResult((HANDLE) fr->fd, &rov, &rcvd, FALSE))
1855 fcgi_buf_added(fr->serverInputBuffer, rcvd);
1856 if (dynamic_first_recv)
1858 dynamic_first_recv = 0;
1861 else
1863 ap_log_rerror(FCGI_LOG_ERR, r, "FastCGI: comm with server "
1864 "\"%s\" aborted: GetOverlappedResult() failed", fr->fs_path);
1865 state = STATE_ERROR;
1866 break;
1872 if (fcgi_protocol_dequeue(rp, fr))
1874 state = STATE_ERROR;
1875 break;
1878 if (fr->parseHeader == SCAN_CGI_READING_HEADERS)
1880 const char * err = process_headers(r, fr);
1881 if (err)
1883 ap_log_rerror(FCGI_LOG_ERR_NOERRNO, r,
1884 "FastCGI: comm with server \"%s\" aborted: "
1885 "error parsing headers: %s", fr->fs_path, err);
1886 state = STATE_ERROR;
1887 break;
1891 if (fr->exitStatusSet)
1893 fr->keepReadingFromFcgiApp = FALSE;
1894 state = STATE_CLIENT_SEND;
1895 break;
1899 if (! fr->exitStatusSet || ! fr->eofSent)
1901 CancelIo((HANDLE) fr->fd);
1904 CloseHandle(rov.hEvent);
1905 CloseHandle(sov.hEvent);
1907 return (state == STATE_ERROR);
1909 #endif /* WIN32 */
1911 static int socket_io(fcgi_request * const fr)
1913 enum
1915 STATE_SOCKET_NONE,
1916 STATE_ENV_SEND,
1917 STATE_CLIENT_RECV,
1918 STATE_SERVER_SEND,
1919 STATE_SERVER_RECV,
1920 STATE_CLIENT_SEND,
1921 STATE_ERROR,
1922 STATE_CLIENT_ERROR
1924 state = STATE_ENV_SEND;
1926 request_rec * const r = fr->r;
1928 struct timeval timeout;
1929 struct timeval dynamic_last_io_time = {0, 0};
1930 fd_set read_set;
1931 fd_set write_set;
1932 int nfds = fr->fd + 1;
1933 int select_status = 1;
1934 int idle_timeout;
1935 int rv;
1936 int dynamic_first_recv = fr->dynamic ? 1 : 0;
1937 int client_send = FALSE;
1938 int client_recv = FALSE;
1939 env_status env;
1940 pool *rp = r->pool;
1942 if (fr->role == FCGI_RESPONDER)
1944 client_recv = (fr->expectingClientContent != 0);
1947 idle_timeout = fr->dynamic ? dynamic_idle_timeout : fr->fs->idle_timeout;
1949 env.envp = NULL;
1951 if (fr->dynamic)
1953 dynamic_last_io_time = fr->startTime;
1955 if (dynamicAppConnectTimeout)
1957 struct timeval qwait;
1958 timersub(&fr->queueTime, &fr->startTime, &qwait);
1959 dynamic_first_recv = qwait.tv_sec / dynamicPleaseStartDelay + 1;
1963 ap_hard_timeout("FastCGI request processing", r);
1965 set_nonblocking(fr, TRUE);
1967 for (;;)
1969 FD_ZERO(&read_set);
1970 FD_ZERO(&write_set);
1972 switch (state)
1974 case STATE_ENV_SEND:
1976 if (fcgi_protocol_queue_env(r, fr, &env) == 0)
1978 goto SERVER_SEND;
1981 state = STATE_CLIENT_RECV;
1983 /* fall through */
1985 case STATE_CLIENT_RECV:
1987 if (read_from_client_n_queue(fr))
1989 state = STATE_CLIENT_ERROR;
1990 break;
1993 if (fr->eofSent)
1995 state = STATE_SERVER_SEND;
1998 /* fall through */
2000 SERVER_SEND:
2002 case STATE_SERVER_SEND:
2004 if (BufferLength(fr->serverOutputBuffer))
2006 FD_SET(fr->fd, &write_set);
2008 else
2010 ap_assert(fr->eofSent);
2011 state = STATE_SERVER_RECV;
2014 /* fall through */
2016 case STATE_SERVER_RECV:
2018 FD_SET(fr->fd, &read_set);
2020 /* fall through */
2022 case STATE_CLIENT_SEND:
2024 if (client_send || ! BufferFree(fr->clientOutputBuffer))
2026 if (write_to_client(fr))
2028 state = STATE_CLIENT_ERROR;
2029 break;
2032 client_send = 0;
2035 break;
2037 case STATE_ERROR:
2038 case STATE_CLIENT_ERROR:
2040 break;
2042 default:
2044 ap_assert(0);
2047 if (state == STATE_CLIENT_ERROR || state == STATE_ERROR)
2049 break;
2052 /* setup the io timeout */
2054 if (BufferLength(fr->clientOutputBuffer))
2056 /* don't let client data sit too long, it might be a push */
2057 timeout.tv_sec = 0;
2058 timeout.tv_usec = 100000;
2060 else if (dynamic_first_recv)
2062 int delay;
2063 struct timeval qwait;
2065 fcgi_util_ticks(&fr->queueTime);
2067 if (select_status)
2069 /* a send() succeeded last pass */
2070 dynamic_last_io_time = fr->queueTime;
2072 else
2074 /* timed out last pass */
2075 struct timeval idle_time;
2077 timersub(&fr->queueTime, &dynamic_last_io_time, &idle_time);
2079 if (idle_time.tv_sec > idle_timeout)
2081 send_to_pm(FCGI_REQUEST_TIMEOUT_JOB, fr->fs_path, fr->user, fr->group, 0, 0);
2082 ap_log_rerror(FCGI_LOG_ERR_NOERRNO, r, "FastCGI: comm "
2083 "with (dynamic) server \"%s\" aborted: (first read) "
2084 "idle timeout (%d sec)", fr->fs_path, idle_timeout);
2085 state = STATE_ERROR;
2086 break;
2090 timersub(&fr->queueTime, &fr->startTime, &qwait);
2092 delay = dynamic_first_recv * dynamicPleaseStartDelay;
2094 FCGIDBG5("qwait=%ld.%06ld delay=%d first_recv=%d", qwait.tv_sec, qwait.tv_usec, delay, dynamic_first_recv);
2096 if (qwait.tv_sec < delay)
2098 timeout.tv_sec = delay;
2099 timeout.tv_usec = 100000; /* fudge for select() slop */
2100 timersub(&timeout, &qwait, &timeout);
2102 else
2104 /* Killed time somewhere.. client read? */
2105 send_to_pm(FCGI_REQUEST_TIMEOUT_JOB, fr->fs_path, fr->user, fr->group, 0, 0);
2106 dynamic_first_recv = qwait.tv_sec / dynamicPleaseStartDelay + 1;
2107 timeout.tv_sec = dynamic_first_recv * dynamicPleaseStartDelay;
2108 timeout.tv_usec = 100000; /* fudge for select() slop */
2109 timersub(&timeout, &qwait, &timeout);
2112 else
2114 timeout.tv_sec = idle_timeout;
2115 timeout.tv_usec = 0;
2118 /* wait on the socket */
2119 select_status = ap_select(nfds, &read_set, &write_set, NULL, &timeout);
2121 if (select_status < 0)
2123 ap_log_rerror(FCGI_LOG_ERR_ERRNO, r, "FastCGI: comm with server "
2124 "\"%s\" aborted: select() failed", fr->fs_path);
2125 state = STATE_ERROR;
2126 break;
2129 if (select_status == 0)
2131 /* select() timeout */
2133 if (BufferLength(fr->clientOutputBuffer))
2135 if (fr->role == FCGI_RESPONDER)
2137 client_send = TRUE;
2140 else if (dynamic_first_recv)
2142 struct timeval qwait;
2144 fcgi_util_ticks(&fr->queueTime);
2145 timersub(&fr->queueTime, &fr->startTime, &qwait);
2147 send_to_pm(FCGI_REQUEST_TIMEOUT_JOB, fr->fs_path, fr->user, fr->group, 0, 0);
2149 dynamic_first_recv = qwait.tv_sec / dynamicPleaseStartDelay + 1;
2150 continue;
2152 else
2154 ap_log_rerror(FCGI_LOG_ERR_NOERRNO, r, "FastCGI: comm with "
2155 "server \"%s\" aborted: idle timeout (%d sec)",
2156 fr->fs_path, idle_timeout);
2157 state = STATE_ERROR;
2161 if (FD_ISSET(fr->fd, &write_set))
2163 /* send to the server */
2165 rv = fcgi_buf_socket_send(fr->serverOutputBuffer, fr->fd);
2167 if (rv < 0)
2169 ap_log_rerror(FCGI_LOG_ERR, r, "FastCGI: comm with server "
2170 "\"%s\" aborted: write failed", fr->fs_path);
2171 state = STATE_ERROR;
2172 break;
2176 if (FD_ISSET(fr->fd, &read_set))
2178 /* recv from the server */
2180 if (dynamic_first_recv)
2182 dynamic_first_recv = 0;
2183 fcgi_util_ticks(&fr->queueTime);
2186 rv = fcgi_buf_socket_recv(fr->serverInputBuffer, fr->fd);
2188 if (rv < 0)
2190 ap_log_rerror(FCGI_LOG_ERR, r, "FastCGI: comm with server "
2191 "\"%s\" aborted: read failed", fr->fs_path);
2192 state = STATE_ERROR;
2193 break;
2196 if (rv == 0)
2198 fr->keepReadingFromFcgiApp = FALSE;
2199 state = STATE_CLIENT_SEND;
2200 break;
2204 if (fcgi_protocol_dequeue(rp, fr))
2206 state = STATE_ERROR;
2207 break;
2210 if (fr->parseHeader == SCAN_CGI_READING_HEADERS)
2212 const char * err = process_headers(r, fr);
2213 if (err)
2215 ap_log_rerror(FCGI_LOG_ERR_NOERRNO, r,
2216 "FastCGI: comm with server \"%s\" aborted: "
2217 "error parsing headers: %s", fr->fs_path, err);
2218 state = STATE_ERROR;
2219 break;
2223 if (fr->exitStatusSet)
2225 fr->keepReadingFromFcgiApp = FALSE;
2226 state = STATE_CLIENT_SEND;
2227 break;
2231 return (state == STATE_ERROR);
2235 /*----------------------------------------------------------------------
2236 * This is the core routine for moving data between the FastCGI
2237 * application and the Web server's client.
2239 static int do_work(request_rec * const r, fcgi_request * const fr)
2241 int rv;
2242 pool *rp = r->pool;
2244 fcgi_protocol_queue_begin_request(fr);
2246 if (fr->role == FCGI_RESPONDER)
2248 rv = ap_setup_client_block(r, REQUEST_CHUNKED_ERROR);
2249 if (rv != OK)
2251 ap_kill_timeout(r);
2252 return rv;
2255 fr->expectingClientContent = ap_should_client_block(r);
2258 ap_block_alarms();
2259 ap_register_cleanup(rp, (void *)fr, cleanup, ap_null_cleanup);
2260 ap_unblock_alarms();
2262 ap_hard_timeout("connect() to FastCGI server", r);
2264 /* Connect to the FastCGI Application */
2265 if (open_connection_to_fs(fr) != FCGI_OK)
2267 ap_kill_timeout(r);
2268 return HTTP_INTERNAL_SERVER_ERROR;
2271 #ifdef WIN32
2272 if (fr->using_npipe_io)
2274 rv = npipe_io(fr);
2276 else
2277 #endif
2279 rv = socket_io(fr);
2282 /* comm with the server is done */
2283 close_connection_to_fs(fr);
2285 if (fr->role == FCGI_RESPONDER)
2287 sink_client_data(fr);
2290 while (rv == 0 && (BufferLength(fr->serverInputBuffer) || BufferLength(fr->clientOutputBuffer)))
2292 if (fcgi_protocol_dequeue(rp, fr))
2294 rv = HTTP_INTERNAL_SERVER_ERROR;
2297 if (fr->parseHeader == SCAN_CGI_READING_HEADERS)
2299 const char * err = process_headers(r, fr);
2300 if (err)
2302 ap_log_rerror(FCGI_LOG_ERR_NOERRNO, r,
2303 "FastCGI: comm with server \"%s\" aborted: "
2304 "error parsing headers: %s", fr->fs_path, err);
2305 rv = HTTP_INTERNAL_SERVER_ERROR;
2309 if (fr->role == FCGI_RESPONDER)
2311 if (write_to_client(fr))
2313 break;
2316 else
2318 fcgi_buf_reset(fr->clientOutputBuffer);
2322 switch (fr->parseHeader)
2324 case SCAN_CGI_FINISHED:
2326 if (fr->role == FCGI_RESPONDER)
2328 /* RUSSIAN_APACHE requires rflush() over bflush() */
2329 ap_rflush(r);
2330 #ifndef APACHE2
2331 ap_bgetopt(r->connection->client, BO_BYTECT, &r->bytes_sent);
2332 #endif
2335 /* fall through */
2337 case SCAN_CGI_INT_REDIRECT:
2338 case SCAN_CGI_SRV_REDIRECT:
2340 break;
2342 case SCAN_CGI_READING_HEADERS:
2344 ap_log_rerror(FCGI_LOG_ERR_NOERRNO, r, "FastCGI: incomplete headers "
2345 "(%d bytes) received from server \"%s\"", fr->header->nelts, fr->fs_path);
2347 /* fall through */
2349 case SCAN_CGI_BAD_HEADER:
2351 rv = HTTP_INTERNAL_SERVER_ERROR;
2352 break;
2354 default:
2356 ap_assert(0);
2357 rv = HTTP_INTERNAL_SERVER_ERROR;
2360 ap_kill_timeout(r);
2361 return rv;
2364 static fcgi_request *create_fcgi_request(request_rec * const r, const char *path)
2366 const char *fs_path;
2367 pool * const p = r->pool;
2368 fcgi_server *fs;
2369 fcgi_request * const fr = (fcgi_request *)ap_pcalloc(p, sizeof(fcgi_request));
2371 fs_path = path ? path : r->filename;
2373 fs = fcgi_util_fs_get_by_id(fs_path, fcgi_util_get_server_uid(r->server),
2374 fcgi_util_get_server_gid(r->server));
2375 if (fs == NULL)
2377 const char * err;
2378 struct stat *my_finfo;
2380 /* dynamic? */
2382 #ifndef APACHE2
2383 if (path == NULL)
2385 /* AP2: its bogus that we don't make use of r->finfo, but
2386 * its an apr_finfo_t and there is no apr_os_finfo_get() */
2388 my_finfo = &r->finfo;
2390 else
2391 #endif
2393 my_finfo = (struct stat *) ap_palloc(p, sizeof(struct stat));
2395 if (stat(fs_path, my_finfo) < 0)
2397 ap_log_rerror(FCGI_LOG_ERR_ERRNO, r,
2398 "FastCGI: stat() of \"%s\" failed", fs_path);
2399 return NULL;
2403 err = fcgi_util_fs_is_path_ok(p, fs_path, my_finfo);
2405 if (err)
2407 ap_log_rerror(FCGI_LOG_ERR_NOERRNO, r,
2408 "FastCGI: invalid (dynamic) server \"%s\": %s", fs_path, err);
2409 return NULL;
2413 fr->serverInputBuffer = fcgi_buf_new(p, SERVER_BUFSIZE);
2414 fr->serverOutputBuffer = fcgi_buf_new(p, SERVER_BUFSIZE);
2415 fr->clientInputBuffer = fcgi_buf_new(p, SERVER_BUFSIZE);
2416 fr->clientOutputBuffer = fcgi_buf_new(p, SERVER_BUFSIZE);
2417 fr->erBufPtr = fcgi_buf_new(p, sizeof(FCGI_EndRequestBody) + 1);
2418 fr->gotHeader = FALSE;
2419 fr->parseHeader = SCAN_CGI_READING_HEADERS;
2420 fr->header = ap_make_array(p, 1, 1);
2421 fr->fs_stderr = NULL;
2422 fr->r = r;
2423 fr->readingEndRequestBody = FALSE;
2424 fr->exitStatus = 0;
2425 fr->exitStatusSet = FALSE;
2426 fr->requestId = 1; /* anything but zero is OK here */
2427 fr->eofSent = FALSE;
2428 fr->role = FCGI_RESPONDER;
2429 fr->expectingClientContent = FALSE;
2430 fr->keepReadingFromFcgiApp = TRUE;
2431 fr->fs = fs;
2432 fr->fs_path = fs_path;
2433 fr->authHeaders = ap_make_table(p, 10);
2434 #ifdef WIN32
2435 fr->fd = INVALID_SOCKET;
2436 fr->dynamic = ((fs == NULL) || (fs->directive == APP_CLASS_DYNAMIC)) ? TRUE : FALSE;
2437 fr->using_npipe_io = FALSE;
2438 #else
2439 fr->dynamic = (fs == NULL) ? TRUE : FALSE;
2440 fr->fd = -1;
2441 #endif
2443 set_uid_n_gid(r, &fr->user, &fr->group);
2445 return fr;
2449 *----------------------------------------------------------------------
2451 * handler --
2453 * This routine gets called for a request that corresponds to
2454 * a FastCGI connection. It performs the request synchronously.
2456 * Results:
2457 * Final status of request: OK or NOT_FOUND or HTTP_INTERNAL_SERVER_ERROR.
2459 * Side effects:
2460 * Request performed.
2462 *----------------------------------------------------------------------
2465 /* Stolen from mod_cgi.c..
2466 * KLUDGE --- for back-combatibility, we don't have to check ExecCGI
2467 * in ScriptAliased directories, which means we need to know if this
2468 * request came through ScriptAlias or not... so the Alias module
2469 * leaves a note for us.
2471 static int apache_is_scriptaliased(request_rec *r)
2473 const char *t = ap_table_get(r->notes, "alias-forced-type");
2474 return t && (!strcasecmp(t, "cgi-script"));
2477 /* If a script wants to produce its own Redirect body, it now
2478 * has to explicitly *say* "Status: 302". If it wants to use
2479 * Apache redirects say "Status: 200". See process_headers().
2481 static int post_process_for_redirects(request_rec * const r,
2482 const fcgi_request * const fr)
2484 switch(fr->parseHeader) {
2485 case SCAN_CGI_INT_REDIRECT:
2487 /* @@@ There are still differences between the handling in
2488 * mod_cgi and mod_fastcgi. This needs to be revisited.
2490 /* We already read the message body (if any), so don't allow
2491 * the redirected request to think it has one. We can ignore
2492 * Transfer-Encoding, since we used REQUEST_CHUNKED_ERROR.
2494 r->method = "GET";
2495 r->method_number = M_GET;
2496 ap_table_unset(r->headers_in, "Content-length");
2498 ap_internal_redirect_handler(ap_table_get(r->headers_out, "Location"), r);
2499 return OK;
2501 case SCAN_CGI_SRV_REDIRECT:
2502 return HTTP_MOVED_TEMPORARILY;
2504 default:
2505 return OK;
2509 /******************************************************************************
2510 * Process fastcgi-script requests. Based on mod_cgi::cgi_handler().
2512 static int content_handler(request_rec *r)
2514 fcgi_request *fr = NULL;
2515 int ret;
2517 #ifdef APACHE2
2518 if (strcmp(r->handler, FASTCGI_HANDLER_NAME))
2519 return DECLINED;
2520 #endif
2522 /* Setup a new FastCGI request */
2523 if ((fr = create_fcgi_request(r, NULL)) == NULL)
2524 return HTTP_INTERNAL_SERVER_ERROR;
2526 /* If its a dynamic invocation, make sure scripts are OK here */
2527 if (fr->dynamic && !(ap_allow_options(r) & OPT_EXECCGI) && !apache_is_scriptaliased(r)) {
2528 ap_log_rerror(FCGI_LOG_ERR_NOERRNO, r,
2529 "FastCGI: \"ExecCGI Option\" is off in this directory: %s", r->uri);
2530 return HTTP_INTERNAL_SERVER_ERROR;
2533 /* Process the fastcgi-script request */
2534 if ((ret = do_work(r, fr)) != OK)
2535 return ret;
2537 /* Special case redirects */
2538 ret = post_process_for_redirects(r, fr);
2540 return ret;
2544 static int post_process_auth_passed_header(table *t, const char *key, const char * const val)
2546 if (strncasecmp(key, "Variable-", 9) == 0)
2547 key += 9;
2549 ap_table_setn(t, key, val);
2550 return 1;
2553 static int post_process_auth_passed_compat_header(table *t, const char *key, const char * const val)
2555 if (strncasecmp(key, "Variable-", 9) == 0)
2556 ap_table_setn(t, key + 9, val);
2558 return 1;
2561 static int post_process_auth_failed_header(table * const t, const char * const key, const char * const val)
2563 ap_table_setn(t, key, val);
2564 return 1;
2567 static void post_process_auth(fcgi_request * const fr, const int passed)
2569 request_rec * const r = fr->r;
2571 /* Restore the saved subprocess_env because we muddied ours up */
2572 r->subprocess_env = fr->saved_subprocess_env;
2574 if (passed) {
2575 if (fr->auth_compat) {
2576 ap_table_do((int (*)(void *, const char *, const char *))post_process_auth_passed_compat_header,
2577 (void *)r->subprocess_env, fr->authHeaders, NULL);
2579 else {
2580 ap_table_do((int (*)(void *, const char *, const char *))post_process_auth_passed_header,
2581 (void *)r->subprocess_env, fr->authHeaders, NULL);
2584 else {
2585 ap_table_do((int (*)(void *, const char *, const char *))post_process_auth_failed_header,
2586 (void *)r->err_headers_out, fr->authHeaders, NULL);
2589 /* @@@ Restore these.. its a hack until I rewrite the header handling */
2590 r->status = HTTP_OK;
2591 r->status_line = NULL;
2594 static int check_user_authentication(request_rec *r)
2596 int res, authenticated = 0;
2597 const char *password;
2598 fcgi_request *fr;
2599 const fcgi_dir_config * const dir_config =
2600 (const fcgi_dir_config *)ap_get_module_config(r->per_dir_config, &fastcgi_module);
2602 if (dir_config->authenticator == NULL)
2603 return DECLINED;
2605 /* Get the user password */
2606 if ((res = ap_get_basic_auth_pw(r, &password)) != OK)
2607 return res;
2609 if ((fr = create_fcgi_request(r, dir_config->authenticator)) == NULL)
2610 return HTTP_INTERNAL_SERVER_ERROR;
2612 /* Save the existing subprocess_env, because we're gonna muddy it up */
2613 fr->saved_subprocess_env = ap_copy_table(r->pool, r->subprocess_env);
2615 ap_table_setn(r->subprocess_env, "REMOTE_PASSWD", password);
2616 ap_table_setn(r->subprocess_env, "FCGI_APACHE_ROLE", "AUTHENTICATOR");
2618 /* The FastCGI Protocol doesn't differentiate authentication */
2619 fr->role = FCGI_AUTHORIZER;
2621 /* Do we need compatibility mode? */
2622 fr->auth_compat = (dir_config->authenticator_options & FCGI_COMPAT);
2624 if ((res = do_work(r, fr)) != OK)
2625 goto AuthenticationFailed;
2627 authenticated = (r->status == 200);
2628 post_process_auth(fr, authenticated);
2630 /* A redirect shouldn't be allowed during the authentication phase */
2631 if (ap_table_get(r->headers_out, "Location") != NULL) {
2632 ap_log_rerror(FCGI_LOG_ERR_NOERRNO, r,
2633 "FastCGI: FastCgiAuthenticator \"%s\" redirected (not allowed)",
2634 dir_config->authenticator);
2635 goto AuthenticationFailed;
2638 if (authenticated)
2639 return OK;
2641 AuthenticationFailed:
2642 if (!(dir_config->authenticator_options & FCGI_AUTHORITATIVE))
2643 return DECLINED;
2645 /* @@@ Probably should support custom_responses */
2646 ap_note_basic_auth_failure(r);
2647 ap_log_rerror(FCGI_LOG_ERR_NOERRNO, r,
2648 "FastCGI: authentication failed for user \"%s\": %s",
2649 #ifdef APACHE2
2650 r->user, r->uri);
2651 #else
2652 r->connection->user, r->uri);
2653 #endif
2655 return (res == OK) ? HTTP_UNAUTHORIZED : res;
2658 static int check_user_authorization(request_rec *r)
2660 int res, authorized = 0;
2661 fcgi_request *fr;
2662 const fcgi_dir_config * const dir_config =
2663 (const fcgi_dir_config *)ap_get_module_config(r->per_dir_config, &fastcgi_module);
2665 if (dir_config->authorizer == NULL)
2666 return DECLINED;
2668 /* @@@ We should probably honor the existing parameters to the require directive
2669 * as well as allow the definition of new ones (or use the basename of the
2670 * FastCGI server and pass the rest of the directive line), but for now keep
2671 * it simple. */
2673 if ((fr = create_fcgi_request(r, dir_config->authorizer)) == NULL)
2674 return HTTP_INTERNAL_SERVER_ERROR;
2676 /* Save the existing subprocess_env, because we're gonna muddy it up */
2677 fr->saved_subprocess_env = ap_copy_table(r->pool, r->subprocess_env);
2679 ap_table_setn(r->subprocess_env, "FCGI_APACHE_ROLE", "AUTHORIZER");
2681 fr->role = FCGI_AUTHORIZER;
2683 /* Do we need compatibility mode? */
2684 fr->auth_compat = (dir_config->authorizer_options & FCGI_COMPAT);
2686 if ((res = do_work(r, fr)) != OK)
2687 goto AuthorizationFailed;
2689 authorized = (r->status == 200);
2690 post_process_auth(fr, authorized);
2692 /* A redirect shouldn't be allowed during the authorization phase */
2693 if (ap_table_get(r->headers_out, "Location") != NULL) {
2694 ap_log_rerror(FCGI_LOG_ERR_NOERRNO, r,
2695 "FastCGI: FastCgiAuthorizer \"%s\" redirected (not allowed)",
2696 dir_config->authorizer);
2697 goto AuthorizationFailed;
2700 if (authorized)
2701 return OK;
2703 AuthorizationFailed:
2704 if (!(dir_config->authorizer_options & FCGI_AUTHORITATIVE))
2705 return DECLINED;
2707 /* @@@ Probably should support custom_responses */
2708 ap_note_basic_auth_failure(r);
2709 ap_log_rerror(FCGI_LOG_ERR_NOERRNO, r,
2710 "FastCGI: authorization failed for user \"%s\": %s",
2711 #ifdef APACHE2
2712 r->user, r->uri);
2713 #else
2714 r->connection->user, r->uri);
2715 #endif
2717 return (res == OK) ? HTTP_UNAUTHORIZED : res;
2720 static int check_access(request_rec *r)
2722 int res, access_allowed = 0;
2723 fcgi_request *fr;
2724 const fcgi_dir_config * const dir_config =
2725 (fcgi_dir_config *)ap_get_module_config(r->per_dir_config, &fastcgi_module);
2727 if (dir_config == NULL || dir_config->access_checker == NULL)
2728 return DECLINED;
2730 if ((fr = create_fcgi_request(r, dir_config->access_checker)) == NULL)
2731 return HTTP_INTERNAL_SERVER_ERROR;
2733 /* Save the existing subprocess_env, because we're gonna muddy it up */
2734 fr->saved_subprocess_env = ap_copy_table(r->pool, r->subprocess_env);
2736 ap_table_setn(r->subprocess_env, "FCGI_APACHE_ROLE", "ACCESS_CHECKER");
2738 /* The FastCGI Protocol doesn't differentiate access control */
2739 fr->role = FCGI_AUTHORIZER;
2741 /* Do we need compatibility mode? */
2742 fr->auth_compat = (dir_config->access_checker_options & FCGI_COMPAT);
2744 if ((res = do_work(r, fr)) != OK)
2745 goto AccessFailed;
2747 access_allowed = (r->status == 200);
2748 post_process_auth(fr, access_allowed);
2750 /* A redirect shouldn't be allowed during the access check phase */
2751 if (ap_table_get(r->headers_out, "Location") != NULL) {
2752 ap_log_rerror(FCGI_LOG_ERR_NOERRNO, r,
2753 "FastCGI: FastCgiAccessChecker \"%s\" redirected (not allowed)",
2754 dir_config->access_checker);
2755 goto AccessFailed;
2758 if (access_allowed)
2759 return OK;
2761 AccessFailed:
2762 if (!(dir_config->access_checker_options & FCGI_AUTHORITATIVE))
2763 return DECLINED;
2765 /* @@@ Probably should support custom_responses */
2766 ap_log_rerror(FCGI_LOG_ERR_NOERRNO, r, "FastCGI: access denied: %s", r->uri);
2767 return (res == OK) ? HTTP_FORBIDDEN : res;
2770 static int
2771 fixups(request_rec * r)
2773 if (fcgi_util_fs_get_by_id(r->filename,
2774 fcgi_util_get_server_uid(r->server),
2775 fcgi_util_get_server_gid(r->server)))
2777 r->handler = FASTCGI_HANDLER_NAME;
2778 return OK;
2781 return DECLINED;
2784 #ifndef APACHE2
2786 # define AP_INIT_RAW_ARGS(directive, func, mconfig, where, help) \
2787 { directive, func, mconfig, where, RAW_ARGS, help }
2788 # define AP_INIT_TAKE1(directive, func, mconfig, where, help) \
2789 { directive, func, mconfig, where, TAKE1, help }
2790 # define AP_INIT_TAKE12(directive, func, mconfig, where, help) \
2791 { directive, func, mconfig, where, TAKE12, help }
2792 # define AP_INIT_FLAG(directive, func, mconfig, where, help) \
2793 { directive, func, mconfig, where, FLAG, help }
2795 #endif
2797 static const command_rec fastcgi_cmds[] =
2799 AP_INIT_RAW_ARGS("AppClass", fcgi_config_new_static_server, NULL, RSRC_CONF, NULL),
2800 AP_INIT_RAW_ARGS("FastCgiServer", fcgi_config_new_static_server, NULL, RSRC_CONF, NULL),
2802 AP_INIT_RAW_ARGS("ExternalAppClass", fcgi_config_new_external_server, NULL, RSRC_CONF, NULL),
2803 AP_INIT_RAW_ARGS("FastCgiExternalServer", fcgi_config_new_external_server, NULL, RSRC_CONF, NULL),
2805 AP_INIT_TAKE1("FastCgiIpcDir", fcgi_config_set_socket_dir, NULL, RSRC_CONF, NULL),
2807 AP_INIT_TAKE1("FastCgiSuexec", fcgi_config_set_wrapper, NULL, RSRC_CONF, NULL),
2808 AP_INIT_TAKE1("FastCgiWrapper", fcgi_config_set_wrapper, NULL, RSRC_CONF, NULL),
2810 AP_INIT_RAW_ARGS("FCGIConfig", fcgi_config_set_config, NULL, RSRC_CONF, NULL),
2811 AP_INIT_RAW_ARGS("FastCgiConfig", fcgi_config_set_config, NULL, RSRC_CONF, NULL),
2813 AP_INIT_TAKE12("FastCgiAuthenticator", fcgi_config_new_auth_server,
2814 (void *)FCGI_AUTH_TYPE_AUTHENTICATOR, ACCESS_CONF,
2815 "a fastcgi-script path (absolute or relative to ServerRoot) followed by an optional -compat"),
2816 AP_INIT_FLAG("FastCgiAuthenticatorAuthoritative", fcgi_config_set_authoritative_slot,
2817 (void *)XtOffsetOf(fcgi_dir_config, authenticator_options), ACCESS_CONF,
2818 "Set to 'off' to allow authentication to be passed along to lower modules upon failure"),
2820 AP_INIT_TAKE12("FastCgiAuthorizer", fcgi_config_new_auth_server,
2821 (void *)FCGI_AUTH_TYPE_AUTHORIZER, ACCESS_CONF,
2822 "a fastcgi-script path (absolute or relative to ServerRoot) followed by an optional -compat"),
2823 AP_INIT_FLAG("FastCgiAuthorizerAuthoritative", fcgi_config_set_authoritative_slot,
2824 (void *)XtOffsetOf(fcgi_dir_config, authorizer_options), ACCESS_CONF,
2825 "Set to 'off' to allow authorization to be passed along to lower modules upon failure"),
2827 AP_INIT_TAKE12("FastCgiAccessChecker", fcgi_config_new_auth_server,
2828 (void *)FCGI_AUTH_TYPE_ACCESS_CHECKER, ACCESS_CONF,
2829 "a fastcgi-script path (absolute or relative to ServerRoot) followed by an optional -compat"),
2830 AP_INIT_FLAG("FastCgiAccessCheckerAuthoritative", fcgi_config_set_authoritative_slot,
2831 (void *)XtOffsetOf(fcgi_dir_config, access_checker_options), ACCESS_CONF,
2832 "Set to 'off' to allow access control to be passed along to lower modules upon failure"),
2833 { NULL }
2836 #ifdef APACHE2
2838 static void register_hooks(apr_pool_t * p)
2840 // ap_hook_pre_config(x_pre_config, NULL, NULL, APR_HOOK_MIDDLE);
2841 ap_hook_post_config(init_module, NULL, NULL, APR_HOOK_MIDDLE);
2842 ap_hook_child_init(fcgi_child_init, NULL, NULL, APR_HOOK_MIDDLE);
2843 ap_hook_handler(content_handler, NULL, NULL, APR_HOOK_MIDDLE);
2844 ap_hook_check_user_id(check_user_authentication, NULL, NULL, APR_HOOK_MIDDLE);
2845 ap_hook_access_checker(check_access, NULL, NULL, APR_HOOK_MIDDLE);
2846 ap_hook_auth_checker(check_user_authorization, NULL, NULL, APR_HOOK_MIDDLE);
2847 ap_hook_fixups(fixups, NULL, NULL, APR_HOOK_MIDDLE);
2850 module AP_MODULE_DECLARE_DATA fastcgi_module =
2852 STANDARD20_MODULE_STUFF,
2853 fcgi_config_create_dir_config, /* per-directory config creator */
2854 NULL, /* dir config merger */
2855 NULL, /* server config creator */
2856 NULL, /* server config merger */
2857 fastcgi_cmds, /* command table */
2858 register_hooks, /* set up other request processing hooks */
2861 #else /* !APACHE2 */
2863 handler_rec fastcgi_handlers[] = {
2864 { FCGI_MAGIC_TYPE, content_handler },
2865 { FASTCGI_HANDLER_NAME, content_handler },
2866 { NULL }
2869 module MODULE_VAR_EXPORT fastcgi_module = {
2870 STANDARD_MODULE_STUFF,
2871 init_module, /* initializer */
2872 fcgi_config_create_dir_config, /* per-dir config creator */
2873 NULL, /* per-dir config merger (default: override) */
2874 NULL, /* per-server config creator */
2875 NULL, /* per-server config merger (default: override) */
2876 fastcgi_cmds, /* command table */
2877 fastcgi_handlers, /* [9] content handlers */
2878 NULL, /* [2] URI-to-filename translation */
2879 check_user_authentication, /* [5] authenticate user_id */
2880 check_user_authorization, /* [6] authorize user_id */
2881 check_access, /* [4] check access (based on src & http headers) */
2882 NULL, /* [7] check/set MIME type */
2883 fixups, /* [8] fixups */
2884 NULL, /* [10] logger */
2885 NULL, /* [3] header-parser */
2886 fcgi_child_init, /* process initialization */
2887 #ifdef WIN32
2888 fcgi_child_exit, /* process exit/cleanup */
2889 #else
2890 NULL,
2891 #endif
2892 NULL /* [1] post read-request handling */
2895 #endif /* !APACHE2 */