Change the suexec enabled msg from Info to Notice LogLevel
[mod_fastcgi.git] / mod_fastcgi.c
bloba7ece9498dff7a88509e90817195b306d39fa227
1 /*
2 * mod_fastcgi.c --
4 * Apache server module for FastCGI.
6 * $Id: mod_fastcgi.c,v 1.96 2000/07/31 00:33:42 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) {
175 case PLEASE_START:
176 #ifdef WIN32
177 job->id = id;
178 job->fs_path = strdup(fs_path);
179 job->user = strdup(user);
180 job->group = strdup(group);
181 job->qsec = 0L;
182 job->start_time = 0L;
183 #else
184 buflen = sprintf(buf, "%c %s %s %s*", id, fs_path, user, group);
185 #endif
186 break;
188 case CONN_TIMEOUT:
189 #ifdef WIN32
190 job->id = id;
191 job->fs_path = strdup(fs_path);
192 job->user = strdup(user);
193 job->group = strdup(group);
194 job->qsec = 0L;
195 job->start_time = 0L;
196 #else
197 buflen = sprintf(buf, "%c %s %s %s*", id, fs_path, user, group);
198 #endif
199 break;
201 case REQ_COMPLETE:
202 #ifdef WIN32
203 job->id = id;
204 job->fs_path = strdup(fs_path);
205 job->qsec = q_usec;
206 job->start_time = req_usec;
207 job->user = strdup(user);
208 job->group = strdup(group);
209 #else
210 buflen = sprintf(buf, "%c %s %s %s %lu %lu*", id, fs_path, user, group, q_usec, req_usec);
211 #endif
212 break;
215 #ifdef WIN32
216 if (fcgi_pm_add_job(job) == 0)
217 return;
219 SetEvent(fcgi_event_handles[MBOX_EVENT]);
220 #else
221 ap_assert(buflen <= FCGI_MAX_MSG_LEN);
223 if (write(fcgi_pm_pipe[1], (const void *)buf, buflen) != buflen) {
224 ap_log_error(FCGI_LOG_WARN, fcgi_apache_main_server,
225 "FastCGI: write() to PM failed");
227 #endif
232 *----------------------------------------------------------------------
234 * init_module
236 * An Apache module initializer, called by the Apache core
237 * after reading the server config.
239 * Start the process manager no matter what, since there may be a
240 * request for dynamic FastCGI applications without any being
241 * configured as static applications. Also, check for the existence
242 * and create if necessary a subdirectory into which all dynamic
243 * sockets will go.
245 *----------------------------------------------------------------------
247 static void init_module(server_rec *s, pool *p)
249 const char *err;
251 /* Register to reset to default values when the config pool is cleaned */
252 ap_block_alarms();
253 ap_register_cleanup(p, NULL, fcgi_config_reset_globals, ap_null_cleanup);
254 ap_unblock_alarms();
256 ap_add_version_component("mod_fastcgi/" MOD_FASTCGI_VERSION);
258 fcgi_config_set_fcgi_uid_n_gid(1);
260 /* keep these handy */
261 fcgi_config_pool = p;
262 fcgi_apache_main_server = s;
264 #ifndef WIN32
265 /* Create Unix/Domain socket directory */
266 if ((err = fcgi_config_make_dir(p, fcgi_socket_dir)))
267 ap_log_error(FCGI_LOG_ERR, s, "FastCGI: %s", err);
268 #endif
270 /* Create Dynamic directory */
271 if ((err = fcgi_config_make_dynamic_dir(p, 1)))
272 ap_log_error(FCGI_LOG_ERR, s, "FastCGI: %s", err);
274 #ifndef WIN32
275 /* Create the pipe for comm with the PM */
276 if (pipe(fcgi_pm_pipe) < 0) {
277 ap_log_error(FCGI_LOG_ERR, s, "FastCGI: pipe() failed");
280 /* Spawn the PM only once. Under Unix, Apache calls init() routines
281 * twice, once before detach() and once after. Win32 doesn't detach.
282 * Under DSO, DSO modules are unloaded between the two init() calls.
283 * Under Unix, the -X switch causes two calls to init() but no detach
284 * (but all subprocesses are wacked so the PM is toasted anyway)! */
286 if (ap_standalone && getppid() != 1)
287 return;
289 /* Start the Process Manager */
290 fcgi_pm_pid = ap_spawn_child(p, fcgi_pm_main, NULL, kill_only_once, NULL, NULL, NULL);
291 if (fcgi_pm_pid <= 0) {
292 ap_log_error(FCGI_LOG_ALERT, s,
293 "FastCGI: can't start the process manager, spawn_child() failed");
296 close(fcgi_pm_pipe[0]);
297 #endif
300 static void fcgi_child_init(server_rec *server_conf, pool *p)
302 #ifdef WIN32
303 /* Create the Event Handlers */
304 fcgi_event_handles[0] = CreateEvent(NULL, FALSE, FALSE, NULL);
305 fcgi_event_handles[1] = CreateEvent(NULL, FALSE, FALSE, NULL);
306 fcgi_event_handles[2] = CreateEvent(NULL, FALSE, FALSE, NULL);
307 fcgi_dynamic_mbox_mutex = ap_create_mutex("fcgi_dynamic_mbox_mutex");
309 /* Spawn of the process manager thread */
310 fcgi_pm_thread = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)fcgi_pm_main, NULL, 0, NULL);
311 #endif
312 return;
315 static void fcgi_child_exit(server_rec *server_conf, pool *p) {
317 #ifdef WIN32
318 /* Signaling the PM thread tp exit*/
319 SetEvent(fcgi_event_handles[TERM_EVENT]);
321 /* Waiting on pm thread to exit */
322 WaitForSingleObject(fcgi_pm_thread, INFINITE);
323 #endif
325 return;
329 *----------------------------------------------------------------------
331 * get_header_line --
333 * Terminate a line: scan to the next newline, scan back to the
334 * first non-space character and store a terminating zero. Return
335 * the next character past the end of the newline.
337 * If the end of the string is reached, ASSERT!
339 * If the FIRST character(s) in the line are '\n' or "\r\n", the
340 * first character is replaced with a NULL and next character
341 * past the newline is returned. NOTE: this condition supercedes
342 * the processing of RFC-822 continuation lines.
344 * If continuation is set to 'TRUE', then it parses a (possible)
345 * sequence of RFC-822 continuation lines.
347 * Results:
348 * As above.
350 * Side effects:
351 * Termination byte stored in string.
353 *----------------------------------------------------------------------
355 static char *get_header_line(char *start, int continuation)
357 char *p = start;
358 char *end = start;
360 if(p[0] == '\r' && p[1] == '\n') { /* If EOL in 1st 2 chars */
361 p++; /* point to \n and stop */
362 } else if(*p != '\n') {
363 if(continuation) {
364 while(*p != '\0') {
365 if(*p == '\n' && p[1] != ' ' && p[1] != '\t')
366 break;
367 p++;
369 } else {
370 while(*p != '\0' && *p != '\n') {
371 p++;
376 ap_assert(*p != '\0');
377 end = p;
378 end++;
381 * Trim any trailing whitespace.
383 while(isspace((unsigned char)p[-1]) && p > start) {
384 p--;
387 *p = '\0';
388 return end;
392 *----------------------------------------------------------------------
394 * process_headers --
396 * Call with r->parseHeader == SCAN_CGI_READING_HEADERS
397 * and initial script output in fr->header.
399 * If the initial script output does not include the header
400 * terminator ("\r\n\r\n") process_headers returns with no side
401 * effects, to be called again when more script output
402 * has been appended to fr->header.
404 * If the initial script output includes the header terminator,
405 * process_headers parses the headers and determines whether or
406 * not the remaining script output will be sent to the client.
407 * If so, process_headers sends the HTTP response headers to the
408 * client and copies any non-header script output to the output
409 * buffer reqOutbuf.
411 * Results:
412 * none.
414 * Side effects:
415 * May set r->parseHeader to:
416 * SCAN_CGI_FINISHED -- headers parsed, returning script response
417 * SCAN_CGI_BAD_HEADER -- malformed header from script
418 * SCAN_CGI_INT_REDIRECT -- handler should perform internal redirect
419 * SCAN_CGI_SRV_REDIRECT -- handler should return REDIRECT
421 *----------------------------------------------------------------------
424 static const char *process_headers(request_rec *r, fcgi_request *fr)
426 char *p, *next, *name, *value;
427 int len, flag;
428 int hasContentType, hasStatus, hasLocation;
430 ap_assert(fr->parseHeader == SCAN_CGI_READING_HEADERS);
432 if (fr->header == NULL)
433 return NULL;
436 * Do we have the entire header? Scan for the blank line that
437 * terminates the header.
439 p = (char *)fr->header->elts;
440 len = fr->header->nelts;
441 flag = 0;
442 while(len-- && flag < 2) {
443 switch(*p) {
444 case '\r':
445 break;
446 case '\n':
447 flag++;
448 break;
449 case '\0':
450 case '\v':
451 case '\f':
452 name = "Invalid Character";
453 goto BadHeader;
454 break;
455 default:
456 flag = 0;
457 break;
459 p++;
462 /* Return (to be called later when we have more data)
463 * if we don't have an entire header. */
464 if (flag < 2)
465 return NULL;
468 * Parse all the headers.
470 fr->parseHeader = SCAN_CGI_FINISHED;
471 hasContentType = hasStatus = hasLocation = FALSE;
472 next = (char *)fr->header->elts;
473 for(;;) {
474 next = get_header_line(name = next, TRUE);
475 if (*name == '\0') {
476 break;
478 if ((p = strchr(name, ':')) == NULL) {
479 goto BadHeader;
481 value = p + 1;
482 while (p != name && isspace((unsigned char)*(p - 1))) {
483 p--;
485 if (p == name) {
486 goto BadHeader;
488 *p = '\0';
489 if (strpbrk(name, " \t") != NULL) {
490 *p = ' ';
491 goto BadHeader;
493 while (isspace((unsigned char)*value)) {
494 value++;
497 if (strcasecmp(name, "Status") == 0) {
498 int statusValue = strtol(value, NULL, 10);
500 if (hasStatus) {
501 goto DuplicateNotAllowed;
503 if (statusValue < 0) {
504 fr->parseHeader = SCAN_CGI_BAD_HEADER;
505 return ap_psprintf(r->pool, "invalid Status '%s'", value);
507 hasStatus = TRUE;
508 r->status = statusValue;
509 r->status_line = ap_pstrdup(r->pool, value);
510 continue;
513 if (fr->role == FCGI_RESPONDER) {
514 if (strcasecmp(name, "Content-type") == 0) {
515 if (hasContentType) {
516 goto DuplicateNotAllowed;
518 hasContentType = TRUE;
519 r->content_type = ap_pstrdup(r->pool, value);
520 continue;
523 if (strcasecmp(name, "Location") == 0) {
524 if (hasLocation) {
525 goto DuplicateNotAllowed;
527 hasLocation = TRUE;
528 ap_table_set(r->headers_out, "Location", value);
529 continue;
532 /* If the script wants them merged, it can do it */
533 ap_table_add(r->err_headers_out, name, value);
534 continue;
536 else {
537 ap_table_add(fr->authHeaders, name, value);
541 if (fr->role != FCGI_RESPONDER)
542 return NULL;
545 * Who responds, this handler or Apache?
547 if (hasLocation) {
548 const char *location = ap_table_get(r->headers_out, "Location");
550 * Based on internal redirect handling in mod_cgi.c...
552 * If a script wants to produce its own Redirect
553 * body, it now has to explicitly *say* "Status: 302"
555 if (r->status == 200) {
556 if(location[0] == '/') {
558 * Location is an relative path. This handler will
559 * consume all script output, then have Apache perform an
560 * internal redirect.
562 fr->parseHeader = SCAN_CGI_INT_REDIRECT;
563 return NULL;
564 } else {
566 * Location is an absolute URL. If the script didn't
567 * produce a Content-type header, this handler will
568 * consume all script output and then have Apache generate
569 * its standard redirect response. Otherwise this handler
570 * will transmit the script's response.
572 fr->parseHeader = SCAN_CGI_SRV_REDIRECT;
573 return NULL;
578 * We're responding. Send headers, buffer excess script output.
580 ap_send_http_header(r);
582 /* We need to reinstate our timeout, send_http_header() kill()s it */
583 ap_hard_timeout("FastCGI request processing", r);
585 if (r->header_only)
586 return NULL;
588 len = fr->header->nelts - (next - fr->header->elts);
589 ap_assert(len >= 0);
590 ap_assert(BufferLength(fr->clientOutputBuffer) == 0);
591 if (BufferFree(fr->clientOutputBuffer) < len) {
592 fr->clientOutputBuffer = fcgi_buf_new(r->pool, len);
594 ap_assert(BufferFree(fr->clientOutputBuffer) >= len);
595 if (len > 0) {
596 int sent = fcgi_buf_add_block(fr->clientOutputBuffer, next, len);
597 ap_assert(sent == len);
599 return NULL;
601 BadHeader:
602 /* Log first line of a multi-line header */
603 if ((p = strpbrk(name, "\r\n")) != NULL)
604 *p = '\0';
605 fr->parseHeader = SCAN_CGI_BAD_HEADER;
606 return ap_psprintf(r->pool, "malformed header '%s'", name);
608 DuplicateNotAllowed:
609 fr->parseHeader = SCAN_CGI_BAD_HEADER;
610 return ap_psprintf(r->pool, "duplicate header '%s'", name);
614 * Read from the client filling both the FastCGI server buffer and the
615 * client buffer with the hopes of buffering the client data before
616 * making the connect() to the FastCGI server. This prevents slow
617 * clients from keeping the FastCGI server in processing longer than is
618 * necessary.
620 static int read_from_client_n_queue(fcgi_request *fr)
622 char *end;
623 unsigned int count;
624 long int countRead;
626 while (BufferFree(fr->clientInputBuffer) > 0 || BufferFree(fr->serverOutputBuffer) > 0) {
627 fcgi_protocol_queue_client_buffer(fr);
629 if (fr->expectingClientContent <= 0)
630 return OK;
632 fcgi_buf_get_free_block_info(fr->clientInputBuffer, &end, &count);
633 if (count == 0)
634 return OK;
636 if ((countRead = ap_get_client_block(fr->r, end, count)) < 0)
637 return -1;
639 if (countRead == 0)
640 fr->expectingClientContent = 0;
641 else
642 fcgi_buf_add_update(fr->clientInputBuffer, countRead);
645 return OK;
648 static int write_to_client(fcgi_request *fr)
650 char *begin;
651 unsigned int count;
653 fcgi_buf_get_block_info(fr->clientOutputBuffer, &begin, &count);
654 if (count == 0)
655 return OK;
657 /* If fewer than count bytes are written, an error occured.
658 * ap_bwrite() typically forces a flushed write to the client, this
659 * effectively results in a block (and short packets) - it should
660 * be fixed, but I didn't win much support for the idea on new-httpd.
661 * So, without patching Apache, the best way to deal with this is
662 * to size the fcgi_bufs to hold all of the script output (within
663 * reason) so the script can be released from having to wait around
664 * for the transmission to the client to complete. */
665 #ifdef RUSSIAN_APACHE
666 if (ap_rwrite(begin, count, fr->r) != count) {
667 ap_log_rerror(FCGI_LOG_INFO, fr->r,
668 "FastCGI: client stopped connection before send body completed");
669 return -1;
671 #else
672 if (ap_bwrite(fr->r->connection->client, begin, count) != (int) count) {
673 ap_log_rerror(FCGI_LOG_INFO, fr->r,
674 "FastCGI: client stopped connection before send body completed");
675 return -1;
677 #endif
680 /* Don't bother with a wrapped buffer, limiting exposure to slow
681 * clients. The BUFF routines don't allow a writev from above,
682 * and don't always memcpy to minimize small write()s, this should
683 * be fixed, but I didn't win much support for the idea on
684 * new-httpd - I'll have to _prove_ its a problem first.. */
686 /* The default behaviour used to be to flush with every write, but this
687 * can tie up the FastCGI server longer than is necessary so its an option now */
688 if (fr->fs && fr->fs->flush) {
689 #ifdef RUSSIAN_APACHE
690 if (ap_rflush(fr->r)) {
691 ap_log_rerror(FCGI_LOG_INFO, fr->r,
692 "FastCGI: client stopped connection before send body completed");
693 return -1;
695 #else
696 if (ap_bflush(fr->r->connection->client)) {
697 ap_log_rerror(FCGI_LOG_INFO, fr->r,
698 "FastCGI: client stopped connection before send body completed");
699 return -1;
701 #endif
704 fcgi_buf_toss(fr->clientOutputBuffer, count);
705 return OK;
708 /*******************************************************************************
709 * Determine the user and group suexec should be called with.
710 * Based on code in Apache's create_argv_cmd() (util_script.c).
712 static void set_uid_n_gid(request_rec *r, const char **user, const char **group)
714 if (fcgi_suexec == NULL) {
715 *user = "-";
716 *group = "-";
717 return;
720 if (strncmp("/~", r->uri, 2) == 0) {
721 /* its a user dir uri, just send the ~user, and leave it to the PM */
722 char *end = strchr(r->uri + 2, '/');
724 if (end)
725 *user = memcpy(ap_pcalloc(r->pool, end - r->uri), r->uri + 1, end - r->uri - 1);
726 else
727 *user = ap_pstrdup(r->pool, r->uri + 1);
728 *group = "-";
730 else {
731 *user = ap_psprintf(r->pool, "%ld", (long)r->server->server_uid);
732 *group = ap_psprintf(r->pool, "%ld", (long)r->server->server_gid);
736 /*******************************************************************************
737 * Close the connection to the FastCGI server. This is normally called by
738 * do_work(), but may also be called as in request pool cleanup.
740 static void close_connection_to_fs(fcgi_request *fr)
742 pool *rp = fr->r->pool;
744 if (fr->fd != -1)
745 ap_pclosesocket(rp, fr->fd);
747 if (fr->dynamic) {
748 #ifdef WIN32
749 fcgi_rdwr_unlock(fr->lockFd, READER);
750 #else
751 ap_pclosef(rp, fr->lockFd);
752 #endif
754 if (fr->keepReadingFromFcgiApp == FALSE) {
755 /* XXX REQ_COMPLETE is only sent for requests which complete
756 * normally WRT the fcgi app. There is no data sent for
757 * connect() timeouts or requests which complete abnormally.
758 * KillDynamicProcs() and RemoveRecords() need to be looked at
759 * to be sure they can reasonably handle these cases before
760 * sending these sort of stats - theres some funk in there.
761 * XXX We should do something special when this a pool cleanup.
763 if (fcgi_util_gettimeofday(&fr->completeTime) < 0) {
764 /* there's no point to aborting the request, just log it */
765 ap_log_error(FCGI_LOG_ERR, fr->r->server, "FastCGI: gettimeofday() failed");
766 } else {
767 struct timeval qtime, rtime;
769 timersub(&fr->queueTime, &fr->startTime, &qtime);
770 timersub(&fr->completeTime, &fr->queueTime, &rtime);
772 send_to_pm(rp, REQ_COMPLETE, fr->fs_path,
773 fr->user, fr->group,
774 qtime.tv_sec * 1000000 + qtime.tv_usec,
775 rtime.tv_sec * 1000000 + rtime.tv_usec);
781 #ifdef WIN32
782 static void lock_cleanup(void * data)
784 fcgi_rdwr_unlock((FcgiRWLock *) data, READER);
786 #endif
788 /*******************************************************************************
789 * Connect to the FastCGI server.
791 static const char *open_connection_to_fs(fcgi_request *fr)
793 struct timeval tval;
794 fd_set write_fds, read_fds;
795 int status;
796 request_rec * const r = fr->r;
797 pool * const rp = r->pool;
798 const char *socket_path = NULL;
799 struct sockaddr *socket_addr = NULL;
800 int socket_addr_len = 0;
801 #ifdef WIN32
802 unsigned long ioctl_arg;
803 int errcode;
804 #else
805 int fd_flags = 0;
806 const char *err = NULL;
807 #endif
809 /* Create the connection point */
810 if (fr->dynamic) {
811 socket_path = fcgi_util_socket_hash_filename(rp, fr->fs_path, fr->user, fr->group);
812 socket_path = fcgi_util_socket_make_path_absolute(rp, socket_path, 1);
814 #ifndef WIN32
815 err = fcgi_util_socket_make_domain_addr(rp, (struct sockaddr_un **)&socket_addr,
816 &socket_addr_len, socket_path);
817 if (err)
818 return err;
819 #endif
820 } else {
821 #ifdef WIN32
822 if (fr->fs->dest_addr != NULL) {
823 socket_addr = fr->fs->dest_addr;
825 else if (fr->fs->socket_addr) {
826 socket_addr = fr->fs->socket_addr;
828 else {
829 socket_path = fr->fs->socket_path;
831 #else
832 socket_addr = fr->fs->socket_addr;
833 #endif
834 socket_addr_len = fr->fs->socket_addr_len;
837 /* Dynamic app's lockfile handling */
838 if (fr->dynamic) {
839 #ifndef WIN32
840 const char *lockFileName = fcgi_util_socket_get_lock_filename(rp, socket_path);
841 struct stat lstbuf;
842 #endif
843 struct stat bstbuf;
844 int result = 0;
846 do {
847 #ifdef WIN32
848 if (fr->fs != NULL)
849 #else
850 if (stat(lockFileName, &lstbuf) == 0 && S_ISREG(lstbuf.st_mode))
851 #endif
853 if (dynamicAutoUpdate && (stat(fr->fs_path, &bstbuf) == 0)
854 #ifdef WIN32
855 && ((fr->fs->restartTime > 0) && (fr->fs->restartTime < bstbuf.st_mtime)))
856 #else
857 && (lstbuf.st_mtime < bstbuf.st_mtime))
858 #endif
860 struct timeval tv = {1, 0};
862 /* Its already running, but there's a newer one,
863 * ask the process manager to start it.
864 * it will notice that the binary is newer,
865 * and do a restart instead.
867 send_to_pm(rp, PLEASE_START, fr->fs_path, fr->user, fr->group, 0, 0);
869 /* Avoid sleep/alarm interactions */
870 ap_select(0, NULL, NULL, NULL, &tv);
872 #ifdef WIN32
873 fr->lockFd = fr->fs->dynamic_lock;
874 result = 1;
875 #else
876 fr->lockFd = ap_popenf(rp, lockFileName, O_APPEND, 0);
877 result = (fr->lockFd < 0) ? (0) : (1);
878 #endif
879 } else {
880 struct timeval tv = {1, 0};
882 send_to_pm(rp, PLEASE_START, fr->fs_path, fr->user, fr->group, 0, 0);
884 #ifdef WIN32
885 Sleep(0);
886 #else
887 /* Avoid sleep/alarm interactions */
888 ap_select(0, NULL, NULL, NULL, &tv);
889 #endif
891 #ifdef WIN32
892 fr->fs = fcgi_util_fs_get_by_id(fr->fs_path, 0, 0);
893 #endif
894 } while (result != 1);
896 /* Block until we get a shared (non-exclusive) read Lock */
897 if (fcgi_wait_for_shared_read_lock(fr->lockFd) < 0)
898 return "failed to obtain a shared read lock";
900 #ifdef WIN32
901 ap_block_alarms();
902 ap_register_cleanup(rp, (void *) fr->lockFd, lock_cleanup, ap_null_cleanup);
903 ap_unblock_alarms();
904 #endif
906 FCGIDBG2("got_dynamic_shared_read_lock: %s", fr->fs_path);
909 #ifdef WIN32
910 if (socket_path)
912 BOOL ready;
913 int connect_time;
915 DWORD interval;
916 int max_connect_time = FCGI_NAMED_PIPE_CONNECT_TIMEOUT;
918 fr->using_npipe_io = TRUE;
920 if (fr->dynamic)
922 interval = dynamicPleaseStartDelay * 1000;
924 if (dynamicAppConnectTimeout) {
925 max_connect_time = dynamicAppConnectTimeout;
928 else
930 interval = FCGI_NAMED_PIPE_CONNECT_TIMEOUT * 1000;
932 if (fr->fs->appConnectTimeout) {
933 max_connect_time = fr->fs->appConnectTimeout;
937 if (fcgi_util_gettimeofday(&fr->startTime) < 0) {
938 return "gettimeofday() failed";
943 fr->fd = (SOCKET) CreateFile(socket_path,
944 GENERIC_READ | GENERIC_WRITE,
945 FILE_SHARE_READ | FILE_SHARE_WRITE,
946 NULL, // no security attributes
947 OPEN_EXISTING, // opens existing pipe
948 FILE_ATTRIBUTE_NORMAL, // default attributes
949 NULL); // no template file
951 if (fr->fd != (SOCKET) INVALID_HANDLE_VALUE) {
952 break;
955 if (GetLastError() != ERROR_PIPE_BUSY) {
956 return("CreateFile() failed ()");
959 // All pipe instances are busy, so wait
960 ready = WaitNamedPipe(socket_path, interval);
962 if (fr->dynamic && !ready) {
963 send_to_pm(rp, CONN_TIMEOUT, fr->fs_path, fr->user, fr->group, 0, 0);
966 if (fcgi_util_gettimeofday(&fr->queueTime) < 0) {
967 return "gettimeofday() failed";
970 connect_time = fr->queueTime.tv_sec - fr->startTime.tv_sec;
972 FCGIDBG5("interval=%d, max_connect_time=%d, connect_time=%d, ready=%d", interval, max_connect_time, connect_time, ready);
974 } while (connect_time < max_connect_time);
976 if (fr->fd == (SOCKET) INVALID_HANDLE_VALUE) {
977 return "CreateFile()/WaitNamedPipe() timed out";
980 FCGIDBG2("got_named_pipe_connect: %s", fr->fs_path);
982 ap_block_alarms();
983 ap_note_cleanups_for_h(rp, (HANDLE) fr->fd);
984 ap_unblock_alarms();
986 return NULL;
988 #endif
990 /* Create the socket */
991 fr->fd = ap_psocket(rp, socket_addr->sa_family, SOCK_STREAM, 0);
993 if (fr->fd < 0)
994 return "ap_psocket() failed";
996 #ifndef WIN32
997 if (fr->fd >= FD_SETSIZE) {
998 return ap_psprintf(rp, "socket file descriptor (%u) is larger than "
999 "FD_SETSIZE (%u), you probably need to rebuild Apache with a "
1000 "larger FD_SETSIZE", fr->fd, FD_SETSIZE);
1002 #endif
1004 /* If appConnectTimeout is non-zero, setup do a non-blocking connect */
1005 if ((fr->dynamic && dynamicAppConnectTimeout) || (!fr->dynamic && fr->fs->appConnectTimeout)) {
1006 #ifndef WIN32
1007 if ((fd_flags = fcntl(fr->fd, F_GETFL, 0)) < 0)
1008 return "fcntl(F_GETFL) failed";
1009 if (fcntl(fr->fd, F_SETFL, fd_flags | O_NONBLOCK) < 0)
1010 return "fcntl(F_SETFL) failed";
1011 #else
1012 ioctl_arg =1;
1013 if (ioctlsocket(fr->fd, FIONBIO, &ioctl_arg) != 0)
1014 return "ioctlsocket(FIONBIO) failed";
1015 #endif
1018 if (fr->dynamic && fcgi_util_gettimeofday(&fr->startTime) < 0)
1019 return "gettimeofday() failed";
1021 /* Connect */
1022 if (connect(fr->fd, (struct sockaddr *)socket_addr, socket_addr_len) == 0)
1023 goto ConnectionComplete;
1025 #ifdef WIN32
1026 errcode = GetLastError();
1027 if (errcode != WSAEWOULDBLOCK)
1028 return "connect() failed";
1029 #else
1030 /* ECONNREFUSED means the listen queue is full (or there isn't one).
1031 * With dynamic I can at least make sure the PM knows this is occuring */
1032 if (fr->dynamic && errno == ECONNREFUSED) {
1033 /* @@@ This might be better as some other "kind" of message */
1034 send_to_pm(rp, CONN_TIMEOUT, fr->fs_path, fr->user, fr->group, 0, 0);
1036 errno = ECONNREFUSED;
1039 if (errno != EINPROGRESS)
1040 return "connect() failed";
1041 #endif
1043 /* The connect() is non-blocking */
1045 errno = 0;
1047 if (fr->dynamic) {
1048 do {
1049 FD_ZERO(&write_fds);
1050 FD_SET(fr->fd, &write_fds);
1051 read_fds = write_fds;
1052 tval.tv_sec = dynamicPleaseStartDelay;
1053 tval.tv_usec = 0;
1055 status = ap_select((fr->fd+1), &read_fds, &write_fds, NULL, &tval);
1056 if (status < 0)
1057 break;
1059 if (fcgi_util_gettimeofday(&fr->queueTime) < 0)
1060 return "gettimeofday() failed";
1061 if (status > 0)
1062 break;
1064 /* select() timed out */
1065 send_to_pm(rp, CONN_TIMEOUT, fr->fs_path, fr->user, fr->group, 0, 0);
1066 } while ((fr->queueTime.tv_sec - fr->startTime.tv_sec) < (int)dynamicAppConnectTimeout);
1068 /* XXX These can be moved down when dynamic vars live is a struct */
1069 if (status == 0) {
1070 return ap_psprintf(rp, "connect() timed out (appConnTimeout=%dsec)",
1071 dynamicAppConnectTimeout);
1073 } /* dynamic */
1074 else {
1075 tval.tv_sec = fr->fs->appConnectTimeout;
1076 tval.tv_usec = 0;
1077 FD_ZERO(&write_fds);
1078 FD_SET(fr->fd, &write_fds);
1079 read_fds = write_fds;
1081 status = ap_select((fr->fd+1), &read_fds, &write_fds, NULL, &tval);
1082 if (status == 0) {
1083 return ap_psprintf(rp, "connect() timed out (appConnTimeout=%dsec)",
1084 fr->fs->appConnectTimeout);
1086 } /* !dynamic */
1088 if (status < 0)
1089 return "select() failed";
1091 if (FD_ISSET(fr->fd, &write_fds) || FD_ISSET(fr->fd, &read_fds)) {
1092 int error = 0;
1093 NET_SIZE_T len = sizeof(error);
1095 if (getsockopt(fr->fd, SOL_SOCKET, SO_ERROR, (char *)&error, &len) < 0)
1096 /* Solaris pending error */
1097 return "select() failed (Solaris pending error)";
1099 if (error != 0) {
1100 /* Berkeley-derived pending error */
1101 errno = error;
1102 return "select() failed (pending error)";
1104 } else
1105 return "select() error - THIS CAN'T HAPPEN!";
1107 ConnectionComplete:
1108 /* Return to blocking mode if it was set up */
1109 if ((fr->dynamic && dynamicAppConnectTimeout) || (!fr->dynamic && fr->fs->appConnectTimeout)) {
1110 #ifdef WIN32
1111 ioctl_arg = 0;
1112 if (ioctlsocket(fr->fd, FIONBIO, &ioctl_arg) != 0)
1113 return "ioctlsocket(FIONBIO) failed";
1114 #else
1115 if ((fcntl(fr->fd, F_SETFL, fd_flags)) < 0)
1116 return "fcntl(F_SETFL) failed";
1117 #endif
1120 #ifdef TCP_NODELAY
1121 if (socket_addr->sa_family == AF_INET) {
1122 /* We shouldn't be sending small packets and there's no application
1123 * level ack of the data we send, so disable Nagle */
1124 int set = 1;
1125 setsockopt(fr->fd, IPPROTO_TCP, TCP_NODELAY, (char *)&set, sizeof(set));
1127 #endif
1129 return NULL;
1132 static int server_error(fcgi_request *fr)
1134 #if defined(SIGPIPE) && MODULE_MAGIC_NUMBER < 19990320
1135 /* Make sure we leave with Apache's sigpipe_handler in place */
1136 if (fr->apache_sigpipe_handler != NULL)
1137 signal(SIGPIPE, fr->apache_sigpipe_handler);
1138 #endif
1139 close_connection_to_fs(fr);
1140 ap_kill_timeout(fr->r);
1141 return SERVER_ERROR;
1144 static void log_fcgi_server_stderr(void *data)
1146 const fcgi_request * const fr = (fcgi_request *)data;
1148 if (fr == NULL)
1149 return ;
1151 if (fr->fs_stderr_len) {
1152 ap_log_rerror(FCGI_LOG_ERR_NOERRNO, fr->r,
1153 "FastCGI: server \"%s\" stderr: %s", fr->fs_path, fr->fs_stderr);
1157 /*----------------------------------------------------------------------
1158 * This is the core routine for moving data between the FastCGI
1159 * application and the Web server's client.
1161 static int do_work(request_rec *r, fcgi_request *fr)
1163 struct timeval timeOut, dynamic_last_activity_time = {0, 0};
1164 fd_set read_set, write_set;
1165 int status = 0, idle_timeout;
1166 int numFDs, dynamic_first_read = fr->dynamic ? 1 : 0;
1167 int doClientWrite;
1168 int envSent = FALSE; /* has the complete ENV been buffered? */
1169 env_status env;
1170 pool *rp = r->pool;
1171 const char *err = NULL;
1173 FD_ZERO(&read_set);
1174 FD_ZERO(&write_set);
1176 fcgi_protocol_queue_begin_request(fr);
1178 /* Buffer as much of the environment as we can fit */
1179 env.envp = NULL;
1180 envSent = fcgi_protocol_queue_env(r, fr, &env);
1182 /* Start the Apache dropdead timer. See comments at top of file. */
1183 ap_hard_timeout("buffering of FastCGI client data", r);
1185 /* Read as much as possible from the client. */
1186 if (fr->role == FCGI_RESPONDER) {
1187 status = ap_setup_client_block(r, REQUEST_CHUNKED_ERROR);
1188 if (status != OK) {
1189 ap_kill_timeout(r);
1190 return status;
1192 fr->expectingClientContent = (ap_should_client_block(r) != 0);
1194 if (read_from_client_n_queue(fr) != OK)
1195 return server_error(fr);
1198 /* Connect to the FastCGI Application */
1199 ap_hard_timeout("connect() to FastCGI server", r);
1200 if ((err = open_connection_to_fs(fr))) {
1201 ap_log_rerror(FCGI_LOG_ERR, r,
1202 "FastCGI: failed to connect to server \"%s\": %s", fr->fs_path, err);
1203 return server_error(fr);
1206 numFDs = fr->fd + 1;
1207 idle_timeout = fr->dynamic ? dynamic_idle_timeout : fr->fs->idle_timeout;
1209 if (dynamic_first_read) {
1210 dynamic_last_activity_time = fr->startTime;
1212 if (dynamicAppConnectTimeout) {
1213 struct timeval qwait;
1214 timersub(&fr->queueTime, &fr->startTime, &qwait);
1215 dynamic_first_read = qwait.tv_sec / dynamicPleaseStartDelay + 1;
1219 /* @@@ We never reset the timer in this loop, most folks don't mess w/
1220 * Timeout directive which means we've got the 5 min default which is way
1221 * to long to tie up a fs. We need a better/configurable solution that
1222 * uses the select */
1223 ap_hard_timeout("FastCGI request processing", r);
1225 /* Register to get the script's stderr logged at the end of the request */
1226 ap_block_alarms();
1227 ap_register_cleanup(rp, (void *)fr, log_fcgi_server_stderr, ap_null_cleanup);
1228 ap_unblock_alarms();
1230 /* The socket is writeable, so get the first write out of the way */
1231 if (fcgi_buf_get_to_fd(fr->serverOutputBuffer, fr->fd) < 0) {
1232 ap_log_rerror(FCGI_LOG_ERR, r,
1233 "FastCGI: comm with server \"%s\" aborted: write failed", fr->fs_path);
1234 return server_error(fr);
1237 while (fr->keepReadingFromFcgiApp
1238 || BufferLength(fr->serverInputBuffer) > 0
1239 || BufferLength(fr->clientOutputBuffer) > 0) {
1241 /* If we didn't buffer all of the environment yet, buffer some more */
1242 if (!envSent)
1243 envSent = fcgi_protocol_queue_env(r, fr, &env);
1245 /* Read as much as possible from the client. */
1246 if (fr->role == FCGI_RESPONDER && !fr->eofSent && envSent) {
1247 if (read_from_client_n_queue(fr) != OK)
1248 return server_error(fr);
1251 /* To avoid deadlock, don't do a blocking select to write to
1252 * the FastCGI application without selecting to read from the
1253 * FastCGI application.
1255 doClientWrite = FALSE;
1256 if (fr->keepReadingFromFcgiApp && BufferFree(fr->serverInputBuffer) > 0) {
1258 #ifdef WIN32
1259 if (!fr->using_npipe_io) {
1260 #endif
1261 FD_SET(fr->fd, &read_set);
1263 /* Is data buffered for output to the FastCGI server? */
1264 if (BufferLength(fr->serverOutputBuffer) > 0) {
1265 FD_SET(fr->fd, &write_set);
1266 } else {
1267 FD_CLR(fr->fd, &write_set);
1269 #ifdef WIN32
1271 #endif
1273 * If there's data buffered to send to the client, don't
1274 * wait indefinitely for the FastCGI app; the app might
1275 * be doing server push.
1277 if (BufferLength(fr->clientOutputBuffer) > 0) {
1278 timeOut.tv_sec = 0;
1279 timeOut.tv_usec = 100000; /* 0.1 sec */
1281 else if (dynamic_first_read) {
1282 int delay;
1283 struct timeval qwait;
1285 if (fcgi_util_gettimeofday(&fr->queueTime) < 0) {
1286 ap_log_rerror(FCGI_LOG_ERR, r, "FastCGI: gettimeofday() failed");
1287 return server_error(fr);
1290 /* Check for idle_timeout */
1291 if (status) {
1292 dynamic_last_activity_time = fr->queueTime;
1294 else {
1295 struct timeval idle_time;
1296 timersub(&fr->queueTime, &dynamic_last_activity_time, &idle_time);
1297 if (idle_time.tv_sec > idle_timeout) {
1298 send_to_pm(rp, CONN_TIMEOUT, fr->fs_path, fr->user, fr->group, 0, 0);
1299 ap_log_rerror(FCGI_LOG_ERR_NOERRNO, r,
1300 "FastCGI: comm with (dynamic) server \"%s\" aborted: (first read) idle timeout (%d sec)",
1301 fr->fs_path, idle_timeout);
1302 return server_error(fr);
1306 timersub(&fr->queueTime, &fr->startTime, &qwait);
1308 delay = dynamic_first_read * dynamicPleaseStartDelay;
1309 if (qwait.tv_sec < delay) {
1310 timeOut.tv_sec = delay;
1311 timeOut.tv_usec = 100000; /* fudge for select() slop */
1312 timersub(&timeOut, &qwait, &timeOut);
1314 else {
1315 /* Killed time somewhere.. client read? */
1316 send_to_pm(rp, CONN_TIMEOUT, fr->fs_path, fr->user, fr->group, 0, 0);
1317 dynamic_first_read = qwait.tv_sec / dynamicPleaseStartDelay + 1;
1318 timeOut.tv_sec = dynamic_first_read * dynamicPleaseStartDelay;
1319 timeOut.tv_usec = 100000; /* fudge for select() slop */
1320 timersub(&timeOut, &qwait, &timeOut);
1323 else {
1324 timeOut.tv_sec = idle_timeout;
1325 timeOut.tv_usec = 0;
1328 #ifdef WIN32
1329 if (!fr->using_npipe_io) {
1330 #endif
1331 if ((status = ap_select(numFDs, &read_set, &write_set, NULL, &timeOut)) < 0) {
1332 ap_log_rerror(FCGI_LOG_ERR, r,
1333 "FastCGI: comm with server \"%s\" aborted: select() failed", fr->fs_path);
1334 return server_error(fr);
1336 #ifdef WIN32
1338 else {
1339 int stopTime = time(NULL) + timeOut.tv_sec;
1340 DWORD bytesavail=0;
1342 if (!(BufferLength(fr->serverOutputBuffer) > 0)) {
1343 status = 0;
1345 while ((timeOut.tv_sec != 0) && (time(NULL) <= stopTime)) {
1346 if (PeekNamedPipe((HANDLE) fr->fd,NULL, 0, NULL, &bytesavail, NULL) &&
1347 bytesavail > 0)
1349 status =1;
1350 break;
1352 Sleep(100);
1355 else {
1356 status = 1;
1359 #endif
1361 if (status == 0) {
1362 if (BufferLength(fr->clientOutputBuffer) > 0) {
1363 doClientWrite = TRUE;
1365 else if (dynamic_first_read) {
1366 struct timeval qwait;
1368 if (fcgi_util_gettimeofday(&fr->queueTime) < 0) {
1369 ap_log_rerror(FCGI_LOG_ERR, r, "FastCGI: gettimeofday() failed");
1370 return server_error(fr);
1373 timersub(&fr->queueTime, &fr->startTime, &qwait);
1375 send_to_pm(rp, CONN_TIMEOUT, fr->fs_path, fr->user, fr->group, 0, 0);
1377 dynamic_first_read = qwait.tv_sec / dynamicPleaseStartDelay + 1;
1379 else {
1380 ap_log_rerror(FCGI_LOG_ERR_NOERRNO, r,
1381 "FastCGI: comm with server \"%s\" aborted: idle timeout (%d sec)",
1382 fr->fs_path, idle_timeout);
1383 return server_error(fr);
1387 #if defined(SIGPIPE) && MODULE_MAGIC_NUMBER < 19990320
1388 /* Disable Apache's SIGPIPE handler */
1389 fr->apache_sigpipe_handler = signal(SIGPIPE, SIG_IGN);
1390 #endif
1392 /* Read from the FastCGI server */
1393 #ifdef WIN32
1394 if (((fr->using_npipe_io) &&
1395 (BufferFree(fr->serverInputBuffer) > 0)) || FD_ISSET(fr->fd, &read_set)) {
1396 #else
1397 if (FD_ISSET(fr->fd, &read_set)) {
1398 #endif
1399 if (dynamic_first_read) {
1400 dynamic_first_read = 0;
1401 if (fcgi_util_gettimeofday(&fr->queueTime) < 0) {
1402 ap_log_rerror(FCGI_LOG_ERR, r, "FastCGI: gettimeofday() failed");
1403 return server_error(fr);
1407 if ((status = fcgi_buf_add_fd(fr->serverInputBuffer, fr->fd)) < 0) {
1408 ap_log_rerror(FCGI_LOG_ERR, r,
1409 "FastCGI: comm with server \"%s\" aborted: read failed", fr->fs_path);
1410 return server_error(fr);
1413 if (status == 0) {
1414 fr->keepReadingFromFcgiApp = FALSE;
1415 close_connection_to_fs(fr);
1419 /* Write to the FastCGI server */
1420 #ifdef WIN32
1421 if (((fr->using_npipe_io) &&
1422 (BufferLength(fr->serverOutputBuffer) > 0)) || FD_ISSET(fr->fd, &write_set)) {
1423 #else
1424 if (FD_ISSET(fr->fd, &write_set)) {
1425 #endif
1427 if (fcgi_buf_get_to_fd(fr->serverOutputBuffer, fr->fd) < 0) {
1428 ap_log_rerror(FCGI_LOG_ERR, r,
1429 "FastCGI: comm with server \"%s\" aborted: write failed", fr->fs_path);
1430 return server_error(fr);
1434 #if defined(SIGPIPE) && MODULE_MAGIC_NUMBER < 19990320
1435 /* Reinstall Apache's SIGPIPE handler */
1436 signal(SIGPIPE, fr->apache_sigpipe_handler);
1437 #endif
1439 } else {
1440 doClientWrite = TRUE;
1443 if (fr->role == FCGI_RESPONDER && doClientWrite) {
1444 if (write_to_client(fr) != OK) {
1445 #if defined(SIGPIPE) && MODULE_MAGIC_NUMBER < 19990320
1446 /* Make sure we leave with Apache's sigpipe_handler in place */
1447 if (fr->apache_sigpipe_handler != NULL)
1448 signal(SIGPIPE, fr->apache_sigpipe_handler);
1449 #endif
1450 close_connection_to_fs(fr);
1451 ap_kill_timeout(fr->r);
1452 return OK;
1456 if (fcgi_protocol_dequeue(rp, fr) != OK)
1457 return server_error(fr);
1459 if (fr->keepReadingFromFcgiApp && fr->exitStatusSet) {
1460 /* we're done talking to the fcgi app */
1461 fr->keepReadingFromFcgiApp = FALSE;
1462 close_connection_to_fs(fr);
1465 if (fr->parseHeader == SCAN_CGI_READING_HEADERS) {
1466 if ((err = process_headers(r, fr))) {
1467 ap_log_rerror(FCGI_LOG_ERR, r,
1468 "FastCGI: comm with server \"%s\" aborted: error parsing headers: %s", fr->fs_path, err);
1469 return server_error(fr);
1473 } /* while */
1475 switch (fr->parseHeader) {
1477 case SCAN_CGI_FINISHED:
1478 if (fr->role == FCGI_RESPONDER) {
1479 #ifdef RUSSIAN_APACHE
1480 ap_rflush(r);
1481 #else
1482 ap_bflush(r->connection->client);
1483 #endif
1484 ap_bgetopt(r->connection->client, BO_BYTECT, &r->bytes_sent);
1486 break;
1488 case SCAN_CGI_READING_HEADERS:
1489 ap_log_rerror(FCGI_LOG_ERR, r,
1490 "FastCGI: incomplete headers (%d bytes) received from server \"%s\"",
1491 fr->header->nelts, fr->fs_path);
1492 return server_error(fr);
1494 case SCAN_CGI_BAD_HEADER:
1495 return server_error(fr);
1497 case SCAN_CGI_INT_REDIRECT:
1498 case SCAN_CGI_SRV_REDIRECT:
1500 * XXX We really should be soaking all client input
1501 * and all script output. See mod_cgi.c.
1502 * There's other differences we need to pick up here as well!
1503 * This has to be revisited.
1505 break;
1507 default:
1508 ap_assert(FALSE);
1511 ap_kill_timeout(r);
1512 return OK;
1516 static fcgi_request *create_fcgi_request(request_rec * const r, const char *fs_path)
1518 struct stat *my_finfo;
1519 pool * const p = r->pool;
1520 fcgi_server *fs;
1521 fcgi_request * const fr = (fcgi_request *)ap_pcalloc(p, sizeof(fcgi_request));
1523 if (fs_path) {
1524 my_finfo = (struct stat *)ap_palloc(p, sizeof(struct stat));
1525 if (stat(fs_path, my_finfo) < 0) {
1526 ap_log_rerror(FCGI_LOG_ERR, r, "FastCGI: stat() of \"%s\" failed", fs_path);
1527 return NULL;
1530 else {
1531 my_finfo = &r->finfo;
1532 fs_path = r->filename;
1535 fs = fcgi_util_fs_get_by_id(fs_path, r->server->server_uid, r->server->server_gid);
1536 if (fs == NULL) {
1537 /* Its a request for a dynamic FastCGI application */
1538 const char * const err =
1539 fcgi_util_fs_is_path_ok(p, fs_path, my_finfo, r->server->server_uid, r->server->server_gid);
1541 if (err) {
1542 ap_log_rerror(FCGI_LOG_ERR_NOERRNO, r, "FastCGI: invalid (dynamic) server \"%s\": %s", fs_path, err);
1543 return NULL;
1547 fr->serverInputBuffer = fcgi_buf_new(p, SERVER_BUFSIZE);
1548 fr->serverOutputBuffer = fcgi_buf_new(p, SERVER_BUFSIZE);
1549 fr->clientInputBuffer = fcgi_buf_new(p, SERVER_BUFSIZE);
1550 fr->clientOutputBuffer = fcgi_buf_new(p, SERVER_BUFSIZE);
1551 fr->erBufPtr = fcgi_buf_new(p, sizeof(FCGI_EndRequestBody) + 1);
1552 fr->gotHeader = FALSE;
1553 fr->parseHeader = SCAN_CGI_READING_HEADERS;
1554 fr->header = ap_make_array(p, 1, 1);
1555 fr->fs_stderr = NULL;
1556 fr->r = r;
1557 fr->readingEndRequestBody = FALSE;
1558 fr->exitStatus = 0;
1559 fr->exitStatusSet = FALSE;
1560 fr->requestId = 1; /* anything but zero is OK here */
1561 fr->eofSent = FALSE;
1562 fr->role = FCGI_RESPONDER;
1563 fr->expectingClientContent = FALSE;
1564 fr->keepReadingFromFcgiApp = TRUE;
1565 fr->fs = fs;
1566 fr->fs_path = fs_path;
1567 fr->authHeaders = ap_make_table(p, 10);
1568 #ifdef WIN32
1569 fr->fd = INVALID_SOCKET;
1570 fr->dynamic = ((fs == NULL) || (fs->directive == APP_CLASS_DYNAMIC)) ? TRUE : FALSE;
1571 fr->using_npipe_io = FALSE;
1572 #else
1573 fr->dynamic = (fs == NULL) ? TRUE : FALSE;
1574 fr->fd = -1;
1575 #endif
1577 set_uid_n_gid(r, &fr->user, &fr->group);
1579 return fr;
1583 *----------------------------------------------------------------------
1585 * handler --
1587 * This routine gets called for a request that corresponds to
1588 * a FastCGI connection. It performs the request synchronously.
1590 * Results:
1591 * Final status of request: OK or NOT_FOUND or SERVER_ERROR.
1593 * Side effects:
1594 * Request performed.
1596 *----------------------------------------------------------------------
1599 /* Stolen from mod_cgi.c..
1600 * KLUDGE --- for back-combatibility, we don't have to check ExecCGI
1601 * in ScriptAliased directories, which means we need to know if this
1602 * request came through ScriptAlias or not... so the Alias module
1603 * leaves a note for us.
1605 static int apache_is_scriptaliased(request_rec *r)
1607 const char *t = ap_table_get(r->notes, "alias-forced-type");
1608 return t && (!strcasecmp(t, "cgi-script"));
1611 /* If a script wants to produce its own Redirect body, it now
1612 * has to explicitly *say* "Status: 302". If it wants to use
1613 * Apache redirects say "Status: 200". See process_headers().
1615 static int post_process_for_redirects(request_rec * const r,
1616 const fcgi_request * const fr)
1618 switch(fr->parseHeader) {
1619 case SCAN_CGI_INT_REDIRECT:
1621 /* @@@ There are still differences between the handling in
1622 * mod_cgi and mod_fastcgi. This needs to be revisited.
1624 /* We already read the message body (if any), so don't allow
1625 * the redirected request to think it has one. We can ignore
1626 * Transfer-Encoding, since we used REQUEST_CHUNKED_ERROR.
1628 r->method = "GET";
1629 r->method_number = M_GET;
1630 ap_table_unset(r->headers_in, "Content-length");
1632 ap_internal_redirect_handler(ap_table_get(r->headers_out, "Location"), r);
1633 return OK;
1635 case SCAN_CGI_SRV_REDIRECT:
1636 return REDIRECT;
1638 default:
1639 return OK;
1643 /******************************************************************************
1644 * Process fastcgi-script requests. Based on mod_cgi::cgi_handler().
1646 static int content_handler(request_rec *r)
1648 fcgi_request *fr = NULL;
1649 int ret;
1651 /* Setup a new FastCGI request */
1652 if ((fr = create_fcgi_request(r, NULL)) == NULL)
1653 return SERVER_ERROR;
1655 /* If its a dynamic invocation, make sure scripts are OK here */
1656 if (fr->dynamic && !(ap_allow_options(r) & OPT_EXECCGI) && !apache_is_scriptaliased(r)) {
1657 ap_log_rerror(FCGI_LOG_ERR_NOERRNO, r,
1658 "FastCGI: \"ExecCGI Option\" is off in this directory: %s", r->uri);
1659 return SERVER_ERROR;
1662 /* Process the fastcgi-script request */
1663 if ((ret = do_work(r, fr)) != OK)
1664 return ret;
1666 /* Special case redirects */
1667 return post_process_for_redirects(r, fr);
1671 static int post_process_auth_passed_header(table *t, const char *key, const char * const val)
1673 if (strncasecmp(key, "Variable-", 9) == 0)
1674 key += 9;
1676 ap_table_setn(t, key, val);
1677 return 1;
1680 static int post_process_auth_passed_compat_header(table *t, const char *key, const char * const val)
1682 if (strncasecmp(key, "Variable-", 9) == 0)
1683 ap_table_setn(t, key + 9, val);
1685 return 1;
1688 static int post_process_auth_failed_header(table * const t, const char * const key, const char * const val)
1690 ap_table_setn(t, key, val);
1691 return 1;
1694 static void post_process_auth(fcgi_request * const fr, const int passed)
1696 request_rec * const r = fr->r;
1698 /* Restore the saved subprocess_env because we muddied ours up */
1699 r->subprocess_env = fr->saved_subprocess_env;
1701 if (passed) {
1702 if (fr->auth_compat) {
1703 ap_table_do((int (*)(void *, const char *, const char *))post_process_auth_passed_compat_header,
1704 (void *)r->subprocess_env, fr->authHeaders, NULL);
1706 else {
1707 ap_table_do((int (*)(void *, const char *, const char *))post_process_auth_passed_header,
1708 (void *)r->subprocess_env, fr->authHeaders, NULL);
1711 else {
1712 ap_table_do((int (*)(void *, const char *, const char *))post_process_auth_failed_header,
1713 (void *)r->err_headers_out, fr->authHeaders, NULL);
1716 /* @@@ Restore these.. its a hack until I rewrite the header handling */
1717 r->status = HTTP_OK;
1718 r->status_line = NULL;
1721 static int check_user_authentication(request_rec *r)
1723 int res, authenticated = 0;
1724 const char *password;
1725 fcgi_request *fr;
1726 const fcgi_dir_config * const dir_config =
1727 (const fcgi_dir_config *)ap_get_module_config(r->per_dir_config, &fastcgi_module);
1729 if (dir_config->authenticator == NULL)
1730 return DECLINED;
1732 /* Get the user password */
1733 if ((res = ap_get_basic_auth_pw(r, &password)) != OK)
1734 return res;
1736 if ((fr = create_fcgi_request(r, dir_config->authenticator)) == NULL)
1737 return SERVER_ERROR;
1739 /* Save the existing subprocess_env, because we're gonna muddy it up */
1740 fr->saved_subprocess_env = ap_copy_table(r->pool, r->subprocess_env);
1742 ap_table_setn(r->subprocess_env, "REMOTE_PASSWD", password);
1743 ap_table_setn(r->subprocess_env, "FCGI_APACHE_ROLE", "AUTHENTICATOR");
1745 /* The FastCGI Protocol doesn't differentiate authentication */
1746 fr->role = FCGI_AUTHORIZER;
1748 /* Do we need compatibility mode? */
1749 fr->auth_compat = (dir_config->authenticator_options & FCGI_COMPAT);
1751 if ((res = do_work(r, fr)) != OK)
1752 goto AuthenticationFailed;
1754 authenticated = (r->status == 200);
1755 post_process_auth(fr, authenticated);
1757 /* A redirect shouldn't be allowed during the authentication phase */
1758 if (ap_table_get(r->headers_out, "Location") != NULL) {
1759 ap_log_rerror(FCGI_LOG_ERR_NOERRNO, r,
1760 "FastCGI: FastCgiAuthenticator \"%s\" redirected (not allowed)",
1761 dir_config->authenticator);
1762 goto AuthenticationFailed;
1765 if (authenticated)
1766 return OK;
1768 AuthenticationFailed:
1769 if (!(dir_config->authenticator_options & FCGI_AUTHORITATIVE))
1770 return DECLINED;
1772 /* @@@ Probably should support custom_responses */
1773 ap_note_basic_auth_failure(r);
1774 ap_log_rerror(FCGI_LOG_ERR_NOERRNO, r,
1775 "FastCGI: authentication failed for user \"%s\": %s", r->connection->user, r->uri);
1776 return (res == OK) ? AUTH_REQUIRED : res;
1779 static int check_user_authorization(request_rec *r)
1781 int res, authorized = 0;
1782 fcgi_request *fr;
1783 const fcgi_dir_config * const dir_config =
1784 (const fcgi_dir_config *)ap_get_module_config(r->per_dir_config, &fastcgi_module);
1786 if (dir_config->authorizer == NULL)
1787 return DECLINED;
1789 /* @@@ We should probably honor the existing parameters to the require directive
1790 * as well as allow the definition of new ones (or use the basename of the
1791 * FastCGI server and pass the rest of the directive line), but for now keep
1792 * it simple. */
1794 if ((fr = create_fcgi_request(r, dir_config->authorizer)) == NULL)
1795 return SERVER_ERROR;
1797 /* Save the existing subprocess_env, because we're gonna muddy it up */
1798 fr->saved_subprocess_env = ap_copy_table(r->pool, r->subprocess_env);
1800 ap_table_setn(r->subprocess_env, "FCGI_APACHE_ROLE", "AUTHORIZER");
1802 fr->role = FCGI_AUTHORIZER;
1804 /* Do we need compatibility mode? */
1805 fr->auth_compat = (dir_config->authenticator_options & FCGI_COMPAT);
1807 if ((res = do_work(r, fr)) != OK)
1808 goto AuthorizationFailed;
1810 authorized = (r->status == 200);
1811 post_process_auth(fr, authorized);
1813 /* A redirect shouldn't be allowed during the authorization phase */
1814 if (ap_table_get(r->headers_out, "Location") != NULL) {
1815 ap_log_rerror(FCGI_LOG_ERR_NOERRNO, r,
1816 "FastCGI: FastCgiAuthorizer \"%s\" redirected (not allowed)",
1817 dir_config->authorizer);
1818 goto AuthorizationFailed;
1821 if (authorized)
1822 return OK;
1824 AuthorizationFailed:
1825 if (!(dir_config->authorizer_options & FCGI_AUTHORITATIVE))
1826 return DECLINED;
1828 /* @@@ Probably should support custom_responses */
1829 ap_note_basic_auth_failure(r);
1830 ap_log_rerror(FCGI_LOG_ERR_NOERRNO, r,
1831 "FastCGI: authorization failed for user \"%s\": %s", r->connection->user, r->uri);
1832 return (res == OK) ? AUTH_REQUIRED : res;
1835 static int check_access(request_rec *r)
1837 int res, access_allowed = 0;
1838 fcgi_request *fr;
1839 const fcgi_dir_config * const dir_config =
1840 (fcgi_dir_config *)ap_get_module_config(r->per_dir_config, &fastcgi_module);
1842 if (dir_config == NULL || dir_config->access_checker == NULL)
1843 return DECLINED;
1845 if ((fr = create_fcgi_request(r, dir_config->access_checker)) == NULL)
1846 return SERVER_ERROR;
1848 /* Save the existing subprocess_env, because we're gonna muddy it up */
1849 fr->saved_subprocess_env = ap_copy_table(r->pool, r->subprocess_env);
1851 ap_table_setn(r->subprocess_env, "FCGI_APACHE_ROLE", "ACCESS_CHECKER");
1853 /* The FastCGI Protocol doesn't differentiate access control */
1854 fr->role = FCGI_AUTHORIZER;
1856 /* Do we need compatibility mode? */
1857 fr->auth_compat = (dir_config->authenticator_options & FCGI_COMPAT);
1859 if ((res = do_work(r, fr)) != OK)
1860 goto AccessFailed;
1862 access_allowed = (r->status == 200);
1863 post_process_auth(fr, access_allowed);
1865 /* A redirect shouldn't be allowed during the access check phase */
1866 if (ap_table_get(r->headers_out, "Location") != NULL) {
1867 ap_log_rerror(FCGI_LOG_ERR_NOERRNO, r,
1868 "FastCGI: FastCgiAccessChecker \"%s\" redirected (not allowed)",
1869 dir_config->access_checker);
1870 goto AccessFailed;
1873 if (access_allowed)
1874 return OK;
1876 AccessFailed:
1877 if (!(dir_config->access_checker_options & FCGI_AUTHORITATIVE))
1878 return DECLINED;
1880 /* @@@ Probably should support custom_responses */
1881 ap_log_rerror(FCGI_LOG_ERR_NOERRNO, r, "FastCGI: access denied: %s", r->uri);
1882 return (res == OK) ? FORBIDDEN : res;
1887 command_rec fastcgi_cmds[] = {
1888 { "AppClass", fcgi_config_new_static_server, NULL, RSRC_CONF, RAW_ARGS, NULL },
1889 { "FastCgiServer", fcgi_config_new_static_server, NULL, RSRC_CONF, RAW_ARGS, NULL },
1891 { "ExternalAppClass", fcgi_config_new_external_server, NULL, RSRC_CONF, RAW_ARGS, NULL },
1892 { "FastCgiExternalServer", fcgi_config_new_external_server, NULL, RSRC_CONF, RAW_ARGS, NULL },
1894 { "FastCgiIpcDir", fcgi_config_set_socket_dir, NULL, RSRC_CONF, TAKE1, NULL },
1896 { "FastCgiSuexec", fcgi_config_set_suexec, NULL, RSRC_CONF, TAKE1, NULL },
1898 { "FCGIConfig", fcgi_config_set_config, NULL, RSRC_CONF, RAW_ARGS, NULL },
1899 { "FastCgiConfig", fcgi_config_set_config, NULL, RSRC_CONF, RAW_ARGS, NULL },
1901 { "FastCgiAuthenticator", fcgi_config_new_auth_server,
1902 (void *)FCGI_AUTH_TYPE_AUTHENTICATOR, ACCESS_CONF, TAKE12,
1903 "a fastcgi-script path (absolute or relative to ServerRoot) followed by an optional -compat" },
1904 { "FastCgiAuthenticatorAuthoritative", fcgi_config_set_authoritative_slot,
1905 (void *)XtOffsetOf(fcgi_dir_config, authenticator_options), ACCESS_CONF, FLAG,
1906 "Set to 'off' to allow authentication to be passed along to lower modules upon failure" },
1908 { "FastCgiAuthorizer", fcgi_config_new_auth_server,
1909 (void *)FCGI_AUTH_TYPE_AUTHORIZER, ACCESS_CONF, TAKE12,
1910 "a fastcgi-script path (absolute or relative to ServerRoot) followed by an optional -compat" },
1911 { "FastCgiAuthorizerAuthoritative", fcgi_config_set_authoritative_slot,
1912 (void *)XtOffsetOf(fcgi_dir_config, authorizer_options), ACCESS_CONF, FLAG,
1913 "Set to 'off' to allow authorization to be passed along to lower modules upon failure" },
1915 { "FastCgiAccessChecker", fcgi_config_new_auth_server,
1916 (void *)FCGI_AUTH_TYPE_ACCESS_CHECKER, ACCESS_CONF, TAKE12,
1917 "a fastcgi-script path (absolute or relative to ServerRoot) followed by an optional -compat" },
1918 { "FastCgiAccessCheckerAuthoritative", fcgi_config_set_authoritative_slot,
1919 (void *)XtOffsetOf(fcgi_dir_config, access_checker_options), ACCESS_CONF, FLAG,
1920 "Set to 'off' to allow access control to be passed along to lower modules upon failure" },
1921 { NULL }
1925 handler_rec fastcgi_handlers[] = {
1926 { FCGI_MAGIC_TYPE, content_handler },
1927 { "fastcgi-script", content_handler },
1928 { NULL }
1932 module MODULE_VAR_EXPORT fastcgi_module = {
1933 STANDARD_MODULE_STUFF,
1934 init_module, /* initializer */
1935 fcgi_config_create_dir_config, /* per-dir config creator */
1936 NULL, /* per-dir config merger (default: override) */
1937 NULL, /* per-server config creator */
1938 NULL, /* per-server config merger (default: override) */
1939 fastcgi_cmds, /* command table */
1940 fastcgi_handlers, /* [9] content handlers */
1941 NULL, /* [2] URI-to-filename translation */
1942 check_user_authentication, /* [5] authenticate user_id */
1943 check_user_authorization, /* [6] authorize user_id */
1944 check_access, /* [4] check access (based on src & http headers) */
1945 NULL, /* [7] check/set MIME type */
1946 NULL, /* [8] fixups */
1947 NULL, /* [10] logger */
1948 NULL, /* [3] header-parser */
1949 fcgi_child_init, /* process initialization */
1950 fcgi_child_exit, /* process exit/cleanup */
1951 NULL /* [1] post read-request handling */