Call WSASetLastError() instead of SetLastError()
[mod_fastcgi.git] / mod_fastcgi.c
blob1623f779485fcb5e1127f0da80ce1225dfcfce4a
1 /*
2 * mod_fastcgi.c --
4 * Apache server module for FastCGI.
6 * $Id: mod_fastcgi.c,v 1.125 2002/03/04 02:29:33 robs Exp $
8 * Copyright (c) 1995-1996 Open Market, Inc.
10 * See the file "LICENSE.TERMS" for information on usage and redistribution
11 * of this file, and for a DISCLAIMER OF ALL WARRANTIES.
14 * Patches for Apache-1.1 provided by
15 * Ralf S. Engelschall
16 * <rse@en.muc.de>
18 * Patches for Linux provided by
19 * Scott Langley
20 * <langles@vote-smart.org>
22 * Patches for suexec handling by
23 * Brian Grossman <brian@SoftHome.net> and
24 * Rob Saccoccio <robs@ipass.net>
28 * Module design notes.
30 * 1. Restart cleanup.
32 * mod_fastcgi spawns several processes: one process manager process
33 * and several application processes. None of these processes
34 * handle SIGHUP, so they just go away when the Web server performs
35 * a restart (as Apache does every time it starts.)
37 * In order to allow the process manager to properly cleanup the
38 * running fastcgi processes (without being disturbed by Apache),
39 * an intermediate process was introduced. The diagram is as follows;
41 * ApacheWS --> MiddleProc --> ProcMgr --> FCGI processes
43 * On a restart, ApacheWS sends a SIGKILL to MiddleProc and then
44 * collects it via waitpid(). The ProcMgr periodically checks for
45 * its parent (via getppid()) and if it does not have one, as in
46 * case when MiddleProc has terminated, ProcMgr issues a SIGTERM
47 * to all FCGI processes, waitpid()s on them and then exits, so it
48 * can be collected by init(1). Doing it any other way (short of
49 * changing Apache API), results either in inconsistent results or
50 * in generation of zombie processes.
52 * XXX: How does Apache 1.2 implement "gentle" restart
53 * that does not disrupt current connections? How does
54 * gentle restart interact with restart cleanup?
56 * 2. Request timeouts.
58 * Earlier versions of this module used ap_soft_timeout() rather than
59 * ap_hard_timeout() and ate FastCGI server output until it completed.
60 * This precluded the FastCGI server from having to implement a
61 * SIGPIPE handler, but meant hanging the application longer than
62 * necessary. SIGPIPE handler now must be installed in ALL FastCGI
63 * applications. The handler should abort further processing and go
64 * back into the accept() loop.
66 * Although using ap_soft_timeout() is better than ap_hard_timeout()
67 * we have to be more careful about SIGINT handling and subsequent
68 * processing, so, for now, make it hard.
72 #include "fcgi.h"
74 #ifndef timersub
75 #define timersub(a, b, result) \
76 do { \
77 (result)->tv_sec = (a)->tv_sec - (b)->tv_sec; \
78 (result)->tv_usec = (a)->tv_usec - (b)->tv_usec; \
79 if ((result)->tv_usec < 0) { \
80 --(result)->tv_sec; \
81 (result)->tv_usec += 1000000; \
82 } \
83 } while (0)
84 #endif
87 * Global variables
90 pool *fcgi_config_pool; /* the config pool */
91 server_rec *fcgi_apache_main_server;
93 const char *fcgi_wrapper = NULL; /* wrapper path */
94 uid_t fcgi_user_id; /* the run uid of Apache & PM */
95 gid_t fcgi_group_id; /* the run gid of Apache & PM */
97 fcgi_server *fcgi_servers = NULL; /* AppClasses */
99 char *fcgi_socket_dir = DEFAULT_SOCK_DIR; /* default FastCgiIpcDir */
101 char *fcgi_dynamic_dir = NULL; /* directory for the dynamic
102 * fastcgi apps' sockets */
104 #ifdef WIN32
106 #pragma warning( disable : 4706 4100 4127)
107 fcgi_pm_job *fcgi_dynamic_mbox = NULL;
108 HANDLE *fcgi_dynamic_mbox_mutex = NULL;
109 HANDLE fcgi_pm_thread = INVALID_HANDLE_VALUE;
111 #else
113 int fcgi_pm_pipe[2] = { -1, -1 };
114 pid_t fcgi_pm_pid = -1;
116 #endif
118 char *fcgi_empty_env = NULL;
120 u_int dynamicMaxProcs = FCGI_DEFAULT_MAX_PROCS;
121 int dynamicMinProcs = FCGI_DEFAULT_MIN_PROCS;
122 int dynamicMaxClassProcs = FCGI_DEFAULT_MAX_CLASS_PROCS;
123 u_int dynamicKillInterval = FCGI_DEFAULT_KILL_INTERVAL;
124 u_int dynamicUpdateInterval = FCGI_DEFAULT_UPDATE_INTERVAL;
125 float dynamicGain = FCGI_DEFAULT_GAIN;
126 int dynamicThreshold1 = FCGI_DEFAULT_THRESHOLD_1;
127 int dynamicThresholdN = FCGI_DEFAULT_THRESHOLD_N;
128 u_int dynamicPleaseStartDelay = FCGI_DEFAULT_START_PROCESS_DELAY;
129 u_int dynamicAppConnectTimeout = FCGI_DEFAULT_APP_CONN_TIMEOUT;
130 char **dynamicEnvp = &fcgi_empty_env;
131 u_int dynamicProcessSlack = FCGI_DEFAULT_PROCESS_SLACK;
132 int dynamicAutoRestart = FCGI_DEFAULT_RESTART_DYNAMIC;
133 int dynamicAutoUpdate = FCGI_DEFAULT_AUTOUPDATE;
134 int dynamicFlush = FCGI_FLUSH;
135 u_int dynamicListenQueueDepth = FCGI_DEFAULT_LISTEN_Q;
136 u_int dynamicInitStartDelay = DEFAULT_INIT_START_DELAY;
137 u_int dynamicRestartDelay = FCGI_DEFAULT_RESTART_DELAY;
138 array_header *dynamic_pass_headers = NULL;
139 u_int dynamic_idle_timeout = FCGI_DEFAULT_IDLE_TIMEOUT;
141 /*******************************************************************************
142 * Construct a message and write it to the pm_pipe.
144 static void send_to_pm(const char id, const char * const fs_path,
145 const char *user, const char * const group, const unsigned long q_usec,
146 const unsigned long req_usec)
148 #ifdef WIN32
149 fcgi_pm_job *job = NULL;
151 if (!(job = (fcgi_pm_job *) malloc(sizeof(fcgi_pm_job))))
152 return;
153 #else
154 static int failed_count = 0;
155 int buflen = 0;
156 char buf[FCGI_MAX_MSG_LEN];
157 #endif
159 if (strlen(fs_path) > FCGI_MAXPATH) {
160 ap_log_error(FCGI_LOG_ERR_NOERRNO, fcgi_apache_main_server,
161 "FastCGI: the path \"%s\" is too long (>%d) for a dynamic server", fs_path, FCGI_MAXPATH);
162 return;
165 switch(id) {
167 case FCGI_SERVER_START_JOB:
168 case FCGI_SERVER_RESTART_JOB:
169 #ifdef WIN32
170 job->id = id;
171 job->fs_path = strdup(fs_path);
172 job->user = strdup(user);
173 job->group = strdup(group);
174 job->qsec = 0L;
175 job->start_time = 0L;
176 #else
177 buflen = sprintf(buf, "%c %s %s %s*", id, fs_path, user, group);
178 #endif
179 break;
181 case FCGI_REQUEST_TIMEOUT_JOB:
182 #ifdef WIN32
183 job->id = id;
184 job->fs_path = strdup(fs_path);
185 job->user = strdup(user);
186 job->group = strdup(group);
187 job->qsec = 0L;
188 job->start_time = 0L;
189 #else
190 buflen = sprintf(buf, "%c %s %s %s*", id, fs_path, user, group);
191 #endif
192 break;
194 case FCGI_REQUEST_COMPLETE_JOB:
195 #ifdef WIN32
196 job->id = id;
197 job->fs_path = strdup(fs_path);
198 job->qsec = q_usec;
199 job->start_time = req_usec;
200 job->user = strdup(user);
201 job->group = strdup(group);
202 #else
203 buflen = sprintf(buf, "%c %s %s %s %lu %lu*", id, fs_path, user, group, q_usec, req_usec);
204 #endif
205 break;
208 #ifdef WIN32
209 if (fcgi_pm_add_job(job)) return;
211 SetEvent(fcgi_event_handles[MBOX_EVENT]);
212 #else
213 ap_assert(buflen <= FCGI_MAX_MSG_LEN);
215 /* There is no apache flag or function that can be used to id
216 * restart/shutdown pending so ignore the first few failures as
217 * once it breaks it will stay broke */
218 if (write(fcgi_pm_pipe[1], (const void *)buf, buflen) != buflen
219 && failed_count++ > 10)
221 ap_log_error(FCGI_LOG_WARN, fcgi_apache_main_server,
222 "FastCGI: write() to PM failed (ignore if a restart or shutdown is pending)");
224 #endif
228 *----------------------------------------------------------------------
230 * init_module
232 * An Apache module initializer, called by the Apache core
233 * after reading the server config.
235 * Start the process manager no matter what, since there may be a
236 * request for dynamic FastCGI applications without any being
237 * configured as static applications. Also, check for the existence
238 * and create if necessary a subdirectory into which all dynamic
239 * sockets will go.
241 *----------------------------------------------------------------------
243 static void init_module(server_rec *s, pool *p)
245 const char *err;
247 /* Register to reset to default values when the config pool is cleaned */
248 ap_block_alarms();
249 ap_register_cleanup(p, NULL, fcgi_config_reset_globals, ap_null_cleanup);
250 ap_unblock_alarms();
252 ap_add_version_component("mod_fastcgi/" MOD_FASTCGI_VERSION);
254 fcgi_config_set_fcgi_uid_n_gid(1);
256 /* keep these handy */
257 fcgi_config_pool = p;
258 fcgi_apache_main_server = s;
260 #ifndef WIN32
261 /* Create Unix/Domain socket directory */
262 if ((err = fcgi_config_make_dir(p, fcgi_socket_dir)))
263 ap_log_error(FCGI_LOG_ERR, s, "FastCGI: %s", err);
264 #endif
266 /* Create Dynamic directory */
267 if ((err = fcgi_config_make_dynamic_dir(p, 1)))
268 ap_log_error(FCGI_LOG_ERR, s, "FastCGI: %s", err);
270 #ifndef WIN32
271 /* Spawn the PM only once. Under Unix, Apache calls init() routines
272 * twice, once before detach() and once after. Win32 doesn't detach.
273 * Under DSO, DSO modules are unloaded between the two init() calls.
274 * Under Unix, the -X switch causes two calls to init() but no detach
275 * (but all subprocesses are wacked so the PM is toasted anyway)! */
277 if (ap_standalone && ap_restart_time == 0)
278 return;
280 /* Create the pipe for comm with the PM */
281 if (pipe(fcgi_pm_pipe) < 0) {
282 ap_log_error(FCGI_LOG_ERR, s, "FastCGI: pipe() failed");
285 /* Start the Process Manager */
286 fcgi_pm_pid = ap_spawn_child(p, fcgi_pm_main, NULL, kill_only_once, NULL, NULL, NULL);
287 if (fcgi_pm_pid <= 0) {
288 ap_log_error(FCGI_LOG_ALERT, s,
289 "FastCGI: can't start the process manager, spawn_child() failed");
292 close(fcgi_pm_pipe[0]);
293 #endif
296 static void fcgi_child_init(server_rec *dc0, pool *dc1)
298 #ifdef WIN32
299 /* Create the MBOX, TERM, and WAKE event handlers */
300 fcgi_event_handles[0] = CreateEvent(NULL, FALSE, FALSE, NULL);
301 if (fcgi_event_handles[0] == NULL) {
302 ap_log_error(FCGI_LOG_ALERT, fcgi_apache_main_server,
303 "FastCGI: CreateEvent() failed");
305 fcgi_event_handles[1] = CreateEvent(NULL, FALSE, FALSE, NULL);
306 if (fcgi_event_handles[1] == NULL) {
307 ap_log_error(FCGI_LOG_ALERT, fcgi_apache_main_server,
308 "FastCGI: CreateEvent() failed");
310 fcgi_event_handles[2] = CreateEvent(NULL, FALSE, FALSE, NULL);
311 if (fcgi_event_handles[2] == NULL) {
312 ap_log_error(FCGI_LOG_ALERT, fcgi_apache_main_server,
313 "FastCGI: CreateEvent() failed");
316 /* Create the mbox mutex (PM - request threads) */
317 fcgi_dynamic_mbox_mutex = CreateMutex(NULL, FALSE, NULL);
318 if (fcgi_dynamic_mbox_mutex == NULL) {
319 ap_log_error(FCGI_LOG_ALERT, fcgi_apache_main_server,
320 "FastCGI: CreateMutex() failed");
323 /* Spawn of the process manager thread */
324 fcgi_pm_thread = (HANDLE) _beginthread(fcgi_pm_main, 0, NULL);
325 if (fcgi_pm_thread == (HANDLE) -1) {
326 ap_log_error(FCGI_LOG_ALERT, fcgi_apache_main_server,
327 "_beginthread() failed to spawn the process manager");
329 #endif
331 return;
334 static void fcgi_child_exit(server_rec *dc0, pool *dc1)
336 #ifdef WIN32
337 /* Signal the PM thread to exit*/
338 SetEvent(fcgi_event_handles[TERM_EVENT]);
340 /* Waiting on pm thread to exit */
341 WaitForSingleObject(fcgi_pm_thread, INFINITE);
342 #endif
344 return;
348 *----------------------------------------------------------------------
350 * get_header_line --
352 * Terminate a line: scan to the next newline, scan back to the
353 * first non-space character and store a terminating zero. Return
354 * the next character past the end of the newline.
356 * If the end of the string is reached, ASSERT!
358 * If the FIRST character(s) in the line are '\n' or "\r\n", the
359 * first character is replaced with a NULL and next character
360 * past the newline is returned. NOTE: this condition supercedes
361 * the processing of RFC-822 continuation lines.
363 * If continuation is set to 'TRUE', then it parses a (possible)
364 * sequence of RFC-822 continuation lines.
366 * Results:
367 * As above.
369 * Side effects:
370 * Termination byte stored in string.
372 *----------------------------------------------------------------------
374 static char *get_header_line(char *start, int continuation)
376 char *p = start;
377 char *end = start;
379 if(p[0] == '\r' && p[1] == '\n') { /* If EOL in 1st 2 chars */
380 p++; /* point to \n and stop */
381 } else if(*p != '\n') {
382 if(continuation) {
383 while(*p != '\0') {
384 if(*p == '\n' && p[1] != ' ' && p[1] != '\t')
385 break;
386 p++;
388 } else {
389 while(*p != '\0' && *p != '\n') {
390 p++;
395 ap_assert(*p != '\0');
396 end = p;
397 end++;
400 * Trim any trailing whitespace.
402 while(isspace((unsigned char)p[-1]) && p > start) {
403 p--;
406 *p = '\0';
407 return end;
411 *----------------------------------------------------------------------
413 * process_headers --
415 * Call with r->parseHeader == SCAN_CGI_READING_HEADERS
416 * and initial script output in fr->header.
418 * If the initial script output does not include the header
419 * terminator ("\r\n\r\n") process_headers returns with no side
420 * effects, to be called again when more script output
421 * has been appended to fr->header.
423 * If the initial script output includes the header terminator,
424 * process_headers parses the headers and determines whether or
425 * not the remaining script output will be sent to the client.
426 * If so, process_headers sends the HTTP response headers to the
427 * client and copies any non-header script output to the output
428 * buffer reqOutbuf.
430 * Results:
431 * none.
433 * Side effects:
434 * May set r->parseHeader to:
435 * SCAN_CGI_FINISHED -- headers parsed, returning script response
436 * SCAN_CGI_BAD_HEADER -- malformed header from script
437 * SCAN_CGI_INT_REDIRECT -- handler should perform internal redirect
438 * SCAN_CGI_SRV_REDIRECT -- handler should return REDIRECT
440 *----------------------------------------------------------------------
443 static const char *process_headers(request_rec *r, fcgi_request *fr)
445 char *p, *next, *name, *value;
446 int len, flag;
447 int hasContentType, hasStatus, hasLocation;
449 ap_assert(fr->parseHeader == SCAN_CGI_READING_HEADERS);
451 if (fr->header == NULL)
452 return NULL;
455 * Do we have the entire header? Scan for the blank line that
456 * terminates the header.
458 p = (char *)fr->header->elts;
459 len = fr->header->nelts;
460 flag = 0;
461 while(len-- && flag < 2) {
462 switch(*p) {
463 case '\r':
464 break;
465 case '\n':
466 flag++;
467 break;
468 case '\0':
469 case '\v':
470 case '\f':
471 name = "Invalid Character";
472 goto BadHeader;
473 break;
474 default:
475 flag = 0;
476 break;
478 p++;
481 /* Return (to be called later when we have more data)
482 * if we don't have an entire header. */
483 if (flag < 2)
484 return NULL;
487 * Parse all the headers.
489 fr->parseHeader = SCAN_CGI_FINISHED;
490 hasContentType = hasStatus = hasLocation = FALSE;
491 next = (char *)fr->header->elts;
492 for(;;) {
493 next = get_header_line(name = next, TRUE);
494 if (*name == '\0') {
495 break;
497 if ((p = strchr(name, ':')) == NULL) {
498 goto BadHeader;
500 value = p + 1;
501 while (p != name && isspace((unsigned char)*(p - 1))) {
502 p--;
504 if (p == name) {
505 goto BadHeader;
507 *p = '\0';
508 if (strpbrk(name, " \t") != NULL) {
509 *p = ' ';
510 goto BadHeader;
512 while (isspace((unsigned char)*value)) {
513 value++;
516 if (strcasecmp(name, "Status") == 0) {
517 int statusValue = strtol(value, NULL, 10);
519 if (hasStatus) {
520 goto DuplicateNotAllowed;
522 if (statusValue < 0) {
523 fr->parseHeader = SCAN_CGI_BAD_HEADER;
524 return ap_psprintf(r->pool, "invalid Status '%s'", value);
526 hasStatus = TRUE;
527 r->status = statusValue;
528 r->status_line = ap_pstrdup(r->pool, value);
529 continue;
532 if (fr->role == FCGI_RESPONDER) {
533 if (strcasecmp(name, "Content-type") == 0) {
534 if (hasContentType) {
535 goto DuplicateNotAllowed;
537 hasContentType = TRUE;
538 r->content_type = ap_pstrdup(r->pool, value);
539 continue;
542 if (strcasecmp(name, "Location") == 0) {
543 if (hasLocation) {
544 goto DuplicateNotAllowed;
546 hasLocation = TRUE;
547 ap_table_set(r->headers_out, "Location", value);
548 continue;
551 /* If the script wants them merged, it can do it */
552 ap_table_add(r->err_headers_out, name, value);
553 continue;
555 else {
556 ap_table_add(fr->authHeaders, name, value);
560 if (fr->role != FCGI_RESPONDER)
561 return NULL;
564 * Who responds, this handler or Apache?
566 if (hasLocation) {
567 const char *location = ap_table_get(r->headers_out, "Location");
569 * Based on internal redirect handling in mod_cgi.c...
571 * If a script wants to produce its own Redirect
572 * body, it now has to explicitly *say* "Status: 302"
574 if (r->status == 200) {
575 if(location[0] == '/') {
577 * Location is an relative path. This handler will
578 * consume all script output, then have Apache perform an
579 * internal redirect.
581 fr->parseHeader = SCAN_CGI_INT_REDIRECT;
582 return NULL;
583 } else {
585 * Location is an absolute URL. If the script didn't
586 * produce a Content-type header, this handler will
587 * consume all script output and then have Apache generate
588 * its standard redirect response. Otherwise this handler
589 * will transmit the script's response.
591 fr->parseHeader = SCAN_CGI_SRV_REDIRECT;
592 return NULL;
597 * We're responding. Send headers, buffer excess script output.
599 ap_send_http_header(r);
601 /* We need to reinstate our timeout, send_http_header() kill()s it */
602 ap_hard_timeout("FastCGI request processing", r);
604 if (r->header_only)
605 return NULL;
607 len = fr->header->nelts - (next - fr->header->elts);
608 ap_assert(len >= 0);
609 ap_assert(BufferLength(fr->clientOutputBuffer) == 0);
610 if (BufferFree(fr->clientOutputBuffer) < len) {
611 fr->clientOutputBuffer = fcgi_buf_new(r->pool, len);
613 ap_assert(BufferFree(fr->clientOutputBuffer) >= len);
614 if (len > 0) {
615 int sent = fcgi_buf_add_block(fr->clientOutputBuffer, next, len);
616 ap_assert(sent == len);
618 return NULL;
620 BadHeader:
621 /* Log first line of a multi-line header */
622 if ((p = strpbrk(name, "\r\n")) != NULL)
623 *p = '\0';
624 fr->parseHeader = SCAN_CGI_BAD_HEADER;
625 return ap_psprintf(r->pool, "malformed header '%s'", name);
627 DuplicateNotAllowed:
628 fr->parseHeader = SCAN_CGI_BAD_HEADER;
629 return ap_psprintf(r->pool, "duplicate header '%s'", name);
633 * Read from the client filling both the FastCGI server buffer and the
634 * client buffer with the hopes of buffering the client data before
635 * making the connect() to the FastCGI server. This prevents slow
636 * clients from keeping the FastCGI server in processing longer than is
637 * necessary.
639 static int read_from_client_n_queue(fcgi_request *fr)
641 char *end;
642 int count;
643 long int countRead;
645 while (BufferFree(fr->clientInputBuffer) > 0 || BufferFree(fr->serverOutputBuffer) > 0) {
646 fcgi_protocol_queue_client_buffer(fr);
648 if (fr->expectingClientContent <= 0)
649 return OK;
651 fcgi_buf_get_free_block_info(fr->clientInputBuffer, &end, &count);
652 if (count == 0)
653 return OK;
655 if ((countRead = ap_get_client_block(fr->r, end, count)) < 0)
656 return -1;
658 if (countRead == 0) {
659 fr->expectingClientContent = 0;
661 else {
662 fcgi_buf_add_update(fr->clientInputBuffer, countRead);
663 ap_reset_timeout(fr->r);
666 return OK;
669 static int write_to_client(fcgi_request *fr)
671 char *begin;
672 int count;
674 fcgi_buf_get_block_info(fr->clientOutputBuffer, &begin, &count);
675 if (count == 0)
676 return OK;
678 /* If fewer than count bytes are written, an error occured.
679 * ap_bwrite() typically forces a flushed write to the client, this
680 * effectively results in a block (and short packets) - it should
681 * be fixed, but I didn't win much support for the idea on new-httpd.
682 * So, without patching Apache, the best way to deal with this is
683 * to size the fcgi_bufs to hold all of the script output (within
684 * reason) so the script can be released from having to wait around
685 * for the transmission to the client to complete. */
686 #ifdef RUSSIAN_APACHE
687 if (ap_rwrite(begin, count, fr->r) != count) {
688 ap_log_rerror(FCGI_LOG_INFO_NOERRNO, fr->r,
689 "FastCGI: client stopped connection before send body completed");
690 return -1;
692 #else
693 if (ap_bwrite(fr->r->connection->client, begin, count) != count) {
694 ap_log_rerror(FCGI_LOG_INFO_NOERRNO, fr->r,
695 "FastCGI: client stopped connection before send body completed");
696 return -1;
698 #endif
700 ap_reset_timeout(fr->r);
702 /* Don't bother with a wrapped buffer, limiting exposure to slow
703 * clients. The BUFF routines don't allow a writev from above,
704 * and don't always memcpy to minimize small write()s, this should
705 * be fixed, but I didn't win much support for the idea on
706 * new-httpd - I'll have to _prove_ its a problem first.. */
708 /* The default behaviour used to be to flush with every write, but this
709 * can tie up the FastCGI server longer than is necessary so its an option now */
710 if (fr->fs ? fr->fs->flush : dynamicFlush) {
711 #ifdef RUSSIAN_APACHE
712 if (ap_rflush(fr->r)) {
713 ap_log_rerror(FCGI_LOG_INFO_NOERRNO, fr->r,
714 "FastCGI: client stopped connection before send body completed");
715 return -1;
717 #else
718 if (ap_bflush(fr->r->connection->client)) {
719 ap_log_rerror(FCGI_LOG_INFO_NOERRNO, fr->r,
720 "FastCGI: client stopped connection before send body completed");
721 return -1;
723 #endif
724 ap_reset_timeout(fr->r);
727 fcgi_buf_toss(fr->clientOutputBuffer, count);
728 return OK;
731 /*******************************************************************************
732 * Determine the user and group the wrapper should be called with.
733 * Based on code in Apache's create_argv_cmd() (util_script.c).
735 static void set_uid_n_gid(request_rec *r, const char **user, const char **group)
737 if (fcgi_wrapper == NULL) {
738 *user = "-";
739 *group = "-";
740 return;
743 if (strncmp("/~", r->uri, 2) == 0) {
744 /* its a user dir uri, just send the ~user, and leave it to the PM */
745 char *end = strchr(r->uri + 2, '/');
747 if (end)
748 *user = memcpy(ap_pcalloc(r->pool, end - r->uri), r->uri + 1, end - r->uri - 1);
749 else
750 *user = ap_pstrdup(r->pool, r->uri + 1);
751 *group = "-";
753 else {
754 *user = ap_psprintf(r->pool, "%ld", (long)r->server->server_uid);
755 *group = ap_psprintf(r->pool, "%ld", (long)r->server->server_gid);
759 static void send_request_complete(fcgi_request *fr)
761 if (fr->completeTime.tv_sec)
763 struct timeval qtime, rtime;
765 timersub(&fr->queueTime, &fr->startTime, &qtime);
766 timersub(&fr->completeTime, &fr->queueTime, &rtime);
768 send_to_pm(FCGI_REQUEST_COMPLETE_JOB, fr->fs_path,
769 fr->user, fr->group,
770 qtime.tv_sec * 1000000 + qtime.tv_usec,
771 rtime.tv_sec * 1000000 + rtime.tv_usec);
775 #ifdef WIN32
777 static int set_nonblocking(const fcgi_request * fr, int nonblocking)
779 if (fr->using_npipe_io)
781 if (nonblocking)
783 DWORD mode = PIPE_NOWAIT | PIPE_READMODE_BYTE;
784 if (SetNamedPipeHandleState((HANDLE) fr->fd, &mode, NULL, NULL) == 0)
786 ap_log_rerror(FCGI_LOG_ERR, fr->r,
787 "FastCGI: SetNamedPipeHandleState() failed");
788 return -1;
792 else
794 unsigned long ioctl_arg = (nonblocking) ? 1 : 0;
795 if (ioctlsocket(fr->fd, FIONBIO, &ioctl_arg) != 0)
797 errno = WSAGetLastError();
798 ap_log_rerror(FCGI_LOG_ERR_ERRNO, fr->r,
799 "FastCGI: ioctlsocket() failed");
800 return -1;
804 return 0;
807 #else
809 static int set_nonblocking(const fcgi_request * fr, int nonblocking)
811 int nb_flag = 0;
812 int fd_flags = fcntl(fr->fd, F_GETFL, 0);
814 if (fd_flags < 0) return -1;
816 #if defined(O_NONBLOCK)
817 nb_flag = O_NONBLOCK;
818 #elif defined(O_NDELAY)
819 nb_flag = O_NDELAY;
820 #elif defined(FNDELAY)
821 nb_flag = FNDELAY;
822 #else
823 #error "TODO - don't read from app until all data from client is posted."
824 #endif
826 fd_flags = (nonblocking) ? (fd_flags | nb_flag) : (fd_flags & ~nb_flag);
828 return fcntl(fr->fd, F_SETFL, fd_flags);
831 #endif
833 /*******************************************************************************
834 * Close the connection to the FastCGI server. This is normally called by
835 * do_work(), but may also be called as in request pool cleanup.
837 static void close_connection_to_fs(fcgi_request *fr)
839 #ifdef WIN32
841 if (fr->fd != INVALID_SOCKET)
843 set_nonblocking(fr, FALSE);
845 if (fr->using_npipe_io)
847 CloseHandle((HANDLE) fr->fd);
849 else
851 closesocket(fr->fd);
854 fr->fd = INVALID_SOCKET;
857 #else /* ! WIN32 */
859 if (fr->fd >= 0)
861 set_nonblocking(fr, FALSE);
862 closesocket(fr->fd);
863 fr->fd = -1;
866 #endif /* ! WIN32 */
868 if (fr->dynamic && fr->keepReadingFromFcgiApp == FALSE)
870 /* XXX FCGI_REQUEST_COMPLETE_JOB is only sent for requests which complete
871 * normally WRT the fcgi app. There is no data sent for
872 * connect() timeouts or requests which complete abnormally.
873 * KillDynamicProcs() and RemoveRecords() need to be looked at
874 * to be sure they can reasonably handle these cases before
875 * sending these sort of stats - theres some funk in there.
877 if (fcgi_util_ticks(&fr->completeTime) < 0)
879 /* there's no point to aborting the request, just log it */
880 ap_log_error(FCGI_LOG_ERR, fr->r->server, "FastCGI: can't get time of day");
885 /*******************************************************************************
886 * Connect to the FastCGI server.
888 static int open_connection_to_fs(fcgi_request *fr)
890 struct timeval tval;
891 fd_set write_fds, read_fds;
892 int status;
893 request_rec * const r = fr->r;
894 pool * const rp = r->pool;
895 const char *socket_path = NULL;
896 struct sockaddr *socket_addr = NULL;
897 int socket_addr_len = 0;
898 #ifndef WIN32
899 const char *err = NULL;
900 #endif
902 /* Create the connection point */
903 if (fr->dynamic)
905 socket_path = fcgi_util_socket_hash_filename(rp, fr->fs_path, fr->user, fr->group);
906 socket_path = fcgi_util_socket_make_path_absolute(rp, socket_path, 1);
908 #ifndef WIN32
909 err = fcgi_util_socket_make_domain_addr(rp, (struct sockaddr_un **)&socket_addr,
910 &socket_addr_len, socket_path);
911 if (err) {
912 ap_log_rerror(FCGI_LOG_ERR, r,
913 "FastCGI: failed to connect to server \"%s\": "
914 "%s", fr->fs_path, err);
915 return FCGI_FAILED;
917 #endif
919 else
921 #ifdef WIN32
922 if (fr->fs->dest_addr != NULL) {
923 socket_addr = fr->fs->dest_addr;
925 else if (fr->fs->socket_addr) {
926 socket_addr = fr->fs->socket_addr;
928 else {
929 socket_path = fr->fs->socket_path;
931 #else
932 socket_addr = fr->fs->socket_addr;
933 #endif
934 socket_addr_len = fr->fs->socket_addr_len;
937 if (fr->dynamic)
939 #ifdef WIN32
940 if (fr->fs && fr->fs->restartTime)
941 #else
942 struct stat sock_stat;
944 if (stat(socket_path, &sock_stat) == 0)
945 #endif
947 // It exists
948 if (dynamicAutoUpdate)
950 struct stat app_stat;
952 /* TODO: follow sym links */
954 if (stat(fr->fs_path, &app_stat) == 0)
956 #ifdef WIN32
957 if (fr->fs->restartTime < app_stat.st_mtime)
958 #else
959 if (sock_stat.st_mtime < app_stat.st_mtime)
960 #endif
962 #ifndef WIN32
963 struct timeval tv = {1, 0};
964 #endif
966 * There's a newer one, request a restart.
968 send_to_pm(FCGI_SERVER_RESTART_JOB, fr->fs_path, fr->user, fr->group, 0, 0);
970 #ifdef WIN32
971 Sleep(1000);
972 #else
973 /* Avoid sleep/alarm interactions */
974 ap_select(0, NULL, NULL, NULL, &tv);
975 #endif
980 else
982 send_to_pm(FCGI_SERVER_START_JOB, fr->fs_path, fr->user, fr->group, 0, 0);
984 /* Wait until it looks like its running */
986 for (;;)
988 #ifdef WIN32
989 Sleep(1000);
991 fr->fs = fcgi_util_fs_get_by_id(fr->fs_path, 0, 0);
993 if (fr->fs && fr->fs->restartTime)
994 #else
995 struct timeval tv = {1, 0};
997 /* Avoid sleep/alarm interactions */
998 ap_select(0, NULL, NULL, NULL, &tv);
1000 if (stat(socket_path, &sock_stat) == 0)
1001 #endif
1003 break;
1009 #ifdef WIN32
1010 if (socket_path)
1012 BOOL ready;
1013 int connect_time;
1015 DWORD interval;
1016 int max_connect_time = FCGI_NAMED_PIPE_CONNECT_TIMEOUT;
1018 fr->using_npipe_io = TRUE;
1020 if (fr->dynamic)
1022 interval = dynamicPleaseStartDelay * 1000;
1024 if (dynamicAppConnectTimeout) {
1025 max_connect_time = dynamicAppConnectTimeout;
1028 else
1030 interval = FCGI_NAMED_PIPE_CONNECT_TIMEOUT * 1000;
1032 if (fr->fs->appConnectTimeout) {
1033 max_connect_time = fr->fs->appConnectTimeout;
1037 if (fcgi_util_ticks(&fr->startTime) < 0) {
1038 ap_log_rerror(FCGI_LOG_ERR, r,
1039 "FastCGI: failed to connect to server \"%s\": "
1040 "can't get time of day", fr->fs_path);
1041 return FCGI_FAILED;
1046 fr->fd = (SOCKET) CreateFile(socket_path,
1047 GENERIC_READ | GENERIC_WRITE,
1048 FILE_SHARE_READ | FILE_SHARE_WRITE,
1049 NULL, // no security attributes
1050 OPEN_EXISTING, // opens existing pipe
1051 FILE_ATTRIBUTE_NORMAL, // default attributes
1052 NULL); // no template file
1054 if (fr->fd != (SOCKET) INVALID_HANDLE_VALUE) {
1055 break;
1058 if (GetLastError() != ERROR_PIPE_BUSY
1059 && GetLastError() != ERROR_FILE_NOT_FOUND)
1061 ap_log_rerror(FCGI_LOG_ERR, r,
1062 "FastCGI: failed to connect to server \"%s\": "
1063 "CreateFile() failed", fr->fs_path);
1064 return FCGI_FAILED;
1067 // All pipe instances are busy, so wait
1068 ready = WaitNamedPipe(socket_path, interval);
1070 if (fr->dynamic && !ready) {
1071 send_to_pm(FCGI_REQUEST_TIMEOUT_JOB, fr->fs_path, fr->user, fr->group, 0, 0);
1074 if (fcgi_util_ticks(&fr->queueTime) < 0) {
1075 ap_log_rerror(FCGI_LOG_ERR, r,
1076 "FastCGI: failed to connect to server \"%s\": "
1077 "can't get time of day", fr->fs_path);
1078 return FCGI_FAILED;
1081 connect_time = fr->queueTime.tv_sec - fr->startTime.tv_sec;
1083 FCGIDBG5("interval=%d, max_connect_time=%d, connect_time=%d, ready=%d", interval, max_connect_time, connect_time, ready);
1085 } while (connect_time < max_connect_time);
1087 if (fr->fd == (SOCKET) INVALID_HANDLE_VALUE) {
1088 ap_log_rerror(FCGI_LOG_ERR, r,
1089 "FastCGI: failed to connect to server \"%s\": "
1090 "CreateFile()/WaitNamedPipe() timed out", fr->fs_path);
1091 fr->fd = INVALID_SOCKET;
1092 return FCGI_FAILED;
1095 FCGIDBG2("got_named_pipe_connect: %s", fr->fs_path);
1097 return FCGI_OK;
1099 #endif
1101 /* Create the socket */
1102 fr->fd = socket(socket_addr->sa_family, SOCK_STREAM, 0);
1104 #ifdef WIN32
1105 if (fr->fd == INVALID_SOCKET) {
1106 errno = WSAGetLastError(); // Not sure this is going to work as expected
1107 #else
1108 if (fr->fd < 0) {
1109 #endif
1110 ap_log_rerror(FCGI_LOG_ERR_ERRNO, r,
1111 "FastCGI: failed to connect to server \"%s\": "
1112 "socket() failed", fr->fs_path);
1113 return FCGI_FAILED;
1116 #ifndef WIN32
1117 if (fr->fd >= FD_SETSIZE) {
1118 ap_log_rerror(FCGI_LOG_ERR, r,
1119 "FastCGI: failed to connect to server \"%s\": "
1120 "socket file descriptor (%u) is larger than "
1121 "FD_SETSIZE (%u), you probably need to rebuild Apache with a "
1122 "larger FD_SETSIZE", fr->fs_path, fr->fd, FD_SETSIZE);
1123 return FCGI_FAILED;
1125 #endif
1127 /* If appConnectTimeout is non-zero, setup do a non-blocking connect */
1128 if ((fr->dynamic && dynamicAppConnectTimeout) || (!fr->dynamic && fr->fs->appConnectTimeout)) {
1129 set_nonblocking(fr, TRUE);
1132 if (fr->dynamic && fcgi_util_ticks(&fr->startTime) < 0) {
1133 ap_log_rerror(FCGI_LOG_ERR, r,
1134 "FastCGI: failed to connect to server \"%s\": "
1135 "can't get time of day", fr->fs_path);
1136 return FCGI_FAILED;
1139 /* Connect */
1140 if (connect(fr->fd, (struct sockaddr *)socket_addr, socket_addr_len) == 0)
1141 goto ConnectionComplete;
1143 #ifdef WIN32
1145 errno = WSAGetLastError();
1146 if (errno != WSAEWOULDBLOCK) {
1147 ap_log_rerror(FCGI_LOG_ERR_ERRNO, r,
1148 "FastCGI: failed to connect to server \"%s\": "
1149 "connect() failed", fr->fs_path);
1150 return FCGI_FAILED;
1153 #else
1155 /* ECONNREFUSED means the listen queue is full (or there isn't one).
1156 * With dynamic I can at least make sure the PM knows this is occuring */
1157 if (fr->dynamic && errno == ECONNREFUSED) {
1158 /* @@@ This might be better as some other "kind" of message */
1159 send_to_pm(FCGI_REQUEST_TIMEOUT_JOB, fr->fs_path, fr->user, fr->group, 0, 0);
1161 errno = ECONNREFUSED;
1164 if (errno != EINPROGRESS) {
1165 ap_log_rerror(FCGI_LOG_ERR, r,
1166 "FastCGI: failed to connect to server \"%s\": "
1167 "connect() failed", fr->fs_path);
1168 return FCGI_FAILED;
1171 #endif
1173 /* The connect() is non-blocking */
1175 errno = 0;
1177 if (fr->dynamic) {
1178 do {
1179 FD_ZERO(&write_fds);
1180 FD_SET(fr->fd, &write_fds);
1181 read_fds = write_fds;
1182 tval.tv_sec = dynamicPleaseStartDelay;
1183 tval.tv_usec = 0;
1185 status = ap_select((fr->fd+1), &read_fds, &write_fds, NULL, &tval);
1186 if (status < 0)
1187 break;
1189 if (fcgi_util_ticks(&fr->queueTime) < 0) {
1190 ap_log_rerror(FCGI_LOG_ERR, r,
1191 "FastCGI: failed to connect to server \"%s\": "
1192 "can't get time of day", fr->fs_path);
1193 return FCGI_FAILED;
1196 if (status > 0)
1197 break;
1199 /* select() timed out */
1200 send_to_pm(FCGI_REQUEST_TIMEOUT_JOB, fr->fs_path, fr->user, fr->group, 0, 0);
1201 } while ((fr->queueTime.tv_sec - fr->startTime.tv_sec) < (int)dynamicAppConnectTimeout);
1203 /* XXX These can be moved down when dynamic vars live is a struct */
1204 if (status == 0) {
1205 ap_log_rerror(FCGI_LOG_ERR_NOERRNO, r,
1206 "FastCGI: failed to connect to server \"%s\": "
1207 "connect() timed out (appConnTimeout=%dsec)",
1208 fr->fs_path, dynamicAppConnectTimeout);
1209 return FCGI_FAILED;
1211 } /* dynamic */
1212 else {
1213 tval.tv_sec = fr->fs->appConnectTimeout;
1214 tval.tv_usec = 0;
1215 FD_ZERO(&write_fds);
1216 FD_SET(fr->fd, &write_fds);
1217 read_fds = write_fds;
1219 status = ap_select((fr->fd+1), &read_fds, &write_fds, NULL, &tval);
1221 if (status == 0) {
1222 ap_log_rerror(FCGI_LOG_ERR_NOERRNO, r,
1223 "FastCGI: failed to connect to server \"%s\": "
1224 "connect() timed out (appConnTimeout=%dsec)",
1225 fr->fs_path, dynamicAppConnectTimeout);
1226 return FCGI_FAILED;
1228 } /* !dynamic */
1230 if (status < 0) {
1231 #ifdef WIN32
1232 errno = WSAGetLastError();
1233 #endif
1234 ap_log_rerror(FCGI_LOG_ERR_ERRNO, r,
1235 "FastCGI: failed to connect to server \"%s\": "
1236 "select() failed", fr->fs_path);
1237 return FCGI_FAILED;
1240 if (FD_ISSET(fr->fd, &write_fds) || FD_ISSET(fr->fd, &read_fds)) {
1241 int error = 0;
1242 NET_SIZE_T len = sizeof(error);
1244 if (getsockopt(fr->fd, SOL_SOCKET, SO_ERROR, (char *)&error, &len) < 0) {
1245 /* Solaris pending error */
1246 #ifdef WIN32
1247 errno = WSAGetLastError();
1248 #endif
1249 ap_log_rerror(FCGI_LOG_ERR_ERRNO, r,
1250 "FastCGI: failed to connect to server \"%s\": "
1251 "select() failed (Solaris pending error)", fr->fs_path);
1252 return FCGI_FAILED;
1255 if (error != 0) {
1256 /* Berkeley-derived pending error */
1257 errno = error;
1258 ap_log_rerror(FCGI_LOG_ERR_ERRNO, r,
1259 "FastCGI: failed to connect to server \"%s\": "
1260 "select() failed (pending error)", fr->fs_path);
1261 return FCGI_FAILED;
1264 else {
1265 #ifdef WIN32
1266 errno = WSAGetLastError();
1267 #endif
1268 ap_log_rerror(FCGI_LOG_ERR_ERRNO, r,
1269 "FastCGI: failed to connect to server \"%s\": "
1270 "select() error - THIS CAN'T HAPPEN!", fr->fs_path);
1271 return FCGI_FAILED;
1274 ConnectionComplete:
1275 /* Return to blocking mode if it was set up */
1276 if ((fr->dynamic && dynamicAppConnectTimeout) || (!fr->dynamic && fr->fs->appConnectTimeout)) {
1277 set_nonblocking(fr, FALSE);
1280 #ifdef TCP_NODELAY
1281 if (socket_addr->sa_family == AF_INET) {
1282 /* We shouldn't be sending small packets and there's no application
1283 * level ack of the data we send, so disable Nagle */
1284 int set = 1;
1285 setsockopt(fr->fd, IPPROTO_TCP, TCP_NODELAY, (char *)&set, sizeof(set));
1287 #endif
1289 return FCGI_OK;
1292 static void sink_client_data(fcgi_request *fr)
1294 char *base;
1295 int size;
1297 fcgi_buf_reset(fr->clientInputBuffer);
1298 fcgi_buf_get_free_block_info(fr->clientInputBuffer, &base, &size);
1299 while (ap_get_client_block(fr->r, base, size) > 0);
1303 static int server_error(fcgi_request *fr)
1305 int rv;
1306 request_rec *r = fr->r;
1308 #if defined(SIGPIPE) && MODULE_MAGIC_NUMBER < 19990320
1309 /* Make sure we leave with Apache's sigpipe_handler in place */
1310 if (fr->apache_sigpipe_handler != NULL)
1311 signal(SIGPIPE, fr->apache_sigpipe_handler);
1312 #endif
1314 close_connection_to_fs(fr);
1316 if (fr->role == FCGI_RESPONDER) {
1317 sink_client_data(fr);
1320 switch (fr->parseHeader) {
1322 case SCAN_CGI_FINISHED:
1324 if (fr->role == FCGI_RESPONDER) {
1326 write_to_client(fr);
1328 #ifdef RUSSIAN_APACHE
1329 ap_rflush(r);
1330 #else
1331 ap_bflush(r->connection->client);
1332 #endif
1333 ap_bgetopt(r->connection->client, BO_BYTECT, &r->bytes_sent);
1336 /* fall through */
1338 case SCAN_CGI_INT_REDIRECT:
1339 case SCAN_CGI_SRV_REDIRECT:
1341 rv = OK;
1342 break;
1344 case SCAN_CGI_READING_HEADERS:
1345 case SCAN_CGI_BAD_HEADER:
1346 default:
1348 rv = SERVER_ERROR;
1349 break;
1352 ap_kill_timeout(r);
1354 return rv;
1357 static void cleanup(void *data)
1359 fcgi_request * const fr = (fcgi_request *) data;
1361 if (fr == NULL) return;
1363 /* its more than likely already run, but... */
1364 close_connection_to_fs(fr);
1366 send_request_complete(fr);
1368 if (fr->fs_stderr_len) {
1369 ap_log_rerror(FCGI_LOG_ERR_NOERRNO, fr->r,
1370 "FastCGI: server \"%s\" stderr: %s", fr->fs_path, fr->fs_stderr);
1374 /*----------------------------------------------------------------------
1375 * This is the core routine for moving data between the FastCGI
1376 * application and the Web server's client.
1378 static int do_work(request_rec *r, fcgi_request *fr)
1380 struct timeval timeOut, dynamic_last_activity_time = {0, 0};
1381 fd_set read_set, write_set;
1382 int status = 0, idle_timeout;
1383 int numFDs, dynamic_first_read = fr->dynamic ? 1 : 0;
1384 int doClientWrite;
1385 int envSent = FALSE; /* has the complete ENV been buffered? */
1386 env_status env;
1387 pool *rp = r->pool;
1388 const char *err = NULL;
1390 FD_ZERO(&read_set);
1391 FD_ZERO(&write_set);
1393 fcgi_protocol_queue_begin_request(fr);
1395 /* Buffer as much of the environment as we can fit */
1396 env.envp = NULL;
1397 envSent = fcgi_protocol_queue_env(r, fr, &env);
1399 /* Start the Apache dropdead timer. See comments at top of file. */
1400 ap_hard_timeout("buffering of FastCGI client data", r);
1402 /* Read as much as possible from the client. */
1403 if (fr->role == FCGI_RESPONDER) {
1404 status = ap_setup_client_block(r, REQUEST_CHUNKED_ERROR);
1405 if (status != OK) {
1406 ap_kill_timeout(r);
1407 return status;
1409 fr->expectingClientContent = (ap_should_client_block(r) != 0);
1411 if (read_from_client_n_queue(fr) != OK)
1412 return server_error(fr);
1415 ap_block_alarms();
1416 ap_register_cleanup(rp, (void *)fr, cleanup, ap_null_cleanup);
1417 ap_unblock_alarms();
1419 /* Connect to the FastCGI Application */
1420 ap_hard_timeout("connect() to FastCGI server", r);
1421 if (open_connection_to_fs(fr) != FCGI_OK) {
1422 return server_error(fr);
1425 numFDs = fr->fd + 1;
1426 idle_timeout = fr->dynamic ? dynamic_idle_timeout : fr->fs->idle_timeout;
1428 if (dynamic_first_read) {
1429 dynamic_last_activity_time = fr->startTime;
1431 if (dynamicAppConnectTimeout) {
1432 struct timeval qwait;
1433 timersub(&fr->queueTime, &fr->startTime, &qwait);
1434 dynamic_first_read = qwait.tv_sec / dynamicPleaseStartDelay + 1;
1438 /* @@@ We never reset the timer in this loop, most folks don't mess w/
1439 * Timeout directive which means we've got the 5 min default which is way
1440 * to long to tie up a fs. We need a better/configurable solution that
1441 * uses the select */
1442 ap_hard_timeout("FastCGI request processing", r);
1444 /* Before we do any writing, set the connection non-blocking */
1445 set_nonblocking(fr, TRUE);
1447 /* The socket is writeable, so get the first write out of the way */
1448 if (fcgi_buf_get_to_fd(fr->serverOutputBuffer, fr->fd) < 0) {
1449 #ifdef WIN32
1450 if (! fr->using_npipe_io)
1451 ap_log_rerror(FCGI_LOG_ERR_ERRNO, r,
1452 "FastCGI: comm with server \"%s\" aborted: write failed", fr->fs_path);
1453 else
1454 #endif
1455 ap_log_rerror(FCGI_LOG_ERR, r,
1456 "FastCGI: comm with server \"%s\" aborted: write failed", fr->fs_path);
1457 return server_error(fr);
1460 while (fr->keepReadingFromFcgiApp
1461 || BufferLength(fr->serverInputBuffer) > 0
1462 || BufferLength(fr->clientOutputBuffer) > 0) {
1464 /* If we didn't buffer all of the environment yet, buffer some more */
1465 if (!envSent)
1466 envSent = fcgi_protocol_queue_env(r, fr, &env);
1468 /* Read as much as possible from the client. */
1469 if (fr->role == FCGI_RESPONDER && !fr->eofSent && envSent) {
1471 /* ap_get_client_block() (called in read_from_client_n_queue()
1472 * can't handle a non-blocking fd, its a bummer. We might be
1473 * able to completely bypass the Apache BUFF routines in still
1474 * do it, but thats a major hassle. Apache 2.X will handle it,
1475 * and then so will we. */
1477 if (read_from_client_n_queue(fr) != OK)
1478 return server_error(fr);
1481 /* To avoid deadlock, don't do a blocking select to write to
1482 * the FastCGI application without selecting to read from the
1483 * FastCGI application.
1485 doClientWrite = FALSE;
1486 if (fr->keepReadingFromFcgiApp && BufferFree(fr->serverInputBuffer) > 0) {
1488 #ifdef WIN32
1489 DWORD bytesavail = 0;
1491 if (!fr->using_npipe_io) {
1492 #endif
1493 FD_SET(fr->fd, &read_set);
1495 /* Is data buffered for output to the FastCGI server? */
1496 if (BufferLength(fr->serverOutputBuffer) > 0) {
1497 FD_SET(fr->fd, &write_set);
1498 } else {
1499 FD_CLR(fr->fd, &write_set);
1501 #ifdef WIN32
1503 #endif
1505 * If there's data buffered to send to the client, don't
1506 * wait indefinitely for the FastCGI app; the app might
1507 * be doing server push.
1509 if (BufferLength(fr->clientOutputBuffer) > 0) {
1510 timeOut.tv_sec = 0;
1511 timeOut.tv_usec = 100000; /* 0.1 sec */
1513 else if (dynamic_first_read) {
1514 int delay;
1515 struct timeval qwait;
1517 if (fcgi_util_ticks(&fr->queueTime) < 0) {
1518 ap_log_rerror(FCGI_LOG_ERR, r, "FastCGI: can't get time of day");
1519 return server_error(fr);
1522 /* Check for idle_timeout */
1523 if (status) {
1524 dynamic_last_activity_time = fr->queueTime;
1526 else {
1527 struct timeval idle_time;
1528 timersub(&fr->queueTime, &dynamic_last_activity_time, &idle_time);
1529 if (idle_time.tv_sec > idle_timeout) {
1530 send_to_pm(FCGI_REQUEST_TIMEOUT_JOB, fr->fs_path, fr->user, fr->group, 0, 0);
1531 ap_log_rerror(FCGI_LOG_ERR_NOERRNO, r,
1532 "FastCGI: comm with (dynamic) server \"%s\" aborted: (first read) idle timeout (%d sec)",
1533 fr->fs_path, idle_timeout);
1534 return server_error(fr);
1538 timersub(&fr->queueTime, &fr->startTime, &qwait);
1540 delay = dynamic_first_read * dynamicPleaseStartDelay;
1541 if (qwait.tv_sec < delay) {
1542 timeOut.tv_sec = delay;
1543 timeOut.tv_usec = 100000; /* fudge for select() slop */
1544 timersub(&timeOut, &qwait, &timeOut);
1546 else {
1547 /* Killed time somewhere.. client read? */
1548 send_to_pm(FCGI_REQUEST_TIMEOUT_JOB, fr->fs_path, fr->user, fr->group, 0, 0);
1549 dynamic_first_read = qwait.tv_sec / dynamicPleaseStartDelay + 1;
1550 timeOut.tv_sec = dynamic_first_read * dynamicPleaseStartDelay;
1551 timeOut.tv_usec = 100000; /* fudge for select() slop */
1552 timersub(&timeOut, &qwait, &timeOut);
1555 else {
1556 timeOut.tv_sec = idle_timeout;
1557 timeOut.tv_usec = 0;
1560 #ifdef WIN32
1561 if (!fr->using_npipe_io) {
1562 #endif
1563 if ((status = ap_select(numFDs, &read_set, &write_set, NULL, &timeOut)) < 0) {
1564 #ifdef WIN32
1565 errno = WSAGetLastError();
1566 #endif
1567 ap_log_rerror(FCGI_LOG_ERR_ERRNO, r,
1568 "FastCGI: comm with server \"%s\" aborted: select() failed", fr->fs_path);
1569 return server_error(fr);
1571 #ifdef WIN32
1573 else {
1574 int stopTime = time(NULL) + timeOut.tv_sec;
1576 if (BufferLength(fr->serverOutputBuffer) == 0)
1578 status = 0;
1580 while ((timeOut.tv_sec != 0) && (time(NULL) <= stopTime))
1582 BOOL ok = PeekNamedPipe((HANDLE) fr->fd,NULL, 0, NULL, &bytesavail, NULL);
1583 if (! ok)
1585 ap_log_rerror(FCGI_LOG_ERR, r,
1586 "FastCGI: comm with sever \"%s\" aborted: PeekNamedPipe() failed",
1587 fr->fs_path);
1588 return server_error(fr);
1590 if (bytesavail > 0)
1592 status =1;
1593 break;
1595 Sleep(100);
1598 else {
1599 status = 1;
1602 #endif
1604 if (status == 0) {
1605 if (BufferLength(fr->clientOutputBuffer) > 0) {
1606 doClientWrite = TRUE;
1608 else if (dynamic_first_read) {
1609 struct timeval qwait;
1611 if (fcgi_util_ticks(&fr->queueTime) < 0) {
1612 ap_log_rerror(FCGI_LOG_ERR, r, "FastCGI: can't get time of day");
1613 return server_error(fr);
1616 timersub(&fr->queueTime, &fr->startTime, &qwait);
1618 send_to_pm(FCGI_REQUEST_TIMEOUT_JOB, fr->fs_path, fr->user, fr->group, 0, 0);
1620 dynamic_first_read = qwait.tv_sec / dynamicPleaseStartDelay + 1;
1622 else {
1623 ap_log_rerror(FCGI_LOG_ERR_NOERRNO, r,
1624 "FastCGI: comm with server \"%s\" aborted: idle timeout (%d sec)",
1625 fr->fs_path, idle_timeout);
1626 return server_error(fr);
1630 #if defined(SIGPIPE) && MODULE_MAGIC_NUMBER < 19990320
1631 /* Disable Apache's SIGPIPE handler */
1632 fr->apache_sigpipe_handler = signal(SIGPIPE, SIG_IGN);
1633 #endif
1635 /* Read from the FastCGI server */
1636 #ifdef WIN32
1637 if ((fr->using_npipe_io
1638 && (BufferFree(fr->serverInputBuffer) > 0)
1639 && PeekNamedPipe((HANDLE) fr->fd, NULL, 0, NULL, &bytesavail, NULL)
1640 && (bytesavail > 0))
1641 || FD_ISSET(fr->fd, &read_set)) {
1642 #else
1643 if (FD_ISSET(fr->fd, &read_set)) {
1644 #endif
1645 if (dynamic_first_read) {
1646 dynamic_first_read = 0;
1647 if (fcgi_util_ticks(&fr->queueTime) < 0) {
1648 ap_log_rerror(FCGI_LOG_ERR, r, "FastCGI: can't get time of day");
1649 return server_error(fr);
1653 if ((status = fcgi_buf_add_fd(fr->serverInputBuffer, fr->fd)) < 0) {
1654 #ifdef WIN32
1655 if (! fr->using_npipe_io)
1656 ap_log_rerror(FCGI_LOG_ERR_ERRNO, r,
1657 "FastCGI: comm with server \"%s\" aborted: read failed", fr->fs_path);
1658 else
1659 #endif
1660 ap_log_rerror(FCGI_LOG_ERR, r,
1661 "FastCGI: comm with server \"%s\" aborted: read failed", fr->fs_path);
1662 return server_error(fr);
1665 if (status == 0) {
1666 fr->keepReadingFromFcgiApp = FALSE;
1667 close_connection_to_fs(fr);
1669 else {
1670 if (fcgi_protocol_dequeue(rp, fr) != OK) {
1671 return server_error(fr);
1674 if (fr->parseHeader == SCAN_CGI_READING_HEADERS) {
1675 if ((err = process_headers(r, fr))) {
1676 ap_log_rerror(FCGI_LOG_ERR_NOERRNO, r,
1677 "FastCGI: comm with server \"%s\" aborted: "
1678 "error parsing headers: %s", fr->fs_path, err);
1679 return server_error(fr);
1685 /* Write to the FastCGI server */
1686 if (BufferLength(fr->serverOutputBuffer) > 0)
1688 #ifdef WIN32
1689 /* XXX this is broke because it will cause a spin if the app doesn't read */
1690 if (fr->using_npipe_io || FD_ISSET(fr->fd, &write_set))
1691 #else
1692 if (FD_ISSET(fr->fd, &write_set))
1693 #endif
1695 if (fcgi_buf_get_to_fd(fr->serverOutputBuffer, fr->fd) < 0)
1697 /* XXX this could fail even if the app finished sending a response */
1698 #ifdef WIN32
1699 if (! fr->using_npipe_io)
1700 ap_log_rerror(FCGI_LOG_ERR_ERRNO, r,
1701 "FastCGI: comm with server \"%s\" aborted: write failed", fr->fs_path);
1702 else
1703 #endif
1704 ap_log_rerror(FCGI_LOG_ERR, r,
1705 "FastCGI: comm with server \"%s\" aborted: write failed", fr->fs_path);
1707 return server_error(fr);
1712 #if defined(SIGPIPE) && MODULE_MAGIC_NUMBER < 19990320
1713 /* Reinstall Apache's SIGPIPE handler */
1714 signal(SIGPIPE, fr->apache_sigpipe_handler);
1715 #endif
1717 } else {
1718 doClientWrite = TRUE;
1721 if (fr->role == FCGI_RESPONDER && doClientWrite) {
1723 if (write_to_client(fr) != OK) {
1724 #if defined(SIGPIPE) && MODULE_MAGIC_NUMBER < 19990320
1725 /* Make sure we leave with Apache's sigpipe_handler in place */
1726 if (fr->apache_sigpipe_handler != NULL)
1727 signal(SIGPIPE, fr->apache_sigpipe_handler);
1728 #endif
1729 close_connection_to_fs(fr);
1730 ap_kill_timeout(fr->r);
1731 return OK;
1735 if (fcgi_protocol_dequeue(rp, fr) != OK)
1736 return server_error(fr);
1738 if (fr->keepReadingFromFcgiApp && fr->exitStatusSet) {
1739 /* we're done talking to the fcgi app */
1740 fr->keepReadingFromFcgiApp = FALSE;
1741 close_connection_to_fs(fr);
1744 if (fr->parseHeader == SCAN_CGI_READING_HEADERS) {
1745 if ((err = process_headers(r, fr))) {
1746 ap_log_rerror(FCGI_LOG_ERR_NOERRNO, r,
1747 "FastCGI: comm with server \"%s\" aborted: error parsing headers: %s", fr->fs_path, err);
1748 return server_error(fr);
1752 } /* while */
1754 if (fr->role == FCGI_RESPONDER) {
1755 sink_client_data(fr);
1758 switch (fr->parseHeader) {
1760 case SCAN_CGI_FINISHED:
1762 if (fr->role == FCGI_RESPONDER) {
1763 #ifdef RUSSIAN_APACHE
1764 ap_rflush(r);
1765 #else
1766 ap_bflush(r->connection->client);
1767 #endif
1768 ap_bgetopt(r->connection->client, BO_BYTECT, &r->bytes_sent);
1770 break;
1772 case SCAN_CGI_READING_HEADERS:
1774 ap_log_rerror(FCGI_LOG_ERR_NOERRNO, r,
1775 "FastCGI: incomplete headers (%d bytes) received from server \"%s\"",
1776 fr->header->nelts, fr->fs_path);
1777 return server_error(fr);
1779 case SCAN_CGI_BAD_HEADER:
1781 return server_error(fr);
1783 case SCAN_CGI_INT_REDIRECT:
1784 case SCAN_CGI_SRV_REDIRECT:
1786 break;
1788 default:
1789 ap_assert(FALSE);
1792 ap_kill_timeout(r);
1793 return OK;
1796 static fcgi_request *create_fcgi_request(request_rec * const r, const char *fs_path)
1798 struct stat *my_finfo;
1799 pool * const p = r->pool;
1800 fcgi_server *fs;
1801 fcgi_request * const fr = (fcgi_request *)ap_pcalloc(p, sizeof(fcgi_request));
1803 if (fs_path) {
1804 my_finfo = (struct stat *)ap_palloc(p, sizeof(struct stat));
1805 if (stat(fs_path, my_finfo) < 0) {
1806 ap_log_rerror(FCGI_LOG_ERR_ERRNO, r,
1807 "FastCGI: stat() of \"%s\" failed", fs_path);
1808 return NULL;
1811 else {
1812 my_finfo = &r->finfo;
1813 fs_path = r->filename;
1816 fs = fcgi_util_fs_get_by_id(fs_path, r->server->server_uid, r->server->server_gid);
1817 if (fs == NULL) {
1818 /* Its a request for a dynamic FastCGI application */
1819 const char * const err =
1820 fcgi_util_fs_is_path_ok(p, fs_path, my_finfo);
1822 if (err) {
1823 ap_log_rerror(FCGI_LOG_ERR_NOERRNO, r, "FastCGI: invalid (dynamic) server \"%s\": %s", fs_path, err);
1824 return NULL;
1828 fr->serverInputBuffer = fcgi_buf_new(p, SERVER_BUFSIZE);
1829 fr->serverOutputBuffer = fcgi_buf_new(p, SERVER_BUFSIZE);
1830 fr->clientInputBuffer = fcgi_buf_new(p, SERVER_BUFSIZE);
1831 fr->clientOutputBuffer = fcgi_buf_new(p, SERVER_BUFSIZE);
1832 fr->erBufPtr = fcgi_buf_new(p, sizeof(FCGI_EndRequestBody) + 1);
1833 fr->gotHeader = FALSE;
1834 fr->parseHeader = SCAN_CGI_READING_HEADERS;
1835 fr->header = ap_make_array(p, 1, 1);
1836 fr->fs_stderr = NULL;
1837 fr->r = r;
1838 fr->readingEndRequestBody = FALSE;
1839 fr->exitStatus = 0;
1840 fr->exitStatusSet = FALSE;
1841 fr->requestId = 1; /* anything but zero is OK here */
1842 fr->eofSent = FALSE;
1843 fr->role = FCGI_RESPONDER;
1844 fr->expectingClientContent = FALSE;
1845 fr->keepReadingFromFcgiApp = TRUE;
1846 fr->fs = fs;
1847 fr->fs_path = fs_path;
1848 fr->authHeaders = ap_make_table(p, 10);
1849 #ifdef WIN32
1850 fr->fd = INVALID_SOCKET;
1851 fr->dynamic = ((fs == NULL) || (fs->directive == APP_CLASS_DYNAMIC)) ? TRUE : FALSE;
1852 fr->using_npipe_io = FALSE;
1853 #else
1854 fr->dynamic = (fs == NULL) ? TRUE : FALSE;
1855 fr->fd = -1;
1856 #endif
1858 set_uid_n_gid(r, &fr->user, &fr->group);
1860 return fr;
1864 *----------------------------------------------------------------------
1866 * handler --
1868 * This routine gets called for a request that corresponds to
1869 * a FastCGI connection. It performs the request synchronously.
1871 * Results:
1872 * Final status of request: OK or NOT_FOUND or SERVER_ERROR.
1874 * Side effects:
1875 * Request performed.
1877 *----------------------------------------------------------------------
1880 /* Stolen from mod_cgi.c..
1881 * KLUDGE --- for back-combatibility, we don't have to check ExecCGI
1882 * in ScriptAliased directories, which means we need to know if this
1883 * request came through ScriptAlias or not... so the Alias module
1884 * leaves a note for us.
1886 static int apache_is_scriptaliased(request_rec *r)
1888 const char *t = ap_table_get(r->notes, "alias-forced-type");
1889 return t && (!strcasecmp(t, "cgi-script"));
1892 /* If a script wants to produce its own Redirect body, it now
1893 * has to explicitly *say* "Status: 302". If it wants to use
1894 * Apache redirects say "Status: 200". See process_headers().
1896 static int post_process_for_redirects(request_rec * const r,
1897 const fcgi_request * const fr)
1899 switch(fr->parseHeader) {
1900 case SCAN_CGI_INT_REDIRECT:
1902 /* @@@ There are still differences between the handling in
1903 * mod_cgi and mod_fastcgi. This needs to be revisited.
1905 /* We already read the message body (if any), so don't allow
1906 * the redirected request to think it has one. We can ignore
1907 * Transfer-Encoding, since we used REQUEST_CHUNKED_ERROR.
1909 r->method = "GET";
1910 r->method_number = M_GET;
1911 ap_table_unset(r->headers_in, "Content-length");
1913 ap_internal_redirect_handler(ap_table_get(r->headers_out, "Location"), r);
1914 return OK;
1916 case SCAN_CGI_SRV_REDIRECT:
1917 return REDIRECT;
1919 default:
1920 return OK;
1924 /******************************************************************************
1925 * Process fastcgi-script requests. Based on mod_cgi::cgi_handler().
1927 static int content_handler(request_rec *r)
1929 fcgi_request *fr = NULL;
1930 int ret;
1932 /* Setup a new FastCGI request */
1933 if ((fr = create_fcgi_request(r, NULL)) == NULL)
1934 return SERVER_ERROR;
1936 /* If its a dynamic invocation, make sure scripts are OK here */
1937 if (fr->dynamic && !(ap_allow_options(r) & OPT_EXECCGI) && !apache_is_scriptaliased(r)) {
1938 ap_log_rerror(FCGI_LOG_ERR_NOERRNO, r,
1939 "FastCGI: \"ExecCGI Option\" is off in this directory: %s", r->uri);
1940 return SERVER_ERROR;
1943 /* Process the fastcgi-script request */
1944 if ((ret = do_work(r, fr)) != OK)
1945 return ret;
1947 /* Special case redirects */
1948 ret = post_process_for_redirects(r, fr);
1950 return ret;
1954 static int post_process_auth_passed_header(table *t, const char *key, const char * const val)
1956 if (strncasecmp(key, "Variable-", 9) == 0)
1957 key += 9;
1959 ap_table_setn(t, key, val);
1960 return 1;
1963 static int post_process_auth_passed_compat_header(table *t, const char *key, const char * const val)
1965 if (strncasecmp(key, "Variable-", 9) == 0)
1966 ap_table_setn(t, key + 9, val);
1968 return 1;
1971 static int post_process_auth_failed_header(table * const t, const char * const key, const char * const val)
1973 ap_table_setn(t, key, val);
1974 return 1;
1977 static void post_process_auth(fcgi_request * const fr, const int passed)
1979 request_rec * const r = fr->r;
1981 /* Restore the saved subprocess_env because we muddied ours up */
1982 r->subprocess_env = fr->saved_subprocess_env;
1984 if (passed) {
1985 if (fr->auth_compat) {
1986 ap_table_do((int (*)(void *, const char *, const char *))post_process_auth_passed_compat_header,
1987 (void *)r->subprocess_env, fr->authHeaders, NULL);
1989 else {
1990 ap_table_do((int (*)(void *, const char *, const char *))post_process_auth_passed_header,
1991 (void *)r->subprocess_env, fr->authHeaders, NULL);
1994 else {
1995 ap_table_do((int (*)(void *, const char *, const char *))post_process_auth_failed_header,
1996 (void *)r->err_headers_out, fr->authHeaders, NULL);
1999 /* @@@ Restore these.. its a hack until I rewrite the header handling */
2000 r->status = HTTP_OK;
2001 r->status_line = NULL;
2004 static int check_user_authentication(request_rec *r)
2006 int res, authenticated = 0;
2007 const char *password;
2008 fcgi_request *fr;
2009 const fcgi_dir_config * const dir_config =
2010 (const fcgi_dir_config *)ap_get_module_config(r->per_dir_config, &fastcgi_module);
2012 if (dir_config->authenticator == NULL)
2013 return DECLINED;
2015 /* Get the user password */
2016 if ((res = ap_get_basic_auth_pw(r, &password)) != OK)
2017 return res;
2019 if ((fr = create_fcgi_request(r, dir_config->authenticator)) == NULL)
2020 return SERVER_ERROR;
2022 /* Save the existing subprocess_env, because we're gonna muddy it up */
2023 fr->saved_subprocess_env = ap_copy_table(r->pool, r->subprocess_env);
2025 ap_table_setn(r->subprocess_env, "REMOTE_PASSWD", password);
2026 ap_table_setn(r->subprocess_env, "FCGI_APACHE_ROLE", "AUTHENTICATOR");
2028 /* The FastCGI Protocol doesn't differentiate authentication */
2029 fr->role = FCGI_AUTHORIZER;
2031 /* Do we need compatibility mode? */
2032 fr->auth_compat = (dir_config->authenticator_options & FCGI_COMPAT);
2034 if ((res = do_work(r, fr)) != OK)
2035 goto AuthenticationFailed;
2037 authenticated = (r->status == 200);
2038 post_process_auth(fr, authenticated);
2040 /* A redirect shouldn't be allowed during the authentication phase */
2041 if (ap_table_get(r->headers_out, "Location") != NULL) {
2042 ap_log_rerror(FCGI_LOG_ERR_NOERRNO, r,
2043 "FastCGI: FastCgiAuthenticator \"%s\" redirected (not allowed)",
2044 dir_config->authenticator);
2045 goto AuthenticationFailed;
2048 if (authenticated)
2049 return OK;
2051 AuthenticationFailed:
2052 if (!(dir_config->authenticator_options & FCGI_AUTHORITATIVE))
2053 return DECLINED;
2055 /* @@@ Probably should support custom_responses */
2056 ap_note_basic_auth_failure(r);
2057 ap_log_rerror(FCGI_LOG_ERR_NOERRNO, r,
2058 "FastCGI: authentication failed for user \"%s\": %s", r->connection->user, r->uri);
2059 return (res == OK) ? AUTH_REQUIRED : res;
2062 static int check_user_authorization(request_rec *r)
2064 int res, authorized = 0;
2065 fcgi_request *fr;
2066 const fcgi_dir_config * const dir_config =
2067 (const fcgi_dir_config *)ap_get_module_config(r->per_dir_config, &fastcgi_module);
2069 if (dir_config->authorizer == NULL)
2070 return DECLINED;
2072 /* @@@ We should probably honor the existing parameters to the require directive
2073 * as well as allow the definition of new ones (or use the basename of the
2074 * FastCGI server and pass the rest of the directive line), but for now keep
2075 * it simple. */
2077 if ((fr = create_fcgi_request(r, dir_config->authorizer)) == NULL)
2078 return SERVER_ERROR;
2080 /* Save the existing subprocess_env, because we're gonna muddy it up */
2081 fr->saved_subprocess_env = ap_copy_table(r->pool, r->subprocess_env);
2083 ap_table_setn(r->subprocess_env, "FCGI_APACHE_ROLE", "AUTHORIZER");
2085 fr->role = FCGI_AUTHORIZER;
2087 /* Do we need compatibility mode? */
2088 fr->auth_compat = (dir_config->authenticator_options & FCGI_COMPAT);
2090 if ((res = do_work(r, fr)) != OK)
2091 goto AuthorizationFailed;
2093 authorized = (r->status == 200);
2094 post_process_auth(fr, authorized);
2096 /* A redirect shouldn't be allowed during the authorization phase */
2097 if (ap_table_get(r->headers_out, "Location") != NULL) {
2098 ap_log_rerror(FCGI_LOG_ERR_NOERRNO, r,
2099 "FastCGI: FastCgiAuthorizer \"%s\" redirected (not allowed)",
2100 dir_config->authorizer);
2101 goto AuthorizationFailed;
2104 if (authorized)
2105 return OK;
2107 AuthorizationFailed:
2108 if (!(dir_config->authorizer_options & FCGI_AUTHORITATIVE))
2109 return DECLINED;
2111 /* @@@ Probably should support custom_responses */
2112 ap_note_basic_auth_failure(r);
2113 ap_log_rerror(FCGI_LOG_ERR_NOERRNO, r,
2114 "FastCGI: authorization failed for user \"%s\": %s", r->connection->user, r->uri);
2115 return (res == OK) ? AUTH_REQUIRED : res;
2118 static int check_access(request_rec *r)
2120 int res, access_allowed = 0;
2121 fcgi_request *fr;
2122 const fcgi_dir_config * const dir_config =
2123 (fcgi_dir_config *)ap_get_module_config(r->per_dir_config, &fastcgi_module);
2125 if (dir_config == NULL || dir_config->access_checker == NULL)
2126 return DECLINED;
2128 if ((fr = create_fcgi_request(r, dir_config->access_checker)) == NULL)
2129 return SERVER_ERROR;
2131 /* Save the existing subprocess_env, because we're gonna muddy it up */
2132 fr->saved_subprocess_env = ap_copy_table(r->pool, r->subprocess_env);
2134 ap_table_setn(r->subprocess_env, "FCGI_APACHE_ROLE", "ACCESS_CHECKER");
2136 /* The FastCGI Protocol doesn't differentiate access control */
2137 fr->role = FCGI_AUTHORIZER;
2139 /* Do we need compatibility mode? */
2140 fr->auth_compat = (dir_config->authenticator_options & FCGI_COMPAT);
2142 if ((res = do_work(r, fr)) != OK)
2143 goto AccessFailed;
2145 access_allowed = (r->status == 200);
2146 post_process_auth(fr, access_allowed);
2148 /* A redirect shouldn't be allowed during the access check phase */
2149 if (ap_table_get(r->headers_out, "Location") != NULL) {
2150 ap_log_rerror(FCGI_LOG_ERR_NOERRNO, r,
2151 "FastCGI: FastCgiAccessChecker \"%s\" redirected (not allowed)",
2152 dir_config->access_checker);
2153 goto AccessFailed;
2156 if (access_allowed)
2157 return OK;
2159 AccessFailed:
2160 if (!(dir_config->access_checker_options & FCGI_AUTHORITATIVE))
2161 return DECLINED;
2163 /* @@@ Probably should support custom_responses */
2164 ap_log_rerror(FCGI_LOG_ERR_NOERRNO, r, "FastCGI: access denied: %s", r->uri);
2165 return (res == OK) ? FORBIDDEN : res;
2168 command_rec fastcgi_cmds[] = {
2169 { "AppClass", fcgi_config_new_static_server, NULL, RSRC_CONF, RAW_ARGS, NULL },
2170 { "FastCgiServer", fcgi_config_new_static_server, NULL, RSRC_CONF, RAW_ARGS, NULL },
2172 { "ExternalAppClass", fcgi_config_new_external_server, NULL, RSRC_CONF, RAW_ARGS, NULL },
2173 { "FastCgiExternalServer", fcgi_config_new_external_server, NULL, RSRC_CONF, RAW_ARGS, NULL },
2175 { "FastCgiIpcDir", fcgi_config_set_socket_dir, NULL, RSRC_CONF, TAKE1, NULL },
2177 { "FastCgiSuexec", fcgi_config_set_wrapper, NULL, RSRC_CONF, TAKE1, NULL },
2178 { "FastCgiWrapper", fcgi_config_set_wrapper, NULL, RSRC_CONF, TAKE1, NULL },
2180 { "FCGIConfig", fcgi_config_set_config, NULL, RSRC_CONF, RAW_ARGS, NULL },
2181 { "FastCgiConfig", fcgi_config_set_config, NULL, RSRC_CONF, RAW_ARGS, NULL },
2183 { "FastCgiAuthenticator", fcgi_config_new_auth_server,
2184 (void *)FCGI_AUTH_TYPE_AUTHENTICATOR, ACCESS_CONF, TAKE12,
2185 "a fastcgi-script path (absolute or relative to ServerRoot) followed by an optional -compat" },
2186 { "FastCgiAuthenticatorAuthoritative", fcgi_config_set_authoritative_slot,
2187 (void *)XtOffsetOf(fcgi_dir_config, authenticator_options), ACCESS_CONF, FLAG,
2188 "Set to 'off' to allow authentication to be passed along to lower modules upon failure" },
2190 { "FastCgiAuthorizer", fcgi_config_new_auth_server,
2191 (void *)FCGI_AUTH_TYPE_AUTHORIZER, ACCESS_CONF, TAKE12,
2192 "a fastcgi-script path (absolute or relative to ServerRoot) followed by an optional -compat" },
2193 { "FastCgiAuthorizerAuthoritative", fcgi_config_set_authoritative_slot,
2194 (void *)XtOffsetOf(fcgi_dir_config, authorizer_options), ACCESS_CONF, FLAG,
2195 "Set to 'off' to allow authorization to be passed along to lower modules upon failure" },
2197 { "FastCgiAccessChecker", fcgi_config_new_auth_server,
2198 (void *)FCGI_AUTH_TYPE_ACCESS_CHECKER, ACCESS_CONF, TAKE12,
2199 "a fastcgi-script path (absolute or relative to ServerRoot) followed by an optional -compat" },
2200 { "FastCgiAccessCheckerAuthoritative", fcgi_config_set_authoritative_slot,
2201 (void *)XtOffsetOf(fcgi_dir_config, access_checker_options), ACCESS_CONF, FLAG,
2202 "Set to 'off' to allow access control to be passed along to lower modules upon failure" },
2203 { NULL }
2207 handler_rec fastcgi_handlers[] = {
2208 { FCGI_MAGIC_TYPE, content_handler },
2209 { "fastcgi-script", content_handler },
2210 { NULL }
2214 module MODULE_VAR_EXPORT fastcgi_module = {
2215 STANDARD_MODULE_STUFF,
2216 init_module, /* initializer */
2217 fcgi_config_create_dir_config, /* per-dir config creator */
2218 NULL, /* per-dir config merger (default: override) */
2219 NULL, /* per-server config creator */
2220 NULL, /* per-server config merger (default: override) */
2221 fastcgi_cmds, /* command table */
2222 fastcgi_handlers, /* [9] content handlers */
2223 NULL, /* [2] URI-to-filename translation */
2224 check_user_authentication, /* [5] authenticate user_id */
2225 check_user_authorization, /* [6] authorize user_id */
2226 check_access, /* [4] check access (based on src & http headers) */
2227 NULL, /* [7] check/set MIME type */
2228 NULL, /* [8] fixups */
2229 NULL, /* [10] logger */
2230 NULL, /* [3] header-parser */
2231 fcgi_child_init, /* process initialization */
2232 fcgi_child_exit, /* process exit/cleanup */
2233 NULL /* [1] post read-request handling */