Add -user and -group options to FastCgiServer and FastCgiExternalServer.
[mod_fastcgi.git] / mod_fastcgi.c
blob2f9cb0a9ba2c76cfe7251eeb2cd61c53b835cd3a
1 /*
2 * mod_fastcgi.c --
4 * Apache server module for FastCGI.
6 * $Id: mod_fastcgi.c,v 1.139 2002/09/21 13:55:35 robs Exp $
8 * Copyright (c) 1995-1996 Open Market, Inc.
10 * See the file "LICENSE.TERMS" for information on usage and redistribution
11 * of this file, and for a DISCLAIMER OF ALL WARRANTIES.
14 * Patches for Apache-1.1 provided by
15 * Ralf S. Engelschall
16 * <rse@en.muc.de>
18 * Patches for Linux provided by
19 * Scott Langley
20 * <langles@vote-smart.org>
22 * Patches for suexec handling by
23 * Brian Grossman <brian@SoftHome.net> and
24 * Rob Saccoccio <robs@ipass.net>
28 * Module design notes.
30 * 1. Restart cleanup.
32 * mod_fastcgi spawns several processes: one process manager process
33 * and several application processes. None of these processes
34 * handle SIGHUP, so they just go away when the Web server performs
35 * a restart (as Apache does every time it starts.)
37 * In order to allow the process manager to properly cleanup the
38 * running fastcgi processes (without being disturbed by Apache),
39 * an intermediate process was introduced. The diagram is as follows;
41 * ApacheWS --> MiddleProc --> ProcMgr --> FCGI processes
43 * On a restart, ApacheWS sends a SIGKILL to MiddleProc and then
44 * collects it via waitpid(). The ProcMgr periodically checks for
45 * its parent (via getppid()) and if it does not have one, as in
46 * case when MiddleProc has terminated, ProcMgr issues a SIGTERM
47 * to all FCGI processes, waitpid()s on them and then exits, so it
48 * can be collected by init(1). Doing it any other way (short of
49 * changing Apache API), results either in inconsistent results or
50 * in generation of zombie processes.
52 * XXX: How does Apache 1.2 implement "gentle" restart
53 * that does not disrupt current connections? How does
54 * gentle restart interact with restart cleanup?
56 * 2. Request timeouts.
58 * Earlier versions of this module used ap_soft_timeout() rather than
59 * ap_hard_timeout() and ate FastCGI server output until it completed.
60 * This precluded the FastCGI server from having to implement a
61 * SIGPIPE handler, but meant hanging the application longer than
62 * necessary. SIGPIPE handler now must be installed in ALL FastCGI
63 * applications. The handler should abort further processing and go
64 * back into the accept() loop.
66 * Although using ap_soft_timeout() is better than ap_hard_timeout()
67 * we have to be more careful about SIGINT handling and subsequent
68 * processing, so, for now, make it hard.
72 #include "fcgi.h"
74 #ifndef timersub
75 #define timersub(a, b, result) \
76 do { \
77 (result)->tv_sec = (a)->tv_sec - (b)->tv_sec; \
78 (result)->tv_usec = (a)->tv_usec - (b)->tv_usec; \
79 if ((result)->tv_usec < 0) { \
80 --(result)->tv_sec; \
81 (result)->tv_usec += 1000000; \
82 } \
83 } while (0)
84 #endif
87 * Global variables
90 pool *fcgi_config_pool; /* the config pool */
91 server_rec *fcgi_apache_main_server;
93 const char *fcgi_wrapper = NULL; /* wrapper path */
94 uid_t fcgi_user_id; /* the run uid of Apache & PM */
95 gid_t fcgi_group_id; /* the run gid of Apache & PM */
97 fcgi_server *fcgi_servers = NULL; /* AppClasses */
99 char *fcgi_socket_dir = DEFAULT_SOCK_DIR; /* default FastCgiIpcDir */
101 char *fcgi_dynamic_dir = NULL; /* directory for the dynamic
102 * fastcgi apps' sockets */
104 #ifdef WIN32
106 #pragma warning( disable : 4706 4100 4127)
107 fcgi_pm_job *fcgi_dynamic_mbox = NULL;
108 HANDLE *fcgi_dynamic_mbox_mutex = NULL;
109 HANDLE fcgi_pm_thread = INVALID_HANDLE_VALUE;
111 #else
113 int fcgi_pm_pipe[2] = { -1, -1 };
114 pid_t fcgi_pm_pid = -1;
116 #endif
118 char *fcgi_empty_env = NULL;
120 u_int dynamicMaxProcs = FCGI_DEFAULT_MAX_PROCS;
121 int dynamicMinProcs = FCGI_DEFAULT_MIN_PROCS;
122 int dynamicMaxClassProcs = FCGI_DEFAULT_MAX_CLASS_PROCS;
123 u_int dynamicKillInterval = FCGI_DEFAULT_KILL_INTERVAL;
124 u_int dynamicUpdateInterval = FCGI_DEFAULT_UPDATE_INTERVAL;
125 float dynamicGain = FCGI_DEFAULT_GAIN;
126 int dynamicThreshold1 = FCGI_DEFAULT_THRESHOLD_1;
127 int dynamicThresholdN = FCGI_DEFAULT_THRESHOLD_N;
128 u_int dynamicPleaseStartDelay = FCGI_DEFAULT_START_PROCESS_DELAY;
129 u_int dynamicAppConnectTimeout = FCGI_DEFAULT_APP_CONN_TIMEOUT;
130 char **dynamicEnvp = &fcgi_empty_env;
131 u_int dynamicProcessSlack = FCGI_DEFAULT_PROCESS_SLACK;
132 int dynamicAutoRestart = FCGI_DEFAULT_RESTART_DYNAMIC;
133 int dynamicAutoUpdate = FCGI_DEFAULT_AUTOUPDATE;
134 int dynamicFlush = FCGI_FLUSH;
135 u_int dynamicListenQueueDepth = FCGI_DEFAULT_LISTEN_Q;
136 u_int dynamicInitStartDelay = DEFAULT_INIT_START_DELAY;
137 u_int dynamicRestartDelay = FCGI_DEFAULT_RESTART_DELAY;
138 array_header *dynamic_pass_headers = NULL;
139 u_int dynamic_idle_timeout = FCGI_DEFAULT_IDLE_TIMEOUT;
141 /*******************************************************************************
142 * Construct a message and write it to the pm_pipe.
144 static void send_to_pm(const char id, const char * const fs_path,
145 const char *user, const char * const group, const unsigned long q_usec,
146 const unsigned long req_usec)
148 #ifdef WIN32
149 fcgi_pm_job *job = NULL;
151 if (!(job = (fcgi_pm_job *) malloc(sizeof(fcgi_pm_job))))
152 return;
153 #else
154 static int failed_count = 0;
155 int buflen = 0;
156 char buf[FCGI_MAX_MSG_LEN];
157 #endif
159 if (strlen(fs_path) > FCGI_MAXPATH) {
160 ap_log_error(FCGI_LOG_ERR_NOERRNO, fcgi_apache_main_server,
161 "FastCGI: the path \"%s\" is too long (>%d) for a dynamic server", fs_path, FCGI_MAXPATH);
162 return;
165 switch(id) {
167 case FCGI_SERVER_START_JOB:
168 case FCGI_SERVER_RESTART_JOB:
169 #ifdef WIN32
170 job->id = id;
171 job->fs_path = strdup(fs_path);
172 job->user = strdup(user);
173 job->group = strdup(group);
174 job->qsec = 0L;
175 job->start_time = 0L;
176 #else
177 buflen = sprintf(buf, "%c %s %s %s*", id, fs_path, user, group);
178 #endif
179 break;
181 case FCGI_REQUEST_TIMEOUT_JOB:
182 #ifdef WIN32
183 job->id = id;
184 job->fs_path = strdup(fs_path);
185 job->user = strdup(user);
186 job->group = strdup(group);
187 job->qsec = 0L;
188 job->start_time = 0L;
189 #else
190 buflen = sprintf(buf, "%c %s %s %s*", id, fs_path, user, group);
191 #endif
192 break;
194 case FCGI_REQUEST_COMPLETE_JOB:
195 #ifdef WIN32
196 job->id = id;
197 job->fs_path = strdup(fs_path);
198 job->qsec = q_usec;
199 job->start_time = req_usec;
200 job->user = strdup(user);
201 job->group = strdup(group);
202 #else
203 buflen = sprintf(buf, "%c %s %s %s %lu %lu*", id, fs_path, user, group, q_usec, req_usec);
204 #endif
205 break;
208 #ifdef WIN32
209 if (fcgi_pm_add_job(job)) return;
211 SetEvent(fcgi_event_handles[MBOX_EVENT]);
212 #else
213 ap_assert(buflen <= FCGI_MAX_MSG_LEN);
215 /* There is no apache flag or function that can be used to id
216 * restart/shutdown pending so ignore the first few failures as
217 * once it breaks it will stay broke */
218 if (write(fcgi_pm_pipe[1], (const void *)buf, buflen) != buflen
219 && failed_count++ > 10)
221 ap_log_error(FCGI_LOG_WARN, fcgi_apache_main_server,
222 "FastCGI: write() to PM failed (ignore if a restart or shutdown is pending)");
224 #endif
228 *----------------------------------------------------------------------
230 * init_module
232 * An Apache module initializer, called by the Apache core
233 * after reading the server config.
235 * Start the process manager no matter what, since there may be a
236 * request for dynamic FastCGI applications without any being
237 * configured as static applications. Also, check for the existence
238 * and create if necessary a subdirectory into which all dynamic
239 * sockets will go.
241 *----------------------------------------------------------------------
243 #ifdef APACHE2
244 static apcb_t init_module(apr_pool_t * p, apr_pool_t * plog,
245 apr_pool_t * tp, server_rec * s)
246 #else
247 static apcb_t init_module(server_rec *s, pool *p)
248 #endif
250 const char *err;
252 /* Register to reset to default values when the config pool is cleaned */
253 ap_block_alarms();
254 ap_register_cleanup(p, NULL, fcgi_config_reset_globals, ap_null_cleanup);
255 ap_unblock_alarms();
257 #ifdef APACHE2
258 ap_add_version_component(p, "mod_fastcgi/" MOD_FASTCGI_VERSION);
259 #else
260 ap_add_version_component("mod_fastcgi/" MOD_FASTCGI_VERSION);
261 #endif
263 fcgi_config_set_fcgi_uid_n_gid(1);
265 /* keep these handy */
266 fcgi_config_pool = p;
267 fcgi_apache_main_server = s;
269 #ifndef WIN32
270 /* Create Unix/Domain socket directory */
271 if ((err = fcgi_config_make_dir(p, fcgi_socket_dir)))
272 ap_log_error(FCGI_LOG_ERR, s, "FastCGI: %s", err);
273 #endif
275 /* Create Dynamic directory */
276 if ((err = fcgi_config_make_dynamic_dir(p, 1)))
277 ap_log_error(FCGI_LOG_ERR, s, "FastCGI: %s", err);
279 #ifndef WIN32
280 /* Spawn the PM only once. Under Unix, Apache calls init() routines
281 * twice, once before detach() and once after. Win32 doesn't detach.
282 * Under DSO, DSO modules are unloaded between the two init() calls.
283 * Under Unix, the -X switch causes two calls to init() but no detach
284 * (but all subprocesses are wacked so the PM is toasted anyway)! */
286 #ifndef APACHE2
287 if (ap_standalone && ap_restart_time == 0)
288 return;
289 #endif
291 /* Create the pipe for comm with the PM */
292 if (pipe(fcgi_pm_pipe) < 0) {
293 ap_log_error(FCGI_LOG_ERR, s, "FastCGI: pipe() failed");
296 /* Start the Process Manager */
298 #ifdef APACHE2
300 apr_proc_t * proc = apr_palloc(p, sizeof(*proc));
301 apr_status_t rv;
303 rv = apr_proc_fork(proc, tp);
305 if (rv == APR_INCHILD)
307 /* child */
308 fcgi_pm_main(NULL);
309 exit(1);
311 else if (rv != APR_INPARENT)
313 return rv;
316 /* parent */
318 apr_pool_note_subprocess(p, proc, APR_KILL_ONLY_ONCE);
320 #else /* !APACHE2 */
322 fcgi_pm_pid = ap_spawn_child(p, fcgi_pm_main, NULL, kill_only_once, NULL, NULL, NULL);
323 if (fcgi_pm_pid <= 0) {
324 ap_log_error(FCGI_LOG_ALERT, s,
325 "FastCGI: can't start the process manager, spawn_child() failed");
328 #endif /* !APACHE2 */
330 close(fcgi_pm_pipe[0]);
332 #endif /* !WIN32 */
334 return APCB_OK;
337 #ifdef APACHE2
338 static apcb_t fcgi_child_exit(void * dc)
339 #else
340 static apcb_t fcgi_child_exit(server_rec *dc0, pool *dc1)
341 #endif
343 #ifdef WIN32
344 /* Signal the PM thread to exit*/
345 SetEvent(fcgi_event_handles[TERM_EVENT]);
347 /* Waiting on pm thread to exit */
348 WaitForSingleObject(fcgi_pm_thread, INFINITE);
349 #endif
351 return APCB_OK;
354 #ifdef APACHE2
355 static void fcgi_child_init(apr_pool_t * p, server_rec * dc)
356 #else
357 static void fcgi_child_init(server_rec *dc, pool *p)
358 #endif
360 #ifdef WIN32
361 /* Create the MBOX, TERM, and WAKE event handlers */
362 fcgi_event_handles[0] = CreateEvent(NULL, FALSE, FALSE, NULL);
363 if (fcgi_event_handles[0] == NULL) {
364 ap_log_error(FCGI_LOG_ALERT, fcgi_apache_main_server,
365 "FastCGI: CreateEvent() failed");
367 fcgi_event_handles[1] = CreateEvent(NULL, FALSE, FALSE, NULL);
368 if (fcgi_event_handles[1] == NULL) {
369 ap_log_error(FCGI_LOG_ALERT, fcgi_apache_main_server,
370 "FastCGI: CreateEvent() failed");
372 fcgi_event_handles[2] = CreateEvent(NULL, FALSE, FALSE, NULL);
373 if (fcgi_event_handles[2] == NULL) {
374 ap_log_error(FCGI_LOG_ALERT, fcgi_apache_main_server,
375 "FastCGI: CreateEvent() failed");
378 /* Create the mbox mutex (PM - request threads) */
379 fcgi_dynamic_mbox_mutex = CreateMutex(NULL, FALSE, NULL);
380 if (fcgi_dynamic_mbox_mutex == NULL) {
381 ap_log_error(FCGI_LOG_ALERT, fcgi_apache_main_server,
382 "FastCGI: CreateMutex() failed");
385 /* Spawn of the process manager thread */
386 fcgi_pm_thread = (HANDLE) _beginthread(fcgi_pm_main, 0, NULL);
387 if (fcgi_pm_thread == (HANDLE) -1) {
388 ap_log_error(FCGI_LOG_ALERT, fcgi_apache_main_server,
389 "_beginthread() failed to spawn the process manager");
392 #ifdef APACHE2
393 apr_pool_cleanup_register(p, NULL, fcgi_child_exit, fcgi_child_exit);
394 #endif
395 #endif
399 *----------------------------------------------------------------------
401 * get_header_line --
403 * Terminate a line: scan to the next newline, scan back to the
404 * first non-space character and store a terminating zero. Return
405 * the next character past the end of the newline.
407 * If the end of the string is reached, ASSERT!
409 * If the FIRST character(s) in the line are '\n' or "\r\n", the
410 * first character is replaced with a NULL and next character
411 * past the newline is returned. NOTE: this condition supercedes
412 * the processing of RFC-822 continuation lines.
414 * If continuation is set to 'TRUE', then it parses a (possible)
415 * sequence of RFC-822 continuation lines.
417 * Results:
418 * As above.
420 * Side effects:
421 * Termination byte stored in string.
423 *----------------------------------------------------------------------
425 static char *get_header_line(char *start, int continuation)
427 char *p = start;
428 char *end = start;
430 if(p[0] == '\r' && p[1] == '\n') { /* If EOL in 1st 2 chars */
431 p++; /* point to \n and stop */
432 } else if(*p != '\n') {
433 if(continuation) {
434 while(*p != '\0') {
435 if(*p == '\n' && p[1] != ' ' && p[1] != '\t')
436 break;
437 p++;
439 } else {
440 while(*p != '\0' && *p != '\n') {
441 p++;
446 ap_assert(*p != '\0');
447 end = p;
448 end++;
451 * Trim any trailing whitespace.
453 while(isspace((unsigned char)p[-1]) && p > start) {
454 p--;
457 *p = '\0';
458 return end;
461 #ifdef WIN32
463 static int set_nonblocking(const fcgi_request * fr, int nonblocking)
465 if (fr->using_npipe_io)
467 if (nonblocking)
469 DWORD mode = PIPE_NOWAIT | PIPE_READMODE_BYTE;
470 if (SetNamedPipeHandleState((HANDLE) fr->fd, &mode, NULL, NULL) == 0)
472 ap_log_rerror(FCGI_LOG_ERR, fr->r,
473 "FastCGI: SetNamedPipeHandleState() failed");
474 return -1;
478 else
480 unsigned long ioctl_arg = (nonblocking) ? 1 : 0;
481 if (ioctlsocket(fr->fd, FIONBIO, &ioctl_arg) != 0)
483 errno = WSAGetLastError();
484 ap_log_rerror(FCGI_LOG_ERR_ERRNO, fr->r,
485 "FastCGI: ioctlsocket() failed");
486 return -1;
490 return 0;
493 #else
495 static int set_nonblocking(const fcgi_request * fr, int nonblocking)
497 int nb_flag = 0;
498 int fd_flags = fcntl(fr->fd, F_GETFL, 0);
500 if (fd_flags < 0) return -1;
502 #if defined(O_NONBLOCK)
503 nb_flag = O_NONBLOCK;
504 #elif defined(O_NDELAY)
505 nb_flag = O_NDELAY;
506 #elif defined(FNDELAY)
507 nb_flag = FNDELAY;
508 #else
509 #error "TODO - don't read from app until all data from client is posted."
510 #endif
512 fd_flags = (nonblocking) ? (fd_flags | nb_flag) : (fd_flags & ~nb_flag);
514 return fcntl(fr->fd, F_SETFL, fd_flags);
517 #endif
519 /*******************************************************************************
520 * Close the connection to the FastCGI server. This is normally called by
521 * do_work(), but may also be called as in request pool cleanup.
523 static void close_connection_to_fs(fcgi_request *fr)
525 #ifdef WIN32
527 if (fr->fd != INVALID_SOCKET)
529 set_nonblocking(fr, FALSE);
531 if (fr->using_npipe_io)
533 CloseHandle((HANDLE) fr->fd);
535 else
537 /* abort the connection entirely */
538 struct linger linger = {0, 0};
539 setsockopt(fr->fd, SOL_SOCKET, SO_LINGER, (void *) &linger, sizeof(linger));
540 closesocket(fr->fd);
543 fr->fd = INVALID_SOCKET;
545 #else /* ! WIN32 */
547 if (fr->fd >= 0)
549 struct linger linger = {0, 0};
550 set_nonblocking(fr, FALSE);
551 /* abort the connection entirely */
552 setsockopt(fr->fd, SOL_SOCKET, SO_LINGER, &linger, sizeof(linger));
553 close(fr->fd);
554 fr->fd = -1;
556 #endif /* ! WIN32 */
558 if (fr->dynamic && fr->keepReadingFromFcgiApp == FALSE)
560 /* XXX FCGI_REQUEST_COMPLETE_JOB is only sent for requests which complete
561 * normally WRT the fcgi app. There is no data sent for
562 * connect() timeouts or requests which complete abnormally.
563 * KillDynamicProcs() and RemoveRecords() need to be looked at
564 * to be sure they can reasonably handle these cases before
565 * sending these sort of stats - theres some funk in there.
567 if (fcgi_util_ticks(&fr->completeTime) < 0)
569 /* there's no point to aborting the request, just log it */
570 ap_log_error(FCGI_LOG_ERR, fr->r->server, "FastCGI: can't get time of day");
578 *----------------------------------------------------------------------
580 * process_headers --
582 * Call with r->parseHeader == SCAN_CGI_READING_HEADERS
583 * and initial script output in fr->header.
585 * If the initial script output does not include the header
586 * terminator ("\r\n\r\n") process_headers returns with no side
587 * effects, to be called again when more script output
588 * has been appended to fr->header.
590 * If the initial script output includes the header terminator,
591 * process_headers parses the headers and determines whether or
592 * not the remaining script output will be sent to the client.
593 * If so, process_headers sends the HTTP response headers to the
594 * client and copies any non-header script output to the output
595 * buffer reqOutbuf.
597 * Results:
598 * none.
600 * Side effects:
601 * May set r->parseHeader to:
602 * SCAN_CGI_FINISHED -- headers parsed, returning script response
603 * SCAN_CGI_BAD_HEADER -- malformed header from script
604 * SCAN_CGI_INT_REDIRECT -- handler should perform internal redirect
605 * SCAN_CGI_SRV_REDIRECT -- handler should return REDIRECT
607 *----------------------------------------------------------------------
610 static const char *process_headers(request_rec *r, fcgi_request *fr)
612 char *p, *next, *name, *value;
613 int len, flag;
614 int hasContentType, hasStatus, hasLocation;
616 ap_assert(fr->parseHeader == SCAN_CGI_READING_HEADERS);
618 if (fr->header == NULL)
619 return NULL;
622 * Do we have the entire header? Scan for the blank line that
623 * terminates the header.
625 p = (char *)fr->header->elts;
626 len = fr->header->nelts;
627 flag = 0;
628 while(len-- && flag < 2) {
629 switch(*p) {
630 case '\r':
631 break;
632 case '\n':
633 flag++;
634 break;
635 case '\0':
636 case '\v':
637 case '\f':
638 name = "Invalid Character";
639 goto BadHeader;
640 break;
641 default:
642 flag = 0;
643 break;
645 p++;
648 /* Return (to be called later when we have more data)
649 * if we don't have an entire header. */
650 if (flag < 2)
651 return NULL;
654 * Parse all the headers.
656 fr->parseHeader = SCAN_CGI_FINISHED;
657 hasContentType = hasStatus = hasLocation = FALSE;
658 next = (char *)fr->header->elts;
659 for(;;) {
660 next = get_header_line(name = next, TRUE);
661 if (*name == '\0') {
662 break;
664 if ((p = strchr(name, ':')) == NULL) {
665 goto BadHeader;
667 value = p + 1;
668 while (p != name && isspace((unsigned char)*(p - 1))) {
669 p--;
671 if (p == name) {
672 goto BadHeader;
674 *p = '\0';
675 if (strpbrk(name, " \t") != NULL) {
676 *p = ' ';
677 goto BadHeader;
679 while (isspace((unsigned char)*value)) {
680 value++;
683 if (strcasecmp(name, "Status") == 0) {
684 int statusValue = strtol(value, NULL, 10);
686 if (hasStatus) {
687 goto DuplicateNotAllowed;
689 if (statusValue < 0) {
690 fr->parseHeader = SCAN_CGI_BAD_HEADER;
691 return ap_psprintf(r->pool, "invalid Status '%s'", value);
693 hasStatus = TRUE;
694 r->status = statusValue;
695 r->status_line = ap_pstrdup(r->pool, value);
696 continue;
699 if (fr->role == FCGI_RESPONDER) {
700 if (strcasecmp(name, "Content-type") == 0) {
701 if (hasContentType) {
702 goto DuplicateNotAllowed;
704 hasContentType = TRUE;
705 r->content_type = ap_pstrdup(r->pool, value);
706 continue;
709 if (strcasecmp(name, "Location") == 0) {
710 if (hasLocation) {
711 goto DuplicateNotAllowed;
713 hasLocation = TRUE;
714 ap_table_set(r->headers_out, "Location", value);
715 continue;
718 /* If the script wants them merged, it can do it */
719 ap_table_add(r->err_headers_out, name, value);
720 continue;
722 else {
723 ap_table_add(fr->authHeaders, name, value);
727 if (fr->role != FCGI_RESPONDER)
728 return NULL;
731 * Who responds, this handler or Apache?
733 if (hasLocation) {
734 const char *location = ap_table_get(r->headers_out, "Location");
736 * Based on internal redirect handling in mod_cgi.c...
738 * If a script wants to produce its own Redirect
739 * body, it now has to explicitly *say* "Status: 302"
741 if (r->status == 200) {
742 if(location[0] == '/') {
744 * Location is an relative path. This handler will
745 * consume all script output, then have Apache perform an
746 * internal redirect.
748 fr->parseHeader = SCAN_CGI_INT_REDIRECT;
749 return NULL;
750 } else {
752 * Location is an absolute URL. If the script didn't
753 * produce a Content-type header, this handler will
754 * consume all script output and then have Apache generate
755 * its standard redirect response. Otherwise this handler
756 * will transmit the script's response.
758 fr->parseHeader = SCAN_CGI_SRV_REDIRECT;
759 return NULL;
764 * We're responding. Send headers, buffer excess script output.
766 ap_send_http_header(r);
768 /* We need to reinstate our timeout, send_http_header() kill()s it */
769 ap_hard_timeout("FastCGI request processing", r);
771 if (r->header_only) {
772 /* we've got all we want from the server */
773 close_connection_to_fs(fr);
774 fr->exitStatusSet = 1;
775 fcgi_buf_reset(fr->clientOutputBuffer);
776 fcgi_buf_reset(fr->serverOutputBuffer);
777 return NULL;
780 len = fr->header->nelts - (next - fr->header->elts);
781 ap_assert(len >= 0);
782 ap_assert(BufferLength(fr->clientOutputBuffer) == 0);
783 if (BufferFree(fr->clientOutputBuffer) < len) {
784 fr->clientOutputBuffer = fcgi_buf_new(r->pool, len);
786 ap_assert(BufferFree(fr->clientOutputBuffer) >= len);
787 if (len > 0) {
788 int sent = fcgi_buf_add_block(fr->clientOutputBuffer, next, len);
789 ap_assert(sent == len);
791 return NULL;
793 BadHeader:
794 /* Log first line of a multi-line header */
795 if ((p = strpbrk(name, "\r\n")) != NULL)
796 *p = '\0';
797 fr->parseHeader = SCAN_CGI_BAD_HEADER;
798 return ap_psprintf(r->pool, "malformed header '%s'", name);
800 DuplicateNotAllowed:
801 fr->parseHeader = SCAN_CGI_BAD_HEADER;
802 return ap_psprintf(r->pool, "duplicate header '%s'", name);
806 * Read from the client filling both the FastCGI server buffer and the
807 * client buffer with the hopes of buffering the client data before
808 * making the connect() to the FastCGI server. This prevents slow
809 * clients from keeping the FastCGI server in processing longer than is
810 * necessary.
812 static int read_from_client_n_queue(fcgi_request *fr)
814 char *end;
815 int count;
816 long int countRead;
818 while (BufferFree(fr->clientInputBuffer) > 0 || BufferFree(fr->serverOutputBuffer) > 0) {
819 fcgi_protocol_queue_client_buffer(fr);
821 if (fr->expectingClientContent <= 0)
822 return OK;
824 fcgi_buf_get_free_block_info(fr->clientInputBuffer, &end, &count);
825 if (count == 0)
826 return OK;
828 if ((countRead = ap_get_client_block(fr->r, end, count)) < 0)
829 return -1;
831 if (countRead == 0) {
832 fr->expectingClientContent = 0;
834 else {
835 fcgi_buf_add_update(fr->clientInputBuffer, countRead);
836 ap_reset_timeout(fr->r);
839 return OK;
842 static int write_to_client(fcgi_request *fr)
844 char *begin;
845 int count;
846 int rv;
847 #ifdef APACHE2
848 apr_bucket * bkt;
849 apr_bucket_brigade * bde;
850 apr_bucket_alloc_t * const bkt_alloc = fr->r->connection->bucket_alloc;
851 #endif
853 fcgi_buf_get_block_info(fr->clientOutputBuffer, &begin, &count);
854 if (count == 0)
855 return OK;
857 /* If fewer than count bytes are written, an error occured.
858 * ap_bwrite() typically forces a flushed write to the client, this
859 * effectively results in a block (and short packets) - it should
860 * be fixed, but I didn't win much support for the idea on new-httpd.
861 * So, without patching Apache, the best way to deal with this is
862 * to size the fcgi_bufs to hold all of the script output (within
863 * reason) so the script can be released from having to wait around
864 * for the transmission to the client to complete. */
866 #ifdef APACHE2
868 bde = apr_brigade_create(fr->r->pool, bkt_alloc);
869 bkt = apr_bucket_transient_create(begin, count, bkt_alloc);
870 APR_BRIGADE_INSERT_TAIL(bde, bkt);
872 if (fr->fs ? fr->fs->flush : dynamicFlush)
874 bkt = apr_bucket_flush_create(bkt_alloc);
875 APR_BRIGADE_INSERT_TAIL(bde, bkt);
878 rv = ap_pass_brigade(fr->r->output_filters, bde);
880 #elif defined(RUSSIAN_APACHE)
882 rv = (ap_rwrite(begin, count, fr->r) != count);
884 #else
886 rv = (ap_bwrite(fr->r->connection->client, begin, count) != count);
888 #endif
890 if (rv)
892 ap_log_rerror(FCGI_LOG_INFO_NOERRNO, fr->r,
893 "FastCGI: client stopped connection before send body completed");
894 return -1;
897 #ifndef APACHE2
899 ap_reset_timeout(fr->r);
901 /* Don't bother with a wrapped buffer, limiting exposure to slow
902 * clients. The BUFF routines don't allow a writev from above,
903 * and don't always memcpy to minimize small write()s, this should
904 * be fixed, but I didn't win much support for the idea on
905 * new-httpd - I'll have to _prove_ its a problem first.. */
907 /* The default behaviour used to be to flush with every write, but this
908 * can tie up the FastCGI server longer than is necessary so its an option now */
910 if (fr->fs ? fr->fs->flush : dynamicFlush)
912 #ifdef RUSSIAN_APACHE
913 rv = ap_rflush(fr->r);
914 #else
915 rv = ap_bflush(fr->r->connection->client);
916 #endif
918 if (rv)
920 ap_log_rerror(FCGI_LOG_INFO_NOERRNO, fr->r,
921 "FastCGI: client stopped connection before send body completed");
922 return -1;
925 ap_reset_timeout(fr->r);
928 #endif /* !APACHE2 */
930 fcgi_buf_toss(fr->clientOutputBuffer, count);
931 return OK;
934 /*******************************************************************************
935 * Determine the user and group the wrapper should be called with.
936 * Based on code in Apache's create_argv_cmd() (util_script.c).
938 static void set_uid_n_gid(request_rec *r, const char **user, const char **group)
940 if (fcgi_wrapper == NULL) {
941 *user = "-";
942 *group = "-";
943 return;
946 if (strncmp("/~", r->uri, 2) == 0) {
947 /* its a user dir uri, just send the ~user, and leave it to the PM */
948 char *end = strchr(r->uri + 2, '/');
950 if (end)
951 *user = memcpy(ap_pcalloc(r->pool, end - r->uri), r->uri + 1, end - r->uri - 1);
952 else
953 *user = ap_pstrdup(r->pool, r->uri + 1);
954 *group = "-";
956 else {
957 *user = ap_psprintf(r->pool, "%ld", (long) fcgi_util_get_server_uid(r->server));
958 *group = ap_psprintf(r->pool, "%ld", (long) fcgi_util_get_server_gid(r->server));
962 static void send_request_complete(fcgi_request *fr)
964 if (fr->completeTime.tv_sec)
966 struct timeval qtime, rtime;
968 timersub(&fr->queueTime, &fr->startTime, &qtime);
969 timersub(&fr->completeTime, &fr->queueTime, &rtime);
971 send_to_pm(FCGI_REQUEST_COMPLETE_JOB, fr->fs_path,
972 fr->user, fr->group,
973 qtime.tv_sec * 1000000 + qtime.tv_usec,
974 rtime.tv_sec * 1000000 + rtime.tv_usec);
979 /*******************************************************************************
980 * Connect to the FastCGI server.
982 static int open_connection_to_fs(fcgi_request *fr)
984 struct timeval tval;
985 fd_set write_fds, read_fds;
986 int status;
987 request_rec * const r = fr->r;
988 pool * const rp = r->pool;
989 const char *socket_path = NULL;
990 struct sockaddr *socket_addr = NULL;
991 int socket_addr_len = 0;
992 #ifndef WIN32
993 const char *err = NULL;
994 #endif
996 /* Create the connection point */
997 if (fr->dynamic)
999 socket_path = fcgi_util_socket_hash_filename(rp, fr->fs_path, fr->user, fr->group);
1000 socket_path = fcgi_util_socket_make_path_absolute(rp, socket_path, 1);
1002 #ifndef WIN32
1003 err = fcgi_util_socket_make_domain_addr(rp, (struct sockaddr_un **)&socket_addr,
1004 &socket_addr_len, socket_path);
1005 if (err) {
1006 ap_log_rerror(FCGI_LOG_ERR, r,
1007 "FastCGI: failed to connect to server \"%s\": "
1008 "%s", fr->fs_path, err);
1009 return FCGI_FAILED;
1011 #endif
1013 else
1015 #ifdef WIN32
1016 if (fr->fs->dest_addr != NULL) {
1017 socket_addr = fr->fs->dest_addr;
1019 else if (fr->fs->socket_addr) {
1020 socket_addr = fr->fs->socket_addr;
1022 else {
1023 socket_path = fr->fs->socket_path;
1025 #else
1026 socket_addr = fr->fs->socket_addr;
1027 #endif
1028 socket_addr_len = fr->fs->socket_addr_len;
1031 if (fr->dynamic)
1033 #ifdef WIN32
1034 if (fr->fs && fr->fs->restartTime)
1035 #else
1036 struct stat sock_stat;
1038 if (stat(socket_path, &sock_stat) == 0)
1039 #endif
1041 // It exists
1042 if (dynamicAutoUpdate)
1044 struct stat app_stat;
1046 /* TODO: follow sym links */
1048 if (stat(fr->fs_path, &app_stat) == 0)
1050 #ifdef WIN32
1051 if (fr->fs->startTime < app_stat.st_mtime)
1052 #else
1053 if (sock_stat.st_mtime < app_stat.st_mtime)
1054 #endif
1056 #ifndef WIN32
1057 struct timeval tv = {1, 0};
1058 #endif
1060 * There's a newer one, request a restart.
1062 send_to_pm(FCGI_SERVER_RESTART_JOB, fr->fs_path, fr->user, fr->group, 0, 0);
1064 #ifdef WIN32
1065 Sleep(1000);
1066 #else
1067 /* Avoid sleep/alarm interactions */
1068 ap_select(0, NULL, NULL, NULL, &tv);
1069 #endif
1074 else
1076 send_to_pm(FCGI_SERVER_START_JOB, fr->fs_path, fr->user, fr->group, 0, 0);
1078 /* Wait until it looks like its running */
1080 for (;;)
1082 #ifdef WIN32
1083 Sleep(1000);
1085 fr->fs = fcgi_util_fs_get_by_id(fr->fs_path, 0, 0);
1087 if (fr->fs && fr->fs->restartTime)
1088 #else
1089 struct timeval tv = {1, 0};
1091 /* Avoid sleep/alarm interactions */
1092 ap_select(0, NULL, NULL, NULL, &tv);
1094 if (stat(socket_path, &sock_stat) == 0)
1095 #endif
1097 break;
1103 #ifdef WIN32
1104 if (socket_path)
1106 BOOL ready;
1107 DWORD connect_time;
1108 int rv;
1109 HANDLE wait_npipe_mutex;
1110 DWORD interval;
1111 DWORD max_connect_time = FCGI_NAMED_PIPE_CONNECT_TIMEOUT;
1113 fr->using_npipe_io = TRUE;
1115 if (fr->dynamic)
1117 interval = dynamicPleaseStartDelay * 1000;
1119 if (dynamicAppConnectTimeout) {
1120 max_connect_time = dynamicAppConnectTimeout;
1123 else
1125 interval = FCGI_NAMED_PIPE_CONNECT_TIMEOUT * 1000;
1127 if (fr->fs->appConnectTimeout) {
1128 max_connect_time = fr->fs->appConnectTimeout;
1132 fcgi_util_ticks(&fr->startTime);
1135 // xxx this handle should live somewhere (see CloseHandle()s below too)
1136 char * wait_npipe_mutex_name, * cp;
1137 wait_npipe_mutex_name = cp = ap_pstrdup(rp, socket_path);
1138 while ((cp = strchr(cp, '\\'))) *cp = '/';
1140 wait_npipe_mutex = CreateMutex(NULL, FALSE, wait_npipe_mutex_name);
1143 if (wait_npipe_mutex == NULL)
1145 ap_log_rerror(FCGI_LOG_ERR, r,
1146 "FastCGI: failed to connect to server \"%s\": "
1147 "can't create the WaitNamedPipe mutex", fr->fs_path);
1148 return FCGI_FAILED;
1151 SetLastError(ERROR_SUCCESS);
1153 rv = WaitForSingleObject(wait_npipe_mutex, max_connect_time * 1000);
1155 if (rv == WAIT_TIMEOUT || rv == WAIT_FAILED)
1157 if (fr->dynamic)
1159 send_to_pm(FCGI_REQUEST_TIMEOUT_JOB, fr->fs_path, fr->user, fr->group, 0, 0);
1161 ap_log_rerror(FCGI_LOG_ERR_NOERRNO, r,
1162 "FastCGI: failed to connect to server \"%s\": "
1163 "wait for a npipe instance failed", fr->fs_path);
1164 FCGIDBG3("interval=%d, max_connect_time=%d", interval, max_connect_time);
1165 CloseHandle(wait_npipe_mutex);
1166 return FCGI_FAILED;
1169 fcgi_util_ticks(&fr->queueTime);
1171 connect_time = fr->queueTime.tv_sec - fr->startTime.tv_sec;
1173 if (fr->dynamic)
1175 if (connect_time >= interval)
1177 send_to_pm(FCGI_REQUEST_TIMEOUT_JOB, fr->fs_path, fr->user, fr->group, 0, 0);
1178 FCGIDBG4("connect_time=%d, interval=%d, max_connect_time=%d", connect_time, interval, max_connect_time);
1180 if (max_connect_time - connect_time < interval)
1182 interval = max_connect_time - connect_time;
1185 else
1187 interval -= connect_time * 1000;
1190 for (;;)
1192 ready = WaitNamedPipe(socket_path, interval);
1194 if (ready)
1196 fr->fd = (SOCKET) CreateFile(socket_path,
1197 GENERIC_READ | GENERIC_WRITE,
1198 FILE_SHARE_READ | FILE_SHARE_WRITE,
1199 NULL, // no security attributes
1200 OPEN_EXISTING, // opens existing pipe
1201 FILE_FLAG_OVERLAPPED,
1202 NULL); // no template file
1204 if (fr->fd != (SOCKET) INVALID_HANDLE_VALUE)
1206 ReleaseMutex(wait_npipe_mutex);
1207 CloseHandle(wait_npipe_mutex);
1208 fcgi_util_ticks(&fr->queueTime);
1209 FCGIDBG2("got npipe connect: %s", fr->fs_path);
1210 return FCGI_OK;
1213 if (GetLastError() != ERROR_PIPE_BUSY
1214 && GetLastError() != ERROR_FILE_NOT_FOUND)
1216 ap_log_rerror(FCGI_LOG_ERR, r,
1217 "FastCGI: failed to connect to server \"%s\": "
1218 "CreateFile() failed", fr->fs_path);
1219 break;
1222 FCGIDBG2("missed npipe connect: %s", fr->fs_path);
1225 if (fr->dynamic)
1227 send_to_pm(FCGI_REQUEST_TIMEOUT_JOB, fr->fs_path, fr->user, fr->group, 0, 0);
1230 fcgi_util_ticks(&fr->queueTime);
1232 connect_time = fr->queueTime.tv_sec - fr->startTime.tv_sec;
1234 FCGIDBG5("interval=%d, max_connect_time=%d, connect_time=%d, ready=%d", interval, max_connect_time, connect_time, ready);
1236 if (connect_time >= max_connect_time)
1238 ap_log_rerror(FCGI_LOG_ERR, r,
1239 "FastCGI: failed to connect to server \"%s\": "
1240 "CreateFile()/WaitNamedPipe() timed out", fr->fs_path);
1241 break;
1245 ReleaseMutex(wait_npipe_mutex);
1246 CloseHandle(wait_npipe_mutex);
1247 fr->fd = INVALID_SOCKET;
1248 return FCGI_FAILED;
1251 #endif
1253 /* Create the socket */
1254 fr->fd = socket(socket_addr->sa_family, SOCK_STREAM, 0);
1256 #ifdef WIN32
1257 if (fr->fd == INVALID_SOCKET) {
1258 errno = WSAGetLastError(); // Not sure this is going to work as expected
1259 #else
1260 if (fr->fd < 0) {
1261 #endif
1262 ap_log_rerror(FCGI_LOG_ERR_ERRNO, r,
1263 "FastCGI: failed to connect to server \"%s\": "
1264 "socket() failed", fr->fs_path);
1265 return FCGI_FAILED;
1268 #ifndef WIN32
1269 if (fr->fd >= FD_SETSIZE) {
1270 ap_log_rerror(FCGI_LOG_ERR, r,
1271 "FastCGI: failed to connect to server \"%s\": "
1272 "socket file descriptor (%u) is larger than "
1273 "FD_SETSIZE (%u), you probably need to rebuild Apache with a "
1274 "larger FD_SETSIZE", fr->fs_path, fr->fd, FD_SETSIZE);
1275 return FCGI_FAILED;
1277 #endif
1279 /* If appConnectTimeout is non-zero, setup do a non-blocking connect */
1280 if ((fr->dynamic && dynamicAppConnectTimeout) || (!fr->dynamic && fr->fs->appConnectTimeout)) {
1281 set_nonblocking(fr, TRUE);
1284 if (fr->dynamic) {
1285 fcgi_util_ticks(&fr->startTime);
1288 /* Connect */
1289 if (connect(fr->fd, (struct sockaddr *)socket_addr, socket_addr_len) == 0)
1290 goto ConnectionComplete;
1292 #ifdef WIN32
1294 errno = WSAGetLastError();
1295 if (errno != WSAEWOULDBLOCK) {
1296 ap_log_rerror(FCGI_LOG_ERR_ERRNO, r,
1297 "FastCGI: failed to connect to server \"%s\": "
1298 "connect() failed", fr->fs_path);
1299 return FCGI_FAILED;
1302 #else
1304 /* ECONNREFUSED means the listen queue is full (or there isn't one).
1305 * With dynamic I can at least make sure the PM knows this is occuring */
1306 if (fr->dynamic && errno == ECONNREFUSED) {
1307 /* @@@ This might be better as some other "kind" of message */
1308 send_to_pm(FCGI_REQUEST_TIMEOUT_JOB, fr->fs_path, fr->user, fr->group, 0, 0);
1310 errno = ECONNREFUSED;
1313 if (errno != EINPROGRESS) {
1314 ap_log_rerror(FCGI_LOG_ERR, r,
1315 "FastCGI: failed to connect to server \"%s\": "
1316 "connect() failed", fr->fs_path);
1317 return FCGI_FAILED;
1320 #endif
1322 /* The connect() is non-blocking */
1324 errno = 0;
1326 if (fr->dynamic) {
1327 do {
1328 FD_ZERO(&write_fds);
1329 FD_SET(fr->fd, &write_fds);
1330 read_fds = write_fds;
1331 tval.tv_sec = dynamicPleaseStartDelay;
1332 tval.tv_usec = 0;
1334 status = ap_select((fr->fd+1), &read_fds, &write_fds, NULL, &tval);
1335 if (status < 0)
1336 break;
1338 fcgi_util_ticks(&fr->queueTime);
1340 if (status > 0)
1341 break;
1343 /* select() timed out */
1344 send_to_pm(FCGI_REQUEST_TIMEOUT_JOB, fr->fs_path, fr->user, fr->group, 0, 0);
1345 } while ((fr->queueTime.tv_sec - fr->startTime.tv_sec) < (int)dynamicAppConnectTimeout);
1347 /* XXX These can be moved down when dynamic vars live is a struct */
1348 if (status == 0) {
1349 ap_log_rerror(FCGI_LOG_ERR_NOERRNO, r,
1350 "FastCGI: failed to connect to server \"%s\": "
1351 "connect() timed out (appConnTimeout=%dsec)",
1352 fr->fs_path, dynamicAppConnectTimeout);
1353 return FCGI_FAILED;
1355 } /* dynamic */
1356 else {
1357 tval.tv_sec = fr->fs->appConnectTimeout;
1358 tval.tv_usec = 0;
1359 FD_ZERO(&write_fds);
1360 FD_SET(fr->fd, &write_fds);
1361 read_fds = write_fds;
1363 status = ap_select((fr->fd+1), &read_fds, &write_fds, NULL, &tval);
1365 if (status == 0) {
1366 ap_log_rerror(FCGI_LOG_ERR_NOERRNO, r,
1367 "FastCGI: failed to connect to server \"%s\": "
1368 "connect() timed out (appConnTimeout=%dsec)",
1369 fr->fs_path, dynamicAppConnectTimeout);
1370 return FCGI_FAILED;
1372 } /* !dynamic */
1374 if (status < 0) {
1375 #ifdef WIN32
1376 errno = WSAGetLastError();
1377 #endif
1378 ap_log_rerror(FCGI_LOG_ERR_ERRNO, r,
1379 "FastCGI: failed to connect to server \"%s\": "
1380 "select() failed", fr->fs_path);
1381 return FCGI_FAILED;
1384 if (FD_ISSET(fr->fd, &write_fds) || FD_ISSET(fr->fd, &read_fds)) {
1385 int error = 0;
1386 NET_SIZE_T len = sizeof(error);
1388 if (getsockopt(fr->fd, SOL_SOCKET, SO_ERROR, (char *)&error, &len) < 0) {
1389 /* Solaris pending error */
1390 #ifdef WIN32
1391 errno = WSAGetLastError();
1392 #endif
1393 ap_log_rerror(FCGI_LOG_ERR_ERRNO, r,
1394 "FastCGI: failed to connect to server \"%s\": "
1395 "select() failed (Solaris pending error)", fr->fs_path);
1396 return FCGI_FAILED;
1399 if (error != 0) {
1400 /* Berkeley-derived pending error */
1401 errno = error;
1402 ap_log_rerror(FCGI_LOG_ERR_ERRNO, r,
1403 "FastCGI: failed to connect to server \"%s\": "
1404 "select() failed (pending error)", fr->fs_path);
1405 return FCGI_FAILED;
1408 else {
1409 #ifdef WIN32
1410 errno = WSAGetLastError();
1411 #endif
1412 ap_log_rerror(FCGI_LOG_ERR_ERRNO, r,
1413 "FastCGI: failed to connect to server \"%s\": "
1414 "select() error - THIS CAN'T HAPPEN!", fr->fs_path);
1415 return FCGI_FAILED;
1418 ConnectionComplete:
1419 /* Return to blocking mode if it was set up */
1420 if ((fr->dynamic && dynamicAppConnectTimeout) || (!fr->dynamic && fr->fs->appConnectTimeout)) {
1421 set_nonblocking(fr, FALSE);
1424 #ifdef TCP_NODELAY
1425 if (socket_addr->sa_family == AF_INET) {
1426 /* We shouldn't be sending small packets and there's no application
1427 * level ack of the data we send, so disable Nagle */
1428 int set = 1;
1429 setsockopt(fr->fd, IPPROTO_TCP, TCP_NODELAY, (char *)&set, sizeof(set));
1431 #endif
1433 return FCGI_OK;
1436 static void sink_client_data(fcgi_request *fr)
1438 char *base;
1439 int size;
1441 fcgi_buf_reset(fr->clientInputBuffer);
1442 fcgi_buf_get_free_block_info(fr->clientInputBuffer, &base, &size);
1443 while (ap_get_client_block(fr->r, base, size) > 0);
1446 static apcb_t cleanup(void *data)
1448 fcgi_request * const fr = (fcgi_request *) data;
1450 if (fr == NULL) return APCB_OK;
1452 /* its more than likely already run, but... */
1453 close_connection_to_fs(fr);
1455 send_request_complete(fr);
1457 if (fr->fs_stderr_len) {
1458 ap_log_rerror(FCGI_LOG_ERR_NOERRNO, fr->r,
1459 "FastCGI: server \"%s\" stderr: %s", fr->fs_path, fr->fs_stderr);
1462 return APCB_OK;
1465 #ifdef WIN32
1466 static int npipe_io(fcgi_request * const fr)
1468 request_rec * const r = fr->r;
1469 enum
1471 STATE_ENV_SEND,
1472 STATE_CLIENT_RECV,
1473 STATE_SERVER_SEND,
1474 STATE_SERVER_RECV,
1475 STATE_CLIENT_SEND,
1476 STATE_CLIENT_ERROR,
1477 STATE_ERROR
1479 state = STATE_ENV_SEND;
1480 env_status env_status;
1481 int client_recv;
1482 int dynamic_first_recv = fr->dynamic;
1483 int idle_timeout = fr->dynamic ? dynamic_idle_timeout : fr->fs->idle_timeout;
1484 int send_pending = 0;
1485 int recv_pending = 0;
1486 int client_send = 0;
1487 int rv;
1488 OVERLAPPED rov = { 0 };
1489 OVERLAPPED sov = { 0 };
1490 HANDLE events[2];
1491 struct timeval timeout;
1492 struct timeval dynamic_last_io_time = {0, 0};
1493 int did_io = 1;
1494 pool * const rp = r->pool;
1496 DWORD recv_count = 0;
1498 if (fr->role == FCGI_RESPONDER)
1500 client_recv = (fr->expectingClientContent != 0);
1503 idle_timeout = fr->dynamic ? dynamic_idle_timeout : fr->fs->idle_timeout;
1505 env_status.envp = NULL;
1507 events[0] = CreateEvent(NULL, TRUE, FALSE, NULL);
1508 events[1] = CreateEvent(NULL, TRUE, FALSE, NULL);
1509 sov.hEvent = events[0];
1510 rov.hEvent = events[1];
1512 if (fr->dynamic)
1514 dynamic_last_io_time = fr->startTime;
1516 if (dynamicAppConnectTimeout)
1518 struct timeval qwait;
1519 timersub(&fr->queueTime, &fr->startTime, &qwait);
1520 dynamic_first_recv = qwait.tv_sec / dynamicPleaseStartDelay + 1;
1524 ap_hard_timeout("FastCGI request processing", r);
1526 while (state != STATE_CLIENT_SEND)
1528 DWORD msec_timeout;
1530 switch (state)
1532 case STATE_ENV_SEND:
1534 if (fcgi_protocol_queue_env(r, fr, &env_status) == 0)
1536 goto SERVER_SEND;
1539 state = STATE_CLIENT_RECV;
1541 /* fall through */
1543 case STATE_CLIENT_RECV:
1545 if (read_from_client_n_queue(fr) != OK)
1547 state = STATE_CLIENT_ERROR;
1548 break;
1551 if (fr->eofSent)
1553 state = STATE_SERVER_SEND;
1556 /* fall through */
1558 SERVER_SEND:
1560 case STATE_SERVER_SEND:
1562 if (! send_pending && BufferLength(fr->serverOutputBuffer))
1564 Buffer * b = fr->serverOutputBuffer;
1565 DWORD sent, len;
1567 len = min(b->length, b->data + b->size - b->begin);
1569 if (WriteFile((HANDLE) fr->fd, b->begin, len, &sent, &sov))
1571 fcgi_buf_removed(b, sent);
1572 ResetEvent(sov.hEvent);
1574 else if (GetLastError() == ERROR_IO_PENDING)
1576 send_pending = 1;
1578 else
1580 ap_log_rerror(FCGI_LOG_ERR, r, "FastCGI: comm with server "
1581 "\"%s\" aborted: WriteFile() failed", fr->fs_path);
1582 state = STATE_ERROR;
1583 break;
1587 /* fall through */
1589 case STATE_SERVER_RECV:
1592 * Only get more data when the serverInputBuffer is empty.
1593 * Otherwise we may already have the END_REQUEST buffered
1594 * (but not processed) and a read on a closed named pipe
1595 * results in an error that is normally abnormal.
1597 if (! recv_pending && BufferLength(fr->serverInputBuffer) == 0)
1599 Buffer * b = fr->serverInputBuffer;
1600 DWORD rcvd, len;
1602 len = min(b->size - b->length, b->data + b->size - b->end);
1604 if (ReadFile((HANDLE) fr->fd, b->end, len, &rcvd, &rov))
1606 fcgi_buf_added(b, rcvd);
1607 recv_count += rcvd;
1608 ResetEvent(rov.hEvent);
1609 if (dynamic_first_recv)
1611 dynamic_first_recv = 0;
1614 else if (GetLastError() == ERROR_IO_PENDING)
1616 recv_pending = 1;
1618 else if (GetLastError() == ERROR_HANDLE_EOF)
1620 fr->keepReadingFromFcgiApp = FALSE;
1621 state = STATE_CLIENT_SEND;
1622 ResetEvent(rov.hEvent);
1623 break;
1625 else if (GetLastError() == ERROR_NO_DATA)
1627 break;
1629 else
1631 ap_log_rerror(FCGI_LOG_ERR, r, "FastCGI: comm with server "
1632 "\"%s\" aborted: ReadFile() failed", fr->fs_path);
1633 state = STATE_ERROR;
1634 break;
1638 /* fall through */
1640 case STATE_CLIENT_SEND:
1642 if (client_send || ! BufferFree(fr->clientOutputBuffer))
1644 if (write_to_client(fr))
1646 state = STATE_CLIENT_ERROR;
1647 break;
1650 client_send = 0;
1653 break;
1655 default:
1657 ap_assert(0);
1660 if (state == STATE_CLIENT_ERROR || state == STATE_ERROR)
1662 break;
1665 /* setup the io timeout */
1667 if (BufferLength(fr->clientOutputBuffer))
1669 /* don't let client data sit too long, it might be a push */
1670 timeout.tv_sec = 0;
1671 timeout.tv_usec = 100000;
1673 else if (dynamic_first_recv)
1675 int delay;
1676 struct timeval qwait;
1678 fcgi_util_ticks(&fr->queueTime);
1680 if (did_io)
1682 /* a send() succeeded last pass */
1683 dynamic_last_io_time = fr->queueTime;
1685 else
1687 /* timed out last pass */
1688 struct timeval idle_time;
1690 timersub(&fr->queueTime, &dynamic_last_io_time, &idle_time);
1692 if (idle_time.tv_sec > idle_timeout)
1694 send_to_pm(FCGI_REQUEST_TIMEOUT_JOB, fr->fs_path, fr->user, fr->group, 0, 0);
1695 ap_log_rerror(FCGI_LOG_ERR_NOERRNO, r, "FastCGI: comm "
1696 "with (dynamic) server \"%s\" aborted: (first read) "
1697 "idle timeout (%d sec)", fr->fs_path, idle_timeout);
1698 state = STATE_ERROR;
1699 break;
1703 timersub(&fr->queueTime, &fr->startTime, &qwait);
1705 delay = dynamic_first_recv * dynamicPleaseStartDelay;
1707 if (qwait.tv_sec < delay)
1709 timeout.tv_sec = delay;
1710 timeout.tv_usec = 100000; /* fudge for select() slop */
1711 timersub(&timeout, &qwait, &timeout);
1713 else
1715 /* Killed time somewhere.. client read? */
1716 send_to_pm(FCGI_REQUEST_TIMEOUT_JOB, fr->fs_path, fr->user, fr->group, 0, 0);
1717 dynamic_first_recv = qwait.tv_sec / dynamicPleaseStartDelay + 1;
1718 timeout.tv_sec = dynamic_first_recv * dynamicPleaseStartDelay;
1719 timeout.tv_usec = 100000; /* fudge for select() slop */
1720 timersub(&timeout, &qwait, &timeout);
1723 else
1725 timeout.tv_sec = idle_timeout;
1726 timeout.tv_usec = 0;
1729 /* require a pended recv otherwise the app can deadlock */
1730 if (recv_pending)
1732 msec_timeout = timeout.tv_sec * 1000 + timeout.tv_usec / 1000;
1734 rv = WaitForMultipleObjects(2, events, FALSE, msec_timeout);
1736 if (rv == WAIT_TIMEOUT)
1738 did_io = 0;
1740 if (BufferLength(fr->clientOutputBuffer))
1742 client_send = 1;
1744 else if (dynamic_first_recv)
1746 struct timeval qwait;
1748 fcgi_util_ticks(&fr->queueTime);
1749 timersub(&fr->queueTime, &fr->startTime, &qwait);
1751 send_to_pm(FCGI_REQUEST_TIMEOUT_JOB, fr->fs_path, fr->user, fr->group, 0, 0);
1753 dynamic_first_recv = qwait.tv_sec / dynamicPleaseStartDelay + 1;
1755 else
1757 ap_log_rerror(FCGI_LOG_ERR_NOERRNO, r, "FastCGI: comm with "
1758 "server \"%s\" aborted: idle timeout (%d sec)",
1759 fr->fs_path, idle_timeout);
1760 state = STATE_ERROR;
1761 break;
1764 else
1766 int i = rv - WAIT_OBJECT_0;
1768 did_io = 1;
1770 if (i == 0)
1772 DWORD sent;
1774 if (GetOverlappedResult((HANDLE) fr->fd, &sov, &sent, FALSE))
1776 send_pending = 0;
1777 ResetEvent(sov.hEvent);
1778 fcgi_buf_removed(fr->serverOutputBuffer, sent);
1780 else
1782 ap_log_rerror(FCGI_LOG_ERR, r, "FastCGI: comm with server "
1783 "\"%s\" aborted: GetOverlappedResult() failed", fr->fs_path);
1784 state = STATE_ERROR;
1785 break;
1788 else
1790 DWORD rcvd;
1792 ap_assert(i == 1);
1794 recv_pending = 0;
1795 ResetEvent(rov.hEvent);
1797 if (GetOverlappedResult((HANDLE) fr->fd, &rov, &rcvd, FALSE))
1799 fcgi_buf_added(fr->serverInputBuffer, rcvd);
1800 if (dynamic_first_recv)
1802 dynamic_first_recv = 0;
1805 else
1807 ap_log_rerror(FCGI_LOG_ERR, r, "FastCGI: comm with server "
1808 "\"%s\" aborted: GetOverlappedResult() failed", fr->fs_path);
1809 state = STATE_ERROR;
1810 break;
1816 if (fcgi_protocol_dequeue(rp, fr))
1818 state = STATE_ERROR;
1819 break;
1822 if (fr->parseHeader == SCAN_CGI_READING_HEADERS)
1824 const char * err = process_headers(r, fr);
1825 if (err)
1827 ap_log_rerror(FCGI_LOG_ERR_NOERRNO, r,
1828 "FastCGI: comm with server \"%s\" aborted: "
1829 "error parsing headers: %s", fr->fs_path, err);
1830 state = STATE_ERROR;
1831 break;
1835 if (fr->exitStatusSet)
1837 fr->keepReadingFromFcgiApp = FALSE;
1838 state = STATE_CLIENT_SEND;
1839 break;
1843 if (! fr->exitStatusSet || ! fr->eofSent)
1845 CancelIo((HANDLE) fr->fd);
1848 CloseHandle(rov.hEvent);
1849 CloseHandle(sov.hEvent);
1851 return (state == STATE_ERROR);
1853 #endif /* WIN32 */
1855 static int socket_io(fcgi_request * const fr)
1857 enum
1859 STATE_SOCKET_NONE,
1860 STATE_ENV_SEND,
1861 STATE_CLIENT_RECV,
1862 STATE_SERVER_SEND,
1863 STATE_SERVER_RECV,
1864 STATE_CLIENT_SEND,
1865 STATE_ERROR,
1866 STATE_CLIENT_ERROR
1868 state = STATE_ENV_SEND;
1870 request_rec * const r = fr->r;
1872 struct timeval timeout;
1873 struct timeval dynamic_last_io_time = {0, 0};
1874 fd_set read_set;
1875 fd_set write_set;
1876 int nfds = fr->fd + 1;
1877 int select_status = 1;
1878 int idle_timeout;
1879 int rv;
1880 int dynamic_first_recv = fr->dynamic ? 1 : 0;
1881 int client_send = FALSE;
1882 int client_recv = FALSE;
1883 env_status env;
1884 pool *rp = r->pool;
1886 if (fr->role == FCGI_RESPONDER)
1888 client_recv = (fr->expectingClientContent != 0);
1891 idle_timeout = fr->dynamic ? dynamic_idle_timeout : fr->fs->idle_timeout;
1893 env.envp = NULL;
1895 if (fr->dynamic)
1897 dynamic_last_io_time = fr->startTime;
1899 if (dynamicAppConnectTimeout)
1901 struct timeval qwait;
1902 timersub(&fr->queueTime, &fr->startTime, &qwait);
1903 dynamic_first_recv = qwait.tv_sec / dynamicPleaseStartDelay + 1;
1907 ap_hard_timeout("FastCGI request processing", r);
1909 set_nonblocking(fr, TRUE);
1911 for (;;)
1913 FD_ZERO(&read_set);
1914 FD_ZERO(&write_set);
1916 switch (state)
1918 case STATE_ENV_SEND:
1920 if (fcgi_protocol_queue_env(r, fr, &env) == 0)
1922 goto SERVER_SEND;
1925 state = STATE_CLIENT_RECV;
1927 /* fall through */
1929 case STATE_CLIENT_RECV:
1931 if (read_from_client_n_queue(fr))
1933 state = STATE_CLIENT_ERROR;
1934 break;
1937 if (fr->eofSent)
1939 state = STATE_SERVER_SEND;
1942 /* fall through */
1944 SERVER_SEND:
1946 case STATE_SERVER_SEND:
1948 if (BufferLength(fr->serverOutputBuffer))
1950 FD_SET(fr->fd, &write_set);
1952 else
1954 ap_assert(fr->eofSent);
1955 state = STATE_SERVER_RECV;
1958 /* fall through */
1960 case STATE_SERVER_RECV:
1962 FD_SET(fr->fd, &read_set);
1964 /* fall through */
1966 case STATE_CLIENT_SEND:
1968 if (client_send || ! BufferFree(fr->clientOutputBuffer))
1970 if (write_to_client(fr))
1972 state = STATE_CLIENT_ERROR;
1973 break;
1976 client_send = 0;
1979 break;
1981 case STATE_ERROR:
1982 case STATE_CLIENT_ERROR:
1984 break;
1986 default:
1988 ap_assert(0);
1991 if (state == STATE_CLIENT_ERROR || state == STATE_ERROR)
1993 break;
1996 /* setup the io timeout */
1998 if (BufferLength(fr->clientOutputBuffer))
2000 /* don't let client data sit too long, it might be a push */
2001 timeout.tv_sec = 0;
2002 timeout.tv_usec = 100000;
2004 else if (dynamic_first_recv)
2006 int delay;
2007 struct timeval qwait;
2009 fcgi_util_ticks(&fr->queueTime);
2011 if (select_status)
2013 /* a send() succeeded last pass */
2014 dynamic_last_io_time = fr->queueTime;
2016 else
2018 /* timed out last pass */
2019 struct timeval idle_time;
2021 timersub(&fr->queueTime, &dynamic_last_io_time, &idle_time);
2023 if (idle_time.tv_sec > idle_timeout)
2025 send_to_pm(FCGI_REQUEST_TIMEOUT_JOB, fr->fs_path, fr->user, fr->group, 0, 0);
2026 ap_log_rerror(FCGI_LOG_ERR_NOERRNO, r, "FastCGI: comm "
2027 "with (dynamic) server \"%s\" aborted: (first read) "
2028 "idle timeout (%d sec)", fr->fs_path, idle_timeout);
2029 state = STATE_ERROR;
2030 break;
2034 timersub(&fr->queueTime, &fr->startTime, &qwait);
2036 delay = dynamic_first_recv * dynamicPleaseStartDelay;
2038 FCGIDBG5("qwait=%ld.%06ld delay=%d first_recv=%d", qwait.tv_sec, qwait.tv_usec, delay, dynamic_first_recv);
2040 if (qwait.tv_sec < delay)
2042 timeout.tv_sec = delay;
2043 timeout.tv_usec = 100000; /* fudge for select() slop */
2044 timersub(&timeout, &qwait, &timeout);
2046 else
2048 /* Killed time somewhere.. client read? */
2049 send_to_pm(FCGI_REQUEST_TIMEOUT_JOB, fr->fs_path, fr->user, fr->group, 0, 0);
2050 dynamic_first_recv = qwait.tv_sec / dynamicPleaseStartDelay + 1;
2051 timeout.tv_sec = dynamic_first_recv * dynamicPleaseStartDelay;
2052 timeout.tv_usec = 100000; /* fudge for select() slop */
2053 timersub(&timeout, &qwait, &timeout);
2056 else
2058 timeout.tv_sec = idle_timeout;
2059 timeout.tv_usec = 0;
2062 /* wait on the socket */
2063 select_status = ap_select(nfds, &read_set, &write_set, NULL, &timeout);
2065 if (select_status < 0)
2067 ap_log_rerror(FCGI_LOG_ERR_ERRNO, r, "FastCGI: comm with server "
2068 "\"%s\" aborted: select() failed", fr->fs_path);
2069 state = STATE_ERROR;
2070 break;
2073 if (select_status == 0)
2075 /* select() timeout */
2077 if (BufferLength(fr->clientOutputBuffer))
2079 if (fr->role == FCGI_RESPONDER)
2081 client_send = TRUE;
2084 else if (dynamic_first_recv)
2086 struct timeval qwait;
2088 fcgi_util_ticks(&fr->queueTime);
2089 timersub(&fr->queueTime, &fr->startTime, &qwait);
2091 send_to_pm(FCGI_REQUEST_TIMEOUT_JOB, fr->fs_path, fr->user, fr->group, 0, 0);
2093 dynamic_first_recv = qwait.tv_sec / dynamicPleaseStartDelay + 1;
2094 continue;
2096 else
2098 ap_log_rerror(FCGI_LOG_ERR_NOERRNO, r, "FastCGI: comm with "
2099 "server \"%s\" aborted: idle timeout (%d sec)",
2100 fr->fs_path, idle_timeout);
2101 state = STATE_ERROR;
2105 if (FD_ISSET(fr->fd, &write_set))
2107 /* send to the server */
2109 rv = fcgi_buf_socket_send(fr->serverOutputBuffer, fr->fd);
2111 if (rv < 0)
2113 ap_log_rerror(FCGI_LOG_ERR, r, "FastCGI: comm with server "
2114 "\"%s\" aborted: write failed", fr->fs_path);
2115 state = STATE_ERROR;
2116 break;
2120 if (FD_ISSET(fr->fd, &read_set))
2122 /* recv from the server */
2124 if (dynamic_first_recv)
2126 dynamic_first_recv = 0;
2127 fcgi_util_ticks(&fr->queueTime);
2130 rv = fcgi_buf_socket_recv(fr->serverInputBuffer, fr->fd);
2132 if (rv < 0)
2134 ap_log_rerror(FCGI_LOG_ERR, r, "FastCGI: comm with server "
2135 "\"%s\" aborted: read failed", fr->fs_path);
2136 state = STATE_ERROR;
2137 break;
2140 if (rv == 0)
2142 fr->keepReadingFromFcgiApp = FALSE;
2143 state = STATE_CLIENT_SEND;
2144 break;
2148 if (fcgi_protocol_dequeue(rp, fr))
2150 state = STATE_ERROR;
2151 break;
2154 if (fr->parseHeader == SCAN_CGI_READING_HEADERS)
2156 const char * err = process_headers(r, fr);
2157 if (err)
2159 ap_log_rerror(FCGI_LOG_ERR_NOERRNO, r,
2160 "FastCGI: comm with server \"%s\" aborted: "
2161 "error parsing headers: %s", fr->fs_path, err);
2162 state = STATE_ERROR;
2163 break;
2167 if (fr->exitStatusSet)
2169 fr->keepReadingFromFcgiApp = FALSE;
2170 state = STATE_CLIENT_SEND;
2171 break;
2175 return (state == STATE_ERROR);
2179 /*----------------------------------------------------------------------
2180 * This is the core routine for moving data between the FastCGI
2181 * application and the Web server's client.
2183 static int do_work(request_rec * const r, fcgi_request * const fr)
2185 int rv;
2186 pool *rp = r->pool;
2188 fcgi_protocol_queue_begin_request(fr);
2190 if (fr->role == FCGI_RESPONDER)
2192 rv = ap_setup_client_block(r, REQUEST_CHUNKED_ERROR);
2193 if (rv != OK)
2195 ap_kill_timeout(r);
2196 return rv;
2199 fr->expectingClientContent = ap_should_client_block(r);
2202 ap_block_alarms();
2203 ap_register_cleanup(rp, (void *)fr, cleanup, ap_null_cleanup);
2204 ap_unblock_alarms();
2206 ap_hard_timeout("connect() to FastCGI server", r);
2208 /* Connect to the FastCGI Application */
2209 if (open_connection_to_fs(fr) != FCGI_OK)
2211 ap_kill_timeout(r);
2212 return HTTP_INTERNAL_SERVER_ERROR;
2215 #ifdef WIN32
2216 if (fr->using_npipe_io)
2218 rv = npipe_io(fr);
2220 else
2221 #endif
2223 rv = socket_io(fr);
2226 /* comm with the server is done */
2227 close_connection_to_fs(fr);
2229 if (fr->role == FCGI_RESPONDER)
2231 sink_client_data(fr);
2234 while (rv == 0 && BufferLength(fr->serverInputBuffer) || BufferLength(fr->clientOutputBuffer))
2236 if (fcgi_protocol_dequeue(rp, fr))
2238 rv = HTTP_INTERNAL_SERVER_ERROR;
2241 if (fr->parseHeader == SCAN_CGI_READING_HEADERS)
2243 const char * err = process_headers(r, fr);
2244 if (err)
2246 ap_log_rerror(FCGI_LOG_ERR_NOERRNO, r,
2247 "FastCGI: comm with server \"%s\" aborted: "
2248 "error parsing headers: %s", fr->fs_path, err);
2249 rv = HTTP_INTERNAL_SERVER_ERROR;
2253 if (fr->role == FCGI_RESPONDER)
2255 if (write_to_client(fr))
2257 break;
2260 else
2262 fcgi_buf_reset(fr->clientOutputBuffer);
2266 switch (fr->parseHeader)
2268 case SCAN_CGI_FINISHED:
2270 if (fr->role == FCGI_RESPONDER)
2272 /* RUSSIAN_APACHE requires rflush() over bflush() */
2273 ap_rflush(r);
2274 #ifndef APACHE2
2275 ap_bgetopt(r->connection->client, BO_BYTECT, &r->bytes_sent);
2276 #endif
2279 /* fall through */
2281 case SCAN_CGI_INT_REDIRECT:
2282 case SCAN_CGI_SRV_REDIRECT:
2284 break;
2286 case SCAN_CGI_READING_HEADERS:
2288 ap_log_rerror(FCGI_LOG_ERR_NOERRNO, r, "FastCGI: incomplete headers "
2289 "(%d bytes) received from server \"%s\"", fr->header->nelts, fr->fs_path);
2291 /* fall through */
2293 case SCAN_CGI_BAD_HEADER:
2295 rv = HTTP_INTERNAL_SERVER_ERROR;
2296 break;
2298 default:
2300 ap_assert(0);
2301 rv = HTTP_INTERNAL_SERVER_ERROR;
2304 ap_kill_timeout(r);
2305 return rv;
2308 static fcgi_request *create_fcgi_request(request_rec * const r, const char *path)
2310 const char *fs_path;
2311 pool * const p = r->pool;
2312 fcgi_server *fs;
2313 fcgi_request * const fr = (fcgi_request *)ap_pcalloc(p, sizeof(fcgi_request));
2315 fs_path = path ? path : r->filename;
2317 fs = fcgi_util_fs_get_by_id(fs_path, fcgi_util_get_server_uid(r->server),
2318 fcgi_util_get_server_gid(r->server));
2319 if (fs == NULL)
2321 const char * err;
2322 struct stat *my_finfo;
2324 /* dynamic? */
2326 #ifndef APACHE2
2327 if (path == NULL)
2329 /* AP2: its bogus that we don't make use of r->finfo, but
2330 * its an apr_finfo_t and there is no apr_os_finfo_get() */
2332 my_finfo = &r->finfo;
2334 else
2335 #endif
2337 my_finfo = (struct stat *) ap_palloc(p, sizeof(struct stat));
2339 if (stat(fs_path, my_finfo) < 0)
2341 ap_log_rerror(FCGI_LOG_ERR_ERRNO, r,
2342 "FastCGI: stat() of \"%s\" failed", fs_path);
2343 return NULL;
2347 err = fcgi_util_fs_is_path_ok(p, fs_path, my_finfo);
2349 if (err)
2351 ap_log_rerror(FCGI_LOG_ERR_NOERRNO, r,
2352 "FastCGI: invalid (dynamic) server \"%s\": %s", fs_path, err);
2353 return NULL;
2357 fr->serverInputBuffer = fcgi_buf_new(p, SERVER_BUFSIZE);
2358 fr->serverOutputBuffer = fcgi_buf_new(p, SERVER_BUFSIZE);
2359 fr->clientInputBuffer = fcgi_buf_new(p, SERVER_BUFSIZE);
2360 fr->clientOutputBuffer = fcgi_buf_new(p, SERVER_BUFSIZE);
2361 fr->erBufPtr = fcgi_buf_new(p, sizeof(FCGI_EndRequestBody) + 1);
2362 fr->gotHeader = FALSE;
2363 fr->parseHeader = SCAN_CGI_READING_HEADERS;
2364 fr->header = ap_make_array(p, 1, 1);
2365 fr->fs_stderr = NULL;
2366 fr->r = r;
2367 fr->readingEndRequestBody = FALSE;
2368 fr->exitStatus = 0;
2369 fr->exitStatusSet = FALSE;
2370 fr->requestId = 1; /* anything but zero is OK here */
2371 fr->eofSent = FALSE;
2372 fr->role = FCGI_RESPONDER;
2373 fr->expectingClientContent = FALSE;
2374 fr->keepReadingFromFcgiApp = TRUE;
2375 fr->fs = fs;
2376 fr->fs_path = fs_path;
2377 fr->authHeaders = ap_make_table(p, 10);
2378 #ifdef WIN32
2379 fr->fd = INVALID_SOCKET;
2380 fr->dynamic = ((fs == NULL) || (fs->directive == APP_CLASS_DYNAMIC)) ? TRUE : FALSE;
2381 fr->using_npipe_io = FALSE;
2382 #else
2383 fr->dynamic = (fs == NULL) ? TRUE : FALSE;
2384 fr->fd = -1;
2385 #endif
2387 set_uid_n_gid(r, &fr->user, &fr->group);
2389 return fr;
2393 *----------------------------------------------------------------------
2395 * handler --
2397 * This routine gets called for a request that corresponds to
2398 * a FastCGI connection. It performs the request synchronously.
2400 * Results:
2401 * Final status of request: OK or NOT_FOUND or HTTP_INTERNAL_SERVER_ERROR.
2403 * Side effects:
2404 * Request performed.
2406 *----------------------------------------------------------------------
2409 /* Stolen from mod_cgi.c..
2410 * KLUDGE --- for back-combatibility, we don't have to check ExecCGI
2411 * in ScriptAliased directories, which means we need to know if this
2412 * request came through ScriptAlias or not... so the Alias module
2413 * leaves a note for us.
2415 static int apache_is_scriptaliased(request_rec *r)
2417 const char *t = ap_table_get(r->notes, "alias-forced-type");
2418 return t && (!strcasecmp(t, "cgi-script"));
2421 /* If a script wants to produce its own Redirect body, it now
2422 * has to explicitly *say* "Status: 302". If it wants to use
2423 * Apache redirects say "Status: 200". See process_headers().
2425 static int post_process_for_redirects(request_rec * const r,
2426 const fcgi_request * const fr)
2428 switch(fr->parseHeader) {
2429 case SCAN_CGI_INT_REDIRECT:
2431 /* @@@ There are still differences between the handling in
2432 * mod_cgi and mod_fastcgi. This needs to be revisited.
2434 /* We already read the message body (if any), so don't allow
2435 * the redirected request to think it has one. We can ignore
2436 * Transfer-Encoding, since we used REQUEST_CHUNKED_ERROR.
2438 r->method = "GET";
2439 r->method_number = M_GET;
2440 ap_table_unset(r->headers_in, "Content-length");
2442 ap_internal_redirect_handler(ap_table_get(r->headers_out, "Location"), r);
2443 return OK;
2445 case SCAN_CGI_SRV_REDIRECT:
2446 return HTTP_MOVED_TEMPORARILY;
2448 default:
2449 return OK;
2453 /******************************************************************************
2454 * Process fastcgi-script requests. Based on mod_cgi::cgi_handler().
2456 static int content_handler(request_rec *r)
2458 fcgi_request *fr = NULL;
2459 int ret;
2461 #ifdef APACHE2
2462 if (strcmp(r->handler, "fastcgi-script"))
2463 return DECLINED;
2464 #endif
2466 /* Setup a new FastCGI request */
2467 if ((fr = create_fcgi_request(r, NULL)) == NULL)
2468 return HTTP_INTERNAL_SERVER_ERROR;
2470 /* If its a dynamic invocation, make sure scripts are OK here */
2471 if (fr->dynamic && !(ap_allow_options(r) & OPT_EXECCGI) && !apache_is_scriptaliased(r)) {
2472 ap_log_rerror(FCGI_LOG_ERR_NOERRNO, r,
2473 "FastCGI: \"ExecCGI Option\" is off in this directory: %s", r->uri);
2474 return HTTP_INTERNAL_SERVER_ERROR;
2477 /* Process the fastcgi-script request */
2478 if ((ret = do_work(r, fr)) != OK)
2479 return ret;
2481 /* Special case redirects */
2482 ret = post_process_for_redirects(r, fr);
2484 return ret;
2488 static int post_process_auth_passed_header(table *t, const char *key, const char * const val)
2490 if (strncasecmp(key, "Variable-", 9) == 0)
2491 key += 9;
2493 ap_table_setn(t, key, val);
2494 return 1;
2497 static int post_process_auth_passed_compat_header(table *t, const char *key, const char * const val)
2499 if (strncasecmp(key, "Variable-", 9) == 0)
2500 ap_table_setn(t, key + 9, val);
2502 return 1;
2505 static int post_process_auth_failed_header(table * const t, const char * const key, const char * const val)
2507 ap_table_setn(t, key, val);
2508 return 1;
2511 static void post_process_auth(fcgi_request * const fr, const int passed)
2513 request_rec * const r = fr->r;
2515 /* Restore the saved subprocess_env because we muddied ours up */
2516 r->subprocess_env = fr->saved_subprocess_env;
2518 if (passed) {
2519 if (fr->auth_compat) {
2520 ap_table_do((int (*)(void *, const char *, const char *))post_process_auth_passed_compat_header,
2521 (void *)r->subprocess_env, fr->authHeaders, NULL);
2523 else {
2524 ap_table_do((int (*)(void *, const char *, const char *))post_process_auth_passed_header,
2525 (void *)r->subprocess_env, fr->authHeaders, NULL);
2528 else {
2529 ap_table_do((int (*)(void *, const char *, const char *))post_process_auth_failed_header,
2530 (void *)r->err_headers_out, fr->authHeaders, NULL);
2533 /* @@@ Restore these.. its a hack until I rewrite the header handling */
2534 r->status = HTTP_OK;
2535 r->status_line = NULL;
2538 static int check_user_authentication(request_rec *r)
2540 int res, authenticated = 0;
2541 const char *password;
2542 fcgi_request *fr;
2543 const fcgi_dir_config * const dir_config =
2544 (const fcgi_dir_config *)ap_get_module_config(r->per_dir_config, &fastcgi_module);
2546 if (dir_config->authenticator == NULL)
2547 return DECLINED;
2549 /* Get the user password */
2550 if ((res = ap_get_basic_auth_pw(r, &password)) != OK)
2551 return res;
2553 if ((fr = create_fcgi_request(r, dir_config->authenticator)) == NULL)
2554 return HTTP_INTERNAL_SERVER_ERROR;
2556 /* Save the existing subprocess_env, because we're gonna muddy it up */
2557 fr->saved_subprocess_env = ap_copy_table(r->pool, r->subprocess_env);
2559 ap_table_setn(r->subprocess_env, "REMOTE_PASSWD", password);
2560 ap_table_setn(r->subprocess_env, "FCGI_APACHE_ROLE", "AUTHENTICATOR");
2562 /* The FastCGI Protocol doesn't differentiate authentication */
2563 fr->role = FCGI_AUTHORIZER;
2565 /* Do we need compatibility mode? */
2566 fr->auth_compat = (dir_config->authenticator_options & FCGI_COMPAT);
2568 if ((res = do_work(r, fr)) != OK)
2569 goto AuthenticationFailed;
2571 authenticated = (r->status == 200);
2572 post_process_auth(fr, authenticated);
2574 /* A redirect shouldn't be allowed during the authentication phase */
2575 if (ap_table_get(r->headers_out, "Location") != NULL) {
2576 ap_log_rerror(FCGI_LOG_ERR_NOERRNO, r,
2577 "FastCGI: FastCgiAuthenticator \"%s\" redirected (not allowed)",
2578 dir_config->authenticator);
2579 goto AuthenticationFailed;
2582 if (authenticated)
2583 return OK;
2585 AuthenticationFailed:
2586 if (!(dir_config->authenticator_options & FCGI_AUTHORITATIVE))
2587 return DECLINED;
2589 /* @@@ Probably should support custom_responses */
2590 ap_note_basic_auth_failure(r);
2591 ap_log_rerror(FCGI_LOG_ERR_NOERRNO, r,
2592 "FastCGI: authentication failed for user \"%s\": %s",
2593 #ifdef APACHE2
2594 r->user, r->uri);
2595 #else
2596 r->connection->user, r->uri);
2597 #endif
2599 return (res == OK) ? HTTP_UNAUTHORIZED : res;
2602 static int check_user_authorization(request_rec *r)
2604 int res, authorized = 0;
2605 fcgi_request *fr;
2606 const fcgi_dir_config * const dir_config =
2607 (const fcgi_dir_config *)ap_get_module_config(r->per_dir_config, &fastcgi_module);
2609 if (dir_config->authorizer == NULL)
2610 return DECLINED;
2612 /* @@@ We should probably honor the existing parameters to the require directive
2613 * as well as allow the definition of new ones (or use the basename of the
2614 * FastCGI server and pass the rest of the directive line), but for now keep
2615 * it simple. */
2617 if ((fr = create_fcgi_request(r, dir_config->authorizer)) == NULL)
2618 return HTTP_INTERNAL_SERVER_ERROR;
2620 /* Save the existing subprocess_env, because we're gonna muddy it up */
2621 fr->saved_subprocess_env = ap_copy_table(r->pool, r->subprocess_env);
2623 ap_table_setn(r->subprocess_env, "FCGI_APACHE_ROLE", "AUTHORIZER");
2625 fr->role = FCGI_AUTHORIZER;
2627 /* Do we need compatibility mode? */
2628 fr->auth_compat = (dir_config->authorizer_options & FCGI_COMPAT);
2630 if ((res = do_work(r, fr)) != OK)
2631 goto AuthorizationFailed;
2633 authorized = (r->status == 200);
2634 post_process_auth(fr, authorized);
2636 /* A redirect shouldn't be allowed during the authorization phase */
2637 if (ap_table_get(r->headers_out, "Location") != NULL) {
2638 ap_log_rerror(FCGI_LOG_ERR_NOERRNO, r,
2639 "FastCGI: FastCgiAuthorizer \"%s\" redirected (not allowed)",
2640 dir_config->authorizer);
2641 goto AuthorizationFailed;
2644 if (authorized)
2645 return OK;
2647 AuthorizationFailed:
2648 if (!(dir_config->authorizer_options & FCGI_AUTHORITATIVE))
2649 return DECLINED;
2651 /* @@@ Probably should support custom_responses */
2652 ap_note_basic_auth_failure(r);
2653 ap_log_rerror(FCGI_LOG_ERR_NOERRNO, r,
2654 "FastCGI: authorization failed for user \"%s\": %s",
2655 #ifdef APACHE2
2656 r->user, r->uri);
2657 #else
2658 r->connection->user, r->uri);
2659 #endif
2661 return (res == OK) ? HTTP_UNAUTHORIZED : res;
2664 static int check_access(request_rec *r)
2666 int res, access_allowed = 0;
2667 fcgi_request *fr;
2668 const fcgi_dir_config * const dir_config =
2669 (fcgi_dir_config *)ap_get_module_config(r->per_dir_config, &fastcgi_module);
2671 if (dir_config == NULL || dir_config->access_checker == NULL)
2672 return DECLINED;
2674 if ((fr = create_fcgi_request(r, dir_config->access_checker)) == NULL)
2675 return HTTP_INTERNAL_SERVER_ERROR;
2677 /* Save the existing subprocess_env, because we're gonna muddy it up */
2678 fr->saved_subprocess_env = ap_copy_table(r->pool, r->subprocess_env);
2680 ap_table_setn(r->subprocess_env, "FCGI_APACHE_ROLE", "ACCESS_CHECKER");
2682 /* The FastCGI Protocol doesn't differentiate access control */
2683 fr->role = FCGI_AUTHORIZER;
2685 /* Do we need compatibility mode? */
2686 fr->auth_compat = (dir_config->access_checker_options & FCGI_COMPAT);
2688 if ((res = do_work(r, fr)) != OK)
2689 goto AccessFailed;
2691 access_allowed = (r->status == 200);
2692 post_process_auth(fr, access_allowed);
2694 /* A redirect shouldn't be allowed during the access check phase */
2695 if (ap_table_get(r->headers_out, "Location") != NULL) {
2696 ap_log_rerror(FCGI_LOG_ERR_NOERRNO, r,
2697 "FastCGI: FastCgiAccessChecker \"%s\" redirected (not allowed)",
2698 dir_config->access_checker);
2699 goto AccessFailed;
2702 if (access_allowed)
2703 return OK;
2705 AccessFailed:
2706 if (!(dir_config->access_checker_options & FCGI_AUTHORITATIVE))
2707 return DECLINED;
2709 /* @@@ Probably should support custom_responses */
2710 ap_log_rerror(FCGI_LOG_ERR_NOERRNO, r, "FastCGI: access denied: %s", r->uri);
2711 return (res == OK) ? HTTP_FORBIDDEN : res;
2714 #ifndef APACHE2
2716 # define AP_INIT_RAW_ARGS(directive, func, mconfig, where, help) \
2717 { directive, func, mconfig, where, RAW_ARGS, help }
2718 # define AP_INIT_TAKE1(directive, func, mconfig, where, help) \
2719 { directive, func, mconfig, where, TAKE1, help }
2720 # define AP_INIT_TAKE12(directive, func, mconfig, where, help) \
2721 { directive, func, mconfig, where, TAKE12, help }
2722 # define AP_INIT_FLAG(directive, func, mconfig, where, help) \
2723 { directive, func, mconfig, where, FLAG, help }
2725 #endif
2727 static const command_rec fastcgi_cmds[] =
2729 AP_INIT_RAW_ARGS("AppClass", fcgi_config_new_static_server, NULL, RSRC_CONF, NULL),
2730 AP_INIT_RAW_ARGS("FastCgiServer", fcgi_config_new_static_server, NULL, RSRC_CONF, NULL),
2732 AP_INIT_RAW_ARGS("ExternalAppClass", fcgi_config_new_external_server, NULL, RSRC_CONF, NULL),
2733 AP_INIT_RAW_ARGS("FastCgiExternalServer", fcgi_config_new_external_server, NULL, RSRC_CONF, NULL),
2735 AP_INIT_TAKE1("FastCgiIpcDir", fcgi_config_set_socket_dir, NULL, RSRC_CONF, NULL),
2737 AP_INIT_TAKE1("FastCgiSuexec", fcgi_config_set_wrapper, NULL, RSRC_CONF, NULL),
2738 AP_INIT_TAKE1("FastCgiWrapper", fcgi_config_set_wrapper, NULL, RSRC_CONF, NULL),
2740 AP_INIT_RAW_ARGS("FCGIConfig", fcgi_config_set_config, NULL, RSRC_CONF, NULL),
2741 AP_INIT_RAW_ARGS("FastCgiConfig", fcgi_config_set_config, NULL, RSRC_CONF, NULL),
2743 AP_INIT_TAKE12("FastCgiAuthenticator", fcgi_config_new_auth_server,
2744 (void *)FCGI_AUTH_TYPE_AUTHENTICATOR, ACCESS_CONF,
2745 "a fastcgi-script path (absolute or relative to ServerRoot) followed by an optional -compat"),
2746 AP_INIT_FLAG("FastCgiAuthenticatorAuthoritative", fcgi_config_set_authoritative_slot,
2747 (void *)XtOffsetOf(fcgi_dir_config, authenticator_options), ACCESS_CONF,
2748 "Set to 'off' to allow authentication to be passed along to lower modules upon failure"),
2750 AP_INIT_TAKE12("FastCgiAuthorizer", fcgi_config_new_auth_server,
2751 (void *)FCGI_AUTH_TYPE_AUTHORIZER, ACCESS_CONF,
2752 "a fastcgi-script path (absolute or relative to ServerRoot) followed by an optional -compat"),
2753 AP_INIT_FLAG("FastCgiAuthorizerAuthoritative", fcgi_config_set_authoritative_slot,
2754 (void *)XtOffsetOf(fcgi_dir_config, authorizer_options), ACCESS_CONF,
2755 "Set to 'off' to allow authorization to be passed along to lower modules upon failure"),
2757 AP_INIT_TAKE12("FastCgiAccessChecker", fcgi_config_new_auth_server,
2758 (void *)FCGI_AUTH_TYPE_ACCESS_CHECKER, ACCESS_CONF,
2759 "a fastcgi-script path (absolute or relative to ServerRoot) followed by an optional -compat"),
2760 AP_INIT_FLAG("FastCgiAccessCheckerAuthoritative", fcgi_config_set_authoritative_slot,
2761 (void *)XtOffsetOf(fcgi_dir_config, access_checker_options), ACCESS_CONF,
2762 "Set to 'off' to allow access control to be passed along to lower modules upon failure"),
2763 { NULL }
2766 #ifdef APACHE2
2768 static void register_hooks(apr_pool_t * p)
2770 // ap_hook_pre_config(x_pre_config, NULL, NULL, APR_HOOK_MIDDLE);
2771 ap_hook_post_config(init_module, NULL, NULL, APR_HOOK_MIDDLE);
2772 ap_hook_child_init(fcgi_child_init, NULL, NULL, APR_HOOK_MIDDLE);
2773 ap_hook_handler(content_handler, NULL, NULL, APR_HOOK_MIDDLE);
2774 ap_hook_check_user_id(check_user_authentication, NULL, NULL, APR_HOOK_MIDDLE);
2775 ap_hook_access_checker(check_access, NULL, NULL, APR_HOOK_MIDDLE);
2776 ap_hook_auth_checker(check_user_authorization, NULL, NULL, APR_HOOK_MIDDLE);
2779 module AP_MODULE_DECLARE_DATA fastcgi_module =
2781 STANDARD20_MODULE_STUFF,
2782 fcgi_config_create_dir_config, /* per-directory config creator */
2783 NULL, /* dir config merger */
2784 NULL, /* server config creator */
2785 NULL, /* server config merger */
2786 fastcgi_cmds, /* command table */
2787 register_hooks, /* set up other request processing hooks */
2790 #else /* !APACHE2 */
2792 handler_rec fastcgi_handlers[] = {
2793 { FCGI_MAGIC_TYPE, content_handler },
2794 { "fastcgi-script", content_handler },
2795 { NULL }
2798 module MODULE_VAR_EXPORT fastcgi_module = {
2799 STANDARD_MODULE_STUFF,
2800 init_module, /* initializer */
2801 fcgi_config_create_dir_config, /* per-dir config creator */
2802 NULL, /* per-dir config merger (default: override) */
2803 NULL, /* per-server config creator */
2804 NULL, /* per-server config merger (default: override) */
2805 fastcgi_cmds, /* command table */
2806 fastcgi_handlers, /* [9] content handlers */
2807 NULL, /* [2] URI-to-filename translation */
2808 check_user_authentication, /* [5] authenticate user_id */
2809 check_user_authorization, /* [6] authorize user_id */
2810 check_access, /* [4] check access (based on src & http headers) */
2811 NULL, /* [7] check/set MIME type */
2812 NULL, /* [8] fixups */
2813 NULL, /* [10] logger */
2814 NULL, /* [3] header-parser */
2815 fcgi_child_init, /* process initialization */
2816 fcgi_child_exit, /* process exit/cleanup */
2817 NULL /* [1] post read-request handling */
2820 #endif /* !APACHE2 */