clear up some gcc -Wall warnings
[mod_fastcgi.git] / mod_fastcgi.c
blob1951ec551bff1f6df6ebca83d4c26a53ccb9c1ec
1 /*
2 * mod_fastcgi.c --
4 * Apache server module for FastCGI.
6 * $Id: mod_fastcgi.c,v 1.145 2002/10/22 01:02:18 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 fcgi_buf_removed(b, sent);
1620 ResetEvent(sov.hEvent);
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 DWORD sent;
1822 if (GetOverlappedResult((HANDLE) fr->fd, &sov, &sent, FALSE))
1824 send_pending = 0;
1825 ResetEvent(sov.hEvent);
1826 fcgi_buf_removed(fr->serverOutputBuffer, sent);
1828 else
1830 ap_log_rerror(FCGI_LOG_ERR, r, "FastCGI: comm with server "
1831 "\"%s\" aborted: GetOverlappedResult() failed", fr->fs_path);
1832 state = STATE_ERROR;
1833 break;
1836 else
1838 DWORD rcvd;
1840 ap_assert(i == 1);
1842 recv_pending = 0;
1843 ResetEvent(rov.hEvent);
1845 if (GetOverlappedResult((HANDLE) fr->fd, &rov, &rcvd, FALSE))
1847 fcgi_buf_added(fr->serverInputBuffer, rcvd);
1848 if (dynamic_first_recv)
1850 dynamic_first_recv = 0;
1853 else
1855 ap_log_rerror(FCGI_LOG_ERR, r, "FastCGI: comm with server "
1856 "\"%s\" aborted: GetOverlappedResult() failed", fr->fs_path);
1857 state = STATE_ERROR;
1858 break;
1864 if (fcgi_protocol_dequeue(rp, fr))
1866 state = STATE_ERROR;
1867 break;
1870 if (fr->parseHeader == SCAN_CGI_READING_HEADERS)
1872 const char * err = process_headers(r, fr);
1873 if (err)
1875 ap_log_rerror(FCGI_LOG_ERR_NOERRNO, r,
1876 "FastCGI: comm with server \"%s\" aborted: "
1877 "error parsing headers: %s", fr->fs_path, err);
1878 state = STATE_ERROR;
1879 break;
1883 if (fr->exitStatusSet)
1885 fr->keepReadingFromFcgiApp = FALSE;
1886 state = STATE_CLIENT_SEND;
1887 break;
1891 if (! fr->exitStatusSet || ! fr->eofSent)
1893 CancelIo((HANDLE) fr->fd);
1896 CloseHandle(rov.hEvent);
1897 CloseHandle(sov.hEvent);
1899 return (state == STATE_ERROR);
1901 #endif /* WIN32 */
1903 static int socket_io(fcgi_request * const fr)
1905 enum
1907 STATE_SOCKET_NONE,
1908 STATE_ENV_SEND,
1909 STATE_CLIENT_RECV,
1910 STATE_SERVER_SEND,
1911 STATE_SERVER_RECV,
1912 STATE_CLIENT_SEND,
1913 STATE_ERROR,
1914 STATE_CLIENT_ERROR
1916 state = STATE_ENV_SEND;
1918 request_rec * const r = fr->r;
1920 struct timeval timeout;
1921 struct timeval dynamic_last_io_time = {0, 0};
1922 fd_set read_set;
1923 fd_set write_set;
1924 int nfds = fr->fd + 1;
1925 int select_status = 1;
1926 int idle_timeout;
1927 int rv;
1928 int dynamic_first_recv = fr->dynamic ? 1 : 0;
1929 int client_send = FALSE;
1930 int client_recv = FALSE;
1931 env_status env;
1932 pool *rp = r->pool;
1934 if (fr->role == FCGI_RESPONDER)
1936 client_recv = (fr->expectingClientContent != 0);
1939 idle_timeout = fr->dynamic ? dynamic_idle_timeout : fr->fs->idle_timeout;
1941 env.envp = NULL;
1943 if (fr->dynamic)
1945 dynamic_last_io_time = fr->startTime;
1947 if (dynamicAppConnectTimeout)
1949 struct timeval qwait;
1950 timersub(&fr->queueTime, &fr->startTime, &qwait);
1951 dynamic_first_recv = qwait.tv_sec / dynamicPleaseStartDelay + 1;
1955 ap_hard_timeout("FastCGI request processing", r);
1957 set_nonblocking(fr, TRUE);
1959 for (;;)
1961 FD_ZERO(&read_set);
1962 FD_ZERO(&write_set);
1964 switch (state)
1966 case STATE_ENV_SEND:
1968 if (fcgi_protocol_queue_env(r, fr, &env) == 0)
1970 goto SERVER_SEND;
1973 state = STATE_CLIENT_RECV;
1975 /* fall through */
1977 case STATE_CLIENT_RECV:
1979 if (read_from_client_n_queue(fr))
1981 state = STATE_CLIENT_ERROR;
1982 break;
1985 if (fr->eofSent)
1987 state = STATE_SERVER_SEND;
1990 /* fall through */
1992 SERVER_SEND:
1994 case STATE_SERVER_SEND:
1996 if (BufferLength(fr->serverOutputBuffer))
1998 FD_SET(fr->fd, &write_set);
2000 else
2002 ap_assert(fr->eofSent);
2003 state = STATE_SERVER_RECV;
2006 /* fall through */
2008 case STATE_SERVER_RECV:
2010 FD_SET(fr->fd, &read_set);
2012 /* fall through */
2014 case STATE_CLIENT_SEND:
2016 if (client_send || ! BufferFree(fr->clientOutputBuffer))
2018 if (write_to_client(fr))
2020 state = STATE_CLIENT_ERROR;
2021 break;
2024 client_send = 0;
2027 break;
2029 case STATE_ERROR:
2030 case STATE_CLIENT_ERROR:
2032 break;
2034 default:
2036 ap_assert(0);
2039 if (state == STATE_CLIENT_ERROR || state == STATE_ERROR)
2041 break;
2044 /* setup the io timeout */
2046 if (BufferLength(fr->clientOutputBuffer))
2048 /* don't let client data sit too long, it might be a push */
2049 timeout.tv_sec = 0;
2050 timeout.tv_usec = 100000;
2052 else if (dynamic_first_recv)
2054 int delay;
2055 struct timeval qwait;
2057 fcgi_util_ticks(&fr->queueTime);
2059 if (select_status)
2061 /* a send() succeeded last pass */
2062 dynamic_last_io_time = fr->queueTime;
2064 else
2066 /* timed out last pass */
2067 struct timeval idle_time;
2069 timersub(&fr->queueTime, &dynamic_last_io_time, &idle_time);
2071 if (idle_time.tv_sec > idle_timeout)
2073 send_to_pm(FCGI_REQUEST_TIMEOUT_JOB, fr->fs_path, fr->user, fr->group, 0, 0);
2074 ap_log_rerror(FCGI_LOG_ERR_NOERRNO, r, "FastCGI: comm "
2075 "with (dynamic) server \"%s\" aborted: (first read) "
2076 "idle timeout (%d sec)", fr->fs_path, idle_timeout);
2077 state = STATE_ERROR;
2078 break;
2082 timersub(&fr->queueTime, &fr->startTime, &qwait);
2084 delay = dynamic_first_recv * dynamicPleaseStartDelay;
2086 FCGIDBG5("qwait=%ld.%06ld delay=%d first_recv=%d", qwait.tv_sec, qwait.tv_usec, delay, dynamic_first_recv);
2088 if (qwait.tv_sec < delay)
2090 timeout.tv_sec = delay;
2091 timeout.tv_usec = 100000; /* fudge for select() slop */
2092 timersub(&timeout, &qwait, &timeout);
2094 else
2096 /* Killed time somewhere.. client read? */
2097 send_to_pm(FCGI_REQUEST_TIMEOUT_JOB, fr->fs_path, fr->user, fr->group, 0, 0);
2098 dynamic_first_recv = qwait.tv_sec / dynamicPleaseStartDelay + 1;
2099 timeout.tv_sec = dynamic_first_recv * dynamicPleaseStartDelay;
2100 timeout.tv_usec = 100000; /* fudge for select() slop */
2101 timersub(&timeout, &qwait, &timeout);
2104 else
2106 timeout.tv_sec = idle_timeout;
2107 timeout.tv_usec = 0;
2110 /* wait on the socket */
2111 select_status = ap_select(nfds, &read_set, &write_set, NULL, &timeout);
2113 if (select_status < 0)
2115 ap_log_rerror(FCGI_LOG_ERR_ERRNO, r, "FastCGI: comm with server "
2116 "\"%s\" aborted: select() failed", fr->fs_path);
2117 state = STATE_ERROR;
2118 break;
2121 if (select_status == 0)
2123 /* select() timeout */
2125 if (BufferLength(fr->clientOutputBuffer))
2127 if (fr->role == FCGI_RESPONDER)
2129 client_send = TRUE;
2132 else if (dynamic_first_recv)
2134 struct timeval qwait;
2136 fcgi_util_ticks(&fr->queueTime);
2137 timersub(&fr->queueTime, &fr->startTime, &qwait);
2139 send_to_pm(FCGI_REQUEST_TIMEOUT_JOB, fr->fs_path, fr->user, fr->group, 0, 0);
2141 dynamic_first_recv = qwait.tv_sec / dynamicPleaseStartDelay + 1;
2142 continue;
2144 else
2146 ap_log_rerror(FCGI_LOG_ERR_NOERRNO, r, "FastCGI: comm with "
2147 "server \"%s\" aborted: idle timeout (%d sec)",
2148 fr->fs_path, idle_timeout);
2149 state = STATE_ERROR;
2153 if (FD_ISSET(fr->fd, &write_set))
2155 /* send to the server */
2157 rv = fcgi_buf_socket_send(fr->serverOutputBuffer, fr->fd);
2159 if (rv < 0)
2161 ap_log_rerror(FCGI_LOG_ERR, r, "FastCGI: comm with server "
2162 "\"%s\" aborted: write failed", fr->fs_path);
2163 state = STATE_ERROR;
2164 break;
2168 if (FD_ISSET(fr->fd, &read_set))
2170 /* recv from the server */
2172 if (dynamic_first_recv)
2174 dynamic_first_recv = 0;
2175 fcgi_util_ticks(&fr->queueTime);
2178 rv = fcgi_buf_socket_recv(fr->serverInputBuffer, fr->fd);
2180 if (rv < 0)
2182 ap_log_rerror(FCGI_LOG_ERR, r, "FastCGI: comm with server "
2183 "\"%s\" aborted: read failed", fr->fs_path);
2184 state = STATE_ERROR;
2185 break;
2188 if (rv == 0)
2190 fr->keepReadingFromFcgiApp = FALSE;
2191 state = STATE_CLIENT_SEND;
2192 break;
2196 if (fcgi_protocol_dequeue(rp, fr))
2198 state = STATE_ERROR;
2199 break;
2202 if (fr->parseHeader == SCAN_CGI_READING_HEADERS)
2204 const char * err = process_headers(r, fr);
2205 if (err)
2207 ap_log_rerror(FCGI_LOG_ERR_NOERRNO, r,
2208 "FastCGI: comm with server \"%s\" aborted: "
2209 "error parsing headers: %s", fr->fs_path, err);
2210 state = STATE_ERROR;
2211 break;
2215 if (fr->exitStatusSet)
2217 fr->keepReadingFromFcgiApp = FALSE;
2218 state = STATE_CLIENT_SEND;
2219 break;
2223 return (state == STATE_ERROR);
2227 /*----------------------------------------------------------------------
2228 * This is the core routine for moving data between the FastCGI
2229 * application and the Web server's client.
2231 static int do_work(request_rec * const r, fcgi_request * const fr)
2233 int rv;
2234 pool *rp = r->pool;
2236 fcgi_protocol_queue_begin_request(fr);
2238 if (fr->role == FCGI_RESPONDER)
2240 rv = ap_setup_client_block(r, REQUEST_CHUNKED_ERROR);
2241 if (rv != OK)
2243 ap_kill_timeout(r);
2244 return rv;
2247 fr->expectingClientContent = ap_should_client_block(r);
2250 ap_block_alarms();
2251 ap_register_cleanup(rp, (void *)fr, cleanup, ap_null_cleanup);
2252 ap_unblock_alarms();
2254 ap_hard_timeout("connect() to FastCGI server", r);
2256 /* Connect to the FastCGI Application */
2257 if (open_connection_to_fs(fr) != FCGI_OK)
2259 ap_kill_timeout(r);
2260 return HTTP_INTERNAL_SERVER_ERROR;
2263 #ifdef WIN32
2264 if (fr->using_npipe_io)
2266 rv = npipe_io(fr);
2268 else
2269 #endif
2271 rv = socket_io(fr);
2274 /* comm with the server is done */
2275 close_connection_to_fs(fr);
2277 if (fr->role == FCGI_RESPONDER)
2279 sink_client_data(fr);
2282 while (rv == 0 && (BufferLength(fr->serverInputBuffer) || BufferLength(fr->clientOutputBuffer)))
2284 if (fcgi_protocol_dequeue(rp, fr))
2286 rv = HTTP_INTERNAL_SERVER_ERROR;
2289 if (fr->parseHeader == SCAN_CGI_READING_HEADERS)
2291 const char * err = process_headers(r, fr);
2292 if (err)
2294 ap_log_rerror(FCGI_LOG_ERR_NOERRNO, r,
2295 "FastCGI: comm with server \"%s\" aborted: "
2296 "error parsing headers: %s", fr->fs_path, err);
2297 rv = HTTP_INTERNAL_SERVER_ERROR;
2301 if (fr->role == FCGI_RESPONDER)
2303 if (write_to_client(fr))
2305 break;
2308 else
2310 fcgi_buf_reset(fr->clientOutputBuffer);
2314 switch (fr->parseHeader)
2316 case SCAN_CGI_FINISHED:
2318 if (fr->role == FCGI_RESPONDER)
2320 /* RUSSIAN_APACHE requires rflush() over bflush() */
2321 ap_rflush(r);
2322 #ifndef APACHE2
2323 ap_bgetopt(r->connection->client, BO_BYTECT, &r->bytes_sent);
2324 #endif
2327 /* fall through */
2329 case SCAN_CGI_INT_REDIRECT:
2330 case SCAN_CGI_SRV_REDIRECT:
2332 break;
2334 case SCAN_CGI_READING_HEADERS:
2336 ap_log_rerror(FCGI_LOG_ERR_NOERRNO, r, "FastCGI: incomplete headers "
2337 "(%d bytes) received from server \"%s\"", fr->header->nelts, fr->fs_path);
2339 /* fall through */
2341 case SCAN_CGI_BAD_HEADER:
2343 rv = HTTP_INTERNAL_SERVER_ERROR;
2344 break;
2346 default:
2348 ap_assert(0);
2349 rv = HTTP_INTERNAL_SERVER_ERROR;
2352 ap_kill_timeout(r);
2353 return rv;
2356 static fcgi_request *create_fcgi_request(request_rec * const r, const char *path)
2358 const char *fs_path;
2359 pool * const p = r->pool;
2360 fcgi_server *fs;
2361 fcgi_request * const fr = (fcgi_request *)ap_pcalloc(p, sizeof(fcgi_request));
2363 fs_path = path ? path : r->filename;
2365 fs = fcgi_util_fs_get_by_id(fs_path, fcgi_util_get_server_uid(r->server),
2366 fcgi_util_get_server_gid(r->server));
2367 if (fs == NULL)
2369 const char * err;
2370 struct stat *my_finfo;
2372 /* dynamic? */
2374 #ifndef APACHE2
2375 if (path == NULL)
2377 /* AP2: its bogus that we don't make use of r->finfo, but
2378 * its an apr_finfo_t and there is no apr_os_finfo_get() */
2380 my_finfo = &r->finfo;
2382 else
2383 #endif
2385 my_finfo = (struct stat *) ap_palloc(p, sizeof(struct stat));
2387 if (stat(fs_path, my_finfo) < 0)
2389 ap_log_rerror(FCGI_LOG_ERR_ERRNO, r,
2390 "FastCGI: stat() of \"%s\" failed", fs_path);
2391 return NULL;
2395 err = fcgi_util_fs_is_path_ok(p, fs_path, my_finfo);
2397 if (err)
2399 ap_log_rerror(FCGI_LOG_ERR_NOERRNO, r,
2400 "FastCGI: invalid (dynamic) server \"%s\": %s", fs_path, err);
2401 return NULL;
2405 fr->serverInputBuffer = fcgi_buf_new(p, SERVER_BUFSIZE);
2406 fr->serverOutputBuffer = fcgi_buf_new(p, SERVER_BUFSIZE);
2407 fr->clientInputBuffer = fcgi_buf_new(p, SERVER_BUFSIZE);
2408 fr->clientOutputBuffer = fcgi_buf_new(p, SERVER_BUFSIZE);
2409 fr->erBufPtr = fcgi_buf_new(p, sizeof(FCGI_EndRequestBody) + 1);
2410 fr->gotHeader = FALSE;
2411 fr->parseHeader = SCAN_CGI_READING_HEADERS;
2412 fr->header = ap_make_array(p, 1, 1);
2413 fr->fs_stderr = NULL;
2414 fr->r = r;
2415 fr->readingEndRequestBody = FALSE;
2416 fr->exitStatus = 0;
2417 fr->exitStatusSet = FALSE;
2418 fr->requestId = 1; /* anything but zero is OK here */
2419 fr->eofSent = FALSE;
2420 fr->role = FCGI_RESPONDER;
2421 fr->expectingClientContent = FALSE;
2422 fr->keepReadingFromFcgiApp = TRUE;
2423 fr->fs = fs;
2424 fr->fs_path = fs_path;
2425 fr->authHeaders = ap_make_table(p, 10);
2426 #ifdef WIN32
2427 fr->fd = INVALID_SOCKET;
2428 fr->dynamic = ((fs == NULL) || (fs->directive == APP_CLASS_DYNAMIC)) ? TRUE : FALSE;
2429 fr->using_npipe_io = FALSE;
2430 #else
2431 fr->dynamic = (fs == NULL) ? TRUE : FALSE;
2432 fr->fd = -1;
2433 #endif
2435 set_uid_n_gid(r, &fr->user, &fr->group);
2437 return fr;
2441 *----------------------------------------------------------------------
2443 * handler --
2445 * This routine gets called for a request that corresponds to
2446 * a FastCGI connection. It performs the request synchronously.
2448 * Results:
2449 * Final status of request: OK or NOT_FOUND or HTTP_INTERNAL_SERVER_ERROR.
2451 * Side effects:
2452 * Request performed.
2454 *----------------------------------------------------------------------
2457 /* Stolen from mod_cgi.c..
2458 * KLUDGE --- for back-combatibility, we don't have to check ExecCGI
2459 * in ScriptAliased directories, which means we need to know if this
2460 * request came through ScriptAlias or not... so the Alias module
2461 * leaves a note for us.
2463 static int apache_is_scriptaliased(request_rec *r)
2465 const char *t = ap_table_get(r->notes, "alias-forced-type");
2466 return t && (!strcasecmp(t, "cgi-script"));
2469 /* If a script wants to produce its own Redirect body, it now
2470 * has to explicitly *say* "Status: 302". If it wants to use
2471 * Apache redirects say "Status: 200". See process_headers().
2473 static int post_process_for_redirects(request_rec * const r,
2474 const fcgi_request * const fr)
2476 switch(fr->parseHeader) {
2477 case SCAN_CGI_INT_REDIRECT:
2479 /* @@@ There are still differences between the handling in
2480 * mod_cgi and mod_fastcgi. This needs to be revisited.
2482 /* We already read the message body (if any), so don't allow
2483 * the redirected request to think it has one. We can ignore
2484 * Transfer-Encoding, since we used REQUEST_CHUNKED_ERROR.
2486 r->method = "GET";
2487 r->method_number = M_GET;
2488 ap_table_unset(r->headers_in, "Content-length");
2490 ap_internal_redirect_handler(ap_table_get(r->headers_out, "Location"), r);
2491 return OK;
2493 case SCAN_CGI_SRV_REDIRECT:
2494 return HTTP_MOVED_TEMPORARILY;
2496 default:
2497 return OK;
2501 /******************************************************************************
2502 * Process fastcgi-script requests. Based on mod_cgi::cgi_handler().
2504 static int content_handler(request_rec *r)
2506 fcgi_request *fr = NULL;
2507 int ret;
2509 #ifdef APACHE2
2510 if (strcmp(r->handler, FASTCGI_HANDLER_NAME))
2511 return DECLINED;
2512 #endif
2514 /* Setup a new FastCGI request */
2515 if ((fr = create_fcgi_request(r, NULL)) == NULL)
2516 return HTTP_INTERNAL_SERVER_ERROR;
2518 /* If its a dynamic invocation, make sure scripts are OK here */
2519 if (fr->dynamic && !(ap_allow_options(r) & OPT_EXECCGI) && !apache_is_scriptaliased(r)) {
2520 ap_log_rerror(FCGI_LOG_ERR_NOERRNO, r,
2521 "FastCGI: \"ExecCGI Option\" is off in this directory: %s", r->uri);
2522 return HTTP_INTERNAL_SERVER_ERROR;
2525 /* Process the fastcgi-script request */
2526 if ((ret = do_work(r, fr)) != OK)
2527 return ret;
2529 /* Special case redirects */
2530 ret = post_process_for_redirects(r, fr);
2532 return ret;
2536 static int post_process_auth_passed_header(table *t, const char *key, const char * const val)
2538 if (strncasecmp(key, "Variable-", 9) == 0)
2539 key += 9;
2541 ap_table_setn(t, key, val);
2542 return 1;
2545 static int post_process_auth_passed_compat_header(table *t, const char *key, const char * const val)
2547 if (strncasecmp(key, "Variable-", 9) == 0)
2548 ap_table_setn(t, key + 9, val);
2550 return 1;
2553 static int post_process_auth_failed_header(table * const t, const char * const key, const char * const val)
2555 ap_table_setn(t, key, val);
2556 return 1;
2559 static void post_process_auth(fcgi_request * const fr, const int passed)
2561 request_rec * const r = fr->r;
2563 /* Restore the saved subprocess_env because we muddied ours up */
2564 r->subprocess_env = fr->saved_subprocess_env;
2566 if (passed) {
2567 if (fr->auth_compat) {
2568 ap_table_do((int (*)(void *, const char *, const char *))post_process_auth_passed_compat_header,
2569 (void *)r->subprocess_env, fr->authHeaders, NULL);
2571 else {
2572 ap_table_do((int (*)(void *, const char *, const char *))post_process_auth_passed_header,
2573 (void *)r->subprocess_env, fr->authHeaders, NULL);
2576 else {
2577 ap_table_do((int (*)(void *, const char *, const char *))post_process_auth_failed_header,
2578 (void *)r->err_headers_out, fr->authHeaders, NULL);
2581 /* @@@ Restore these.. its a hack until I rewrite the header handling */
2582 r->status = HTTP_OK;
2583 r->status_line = NULL;
2586 static int check_user_authentication(request_rec *r)
2588 int res, authenticated = 0;
2589 const char *password;
2590 fcgi_request *fr;
2591 const fcgi_dir_config * const dir_config =
2592 (const fcgi_dir_config *)ap_get_module_config(r->per_dir_config, &fastcgi_module);
2594 if (dir_config->authenticator == NULL)
2595 return DECLINED;
2597 /* Get the user password */
2598 if ((res = ap_get_basic_auth_pw(r, &password)) != OK)
2599 return res;
2601 if ((fr = create_fcgi_request(r, dir_config->authenticator)) == NULL)
2602 return HTTP_INTERNAL_SERVER_ERROR;
2604 /* Save the existing subprocess_env, because we're gonna muddy it up */
2605 fr->saved_subprocess_env = ap_copy_table(r->pool, r->subprocess_env);
2607 ap_table_setn(r->subprocess_env, "REMOTE_PASSWD", password);
2608 ap_table_setn(r->subprocess_env, "FCGI_APACHE_ROLE", "AUTHENTICATOR");
2610 /* The FastCGI Protocol doesn't differentiate authentication */
2611 fr->role = FCGI_AUTHORIZER;
2613 /* Do we need compatibility mode? */
2614 fr->auth_compat = (dir_config->authenticator_options & FCGI_COMPAT);
2616 if ((res = do_work(r, fr)) != OK)
2617 goto AuthenticationFailed;
2619 authenticated = (r->status == 200);
2620 post_process_auth(fr, authenticated);
2622 /* A redirect shouldn't be allowed during the authentication phase */
2623 if (ap_table_get(r->headers_out, "Location") != NULL) {
2624 ap_log_rerror(FCGI_LOG_ERR_NOERRNO, r,
2625 "FastCGI: FastCgiAuthenticator \"%s\" redirected (not allowed)",
2626 dir_config->authenticator);
2627 goto AuthenticationFailed;
2630 if (authenticated)
2631 return OK;
2633 AuthenticationFailed:
2634 if (!(dir_config->authenticator_options & FCGI_AUTHORITATIVE))
2635 return DECLINED;
2637 /* @@@ Probably should support custom_responses */
2638 ap_note_basic_auth_failure(r);
2639 ap_log_rerror(FCGI_LOG_ERR_NOERRNO, r,
2640 "FastCGI: authentication failed for user \"%s\": %s",
2641 #ifdef APACHE2
2642 r->user, r->uri);
2643 #else
2644 r->connection->user, r->uri);
2645 #endif
2647 return (res == OK) ? HTTP_UNAUTHORIZED : res;
2650 static int check_user_authorization(request_rec *r)
2652 int res, authorized = 0;
2653 fcgi_request *fr;
2654 const fcgi_dir_config * const dir_config =
2655 (const fcgi_dir_config *)ap_get_module_config(r->per_dir_config, &fastcgi_module);
2657 if (dir_config->authorizer == NULL)
2658 return DECLINED;
2660 /* @@@ We should probably honor the existing parameters to the require directive
2661 * as well as allow the definition of new ones (or use the basename of the
2662 * FastCGI server and pass the rest of the directive line), but for now keep
2663 * it simple. */
2665 if ((fr = create_fcgi_request(r, dir_config->authorizer)) == NULL)
2666 return HTTP_INTERNAL_SERVER_ERROR;
2668 /* Save the existing subprocess_env, because we're gonna muddy it up */
2669 fr->saved_subprocess_env = ap_copy_table(r->pool, r->subprocess_env);
2671 ap_table_setn(r->subprocess_env, "FCGI_APACHE_ROLE", "AUTHORIZER");
2673 fr->role = FCGI_AUTHORIZER;
2675 /* Do we need compatibility mode? */
2676 fr->auth_compat = (dir_config->authorizer_options & FCGI_COMPAT);
2678 if ((res = do_work(r, fr)) != OK)
2679 goto AuthorizationFailed;
2681 authorized = (r->status == 200);
2682 post_process_auth(fr, authorized);
2684 /* A redirect shouldn't be allowed during the authorization phase */
2685 if (ap_table_get(r->headers_out, "Location") != NULL) {
2686 ap_log_rerror(FCGI_LOG_ERR_NOERRNO, r,
2687 "FastCGI: FastCgiAuthorizer \"%s\" redirected (not allowed)",
2688 dir_config->authorizer);
2689 goto AuthorizationFailed;
2692 if (authorized)
2693 return OK;
2695 AuthorizationFailed:
2696 if (!(dir_config->authorizer_options & FCGI_AUTHORITATIVE))
2697 return DECLINED;
2699 /* @@@ Probably should support custom_responses */
2700 ap_note_basic_auth_failure(r);
2701 ap_log_rerror(FCGI_LOG_ERR_NOERRNO, r,
2702 "FastCGI: authorization failed for user \"%s\": %s",
2703 #ifdef APACHE2
2704 r->user, r->uri);
2705 #else
2706 r->connection->user, r->uri);
2707 #endif
2709 return (res == OK) ? HTTP_UNAUTHORIZED : res;
2712 static int check_access(request_rec *r)
2714 int res, access_allowed = 0;
2715 fcgi_request *fr;
2716 const fcgi_dir_config * const dir_config =
2717 (fcgi_dir_config *)ap_get_module_config(r->per_dir_config, &fastcgi_module);
2719 if (dir_config == NULL || dir_config->access_checker == NULL)
2720 return DECLINED;
2722 if ((fr = create_fcgi_request(r, dir_config->access_checker)) == NULL)
2723 return HTTP_INTERNAL_SERVER_ERROR;
2725 /* Save the existing subprocess_env, because we're gonna muddy it up */
2726 fr->saved_subprocess_env = ap_copy_table(r->pool, r->subprocess_env);
2728 ap_table_setn(r->subprocess_env, "FCGI_APACHE_ROLE", "ACCESS_CHECKER");
2730 /* The FastCGI Protocol doesn't differentiate access control */
2731 fr->role = FCGI_AUTHORIZER;
2733 /* Do we need compatibility mode? */
2734 fr->auth_compat = (dir_config->access_checker_options & FCGI_COMPAT);
2736 if ((res = do_work(r, fr)) != OK)
2737 goto AccessFailed;
2739 access_allowed = (r->status == 200);
2740 post_process_auth(fr, access_allowed);
2742 /* A redirect shouldn't be allowed during the access check phase */
2743 if (ap_table_get(r->headers_out, "Location") != NULL) {
2744 ap_log_rerror(FCGI_LOG_ERR_NOERRNO, r,
2745 "FastCGI: FastCgiAccessChecker \"%s\" redirected (not allowed)",
2746 dir_config->access_checker);
2747 goto AccessFailed;
2750 if (access_allowed)
2751 return OK;
2753 AccessFailed:
2754 if (!(dir_config->access_checker_options & FCGI_AUTHORITATIVE))
2755 return DECLINED;
2757 /* @@@ Probably should support custom_responses */
2758 ap_log_rerror(FCGI_LOG_ERR_NOERRNO, r, "FastCGI: access denied: %s", r->uri);
2759 return (res == OK) ? HTTP_FORBIDDEN : res;
2762 static int
2763 fixups(request_rec * r)
2765 if (fcgi_util_fs_get_by_id(r->filename,
2766 fcgi_util_get_server_uid(r->server),
2767 fcgi_util_get_server_gid(r->server)))
2769 r->handler = FASTCGI_HANDLER_NAME;
2770 return OK;
2773 return DECLINED;
2776 #ifndef APACHE2
2778 # define AP_INIT_RAW_ARGS(directive, func, mconfig, where, help) \
2779 { directive, func, mconfig, where, RAW_ARGS, help }
2780 # define AP_INIT_TAKE1(directive, func, mconfig, where, help) \
2781 { directive, func, mconfig, where, TAKE1, help }
2782 # define AP_INIT_TAKE12(directive, func, mconfig, where, help) \
2783 { directive, func, mconfig, where, TAKE12, help }
2784 # define AP_INIT_FLAG(directive, func, mconfig, where, help) \
2785 { directive, func, mconfig, where, FLAG, help }
2787 #endif
2789 static const command_rec fastcgi_cmds[] =
2791 AP_INIT_RAW_ARGS("AppClass", fcgi_config_new_static_server, NULL, RSRC_CONF, NULL),
2792 AP_INIT_RAW_ARGS("FastCgiServer", fcgi_config_new_static_server, NULL, RSRC_CONF, NULL),
2794 AP_INIT_RAW_ARGS("ExternalAppClass", fcgi_config_new_external_server, NULL, RSRC_CONF, NULL),
2795 AP_INIT_RAW_ARGS("FastCgiExternalServer", fcgi_config_new_external_server, NULL, RSRC_CONF, NULL),
2797 AP_INIT_TAKE1("FastCgiIpcDir", fcgi_config_set_socket_dir, NULL, RSRC_CONF, NULL),
2799 AP_INIT_TAKE1("FastCgiSuexec", fcgi_config_set_wrapper, NULL, RSRC_CONF, NULL),
2800 AP_INIT_TAKE1("FastCgiWrapper", fcgi_config_set_wrapper, NULL, RSRC_CONF, NULL),
2802 AP_INIT_RAW_ARGS("FCGIConfig", fcgi_config_set_config, NULL, RSRC_CONF, NULL),
2803 AP_INIT_RAW_ARGS("FastCgiConfig", fcgi_config_set_config, NULL, RSRC_CONF, NULL),
2805 AP_INIT_TAKE12("FastCgiAuthenticator", fcgi_config_new_auth_server,
2806 (void *)FCGI_AUTH_TYPE_AUTHENTICATOR, ACCESS_CONF,
2807 "a fastcgi-script path (absolute or relative to ServerRoot) followed by an optional -compat"),
2808 AP_INIT_FLAG("FastCgiAuthenticatorAuthoritative", fcgi_config_set_authoritative_slot,
2809 (void *)XtOffsetOf(fcgi_dir_config, authenticator_options), ACCESS_CONF,
2810 "Set to 'off' to allow authentication to be passed along to lower modules upon failure"),
2812 AP_INIT_TAKE12("FastCgiAuthorizer", fcgi_config_new_auth_server,
2813 (void *)FCGI_AUTH_TYPE_AUTHORIZER, ACCESS_CONF,
2814 "a fastcgi-script path (absolute or relative to ServerRoot) followed by an optional -compat"),
2815 AP_INIT_FLAG("FastCgiAuthorizerAuthoritative", fcgi_config_set_authoritative_slot,
2816 (void *)XtOffsetOf(fcgi_dir_config, authorizer_options), ACCESS_CONF,
2817 "Set to 'off' to allow authorization to be passed along to lower modules upon failure"),
2819 AP_INIT_TAKE12("FastCgiAccessChecker", fcgi_config_new_auth_server,
2820 (void *)FCGI_AUTH_TYPE_ACCESS_CHECKER, ACCESS_CONF,
2821 "a fastcgi-script path (absolute or relative to ServerRoot) followed by an optional -compat"),
2822 AP_INIT_FLAG("FastCgiAccessCheckerAuthoritative", fcgi_config_set_authoritative_slot,
2823 (void *)XtOffsetOf(fcgi_dir_config, access_checker_options), ACCESS_CONF,
2824 "Set to 'off' to allow access control to be passed along to lower modules upon failure"),
2825 { NULL }
2828 #ifdef APACHE2
2830 static void register_hooks(apr_pool_t * p)
2832 // ap_hook_pre_config(x_pre_config, NULL, NULL, APR_HOOK_MIDDLE);
2833 ap_hook_post_config(init_module, NULL, NULL, APR_HOOK_MIDDLE);
2834 ap_hook_child_init(fcgi_child_init, NULL, NULL, APR_HOOK_MIDDLE);
2835 ap_hook_handler(content_handler, NULL, NULL, APR_HOOK_MIDDLE);
2836 ap_hook_check_user_id(check_user_authentication, NULL, NULL, APR_HOOK_MIDDLE);
2837 ap_hook_access_checker(check_access, NULL, NULL, APR_HOOK_MIDDLE);
2838 ap_hook_auth_checker(check_user_authorization, NULL, NULL, APR_HOOK_MIDDLE);
2839 ap_hook_fixups(fixups, NULL, NULL, APR_HOOK_MIDDLE);
2842 module AP_MODULE_DECLARE_DATA fastcgi_module =
2844 STANDARD20_MODULE_STUFF,
2845 fcgi_config_create_dir_config, /* per-directory config creator */
2846 NULL, /* dir config merger */
2847 NULL, /* server config creator */
2848 NULL, /* server config merger */
2849 fastcgi_cmds, /* command table */
2850 register_hooks, /* set up other request processing hooks */
2853 #else /* !APACHE2 */
2855 handler_rec fastcgi_handlers[] = {
2856 { FCGI_MAGIC_TYPE, content_handler },
2857 { FASTCGI_HANDLER_NAME, content_handler },
2858 { NULL }
2861 module MODULE_VAR_EXPORT fastcgi_module = {
2862 STANDARD_MODULE_STUFF,
2863 init_module, /* initializer */
2864 fcgi_config_create_dir_config, /* per-dir config creator */
2865 NULL, /* per-dir config merger (default: override) */
2866 NULL, /* per-server config creator */
2867 NULL, /* per-server config merger (default: override) */
2868 fastcgi_cmds, /* command table */
2869 fastcgi_handlers, /* [9] content handlers */
2870 NULL, /* [2] URI-to-filename translation */
2871 check_user_authentication, /* [5] authenticate user_id */
2872 check_user_authorization, /* [6] authorize user_id */
2873 check_access, /* [4] check access (based on src & http headers) */
2874 NULL, /* [7] check/set MIME type */
2875 fixups, /* [8] fixups */
2876 NULL, /* [10] logger */
2877 NULL, /* [3] header-parser */
2878 fcgi_child_init, /* process initialization */
2879 #ifdef WIN32
2880 fcgi_child_exit, /* process exit/cleanup */
2881 #else
2882 NULL,
2883 #endif
2884 NULL /* [1] post read-request handling */
2887 #endif /* !APACHE2 */