[WIN32] Fix a delay in handling large POSTs to named pipe based
[mod_fastcgi.git] / mod_fastcgi.c
blob76092916f470f7ede29404bdb2132768e3897ca4
1 /*
2 * mod_fastcgi.c --
4 * Apache server module for FastCGI.
6 * $Id: mod_fastcgi.c,v 1.146 2002/12/05 02:41:26 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)
862 return -1;
864 if (countRead == 0) {
865 fr->expectingClientContent = 0;
867 else {
868 fcgi_buf_add_update(fr->clientInputBuffer, countRead);
869 ap_reset_timeout(fr->r);
872 return OK;
875 static int write_to_client(fcgi_request *fr)
877 char *begin;
878 int count;
879 int rv;
880 #ifdef APACHE2
881 apr_bucket * bkt;
882 apr_bucket_brigade * bde;
883 apr_bucket_alloc_t * const bkt_alloc = fr->r->connection->bucket_alloc;
884 #endif
886 fcgi_buf_get_block_info(fr->clientOutputBuffer, &begin, &count);
887 if (count == 0)
888 return OK;
890 /* If fewer than count bytes are written, an error occured.
891 * ap_bwrite() typically forces a flushed write to the client, this
892 * effectively results in a block (and short packets) - it should
893 * be fixed, but I didn't win much support for the idea on new-httpd.
894 * So, without patching Apache, the best way to deal with this is
895 * to size the fcgi_bufs to hold all of the script output (within
896 * reason) so the script can be released from having to wait around
897 * for the transmission to the client to complete. */
899 #ifdef APACHE2
901 bde = apr_brigade_create(fr->r->pool, bkt_alloc);
902 bkt = apr_bucket_transient_create(begin, count, bkt_alloc);
903 APR_BRIGADE_INSERT_TAIL(bde, bkt);
905 if (fr->fs ? fr->fs->flush : dynamicFlush)
907 bkt = apr_bucket_flush_create(bkt_alloc);
908 APR_BRIGADE_INSERT_TAIL(bde, bkt);
911 rv = ap_pass_brigade(fr->r->output_filters, bde);
913 #elif defined(RUSSIAN_APACHE)
915 rv = (ap_rwrite(begin, count, fr->r) != count);
917 #else
919 rv = (ap_bwrite(fr->r->connection->client, begin, count) != count);
921 #endif
923 if (rv)
925 ap_log_rerror(FCGI_LOG_INFO_NOERRNO, fr->r,
926 "FastCGI: client stopped connection before send body completed");
927 return -1;
930 #ifndef APACHE2
932 ap_reset_timeout(fr->r);
934 /* Don't bother with a wrapped buffer, limiting exposure to slow
935 * clients. The BUFF routines don't allow a writev from above,
936 * and don't always memcpy to minimize small write()s, this should
937 * be fixed, but I didn't win much support for the idea on
938 * new-httpd - I'll have to _prove_ its a problem first.. */
940 /* The default behaviour used to be to flush with every write, but this
941 * can tie up the FastCGI server longer than is necessary so its an option now */
943 if (fr->fs ? fr->fs->flush : dynamicFlush)
945 #ifdef RUSSIAN_APACHE
946 rv = ap_rflush(fr->r);
947 #else
948 rv = ap_bflush(fr->r->connection->client);
949 #endif
951 if (rv)
953 ap_log_rerror(FCGI_LOG_INFO_NOERRNO, fr->r,
954 "FastCGI: client stopped connection before send body completed");
955 return -1;
958 ap_reset_timeout(fr->r);
961 #endif /* !APACHE2 */
963 fcgi_buf_toss(fr->clientOutputBuffer, count);
964 return OK;
967 /*******************************************************************************
968 * Determine the user and group the wrapper should be called with.
969 * Based on code in Apache's create_argv_cmd() (util_script.c).
971 static void set_uid_n_gid(request_rec *r, const char **user, const char **group)
973 if (fcgi_wrapper == NULL) {
974 *user = "-";
975 *group = "-";
976 return;
979 if (strncmp("/~", r->uri, 2) == 0) {
980 /* its a user dir uri, just send the ~user, and leave it to the PM */
981 char *end = strchr(r->uri + 2, '/');
983 if (end)
984 *user = memcpy(ap_pcalloc(r->pool, end - r->uri), r->uri + 1, end - r->uri - 1);
985 else
986 *user = ap_pstrdup(r->pool, r->uri + 1);
987 *group = "-";
989 else {
990 *user = ap_psprintf(r->pool, "%ld", (long) fcgi_util_get_server_uid(r->server));
991 *group = ap_psprintf(r->pool, "%ld", (long) fcgi_util_get_server_gid(r->server));
995 static void send_request_complete(fcgi_request *fr)
997 if (fr->completeTime.tv_sec)
999 struct timeval qtime, rtime;
1001 timersub(&fr->queueTime, &fr->startTime, &qtime);
1002 timersub(&fr->completeTime, &fr->queueTime, &rtime);
1004 send_to_pm(FCGI_REQUEST_COMPLETE_JOB, fr->fs_path,
1005 fr->user, fr->group,
1006 qtime.tv_sec * 1000000 + qtime.tv_usec,
1007 rtime.tv_sec * 1000000 + rtime.tv_usec);
1012 /*******************************************************************************
1013 * Connect to the FastCGI server.
1015 static int open_connection_to_fs(fcgi_request *fr)
1017 struct timeval tval;
1018 fd_set write_fds, read_fds;
1019 int status;
1020 request_rec * const r = fr->r;
1021 pool * const rp = r->pool;
1022 const char *socket_path = NULL;
1023 struct sockaddr *socket_addr = NULL;
1024 int socket_addr_len = 0;
1025 #ifndef WIN32
1026 const char *err = NULL;
1027 #endif
1029 /* Create the connection point */
1030 if (fr->dynamic)
1032 socket_path = fcgi_util_socket_hash_filename(rp, fr->fs_path, fr->user, fr->group);
1033 socket_path = fcgi_util_socket_make_path_absolute(rp, socket_path, 1);
1035 #ifndef WIN32
1036 err = fcgi_util_socket_make_domain_addr(rp, (struct sockaddr_un **)&socket_addr,
1037 &socket_addr_len, socket_path);
1038 if (err) {
1039 ap_log_rerror(FCGI_LOG_ERR, r,
1040 "FastCGI: failed to connect to (dynamic) server \"%s\": "
1041 "%s", fr->fs_path, err);
1042 return FCGI_FAILED;
1044 #endif
1046 else
1048 #ifdef WIN32
1049 if (fr->fs->dest_addr != NULL) {
1050 socket_addr = fr->fs->dest_addr;
1052 else if (fr->fs->socket_addr) {
1053 socket_addr = fr->fs->socket_addr;
1055 else {
1056 socket_path = fr->fs->socket_path;
1058 #else
1059 socket_addr = fr->fs->socket_addr;
1060 #endif
1061 socket_addr_len = fr->fs->socket_addr_len;
1064 if (fr->dynamic)
1066 #ifdef WIN32
1067 if (fr->fs && fr->fs->restartTime)
1068 #else
1069 struct stat sock_stat;
1071 if (stat(socket_path, &sock_stat) == 0)
1072 #endif
1074 // It exists
1075 if (dynamicAutoUpdate)
1077 struct stat app_stat;
1079 /* TODO: follow sym links */
1081 if (stat(fr->fs_path, &app_stat) == 0)
1083 #ifdef WIN32
1084 if (fr->fs->startTime < app_stat.st_mtime)
1085 #else
1086 if (sock_stat.st_mtime < app_stat.st_mtime)
1087 #endif
1089 #ifndef WIN32
1090 struct timeval tv = {1, 0};
1091 #endif
1093 * There's a newer one, request a restart.
1095 send_to_pm(FCGI_SERVER_RESTART_JOB, fr->fs_path, fr->user, fr->group, 0, 0);
1097 #ifdef WIN32
1098 Sleep(1000);
1099 #else
1100 /* Avoid sleep/alarm interactions */
1101 ap_select(0, NULL, NULL, NULL, &tv);
1102 #endif
1107 else
1109 int i;
1111 send_to_pm(FCGI_SERVER_START_JOB, fr->fs_path, fr->user, fr->group, 0, 0);
1113 /* wait until it looks like its running - this shouldn't take
1114 * very long at all - the exception is when the sockets are
1115 * removed out from under a running application - the loop
1116 * limit addresses this (preventing spinning) */
1118 for (i = 10; i > 0; i--)
1120 #ifdef WIN32
1121 Sleep(500);
1123 fr->fs = fcgi_util_fs_get_by_id(fr->fs_path, 0, 0);
1125 if (fr->fs && fr->fs->restartTime)
1126 #else
1127 struct timeval tv = {0, 500000};
1129 /* Avoid sleep/alarm interactions */
1130 ap_select(0, NULL, NULL, NULL, &tv);
1132 if (stat(socket_path, &sock_stat) == 0)
1133 #endif
1135 break;
1139 if (i <= 0)
1141 ap_log_rerror(FCGI_LOG_ALERT, r,
1142 "FastCGI: failed to connect to (dynamic) server \"%s\": "
1143 "something is seriously wrong, any chance the "
1144 "socket/named_pipe directory was removed?, see the "
1145 "FastCgiIpcDir directive", fr->fs_path);
1146 return FCGI_FAILED;
1151 #ifdef WIN32
1152 if (socket_path)
1154 BOOL ready;
1155 DWORD connect_time;
1156 int rv;
1157 HANDLE wait_npipe_mutex;
1158 DWORD interval;
1159 DWORD max_connect_time = FCGI_NAMED_PIPE_CONNECT_TIMEOUT;
1161 fr->using_npipe_io = TRUE;
1163 if (fr->dynamic)
1165 interval = dynamicPleaseStartDelay * 1000;
1167 if (dynamicAppConnectTimeout) {
1168 max_connect_time = dynamicAppConnectTimeout;
1171 else
1173 interval = FCGI_NAMED_PIPE_CONNECT_TIMEOUT * 1000;
1175 if (fr->fs->appConnectTimeout) {
1176 max_connect_time = fr->fs->appConnectTimeout;
1180 fcgi_util_ticks(&fr->startTime);
1183 // xxx this handle should live somewhere (see CloseHandle()s below too)
1184 char * wait_npipe_mutex_name, * cp;
1185 wait_npipe_mutex_name = cp = ap_pstrdup(rp, socket_path);
1186 while ((cp = strchr(cp, '\\'))) *cp = '/';
1188 wait_npipe_mutex = CreateMutex(NULL, FALSE, wait_npipe_mutex_name);
1191 if (wait_npipe_mutex == NULL)
1193 ap_log_rerror(FCGI_LOG_ERR, r,
1194 "FastCGI: failed to connect to server \"%s\": "
1195 "can't create the WaitNamedPipe mutex", fr->fs_path);
1196 return FCGI_FAILED;
1199 SetLastError(ERROR_SUCCESS);
1201 rv = WaitForSingleObject(wait_npipe_mutex, max_connect_time * 1000);
1203 if (rv == WAIT_TIMEOUT || rv == WAIT_FAILED)
1205 if (fr->dynamic)
1207 send_to_pm(FCGI_REQUEST_TIMEOUT_JOB, fr->fs_path, fr->user, fr->group, 0, 0);
1209 ap_log_rerror(FCGI_LOG_ERR_NOERRNO, r,
1210 "FastCGI: failed to connect to server \"%s\": "
1211 "wait for a npipe instance failed", fr->fs_path);
1212 FCGIDBG3("interval=%d, max_connect_time=%d", interval, max_connect_time);
1213 CloseHandle(wait_npipe_mutex);
1214 return FCGI_FAILED;
1217 fcgi_util_ticks(&fr->queueTime);
1219 connect_time = fr->queueTime.tv_sec - fr->startTime.tv_sec;
1221 if (fr->dynamic)
1223 if (connect_time >= interval)
1225 send_to_pm(FCGI_REQUEST_TIMEOUT_JOB, fr->fs_path, fr->user, fr->group, 0, 0);
1226 FCGIDBG4("connect_time=%d, interval=%d, max_connect_time=%d", connect_time, interval, max_connect_time);
1228 if (max_connect_time - connect_time < interval)
1230 interval = max_connect_time - connect_time;
1233 else
1235 interval -= connect_time * 1000;
1238 for (;;)
1240 ready = WaitNamedPipe(socket_path, interval);
1242 if (ready)
1244 fr->fd = (SOCKET) CreateFile(socket_path,
1245 GENERIC_READ | GENERIC_WRITE,
1246 FILE_SHARE_READ | FILE_SHARE_WRITE,
1247 NULL, // no security attributes
1248 OPEN_EXISTING, // opens existing pipe
1249 FILE_FLAG_OVERLAPPED,
1250 NULL); // no template file
1252 if (fr->fd != (SOCKET) INVALID_HANDLE_VALUE)
1254 ReleaseMutex(wait_npipe_mutex);
1255 CloseHandle(wait_npipe_mutex);
1256 fcgi_util_ticks(&fr->queueTime);
1257 FCGIDBG2("got npipe connect: %s", fr->fs_path);
1258 return FCGI_OK;
1261 if (GetLastError() != ERROR_PIPE_BUSY
1262 && GetLastError() != ERROR_FILE_NOT_FOUND)
1264 ap_log_rerror(FCGI_LOG_ERR, r,
1265 "FastCGI: failed to connect to server \"%s\": "
1266 "CreateFile() failed", fr->fs_path);
1267 break;
1270 FCGIDBG2("missed npipe connect: %s", fr->fs_path);
1273 if (fr->dynamic)
1275 send_to_pm(FCGI_REQUEST_TIMEOUT_JOB, fr->fs_path, fr->user, fr->group, 0, 0);
1278 fcgi_util_ticks(&fr->queueTime);
1280 connect_time = fr->queueTime.tv_sec - fr->startTime.tv_sec;
1282 FCGIDBG5("interval=%d, max_connect_time=%d, connect_time=%d, ready=%d", interval, max_connect_time, connect_time, ready);
1284 if (connect_time >= max_connect_time)
1286 ap_log_rerror(FCGI_LOG_ERR, r,
1287 "FastCGI: failed to connect to server \"%s\": "
1288 "CreateFile()/WaitNamedPipe() timed out", fr->fs_path);
1289 break;
1293 ReleaseMutex(wait_npipe_mutex);
1294 CloseHandle(wait_npipe_mutex);
1295 fr->fd = INVALID_SOCKET;
1296 return FCGI_FAILED;
1299 #endif
1301 /* Create the socket */
1302 fr->fd = socket(socket_addr->sa_family, SOCK_STREAM, 0);
1304 #ifdef WIN32
1305 if (fr->fd == INVALID_SOCKET) {
1306 errno = WSAGetLastError(); // Not sure this is going to work as expected
1307 #else
1308 if (fr->fd < 0) {
1309 #endif
1310 ap_log_rerror(FCGI_LOG_ERR_ERRNO, r,
1311 "FastCGI: failed to connect to server \"%s\": "
1312 "socket() failed", fr->fs_path);
1313 return FCGI_FAILED;
1316 #ifndef WIN32
1317 if (fr->fd >= FD_SETSIZE) {
1318 ap_log_rerror(FCGI_LOG_ERR, r,
1319 "FastCGI: failed to connect to server \"%s\": "
1320 "socket file descriptor (%u) is larger than "
1321 "FD_SETSIZE (%u), you probably need to rebuild Apache with a "
1322 "larger FD_SETSIZE", fr->fs_path, fr->fd, FD_SETSIZE);
1323 return FCGI_FAILED;
1325 #endif
1327 /* If appConnectTimeout is non-zero, setup do a non-blocking connect */
1328 if ((fr->dynamic && dynamicAppConnectTimeout) || (!fr->dynamic && fr->fs->appConnectTimeout)) {
1329 set_nonblocking(fr, TRUE);
1332 if (fr->dynamic) {
1333 fcgi_util_ticks(&fr->startTime);
1336 /* Connect */
1337 if (connect(fr->fd, (struct sockaddr *)socket_addr, socket_addr_len) == 0)
1338 goto ConnectionComplete;
1340 #ifdef WIN32
1342 errno = WSAGetLastError();
1343 if (errno != WSAEWOULDBLOCK) {
1344 ap_log_rerror(FCGI_LOG_ERR_ERRNO, r,
1345 "FastCGI: failed to connect to server \"%s\": "
1346 "connect() failed", fr->fs_path);
1347 return FCGI_FAILED;
1350 #else
1352 /* ECONNREFUSED means the listen queue is full (or there isn't one).
1353 * With dynamic I can at least make sure the PM knows this is occuring */
1354 if (fr->dynamic && errno == ECONNREFUSED) {
1355 /* @@@ This might be better as some other "kind" of message */
1356 send_to_pm(FCGI_REQUEST_TIMEOUT_JOB, fr->fs_path, fr->user, fr->group, 0, 0);
1358 errno = ECONNREFUSED;
1361 if (errno != EINPROGRESS) {
1362 ap_log_rerror(FCGI_LOG_ERR, r,
1363 "FastCGI: failed to connect to server \"%s\": "
1364 "connect() failed", fr->fs_path);
1365 return FCGI_FAILED;
1368 #endif
1370 /* The connect() is non-blocking */
1372 errno = 0;
1374 if (fr->dynamic) {
1375 do {
1376 FD_ZERO(&write_fds);
1377 FD_SET(fr->fd, &write_fds);
1378 read_fds = write_fds;
1379 tval.tv_sec = dynamicPleaseStartDelay;
1380 tval.tv_usec = 0;
1382 status = ap_select((fr->fd+1), &read_fds, &write_fds, NULL, &tval);
1383 if (status < 0)
1384 break;
1386 fcgi_util_ticks(&fr->queueTime);
1388 if (status > 0)
1389 break;
1391 /* select() timed out */
1392 send_to_pm(FCGI_REQUEST_TIMEOUT_JOB, fr->fs_path, fr->user, fr->group, 0, 0);
1393 } while ((fr->queueTime.tv_sec - fr->startTime.tv_sec) < (int)dynamicAppConnectTimeout);
1395 /* XXX These can be moved down when dynamic vars live is a struct */
1396 if (status == 0) {
1397 ap_log_rerror(FCGI_LOG_ERR_NOERRNO, r,
1398 "FastCGI: failed to connect to server \"%s\": "
1399 "connect() timed out (appConnTimeout=%dsec)",
1400 fr->fs_path, dynamicAppConnectTimeout);
1401 return FCGI_FAILED;
1403 } /* dynamic */
1404 else {
1405 tval.tv_sec = fr->fs->appConnectTimeout;
1406 tval.tv_usec = 0;
1407 FD_ZERO(&write_fds);
1408 FD_SET(fr->fd, &write_fds);
1409 read_fds = write_fds;
1411 status = ap_select((fr->fd+1), &read_fds, &write_fds, NULL, &tval);
1413 if (status == 0) {
1414 ap_log_rerror(FCGI_LOG_ERR_NOERRNO, r,
1415 "FastCGI: failed to connect to server \"%s\": "
1416 "connect() timed out (appConnTimeout=%dsec)",
1417 fr->fs_path, dynamicAppConnectTimeout);
1418 return FCGI_FAILED;
1420 } /* !dynamic */
1422 if (status < 0) {
1423 #ifdef WIN32
1424 errno = WSAGetLastError();
1425 #endif
1426 ap_log_rerror(FCGI_LOG_ERR_ERRNO, r,
1427 "FastCGI: failed to connect to server \"%s\": "
1428 "select() failed", fr->fs_path);
1429 return FCGI_FAILED;
1432 if (FD_ISSET(fr->fd, &write_fds) || FD_ISSET(fr->fd, &read_fds)) {
1433 int error = 0;
1434 NET_SIZE_T len = sizeof(error);
1436 if (getsockopt(fr->fd, SOL_SOCKET, SO_ERROR, (char *)&error, &len) < 0) {
1437 /* Solaris pending error */
1438 #ifdef WIN32
1439 errno = WSAGetLastError();
1440 #endif
1441 ap_log_rerror(FCGI_LOG_ERR_ERRNO, r,
1442 "FastCGI: failed to connect to server \"%s\": "
1443 "select() failed (Solaris pending error)", fr->fs_path);
1444 return FCGI_FAILED;
1447 if (error != 0) {
1448 /* Berkeley-derived pending error */
1449 errno = error;
1450 ap_log_rerror(FCGI_LOG_ERR_ERRNO, r,
1451 "FastCGI: failed to connect to server \"%s\": "
1452 "select() failed (pending error)", fr->fs_path);
1453 return FCGI_FAILED;
1456 else {
1457 #ifdef WIN32
1458 errno = WSAGetLastError();
1459 #endif
1460 ap_log_rerror(FCGI_LOG_ERR_ERRNO, r,
1461 "FastCGI: failed to connect to server \"%s\": "
1462 "select() error - THIS CAN'T HAPPEN!", fr->fs_path);
1463 return FCGI_FAILED;
1466 ConnectionComplete:
1467 /* Return to blocking mode if it was set up */
1468 if ((fr->dynamic && dynamicAppConnectTimeout) || (!fr->dynamic && fr->fs->appConnectTimeout)) {
1469 set_nonblocking(fr, FALSE);
1472 #ifdef TCP_NODELAY
1473 if (socket_addr->sa_family == AF_INET) {
1474 /* We shouldn't be sending small packets and there's no application
1475 * level ack of the data we send, so disable Nagle */
1476 int set = 1;
1477 setsockopt(fr->fd, IPPROTO_TCP, TCP_NODELAY, (char *)&set, sizeof(set));
1479 #endif
1481 return FCGI_OK;
1484 static void sink_client_data(fcgi_request *fr)
1486 char *base;
1487 int size;
1489 fcgi_buf_reset(fr->clientInputBuffer);
1490 fcgi_buf_get_free_block_info(fr->clientInputBuffer, &base, &size);
1491 while (ap_get_client_block(fr->r, base, size) > 0);
1494 static apcb_t cleanup(void *data)
1496 fcgi_request * const fr = (fcgi_request *) data;
1498 if (fr == NULL) return APCB_OK;
1500 /* its more than likely already run, but... */
1501 close_connection_to_fs(fr);
1503 send_request_complete(fr);
1505 if (fr->fs_stderr_len) {
1506 ap_log_rerror(FCGI_LOG_ERR_NOERRNO, fr->r,
1507 "FastCGI: server \"%s\" stderr: %s", fr->fs_path, fr->fs_stderr);
1510 return APCB_OK;
1513 #ifdef WIN32
1514 static int npipe_io(fcgi_request * const fr)
1516 request_rec * const r = fr->r;
1517 enum
1519 STATE_ENV_SEND,
1520 STATE_CLIENT_RECV,
1521 STATE_SERVER_SEND,
1522 STATE_SERVER_RECV,
1523 STATE_CLIENT_SEND,
1524 STATE_CLIENT_ERROR,
1525 STATE_ERROR
1527 state = STATE_ENV_SEND;
1528 env_status env_status;
1529 int client_recv;
1530 int dynamic_first_recv = fr->dynamic;
1531 int idle_timeout = fr->dynamic ? dynamic_idle_timeout : fr->fs->idle_timeout;
1532 int send_pending = 0;
1533 int recv_pending = 0;
1534 int client_send = 0;
1535 int rv;
1536 OVERLAPPED rov = { 0 };
1537 OVERLAPPED sov = { 0 };
1538 HANDLE events[2];
1539 struct timeval timeout;
1540 struct timeval dynamic_last_io_time = {0, 0};
1541 int did_io = 1;
1542 pool * const rp = r->pool;
1544 DWORD recv_count = 0;
1546 if (fr->role == FCGI_RESPONDER)
1548 client_recv = (fr->expectingClientContent != 0);
1551 idle_timeout = fr->dynamic ? dynamic_idle_timeout : fr->fs->idle_timeout;
1553 env_status.envp = NULL;
1555 events[0] = CreateEvent(NULL, TRUE, FALSE, NULL);
1556 events[1] = CreateEvent(NULL, TRUE, FALSE, NULL);
1557 sov.hEvent = events[0];
1558 rov.hEvent = events[1];
1560 if (fr->dynamic)
1562 dynamic_last_io_time = fr->startTime;
1564 if (dynamicAppConnectTimeout)
1566 struct timeval qwait;
1567 timersub(&fr->queueTime, &fr->startTime, &qwait);
1568 dynamic_first_recv = qwait.tv_sec / dynamicPleaseStartDelay + 1;
1572 ap_hard_timeout("FastCGI request processing", r);
1574 while (state != STATE_CLIENT_SEND)
1576 DWORD msec_timeout;
1578 switch (state)
1580 case STATE_ENV_SEND:
1582 if (fcgi_protocol_queue_env(r, fr, &env_status) == 0)
1584 goto SERVER_SEND;
1587 state = STATE_CLIENT_RECV;
1589 /* fall through */
1591 case STATE_CLIENT_RECV:
1593 if (read_from_client_n_queue(fr) != OK)
1595 state = STATE_CLIENT_ERROR;
1596 break;
1599 if (fr->eofSent)
1601 state = STATE_SERVER_SEND;
1604 /* fall through */
1606 SERVER_SEND:
1608 case STATE_SERVER_SEND:
1610 if (! send_pending && BufferLength(fr->serverOutputBuffer))
1612 Buffer * b = fr->serverOutputBuffer;
1613 DWORD sent, len;
1615 len = min(b->length, b->data + b->size - b->begin);
1617 if (WriteFile((HANDLE) fr->fd, b->begin, len, &sent, &sov))
1619 /* sov.hEvent is set */
1620 fcgi_buf_removed(b, sent);
1622 else if (GetLastError() == ERROR_IO_PENDING)
1624 send_pending = 1;
1626 else
1628 ap_log_rerror(FCGI_LOG_ERR, r, "FastCGI: comm with server "
1629 "\"%s\" aborted: WriteFile() failed", fr->fs_path);
1630 state = STATE_ERROR;
1631 break;
1635 /* fall through */
1637 case STATE_SERVER_RECV:
1640 * Only get more data when the serverInputBuffer is empty.
1641 * Otherwise we may already have the END_REQUEST buffered
1642 * (but not processed) and a read on a closed named pipe
1643 * results in an error that is normally abnormal.
1645 if (! recv_pending && BufferLength(fr->serverInputBuffer) == 0)
1647 Buffer * b = fr->serverInputBuffer;
1648 DWORD rcvd, len;
1650 len = min(b->size - b->length, b->data + b->size - b->end);
1652 if (ReadFile((HANDLE) fr->fd, b->end, len, &rcvd, &rov))
1654 fcgi_buf_added(b, rcvd);
1655 recv_count += rcvd;
1656 ResetEvent(rov.hEvent);
1657 if (dynamic_first_recv)
1659 dynamic_first_recv = 0;
1662 else if (GetLastError() == ERROR_IO_PENDING)
1664 recv_pending = 1;
1666 else if (GetLastError() == ERROR_HANDLE_EOF)
1668 fr->keepReadingFromFcgiApp = FALSE;
1669 state = STATE_CLIENT_SEND;
1670 ResetEvent(rov.hEvent);
1671 break;
1673 else if (GetLastError() == ERROR_NO_DATA)
1675 break;
1677 else
1679 ap_log_rerror(FCGI_LOG_ERR, r, "FastCGI: comm with server "
1680 "\"%s\" aborted: ReadFile() failed", fr->fs_path);
1681 state = STATE_ERROR;
1682 break;
1686 /* fall through */
1688 case STATE_CLIENT_SEND:
1690 if (client_send || ! BufferFree(fr->clientOutputBuffer))
1692 if (write_to_client(fr))
1694 state = STATE_CLIENT_ERROR;
1695 break;
1698 client_send = 0;
1701 break;
1703 default:
1705 ap_assert(0);
1708 if (state == STATE_CLIENT_ERROR || state == STATE_ERROR)
1710 break;
1713 /* setup the io timeout */
1715 if (BufferLength(fr->clientOutputBuffer))
1717 /* don't let client data sit too long, it might be a push */
1718 timeout.tv_sec = 0;
1719 timeout.tv_usec = 100000;
1721 else if (dynamic_first_recv)
1723 int delay;
1724 struct timeval qwait;
1726 fcgi_util_ticks(&fr->queueTime);
1728 if (did_io)
1730 /* a send() succeeded last pass */
1731 dynamic_last_io_time = fr->queueTime;
1733 else
1735 /* timed out last pass */
1736 struct timeval idle_time;
1738 timersub(&fr->queueTime, &dynamic_last_io_time, &idle_time);
1740 if (idle_time.tv_sec > idle_timeout)
1742 send_to_pm(FCGI_REQUEST_TIMEOUT_JOB, fr->fs_path, fr->user, fr->group, 0, 0);
1743 ap_log_rerror(FCGI_LOG_ERR_NOERRNO, r, "FastCGI: comm "
1744 "with (dynamic) server \"%s\" aborted: (first read) "
1745 "idle timeout (%d sec)", fr->fs_path, idle_timeout);
1746 state = STATE_ERROR;
1747 break;
1751 timersub(&fr->queueTime, &fr->startTime, &qwait);
1753 delay = dynamic_first_recv * dynamicPleaseStartDelay;
1755 if (qwait.tv_sec < delay)
1757 timeout.tv_sec = delay;
1758 timeout.tv_usec = 100000; /* fudge for select() slop */
1759 timersub(&timeout, &qwait, &timeout);
1761 else
1763 /* Killed time somewhere.. client read? */
1764 send_to_pm(FCGI_REQUEST_TIMEOUT_JOB, fr->fs_path, fr->user, fr->group, 0, 0);
1765 dynamic_first_recv = qwait.tv_sec / dynamicPleaseStartDelay + 1;
1766 timeout.tv_sec = dynamic_first_recv * dynamicPleaseStartDelay;
1767 timeout.tv_usec = 100000; /* fudge for select() slop */
1768 timersub(&timeout, &qwait, &timeout);
1771 else
1773 timeout.tv_sec = idle_timeout;
1774 timeout.tv_usec = 0;
1777 /* require a pended recv otherwise the app can deadlock */
1778 if (recv_pending)
1780 msec_timeout = timeout.tv_sec * 1000 + timeout.tv_usec / 1000;
1782 rv = WaitForMultipleObjects(2, events, FALSE, msec_timeout);
1784 if (rv == WAIT_TIMEOUT)
1786 did_io = 0;
1788 if (BufferLength(fr->clientOutputBuffer))
1790 client_send = 1;
1792 else if (dynamic_first_recv)
1794 struct timeval qwait;
1796 fcgi_util_ticks(&fr->queueTime);
1797 timersub(&fr->queueTime, &fr->startTime, &qwait);
1799 send_to_pm(FCGI_REQUEST_TIMEOUT_JOB, fr->fs_path, fr->user, fr->group, 0, 0);
1801 dynamic_first_recv = qwait.tv_sec / dynamicPleaseStartDelay + 1;
1803 else
1805 ap_log_rerror(FCGI_LOG_ERR_NOERRNO, r, "FastCGI: comm with "
1806 "server \"%s\" aborted: idle timeout (%d sec)",
1807 fr->fs_path, idle_timeout);
1808 state = STATE_ERROR;
1809 break;
1812 else
1814 int i = rv - WAIT_OBJECT_0;
1816 did_io = 1;
1818 if (i == 0)
1820 if (send_pending)
1822 DWORD sent;
1824 if (GetOverlappedResult((HANDLE) fr->fd, &sov, &sent, FALSE))
1826 send_pending = 0;
1827 fcgi_buf_removed(fr->serverOutputBuffer, sent);
1829 else
1831 ap_log_rerror(FCGI_LOG_ERR, r, "FastCGI: comm with server "
1832 "\"%s\" aborted: GetOverlappedResult() failed", fr->fs_path);
1833 state = STATE_ERROR;
1834 break;
1838 ResetEvent(sov.hEvent);
1840 else
1842 DWORD rcvd;
1844 ap_assert(i == 1);
1846 recv_pending = 0;
1847 ResetEvent(rov.hEvent);
1849 if (GetOverlappedResult((HANDLE) fr->fd, &rov, &rcvd, FALSE))
1851 fcgi_buf_added(fr->serverInputBuffer, rcvd);
1852 if (dynamic_first_recv)
1854 dynamic_first_recv = 0;
1857 else
1859 ap_log_rerror(FCGI_LOG_ERR, r, "FastCGI: comm with server "
1860 "\"%s\" aborted: GetOverlappedResult() failed", fr->fs_path);
1861 state = STATE_ERROR;
1862 break;
1868 if (fcgi_protocol_dequeue(rp, fr))
1870 state = STATE_ERROR;
1871 break;
1874 if (fr->parseHeader == SCAN_CGI_READING_HEADERS)
1876 const char * err = process_headers(r, fr);
1877 if (err)
1879 ap_log_rerror(FCGI_LOG_ERR_NOERRNO, r,
1880 "FastCGI: comm with server \"%s\" aborted: "
1881 "error parsing headers: %s", fr->fs_path, err);
1882 state = STATE_ERROR;
1883 break;
1887 if (fr->exitStatusSet)
1889 fr->keepReadingFromFcgiApp = FALSE;
1890 state = STATE_CLIENT_SEND;
1891 break;
1895 if (! fr->exitStatusSet || ! fr->eofSent)
1897 CancelIo((HANDLE) fr->fd);
1900 CloseHandle(rov.hEvent);
1901 CloseHandle(sov.hEvent);
1903 return (state == STATE_ERROR);
1905 #endif /* WIN32 */
1907 static int socket_io(fcgi_request * const fr)
1909 enum
1911 STATE_SOCKET_NONE,
1912 STATE_ENV_SEND,
1913 STATE_CLIENT_RECV,
1914 STATE_SERVER_SEND,
1915 STATE_SERVER_RECV,
1916 STATE_CLIENT_SEND,
1917 STATE_ERROR,
1918 STATE_CLIENT_ERROR
1920 state = STATE_ENV_SEND;
1922 request_rec * const r = fr->r;
1924 struct timeval timeout;
1925 struct timeval dynamic_last_io_time = {0, 0};
1926 fd_set read_set;
1927 fd_set write_set;
1928 int nfds = fr->fd + 1;
1929 int select_status = 1;
1930 int idle_timeout;
1931 int rv;
1932 int dynamic_first_recv = fr->dynamic ? 1 : 0;
1933 int client_send = FALSE;
1934 int client_recv = FALSE;
1935 env_status env;
1936 pool *rp = r->pool;
1938 if (fr->role == FCGI_RESPONDER)
1940 client_recv = (fr->expectingClientContent != 0);
1943 idle_timeout = fr->dynamic ? dynamic_idle_timeout : fr->fs->idle_timeout;
1945 env.envp = NULL;
1947 if (fr->dynamic)
1949 dynamic_last_io_time = fr->startTime;
1951 if (dynamicAppConnectTimeout)
1953 struct timeval qwait;
1954 timersub(&fr->queueTime, &fr->startTime, &qwait);
1955 dynamic_first_recv = qwait.tv_sec / dynamicPleaseStartDelay + 1;
1959 ap_hard_timeout("FastCGI request processing", r);
1961 set_nonblocking(fr, TRUE);
1963 for (;;)
1965 FD_ZERO(&read_set);
1966 FD_ZERO(&write_set);
1968 switch (state)
1970 case STATE_ENV_SEND:
1972 if (fcgi_protocol_queue_env(r, fr, &env) == 0)
1974 goto SERVER_SEND;
1977 state = STATE_CLIENT_RECV;
1979 /* fall through */
1981 case STATE_CLIENT_RECV:
1983 if (read_from_client_n_queue(fr))
1985 state = STATE_CLIENT_ERROR;
1986 break;
1989 if (fr->eofSent)
1991 state = STATE_SERVER_SEND;
1994 /* fall through */
1996 SERVER_SEND:
1998 case STATE_SERVER_SEND:
2000 if (BufferLength(fr->serverOutputBuffer))
2002 FD_SET(fr->fd, &write_set);
2004 else
2006 ap_assert(fr->eofSent);
2007 state = STATE_SERVER_RECV;
2010 /* fall through */
2012 case STATE_SERVER_RECV:
2014 FD_SET(fr->fd, &read_set);
2016 /* fall through */
2018 case STATE_CLIENT_SEND:
2020 if (client_send || ! BufferFree(fr->clientOutputBuffer))
2022 if (write_to_client(fr))
2024 state = STATE_CLIENT_ERROR;
2025 break;
2028 client_send = 0;
2031 break;
2033 case STATE_ERROR:
2034 case STATE_CLIENT_ERROR:
2036 break;
2038 default:
2040 ap_assert(0);
2043 if (state == STATE_CLIENT_ERROR || state == STATE_ERROR)
2045 break;
2048 /* setup the io timeout */
2050 if (BufferLength(fr->clientOutputBuffer))
2052 /* don't let client data sit too long, it might be a push */
2053 timeout.tv_sec = 0;
2054 timeout.tv_usec = 100000;
2056 else if (dynamic_first_recv)
2058 int delay;
2059 struct timeval qwait;
2061 fcgi_util_ticks(&fr->queueTime);
2063 if (select_status)
2065 /* a send() succeeded last pass */
2066 dynamic_last_io_time = fr->queueTime;
2068 else
2070 /* timed out last pass */
2071 struct timeval idle_time;
2073 timersub(&fr->queueTime, &dynamic_last_io_time, &idle_time);
2075 if (idle_time.tv_sec > idle_timeout)
2077 send_to_pm(FCGI_REQUEST_TIMEOUT_JOB, fr->fs_path, fr->user, fr->group, 0, 0);
2078 ap_log_rerror(FCGI_LOG_ERR_NOERRNO, r, "FastCGI: comm "
2079 "with (dynamic) server \"%s\" aborted: (first read) "
2080 "idle timeout (%d sec)", fr->fs_path, idle_timeout);
2081 state = STATE_ERROR;
2082 break;
2086 timersub(&fr->queueTime, &fr->startTime, &qwait);
2088 delay = dynamic_first_recv * dynamicPleaseStartDelay;
2090 FCGIDBG5("qwait=%ld.%06ld delay=%d first_recv=%d", qwait.tv_sec, qwait.tv_usec, delay, dynamic_first_recv);
2092 if (qwait.tv_sec < delay)
2094 timeout.tv_sec = delay;
2095 timeout.tv_usec = 100000; /* fudge for select() slop */
2096 timersub(&timeout, &qwait, &timeout);
2098 else
2100 /* Killed time somewhere.. client read? */
2101 send_to_pm(FCGI_REQUEST_TIMEOUT_JOB, fr->fs_path, fr->user, fr->group, 0, 0);
2102 dynamic_first_recv = qwait.tv_sec / dynamicPleaseStartDelay + 1;
2103 timeout.tv_sec = dynamic_first_recv * dynamicPleaseStartDelay;
2104 timeout.tv_usec = 100000; /* fudge for select() slop */
2105 timersub(&timeout, &qwait, &timeout);
2108 else
2110 timeout.tv_sec = idle_timeout;
2111 timeout.tv_usec = 0;
2114 /* wait on the socket */
2115 select_status = ap_select(nfds, &read_set, &write_set, NULL, &timeout);
2117 if (select_status < 0)
2119 ap_log_rerror(FCGI_LOG_ERR_ERRNO, r, "FastCGI: comm with server "
2120 "\"%s\" aborted: select() failed", fr->fs_path);
2121 state = STATE_ERROR;
2122 break;
2125 if (select_status == 0)
2127 /* select() timeout */
2129 if (BufferLength(fr->clientOutputBuffer))
2131 if (fr->role == FCGI_RESPONDER)
2133 client_send = TRUE;
2136 else if (dynamic_first_recv)
2138 struct timeval qwait;
2140 fcgi_util_ticks(&fr->queueTime);
2141 timersub(&fr->queueTime, &fr->startTime, &qwait);
2143 send_to_pm(FCGI_REQUEST_TIMEOUT_JOB, fr->fs_path, fr->user, fr->group, 0, 0);
2145 dynamic_first_recv = qwait.tv_sec / dynamicPleaseStartDelay + 1;
2146 continue;
2148 else
2150 ap_log_rerror(FCGI_LOG_ERR_NOERRNO, r, "FastCGI: comm with "
2151 "server \"%s\" aborted: idle timeout (%d sec)",
2152 fr->fs_path, idle_timeout);
2153 state = STATE_ERROR;
2157 if (FD_ISSET(fr->fd, &write_set))
2159 /* send to the server */
2161 rv = fcgi_buf_socket_send(fr->serverOutputBuffer, fr->fd);
2163 if (rv < 0)
2165 ap_log_rerror(FCGI_LOG_ERR, r, "FastCGI: comm with server "
2166 "\"%s\" aborted: write failed", fr->fs_path);
2167 state = STATE_ERROR;
2168 break;
2172 if (FD_ISSET(fr->fd, &read_set))
2174 /* recv from the server */
2176 if (dynamic_first_recv)
2178 dynamic_first_recv = 0;
2179 fcgi_util_ticks(&fr->queueTime);
2182 rv = fcgi_buf_socket_recv(fr->serverInputBuffer, fr->fd);
2184 if (rv < 0)
2186 ap_log_rerror(FCGI_LOG_ERR, r, "FastCGI: comm with server "
2187 "\"%s\" aborted: read failed", fr->fs_path);
2188 state = STATE_ERROR;
2189 break;
2192 if (rv == 0)
2194 fr->keepReadingFromFcgiApp = FALSE;
2195 state = STATE_CLIENT_SEND;
2196 break;
2200 if (fcgi_protocol_dequeue(rp, fr))
2202 state = STATE_ERROR;
2203 break;
2206 if (fr->parseHeader == SCAN_CGI_READING_HEADERS)
2208 const char * err = process_headers(r, fr);
2209 if (err)
2211 ap_log_rerror(FCGI_LOG_ERR_NOERRNO, r,
2212 "FastCGI: comm with server \"%s\" aborted: "
2213 "error parsing headers: %s", fr->fs_path, err);
2214 state = STATE_ERROR;
2215 break;
2219 if (fr->exitStatusSet)
2221 fr->keepReadingFromFcgiApp = FALSE;
2222 state = STATE_CLIENT_SEND;
2223 break;
2227 return (state == STATE_ERROR);
2231 /*----------------------------------------------------------------------
2232 * This is the core routine for moving data between the FastCGI
2233 * application and the Web server's client.
2235 static int do_work(request_rec * const r, fcgi_request * const fr)
2237 int rv;
2238 pool *rp = r->pool;
2240 fcgi_protocol_queue_begin_request(fr);
2242 if (fr->role == FCGI_RESPONDER)
2244 rv = ap_setup_client_block(r, REQUEST_CHUNKED_ERROR);
2245 if (rv != OK)
2247 ap_kill_timeout(r);
2248 return rv;
2251 fr->expectingClientContent = ap_should_client_block(r);
2254 ap_block_alarms();
2255 ap_register_cleanup(rp, (void *)fr, cleanup, ap_null_cleanup);
2256 ap_unblock_alarms();
2258 ap_hard_timeout("connect() to FastCGI server", r);
2260 /* Connect to the FastCGI Application */
2261 if (open_connection_to_fs(fr) != FCGI_OK)
2263 ap_kill_timeout(r);
2264 return HTTP_INTERNAL_SERVER_ERROR;
2267 #ifdef WIN32
2268 if (fr->using_npipe_io)
2270 rv = npipe_io(fr);
2272 else
2273 #endif
2275 rv = socket_io(fr);
2278 /* comm with the server is done */
2279 close_connection_to_fs(fr);
2281 if (fr->role == FCGI_RESPONDER)
2283 sink_client_data(fr);
2286 while (rv == 0 && (BufferLength(fr->serverInputBuffer) || BufferLength(fr->clientOutputBuffer)))
2288 if (fcgi_protocol_dequeue(rp, fr))
2290 rv = HTTP_INTERNAL_SERVER_ERROR;
2293 if (fr->parseHeader == SCAN_CGI_READING_HEADERS)
2295 const char * err = process_headers(r, fr);
2296 if (err)
2298 ap_log_rerror(FCGI_LOG_ERR_NOERRNO, r,
2299 "FastCGI: comm with server \"%s\" aborted: "
2300 "error parsing headers: %s", fr->fs_path, err);
2301 rv = HTTP_INTERNAL_SERVER_ERROR;
2305 if (fr->role == FCGI_RESPONDER)
2307 if (write_to_client(fr))
2309 break;
2312 else
2314 fcgi_buf_reset(fr->clientOutputBuffer);
2318 switch (fr->parseHeader)
2320 case SCAN_CGI_FINISHED:
2322 if (fr->role == FCGI_RESPONDER)
2324 /* RUSSIAN_APACHE requires rflush() over bflush() */
2325 ap_rflush(r);
2326 #ifndef APACHE2
2327 ap_bgetopt(r->connection->client, BO_BYTECT, &r->bytes_sent);
2328 #endif
2331 /* fall through */
2333 case SCAN_CGI_INT_REDIRECT:
2334 case SCAN_CGI_SRV_REDIRECT:
2336 break;
2338 case SCAN_CGI_READING_HEADERS:
2340 ap_log_rerror(FCGI_LOG_ERR_NOERRNO, r, "FastCGI: incomplete headers "
2341 "(%d bytes) received from server \"%s\"", fr->header->nelts, fr->fs_path);
2343 /* fall through */
2345 case SCAN_CGI_BAD_HEADER:
2347 rv = HTTP_INTERNAL_SERVER_ERROR;
2348 break;
2350 default:
2352 ap_assert(0);
2353 rv = HTTP_INTERNAL_SERVER_ERROR;
2356 ap_kill_timeout(r);
2357 return rv;
2360 static fcgi_request *create_fcgi_request(request_rec * const r, const char *path)
2362 const char *fs_path;
2363 pool * const p = r->pool;
2364 fcgi_server *fs;
2365 fcgi_request * const fr = (fcgi_request *)ap_pcalloc(p, sizeof(fcgi_request));
2367 fs_path = path ? path : r->filename;
2369 fs = fcgi_util_fs_get_by_id(fs_path, fcgi_util_get_server_uid(r->server),
2370 fcgi_util_get_server_gid(r->server));
2371 if (fs == NULL)
2373 const char * err;
2374 struct stat *my_finfo;
2376 /* dynamic? */
2378 #ifndef APACHE2
2379 if (path == NULL)
2381 /* AP2: its bogus that we don't make use of r->finfo, but
2382 * its an apr_finfo_t and there is no apr_os_finfo_get() */
2384 my_finfo = &r->finfo;
2386 else
2387 #endif
2389 my_finfo = (struct stat *) ap_palloc(p, sizeof(struct stat));
2391 if (stat(fs_path, my_finfo) < 0)
2393 ap_log_rerror(FCGI_LOG_ERR_ERRNO, r,
2394 "FastCGI: stat() of \"%s\" failed", fs_path);
2395 return NULL;
2399 err = fcgi_util_fs_is_path_ok(p, fs_path, my_finfo);
2401 if (err)
2403 ap_log_rerror(FCGI_LOG_ERR_NOERRNO, r,
2404 "FastCGI: invalid (dynamic) server \"%s\": %s", fs_path, err);
2405 return NULL;
2409 fr->serverInputBuffer = fcgi_buf_new(p, SERVER_BUFSIZE);
2410 fr->serverOutputBuffer = fcgi_buf_new(p, SERVER_BUFSIZE);
2411 fr->clientInputBuffer = fcgi_buf_new(p, SERVER_BUFSIZE);
2412 fr->clientOutputBuffer = fcgi_buf_new(p, SERVER_BUFSIZE);
2413 fr->erBufPtr = fcgi_buf_new(p, sizeof(FCGI_EndRequestBody) + 1);
2414 fr->gotHeader = FALSE;
2415 fr->parseHeader = SCAN_CGI_READING_HEADERS;
2416 fr->header = ap_make_array(p, 1, 1);
2417 fr->fs_stderr = NULL;
2418 fr->r = r;
2419 fr->readingEndRequestBody = FALSE;
2420 fr->exitStatus = 0;
2421 fr->exitStatusSet = FALSE;
2422 fr->requestId = 1; /* anything but zero is OK here */
2423 fr->eofSent = FALSE;
2424 fr->role = FCGI_RESPONDER;
2425 fr->expectingClientContent = FALSE;
2426 fr->keepReadingFromFcgiApp = TRUE;
2427 fr->fs = fs;
2428 fr->fs_path = fs_path;
2429 fr->authHeaders = ap_make_table(p, 10);
2430 #ifdef WIN32
2431 fr->fd = INVALID_SOCKET;
2432 fr->dynamic = ((fs == NULL) || (fs->directive == APP_CLASS_DYNAMIC)) ? TRUE : FALSE;
2433 fr->using_npipe_io = FALSE;
2434 #else
2435 fr->dynamic = (fs == NULL) ? TRUE : FALSE;
2436 fr->fd = -1;
2437 #endif
2439 set_uid_n_gid(r, &fr->user, &fr->group);
2441 return fr;
2445 *----------------------------------------------------------------------
2447 * handler --
2449 * This routine gets called for a request that corresponds to
2450 * a FastCGI connection. It performs the request synchronously.
2452 * Results:
2453 * Final status of request: OK or NOT_FOUND or HTTP_INTERNAL_SERVER_ERROR.
2455 * Side effects:
2456 * Request performed.
2458 *----------------------------------------------------------------------
2461 /* Stolen from mod_cgi.c..
2462 * KLUDGE --- for back-combatibility, we don't have to check ExecCGI
2463 * in ScriptAliased directories, which means we need to know if this
2464 * request came through ScriptAlias or not... so the Alias module
2465 * leaves a note for us.
2467 static int apache_is_scriptaliased(request_rec *r)
2469 const char *t = ap_table_get(r->notes, "alias-forced-type");
2470 return t && (!strcasecmp(t, "cgi-script"));
2473 /* If a script wants to produce its own Redirect body, it now
2474 * has to explicitly *say* "Status: 302". If it wants to use
2475 * Apache redirects say "Status: 200". See process_headers().
2477 static int post_process_for_redirects(request_rec * const r,
2478 const fcgi_request * const fr)
2480 switch(fr->parseHeader) {
2481 case SCAN_CGI_INT_REDIRECT:
2483 /* @@@ There are still differences between the handling in
2484 * mod_cgi and mod_fastcgi. This needs to be revisited.
2486 /* We already read the message body (if any), so don't allow
2487 * the redirected request to think it has one. We can ignore
2488 * Transfer-Encoding, since we used REQUEST_CHUNKED_ERROR.
2490 r->method = "GET";
2491 r->method_number = M_GET;
2492 ap_table_unset(r->headers_in, "Content-length");
2494 ap_internal_redirect_handler(ap_table_get(r->headers_out, "Location"), r);
2495 return OK;
2497 case SCAN_CGI_SRV_REDIRECT:
2498 return HTTP_MOVED_TEMPORARILY;
2500 default:
2501 return OK;
2505 /******************************************************************************
2506 * Process fastcgi-script requests. Based on mod_cgi::cgi_handler().
2508 static int content_handler(request_rec *r)
2510 fcgi_request *fr = NULL;
2511 int ret;
2513 #ifdef APACHE2
2514 if (strcmp(r->handler, FASTCGI_HANDLER_NAME))
2515 return DECLINED;
2516 #endif
2518 /* Setup a new FastCGI request */
2519 if ((fr = create_fcgi_request(r, NULL)) == NULL)
2520 return HTTP_INTERNAL_SERVER_ERROR;
2522 /* If its a dynamic invocation, make sure scripts are OK here */
2523 if (fr->dynamic && !(ap_allow_options(r) & OPT_EXECCGI) && !apache_is_scriptaliased(r)) {
2524 ap_log_rerror(FCGI_LOG_ERR_NOERRNO, r,
2525 "FastCGI: \"ExecCGI Option\" is off in this directory: %s", r->uri);
2526 return HTTP_INTERNAL_SERVER_ERROR;
2529 /* Process the fastcgi-script request */
2530 if ((ret = do_work(r, fr)) != OK)
2531 return ret;
2533 /* Special case redirects */
2534 ret = post_process_for_redirects(r, fr);
2536 return ret;
2540 static int post_process_auth_passed_header(table *t, const char *key, const char * const val)
2542 if (strncasecmp(key, "Variable-", 9) == 0)
2543 key += 9;
2545 ap_table_setn(t, key, val);
2546 return 1;
2549 static int post_process_auth_passed_compat_header(table *t, const char *key, const char * const val)
2551 if (strncasecmp(key, "Variable-", 9) == 0)
2552 ap_table_setn(t, key + 9, val);
2554 return 1;
2557 static int post_process_auth_failed_header(table * const t, const char * const key, const char * const val)
2559 ap_table_setn(t, key, val);
2560 return 1;
2563 static void post_process_auth(fcgi_request * const fr, const int passed)
2565 request_rec * const r = fr->r;
2567 /* Restore the saved subprocess_env because we muddied ours up */
2568 r->subprocess_env = fr->saved_subprocess_env;
2570 if (passed) {
2571 if (fr->auth_compat) {
2572 ap_table_do((int (*)(void *, const char *, const char *))post_process_auth_passed_compat_header,
2573 (void *)r->subprocess_env, fr->authHeaders, NULL);
2575 else {
2576 ap_table_do((int (*)(void *, const char *, const char *))post_process_auth_passed_header,
2577 (void *)r->subprocess_env, fr->authHeaders, NULL);
2580 else {
2581 ap_table_do((int (*)(void *, const char *, const char *))post_process_auth_failed_header,
2582 (void *)r->err_headers_out, fr->authHeaders, NULL);
2585 /* @@@ Restore these.. its a hack until I rewrite the header handling */
2586 r->status = HTTP_OK;
2587 r->status_line = NULL;
2590 static int check_user_authentication(request_rec *r)
2592 int res, authenticated = 0;
2593 const char *password;
2594 fcgi_request *fr;
2595 const fcgi_dir_config * const dir_config =
2596 (const fcgi_dir_config *)ap_get_module_config(r->per_dir_config, &fastcgi_module);
2598 if (dir_config->authenticator == NULL)
2599 return DECLINED;
2601 /* Get the user password */
2602 if ((res = ap_get_basic_auth_pw(r, &password)) != OK)
2603 return res;
2605 if ((fr = create_fcgi_request(r, dir_config->authenticator)) == NULL)
2606 return HTTP_INTERNAL_SERVER_ERROR;
2608 /* Save the existing subprocess_env, because we're gonna muddy it up */
2609 fr->saved_subprocess_env = ap_copy_table(r->pool, r->subprocess_env);
2611 ap_table_setn(r->subprocess_env, "REMOTE_PASSWD", password);
2612 ap_table_setn(r->subprocess_env, "FCGI_APACHE_ROLE", "AUTHENTICATOR");
2614 /* The FastCGI Protocol doesn't differentiate authentication */
2615 fr->role = FCGI_AUTHORIZER;
2617 /* Do we need compatibility mode? */
2618 fr->auth_compat = (dir_config->authenticator_options & FCGI_COMPAT);
2620 if ((res = do_work(r, fr)) != OK)
2621 goto AuthenticationFailed;
2623 authenticated = (r->status == 200);
2624 post_process_auth(fr, authenticated);
2626 /* A redirect shouldn't be allowed during the authentication phase */
2627 if (ap_table_get(r->headers_out, "Location") != NULL) {
2628 ap_log_rerror(FCGI_LOG_ERR_NOERRNO, r,
2629 "FastCGI: FastCgiAuthenticator \"%s\" redirected (not allowed)",
2630 dir_config->authenticator);
2631 goto AuthenticationFailed;
2634 if (authenticated)
2635 return OK;
2637 AuthenticationFailed:
2638 if (!(dir_config->authenticator_options & FCGI_AUTHORITATIVE))
2639 return DECLINED;
2641 /* @@@ Probably should support custom_responses */
2642 ap_note_basic_auth_failure(r);
2643 ap_log_rerror(FCGI_LOG_ERR_NOERRNO, r,
2644 "FastCGI: authentication failed for user \"%s\": %s",
2645 #ifdef APACHE2
2646 r->user, r->uri);
2647 #else
2648 r->connection->user, r->uri);
2649 #endif
2651 return (res == OK) ? HTTP_UNAUTHORIZED : res;
2654 static int check_user_authorization(request_rec *r)
2656 int res, authorized = 0;
2657 fcgi_request *fr;
2658 const fcgi_dir_config * const dir_config =
2659 (const fcgi_dir_config *)ap_get_module_config(r->per_dir_config, &fastcgi_module);
2661 if (dir_config->authorizer == NULL)
2662 return DECLINED;
2664 /* @@@ We should probably honor the existing parameters to the require directive
2665 * as well as allow the definition of new ones (or use the basename of the
2666 * FastCGI server and pass the rest of the directive line), but for now keep
2667 * it simple. */
2669 if ((fr = create_fcgi_request(r, dir_config->authorizer)) == NULL)
2670 return HTTP_INTERNAL_SERVER_ERROR;
2672 /* Save the existing subprocess_env, because we're gonna muddy it up */
2673 fr->saved_subprocess_env = ap_copy_table(r->pool, r->subprocess_env);
2675 ap_table_setn(r->subprocess_env, "FCGI_APACHE_ROLE", "AUTHORIZER");
2677 fr->role = FCGI_AUTHORIZER;
2679 /* Do we need compatibility mode? */
2680 fr->auth_compat = (dir_config->authorizer_options & FCGI_COMPAT);
2682 if ((res = do_work(r, fr)) != OK)
2683 goto AuthorizationFailed;
2685 authorized = (r->status == 200);
2686 post_process_auth(fr, authorized);
2688 /* A redirect shouldn't be allowed during the authorization phase */
2689 if (ap_table_get(r->headers_out, "Location") != NULL) {
2690 ap_log_rerror(FCGI_LOG_ERR_NOERRNO, r,
2691 "FastCGI: FastCgiAuthorizer \"%s\" redirected (not allowed)",
2692 dir_config->authorizer);
2693 goto AuthorizationFailed;
2696 if (authorized)
2697 return OK;
2699 AuthorizationFailed:
2700 if (!(dir_config->authorizer_options & FCGI_AUTHORITATIVE))
2701 return DECLINED;
2703 /* @@@ Probably should support custom_responses */
2704 ap_note_basic_auth_failure(r);
2705 ap_log_rerror(FCGI_LOG_ERR_NOERRNO, r,
2706 "FastCGI: authorization failed for user \"%s\": %s",
2707 #ifdef APACHE2
2708 r->user, r->uri);
2709 #else
2710 r->connection->user, r->uri);
2711 #endif
2713 return (res == OK) ? HTTP_UNAUTHORIZED : res;
2716 static int check_access(request_rec *r)
2718 int res, access_allowed = 0;
2719 fcgi_request *fr;
2720 const fcgi_dir_config * const dir_config =
2721 (fcgi_dir_config *)ap_get_module_config(r->per_dir_config, &fastcgi_module);
2723 if (dir_config == NULL || dir_config->access_checker == NULL)
2724 return DECLINED;
2726 if ((fr = create_fcgi_request(r, dir_config->access_checker)) == NULL)
2727 return HTTP_INTERNAL_SERVER_ERROR;
2729 /* Save the existing subprocess_env, because we're gonna muddy it up */
2730 fr->saved_subprocess_env = ap_copy_table(r->pool, r->subprocess_env);
2732 ap_table_setn(r->subprocess_env, "FCGI_APACHE_ROLE", "ACCESS_CHECKER");
2734 /* The FastCGI Protocol doesn't differentiate access control */
2735 fr->role = FCGI_AUTHORIZER;
2737 /* Do we need compatibility mode? */
2738 fr->auth_compat = (dir_config->access_checker_options & FCGI_COMPAT);
2740 if ((res = do_work(r, fr)) != OK)
2741 goto AccessFailed;
2743 access_allowed = (r->status == 200);
2744 post_process_auth(fr, access_allowed);
2746 /* A redirect shouldn't be allowed during the access check phase */
2747 if (ap_table_get(r->headers_out, "Location") != NULL) {
2748 ap_log_rerror(FCGI_LOG_ERR_NOERRNO, r,
2749 "FastCGI: FastCgiAccessChecker \"%s\" redirected (not allowed)",
2750 dir_config->access_checker);
2751 goto AccessFailed;
2754 if (access_allowed)
2755 return OK;
2757 AccessFailed:
2758 if (!(dir_config->access_checker_options & FCGI_AUTHORITATIVE))
2759 return DECLINED;
2761 /* @@@ Probably should support custom_responses */
2762 ap_log_rerror(FCGI_LOG_ERR_NOERRNO, r, "FastCGI: access denied: %s", r->uri);
2763 return (res == OK) ? HTTP_FORBIDDEN : res;
2766 static int
2767 fixups(request_rec * r)
2769 if (fcgi_util_fs_get_by_id(r->filename,
2770 fcgi_util_get_server_uid(r->server),
2771 fcgi_util_get_server_gid(r->server)))
2773 r->handler = FASTCGI_HANDLER_NAME;
2774 return OK;
2777 return DECLINED;
2780 #ifndef APACHE2
2782 # define AP_INIT_RAW_ARGS(directive, func, mconfig, where, help) \
2783 { directive, func, mconfig, where, RAW_ARGS, help }
2784 # define AP_INIT_TAKE1(directive, func, mconfig, where, help) \
2785 { directive, func, mconfig, where, TAKE1, help }
2786 # define AP_INIT_TAKE12(directive, func, mconfig, where, help) \
2787 { directive, func, mconfig, where, TAKE12, help }
2788 # define AP_INIT_FLAG(directive, func, mconfig, where, help) \
2789 { directive, func, mconfig, where, FLAG, help }
2791 #endif
2793 static const command_rec fastcgi_cmds[] =
2795 AP_INIT_RAW_ARGS("AppClass", fcgi_config_new_static_server, NULL, RSRC_CONF, NULL),
2796 AP_INIT_RAW_ARGS("FastCgiServer", fcgi_config_new_static_server, NULL, RSRC_CONF, NULL),
2798 AP_INIT_RAW_ARGS("ExternalAppClass", fcgi_config_new_external_server, NULL, RSRC_CONF, NULL),
2799 AP_INIT_RAW_ARGS("FastCgiExternalServer", fcgi_config_new_external_server, NULL, RSRC_CONF, NULL),
2801 AP_INIT_TAKE1("FastCgiIpcDir", fcgi_config_set_socket_dir, NULL, RSRC_CONF, NULL),
2803 AP_INIT_TAKE1("FastCgiSuexec", fcgi_config_set_wrapper, NULL, RSRC_CONF, NULL),
2804 AP_INIT_TAKE1("FastCgiWrapper", fcgi_config_set_wrapper, NULL, RSRC_CONF, NULL),
2806 AP_INIT_RAW_ARGS("FCGIConfig", fcgi_config_set_config, NULL, RSRC_CONF, NULL),
2807 AP_INIT_RAW_ARGS("FastCgiConfig", fcgi_config_set_config, NULL, RSRC_CONF, NULL),
2809 AP_INIT_TAKE12("FastCgiAuthenticator", fcgi_config_new_auth_server,
2810 (void *)FCGI_AUTH_TYPE_AUTHENTICATOR, ACCESS_CONF,
2811 "a fastcgi-script path (absolute or relative to ServerRoot) followed by an optional -compat"),
2812 AP_INIT_FLAG("FastCgiAuthenticatorAuthoritative", fcgi_config_set_authoritative_slot,
2813 (void *)XtOffsetOf(fcgi_dir_config, authenticator_options), ACCESS_CONF,
2814 "Set to 'off' to allow authentication to be passed along to lower modules upon failure"),
2816 AP_INIT_TAKE12("FastCgiAuthorizer", fcgi_config_new_auth_server,
2817 (void *)FCGI_AUTH_TYPE_AUTHORIZER, ACCESS_CONF,
2818 "a fastcgi-script path (absolute or relative to ServerRoot) followed by an optional -compat"),
2819 AP_INIT_FLAG("FastCgiAuthorizerAuthoritative", fcgi_config_set_authoritative_slot,
2820 (void *)XtOffsetOf(fcgi_dir_config, authorizer_options), ACCESS_CONF,
2821 "Set to 'off' to allow authorization to be passed along to lower modules upon failure"),
2823 AP_INIT_TAKE12("FastCgiAccessChecker", fcgi_config_new_auth_server,
2824 (void *)FCGI_AUTH_TYPE_ACCESS_CHECKER, ACCESS_CONF,
2825 "a fastcgi-script path (absolute or relative to ServerRoot) followed by an optional -compat"),
2826 AP_INIT_FLAG("FastCgiAccessCheckerAuthoritative", fcgi_config_set_authoritative_slot,
2827 (void *)XtOffsetOf(fcgi_dir_config, access_checker_options), ACCESS_CONF,
2828 "Set to 'off' to allow access control to be passed along to lower modules upon failure"),
2829 { NULL }
2832 #ifdef APACHE2
2834 static void register_hooks(apr_pool_t * p)
2836 // ap_hook_pre_config(x_pre_config, NULL, NULL, APR_HOOK_MIDDLE);
2837 ap_hook_post_config(init_module, NULL, NULL, APR_HOOK_MIDDLE);
2838 ap_hook_child_init(fcgi_child_init, NULL, NULL, APR_HOOK_MIDDLE);
2839 ap_hook_handler(content_handler, NULL, NULL, APR_HOOK_MIDDLE);
2840 ap_hook_check_user_id(check_user_authentication, NULL, NULL, APR_HOOK_MIDDLE);
2841 ap_hook_access_checker(check_access, NULL, NULL, APR_HOOK_MIDDLE);
2842 ap_hook_auth_checker(check_user_authorization, NULL, NULL, APR_HOOK_MIDDLE);
2843 ap_hook_fixups(fixups, NULL, NULL, APR_HOOK_MIDDLE);
2846 module AP_MODULE_DECLARE_DATA fastcgi_module =
2848 STANDARD20_MODULE_STUFF,
2849 fcgi_config_create_dir_config, /* per-directory config creator */
2850 NULL, /* dir config merger */
2851 NULL, /* server config creator */
2852 NULL, /* server config merger */
2853 fastcgi_cmds, /* command table */
2854 register_hooks, /* set up other request processing hooks */
2857 #else /* !APACHE2 */
2859 handler_rec fastcgi_handlers[] = {
2860 { FCGI_MAGIC_TYPE, content_handler },
2861 { FASTCGI_HANDLER_NAME, content_handler },
2862 { NULL }
2865 module MODULE_VAR_EXPORT fastcgi_module = {
2866 STANDARD_MODULE_STUFF,
2867 init_module, /* initializer */
2868 fcgi_config_create_dir_config, /* per-dir config creator */
2869 NULL, /* per-dir config merger (default: override) */
2870 NULL, /* per-server config creator */
2871 NULL, /* per-server config merger (default: override) */
2872 fastcgi_cmds, /* command table */
2873 fastcgi_handlers, /* [9] content handlers */
2874 NULL, /* [2] URI-to-filename translation */
2875 check_user_authentication, /* [5] authenticate user_id */
2876 check_user_authorization, /* [6] authorize user_id */
2877 check_access, /* [4] check access (based on src & http headers) */
2878 NULL, /* [7] check/set MIME type */
2879 fixups, /* [8] fixups */
2880 NULL, /* [10] logger */
2881 NULL, /* [3] header-parser */
2882 fcgi_child_init, /* process initialization */
2883 #ifdef WIN32
2884 fcgi_child_exit, /* process exit/cleanup */
2885 #else
2886 NULL,
2887 #endif
2888 NULL /* [1] post read-request handling */
2891 #endif /* !APACHE2 */