Prevent an assert from popping unnecessarily
[mod_fastcgi.git] / mod_fastcgi.c
bloba94255e66122be1afd080e07575dd9587c60057d
1 /*
2 * mod_fastcgi.c --
4 * Apache server module for FastCGI.
6 * $Id: mod_fastcgi.c,v 1.93 2000/05/24 15:09:39 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 * The Apache Timeout directive allows per-server configuration of
59 * the timeout associated with a request. This is typically used to
60 * detect dead clients. The timer is reset for every successful
61 * read/write. The default value is 5min. Thats way too long to tie
62 * up a FastCGI server. For now this dropdead timer is used a little
63 * differently in FastCGI. All of the FastCGI server I/O AND the
64 * client I/O must complete within Timeout seconds. This isn't
65 * exactly what we want.. it should be revisited. See http_main.h.
67 * We need a way to configurably control the timeout associated with
68 * FastCGI server exchanges AND one for client exchanges. This could
69 * be done with the select() in doWork() (which should be rewritten
70 * anyway). This will allow us to free up the FastCGI as soon as
71 * possible.
73 * Earlier versions of this module used ap_soft_timeout() rather than
74 * ap_hard_timeout() and ate FastCGI server output until it completed.
75 * This precluded the FastCGI server from having to implement a
76 * SIGPIPE handler, but meant hanging the application longer than
77 * necessary. SIGPIPE handler now must be installed in ALL FastCGI
78 * applications. The handler should abort further processing and go
79 * back into the accept() loop.
81 * Although using ap_soft_timeout() is better than ap_hard_timeout()
82 * we have to be more careful about SIGINT handling and subsequent
83 * processing, so, for now, make it hard.
87 #include "fcgi.h"
89 #ifndef timersub
90 #define timersub(a, b, result) \
91 do { \
92 (result)->tv_sec = (a)->tv_sec - (b)->tv_sec; \
93 (result)->tv_usec = (a)->tv_usec - (b)->tv_usec; \
94 if ((result)->tv_usec < 0) { \
95 --(result)->tv_sec; \
96 (result)->tv_usec += 1000000; \
97 } \
98 } while (0)
99 #endif
102 * Global variables
105 pool *fcgi_config_pool; /* the config pool */
106 server_rec *fcgi_apache_main_server;
108 const char *fcgi_suexec = NULL; /* suexec_bin path */
109 uid_t fcgi_user_id; /* the run uid of Apache & PM */
110 gid_t fcgi_group_id; /* the run gid of Apache & PM */
112 fcgi_server *fcgi_servers = NULL; /* AppClasses */
114 char *fcgi_socket_dir = DEFAULT_SOCK_DIR; /* default FastCgiIpcDir */
116 int fcgi_pm_pipe[2];
117 pid_t fcgi_pm_pid = -1;
119 char *fcgi_dynamic_dir = NULL; /* directory for the dynamic
120 * fastcgi apps' sockets */
122 #ifdef WIN32
123 fcgi_pm_job *fcgi_dynamic_mbox = NULL;
124 HANDLE *fcgi_dynamic_mbox_mutex = NULL;
125 HANDLE fcgi_pm_thread = INVALID_HANDLE_VALUE;
126 #endif
128 char *fcgi_empty_env = NULL;
130 u_int dynamicMaxProcs = FCGI_DEFAULT_MAX_PROCS;
131 u_int dynamicMinProcs = FCGI_DEFAULT_MIN_PROCS;
132 u_int dynamicMaxClassProcs = FCGI_DEFAULT_MAX_CLASS_PROCS;
133 u_int dynamicKillInterval = FCGI_DEFAULT_KILL_INTERVAL;
134 u_int dynamicUpdateInterval = FCGI_DEFAULT_UPDATE_INTERVAL;
135 float dynamicGain = FCGI_DEFAULT_GAIN;
136 u_int dynamicThreshhold1 = FCGI_DEFAULT_THRESHHOLD_1;
137 u_int dynamicThreshholdN = FCGI_DEFAULT_THRESHHOLD_N;
138 u_int dynamicPleaseStartDelay = FCGI_DEFAULT_START_PROCESS_DELAY;
139 u_int dynamicAppConnectTimeout = FCGI_DEFAULT_APP_CONN_TIMEOUT;
140 char **dynamicEnvp = &fcgi_empty_env;
141 u_int dynamicProcessSlack = FCGI_DEFAULT_PROCESS_SLACK;
142 int dynamicAutoRestart = FCGI_DEFAULT_RESTART_DYNAMIC;
143 int dynamicAutoUpdate = FCGI_DEFAULT_AUTOUPDATE;
144 u_int dynamicListenQueueDepth = FCGI_DEFAULT_LISTEN_Q;
145 u_int dynamicInitStartDelay = DEFAULT_INIT_START_DELAY;
146 u_int dynamicRestartDelay = FCGI_DEFAULT_RESTART_DELAY;
147 array_header *dynamic_pass_headers = NULL;
148 u_int dynamic_idle_timeout = FCGI_DEFAULT_IDLE_TIMEOUT;
150 /*******************************************************************************
151 * Construct a message and write it to the pm_pipe.
153 static void send_to_pm(pool * const p, const char id, const char * const fs_path,
154 const char *user, const char * const group, const unsigned long q_usec,
155 const unsigned long req_usec)
157 #ifdef WIN32
158 fcgi_pm_job *job = NULL;
160 if (!(job = (fcgi_pm_job *) malloc(sizeof(fcgi_pm_job))))
161 return;
162 #else
163 int buflen = 0;
164 char buf[FCGI_MAX_MSG_LEN];
165 #endif
167 if (strlen(fs_path) > FCGI_MAXPATH) {
168 ap_log_error(FCGI_LOG_ERR_NOERRNO, fcgi_apache_main_server,
169 "FastCGI: the path \"%s\" is too long (>%d) for a dynamic server", fs_path, FCGI_MAXPATH);
170 return;
173 switch(id) {
174 case PLEASE_START:
175 #ifdef WIN32
176 job->id = id;
177 job->fs_path = strdup(fs_path);
178 job->user = strdup(user);
179 job->group = strdup(group);
180 #else
181 buflen = sprintf(buf, "%c %s %s %s*", id, fs_path, user, group);
182 #endif
183 break;
184 case CONN_TIMEOUT:
185 #ifdef WIN32
186 job->id = id;
187 job->fs_path = strdup(fs_path);
188 job->user = strdup(user);
189 job->group = strdup(group);
190 #else
191 buflen = sprintf(buf, "%c %s %s %s*", id, fs_path, user, group);
192 #endif
193 break;
194 case REQ_COMPLETE:
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) == 0)
210 return;
212 SetEvent(fcgi_event_handles[MBOX_EVENT]);
213 #else
214 ap_assert(buflen <= FCGI_MAX_MSG_LEN);
216 if (write(fcgi_pm_pipe[1], (const void *)buf, buflen) != buflen) {
217 ap_log_error(FCGI_LOG_WARN, fcgi_apache_main_server,
218 "FastCGI: write() to PM failed");
220 #endif
225 *----------------------------------------------------------------------
227 * init_module
229 * An Apache module initializer, called by the Apache core
230 * after reading the server config.
232 * Start the process manager no matter what, since there may be a
233 * request for dynamic FastCGI applications without any being
234 * configured as static applications. Also, check for the existence
235 * and create if necessary a subdirectory into which all dynamic
236 * sockets will go.
238 *----------------------------------------------------------------------
240 static void init_module(server_rec *s, pool *p)
242 const char *err;
244 /* Register to reset to default values when the config pool is cleaned */
245 ap_block_alarms();
246 ap_register_cleanup(p, NULL, fcgi_config_reset_globals, ap_null_cleanup);
247 ap_unblock_alarms();
249 ap_add_version_component("mod_fastcgi/" MOD_FASTCGI_VERSION);
251 fcgi_config_set_fcgi_uid_n_gid(1);
253 /* keep these handy */
254 fcgi_config_pool = p;
255 fcgi_apache_main_server = s;
257 #ifndef WIN32
258 /* Create Unix/Domain socket directory */
259 if ((err = fcgi_config_make_dir(p, fcgi_socket_dir)))
260 ap_log_error(FCGI_LOG_ERR, s, "FastCGI: %s", err);
261 #endif
263 /* Create Dynamic directory */
264 if ((err = fcgi_config_make_dynamic_dir(p, 1)))
265 ap_log_error(FCGI_LOG_ERR, s, "FastCGI: %s", err);
267 #ifndef WIN32
268 /* Create the pipe for comm with the PM */
269 if (pipe(fcgi_pm_pipe) < 0) {
270 ap_log_error(FCGI_LOG_ERR, s, "FastCGI: pipe() failed");
273 /* Spawn the PM only once. Under Unix, Apache calls init() routines
274 * twice, once before detach() and once after. Win32 doesn't detach.
275 * Under DSO, DSO modules are unloaded between the two init() calls.
276 * Under Unix, the -X switch causes two calls to init() but no detach
277 * (but all subprocesses are wacked so the PM is toasted anyway)! */
279 if (ap_standalone && getppid() != 1)
280 return;
282 /* Start the Process Manager */
283 fcgi_pm_pid = ap_spawn_child(p, fcgi_pm_main, NULL, kill_only_once, NULL, NULL, NULL);
284 if (fcgi_pm_pid <= 0) {
285 ap_log_error(FCGI_LOG_ALERT, s,
286 "FastCGI: can't start the process manager, spawn_child() failed");
289 close(fcgi_pm_pipe[0]);
290 #endif
293 static void fcgi_child_init(server_rec *server_conf, pool *p)
295 #ifdef WIN32
296 DWORD tid;
298 /* Create the Event Handlers */
299 fcgi_event_handles[0] = CreateEvent(NULL, FALSE, FALSE, NULL);
300 fcgi_event_handles[1] = CreateEvent(NULL, FALSE, FALSE, NULL);
301 fcgi_event_handles[2] = CreateEvent(NULL, FALSE, FALSE, NULL);
302 fcgi_dynamic_mbox_mutex = CreateMutex(FALSE, FALSE, NULL);
304 /* Spawn of the process manager thread */
305 fcgi_pm_thread = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)fcgi_pm_main, NULL, 0, &tid);
306 #endif
307 return;
310 static void fcgi_child_exit(server_rec *server_conf, pool *p) {
312 #ifdef WIN32
313 /* Signaling the PM thread tp exit*/
314 SetEvent(fcgi_event_handles[TERM_EVENT]);
316 /* Waiting on pm thread to exit */
317 WaitForSingleObject(fcgi_pm_thread, INFINITE);
318 #endif
320 return;
324 *----------------------------------------------------------------------
326 * get_header_line --
328 * Terminate a line: scan to the next newline, scan back to the
329 * first non-space character and store a terminating zero. Return
330 * the next character past the end of the newline.
332 * If the end of the string is reached, ASSERT!
334 * If the FIRST character(s) in the line are '\n' or "\r\n", the
335 * first character is replaced with a NULL and next character
336 * past the newline is returned. NOTE: this condition supercedes
337 * the processing of RFC-822 continuation lines.
339 * If continuation is set to 'TRUE', then it parses a (possible)
340 * sequence of RFC-822 continuation lines.
342 * Results:
343 * As above.
345 * Side effects:
346 * Termination byte stored in string.
348 *----------------------------------------------------------------------
350 static char *get_header_line(char *start, int continuation)
352 char *p = start;
353 char *end = start;
355 if(p[0] == '\r' && p[1] == '\n') { /* If EOL in 1st 2 chars */
356 p++; /* point to \n and stop */
357 } else if(*p != '\n') {
358 if(continuation) {
359 while(*p != '\0') {
360 if(*p == '\n' && p[1] != ' ' && p[1] != '\t')
361 break;
362 p++;
364 } else {
365 while(*p != '\0' && *p != '\n') {
366 p++;
371 ap_assert(*p != '\0');
372 end = p;
373 end++;
376 * Trim any trailing whitespace.
378 while(isspace((unsigned char)p[-1]) && p > start) {
379 p--;
382 *p = '\0';
383 return end;
387 *----------------------------------------------------------------------
389 * process_headers --
391 * Call with r->parseHeader == SCAN_CGI_READING_HEADERS
392 * and initial script output in fr->header.
394 * If the initial script output does not include the header
395 * terminator ("\r\n\r\n") process_headers returns with no side
396 * effects, to be called again when more script output
397 * has been appended to fr->header.
399 * If the initial script output includes the header terminator,
400 * process_headers parses the headers and determines whether or
401 * not the remaining script output will be sent to the client.
402 * If so, process_headers sends the HTTP response headers to the
403 * client and copies any non-header script output to the output
404 * buffer reqOutbuf.
406 * Results:
407 * none.
409 * Side effects:
410 * May set r->parseHeader to:
411 * SCAN_CGI_FINISHED -- headers parsed, returning script response
412 * SCAN_CGI_BAD_HEADER -- malformed header from script
413 * SCAN_CGI_INT_REDIRECT -- handler should perform internal redirect
414 * SCAN_CGI_SRV_REDIRECT -- handler should return REDIRECT
416 *----------------------------------------------------------------------
419 static const char *process_headers(request_rec *r, fcgi_request *fr)
421 char *p, *next, *name, *value;
422 int len, flag;
423 int hasContentType, hasStatus, hasLocation;
425 ap_assert(fr->parseHeader == SCAN_CGI_READING_HEADERS);
427 if (fr->header == NULL)
428 return NULL;
431 * Do we have the entire header? Scan for the blank line that
432 * terminates the header.
434 p = (char *)fr->header->elts;
435 len = fr->header->nelts;
436 flag = 0;
437 while(len-- && flag < 2) {
438 switch(*p) {
439 case '\r':
440 break;
441 case '\n':
442 flag++;
443 break;
444 case '\0':
445 case '\v':
446 case '\f':
447 name = "Invalid Character";
448 goto BadHeader;
449 break;
450 default:
451 flag = 0;
452 break;
454 p++;
457 /* Return (to be called later when we have more data)
458 * if we don't have an entire header. */
459 if (flag < 2)
460 return NULL;
463 * Parse all the headers.
465 fr->parseHeader = SCAN_CGI_FINISHED;
466 hasContentType = hasStatus = hasLocation = FALSE;
467 next = (char *)fr->header->elts;
468 for(;;) {
469 next = get_header_line(name = next, TRUE);
470 if (*name == '\0') {
471 break;
473 if ((p = strchr(name, ':')) == NULL) {
474 goto BadHeader;
476 value = p + 1;
477 while (p != name && isspace((unsigned char)*(p - 1))) {
478 p--;
480 if (p == name) {
481 goto BadHeader;
483 *p = '\0';
484 if (strpbrk(name, " \t") != NULL) {
485 *p = ' ';
486 goto BadHeader;
488 while (isspace((unsigned char)*value)) {
489 value++;
492 if (strcasecmp(name, "Status") == 0) {
493 int statusValue = strtol(value, NULL, 10);
495 if (hasStatus) {
496 goto DuplicateNotAllowed;
498 if (statusValue < 0) {
499 fr->parseHeader = SCAN_CGI_BAD_HEADER;
500 return ap_psprintf(r->pool, "invalid Status '%s'", value);
502 hasStatus = TRUE;
503 r->status = statusValue;
504 r->status_line = ap_pstrdup(r->pool, value);
505 continue;
508 if (fr->role == FCGI_RESPONDER) {
509 if (strcasecmp(name, "Content-type") == 0) {
510 if (hasContentType) {
511 goto DuplicateNotAllowed;
513 hasContentType = TRUE;
514 r->content_type = ap_pstrdup(r->pool, value);
515 continue;
518 if (strcasecmp(name, "Location") == 0) {
519 if (hasLocation) {
520 goto DuplicateNotAllowed;
522 hasLocation = TRUE;
523 ap_table_set(r->headers_out, "Location", value);
524 continue;
527 /* If the script wants them merged, it can do it */
528 ap_table_add(r->err_headers_out, name, value);
529 continue;
531 else {
532 ap_table_add(fr->authHeaders, name, value);
536 if (fr->role != FCGI_RESPONDER)
537 return NULL;
540 * Who responds, this handler or Apache?
542 if (hasLocation) {
543 const char *location = ap_table_get(r->headers_out, "Location");
545 * Based on internal redirect handling in mod_cgi.c...
547 * If a script wants to produce its own Redirect
548 * body, it now has to explicitly *say* "Status: 302"
550 if (r->status == 200) {
551 if(location[0] == '/') {
553 * Location is an relative path. This handler will
554 * consume all script output, then have Apache perform an
555 * internal redirect.
557 fr->parseHeader = SCAN_CGI_INT_REDIRECT;
558 return NULL;
559 } else {
561 * Location is an absolute URL. If the script didn't
562 * produce a Content-type header, this handler will
563 * consume all script output and then have Apache generate
564 * its standard redirect response. Otherwise this handler
565 * will transmit the script's response.
567 fr->parseHeader = SCAN_CGI_SRV_REDIRECT;
568 return NULL;
573 * We're responding. Send headers, buffer excess script output.
575 ap_send_http_header(r);
577 /* We need to reinstate our timeout, send_http_header() kill()s it */
578 ap_hard_timeout("FastCGI request processing", r);
580 if (r->header_only)
581 return NULL;
583 len = fr->header->nelts - (next - fr->header->elts);
584 ap_assert(len >= 0);
585 ap_assert(BufferLength(fr->clientOutputBuffer) == 0);
586 if (BufferFree(fr->clientOutputBuffer) < len) {
587 fr->clientOutputBuffer = fcgi_buf_new(r->pool, len);
589 ap_assert(BufferFree(fr->clientOutputBuffer) >= len);
590 if (len > 0) {
591 int sent = fcgi_buf_add_block(fr->clientOutputBuffer, next, len);
592 ap_assert(sent == len);
594 return NULL;
596 BadHeader:
597 /* Log first line of a multi-line header */
598 if ((p = strpbrk(name, "\r\n")) != NULL)
599 *p = '\0';
600 fr->parseHeader = SCAN_CGI_BAD_HEADER;
601 return ap_psprintf(r->pool, "malformed header '%s'", name);
603 DuplicateNotAllowed:
604 fr->parseHeader = SCAN_CGI_BAD_HEADER;
605 return ap_psprintf(r->pool, "duplicate header '%s'", name);
609 * Read from the client filling both the FastCGI server buffer and the
610 * client buffer with the hopes of buffering the client data before
611 * making the connect() to the FastCGI server. This prevents slow
612 * clients from keeping the FastCGI server in processing longer than is
613 * necessary.
615 static int read_from_client_n_queue(fcgi_request *fr)
617 char *end;
618 unsigned int count;
619 long int countRead;
621 while (BufferFree(fr->clientInputBuffer) > 0 || BufferFree(fr->serverOutputBuffer) > 0) {
622 fcgi_protocol_queue_client_buffer(fr);
624 if (fr->expectingClientContent <= 0)
625 return OK;
627 fcgi_buf_get_free_block_info(fr->clientInputBuffer, &end, &count);
628 if (count == 0)
629 return OK;
631 if ((countRead = ap_get_client_block(fr->r, end, count)) < 0)
632 return -1;
634 if (countRead == 0)
635 fr->expectingClientContent = 0;
636 else
637 fcgi_buf_add_update(fr->clientInputBuffer, countRead);
640 return OK;
643 static int write_to_client(fcgi_request *fr)
645 char *begin;
646 unsigned int count;
648 fcgi_buf_get_block_info(fr->clientOutputBuffer, &begin, &count);
649 if (count == 0)
650 return OK;
652 /* If fewer than count bytes are written, an error occured.
653 * ap_bwrite() typically forces a flushed write to the client, this
654 * effectively results in a block (and short packets) - it should
655 * be fixed, but I didn't win much support for the idea on new-httpd.
656 * So, without patching Apache, the best way to deal with this is
657 * to size the fcgi_bufs to hold all of the script output (within
658 * reason) so the script can be released from having to wait around
659 * for the transmission to the client to complete. */
660 #ifdef RUSSIAN_APACHE
661 if (ap_rwrite(begin, count, fr->r) != count) {
662 ap_log_rerror(FCGI_LOG_INFO, fr->r,
663 "FastCGI: client stopped connection before send body completed");
664 return -1;
666 #else
667 if (ap_bwrite(fr->r->connection->client, begin, count) != (int) count) {
668 ap_log_rerror(FCGI_LOG_INFO, fr->r,
669 "FastCGI: client stopped connection before send body completed");
670 return -1;
672 #endif
675 /* Don't bother with a wrapped buffer, limiting exposure to slow
676 * clients. The BUFF routines don't allow a writev from above,
677 * and don't always memcpy to minimize small write()s, this should
678 * be fixed, but I didn't win much support for the idea on
679 * new-httpd - I'll have to _prove_ its a problem first.. */
681 /* The default behaviour used to be to flush with every write, but this
682 * can tie up the FastCGI server longer than is necessary so its an option now */
683 if (fr->fs && fr->fs->flush) {
684 #ifdef RUSSIAN_APACHE
685 if (ap_rflush(fr->r)) {
686 ap_log_rerror(FCGI_LOG_INFO, fr->r,
687 "FastCGI: client stopped connection before send body completed");
688 return -1;
690 #else
691 if (ap_bflush(fr->r->connection->client)) {
692 ap_log_rerror(FCGI_LOG_INFO, fr->r,
693 "FastCGI: client stopped connection before send body completed");
694 return -1;
696 #endif
699 fcgi_buf_toss(fr->clientOutputBuffer, count);
700 return OK;
703 /*******************************************************************************
704 * Determine the user and group suexec should be called with.
705 * Based on code in Apache's create_argv_cmd() (util_script.c).
707 static void set_uid_n_gid(request_rec *r, const char **user, const char **group)
709 if (fcgi_suexec == NULL) {
710 *user = "-";
711 *group = "-";
712 return;
715 if (strncmp("/~", r->uri, 2) == 0) {
716 /* its a user dir uri, just send the ~user, and leave it to the PM */
717 char *end = strchr(r->uri + 2, '/');
719 if (end)
720 *user = memcpy(ap_pcalloc(r->pool, end - r->uri), r->uri + 1, end - r->uri - 1);
721 else
722 *user = ap_pstrdup(r->pool, r->uri + 1);
723 *group = "-";
725 else {
726 *user = ap_psprintf(r->pool, "%ld", (long)r->server->server_uid);
727 *group = ap_psprintf(r->pool, "%ld", (long)r->server->server_gid);
731 /*******************************************************************************
732 * Close the connection to the FastCGI server. This is normally called by
733 * do_work(), but may also be called as in request pool cleanup.
735 static void close_connection_to_fs(fcgi_request *fr)
737 pool *rp = fr->r->pool;
739 if (fr->fd != -1)
740 ap_pclosesocket(rp, fr->fd);
742 if (fr->dynamic) {
743 #ifdef WIN32
744 fcgi_rdwr_unlock(fr->lockFd, READER);
745 #else
746 ap_pclosef(rp, fr->lockFd);
747 #endif
749 if (fr->keepReadingFromFcgiApp == FALSE) {
750 /* XXX REQ_COMPLETE is only sent for requests which complete
751 * normally WRT the fcgi app. There is no data sent for
752 * connect() timeouts or requests which complete abnormally.
753 * KillDynamicProcs() and RemoveRecords() need to be looked at
754 * to be sure they can reasonably handle these cases before
755 * sending these sort of stats - theres some funk in there.
756 * XXX We should do something special when this a pool cleanup.
758 if (fcgi_util_gettimeofday(&fr->completeTime) < 0) {
759 /* there's no point to aborting the request, just log it */
760 ap_log_error(FCGI_LOG_ERR, fr->r->server, "FastCGI: gettimeofday() failed");
761 } else {
762 struct timeval qtime, rtime;
764 timersub(&fr->queueTime, &fr->startTime, &qtime);
765 timersub(&fr->completeTime, &fr->queueTime, &rtime);
767 send_to_pm(rp, REQ_COMPLETE, fr->fs_path,
768 fr->user, fr->group,
769 qtime.tv_sec * 1000000 + qtime.tv_usec,
770 rtime.tv_sec * 1000000 + rtime.tv_usec);
776 /*******************************************************************************
777 * Connect to the FastCGI server.
779 static const char *open_connection_to_fs(fcgi_request *fr)
781 struct timeval tval;
782 fd_set write_fds, read_fds;
783 int status;
784 request_rec * const r = fr->r;
785 pool * const rp = r->pool;
786 const char *socket_path = NULL;
787 struct sockaddr *socket_addr = NULL;
788 int socket_addr_len = 0;
789 #ifdef WIN32
790 unsigned long ioctl_arg;
791 int errcode;
792 #else
793 int fd_flags = 0;
794 const char *err = NULL;
795 #endif
797 /* Create the connection point */
798 if (fr->dynamic) {
799 socket_path = fcgi_util_socket_hash_filename(rp, fr->fs_path, fr->user, fr->group);
800 socket_path = fcgi_util_socket_make_path_absolute(rp, socket_path, 1);
802 #ifndef WIN32
803 err = fcgi_util_socket_make_domain_addr(rp, (struct sockaddr_un **)&socket_addr,
804 &socket_addr_len, socket_path);
805 if (err)
806 return err;
807 #endif
808 } else {
809 #ifdef WIN32
810 if (fr->fs->dest_addr != NULL) {
811 socket_addr = fr->fs->dest_addr;
813 else if (fr->fs->socket_addr) {
814 socket_addr = fr->fs->socket_addr;
816 else {
817 socket_path = fr->fs->socket_path;
819 #else
820 socket_addr = fr->fs->socket_addr;
821 #endif
822 socket_addr_len = fr->fs->socket_addr_len;
825 /* Dynamic app's lockfile handling */
826 if (fr->dynamic) {
827 #ifndef WIN32
828 const char *lockFileName = fcgi_util_socket_get_lock_filename(rp, socket_path);
829 struct stat lstbuf;
830 #endif
831 struct stat bstbuf;
832 int result = 0;
834 do {
835 #ifdef WIN32
836 if (fr->fs != NULL)
837 #else
838 if (stat(lockFileName, &lstbuf) == 0 && S_ISREG(lstbuf.st_mode))
839 #endif
841 if (dynamicAutoUpdate && (stat(fr->fs_path, &bstbuf) == 0)
842 #ifdef WIN32
843 && ((fr->fs->restartTime > 0) && (fr->fs->restartTime < bstbuf.st_mtime)))
844 #else
845 && (lstbuf.st_mtime < bstbuf.st_mtime))
846 #endif
848 struct timeval tv = {1, 0};
850 /* Its already running, but there's a newer one,
851 * ask the process manager to start it.
852 * it will notice that the binary is newer,
853 * and do a restart instead.
855 send_to_pm(rp, PLEASE_START, fr->fs_path, fr->user, fr->group, 0, 0);
857 /* Avoid sleep/alarm interactions */
858 ap_select(0, NULL, NULL, NULL, &tv);
860 #ifdef WIN32
861 fr->lockFd = fr->fs->dynamic_lock;
862 result = 1;
863 #else
864 fr->lockFd = ap_popenf(rp, lockFileName, O_APPEND, 0);
865 result = (fr->lockFd < 0) ? (0) : (1);
866 #endif
867 } else {
868 struct timeval tv = {1, 0};
870 send_to_pm(rp, PLEASE_START, fr->fs_path, fr->user, fr->group, 0, 0);
872 #ifdef WIN32
873 Sleep(0);
874 #else
875 /* Avoid sleep/alarm interactions */
876 ap_select(0, NULL, NULL, NULL, &tv);
877 #endif
879 #ifdef WIN32
880 fr->fs = fcgi_util_fs_get_by_id(fr->fs_path, 0, 0);
881 #endif
882 } while (result != 1);
884 /* Block until we get a shared (non-exclusive) read Lock */
885 if (fcgi_wait_for_shared_read_lock(fr->lockFd) < 0)
886 return "failed to obtain a shared read lock on server lockfile";
889 #ifdef WIN32
890 if (socket_path) {
892 if (fr->dynamic && fcgi_util_gettimeofday(&fr->startTime) < 0)
893 return "gettimeofday() failed";
895 if ((fr->dynamic && dynamicAppConnectTimeout) || (!fr->dynamic && fr->fs->appConnectTimeout)) {
896 DWORD interval = (fr->dynamic ? dynamicAppConnectTimeout : fr->fs->appConnectTimeout) * 1000;
898 if (!WaitNamedPipe(socket_path, interval))
899 return "named pipe failed to connect()";
901 else {
902 if (! WaitNamedPipe(socket_path, NMPWAIT_WAIT_FOREVER) ) {
903 errcode = GetLastError();
904 return "named pipe failed to connect()";
908 fr->fd = (int) CreateFile(socket_path, GENERIC_READ | GENERIC_WRITE,
909 FILE_SHARE_READ | FILE_SHARE_WRITE, NULL,
910 OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
912 if ((HANDLE)fr->fd == INVALID_HANDLE_VALUE) {
913 errno = GetLastError();
914 return "CreateFile() failed";
917 ap_note_cleanups_for_h(rp, (HANDLE)fr->fd);
919 fr->using_npipe_io = TRUE;
921 if (fcgi_util_gettimeofday(&fr->queueTime) < 0)
922 return "gettimeofday() failed";
925 return NULL;
927 #endif
929 /* Create the socket */
930 fr->fd = ap_psocket(rp, socket_addr->sa_family, SOCK_STREAM, 0);
932 if (fr->fd < 0)
933 return "ap_psocket() failed";
935 #ifndef WIN32
936 if (fr->fd >= FD_SETSIZE) {
937 return ap_psprintf(rp, "socket file descriptor (%u) is larger than "
938 "FD_SETSIZE (%u), you probably need to rebuild Apache with a "
939 "larger FD_SETSIZE", fr->fd, FD_SETSIZE);
941 #endif
943 /* If appConnectTimeout is non-zero, setup do a non-blocking connect */
944 if ((fr->dynamic && dynamicAppConnectTimeout) || (!fr->dynamic && fr->fs->appConnectTimeout)) {
945 #ifndef WIN32
946 if ((fd_flags = fcntl(fr->fd, F_GETFL, 0)) < 0)
947 return "fcntl(F_GETFL) failed";
948 if (fcntl(fr->fd, F_SETFL, fd_flags | O_NONBLOCK) < 0)
949 return "fcntl(F_SETFL) failed";
950 #else
951 ioctl_arg =1;
952 if (ioctlsocket(fr->fd, FIONBIO, &ioctl_arg) != 0)
953 return "ioctlsocket(FIONBIO) failed";
954 #endif
957 if (fr->dynamic && fcgi_util_gettimeofday(&fr->startTime) < 0)
958 return "gettimeofday() failed";
960 /* Connect */
961 if (connect(fr->fd, (struct sockaddr *)socket_addr, socket_addr_len) == 0)
962 goto ConnectionComplete;
964 #ifdef WIN32
965 errcode = GetLastError();
966 if (errcode != WSAEWOULDBLOCK)
967 return "connect() failed";
968 #else
969 /* ECONNREFUSED means the listen queue is full (or there isn't one).
970 * With dynamic I can at least make sure the PM knows this is occuring */
971 if (fr->dynamic && errno == ECONNREFUSED) {
972 /* @@@ This might be better as some other "kind" of message */
973 send_to_pm(rp, CONN_TIMEOUT, fr->fs_path, fr->user, fr->group, 0, 0);
975 errno = ECONNREFUSED;
978 if (errno != EINPROGRESS)
979 return "connect() failed";
980 #endif
982 /* The connect() is non-blocking */
984 errno = 0;
986 if (fr->dynamic) {
987 do {
988 FD_ZERO(&write_fds);
989 FD_SET(fr->fd, &write_fds);
990 read_fds = write_fds;
991 tval.tv_sec = dynamicPleaseStartDelay;
992 tval.tv_usec = 0;
994 status = ap_select((fr->fd+1), &read_fds, &write_fds, NULL, &tval);
995 if (status < 0)
996 break;
998 if (fcgi_util_gettimeofday(&fr->queueTime) < 0)
999 return "gettimeofday() failed";
1000 if (status > 0)
1001 break;
1003 /* select() timed out */
1004 send_to_pm(rp, CONN_TIMEOUT, fr->fs_path, fr->user, fr->group, 0, 0);
1005 } while ((fr->queueTime.tv_sec - fr->startTime.tv_sec) < (int)dynamicAppConnectTimeout);
1007 /* XXX These can be moved down when dynamic vars live is a struct */
1008 if (status == 0) {
1009 return ap_psprintf(rp, "connect() timed out (appConnTimeout=%dsec)",
1010 dynamicAppConnectTimeout);
1012 } /* dynamic */
1013 else {
1014 tval.tv_sec = fr->fs->appConnectTimeout;
1015 tval.tv_usec = 0;
1016 FD_ZERO(&write_fds);
1017 FD_SET(fr->fd, &write_fds);
1018 read_fds = write_fds;
1020 status = ap_select((fr->fd+1), &read_fds, &write_fds, NULL, &tval);
1021 if (status == 0) {
1022 return ap_psprintf(rp, "connect() timed out (appConnTimeout=%dsec)",
1023 fr->fs->appConnectTimeout);
1025 } /* !dynamic */
1027 if (status < 0)
1028 return "select() failed";
1030 if (FD_ISSET(fr->fd, &write_fds) || FD_ISSET(fr->fd, &read_fds)) {
1031 int error = 0;
1032 NET_SIZE_T len = sizeof(error);
1034 if (getsockopt(fr->fd, SOL_SOCKET, SO_ERROR, (char *)&error, &len) < 0)
1035 /* Solaris pending error */
1036 return "select() failed (Solaris pending error)";
1038 if (error != 0) {
1039 /* Berkeley-derived pending error */
1040 errno = error;
1041 return "select() failed (pending error)";
1043 } else
1044 return "select() error - THIS CAN'T HAPPEN!";
1046 ConnectionComplete:
1047 /* Return to blocking mode if it was set up */
1048 if ((fr->dynamic && dynamicAppConnectTimeout) || (!fr->dynamic && fr->fs->appConnectTimeout)) {
1049 #ifdef WIN32
1050 ioctl_arg = 0;
1051 if (ioctlsocket(fr->fd, FIONBIO, &ioctl_arg) != 0)
1052 return "ioctlsocket(FIONBIO) failed";
1053 #else
1054 if ((fcntl(fr->fd, F_SETFL, fd_flags)) < 0)
1055 return "fcntl(F_SETFL) failed";
1056 #endif
1059 #ifdef TCP_NODELAY
1060 if (socket_addr->sa_family == AF_INET) {
1061 /* We shouldn't be sending small packets and there's no application
1062 * level ack of the data we send, so disable Nagle */
1063 int set = 1;
1064 setsockopt(fr->fd, IPPROTO_TCP, TCP_NODELAY, (char *)&set, sizeof(set));
1066 #endif
1068 return NULL;
1071 static int server_error(fcgi_request *fr)
1073 #if defined(SIGPIPE) && MODULE_MAGIC_NUMBER < 19990320
1074 /* Make sure we leave with Apache's sigpipe_handler in place */
1075 if (fr->apache_sigpipe_handler != NULL)
1076 signal(SIGPIPE, fr->apache_sigpipe_handler);
1077 #endif
1078 close_connection_to_fs(fr);
1079 ap_kill_timeout(fr->r);
1080 return SERVER_ERROR;
1083 static void log_fcgi_server_stderr(void *data)
1085 const fcgi_request * const fr = (fcgi_request *)data;
1087 if (fr == NULL)
1088 return ;
1090 if (fr->fs_stderr_len) {
1091 ap_log_rerror(FCGI_LOG_ERR_NOERRNO, fr->r,
1092 "FastCGI: server \"%s\" stderr: %s", fr->fs_path, fr->fs_stderr);
1096 /*----------------------------------------------------------------------
1097 * This is the core routine for moving data between the FastCGI
1098 * application and the Web server's client.
1100 static int do_work(request_rec *r, fcgi_request *fr)
1102 struct timeval timeOut, dynamic_last_activity_time = {0, 0};
1103 fd_set read_set, write_set;
1104 int status = 0, idle_timeout;
1105 int numFDs, dynamic_first_read = fr->dynamic ? 1 : 0;
1106 int doClientWrite;
1107 int envSent = FALSE; /* has the complete ENV been buffered? */
1108 env_status env;
1109 pool *rp = r->pool;
1110 const char *err = NULL;
1112 FD_ZERO(&read_set);
1113 FD_ZERO(&write_set);
1115 fcgi_protocol_queue_begin_request(fr);
1117 /* Buffer as much of the environment as we can fit */
1118 env.envp = NULL;
1119 envSent = fcgi_protocol_queue_env(r, fr, &env);
1121 /* Start the Apache dropdead timer. See comments at top of file. */
1122 ap_hard_timeout("buffering of FastCGI client data", r);
1124 /* Read as much as possible from the client. */
1125 if (fr->role == FCGI_RESPONDER) {
1126 status = ap_setup_client_block(r, REQUEST_CHUNKED_ERROR);
1127 if (status != OK) {
1128 ap_kill_timeout(r);
1129 return status;
1131 fr->expectingClientContent = (ap_should_client_block(r) != 0);
1133 if (read_from_client_n_queue(fr) != OK)
1134 return server_error(fr);
1137 /* Connect to the FastCGI Application */
1138 ap_hard_timeout("connect() to FastCGI server", r);
1139 if ((err = open_connection_to_fs(fr))) {
1140 ap_log_rerror(FCGI_LOG_ERR, r,
1141 "FastCGI: failed to connect to server \"%s\": %s", fr->fs_path, err);
1142 return server_error(fr);
1145 numFDs = fr->fd + 1;
1146 idle_timeout = fr->dynamic ? dynamic_idle_timeout : fr->fs->idle_timeout;
1148 if (dynamic_first_read) {
1149 dynamic_last_activity_time = fr->startTime;
1151 if (dynamicAppConnectTimeout) {
1152 struct timeval qwait;
1153 timersub(&fr->queueTime, &fr->startTime, &qwait);
1154 dynamic_first_read = qwait.tv_sec / dynamicPleaseStartDelay + 1;
1158 /* @@@ We never reset the timer in this loop, most folks don't mess w/
1159 * Timeout directive which means we've got the 5 min default which is way
1160 * to long to tie up a fs. We need a better/configurable solution that
1161 * uses the select */
1162 ap_hard_timeout("FastCGI request processing", r);
1164 /* Register to get the script's stderr logged at the end of the request */
1165 ap_block_alarms();
1166 ap_register_cleanup(rp, (void *)fr, log_fcgi_server_stderr, ap_null_cleanup);
1167 ap_unblock_alarms();
1169 /* The socket is writeable, so get the first write out of the way */
1170 if (fcgi_buf_get_to_fd(fr->serverOutputBuffer, fr->fd) < 0) {
1171 ap_log_rerror(FCGI_LOG_ERR, r,
1172 "FastCGI: comm with server \"%s\" aborted: write failed", fr->fs_path);
1173 return server_error(fr);
1176 while (fr->keepReadingFromFcgiApp
1177 || BufferLength(fr->serverInputBuffer) > 0
1178 || BufferLength(fr->clientOutputBuffer) > 0) {
1180 /* If we didn't buffer all of the environment yet, buffer some more */
1181 if (!envSent)
1182 envSent = fcgi_protocol_queue_env(r, fr, &env);
1184 /* Read as much as possible from the client. */
1185 if (fr->role == FCGI_RESPONDER && !fr->eofSent && envSent) {
1186 if (read_from_client_n_queue(fr) != OK)
1187 return server_error(fr);
1190 /* To avoid deadlock, don't do a blocking select to write to
1191 * the FastCGI application without selecting to read from the
1192 * FastCGI application.
1194 doClientWrite = FALSE;
1195 if (fr->keepReadingFromFcgiApp && BufferFree(fr->serverInputBuffer) > 0) {
1197 #ifdef WIN32
1198 if (!fr->using_npipe_io) {
1199 #endif
1200 FD_SET(fr->fd, &read_set);
1202 /* Is data buffered for output to the FastCGI server? */
1203 if (BufferLength(fr->serverOutputBuffer) > 0) {
1204 FD_SET(fr->fd, &write_set);
1205 } else {
1206 FD_CLR(fr->fd, &write_set);
1208 #ifdef WIN32
1210 #endif
1212 * If there's data buffered to send to the client, don't
1213 * wait indefinitely for the FastCGI app; the app might
1214 * be doing server push.
1216 if (BufferLength(fr->clientOutputBuffer) > 0) {
1217 timeOut.tv_sec = 0;
1218 timeOut.tv_usec = 100000; /* 0.1 sec */
1220 else if (dynamic_first_read) {
1221 int delay;
1222 struct timeval qwait;
1224 if (fcgi_util_gettimeofday(&fr->queueTime) < 0) {
1225 ap_log_rerror(FCGI_LOG_ERR, r, "FastCGI: gettimeofday() failed");
1226 return server_error(fr);
1229 /* Check for idle_timeout */
1230 if (status) {
1231 dynamic_last_activity_time = fr->queueTime;
1233 else {
1234 struct timeval idle_time;
1235 timersub(&fr->queueTime, &dynamic_last_activity_time, &idle_time);
1236 if (idle_time.tv_sec > idle_timeout) {
1237 send_to_pm(rp, CONN_TIMEOUT, fr->fs_path, fr->user, fr->group, 0, 0);
1238 ap_log_rerror(FCGI_LOG_ERR, r,
1239 "FastCGI: comm with (dynamic) server \"%s\" aborted: (first read) idle timeout (%d sec)",
1240 fr->fs_path, idle_timeout);
1241 return server_error(fr);
1245 timersub(&fr->queueTime, &fr->startTime, &qwait);
1247 delay = dynamic_first_read * dynamicPleaseStartDelay;
1248 if (qwait.tv_sec < delay) {
1249 timeOut.tv_sec = delay;
1250 timeOut.tv_usec = 100000; /* fudge for select() slop */
1251 timersub(&timeOut, &qwait, &timeOut);
1253 else {
1254 /* Killed time somewhere.. client read? */
1255 send_to_pm(rp, CONN_TIMEOUT, fr->fs_path, fr->user, fr->group, 0, 0);
1256 dynamic_first_read = qwait.tv_sec / dynamicPleaseStartDelay + 1;
1257 timeOut.tv_sec = dynamic_first_read * dynamicPleaseStartDelay;
1258 timeOut.tv_usec = 100000; /* fudge for select() slop */
1259 timersub(&timeOut, &qwait, &timeOut);
1262 else {
1263 timeOut.tv_sec = idle_timeout;
1264 timeOut.tv_usec = 0;
1267 #ifdef WIN32
1268 if (!fr->using_npipe_io) {
1269 #endif
1270 if ((status = ap_select(numFDs, &read_set, &write_set, NULL, &timeOut)) < 0) {
1271 ap_log_rerror(FCGI_LOG_ERR, r,
1272 "FastCGI: comm with server \"%s\" aborted: select() failed", fr->fs_path);
1273 return server_error(fr);
1275 #ifdef WIN32
1277 else {
1278 int stopTime = time(NULL) + timeOut.tv_sec;
1279 DWORD bytesavail=0;
1281 if (!(BufferLength(fr->serverOutputBuffer) > 0)) {
1282 status = 0;
1284 while ((timeOut.tv_sec != 0) && (time(NULL) <= stopTime)) {
1285 if (PeekNamedPipe((HANDLE) fr->fd,NULL, 0, NULL, &bytesavail, NULL) &&
1286 bytesavail > 0)
1288 status =1;
1289 break;
1291 Sleep(100);
1294 else {
1295 status = 1;
1298 #endif
1300 if (status == 0) {
1301 if (BufferLength(fr->clientOutputBuffer) > 0) {
1302 doClientWrite = TRUE;
1304 else if (dynamic_first_read) {
1305 struct timeval qwait;
1307 if (fcgi_util_gettimeofday(&fr->queueTime) < 0) {
1308 ap_log_rerror(FCGI_LOG_ERR, r, "FastCGI: gettimeofday() failed");
1309 return server_error(fr);
1312 timersub(&fr->queueTime, &fr->startTime, &qwait);
1314 send_to_pm(rp, CONN_TIMEOUT, fr->fs_path, fr->user, fr->group, 0, 0);
1316 dynamic_first_read = qwait.tv_sec / dynamicPleaseStartDelay + 1;
1318 else {
1319 ap_log_rerror(FCGI_LOG_ERR, r,
1320 "FastCGI: comm with server \"%s\" aborted: idle timeout (%d sec)",
1321 fr->fs_path, idle_timeout);
1322 return server_error(fr);
1326 #if defined(SIGPIPE) && MODULE_MAGIC_NUMBER < 19990320
1327 /* Disable Apache's SIGPIPE handler */
1328 fr->apache_sigpipe_handler = signal(SIGPIPE, SIG_IGN);
1329 #endif
1331 /* Read from the FastCGI server */
1332 #ifdef WIN32
1333 if (((fr->using_npipe_io) &&
1334 (BufferFree(fr->serverInputBuffer) > 0)) || FD_ISSET(fr->fd, &read_set)) {
1335 #else
1336 if (FD_ISSET(fr->fd, &read_set)) {
1337 #endif
1338 if (dynamic_first_read) {
1339 dynamic_first_read = 0;
1340 if (fcgi_util_gettimeofday(&fr->queueTime) < 0) {
1341 ap_log_rerror(FCGI_LOG_ERR, r, "FastCGI: gettimeofday() failed");
1342 return server_error(fr);
1346 if ((status = fcgi_buf_add_fd(fr->serverInputBuffer, fr->fd)) < 0) {
1347 ap_log_rerror(FCGI_LOG_ERR, r,
1348 "FastCGI: comm with server \"%s\" aborted: read failed", fr->fs_path);
1349 return server_error(fr);
1352 if (status == 0) {
1353 fr->keepReadingFromFcgiApp = FALSE;
1354 close_connection_to_fs(fr);
1358 /* Write to the FastCGI server */
1359 #ifdef WIN32
1360 if (((fr->using_npipe_io) &&
1361 (BufferLength(fr->serverOutputBuffer) > 0)) || FD_ISSET(fr->fd, &write_set)) {
1362 #else
1363 if (FD_ISSET(fr->fd, &write_set)) {
1364 #endif
1366 if (fcgi_buf_get_to_fd(fr->serverOutputBuffer, fr->fd) < 0) {
1367 ap_log_rerror(FCGI_LOG_ERR, r,
1368 "FastCGI: comm with server \"%s\" aborted: write failed", fr->fs_path);
1369 return server_error(fr);
1373 #if defined(SIGPIPE) && MODULE_MAGIC_NUMBER < 19990320
1374 /* Reinstall Apache's SIGPIPE handler */
1375 signal(SIGPIPE, fr->apache_sigpipe_handler);
1376 #endif
1378 } else {
1379 doClientWrite = TRUE;
1382 if (fr->role == FCGI_RESPONDER && doClientWrite) {
1383 if (write_to_client(fr) != OK) {
1384 #if defined(SIGPIPE) && MODULE_MAGIC_NUMBER < 19990320
1385 /* Make sure we leave with Apache's sigpipe_handler in place */
1386 if (fr->apache_sigpipe_handler != NULL)
1387 signal(SIGPIPE, fr->apache_sigpipe_handler);
1388 #endif
1389 close_connection_to_fs(fr);
1390 ap_kill_timeout(fr->r);
1391 return OK;
1395 if (fcgi_protocol_dequeue(rp, fr) != OK)
1396 return server_error(fr);
1398 if (fr->keepReadingFromFcgiApp && fr->exitStatusSet) {
1399 /* we're done talking to the fcgi app */
1400 fr->keepReadingFromFcgiApp = FALSE;
1401 close_connection_to_fs(fr);
1404 if (fr->parseHeader == SCAN_CGI_READING_HEADERS) {
1405 if ((err = process_headers(r, fr))) {
1406 ap_log_rerror(FCGI_LOG_ERR, r,
1407 "FastCGI: comm with server \"%s\" aborted: error parsing headers: %s", fr->fs_path, err);
1408 return server_error(fr);
1412 } /* while */
1414 switch (fr->parseHeader) {
1416 case SCAN_CGI_FINISHED:
1417 if (fr->role == FCGI_RESPONDER) {
1418 #ifdef RUSSIAN_APACHE
1419 ap_rflush(r);
1420 #else
1421 ap_bflush(r->connection->client);
1422 #endif
1423 ap_bgetopt(r->connection->client, BO_BYTECT, &r->bytes_sent);
1425 break;
1427 case SCAN_CGI_READING_HEADERS:
1428 ap_log_rerror(FCGI_LOG_ERR, r,
1429 "FastCGI: incomplete headers (%d bytes) received from server \"%s\"",
1430 fr->header->nelts, fr->fs_path);
1431 return server_error(fr);
1433 case SCAN_CGI_BAD_HEADER:
1434 return server_error(fr);
1436 case SCAN_CGI_INT_REDIRECT:
1437 case SCAN_CGI_SRV_REDIRECT:
1439 * XXX We really should be soaking all client input
1440 * and all script output. See mod_cgi.c.
1441 * There's other differences we need to pick up here as well!
1442 * This has to be revisited.
1444 break;
1446 default:
1447 ap_assert(FALSE);
1450 ap_kill_timeout(r);
1451 return OK;
1455 static fcgi_request *create_fcgi_request(request_rec * const r, const char *fs_path)
1457 struct stat *my_finfo;
1458 pool * const p = r->pool;
1459 fcgi_server *fs;
1460 fcgi_request * const fr = (fcgi_request *)ap_pcalloc(p, sizeof(fcgi_request));
1462 if (fs_path) {
1463 my_finfo = (struct stat *)ap_palloc(p, sizeof(struct stat));
1464 if (stat(fs_path, my_finfo) < 0) {
1465 ap_log_rerror(FCGI_LOG_ERR, r, "FastCGI: stat() of \"%s\" failed", fs_path);
1466 return NULL;
1469 else {
1470 my_finfo = &r->finfo;
1471 fs_path = r->filename;
1474 fs = fcgi_util_fs_get_by_id(fs_path, r->server->server_uid, r->server->server_gid);
1475 if (fs == NULL) {
1476 /* Its a request for a dynamic FastCGI application */
1477 const char * const err =
1478 fcgi_util_fs_is_path_ok(p, fs_path, my_finfo, r->server->server_uid, r->server->server_gid);
1480 if (err) {
1481 ap_log_rerror(FCGI_LOG_ERR_NOERRNO, r, "FastCGI: invalid (dynamic) server \"%s\": %s", fs_path, err);
1482 return NULL;
1486 fr->serverInputBuffer = fcgi_buf_new(p, SERVER_BUFSIZE);
1487 fr->serverOutputBuffer = fcgi_buf_new(p, SERVER_BUFSIZE);
1488 fr->clientInputBuffer = fcgi_buf_new(p, SERVER_BUFSIZE);
1489 fr->clientOutputBuffer = fcgi_buf_new(p, SERVER_BUFSIZE);
1490 fr->erBufPtr = fcgi_buf_new(p, sizeof(FCGI_EndRequestBody) + 1);
1491 fr->gotHeader = FALSE;
1492 fr->parseHeader = SCAN_CGI_READING_HEADERS;
1493 fr->header = ap_make_array(p, 1, 1);
1494 fr->fs_stderr = NULL;
1495 fr->r = r;
1496 fr->readingEndRequestBody = FALSE;
1497 fr->exitStatus = 0;
1498 fr->exitStatusSet = FALSE;
1499 fr->requestId = 1; /* anything but zero is OK here */
1500 fr->eofSent = FALSE;
1501 fr->role = FCGI_RESPONDER;
1502 fr->expectingClientContent = FALSE;
1503 fr->keepReadingFromFcgiApp = TRUE;
1504 fr->fs = fs;
1505 fr->fs_path = fs_path;
1506 fr->authHeaders = ap_make_table(p, 10);
1507 #ifdef WIN32
1508 fr->fd = INVALID_SOCKET;
1509 fr->dynamic = ((fs == NULL) || (fs->directive == APP_CLASS_DYNAMIC)) ? TRUE : FALSE;
1510 fr->using_npipe_io = FALSE;
1511 #else
1512 fr->dynamic = (fs == NULL) ? TRUE : FALSE;
1513 fr->fd = -1;
1514 #endif
1516 set_uid_n_gid(r, &fr->user, &fr->group);
1518 return fr;
1522 *----------------------------------------------------------------------
1524 * handler --
1526 * This routine gets called for a request that corresponds to
1527 * a FastCGI connection. It performs the request synchronously.
1529 * Results:
1530 * Final status of request: OK or NOT_FOUND or SERVER_ERROR.
1532 * Side effects:
1533 * Request performed.
1535 *----------------------------------------------------------------------
1538 /* Stolen from mod_cgi.c..
1539 * KLUDGE --- for back-combatibility, we don't have to check ExecCGI
1540 * in ScriptAliased directories, which means we need to know if this
1541 * request came through ScriptAlias or not... so the Alias module
1542 * leaves a note for us.
1544 static int apache_is_scriptaliased(request_rec *r)
1546 const char *t = ap_table_get(r->notes, "alias-forced-type");
1547 return t && (!strcasecmp(t, "cgi-script"));
1550 /* If a script wants to produce its own Redirect body, it now
1551 * has to explicitly *say* "Status: 302". If it wants to use
1552 * Apache redirects say "Status: 200". See process_headers().
1554 static int post_process_for_redirects(request_rec * const r,
1555 const fcgi_request * const fr)
1557 switch(fr->parseHeader) {
1558 case SCAN_CGI_INT_REDIRECT:
1560 /* @@@ There are still differences between the handling in
1561 * mod_cgi and mod_fastcgi. This needs to be revisited.
1563 /* We already read the message body (if any), so don't allow
1564 * the redirected request to think it has one. We can ignore
1565 * Transfer-Encoding, since we used REQUEST_CHUNKED_ERROR.
1567 r->method = "GET";
1568 r->method_number = M_GET;
1569 ap_table_unset(r->headers_in, "Content-length");
1571 ap_internal_redirect_handler(ap_table_get(r->headers_out, "Location"), r);
1572 return OK;
1574 case SCAN_CGI_SRV_REDIRECT:
1575 return REDIRECT;
1577 default:
1578 return OK;
1582 /******************************************************************************
1583 * Process fastcgi-script requests. Based on mod_cgi::cgi_handler().
1585 static int content_handler(request_rec *r)
1587 fcgi_request *fr = NULL;
1588 int ret;
1590 /* Setup a new FastCGI request */
1591 if ((fr = create_fcgi_request(r, NULL)) == NULL)
1592 return SERVER_ERROR;
1594 /* If its a dynamic invocation, make sure scripts are OK here */
1595 if (fr->dynamic && !(ap_allow_options(r) & OPT_EXECCGI) && !apache_is_scriptaliased(r)) {
1596 ap_log_rerror(FCGI_LOG_ERR_NOERRNO, r,
1597 "FastCGI: \"ExecCGI Option\" is off in this directory: %s", r->uri);
1598 return SERVER_ERROR;
1601 /* Process the fastcgi-script request */
1602 if ((ret = do_work(r, fr)) != OK)
1603 return ret;
1605 /* Special case redirects */
1606 return post_process_for_redirects(r, fr);
1610 static int post_process_auth_passed_header(table *t, const char *key, const char * const val)
1612 if (strncasecmp(key, "Variable-", 9) == 0)
1613 key += 9;
1615 ap_table_setn(t, key, val);
1616 return 1;
1619 static int post_process_auth_passed_compat_header(table *t, const char *key, const char * const val)
1621 if (strncasecmp(key, "Variable-", 9) == 0)
1622 ap_table_setn(t, key + 9, val);
1624 return 1;
1627 static int post_process_auth_failed_header(table * const t, const char * const key, const char * const val)
1629 ap_table_setn(t, key, val);
1630 return 1;
1633 static void post_process_auth(fcgi_request * const fr, const int passed)
1635 request_rec * const r = fr->r;
1637 /* Restore the saved subprocess_env because we muddied ours up */
1638 r->subprocess_env = fr->saved_subprocess_env;
1640 if (passed) {
1641 if (fr->auth_compat) {
1642 ap_table_do((int (*)(void *, const char *, const char *))post_process_auth_passed_compat_header,
1643 (void *)r->subprocess_env, fr->authHeaders, NULL);
1645 else {
1646 ap_table_do((int (*)(void *, const char *, const char *))post_process_auth_passed_header,
1647 (void *)r->subprocess_env, fr->authHeaders, NULL);
1650 else {
1651 ap_table_do((int (*)(void *, const char *, const char *))post_process_auth_failed_header,
1652 (void *)r->err_headers_out, fr->authHeaders, NULL);
1655 /* @@@ Restore these.. its a hack until I rewrite the header handling */
1656 r->status = HTTP_OK;
1657 r->status_line = NULL;
1660 static int check_user_authentication(request_rec *r)
1662 int res, authenticated = 0;
1663 const char *password;
1664 fcgi_request *fr;
1665 const fcgi_dir_config * const dir_config =
1666 (const fcgi_dir_config *)ap_get_module_config(r->per_dir_config, &fastcgi_module);
1668 if (dir_config->authenticator == NULL)
1669 return DECLINED;
1671 /* Get the user password */
1672 if ((res = ap_get_basic_auth_pw(r, &password)) != OK)
1673 return res;
1675 if ((fr = create_fcgi_request(r, dir_config->authenticator)) == NULL)
1676 return SERVER_ERROR;
1678 /* Save the existing subprocess_env, because we're gonna muddy it up */
1679 fr->saved_subprocess_env = ap_copy_table(r->pool, r->subprocess_env);
1681 ap_table_setn(r->subprocess_env, "REMOTE_PASSWD", password);
1682 ap_table_setn(r->subprocess_env, "FCGI_APACHE_ROLE", "AUTHENTICATOR");
1684 /* The FastCGI Protocol doesn't differentiate authentication */
1685 fr->role = FCGI_AUTHORIZER;
1687 /* Do we need compatibility mode? */
1688 fr->auth_compat = (dir_config->authenticator_options & FCGI_COMPAT);
1690 if ((res = do_work(r, fr)) != OK)
1691 goto AuthenticationFailed;
1693 authenticated = (r->status == 200);
1694 post_process_auth(fr, authenticated);
1696 /* A redirect shouldn't be allowed during the authentication phase */
1697 if (ap_table_get(r->headers_out, "Location") != NULL) {
1698 ap_log_rerror(FCGI_LOG_ERR_NOERRNO, r,
1699 "FastCGI: FastCgiAuthenticator \"%s\" redirected (not allowed)",
1700 dir_config->authenticator);
1701 goto AuthenticationFailed;
1704 if (authenticated)
1705 return OK;
1707 AuthenticationFailed:
1708 if (!(dir_config->authenticator_options & FCGI_AUTHORITATIVE))
1709 return DECLINED;
1711 /* @@@ Probably should support custom_responses */
1712 ap_note_basic_auth_failure(r);
1713 ap_log_rerror(FCGI_LOG_ERR_NOERRNO, r,
1714 "FastCGI: authentication failed for user \"%s\": %s", r->connection->user, r->uri);
1715 return (res == OK) ? AUTH_REQUIRED : res;
1718 static int check_user_authorization(request_rec *r)
1720 int res, authorized = 0;
1721 fcgi_request *fr;
1722 const fcgi_dir_config * const dir_config =
1723 (const fcgi_dir_config *)ap_get_module_config(r->per_dir_config, &fastcgi_module);
1725 if (dir_config->authorizer == NULL)
1726 return DECLINED;
1728 /* @@@ We should probably honor the existing parameters to the require directive
1729 * as well as allow the definition of new ones (or use the basename of the
1730 * FastCGI server and pass the rest of the directive line), but for now keep
1731 * it simple. */
1733 if ((fr = create_fcgi_request(r, dir_config->authorizer)) == NULL)
1734 return SERVER_ERROR;
1736 /* Save the existing subprocess_env, because we're gonna muddy it up */
1737 fr->saved_subprocess_env = ap_copy_table(r->pool, r->subprocess_env);
1739 ap_table_setn(r->subprocess_env, "FCGI_APACHE_ROLE", "AUTHORIZER");
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 AuthorizationFailed;
1749 authorized = (r->status == 200);
1750 post_process_auth(fr, authorized);
1752 /* A redirect shouldn't be allowed during the authorization phase */
1753 if (ap_table_get(r->headers_out, "Location") != NULL) {
1754 ap_log_rerror(FCGI_LOG_ERR_NOERRNO, r,
1755 "FastCGI: FastCgiAuthorizer \"%s\" redirected (not allowed)",
1756 dir_config->authorizer);
1757 goto AuthorizationFailed;
1760 if (authorized)
1761 return OK;
1763 AuthorizationFailed:
1764 if (!(dir_config->authorizer_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: authorization failed for user \"%s\": %s", r->connection->user, r->uri);
1771 return (res == OK) ? AUTH_REQUIRED : res;
1774 static int check_access(request_rec *r)
1776 int res, access_allowed = 0;
1777 fcgi_request *fr;
1778 const fcgi_dir_config * const dir_config =
1779 (fcgi_dir_config *)ap_get_module_config(r->per_dir_config, &fastcgi_module);
1781 if (dir_config == NULL || dir_config->access_checker == NULL)
1782 return DECLINED;
1784 if ((fr = create_fcgi_request(r, dir_config->access_checker)) == NULL)
1785 return SERVER_ERROR;
1787 /* Save the existing subprocess_env, because we're gonna muddy it up */
1788 fr->saved_subprocess_env = ap_copy_table(r->pool, r->subprocess_env);
1790 ap_table_setn(r->subprocess_env, "FCGI_APACHE_ROLE", "ACCESS_CHECKER");
1792 /* The FastCGI Protocol doesn't differentiate access control */
1793 fr->role = FCGI_AUTHORIZER;
1795 /* Do we need compatibility mode? */
1796 fr->auth_compat = (dir_config->authenticator_options & FCGI_COMPAT);
1798 if ((res = do_work(r, fr)) != OK)
1799 goto AccessFailed;
1801 access_allowed = (r->status == 200);
1802 post_process_auth(fr, access_allowed);
1804 /* A redirect shouldn't be allowed during the access check phase */
1805 if (ap_table_get(r->headers_out, "Location") != NULL) {
1806 ap_log_rerror(FCGI_LOG_ERR_NOERRNO, r,
1807 "FastCGI: FastCgiAccessChecker \"%s\" redirected (not allowed)",
1808 dir_config->access_checker);
1809 goto AccessFailed;
1812 if (access_allowed)
1813 return OK;
1815 AccessFailed:
1816 if (!(dir_config->access_checker_options & FCGI_AUTHORITATIVE))
1817 return DECLINED;
1819 /* @@@ Probably should support custom_responses */
1820 ap_log_rerror(FCGI_LOG_ERR_NOERRNO, r, "FastCGI: access denied: %s", r->uri);
1821 return (res == OK) ? FORBIDDEN : res;
1826 command_rec fastcgi_cmds[] = {
1827 { "AppClass", fcgi_config_new_static_server, NULL, RSRC_CONF, RAW_ARGS, NULL },
1828 { "FastCgiServer", fcgi_config_new_static_server, NULL, RSRC_CONF, RAW_ARGS, NULL },
1830 { "ExternalAppClass", fcgi_config_new_external_server, NULL, RSRC_CONF, RAW_ARGS, NULL },
1831 { "FastCgiExternalServer", fcgi_config_new_external_server, NULL, RSRC_CONF, RAW_ARGS, NULL },
1833 { "FastCgiIpcDir", fcgi_config_set_socket_dir, NULL, RSRC_CONF, TAKE1, NULL },
1835 { "FastCgiSuexec", fcgi_config_set_suexec, NULL, RSRC_CONF, TAKE1, NULL },
1837 { "FCGIConfig", fcgi_config_set_config, NULL, RSRC_CONF, RAW_ARGS, NULL },
1838 { "FastCgiConfig", fcgi_config_set_config, NULL, RSRC_CONF, RAW_ARGS, NULL },
1840 { "FastCgiAuthenticator", fcgi_config_new_auth_server,
1841 (void *)FCGI_AUTH_TYPE_AUTHENTICATOR, ACCESS_CONF, TAKE12,
1842 "a fastcgi-script path (absolute or relative to ServerRoot) followed by an optional -compat" },
1843 { "FastCgiAuthenticatorAuthoritative", fcgi_config_set_authoritative_slot,
1844 (void *)XtOffsetOf(fcgi_dir_config, authenticator_options), ACCESS_CONF, FLAG,
1845 "Set to 'off' to allow authentication to be passed along to lower modules upon failure" },
1847 { "FastCgiAuthorizer", fcgi_config_new_auth_server,
1848 (void *)FCGI_AUTH_TYPE_AUTHORIZER, ACCESS_CONF, TAKE12,
1849 "a fastcgi-script path (absolute or relative to ServerRoot) followed by an optional -compat" },
1850 { "FastCgiAuthorizerAuthoritative", fcgi_config_set_authoritative_slot,
1851 (void *)XtOffsetOf(fcgi_dir_config, authorizer_options), ACCESS_CONF, FLAG,
1852 "Set to 'off' to allow authorization to be passed along to lower modules upon failure" },
1854 { "FastCgiAccessChecker", fcgi_config_new_auth_server,
1855 (void *)FCGI_AUTH_TYPE_ACCESS_CHECKER, ACCESS_CONF, TAKE12,
1856 "a fastcgi-script path (absolute or relative to ServerRoot) followed by an optional -compat" },
1857 { "FastCgiAccessCheckerAuthoritative", fcgi_config_set_authoritative_slot,
1858 (void *)XtOffsetOf(fcgi_dir_config, access_checker_options), ACCESS_CONF, FLAG,
1859 "Set to 'off' to allow access control to be passed along to lower modules upon failure" },
1860 { NULL }
1864 handler_rec fastcgi_handlers[] = {
1865 { FCGI_MAGIC_TYPE, content_handler },
1866 { "fastcgi-script", content_handler },
1867 { NULL }
1871 module MODULE_VAR_EXPORT fastcgi_module = {
1872 STANDARD_MODULE_STUFF,
1873 init_module, /* initializer */
1874 fcgi_config_create_dir_config, /* per-dir config creator */
1875 NULL, /* per-dir config merger (default: override) */
1876 NULL, /* per-server config creator */
1877 NULL, /* per-server config merger (default: override) */
1878 fastcgi_cmds, /* command table */
1879 fastcgi_handlers, /* [9] content handlers */
1880 NULL, /* [2] URI-to-filename translation */
1881 check_user_authentication, /* [5] authenticate user_id */
1882 check_user_authorization, /* [6] authorize user_id */
1883 check_access, /* [4] check access (based on src & http headers) */
1884 NULL, /* [7] check/set MIME type */
1885 NULL, /* [8] fixups */
1886 NULL, /* [10] logger */
1887 NULL, /* [3] header-parser */
1888 fcgi_child_init, /* process initialization */
1889 fcgi_child_exit, /* process exit/cleanup */
1890 NULL /* [1] post read-request handling */