*** empty log message ***
[mod_fastcgi.git] / mod_fastcgi.c
blob14e9408689a6d99dea21818fc04b91f7af16d7f8
1 /*
2 * mod_fastcgi.c --
4 * Apache server module for FastCGI.
6 * $Id: mod_fastcgi.c,v 1.98 2000/09/19 14:51:35 robs Exp $
8 * Copyright (c) 1995-1996 Open Market, Inc.
10 * See the file "LICENSE.TERMS" for information on usage and redistribution
11 * of this file, and for a DISCLAIMER OF ALL WARRANTIES.
14 * Patches for Apache-1.1 provided by
15 * Ralf S. Engelschall
16 * <rse@en.muc.de>
18 * Patches for Linux provided by
19 * Scott Langley
20 * <langles@vote-smart.org>
22 * Patches for suexec handling by
23 * Brian Grossman <brian@SoftHome.net> and
24 * Rob Saccoccio <robs@ipass.net>
28 * Module design notes.
30 * 1. Restart cleanup.
32 * mod_fastcgi spawns several processes: one process manager process
33 * and several application processes. None of these processes
34 * handle SIGHUP, so they just go away when the Web server performs
35 * a restart (as Apache does every time it starts.)
37 * In order to allow the process manager to properly cleanup the
38 * running fastcgi processes (without being disturbed by Apache),
39 * an intermediate process was introduced. The diagram is as follows;
41 * ApacheWS --> MiddleProc --> ProcMgr --> FCGI processes
43 * On a restart, ApacheWS sends a SIGKILL to MiddleProc and then
44 * collects it via waitpid(). The ProcMgr periodically checks for
45 * its parent (via getppid()) and if it does not have one, as in
46 * case when MiddleProc has terminated, ProcMgr issues a SIGTERM
47 * to all FCGI processes, waitpid()s on them and then exits, so it
48 * can be collected by init(1). Doing it any other way (short of
49 * changing Apache API), results either in inconsistent results or
50 * in generation of zombie processes.
52 * XXX: How does Apache 1.2 implement "gentle" restart
53 * that does not disrupt current connections? How does
54 * gentle restart interact with restart cleanup?
56 * 2. Request timeouts.
58 * 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 size_t 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 size_t 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 >= 0) {
745 ap_pclosesocket(rp, fr->fd);
748 if (fr->dynamic) {
749 #ifdef WIN32
750 if (fr->lockFd != NULL) {
751 fcgi_rdwr_unlock(fr->lockFd, READER);
753 #else
754 if (fr->lockFd >= 0) {
755 ap_pclosef(rp, fr->lockFd);
757 #endif
759 if (fr->keepReadingFromFcgiApp == FALSE) {
760 /* XXX REQ_COMPLETE is only sent for requests which complete
761 * normally WRT the fcgi app. There is no data sent for
762 * connect() timeouts or requests which complete abnormally.
763 * KillDynamicProcs() and RemoveRecords() need to be looked at
764 * to be sure they can reasonably handle these cases before
765 * sending these sort of stats - theres some funk in there.
766 * XXX We should do something special when this a pool cleanup.
768 if (fcgi_util_gettimeofday(&fr->completeTime) < 0) {
769 /* there's no point to aborting the request, just log it */
770 ap_log_error(FCGI_LOG_ERR, fr->r->server, "FastCGI: gettimeofday() failed");
771 } else {
772 struct timeval qtime, rtime;
774 timersub(&fr->queueTime, &fr->startTime, &qtime);
775 timersub(&fr->completeTime, &fr->queueTime, &rtime);
777 send_to_pm(rp, REQ_COMPLETE, fr->fs_path,
778 fr->user, fr->group,
779 qtime.tv_sec * 1000000 + qtime.tv_usec,
780 rtime.tv_sec * 1000000 + rtime.tv_usec);
786 #ifdef WIN32
787 static void lock_cleanup(void * data)
789 fcgi_rdwr_unlock((FcgiRWLock *) data, READER);
791 #endif
793 /*******************************************************************************
794 * Connect to the FastCGI server.
796 static const char *open_connection_to_fs(fcgi_request *fr)
798 struct timeval tval;
799 fd_set write_fds, read_fds;
800 int status;
801 request_rec * const r = fr->r;
802 pool * const rp = r->pool;
803 const char *socket_path = NULL;
804 struct sockaddr *socket_addr = NULL;
805 int socket_addr_len = 0;
806 #ifdef WIN32
807 unsigned long ioctl_arg;
808 int errcode;
809 #else
810 int fd_flags = 0;
811 const char *err = NULL;
812 #endif
814 /* Create the connection point */
815 if (fr->dynamic) {
816 socket_path = fcgi_util_socket_hash_filename(rp, fr->fs_path, fr->user, fr->group);
817 socket_path = fcgi_util_socket_make_path_absolute(rp, socket_path, 1);
819 #ifndef WIN32
820 err = fcgi_util_socket_make_domain_addr(rp, (struct sockaddr_un **)&socket_addr,
821 &socket_addr_len, socket_path);
822 if (err)
823 return err;
824 #endif
825 } else {
826 #ifdef WIN32
827 if (fr->fs->dest_addr != NULL) {
828 socket_addr = fr->fs->dest_addr;
830 else if (fr->fs->socket_addr) {
831 socket_addr = fr->fs->socket_addr;
833 else {
834 socket_path = fr->fs->socket_path;
836 #else
837 socket_addr = fr->fs->socket_addr;
838 #endif
839 socket_addr_len = fr->fs->socket_addr_len;
842 /* Dynamic app's lockfile handling */
843 if (fr->dynamic) {
844 #ifndef WIN32
845 const char *lockFileName = fcgi_util_socket_get_lock_filename(rp, socket_path);
846 struct stat lstbuf;
847 #endif
848 struct stat bstbuf;
849 int result = 0;
851 do {
852 #ifdef WIN32
853 if (fr->fs != NULL)
854 #else
855 if (stat(lockFileName, &lstbuf) == 0 && S_ISREG(lstbuf.st_mode))
856 #endif
858 if (dynamicAutoUpdate && (stat(fr->fs_path, &bstbuf) == 0)
859 #ifdef WIN32
860 && ((fr->fs->restartTime > 0) && (fr->fs->restartTime < bstbuf.st_mtime)))
861 #else
862 && (lstbuf.st_mtime < bstbuf.st_mtime))
863 #endif
865 struct timeval tv = {1, 0};
867 /* Its already running, but there's a newer one,
868 * ask the process manager to start it.
869 * it will notice that the binary is newer,
870 * and do a restart instead.
872 send_to_pm(rp, PLEASE_START, fr->fs_path, fr->user, fr->group, 0, 0);
874 /* Avoid sleep/alarm interactions */
875 ap_select(0, NULL, NULL, NULL, &tv);
877 #ifdef WIN32
878 fr->lockFd = fr->fs->dynamic_lock;
879 result = 1;
880 #else
881 fr->lockFd = ap_popenf(rp, lockFileName, O_APPEND, 0);
882 result = (fr->lockFd < 0) ? (0) : (1);
883 #endif
884 } else {
885 struct timeval tv = {1, 0};
887 send_to_pm(rp, PLEASE_START, fr->fs_path, fr->user, fr->group, 0, 0);
889 #ifdef WIN32
890 Sleep(0);
891 #else
892 /* Avoid sleep/alarm interactions */
893 ap_select(0, NULL, NULL, NULL, &tv);
894 #endif
896 #ifdef WIN32
897 fr->fs = fcgi_util_fs_get_by_id(fr->fs_path, 0, 0);
898 #endif
899 } while (result != 1);
901 /* Block until we get a shared (non-exclusive) read Lock */
902 if (fcgi_wait_for_shared_read_lock(fr->lockFd) < 0)
903 return "failed to obtain a shared read lock";
905 #ifdef WIN32
906 ap_block_alarms();
907 ap_register_cleanup(rp, (void *) fr->lockFd, lock_cleanup, ap_null_cleanup);
908 ap_unblock_alarms();
909 #endif
911 FCGIDBG2("got_dynamic_shared_read_lock: %s", fr->fs_path);
914 #ifdef WIN32
915 if (socket_path)
917 BOOL ready;
918 int connect_time;
920 DWORD interval;
921 int max_connect_time = FCGI_NAMED_PIPE_CONNECT_TIMEOUT;
923 fr->using_npipe_io = TRUE;
925 if (fr->dynamic)
927 interval = dynamicPleaseStartDelay * 1000;
929 if (dynamicAppConnectTimeout) {
930 max_connect_time = dynamicAppConnectTimeout;
933 else
935 interval = FCGI_NAMED_PIPE_CONNECT_TIMEOUT * 1000;
937 if (fr->fs->appConnectTimeout) {
938 max_connect_time = fr->fs->appConnectTimeout;
942 if (fcgi_util_gettimeofday(&fr->startTime) < 0) {
943 return "gettimeofday() failed";
948 fr->fd = (SOCKET) CreateFile(socket_path,
949 GENERIC_READ | GENERIC_WRITE,
950 FILE_SHARE_READ | FILE_SHARE_WRITE,
951 NULL, // no security attributes
952 OPEN_EXISTING, // opens existing pipe
953 FILE_ATTRIBUTE_NORMAL, // default attributes
954 NULL); // no template file
956 if (fr->fd != (SOCKET) INVALID_HANDLE_VALUE) {
957 break;
960 if (GetLastError() != ERROR_PIPE_BUSY) {
961 return("CreateFile() failed ()");
964 // All pipe instances are busy, so wait
965 ready = WaitNamedPipe(socket_path, interval);
967 if (fr->dynamic && !ready) {
968 send_to_pm(rp, CONN_TIMEOUT, fr->fs_path, fr->user, fr->group, 0, 0);
971 if (fcgi_util_gettimeofday(&fr->queueTime) < 0) {
972 return "gettimeofday() failed";
975 connect_time = fr->queueTime.tv_sec - fr->startTime.tv_sec;
977 FCGIDBG5("interval=%d, max_connect_time=%d, connect_time=%d, ready=%d", interval, max_connect_time, connect_time, ready);
979 } while (connect_time < max_connect_time);
981 if (fr->fd == (SOCKET) INVALID_HANDLE_VALUE) {
982 return "CreateFile()/WaitNamedPipe() timed out";
985 FCGIDBG2("got_named_pipe_connect: %s", fr->fs_path);
987 ap_block_alarms();
988 ap_note_cleanups_for_h(rp, (HANDLE) fr->fd);
989 ap_unblock_alarms();
991 return NULL;
993 #endif
995 /* Create the socket */
996 fr->fd = ap_psocket(rp, socket_addr->sa_family, SOCK_STREAM, 0);
998 if (fr->fd < 0)
999 return "ap_psocket() failed";
1001 #ifndef WIN32
1002 if (fr->fd >= FD_SETSIZE) {
1003 return ap_psprintf(rp, "socket file descriptor (%u) is larger than "
1004 "FD_SETSIZE (%u), you probably need to rebuild Apache with a "
1005 "larger FD_SETSIZE", fr->fd, FD_SETSIZE);
1007 #endif
1009 /* If appConnectTimeout is non-zero, setup do a non-blocking connect */
1010 if ((fr->dynamic && dynamicAppConnectTimeout) || (!fr->dynamic && fr->fs->appConnectTimeout)) {
1011 #ifndef WIN32
1012 if ((fd_flags = fcntl(fr->fd, F_GETFL, 0)) < 0)
1013 return "fcntl(F_GETFL) failed";
1014 if (fcntl(fr->fd, F_SETFL, fd_flags | O_NONBLOCK) < 0)
1015 return "fcntl(F_SETFL) failed";
1016 #else
1017 ioctl_arg =1;
1018 if (ioctlsocket(fr->fd, FIONBIO, &ioctl_arg) != 0)
1019 return "ioctlsocket(FIONBIO) failed";
1020 #endif
1023 if (fr->dynamic && fcgi_util_gettimeofday(&fr->startTime) < 0)
1024 return "gettimeofday() failed";
1026 /* Connect */
1027 if (connect(fr->fd, (struct sockaddr *)socket_addr, socket_addr_len) == 0)
1028 goto ConnectionComplete;
1030 #ifdef WIN32
1031 errcode = GetLastError();
1032 if (errcode != WSAEWOULDBLOCK)
1033 return "connect() failed";
1034 #else
1035 /* ECONNREFUSED means the listen queue is full (or there isn't one).
1036 * With dynamic I can at least make sure the PM knows this is occuring */
1037 if (fr->dynamic && errno == ECONNREFUSED) {
1038 /* @@@ This might be better as some other "kind" of message */
1039 send_to_pm(rp, CONN_TIMEOUT, fr->fs_path, fr->user, fr->group, 0, 0);
1041 errno = ECONNREFUSED;
1044 if (errno != EINPROGRESS)
1045 return "connect() failed";
1046 #endif
1048 /* The connect() is non-blocking */
1050 errno = 0;
1052 if (fr->dynamic) {
1053 do {
1054 FD_ZERO(&write_fds);
1055 FD_SET(fr->fd, &write_fds);
1056 read_fds = write_fds;
1057 tval.tv_sec = dynamicPleaseStartDelay;
1058 tval.tv_usec = 0;
1060 status = ap_select((fr->fd+1), &read_fds, &write_fds, NULL, &tval);
1061 if (status < 0)
1062 break;
1064 if (fcgi_util_gettimeofday(&fr->queueTime) < 0)
1065 return "gettimeofday() failed";
1066 if (status > 0)
1067 break;
1069 /* select() timed out */
1070 send_to_pm(rp, CONN_TIMEOUT, fr->fs_path, fr->user, fr->group, 0, 0);
1071 } while ((fr->queueTime.tv_sec - fr->startTime.tv_sec) < (int)dynamicAppConnectTimeout);
1073 /* XXX These can be moved down when dynamic vars live is a struct */
1074 if (status == 0) {
1075 return ap_psprintf(rp, "connect() timed out (appConnTimeout=%dsec)",
1076 dynamicAppConnectTimeout);
1078 } /* dynamic */
1079 else {
1080 tval.tv_sec = fr->fs->appConnectTimeout;
1081 tval.tv_usec = 0;
1082 FD_ZERO(&write_fds);
1083 FD_SET(fr->fd, &write_fds);
1084 read_fds = write_fds;
1086 status = ap_select((fr->fd+1), &read_fds, &write_fds, NULL, &tval);
1087 if (status == 0) {
1088 return ap_psprintf(rp, "connect() timed out (appConnTimeout=%dsec)",
1089 fr->fs->appConnectTimeout);
1091 } /* !dynamic */
1093 if (status < 0)
1094 return "select() failed";
1096 if (FD_ISSET(fr->fd, &write_fds) || FD_ISSET(fr->fd, &read_fds)) {
1097 int error = 0;
1098 NET_SIZE_T len = sizeof(error);
1100 if (getsockopt(fr->fd, SOL_SOCKET, SO_ERROR, (char *)&error, &len) < 0)
1101 /* Solaris pending error */
1102 return "select() failed (Solaris pending error)";
1104 if (error != 0) {
1105 /* Berkeley-derived pending error */
1106 errno = error;
1107 return "select() failed (pending error)";
1109 } else
1110 return "select() error - THIS CAN'T HAPPEN!";
1112 ConnectionComplete:
1113 /* Return to blocking mode if it was set up */
1114 if ((fr->dynamic && dynamicAppConnectTimeout) || (!fr->dynamic && fr->fs->appConnectTimeout)) {
1115 #ifdef WIN32
1116 ioctl_arg = 0;
1117 if (ioctlsocket(fr->fd, FIONBIO, &ioctl_arg) != 0)
1118 return "ioctlsocket(FIONBIO) failed";
1119 #else
1120 if ((fcntl(fr->fd, F_SETFL, fd_flags)) < 0)
1121 return "fcntl(F_SETFL) failed";
1122 #endif
1125 #ifdef TCP_NODELAY
1126 if (socket_addr->sa_family == AF_INET) {
1127 /* We shouldn't be sending small packets and there's no application
1128 * level ack of the data we send, so disable Nagle */
1129 int set = 1;
1130 setsockopt(fr->fd, IPPROTO_TCP, TCP_NODELAY, (char *)&set, sizeof(set));
1132 #endif
1134 return NULL;
1137 static int server_error(fcgi_request *fr)
1139 #if defined(SIGPIPE) && MODULE_MAGIC_NUMBER < 19990320
1140 /* Make sure we leave with Apache's sigpipe_handler in place */
1141 if (fr->apache_sigpipe_handler != NULL)
1142 signal(SIGPIPE, fr->apache_sigpipe_handler);
1143 #endif
1144 close_connection_to_fs(fr);
1145 ap_kill_timeout(fr->r);
1146 return SERVER_ERROR;
1149 static void log_fcgi_server_stderr(void *data)
1151 const fcgi_request * const fr = (fcgi_request *)data;
1153 if (fr == NULL)
1154 return ;
1156 if (fr->fs_stderr_len) {
1157 ap_log_rerror(FCGI_LOG_ERR_NOERRNO, fr->r,
1158 "FastCGI: server \"%s\" stderr: %s", fr->fs_path, fr->fs_stderr);
1162 /*----------------------------------------------------------------------
1163 * This is the core routine for moving data between the FastCGI
1164 * application and the Web server's client.
1166 static int do_work(request_rec *r, fcgi_request *fr)
1168 struct timeval timeOut, dynamic_last_activity_time = {0, 0};
1169 fd_set read_set, write_set;
1170 int status = 0, idle_timeout;
1171 int numFDs, dynamic_first_read = fr->dynamic ? 1 : 0;
1172 int doClientWrite;
1173 int envSent = FALSE; /* has the complete ENV been buffered? */
1174 env_status env;
1175 pool *rp = r->pool;
1176 const char *err = NULL;
1178 FD_ZERO(&read_set);
1179 FD_ZERO(&write_set);
1181 fcgi_protocol_queue_begin_request(fr);
1183 /* Buffer as much of the environment as we can fit */
1184 env.envp = NULL;
1185 envSent = fcgi_protocol_queue_env(r, fr, &env);
1187 /* Start the Apache dropdead timer. See comments at top of file. */
1188 ap_hard_timeout("buffering of FastCGI client data", r);
1190 /* Read as much as possible from the client. */
1191 if (fr->role == FCGI_RESPONDER) {
1192 status = ap_setup_client_block(r, REQUEST_CHUNKED_ERROR);
1193 if (status != OK) {
1194 ap_kill_timeout(r);
1195 return status;
1197 fr->expectingClientContent = (ap_should_client_block(r) != 0);
1199 if (read_from_client_n_queue(fr) != OK)
1200 return server_error(fr);
1203 /* Connect to the FastCGI Application */
1204 ap_hard_timeout("connect() to FastCGI server", r);
1205 if ((err = open_connection_to_fs(fr))) {
1206 ap_log_rerror(FCGI_LOG_ERR, r,
1207 "FastCGI: failed to connect to server \"%s\": %s", fr->fs_path, err);
1208 return server_error(fr);
1211 numFDs = fr->fd + 1;
1212 idle_timeout = fr->dynamic ? dynamic_idle_timeout : fr->fs->idle_timeout;
1214 if (dynamic_first_read) {
1215 dynamic_last_activity_time = fr->startTime;
1217 if (dynamicAppConnectTimeout) {
1218 struct timeval qwait;
1219 timersub(&fr->queueTime, &fr->startTime, &qwait);
1220 dynamic_first_read = qwait.tv_sec / dynamicPleaseStartDelay + 1;
1224 /* @@@ We never reset the timer in this loop, most folks don't mess w/
1225 * Timeout directive which means we've got the 5 min default which is way
1226 * to long to tie up a fs. We need a better/configurable solution that
1227 * uses the select */
1228 ap_hard_timeout("FastCGI request processing", r);
1230 /* Register to get the script's stderr logged at the end of the request */
1231 ap_block_alarms();
1232 ap_register_cleanup(rp, (void *)fr, log_fcgi_server_stderr, ap_null_cleanup);
1233 ap_unblock_alarms();
1235 /* The socket is writeable, so get the first write out of the way */
1236 if (fcgi_buf_get_to_fd(fr->serverOutputBuffer, fr->fd) < 0) {
1237 ap_log_rerror(FCGI_LOG_ERR, r,
1238 "FastCGI: comm with server \"%s\" aborted: write failed", fr->fs_path);
1239 return server_error(fr);
1242 while (fr->keepReadingFromFcgiApp
1243 || BufferLength(fr->serverInputBuffer) > 0
1244 || BufferLength(fr->clientOutputBuffer) > 0) {
1246 /* If we didn't buffer all of the environment yet, buffer some more */
1247 if (!envSent)
1248 envSent = fcgi_protocol_queue_env(r, fr, &env);
1250 /* Read as much as possible from the client. */
1251 if (fr->role == FCGI_RESPONDER && !fr->eofSent && envSent) {
1252 if (read_from_client_n_queue(fr) != OK)
1253 return server_error(fr);
1256 /* To avoid deadlock, don't do a blocking select to write to
1257 * the FastCGI application without selecting to read from the
1258 * FastCGI application.
1260 doClientWrite = FALSE;
1261 if (fr->keepReadingFromFcgiApp && BufferFree(fr->serverInputBuffer) > 0) {
1263 #ifdef WIN32
1264 if (!fr->using_npipe_io) {
1265 #endif
1266 FD_SET(fr->fd, &read_set);
1268 /* Is data buffered for output to the FastCGI server? */
1269 if (BufferLength(fr->serverOutputBuffer) > 0) {
1270 FD_SET(fr->fd, &write_set);
1271 } else {
1272 FD_CLR(fr->fd, &write_set);
1274 #ifdef WIN32
1276 #endif
1278 * If there's data buffered to send to the client, don't
1279 * wait indefinitely for the FastCGI app; the app might
1280 * be doing server push.
1282 if (BufferLength(fr->clientOutputBuffer) > 0) {
1283 timeOut.tv_sec = 0;
1284 timeOut.tv_usec = 100000; /* 0.1 sec */
1286 else if (dynamic_first_read) {
1287 int delay;
1288 struct timeval qwait;
1290 if (fcgi_util_gettimeofday(&fr->queueTime) < 0) {
1291 ap_log_rerror(FCGI_LOG_ERR, r, "FastCGI: gettimeofday() failed");
1292 return server_error(fr);
1295 /* Check for idle_timeout */
1296 if (status) {
1297 dynamic_last_activity_time = fr->queueTime;
1299 else {
1300 struct timeval idle_time;
1301 timersub(&fr->queueTime, &dynamic_last_activity_time, &idle_time);
1302 if (idle_time.tv_sec > idle_timeout) {
1303 send_to_pm(rp, CONN_TIMEOUT, fr->fs_path, fr->user, fr->group, 0, 0);
1304 ap_log_rerror(FCGI_LOG_ERR_NOERRNO, r,
1305 "FastCGI: comm with (dynamic) server \"%s\" aborted: (first read) idle timeout (%d sec)",
1306 fr->fs_path, idle_timeout);
1307 return server_error(fr);
1311 timersub(&fr->queueTime, &fr->startTime, &qwait);
1313 delay = dynamic_first_read * dynamicPleaseStartDelay;
1314 if (qwait.tv_sec < delay) {
1315 timeOut.tv_sec = delay;
1316 timeOut.tv_usec = 100000; /* fudge for select() slop */
1317 timersub(&timeOut, &qwait, &timeOut);
1319 else {
1320 /* Killed time somewhere.. client read? */
1321 send_to_pm(rp, CONN_TIMEOUT, fr->fs_path, fr->user, fr->group, 0, 0);
1322 dynamic_first_read = qwait.tv_sec / dynamicPleaseStartDelay + 1;
1323 timeOut.tv_sec = dynamic_first_read * dynamicPleaseStartDelay;
1324 timeOut.tv_usec = 100000; /* fudge for select() slop */
1325 timersub(&timeOut, &qwait, &timeOut);
1328 else {
1329 timeOut.tv_sec = idle_timeout;
1330 timeOut.tv_usec = 0;
1333 #ifdef WIN32
1334 if (!fr->using_npipe_io) {
1335 #endif
1336 if ((status = ap_select(numFDs, &read_set, &write_set, NULL, &timeOut)) < 0) {
1337 ap_log_rerror(FCGI_LOG_ERR, r,
1338 "FastCGI: comm with server \"%s\" aborted: select() failed", fr->fs_path);
1339 return server_error(fr);
1341 #ifdef WIN32
1343 else {
1344 int stopTime = time(NULL) + timeOut.tv_sec;
1345 DWORD bytesavail=0;
1347 if (!(BufferLength(fr->serverOutputBuffer) > 0)) {
1348 status = 0;
1350 while ((timeOut.tv_sec != 0) && (time(NULL) <= stopTime)) {
1351 if (PeekNamedPipe((HANDLE) fr->fd,NULL, 0, NULL, &bytesavail, NULL) &&
1352 bytesavail > 0)
1354 status =1;
1355 break;
1357 Sleep(100);
1360 else {
1361 status = 1;
1364 #endif
1366 if (status == 0) {
1367 if (BufferLength(fr->clientOutputBuffer) > 0) {
1368 doClientWrite = TRUE;
1370 else if (dynamic_first_read) {
1371 struct timeval qwait;
1373 if (fcgi_util_gettimeofday(&fr->queueTime) < 0) {
1374 ap_log_rerror(FCGI_LOG_ERR, r, "FastCGI: gettimeofday() failed");
1375 return server_error(fr);
1378 timersub(&fr->queueTime, &fr->startTime, &qwait);
1380 send_to_pm(rp, CONN_TIMEOUT, fr->fs_path, fr->user, fr->group, 0, 0);
1382 dynamic_first_read = qwait.tv_sec / dynamicPleaseStartDelay + 1;
1384 else {
1385 ap_log_rerror(FCGI_LOG_ERR_NOERRNO, r,
1386 "FastCGI: comm with server \"%s\" aborted: idle timeout (%d sec)",
1387 fr->fs_path, idle_timeout);
1388 return server_error(fr);
1392 #if defined(SIGPIPE) && MODULE_MAGIC_NUMBER < 19990320
1393 /* Disable Apache's SIGPIPE handler */
1394 fr->apache_sigpipe_handler = signal(SIGPIPE, SIG_IGN);
1395 #endif
1397 /* Read from the FastCGI server */
1398 #ifdef WIN32
1399 if (((fr->using_npipe_io) &&
1400 (BufferFree(fr->serverInputBuffer) > 0)) || FD_ISSET(fr->fd, &read_set)) {
1401 #else
1402 if (FD_ISSET(fr->fd, &read_set)) {
1403 #endif
1404 if (dynamic_first_read) {
1405 dynamic_first_read = 0;
1406 if (fcgi_util_gettimeofday(&fr->queueTime) < 0) {
1407 ap_log_rerror(FCGI_LOG_ERR, r, "FastCGI: gettimeofday() failed");
1408 return server_error(fr);
1412 if ((status = fcgi_buf_add_fd(fr->serverInputBuffer, fr->fd)) < 0) {
1413 ap_log_rerror(FCGI_LOG_ERR, r,
1414 "FastCGI: comm with server \"%s\" aborted: read failed", fr->fs_path);
1415 return server_error(fr);
1418 if (status == 0) {
1419 fr->keepReadingFromFcgiApp = FALSE;
1420 close_connection_to_fs(fr);
1424 /* Write to the FastCGI server */
1425 #ifdef WIN32
1426 if (((fr->using_npipe_io) &&
1427 (BufferLength(fr->serverOutputBuffer) > 0)) || FD_ISSET(fr->fd, &write_set)) {
1428 #else
1429 if (FD_ISSET(fr->fd, &write_set)) {
1430 #endif
1432 if (fcgi_buf_get_to_fd(fr->serverOutputBuffer, fr->fd) < 0) {
1433 ap_log_rerror(FCGI_LOG_ERR, r,
1434 "FastCGI: comm with server \"%s\" aborted: write failed", fr->fs_path);
1435 return server_error(fr);
1439 #if defined(SIGPIPE) && MODULE_MAGIC_NUMBER < 19990320
1440 /* Reinstall Apache's SIGPIPE handler */
1441 signal(SIGPIPE, fr->apache_sigpipe_handler);
1442 #endif
1444 } else {
1445 doClientWrite = TRUE;
1448 if (fr->role == FCGI_RESPONDER && doClientWrite) {
1449 if (write_to_client(fr) != OK) {
1450 #if defined(SIGPIPE) && MODULE_MAGIC_NUMBER < 19990320
1451 /* Make sure we leave with Apache's sigpipe_handler in place */
1452 if (fr->apache_sigpipe_handler != NULL)
1453 signal(SIGPIPE, fr->apache_sigpipe_handler);
1454 #endif
1455 close_connection_to_fs(fr);
1456 ap_kill_timeout(fr->r);
1457 return OK;
1461 if (fcgi_protocol_dequeue(rp, fr) != OK)
1462 return server_error(fr);
1464 if (fr->keepReadingFromFcgiApp && fr->exitStatusSet) {
1465 /* we're done talking to the fcgi app */
1466 fr->keepReadingFromFcgiApp = FALSE;
1467 close_connection_to_fs(fr);
1470 if (fr->parseHeader == SCAN_CGI_READING_HEADERS) {
1471 if ((err = process_headers(r, fr))) {
1472 ap_log_rerror(FCGI_LOG_ERR, r,
1473 "FastCGI: comm with server \"%s\" aborted: error parsing headers: %s", fr->fs_path, err);
1474 return server_error(fr);
1478 } /* while */
1480 switch (fr->parseHeader) {
1482 case SCAN_CGI_FINISHED:
1483 if (fr->role == FCGI_RESPONDER) {
1484 #ifdef RUSSIAN_APACHE
1485 ap_rflush(r);
1486 #else
1487 ap_bflush(r->connection->client);
1488 #endif
1489 ap_bgetopt(r->connection->client, BO_BYTECT, &r->bytes_sent);
1491 break;
1493 case SCAN_CGI_READING_HEADERS:
1494 ap_log_rerror(FCGI_LOG_ERR, r,
1495 "FastCGI: incomplete headers (%d bytes) received from server \"%s\"",
1496 fr->header->nelts, fr->fs_path);
1497 return server_error(fr);
1499 case SCAN_CGI_BAD_HEADER:
1500 return server_error(fr);
1502 case SCAN_CGI_INT_REDIRECT:
1503 case SCAN_CGI_SRV_REDIRECT:
1505 * XXX We really should be soaking all client input
1506 * and all script output. See mod_cgi.c.
1507 * There's other differences we need to pick up here as well!
1508 * This has to be revisited.
1510 break;
1512 default:
1513 ap_assert(FALSE);
1516 ap_kill_timeout(r);
1517 return OK;
1521 static fcgi_request *create_fcgi_request(request_rec * const r, const char *fs_path)
1523 struct stat *my_finfo;
1524 pool * const p = r->pool;
1525 fcgi_server *fs;
1526 fcgi_request * const fr = (fcgi_request *)ap_pcalloc(p, sizeof(fcgi_request));
1528 if (fs_path) {
1529 my_finfo = (struct stat *)ap_palloc(p, sizeof(struct stat));
1530 if (stat(fs_path, my_finfo) < 0) {
1531 ap_log_rerror(FCGI_LOG_ERR, r, "FastCGI: stat() of \"%s\" failed", fs_path);
1532 return NULL;
1535 else {
1536 my_finfo = &r->finfo;
1537 fs_path = r->filename;
1540 fs = fcgi_util_fs_get_by_id(fs_path, r->server->server_uid, r->server->server_gid);
1541 if (fs == NULL) {
1542 /* Its a request for a dynamic FastCGI application */
1543 const char * const err =
1544 fcgi_util_fs_is_path_ok(p, fs_path, my_finfo, r->server->server_uid, r->server->server_gid);
1546 if (err) {
1547 ap_log_rerror(FCGI_LOG_ERR_NOERRNO, r, "FastCGI: invalid (dynamic) server \"%s\": %s", fs_path, err);
1548 return NULL;
1552 fr->serverInputBuffer = fcgi_buf_new(p, SERVER_BUFSIZE);
1553 fr->serverOutputBuffer = fcgi_buf_new(p, SERVER_BUFSIZE);
1554 fr->clientInputBuffer = fcgi_buf_new(p, SERVER_BUFSIZE);
1555 fr->clientOutputBuffer = fcgi_buf_new(p, SERVER_BUFSIZE);
1556 fr->erBufPtr = fcgi_buf_new(p, sizeof(FCGI_EndRequestBody) + 1);
1557 fr->gotHeader = FALSE;
1558 fr->parseHeader = SCAN_CGI_READING_HEADERS;
1559 fr->header = ap_make_array(p, 1, 1);
1560 fr->fs_stderr = NULL;
1561 fr->r = r;
1562 fr->readingEndRequestBody = FALSE;
1563 fr->exitStatus = 0;
1564 fr->exitStatusSet = FALSE;
1565 fr->requestId = 1; /* anything but zero is OK here */
1566 fr->eofSent = FALSE;
1567 fr->role = FCGI_RESPONDER;
1568 fr->expectingClientContent = FALSE;
1569 fr->keepReadingFromFcgiApp = TRUE;
1570 fr->fs = fs;
1571 fr->fs_path = fs_path;
1572 fr->authHeaders = ap_make_table(p, 10);
1573 #ifdef WIN32
1574 fr->fd = INVALID_SOCKET;
1575 fr->dynamic = ((fs == NULL) || (fs->directive == APP_CLASS_DYNAMIC)) ? TRUE : FALSE;
1576 fr->using_npipe_io = FALSE;
1577 #else
1578 fr->dynamic = (fs == NULL) ? TRUE : FALSE;
1579 fr->fd = -1;
1580 fr->lockFd = -1;
1581 #endif
1583 set_uid_n_gid(r, &fr->user, &fr->group);
1585 return fr;
1589 *----------------------------------------------------------------------
1591 * handler --
1593 * This routine gets called for a request that corresponds to
1594 * a FastCGI connection. It performs the request synchronously.
1596 * Results:
1597 * Final status of request: OK or NOT_FOUND or SERVER_ERROR.
1599 * Side effects:
1600 * Request performed.
1602 *----------------------------------------------------------------------
1605 /* Stolen from mod_cgi.c..
1606 * KLUDGE --- for back-combatibility, we don't have to check ExecCGI
1607 * in ScriptAliased directories, which means we need to know if this
1608 * request came through ScriptAlias or not... so the Alias module
1609 * leaves a note for us.
1611 static int apache_is_scriptaliased(request_rec *r)
1613 const char *t = ap_table_get(r->notes, "alias-forced-type");
1614 return t && (!strcasecmp(t, "cgi-script"));
1617 /* If a script wants to produce its own Redirect body, it now
1618 * has to explicitly *say* "Status: 302". If it wants to use
1619 * Apache redirects say "Status: 200". See process_headers().
1621 static int post_process_for_redirects(request_rec * const r,
1622 const fcgi_request * const fr)
1624 switch(fr->parseHeader) {
1625 case SCAN_CGI_INT_REDIRECT:
1627 /* @@@ There are still differences between the handling in
1628 * mod_cgi and mod_fastcgi. This needs to be revisited.
1630 /* We already read the message body (if any), so don't allow
1631 * the redirected request to think it has one. We can ignore
1632 * Transfer-Encoding, since we used REQUEST_CHUNKED_ERROR.
1634 r->method = "GET";
1635 r->method_number = M_GET;
1636 ap_table_unset(r->headers_in, "Content-length");
1638 ap_internal_redirect_handler(ap_table_get(r->headers_out, "Location"), r);
1639 return OK;
1641 case SCAN_CGI_SRV_REDIRECT:
1642 return REDIRECT;
1644 default:
1645 return OK;
1649 /******************************************************************************
1650 * Process fastcgi-script requests. Based on mod_cgi::cgi_handler().
1652 static int content_handler(request_rec *r)
1654 fcgi_request *fr = NULL;
1655 int ret;
1657 /* Setup a new FastCGI request */
1658 if ((fr = create_fcgi_request(r, NULL)) == NULL)
1659 return SERVER_ERROR;
1661 /* If its a dynamic invocation, make sure scripts are OK here */
1662 if (fr->dynamic && !(ap_allow_options(r) & OPT_EXECCGI) && !apache_is_scriptaliased(r)) {
1663 ap_log_rerror(FCGI_LOG_ERR_NOERRNO, r,
1664 "FastCGI: \"ExecCGI Option\" is off in this directory: %s", r->uri);
1665 return SERVER_ERROR;
1668 /* Process the fastcgi-script request */
1669 if ((ret = do_work(r, fr)) != OK)
1670 return ret;
1672 /* Special case redirects */
1673 return post_process_for_redirects(r, fr);
1677 static int post_process_auth_passed_header(table *t, const char *key, const char * const val)
1679 if (strncasecmp(key, "Variable-", 9) == 0)
1680 key += 9;
1682 ap_table_setn(t, key, val);
1683 return 1;
1686 static int post_process_auth_passed_compat_header(table *t, const char *key, const char * const val)
1688 if (strncasecmp(key, "Variable-", 9) == 0)
1689 ap_table_setn(t, key + 9, val);
1691 return 1;
1694 static int post_process_auth_failed_header(table * const t, const char * const key, const char * const val)
1696 ap_table_setn(t, key, val);
1697 return 1;
1700 static void post_process_auth(fcgi_request * const fr, const int passed)
1702 request_rec * const r = fr->r;
1704 /* Restore the saved subprocess_env because we muddied ours up */
1705 r->subprocess_env = fr->saved_subprocess_env;
1707 if (passed) {
1708 if (fr->auth_compat) {
1709 ap_table_do((int (*)(void *, const char *, const char *))post_process_auth_passed_compat_header,
1710 (void *)r->subprocess_env, fr->authHeaders, NULL);
1712 else {
1713 ap_table_do((int (*)(void *, const char *, const char *))post_process_auth_passed_header,
1714 (void *)r->subprocess_env, fr->authHeaders, NULL);
1717 else {
1718 ap_table_do((int (*)(void *, const char *, const char *))post_process_auth_failed_header,
1719 (void *)r->err_headers_out, fr->authHeaders, NULL);
1722 /* @@@ Restore these.. its a hack until I rewrite the header handling */
1723 r->status = HTTP_OK;
1724 r->status_line = NULL;
1727 static int check_user_authentication(request_rec *r)
1729 int res, authenticated = 0;
1730 const char *password;
1731 fcgi_request *fr;
1732 const fcgi_dir_config * const dir_config =
1733 (const fcgi_dir_config *)ap_get_module_config(r->per_dir_config, &fastcgi_module);
1735 if (dir_config->authenticator == NULL)
1736 return DECLINED;
1738 /* Get the user password */
1739 if ((res = ap_get_basic_auth_pw(r, &password)) != OK)
1740 return res;
1742 if ((fr = create_fcgi_request(r, dir_config->authenticator)) == NULL)
1743 return SERVER_ERROR;
1745 /* Save the existing subprocess_env, because we're gonna muddy it up */
1746 fr->saved_subprocess_env = ap_copy_table(r->pool, r->subprocess_env);
1748 ap_table_setn(r->subprocess_env, "REMOTE_PASSWD", password);
1749 ap_table_setn(r->subprocess_env, "FCGI_APACHE_ROLE", "AUTHENTICATOR");
1751 /* The FastCGI Protocol doesn't differentiate authentication */
1752 fr->role = FCGI_AUTHORIZER;
1754 /* Do we need compatibility mode? */
1755 fr->auth_compat = (dir_config->authenticator_options & FCGI_COMPAT);
1757 if ((res = do_work(r, fr)) != OK)
1758 goto AuthenticationFailed;
1760 authenticated = (r->status == 200);
1761 post_process_auth(fr, authenticated);
1763 /* A redirect shouldn't be allowed during the authentication phase */
1764 if (ap_table_get(r->headers_out, "Location") != NULL) {
1765 ap_log_rerror(FCGI_LOG_ERR_NOERRNO, r,
1766 "FastCGI: FastCgiAuthenticator \"%s\" redirected (not allowed)",
1767 dir_config->authenticator);
1768 goto AuthenticationFailed;
1771 if (authenticated)
1772 return OK;
1774 AuthenticationFailed:
1775 if (!(dir_config->authenticator_options & FCGI_AUTHORITATIVE))
1776 return DECLINED;
1778 /* @@@ Probably should support custom_responses */
1779 ap_note_basic_auth_failure(r);
1780 ap_log_rerror(FCGI_LOG_ERR_NOERRNO, r,
1781 "FastCGI: authentication failed for user \"%s\": %s", r->connection->user, r->uri);
1782 return (res == OK) ? AUTH_REQUIRED : res;
1785 static int check_user_authorization(request_rec *r)
1787 int res, authorized = 0;
1788 fcgi_request *fr;
1789 const fcgi_dir_config * const dir_config =
1790 (const fcgi_dir_config *)ap_get_module_config(r->per_dir_config, &fastcgi_module);
1792 if (dir_config->authorizer == NULL)
1793 return DECLINED;
1795 /* @@@ We should probably honor the existing parameters to the require directive
1796 * as well as allow the definition of new ones (or use the basename of the
1797 * FastCGI server and pass the rest of the directive line), but for now keep
1798 * it simple. */
1800 if ((fr = create_fcgi_request(r, dir_config->authorizer)) == NULL)
1801 return SERVER_ERROR;
1803 /* Save the existing subprocess_env, because we're gonna muddy it up */
1804 fr->saved_subprocess_env = ap_copy_table(r->pool, r->subprocess_env);
1806 ap_table_setn(r->subprocess_env, "FCGI_APACHE_ROLE", "AUTHORIZER");
1808 fr->role = FCGI_AUTHORIZER;
1810 /* Do we need compatibility mode? */
1811 fr->auth_compat = (dir_config->authenticator_options & FCGI_COMPAT);
1813 if ((res = do_work(r, fr)) != OK)
1814 goto AuthorizationFailed;
1816 authorized = (r->status == 200);
1817 post_process_auth(fr, authorized);
1819 /* A redirect shouldn't be allowed during the authorization phase */
1820 if (ap_table_get(r->headers_out, "Location") != NULL) {
1821 ap_log_rerror(FCGI_LOG_ERR_NOERRNO, r,
1822 "FastCGI: FastCgiAuthorizer \"%s\" redirected (not allowed)",
1823 dir_config->authorizer);
1824 goto AuthorizationFailed;
1827 if (authorized)
1828 return OK;
1830 AuthorizationFailed:
1831 if (!(dir_config->authorizer_options & FCGI_AUTHORITATIVE))
1832 return DECLINED;
1834 /* @@@ Probably should support custom_responses */
1835 ap_note_basic_auth_failure(r);
1836 ap_log_rerror(FCGI_LOG_ERR_NOERRNO, r,
1837 "FastCGI: authorization failed for user \"%s\": %s", r->connection->user, r->uri);
1838 return (res == OK) ? AUTH_REQUIRED : res;
1841 static int check_access(request_rec *r)
1843 int res, access_allowed = 0;
1844 fcgi_request *fr;
1845 const fcgi_dir_config * const dir_config =
1846 (fcgi_dir_config *)ap_get_module_config(r->per_dir_config, &fastcgi_module);
1848 if (dir_config == NULL || dir_config->access_checker == NULL)
1849 return DECLINED;
1851 if ((fr = create_fcgi_request(r, dir_config->access_checker)) == NULL)
1852 return SERVER_ERROR;
1854 /* Save the existing subprocess_env, because we're gonna muddy it up */
1855 fr->saved_subprocess_env = ap_copy_table(r->pool, r->subprocess_env);
1857 ap_table_setn(r->subprocess_env, "FCGI_APACHE_ROLE", "ACCESS_CHECKER");
1859 /* The FastCGI Protocol doesn't differentiate access control */
1860 fr->role = FCGI_AUTHORIZER;
1862 /* Do we need compatibility mode? */
1863 fr->auth_compat = (dir_config->authenticator_options & FCGI_COMPAT);
1865 if ((res = do_work(r, fr)) != OK)
1866 goto AccessFailed;
1868 access_allowed = (r->status == 200);
1869 post_process_auth(fr, access_allowed);
1871 /* A redirect shouldn't be allowed during the access check phase */
1872 if (ap_table_get(r->headers_out, "Location") != NULL) {
1873 ap_log_rerror(FCGI_LOG_ERR_NOERRNO, r,
1874 "FastCGI: FastCgiAccessChecker \"%s\" redirected (not allowed)",
1875 dir_config->access_checker);
1876 goto AccessFailed;
1879 if (access_allowed)
1880 return OK;
1882 AccessFailed:
1883 if (!(dir_config->access_checker_options & FCGI_AUTHORITATIVE))
1884 return DECLINED;
1886 /* @@@ Probably should support custom_responses */
1887 ap_log_rerror(FCGI_LOG_ERR_NOERRNO, r, "FastCGI: access denied: %s", r->uri);
1888 return (res == OK) ? FORBIDDEN : res;
1893 command_rec fastcgi_cmds[] = {
1894 { "AppClass", fcgi_config_new_static_server, NULL, RSRC_CONF, RAW_ARGS, NULL },
1895 { "FastCgiServer", fcgi_config_new_static_server, NULL, RSRC_CONF, RAW_ARGS, NULL },
1897 { "ExternalAppClass", fcgi_config_new_external_server, NULL, RSRC_CONF, RAW_ARGS, NULL },
1898 { "FastCgiExternalServer", fcgi_config_new_external_server, NULL, RSRC_CONF, RAW_ARGS, NULL },
1900 { "FastCgiIpcDir", fcgi_config_set_socket_dir, NULL, RSRC_CONF, TAKE1, NULL },
1902 { "FastCgiSuexec", fcgi_config_set_suexec, NULL, RSRC_CONF, TAKE1, NULL },
1904 { "FCGIConfig", fcgi_config_set_config, NULL, RSRC_CONF, RAW_ARGS, NULL },
1905 { "FastCgiConfig", fcgi_config_set_config, NULL, RSRC_CONF, RAW_ARGS, NULL },
1907 { "FastCgiAuthenticator", fcgi_config_new_auth_server,
1908 (void *)FCGI_AUTH_TYPE_AUTHENTICATOR, ACCESS_CONF, TAKE12,
1909 "a fastcgi-script path (absolute or relative to ServerRoot) followed by an optional -compat" },
1910 { "FastCgiAuthenticatorAuthoritative", fcgi_config_set_authoritative_slot,
1911 (void *)XtOffsetOf(fcgi_dir_config, authenticator_options), ACCESS_CONF, FLAG,
1912 "Set to 'off' to allow authentication to be passed along to lower modules upon failure" },
1914 { "FastCgiAuthorizer", fcgi_config_new_auth_server,
1915 (void *)FCGI_AUTH_TYPE_AUTHORIZER, ACCESS_CONF, TAKE12,
1916 "a fastcgi-script path (absolute or relative to ServerRoot) followed by an optional -compat" },
1917 { "FastCgiAuthorizerAuthoritative", fcgi_config_set_authoritative_slot,
1918 (void *)XtOffsetOf(fcgi_dir_config, authorizer_options), ACCESS_CONF, FLAG,
1919 "Set to 'off' to allow authorization to be passed along to lower modules upon failure" },
1921 { "FastCgiAccessChecker", fcgi_config_new_auth_server,
1922 (void *)FCGI_AUTH_TYPE_ACCESS_CHECKER, ACCESS_CONF, TAKE12,
1923 "a fastcgi-script path (absolute or relative to ServerRoot) followed by an optional -compat" },
1924 { "FastCgiAccessCheckerAuthoritative", fcgi_config_set_authoritative_slot,
1925 (void *)XtOffsetOf(fcgi_dir_config, access_checker_options), ACCESS_CONF, FLAG,
1926 "Set to 'off' to allow access control to be passed along to lower modules upon failure" },
1927 { NULL }
1931 handler_rec fastcgi_handlers[] = {
1932 { FCGI_MAGIC_TYPE, content_handler },
1933 { "fastcgi-script", content_handler },
1934 { NULL }
1938 module MODULE_VAR_EXPORT fastcgi_module = {
1939 STANDARD_MODULE_STUFF,
1940 init_module, /* initializer */
1941 fcgi_config_create_dir_config, /* per-dir config creator */
1942 NULL, /* per-dir config merger (default: override) */
1943 NULL, /* per-server config creator */
1944 NULL, /* per-server config merger (default: override) */
1945 fastcgi_cmds, /* command table */
1946 fastcgi_handlers, /* [9] content handlers */
1947 NULL, /* [2] URI-to-filename translation */
1948 check_user_authentication, /* [5] authenticate user_id */
1949 check_user_authorization, /* [6] authorize user_id */
1950 check_access, /* [4] check access (based on src & http headers) */
1951 NULL, /* [7] check/set MIME type */
1952 NULL, /* [8] fixups */
1953 NULL, /* [10] logger */
1954 NULL, /* [3] header-parser */
1955 fcgi_child_init, /* process initialization */
1956 fcgi_child_exit, /* process exit/cleanup */
1957 NULL /* [1] post read-request handling */