*** empty log message ***
[mod_fastcgi.git] / mod_fastcgi.c
blobf39940788d9e2aee0d9c1d3727ce6e4fd86f8cd4
1 /*
2 * mod_fastcgi.c --
4 * Apache server module for FastCGI.
6 * $Id: mod_fastcgi.c,v 1.100 2000/10/17 01:58:16 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 int fcgi_pm_pipe[2];
102 pid_t fcgi_pm_pid = -1;
104 char *fcgi_dynamic_dir = NULL; /* directory for the dynamic
105 * fastcgi apps' sockets */
107 #ifdef WIN32
108 fcgi_pm_job *fcgi_dynamic_mbox = NULL;
109 HANDLE *fcgi_dynamic_mbox_mutex = NULL;
110 HANDLE fcgi_pm_thread = INVALID_HANDLE_VALUE;
111 #endif
113 char *fcgi_empty_env = NULL;
115 u_int dynamicMaxProcs = FCGI_DEFAULT_MAX_PROCS;
116 u_int dynamicMinProcs = FCGI_DEFAULT_MIN_PROCS;
117 u_int dynamicMaxClassProcs = FCGI_DEFAULT_MAX_CLASS_PROCS;
118 u_int dynamicKillInterval = FCGI_DEFAULT_KILL_INTERVAL;
119 u_int dynamicUpdateInterval = FCGI_DEFAULT_UPDATE_INTERVAL;
120 float dynamicGain = FCGI_DEFAULT_GAIN;
121 u_int dynamicThreshhold1 = FCGI_DEFAULT_THRESHHOLD_1;
122 u_int dynamicThreshholdN = FCGI_DEFAULT_THRESHHOLD_N;
123 u_int dynamicPleaseStartDelay = FCGI_DEFAULT_START_PROCESS_DELAY;
124 u_int dynamicAppConnectTimeout = FCGI_DEFAULT_APP_CONN_TIMEOUT;
125 char **dynamicEnvp = &fcgi_empty_env;
126 u_int dynamicProcessSlack = FCGI_DEFAULT_PROCESS_SLACK;
127 int dynamicAutoRestart = FCGI_DEFAULT_RESTART_DYNAMIC;
128 int dynamicAutoUpdate = FCGI_DEFAULT_AUTOUPDATE;
129 u_int dynamicListenQueueDepth = FCGI_DEFAULT_LISTEN_Q;
130 u_int dynamicInitStartDelay = DEFAULT_INIT_START_DELAY;
131 u_int dynamicRestartDelay = FCGI_DEFAULT_RESTART_DELAY;
132 array_header *dynamic_pass_headers = NULL;
133 u_int dynamic_idle_timeout = FCGI_DEFAULT_IDLE_TIMEOUT;
135 /*******************************************************************************
136 * Construct a message and write it to the pm_pipe.
138 static void send_to_pm(pool * const p, const char id, const char * const fs_path,
139 const char *user, const char * const group, const unsigned long q_usec,
140 const unsigned long req_usec)
142 #ifdef WIN32
143 fcgi_pm_job *job = NULL;
145 if (!(job = (fcgi_pm_job *) malloc(sizeof(fcgi_pm_job))))
146 return;
147 #else
148 int buflen = 0;
149 char buf[FCGI_MAX_MSG_LEN];
150 #endif
152 if (strlen(fs_path) > FCGI_MAXPATH) {
153 ap_log_error(FCGI_LOG_ERR_NOERRNO, fcgi_apache_main_server,
154 "FastCGI: the path \"%s\" is too long (>%d) for a dynamic server", fs_path, FCGI_MAXPATH);
155 return;
158 switch(id) {
160 case PLEASE_START:
161 #ifdef WIN32
162 job->id = id;
163 job->fs_path = strdup(fs_path);
164 job->user = strdup(user);
165 job->group = strdup(group);
166 job->qsec = 0L;
167 job->start_time = 0L;
168 #else
169 buflen = sprintf(buf, "%c %s %s %s*", id, fs_path, user, group);
170 #endif
171 break;
173 case CONN_TIMEOUT:
174 #ifdef WIN32
175 job->id = id;
176 job->fs_path = strdup(fs_path);
177 job->user = strdup(user);
178 job->group = strdup(group);
179 job->qsec = 0L;
180 job->start_time = 0L;
181 #else
182 buflen = sprintf(buf, "%c %s %s %s*", id, fs_path, user, group);
183 #endif
184 break;
186 case REQ_COMPLETE:
187 #ifdef WIN32
188 job->id = id;
189 job->fs_path = strdup(fs_path);
190 job->qsec = q_usec;
191 job->start_time = req_usec;
192 job->user = strdup(user);
193 job->group = strdup(group);
194 #else
195 buflen = sprintf(buf, "%c %s %s %s %lu %lu*", id, fs_path, user, group, q_usec, req_usec);
196 #endif
197 break;
200 #ifdef WIN32
201 if (fcgi_pm_add_job(job) == 0)
202 return;
204 SetEvent(fcgi_event_handles[MBOX_EVENT]);
205 #else
206 ap_assert(buflen <= FCGI_MAX_MSG_LEN);
208 if (write(fcgi_pm_pipe[1], (const void *)buf, buflen) != buflen) {
209 ap_log_error(FCGI_LOG_WARN, fcgi_apache_main_server,
210 "FastCGI: write() to PM failed");
212 #endif
217 *----------------------------------------------------------------------
219 * init_module
221 * An Apache module initializer, called by the Apache core
222 * after reading the server config.
224 * Start the process manager no matter what, since there may be a
225 * request for dynamic FastCGI applications without any being
226 * configured as static applications. Also, check for the existence
227 * and create if necessary a subdirectory into which all dynamic
228 * sockets will go.
230 *----------------------------------------------------------------------
232 static void init_module(server_rec *s, pool *p)
234 const char *err;
236 /* Register to reset to default values when the config pool is cleaned */
237 ap_block_alarms();
238 ap_register_cleanup(p, NULL, fcgi_config_reset_globals, ap_null_cleanup);
239 ap_unblock_alarms();
241 ap_add_version_component("mod_fastcgi/" MOD_FASTCGI_VERSION);
243 fcgi_config_set_fcgi_uid_n_gid(1);
245 /* keep these handy */
246 fcgi_config_pool = p;
247 fcgi_apache_main_server = s;
249 #ifndef WIN32
250 /* Create Unix/Domain socket directory */
251 if ((err = fcgi_config_make_dir(p, fcgi_socket_dir)))
252 ap_log_error(FCGI_LOG_ERR, s, "FastCGI: %s", err);
253 #endif
255 /* Create Dynamic directory */
256 if ((err = fcgi_config_make_dynamic_dir(p, 1)))
257 ap_log_error(FCGI_LOG_ERR, s, "FastCGI: %s", err);
259 #ifndef WIN32
260 /* Create the pipe for comm with the PM */
261 if (pipe(fcgi_pm_pipe) < 0) {
262 ap_log_error(FCGI_LOG_ERR, s, "FastCGI: pipe() failed");
265 /* Spawn the PM only once. Under Unix, Apache calls init() routines
266 * twice, once before detach() and once after. Win32 doesn't detach.
267 * Under DSO, DSO modules are unloaded between the two init() calls.
268 * Under Unix, the -X switch causes two calls to init() but no detach
269 * (but all subprocesses are wacked so the PM is toasted anyway)! */
271 if (ap_standalone && getppid() != 1)
272 return;
274 /* Start the Process Manager */
275 fcgi_pm_pid = ap_spawn_child(p, fcgi_pm_main, NULL, kill_only_once, NULL, NULL, NULL);
276 if (fcgi_pm_pid <= 0) {
277 ap_log_error(FCGI_LOG_ALERT, s,
278 "FastCGI: can't start the process manager, spawn_child() failed");
281 close(fcgi_pm_pipe[0]);
282 #endif
285 static void fcgi_child_init(server_rec *server_conf, pool *p)
287 #ifdef WIN32
288 /* Create the Event Handlers */
289 fcgi_event_handles[0] = CreateEvent(NULL, FALSE, FALSE, NULL);
290 fcgi_event_handles[1] = CreateEvent(NULL, FALSE, FALSE, NULL);
291 fcgi_event_handles[2] = CreateEvent(NULL, FALSE, FALSE, NULL);
292 fcgi_dynamic_mbox_mutex = ap_create_mutex("fcgi_dynamic_mbox_mutex");
294 /* Spawn of the process manager thread */
295 fcgi_pm_thread = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)fcgi_pm_main, NULL, 0, NULL);
296 #endif
297 return;
300 static void fcgi_child_exit(server_rec *server_conf, pool *p) {
302 #ifdef WIN32
303 /* Signaling the PM thread tp exit*/
304 SetEvent(fcgi_event_handles[TERM_EVENT]);
306 /* Waiting on pm thread to exit */
307 WaitForSingleObject(fcgi_pm_thread, INFINITE);
308 #endif
310 return;
314 *----------------------------------------------------------------------
316 * get_header_line --
318 * Terminate a line: scan to the next newline, scan back to the
319 * first non-space character and store a terminating zero. Return
320 * the next character past the end of the newline.
322 * If the end of the string is reached, ASSERT!
324 * If the FIRST character(s) in the line are '\n' or "\r\n", the
325 * first character is replaced with a NULL and next character
326 * past the newline is returned. NOTE: this condition supercedes
327 * the processing of RFC-822 continuation lines.
329 * If continuation is set to 'TRUE', then it parses a (possible)
330 * sequence of RFC-822 continuation lines.
332 * Results:
333 * As above.
335 * Side effects:
336 * Termination byte stored in string.
338 *----------------------------------------------------------------------
340 static char *get_header_line(char *start, int continuation)
342 char *p = start;
343 char *end = start;
345 if(p[0] == '\r' && p[1] == '\n') { /* If EOL in 1st 2 chars */
346 p++; /* point to \n and stop */
347 } else if(*p != '\n') {
348 if(continuation) {
349 while(*p != '\0') {
350 if(*p == '\n' && p[1] != ' ' && p[1] != '\t')
351 break;
352 p++;
354 } else {
355 while(*p != '\0' && *p != '\n') {
356 p++;
361 ap_assert(*p != '\0');
362 end = p;
363 end++;
366 * Trim any trailing whitespace.
368 while(isspace((unsigned char)p[-1]) && p > start) {
369 p--;
372 *p = '\0';
373 return end;
377 *----------------------------------------------------------------------
379 * process_headers --
381 * Call with r->parseHeader == SCAN_CGI_READING_HEADERS
382 * and initial script output in fr->header.
384 * If the initial script output does not include the header
385 * terminator ("\r\n\r\n") process_headers returns with no side
386 * effects, to be called again when more script output
387 * has been appended to fr->header.
389 * If the initial script output includes the header terminator,
390 * process_headers parses the headers and determines whether or
391 * not the remaining script output will be sent to the client.
392 * If so, process_headers sends the HTTP response headers to the
393 * client and copies any non-header script output to the output
394 * buffer reqOutbuf.
396 * Results:
397 * none.
399 * Side effects:
400 * May set r->parseHeader to:
401 * SCAN_CGI_FINISHED -- headers parsed, returning script response
402 * SCAN_CGI_BAD_HEADER -- malformed header from script
403 * SCAN_CGI_INT_REDIRECT -- handler should perform internal redirect
404 * SCAN_CGI_SRV_REDIRECT -- handler should return REDIRECT
406 *----------------------------------------------------------------------
409 static const char *process_headers(request_rec *r, fcgi_request *fr)
411 char *p, *next, *name, *value;
412 int len, flag;
413 int hasContentType, hasStatus, hasLocation;
415 ap_assert(fr->parseHeader == SCAN_CGI_READING_HEADERS);
417 if (fr->header == NULL)
418 return NULL;
421 * Do we have the entire header? Scan for the blank line that
422 * terminates the header.
424 p = (char *)fr->header->elts;
425 len = fr->header->nelts;
426 flag = 0;
427 while(len-- && flag < 2) {
428 switch(*p) {
429 case '\r':
430 break;
431 case '\n':
432 flag++;
433 break;
434 case '\0':
435 case '\v':
436 case '\f':
437 name = "Invalid Character";
438 goto BadHeader;
439 break;
440 default:
441 flag = 0;
442 break;
444 p++;
447 /* Return (to be called later when we have more data)
448 * if we don't have an entire header. */
449 if (flag < 2)
450 return NULL;
453 * Parse all the headers.
455 fr->parseHeader = SCAN_CGI_FINISHED;
456 hasContentType = hasStatus = hasLocation = FALSE;
457 next = (char *)fr->header->elts;
458 for(;;) {
459 next = get_header_line(name = next, TRUE);
460 if (*name == '\0') {
461 break;
463 if ((p = strchr(name, ':')) == NULL) {
464 goto BadHeader;
466 value = p + 1;
467 while (p != name && isspace((unsigned char)*(p - 1))) {
468 p--;
470 if (p == name) {
471 goto BadHeader;
473 *p = '\0';
474 if (strpbrk(name, " \t") != NULL) {
475 *p = ' ';
476 goto BadHeader;
478 while (isspace((unsigned char)*value)) {
479 value++;
482 if (strcasecmp(name, "Status") == 0) {
483 int statusValue = strtol(value, NULL, 10);
485 if (hasStatus) {
486 goto DuplicateNotAllowed;
488 if (statusValue < 0) {
489 fr->parseHeader = SCAN_CGI_BAD_HEADER;
490 return ap_psprintf(r->pool, "invalid Status '%s'", value);
492 hasStatus = TRUE;
493 r->status = statusValue;
494 r->status_line = ap_pstrdup(r->pool, value);
495 continue;
498 if (fr->role == FCGI_RESPONDER) {
499 if (strcasecmp(name, "Content-type") == 0) {
500 if (hasContentType) {
501 goto DuplicateNotAllowed;
503 hasContentType = TRUE;
504 r->content_type = ap_pstrdup(r->pool, value);
505 continue;
508 if (strcasecmp(name, "Location") == 0) {
509 if (hasLocation) {
510 goto DuplicateNotAllowed;
512 hasLocation = TRUE;
513 ap_table_set(r->headers_out, "Location", value);
514 continue;
517 /* If the script wants them merged, it can do it */
518 ap_table_add(r->err_headers_out, name, value);
519 continue;
521 else {
522 ap_table_add(fr->authHeaders, name, value);
526 if (fr->role != FCGI_RESPONDER)
527 return NULL;
530 * Who responds, this handler or Apache?
532 if (hasLocation) {
533 const char *location = ap_table_get(r->headers_out, "Location");
535 * Based on internal redirect handling in mod_cgi.c...
537 * If a script wants to produce its own Redirect
538 * body, it now has to explicitly *say* "Status: 302"
540 if (r->status == 200) {
541 if(location[0] == '/') {
543 * Location is an relative path. This handler will
544 * consume all script output, then have Apache perform an
545 * internal redirect.
547 fr->parseHeader = SCAN_CGI_INT_REDIRECT;
548 return NULL;
549 } else {
551 * Location is an absolute URL. If the script didn't
552 * produce a Content-type header, this handler will
553 * consume all script output and then have Apache generate
554 * its standard redirect response. Otherwise this handler
555 * will transmit the script's response.
557 fr->parseHeader = SCAN_CGI_SRV_REDIRECT;
558 return NULL;
563 * We're responding. Send headers, buffer excess script output.
565 ap_send_http_header(r);
567 /* We need to reinstate our timeout, send_http_header() kill()s it */
568 ap_hard_timeout("FastCGI request processing", r);
570 if (r->header_only)
571 return NULL;
573 len = fr->header->nelts - (next - fr->header->elts);
574 ap_assert(len >= 0);
575 ap_assert(BufferLength(fr->clientOutputBuffer) == 0);
576 if (BufferFree(fr->clientOutputBuffer) < len) {
577 fr->clientOutputBuffer = fcgi_buf_new(r->pool, len);
579 ap_assert(BufferFree(fr->clientOutputBuffer) >= len);
580 if (len > 0) {
581 int sent = fcgi_buf_add_block(fr->clientOutputBuffer, next, len);
582 ap_assert(sent == len);
584 return NULL;
586 BadHeader:
587 /* Log first line of a multi-line header */
588 if ((p = strpbrk(name, "\r\n")) != NULL)
589 *p = '\0';
590 fr->parseHeader = SCAN_CGI_BAD_HEADER;
591 return ap_psprintf(r->pool, "malformed header '%s'", name);
593 DuplicateNotAllowed:
594 fr->parseHeader = SCAN_CGI_BAD_HEADER;
595 return ap_psprintf(r->pool, "duplicate header '%s'", name);
599 * Read from the client filling both the FastCGI server buffer and the
600 * client buffer with the hopes of buffering the client data before
601 * making the connect() to the FastCGI server. This prevents slow
602 * clients from keeping the FastCGI server in processing longer than is
603 * necessary.
605 static int read_from_client_n_queue(fcgi_request *fr)
607 char *end;
608 size_t count;
609 long int countRead;
611 while (BufferFree(fr->clientInputBuffer) > 0 || BufferFree(fr->serverOutputBuffer) > 0) {
612 fcgi_protocol_queue_client_buffer(fr);
614 if (fr->expectingClientContent <= 0)
615 return OK;
617 fcgi_buf_get_free_block_info(fr->clientInputBuffer, &end, &count);
618 if (count == 0)
619 return OK;
621 if ((countRead = ap_get_client_block(fr->r, end, count)) < 0)
622 return -1;
624 if (countRead == 0) {
625 fr->expectingClientContent = 0;
627 else {
628 fcgi_buf_add_update(fr->clientInputBuffer, countRead);
629 ap_reset_timeout(fr->r);
632 return OK;
635 static int write_to_client(fcgi_request *fr)
637 char *begin;
638 size_t count;
640 fcgi_buf_get_block_info(fr->clientOutputBuffer, &begin, &count);
641 if (count == 0)
642 return OK;
644 /* If fewer than count bytes are written, an error occured.
645 * ap_bwrite() typically forces a flushed write to the client, this
646 * effectively results in a block (and short packets) - it should
647 * be fixed, but I didn't win much support for the idea on new-httpd.
648 * So, without patching Apache, the best way to deal with this is
649 * to size the fcgi_bufs to hold all of the script output (within
650 * reason) so the script can be released from having to wait around
651 * for the transmission to the client to complete. */
652 #ifdef RUSSIAN_APACHE
653 if (ap_rwrite(begin, count, fr->r) != count) {
654 ap_log_rerror(FCGI_LOG_INFO, fr->r,
655 "FastCGI: client stopped connection before send body completed");
656 return -1;
658 #else
659 if (ap_bwrite(fr->r->connection->client, begin, count) != (int) count) {
660 ap_log_rerror(FCGI_LOG_INFO, fr->r,
661 "FastCGI: client stopped connection before send body completed");
662 return -1;
664 #endif
666 ap_reset_timeout(fr->r);
668 /* Don't bother with a wrapped buffer, limiting exposure to slow
669 * clients. The BUFF routines don't allow a writev from above,
670 * and don't always memcpy to minimize small write()s, this should
671 * be fixed, but I didn't win much support for the idea on
672 * new-httpd - I'll have to _prove_ its a problem first.. */
674 /* The default behaviour used to be to flush with every write, but this
675 * can tie up the FastCGI server longer than is necessary so its an option now */
676 if (fr->fs && fr->fs->flush) {
677 #ifdef RUSSIAN_APACHE
678 if (ap_rflush(fr->r)) {
679 ap_log_rerror(FCGI_LOG_INFO, fr->r,
680 "FastCGI: client stopped connection before send body completed");
681 return -1;
683 #else
684 if (ap_bflush(fr->r->connection->client)) {
685 ap_log_rerror(FCGI_LOG_INFO, fr->r,
686 "FastCGI: client stopped connection before send body completed");
687 return -1;
689 #endif
690 ap_reset_timeout(fr->r);
693 fcgi_buf_toss(fr->clientOutputBuffer, count);
694 return OK;
697 /*******************************************************************************
698 * Determine the user and group the wrapper should be called with.
699 * Based on code in Apache's create_argv_cmd() (util_script.c).
701 static void set_uid_n_gid(request_rec *r, const char **user, const char **group)
703 if (fcgi_wrapper == NULL) {
704 *user = "-";
705 *group = "-";
706 return;
709 if (strncmp("/~", r->uri, 2) == 0) {
710 /* its a user dir uri, just send the ~user, and leave it to the PM */
711 char *end = strchr(r->uri + 2, '/');
713 if (end)
714 *user = memcpy(ap_pcalloc(r->pool, end - r->uri), r->uri + 1, end - r->uri - 1);
715 else
716 *user = ap_pstrdup(r->pool, r->uri + 1);
717 *group = "-";
719 else {
720 *user = ap_psprintf(r->pool, "%ld", (long)r->server->server_uid);
721 *group = ap_psprintf(r->pool, "%ld", (long)r->server->server_gid);
725 /*******************************************************************************
726 * Close the connection to the FastCGI server. This is normally called by
727 * do_work(), but may also be called as in request pool cleanup.
729 static void close_connection_to_fs(fcgi_request *fr)
731 pool *rp = fr->r->pool;
733 if (fr->fd >= 0) {
734 ap_pclosesocket(rp, fr->fd);
737 if (fr->dynamic) {
738 #ifdef WIN32
739 if (fr->lockFd != NULL) {
740 fcgi_rdwr_unlock(fr->lockFd, READER);
742 #else
743 if (fr->lockFd >= 0) {
744 ap_pclosef(rp, fr->lockFd);
746 #endif
748 if (fr->keepReadingFromFcgiApp == FALSE) {
749 /* XXX REQ_COMPLETE is only sent for requests which complete
750 * normally WRT the fcgi app. There is no data sent for
751 * connect() timeouts or requests which complete abnormally.
752 * KillDynamicProcs() and RemoveRecords() need to be looked at
753 * to be sure they can reasonably handle these cases before
754 * sending these sort of stats - theres some funk in there.
755 * XXX We should do something special when this a pool cleanup.
757 if (fcgi_util_gettimeofday(&fr->completeTime) < 0) {
758 /* there's no point to aborting the request, just log it */
759 ap_log_error(FCGI_LOG_ERR, fr->r->server, "FastCGI: gettimeofday() failed");
760 } else {
761 struct timeval qtime, rtime;
763 timersub(&fr->queueTime, &fr->startTime, &qtime);
764 timersub(&fr->completeTime, &fr->queueTime, &rtime);
766 send_to_pm(rp, REQ_COMPLETE, fr->fs_path,
767 fr->user, fr->group,
768 qtime.tv_sec * 1000000 + qtime.tv_usec,
769 rtime.tv_sec * 1000000 + rtime.tv_usec);
775 #ifdef WIN32
776 static void lock_cleanup(void * data)
778 fcgi_rdwr_unlock((FcgiRWLock *) data, READER);
780 #endif
782 /*******************************************************************************
783 * Connect to the FastCGI server.
785 static const char *open_connection_to_fs(fcgi_request *fr)
787 struct timeval tval;
788 fd_set write_fds, read_fds;
789 int status;
790 request_rec * const r = fr->r;
791 pool * const rp = r->pool;
792 const char *socket_path = NULL;
793 struct sockaddr *socket_addr = NULL;
794 int socket_addr_len = 0;
795 #ifdef WIN32
796 unsigned long ioctl_arg;
797 int errcode;
798 #else
799 int fd_flags = 0;
800 const char *err = NULL;
801 #endif
803 /* Create the connection point */
804 if (fr->dynamic) {
805 socket_path = fcgi_util_socket_hash_filename(rp, fr->fs_path, fr->user, fr->group);
806 socket_path = fcgi_util_socket_make_path_absolute(rp, socket_path, 1);
808 #ifndef WIN32
809 err = fcgi_util_socket_make_domain_addr(rp, (struct sockaddr_un **)&socket_addr,
810 &socket_addr_len, socket_path);
811 if (err)
812 return err;
813 #endif
814 } else {
815 #ifdef WIN32
816 if (fr->fs->dest_addr != NULL) {
817 socket_addr = fr->fs->dest_addr;
819 else if (fr->fs->socket_addr) {
820 socket_addr = fr->fs->socket_addr;
822 else {
823 socket_path = fr->fs->socket_path;
825 #else
826 socket_addr = fr->fs->socket_addr;
827 #endif
828 socket_addr_len = fr->fs->socket_addr_len;
831 /* Dynamic app's lockfile handling */
832 if (fr->dynamic) {
833 #ifndef WIN32
834 const char *lockFileName = fcgi_util_socket_get_lock_filename(rp, socket_path);
835 struct stat lstbuf;
836 #endif
837 struct stat bstbuf;
838 int result = 0;
840 do {
841 #ifdef WIN32
842 if (fr->fs != NULL)
843 #else
844 if (stat(lockFileName, &lstbuf) == 0 && S_ISREG(lstbuf.st_mode))
845 #endif
847 if (dynamicAutoUpdate && (stat(fr->fs_path, &bstbuf) == 0)
848 #ifdef WIN32
849 && ((fr->fs->restartTime > 0) && (fr->fs->restartTime < bstbuf.st_mtime)))
850 #else
851 && (lstbuf.st_mtime < bstbuf.st_mtime))
852 #endif
854 struct timeval tv = {1, 0};
856 /* Its already running, but there's a newer one,
857 * ask the process manager to start it.
858 * it will notice that the binary is newer,
859 * and do a restart instead.
861 send_to_pm(rp, PLEASE_START, fr->fs_path, fr->user, fr->group, 0, 0);
863 /* Avoid sleep/alarm interactions */
864 ap_select(0, NULL, NULL, NULL, &tv);
866 #ifdef WIN32
867 fr->lockFd = fr->fs->dynamic_lock;
868 result = 1;
869 #else
870 fr->lockFd = ap_popenf(rp, lockFileName, O_APPEND, 0);
871 result = (fr->lockFd < 0) ? (0) : (1);
872 #endif
873 } else {
874 struct timeval tv = {1, 0};
876 send_to_pm(rp, PLEASE_START, fr->fs_path, fr->user, fr->group, 0, 0);
878 #ifdef WIN32
879 Sleep(0);
880 #else
881 /* Avoid sleep/alarm interactions */
882 ap_select(0, NULL, NULL, NULL, &tv);
883 #endif
885 #ifdef WIN32
886 fr->fs = fcgi_util_fs_get_by_id(fr->fs_path, 0, 0);
887 #endif
888 } while (result != 1);
890 /* Block until we get a shared (non-exclusive) read Lock */
891 if (fcgi_wait_for_shared_read_lock(fr->lockFd) < 0)
892 return "failed to obtain a shared read lock";
894 #ifdef WIN32
895 ap_block_alarms();
896 ap_register_cleanup(rp, (void *) fr->lockFd, lock_cleanup, ap_null_cleanup);
897 ap_unblock_alarms();
898 #endif
900 FCGIDBG2("got_dynamic_shared_read_lock: %s", fr->fs_path);
903 #ifdef WIN32
904 if (socket_path)
906 BOOL ready;
907 int connect_time;
909 DWORD interval;
910 int max_connect_time = FCGI_NAMED_PIPE_CONNECT_TIMEOUT;
912 fr->using_npipe_io = TRUE;
914 if (fr->dynamic)
916 interval = dynamicPleaseStartDelay * 1000;
918 if (dynamicAppConnectTimeout) {
919 max_connect_time = dynamicAppConnectTimeout;
922 else
924 interval = FCGI_NAMED_PIPE_CONNECT_TIMEOUT * 1000;
926 if (fr->fs->appConnectTimeout) {
927 max_connect_time = fr->fs->appConnectTimeout;
931 if (fcgi_util_gettimeofday(&fr->startTime) < 0) {
932 return "gettimeofday() failed";
937 fr->fd = (SOCKET) CreateFile(socket_path,
938 GENERIC_READ | GENERIC_WRITE,
939 FILE_SHARE_READ | FILE_SHARE_WRITE,
940 NULL, // no security attributes
941 OPEN_EXISTING, // opens existing pipe
942 FILE_ATTRIBUTE_NORMAL, // default attributes
943 NULL); // no template file
945 if (fr->fd != (SOCKET) INVALID_HANDLE_VALUE) {
946 break;
949 if (GetLastError() != ERROR_PIPE_BUSY) {
950 return("CreateFile() failed ()");
953 // All pipe instances are busy, so wait
954 ready = WaitNamedPipe(socket_path, interval);
956 if (fr->dynamic && !ready) {
957 send_to_pm(rp, CONN_TIMEOUT, fr->fs_path, fr->user, fr->group, 0, 0);
960 if (fcgi_util_gettimeofday(&fr->queueTime) < 0) {
961 return "gettimeofday() failed";
964 connect_time = fr->queueTime.tv_sec - fr->startTime.tv_sec;
966 FCGIDBG5("interval=%d, max_connect_time=%d, connect_time=%d, ready=%d", interval, max_connect_time, connect_time, ready);
968 } while (connect_time < max_connect_time);
970 if (fr->fd == (SOCKET) INVALID_HANDLE_VALUE) {
971 return "CreateFile()/WaitNamedPipe() timed out";
974 FCGIDBG2("got_named_pipe_connect: %s", fr->fs_path);
976 ap_block_alarms();
977 ap_note_cleanups_for_h(rp, (HANDLE) fr->fd);
978 ap_unblock_alarms();
980 return NULL;
982 #endif
984 /* Create the socket */
985 fr->fd = ap_psocket(rp, socket_addr->sa_family, SOCK_STREAM, 0);
987 if (fr->fd < 0)
988 return "ap_psocket() failed";
990 #ifndef WIN32
991 if (fr->fd >= FD_SETSIZE) {
992 return ap_psprintf(rp, "socket file descriptor (%u) is larger than "
993 "FD_SETSIZE (%u), you probably need to rebuild Apache with a "
994 "larger FD_SETSIZE", fr->fd, FD_SETSIZE);
996 #endif
998 /* If appConnectTimeout is non-zero, setup do a non-blocking connect */
999 if ((fr->dynamic && dynamicAppConnectTimeout) || (!fr->dynamic && fr->fs->appConnectTimeout)) {
1000 #ifndef WIN32
1001 if ((fd_flags = fcntl(fr->fd, F_GETFL, 0)) < 0)
1002 return "fcntl(F_GETFL) failed";
1003 if (fcntl(fr->fd, F_SETFL, fd_flags | O_NONBLOCK) < 0)
1004 return "fcntl(F_SETFL) failed";
1005 #else
1006 ioctl_arg =1;
1007 if (ioctlsocket(fr->fd, FIONBIO, &ioctl_arg) != 0)
1008 return "ioctlsocket(FIONBIO) failed";
1009 #endif
1012 if (fr->dynamic && fcgi_util_gettimeofday(&fr->startTime) < 0)
1013 return "gettimeofday() failed";
1015 /* Connect */
1016 if (connect(fr->fd, (struct sockaddr *)socket_addr, socket_addr_len) == 0)
1017 goto ConnectionComplete;
1019 #ifdef WIN32
1020 errcode = GetLastError();
1021 if (errcode != WSAEWOULDBLOCK)
1022 return "connect() failed";
1023 #else
1024 /* ECONNREFUSED means the listen queue is full (or there isn't one).
1025 * With dynamic I can at least make sure the PM knows this is occuring */
1026 if (fr->dynamic && errno == ECONNREFUSED) {
1027 /* @@@ This might be better as some other "kind" of message */
1028 send_to_pm(rp, CONN_TIMEOUT, fr->fs_path, fr->user, fr->group, 0, 0);
1030 errno = ECONNREFUSED;
1033 if (errno != EINPROGRESS)
1034 return "connect() failed";
1035 #endif
1037 /* The connect() is non-blocking */
1039 errno = 0;
1041 if (fr->dynamic) {
1042 do {
1043 FD_ZERO(&write_fds);
1044 FD_SET(fr->fd, &write_fds);
1045 read_fds = write_fds;
1046 tval.tv_sec = dynamicPleaseStartDelay;
1047 tval.tv_usec = 0;
1049 status = ap_select((fr->fd+1), &read_fds, &write_fds, NULL, &tval);
1050 if (status < 0)
1051 break;
1053 if (fcgi_util_gettimeofday(&fr->queueTime) < 0)
1054 return "gettimeofday() failed";
1055 if (status > 0)
1056 break;
1058 /* select() timed out */
1059 send_to_pm(rp, CONN_TIMEOUT, fr->fs_path, fr->user, fr->group, 0, 0);
1060 } while ((fr->queueTime.tv_sec - fr->startTime.tv_sec) < (int)dynamicAppConnectTimeout);
1062 /* XXX These can be moved down when dynamic vars live is a struct */
1063 if (status == 0) {
1064 return ap_psprintf(rp, "connect() timed out (appConnTimeout=%dsec)",
1065 dynamicAppConnectTimeout);
1067 } /* dynamic */
1068 else {
1069 tval.tv_sec = fr->fs->appConnectTimeout;
1070 tval.tv_usec = 0;
1071 FD_ZERO(&write_fds);
1072 FD_SET(fr->fd, &write_fds);
1073 read_fds = write_fds;
1075 status = ap_select((fr->fd+1), &read_fds, &write_fds, NULL, &tval);
1076 if (status == 0) {
1077 return ap_psprintf(rp, "connect() timed out (appConnTimeout=%dsec)",
1078 fr->fs->appConnectTimeout);
1080 } /* !dynamic */
1082 if (status < 0)
1083 return "select() failed";
1085 if (FD_ISSET(fr->fd, &write_fds) || FD_ISSET(fr->fd, &read_fds)) {
1086 int error = 0;
1087 NET_SIZE_T len = sizeof(error);
1089 if (getsockopt(fr->fd, SOL_SOCKET, SO_ERROR, (char *)&error, &len) < 0)
1090 /* Solaris pending error */
1091 return "select() failed (Solaris pending error)";
1093 if (error != 0) {
1094 /* Berkeley-derived pending error */
1095 errno = error;
1096 return "select() failed (pending error)";
1098 } else
1099 return "select() error - THIS CAN'T HAPPEN!";
1101 ConnectionComplete:
1102 /* Return to blocking mode if it was set up */
1103 if ((fr->dynamic && dynamicAppConnectTimeout) || (!fr->dynamic && fr->fs->appConnectTimeout)) {
1104 #ifdef WIN32
1105 ioctl_arg = 0;
1106 if (ioctlsocket(fr->fd, FIONBIO, &ioctl_arg) != 0)
1107 return "ioctlsocket(FIONBIO) failed";
1108 #else
1109 if ((fcntl(fr->fd, F_SETFL, fd_flags)) < 0)
1110 return "fcntl(F_SETFL) failed";
1111 #endif
1114 #ifdef TCP_NODELAY
1115 if (socket_addr->sa_family == AF_INET) {
1116 /* We shouldn't be sending small packets and there's no application
1117 * level ack of the data we send, so disable Nagle */
1118 int set = 1;
1119 setsockopt(fr->fd, IPPROTO_TCP, TCP_NODELAY, (char *)&set, sizeof(set));
1121 #endif
1123 return NULL;
1126 static int server_error(fcgi_request *fr)
1128 #if defined(SIGPIPE) && MODULE_MAGIC_NUMBER < 19990320
1129 /* Make sure we leave with Apache's sigpipe_handler in place */
1130 if (fr->apache_sigpipe_handler != NULL)
1131 signal(SIGPIPE, fr->apache_sigpipe_handler);
1132 #endif
1133 close_connection_to_fs(fr);
1134 ap_kill_timeout(fr->r);
1135 return SERVER_ERROR;
1138 static void log_fcgi_server_stderr(void *data)
1140 const fcgi_request * const fr = (fcgi_request *)data;
1142 if (fr == NULL)
1143 return ;
1145 if (fr->fs_stderr_len) {
1146 ap_log_rerror(FCGI_LOG_ERR_NOERRNO, fr->r,
1147 "FastCGI: server \"%s\" stderr: %s", fr->fs_path, fr->fs_stderr);
1151 /*----------------------------------------------------------------------
1152 * This is the core routine for moving data between the FastCGI
1153 * application and the Web server's client.
1155 static int do_work(request_rec *r, fcgi_request *fr)
1157 struct timeval timeOut, dynamic_last_activity_time = {0, 0};
1158 fd_set read_set, write_set;
1159 int status = 0, idle_timeout;
1160 int numFDs, dynamic_first_read = fr->dynamic ? 1 : 0;
1161 int doClientWrite;
1162 int envSent = FALSE; /* has the complete ENV been buffered? */
1163 env_status env;
1164 pool *rp = r->pool;
1165 const char *err = NULL;
1167 FD_ZERO(&read_set);
1168 FD_ZERO(&write_set);
1170 fcgi_protocol_queue_begin_request(fr);
1172 /* Buffer as much of the environment as we can fit */
1173 env.envp = NULL;
1174 envSent = fcgi_protocol_queue_env(r, fr, &env);
1176 /* Start the Apache dropdead timer. See comments at top of file. */
1177 ap_hard_timeout("buffering of FastCGI client data", r);
1179 /* Read as much as possible from the client. */
1180 if (fr->role == FCGI_RESPONDER) {
1181 status = ap_setup_client_block(r, REQUEST_CHUNKED_ERROR);
1182 if (status != OK) {
1183 ap_kill_timeout(r);
1184 return status;
1186 fr->expectingClientContent = (ap_should_client_block(r) != 0);
1188 if (read_from_client_n_queue(fr) != OK)
1189 return server_error(fr);
1192 /* Connect to the FastCGI Application */
1193 ap_hard_timeout("connect() to FastCGI server", r);
1194 if ((err = open_connection_to_fs(fr))) {
1195 ap_log_rerror(FCGI_LOG_ERR, r,
1196 "FastCGI: failed to connect to server \"%s\": %s", fr->fs_path, err);
1197 return server_error(fr);
1200 numFDs = fr->fd + 1;
1201 idle_timeout = fr->dynamic ? dynamic_idle_timeout : fr->fs->idle_timeout;
1203 if (dynamic_first_read) {
1204 dynamic_last_activity_time = fr->startTime;
1206 if (dynamicAppConnectTimeout) {
1207 struct timeval qwait;
1208 timersub(&fr->queueTime, &fr->startTime, &qwait);
1209 dynamic_first_read = qwait.tv_sec / dynamicPleaseStartDelay + 1;
1213 /* @@@ We never reset the timer in this loop, most folks don't mess w/
1214 * Timeout directive which means we've got the 5 min default which is way
1215 * to long to tie up a fs. We need a better/configurable solution that
1216 * uses the select */
1217 ap_hard_timeout("FastCGI request processing", r);
1219 /* Register to get the script's stderr logged at the end of the request */
1220 ap_block_alarms();
1221 ap_register_cleanup(rp, (void *)fr, log_fcgi_server_stderr, ap_null_cleanup);
1222 ap_unblock_alarms();
1224 /* The socket is writeable, so get the first write out of the way */
1225 if (fcgi_buf_get_to_fd(fr->serverOutputBuffer, fr->fd) < 0) {
1226 ap_log_rerror(FCGI_LOG_ERR, r,
1227 "FastCGI: comm with server \"%s\" aborted: write failed", fr->fs_path);
1228 return server_error(fr);
1231 while (fr->keepReadingFromFcgiApp
1232 || BufferLength(fr->serverInputBuffer) > 0
1233 || BufferLength(fr->clientOutputBuffer) > 0) {
1235 /* If we didn't buffer all of the environment yet, buffer some more */
1236 if (!envSent)
1237 envSent = fcgi_protocol_queue_env(r, fr, &env);
1239 /* Read as much as possible from the client. */
1240 if (fr->role == FCGI_RESPONDER && !fr->eofSent && envSent) {
1241 if (read_from_client_n_queue(fr) != OK)
1242 return server_error(fr);
1245 /* To avoid deadlock, don't do a blocking select to write to
1246 * the FastCGI application without selecting to read from the
1247 * FastCGI application.
1249 doClientWrite = FALSE;
1250 if (fr->keepReadingFromFcgiApp && BufferFree(fr->serverInputBuffer) > 0) {
1252 #ifdef WIN32
1253 if (!fr->using_npipe_io) {
1254 #endif
1255 FD_SET(fr->fd, &read_set);
1257 /* Is data buffered for output to the FastCGI server? */
1258 if (BufferLength(fr->serverOutputBuffer) > 0) {
1259 FD_SET(fr->fd, &write_set);
1260 } else {
1261 FD_CLR(fr->fd, &write_set);
1263 #ifdef WIN32
1265 #endif
1267 * If there's data buffered to send to the client, don't
1268 * wait indefinitely for the FastCGI app; the app might
1269 * be doing server push.
1271 if (BufferLength(fr->clientOutputBuffer) > 0) {
1272 timeOut.tv_sec = 0;
1273 timeOut.tv_usec = 100000; /* 0.1 sec */
1275 else if (dynamic_first_read) {
1276 int delay;
1277 struct timeval qwait;
1279 if (fcgi_util_gettimeofday(&fr->queueTime) < 0) {
1280 ap_log_rerror(FCGI_LOG_ERR, r, "FastCGI: gettimeofday() failed");
1281 return server_error(fr);
1284 /* Check for idle_timeout */
1285 if (status) {
1286 dynamic_last_activity_time = fr->queueTime;
1288 else {
1289 struct timeval idle_time;
1290 timersub(&fr->queueTime, &dynamic_last_activity_time, &idle_time);
1291 if (idle_time.tv_sec > idle_timeout) {
1292 send_to_pm(rp, CONN_TIMEOUT, fr->fs_path, fr->user, fr->group, 0, 0);
1293 ap_log_rerror(FCGI_LOG_ERR_NOERRNO, r,
1294 "FastCGI: comm with (dynamic) server \"%s\" aborted: (first read) idle timeout (%d sec)",
1295 fr->fs_path, idle_timeout);
1296 return server_error(fr);
1300 timersub(&fr->queueTime, &fr->startTime, &qwait);
1302 delay = dynamic_first_read * dynamicPleaseStartDelay;
1303 if (qwait.tv_sec < delay) {
1304 timeOut.tv_sec = delay;
1305 timeOut.tv_usec = 100000; /* fudge for select() slop */
1306 timersub(&timeOut, &qwait, &timeOut);
1308 else {
1309 /* Killed time somewhere.. client read? */
1310 send_to_pm(rp, CONN_TIMEOUT, fr->fs_path, fr->user, fr->group, 0, 0);
1311 dynamic_first_read = qwait.tv_sec / dynamicPleaseStartDelay + 1;
1312 timeOut.tv_sec = dynamic_first_read * dynamicPleaseStartDelay;
1313 timeOut.tv_usec = 100000; /* fudge for select() slop */
1314 timersub(&timeOut, &qwait, &timeOut);
1317 else {
1318 timeOut.tv_sec = idle_timeout;
1319 timeOut.tv_usec = 0;
1322 #ifdef WIN32
1323 if (!fr->using_npipe_io) {
1324 #endif
1325 if ((status = ap_select(numFDs, &read_set, &write_set, NULL, &timeOut)) < 0) {
1326 ap_log_rerror(FCGI_LOG_ERR, r,
1327 "FastCGI: comm with server \"%s\" aborted: select() failed", fr->fs_path);
1328 return server_error(fr);
1330 #ifdef WIN32
1332 else {
1333 int stopTime = time(NULL) + timeOut.tv_sec;
1334 DWORD bytesavail=0;
1336 if (!(BufferLength(fr->serverOutputBuffer) > 0)) {
1337 status = 0;
1339 while ((timeOut.tv_sec != 0) && (time(NULL) <= stopTime)) {
1340 if (PeekNamedPipe((HANDLE) fr->fd,NULL, 0, NULL, &bytesavail, NULL) &&
1341 bytesavail > 0)
1343 status =1;
1344 break;
1346 Sleep(100);
1349 else {
1350 status = 1;
1353 #endif
1355 if (status == 0) {
1356 if (BufferLength(fr->clientOutputBuffer) > 0) {
1357 doClientWrite = TRUE;
1359 else if (dynamic_first_read) {
1360 struct timeval qwait;
1362 if (fcgi_util_gettimeofday(&fr->queueTime) < 0) {
1363 ap_log_rerror(FCGI_LOG_ERR, r, "FastCGI: gettimeofday() failed");
1364 return server_error(fr);
1367 timersub(&fr->queueTime, &fr->startTime, &qwait);
1369 send_to_pm(rp, CONN_TIMEOUT, fr->fs_path, fr->user, fr->group, 0, 0);
1371 dynamic_first_read = qwait.tv_sec / dynamicPleaseStartDelay + 1;
1373 else {
1374 ap_log_rerror(FCGI_LOG_ERR_NOERRNO, r,
1375 "FastCGI: comm with server \"%s\" aborted: idle timeout (%d sec)",
1376 fr->fs_path, idle_timeout);
1377 return server_error(fr);
1381 #if defined(SIGPIPE) && MODULE_MAGIC_NUMBER < 19990320
1382 /* Disable Apache's SIGPIPE handler */
1383 fr->apache_sigpipe_handler = signal(SIGPIPE, SIG_IGN);
1384 #endif
1386 /* Read from the FastCGI server */
1387 #ifdef WIN32
1388 if (((fr->using_npipe_io) &&
1389 (BufferFree(fr->serverInputBuffer) > 0)) || FD_ISSET(fr->fd, &read_set)) {
1390 #else
1391 if (FD_ISSET(fr->fd, &read_set)) {
1392 #endif
1393 if (dynamic_first_read) {
1394 dynamic_first_read = 0;
1395 if (fcgi_util_gettimeofday(&fr->queueTime) < 0) {
1396 ap_log_rerror(FCGI_LOG_ERR, r, "FastCGI: gettimeofday() failed");
1397 return server_error(fr);
1401 if ((status = fcgi_buf_add_fd(fr->serverInputBuffer, fr->fd)) < 0) {
1402 ap_log_rerror(FCGI_LOG_ERR, r,
1403 "FastCGI: comm with server \"%s\" aborted: read failed", fr->fs_path);
1404 return server_error(fr);
1407 if (status == 0) {
1408 fr->keepReadingFromFcgiApp = FALSE;
1409 close_connection_to_fs(fr);
1413 /* Write to the FastCGI server */
1414 #ifdef WIN32
1415 if (((fr->using_npipe_io) &&
1416 (BufferLength(fr->serverOutputBuffer) > 0)) || FD_ISSET(fr->fd, &write_set)) {
1417 #else
1418 if (FD_ISSET(fr->fd, &write_set)) {
1419 #endif
1421 if (fcgi_buf_get_to_fd(fr->serverOutputBuffer, fr->fd) < 0) {
1422 ap_log_rerror(FCGI_LOG_ERR, r,
1423 "FastCGI: comm with server \"%s\" aborted: write failed", fr->fs_path);
1424 return server_error(fr);
1428 #if defined(SIGPIPE) && MODULE_MAGIC_NUMBER < 19990320
1429 /* Reinstall Apache's SIGPIPE handler */
1430 signal(SIGPIPE, fr->apache_sigpipe_handler);
1431 #endif
1433 } else {
1434 doClientWrite = TRUE;
1437 if (fr->role == FCGI_RESPONDER && doClientWrite) {
1438 if (write_to_client(fr) != OK) {
1439 #if defined(SIGPIPE) && MODULE_MAGIC_NUMBER < 19990320
1440 /* Make sure we leave with Apache's sigpipe_handler in place */
1441 if (fr->apache_sigpipe_handler != NULL)
1442 signal(SIGPIPE, fr->apache_sigpipe_handler);
1443 #endif
1444 close_connection_to_fs(fr);
1445 ap_kill_timeout(fr->r);
1446 return OK;
1450 if (fcgi_protocol_dequeue(rp, fr) != OK)
1451 return server_error(fr);
1453 if (fr->keepReadingFromFcgiApp && fr->exitStatusSet) {
1454 /* we're done talking to the fcgi app */
1455 fr->keepReadingFromFcgiApp = FALSE;
1456 close_connection_to_fs(fr);
1459 if (fr->parseHeader == SCAN_CGI_READING_HEADERS) {
1460 if ((err = process_headers(r, fr))) {
1461 ap_log_rerror(FCGI_LOG_ERR, r,
1462 "FastCGI: comm with server \"%s\" aborted: error parsing headers: %s", fr->fs_path, err);
1463 return server_error(fr);
1467 } /* while */
1469 switch (fr->parseHeader) {
1471 case SCAN_CGI_FINISHED:
1472 if (fr->role == FCGI_RESPONDER) {
1473 #ifdef RUSSIAN_APACHE
1474 ap_rflush(r);
1475 #else
1476 ap_bflush(r->connection->client);
1477 #endif
1478 ap_bgetopt(r->connection->client, BO_BYTECT, &r->bytes_sent);
1480 break;
1482 case SCAN_CGI_READING_HEADERS:
1483 ap_log_rerror(FCGI_LOG_ERR, r,
1484 "FastCGI: incomplete headers (%d bytes) received from server \"%s\"",
1485 fr->header->nelts, fr->fs_path);
1486 return server_error(fr);
1488 case SCAN_CGI_BAD_HEADER:
1489 return server_error(fr);
1491 case SCAN_CGI_INT_REDIRECT:
1492 case SCAN_CGI_SRV_REDIRECT:
1494 * XXX We really should be soaking all client input
1495 * and all script output. See mod_cgi.c.
1496 * There's other differences we need to pick up here as well!
1497 * This has to be revisited.
1499 break;
1501 default:
1502 ap_assert(FALSE);
1505 ap_kill_timeout(r);
1506 return OK;
1510 static fcgi_request *create_fcgi_request(request_rec * const r, const char *fs_path)
1512 struct stat *my_finfo;
1513 pool * const p = r->pool;
1514 fcgi_server *fs;
1515 fcgi_request * const fr = (fcgi_request *)ap_pcalloc(p, sizeof(fcgi_request));
1517 if (fs_path) {
1518 my_finfo = (struct stat *)ap_palloc(p, sizeof(struct stat));
1519 if (stat(fs_path, my_finfo) < 0) {
1520 ap_log_rerror(FCGI_LOG_ERR, r, "FastCGI: stat() of \"%s\" failed", fs_path);
1521 return NULL;
1524 else {
1525 my_finfo = &r->finfo;
1526 fs_path = r->filename;
1529 fs = fcgi_util_fs_get_by_id(fs_path, r->server->server_uid, r->server->server_gid);
1530 if (fs == NULL) {
1531 /* Its a request for a dynamic FastCGI application */
1532 const char * const err =
1533 fcgi_util_fs_is_path_ok(p, fs_path, my_finfo, r->server->server_uid, r->server->server_gid);
1535 if (err) {
1536 ap_log_rerror(FCGI_LOG_ERR_NOERRNO, r, "FastCGI: invalid (dynamic) server \"%s\": %s", fs_path, err);
1537 return NULL;
1541 fr->serverInputBuffer = fcgi_buf_new(p, SERVER_BUFSIZE);
1542 fr->serverOutputBuffer = fcgi_buf_new(p, SERVER_BUFSIZE);
1543 fr->clientInputBuffer = fcgi_buf_new(p, SERVER_BUFSIZE);
1544 fr->clientOutputBuffer = fcgi_buf_new(p, SERVER_BUFSIZE);
1545 fr->erBufPtr = fcgi_buf_new(p, sizeof(FCGI_EndRequestBody) + 1);
1546 fr->gotHeader = FALSE;
1547 fr->parseHeader = SCAN_CGI_READING_HEADERS;
1548 fr->header = ap_make_array(p, 1, 1);
1549 fr->fs_stderr = NULL;
1550 fr->r = r;
1551 fr->readingEndRequestBody = FALSE;
1552 fr->exitStatus = 0;
1553 fr->exitStatusSet = FALSE;
1554 fr->requestId = 1; /* anything but zero is OK here */
1555 fr->eofSent = FALSE;
1556 fr->role = FCGI_RESPONDER;
1557 fr->expectingClientContent = FALSE;
1558 fr->keepReadingFromFcgiApp = TRUE;
1559 fr->fs = fs;
1560 fr->fs_path = fs_path;
1561 fr->authHeaders = ap_make_table(p, 10);
1562 #ifdef WIN32
1563 fr->fd = INVALID_SOCKET;
1564 fr->dynamic = ((fs == NULL) || (fs->directive == APP_CLASS_DYNAMIC)) ? TRUE : FALSE;
1565 fr->using_npipe_io = FALSE;
1566 #else
1567 fr->dynamic = (fs == NULL) ? TRUE : FALSE;
1568 fr->fd = -1;
1569 fr->lockFd = -1;
1570 #endif
1572 set_uid_n_gid(r, &fr->user, &fr->group);
1574 return fr;
1578 *----------------------------------------------------------------------
1580 * handler --
1582 * This routine gets called for a request that corresponds to
1583 * a FastCGI connection. It performs the request synchronously.
1585 * Results:
1586 * Final status of request: OK or NOT_FOUND or SERVER_ERROR.
1588 * Side effects:
1589 * Request performed.
1591 *----------------------------------------------------------------------
1594 /* Stolen from mod_cgi.c..
1595 * KLUDGE --- for back-combatibility, we don't have to check ExecCGI
1596 * in ScriptAliased directories, which means we need to know if this
1597 * request came through ScriptAlias or not... so the Alias module
1598 * leaves a note for us.
1600 static int apache_is_scriptaliased(request_rec *r)
1602 const char *t = ap_table_get(r->notes, "alias-forced-type");
1603 return t && (!strcasecmp(t, "cgi-script"));
1606 /* If a script wants to produce its own Redirect body, it now
1607 * has to explicitly *say* "Status: 302". If it wants to use
1608 * Apache redirects say "Status: 200". See process_headers().
1610 static int post_process_for_redirects(request_rec * const r,
1611 const fcgi_request * const fr)
1613 switch(fr->parseHeader) {
1614 case SCAN_CGI_INT_REDIRECT:
1616 /* @@@ There are still differences between the handling in
1617 * mod_cgi and mod_fastcgi. This needs to be revisited.
1619 /* We already read the message body (if any), so don't allow
1620 * the redirected request to think it has one. We can ignore
1621 * Transfer-Encoding, since we used REQUEST_CHUNKED_ERROR.
1623 r->method = "GET";
1624 r->method_number = M_GET;
1625 ap_table_unset(r->headers_in, "Content-length");
1627 ap_internal_redirect_handler(ap_table_get(r->headers_out, "Location"), r);
1628 return OK;
1630 case SCAN_CGI_SRV_REDIRECT:
1631 return REDIRECT;
1633 default:
1634 return OK;
1638 /******************************************************************************
1639 * Process fastcgi-script requests. Based on mod_cgi::cgi_handler().
1641 static int content_handler(request_rec *r)
1643 fcgi_request *fr = NULL;
1644 int ret;
1646 /* Setup a new FastCGI request */
1647 if ((fr = create_fcgi_request(r, NULL)) == NULL)
1648 return SERVER_ERROR;
1650 /* If its a dynamic invocation, make sure scripts are OK here */
1651 if (fr->dynamic && !(ap_allow_options(r) & OPT_EXECCGI) && !apache_is_scriptaliased(r)) {
1652 ap_log_rerror(FCGI_LOG_ERR_NOERRNO, r,
1653 "FastCGI: \"ExecCGI Option\" is off in this directory: %s", r->uri);
1654 return SERVER_ERROR;
1657 /* Process the fastcgi-script request */
1658 if ((ret = do_work(r, fr)) != OK)
1659 return ret;
1661 /* Special case redirects */
1662 return post_process_for_redirects(r, fr);
1666 static int post_process_auth_passed_header(table *t, const char *key, const char * const val)
1668 if (strncasecmp(key, "Variable-", 9) == 0)
1669 key += 9;
1671 ap_table_setn(t, key, val);
1672 return 1;
1675 static int post_process_auth_passed_compat_header(table *t, const char *key, const char * const val)
1677 if (strncasecmp(key, "Variable-", 9) == 0)
1678 ap_table_setn(t, key + 9, val);
1680 return 1;
1683 static int post_process_auth_failed_header(table * const t, const char * const key, const char * const val)
1685 ap_table_setn(t, key, val);
1686 return 1;
1689 static void post_process_auth(fcgi_request * const fr, const int passed)
1691 request_rec * const r = fr->r;
1693 /* Restore the saved subprocess_env because we muddied ours up */
1694 r->subprocess_env = fr->saved_subprocess_env;
1696 if (passed) {
1697 if (fr->auth_compat) {
1698 ap_table_do((int (*)(void *, const char *, const char *))post_process_auth_passed_compat_header,
1699 (void *)r->subprocess_env, fr->authHeaders, NULL);
1701 else {
1702 ap_table_do((int (*)(void *, const char *, const char *))post_process_auth_passed_header,
1703 (void *)r->subprocess_env, fr->authHeaders, NULL);
1706 else {
1707 ap_table_do((int (*)(void *, const char *, const char *))post_process_auth_failed_header,
1708 (void *)r->err_headers_out, fr->authHeaders, NULL);
1711 /* @@@ Restore these.. its a hack until I rewrite the header handling */
1712 r->status = HTTP_OK;
1713 r->status_line = NULL;
1716 static int check_user_authentication(request_rec *r)
1718 int res, authenticated = 0;
1719 const char *password;
1720 fcgi_request *fr;
1721 const fcgi_dir_config * const dir_config =
1722 (const fcgi_dir_config *)ap_get_module_config(r->per_dir_config, &fastcgi_module);
1724 if (dir_config->authenticator == NULL)
1725 return DECLINED;
1727 /* Get the user password */
1728 if ((res = ap_get_basic_auth_pw(r, &password)) != OK)
1729 return res;
1731 if ((fr = create_fcgi_request(r, dir_config->authenticator)) == NULL)
1732 return SERVER_ERROR;
1734 /* Save the existing subprocess_env, because we're gonna muddy it up */
1735 fr->saved_subprocess_env = ap_copy_table(r->pool, r->subprocess_env);
1737 ap_table_setn(r->subprocess_env, "REMOTE_PASSWD", password);
1738 ap_table_setn(r->subprocess_env, "FCGI_APACHE_ROLE", "AUTHENTICATOR");
1740 /* The FastCGI Protocol doesn't differentiate authentication */
1741 fr->role = FCGI_AUTHORIZER;
1743 /* Do we need compatibility mode? */
1744 fr->auth_compat = (dir_config->authenticator_options & FCGI_COMPAT);
1746 if ((res = do_work(r, fr)) != OK)
1747 goto AuthenticationFailed;
1749 authenticated = (r->status == 200);
1750 post_process_auth(fr, authenticated);
1752 /* A redirect shouldn't be allowed during the authentication phase */
1753 if (ap_table_get(r->headers_out, "Location") != NULL) {
1754 ap_log_rerror(FCGI_LOG_ERR_NOERRNO, r,
1755 "FastCGI: FastCgiAuthenticator \"%s\" redirected (not allowed)",
1756 dir_config->authenticator);
1757 goto AuthenticationFailed;
1760 if (authenticated)
1761 return OK;
1763 AuthenticationFailed:
1764 if (!(dir_config->authenticator_options & FCGI_AUTHORITATIVE))
1765 return DECLINED;
1767 /* @@@ Probably should support custom_responses */
1768 ap_note_basic_auth_failure(r);
1769 ap_log_rerror(FCGI_LOG_ERR_NOERRNO, r,
1770 "FastCGI: authentication failed for user \"%s\": %s", r->connection->user, r->uri);
1771 return (res == OK) ? AUTH_REQUIRED : res;
1774 static int check_user_authorization(request_rec *r)
1776 int res, authorized = 0;
1777 fcgi_request *fr;
1778 const fcgi_dir_config * const dir_config =
1779 (const fcgi_dir_config *)ap_get_module_config(r->per_dir_config, &fastcgi_module);
1781 if (dir_config->authorizer == NULL)
1782 return DECLINED;
1784 /* @@@ We should probably honor the existing parameters to the require directive
1785 * as well as allow the definition of new ones (or use the basename of the
1786 * FastCGI server and pass the rest of the directive line), but for now keep
1787 * it simple. */
1789 if ((fr = create_fcgi_request(r, dir_config->authorizer)) == NULL)
1790 return SERVER_ERROR;
1792 /* Save the existing subprocess_env, because we're gonna muddy it up */
1793 fr->saved_subprocess_env = ap_copy_table(r->pool, r->subprocess_env);
1795 ap_table_setn(r->subprocess_env, "FCGI_APACHE_ROLE", "AUTHORIZER");
1797 fr->role = FCGI_AUTHORIZER;
1799 /* Do we need compatibility mode? */
1800 fr->auth_compat = (dir_config->authenticator_options & FCGI_COMPAT);
1802 if ((res = do_work(r, fr)) != OK)
1803 goto AuthorizationFailed;
1805 authorized = (r->status == 200);
1806 post_process_auth(fr, authorized);
1808 /* A redirect shouldn't be allowed during the authorization phase */
1809 if (ap_table_get(r->headers_out, "Location") != NULL) {
1810 ap_log_rerror(FCGI_LOG_ERR_NOERRNO, r,
1811 "FastCGI: FastCgiAuthorizer \"%s\" redirected (not allowed)",
1812 dir_config->authorizer);
1813 goto AuthorizationFailed;
1816 if (authorized)
1817 return OK;
1819 AuthorizationFailed:
1820 if (!(dir_config->authorizer_options & FCGI_AUTHORITATIVE))
1821 return DECLINED;
1823 /* @@@ Probably should support custom_responses */
1824 ap_note_basic_auth_failure(r);
1825 ap_log_rerror(FCGI_LOG_ERR_NOERRNO, r,
1826 "FastCGI: authorization failed for user \"%s\": %s", r->connection->user, r->uri);
1827 return (res == OK) ? AUTH_REQUIRED : res;
1830 static int check_access(request_rec *r)
1832 int res, access_allowed = 0;
1833 fcgi_request *fr;
1834 const fcgi_dir_config * const dir_config =
1835 (fcgi_dir_config *)ap_get_module_config(r->per_dir_config, &fastcgi_module);
1837 if (dir_config == NULL || dir_config->access_checker == NULL)
1838 return DECLINED;
1840 if ((fr = create_fcgi_request(r, dir_config->access_checker)) == NULL)
1841 return SERVER_ERROR;
1843 /* Save the existing subprocess_env, because we're gonna muddy it up */
1844 fr->saved_subprocess_env = ap_copy_table(r->pool, r->subprocess_env);
1846 ap_table_setn(r->subprocess_env, "FCGI_APACHE_ROLE", "ACCESS_CHECKER");
1848 /* The FastCGI Protocol doesn't differentiate access control */
1849 fr->role = FCGI_AUTHORIZER;
1851 /* Do we need compatibility mode? */
1852 fr->auth_compat = (dir_config->authenticator_options & FCGI_COMPAT);
1854 if ((res = do_work(r, fr)) != OK)
1855 goto AccessFailed;
1857 access_allowed = (r->status == 200);
1858 post_process_auth(fr, access_allowed);
1860 /* A redirect shouldn't be allowed during the access check phase */
1861 if (ap_table_get(r->headers_out, "Location") != NULL) {
1862 ap_log_rerror(FCGI_LOG_ERR_NOERRNO, r,
1863 "FastCGI: FastCgiAccessChecker \"%s\" redirected (not allowed)",
1864 dir_config->access_checker);
1865 goto AccessFailed;
1868 if (access_allowed)
1869 return OK;
1871 AccessFailed:
1872 if (!(dir_config->access_checker_options & FCGI_AUTHORITATIVE))
1873 return DECLINED;
1875 /* @@@ Probably should support custom_responses */
1876 ap_log_rerror(FCGI_LOG_ERR_NOERRNO, r, "FastCGI: access denied: %s", r->uri);
1877 return (res == OK) ? FORBIDDEN : res;
1882 command_rec fastcgi_cmds[] = {
1883 { "AppClass", fcgi_config_new_static_server, NULL, RSRC_CONF, RAW_ARGS, NULL },
1884 { "FastCgiServer", fcgi_config_new_static_server, NULL, RSRC_CONF, RAW_ARGS, NULL },
1886 { "ExternalAppClass", fcgi_config_new_external_server, NULL, RSRC_CONF, RAW_ARGS, NULL },
1887 { "FastCgiExternalServer", fcgi_config_new_external_server, NULL, RSRC_CONF, RAW_ARGS, NULL },
1889 { "FastCgiIpcDir", fcgi_config_set_socket_dir, NULL, RSRC_CONF, TAKE1, NULL },
1891 { "FastCgiSuexec", fcgi_config_set_wrapper, NULL, RSRC_CONF, TAKE1, NULL },
1892 { "FastCgiWrapper", fcgi_config_set_wrapper, NULL, RSRC_CONF, TAKE1, NULL },
1894 { "FCGIConfig", fcgi_config_set_config, NULL, RSRC_CONF, RAW_ARGS, NULL },
1895 { "FastCgiConfig", fcgi_config_set_config, NULL, RSRC_CONF, RAW_ARGS, NULL },
1897 { "FastCgiAuthenticator", fcgi_config_new_auth_server,
1898 (void *)FCGI_AUTH_TYPE_AUTHENTICATOR, ACCESS_CONF, TAKE12,
1899 "a fastcgi-script path (absolute or relative to ServerRoot) followed by an optional -compat" },
1900 { "FastCgiAuthenticatorAuthoritative", fcgi_config_set_authoritative_slot,
1901 (void *)XtOffsetOf(fcgi_dir_config, authenticator_options), ACCESS_CONF, FLAG,
1902 "Set to 'off' to allow authentication to be passed along to lower modules upon failure" },
1904 { "FastCgiAuthorizer", fcgi_config_new_auth_server,
1905 (void *)FCGI_AUTH_TYPE_AUTHORIZER, ACCESS_CONF, TAKE12,
1906 "a fastcgi-script path (absolute or relative to ServerRoot) followed by an optional -compat" },
1907 { "FastCgiAuthorizerAuthoritative", fcgi_config_set_authoritative_slot,
1908 (void *)XtOffsetOf(fcgi_dir_config, authorizer_options), ACCESS_CONF, FLAG,
1909 "Set to 'off' to allow authorization to be passed along to lower modules upon failure" },
1911 { "FastCgiAccessChecker", fcgi_config_new_auth_server,
1912 (void *)FCGI_AUTH_TYPE_ACCESS_CHECKER, ACCESS_CONF, TAKE12,
1913 "a fastcgi-script path (absolute or relative to ServerRoot) followed by an optional -compat" },
1914 { "FastCgiAccessCheckerAuthoritative", fcgi_config_set_authoritative_slot,
1915 (void *)XtOffsetOf(fcgi_dir_config, access_checker_options), ACCESS_CONF, FLAG,
1916 "Set to 'off' to allow access control to be passed along to lower modules upon failure" },
1917 { NULL }
1921 handler_rec fastcgi_handlers[] = {
1922 { FCGI_MAGIC_TYPE, content_handler },
1923 { "fastcgi-script", content_handler },
1924 { NULL }
1928 module MODULE_VAR_EXPORT fastcgi_module = {
1929 STANDARD_MODULE_STUFF,
1930 init_module, /* initializer */
1931 fcgi_config_create_dir_config, /* per-dir config creator */
1932 NULL, /* per-dir config merger (default: override) */
1933 NULL, /* per-server config creator */
1934 NULL, /* per-server config merger (default: override) */
1935 fastcgi_cmds, /* command table */
1936 fastcgi_handlers, /* [9] content handlers */
1937 NULL, /* [2] URI-to-filename translation */
1938 check_user_authentication, /* [5] authenticate user_id */
1939 check_user_authorization, /* [6] authorize user_id */
1940 check_access, /* [4] check access (based on src & http headers) */
1941 NULL, /* [7] check/set MIME type */
1942 NULL, /* [8] fixups */
1943 NULL, /* [10] logger */
1944 NULL, /* [3] header-parser */
1945 fcgi_child_init, /* process initialization */
1946 fcgi_child_exit, /* process exit/cleanup */
1947 NULL /* [1] post read-request handling */