4 * Apache server module for FastCGI.
6 * $Id: mod_fastcgi.c,v 1.131 2002/03/13 23:32:19 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
18 * Patches for Linux provided by
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.
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.
75 #define timersub(a, b, result) \
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) { \
81 (result)->tv_usec += 1000000; \
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 */
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
;
113 int fcgi_pm_pipe
[2] = { -1, -1 };
114 pid_t fcgi_pm_pid
= -1;
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
)
149 fcgi_pm_job
*job
= NULL
;
151 if (!(job
= (fcgi_pm_job
*) malloc(sizeof(fcgi_pm_job
))))
154 static int failed_count
= 0;
156 char buf
[FCGI_MAX_MSG_LEN
];
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
);
167 case FCGI_SERVER_START_JOB
:
168 case FCGI_SERVER_RESTART_JOB
:
171 job
->fs_path
= strdup(fs_path
);
172 job
->user
= strdup(user
);
173 job
->group
= strdup(group
);
175 job
->start_time
= 0L;
177 buflen
= sprintf(buf
, "%c %s %s %s*", id
, fs_path
, user
, group
);
181 case FCGI_REQUEST_TIMEOUT_JOB
:
184 job
->fs_path
= strdup(fs_path
);
185 job
->user
= strdup(user
);
186 job
->group
= strdup(group
);
188 job
->start_time
= 0L;
190 buflen
= sprintf(buf
, "%c %s %s %s*", id
, fs_path
, user
, group
);
194 case FCGI_REQUEST_COMPLETE_JOB
:
197 job
->fs_path
= strdup(fs_path
);
199 job
->start_time
= req_usec
;
200 job
->user
= strdup(user
);
201 job
->group
= strdup(group
);
203 buflen
= sprintf(buf
, "%c %s %s %s %lu %lu*", id
, fs_path
, user
, group
, q_usec
, req_usec
);
209 if (fcgi_pm_add_job(job
)) return;
211 SetEvent(fcgi_event_handles
[MBOX_EVENT
]);
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)");
228 *----------------------------------------------------------------------
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
241 *----------------------------------------------------------------------
243 static void init_module(server_rec
*s
, pool
*p
)
247 /* Register to reset to default values when the config pool is cleaned */
249 ap_register_cleanup(p
, NULL
, fcgi_config_reset_globals
, ap_null_cleanup
);
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
;
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
);
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
);
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)
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]);
296 static void fcgi_child_init(server_rec
*dc0
, pool
*dc1
)
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");
334 static void fcgi_child_exit(server_rec
*dc0
, pool
*dc1
)
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
);
348 *----------------------------------------------------------------------
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.
370 * Termination byte stored in string.
372 *----------------------------------------------------------------------
374 static char *get_header_line(char *start
, int continuation
)
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') {
384 if(*p
== '\n' && p
[1] != ' ' && p
[1] != '\t')
389 while(*p
!= '\0' && *p
!= '\n') {
395 ap_assert(*p
!= '\0');
400 * Trim any trailing whitespace.
402 while(isspace((unsigned char)p
[-1]) && p
> start
) {
411 *----------------------------------------------------------------------
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
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
;
447 int hasContentType
, hasStatus
, hasLocation
;
449 ap_assert(fr
->parseHeader
== SCAN_CGI_READING_HEADERS
);
451 if (fr
->header
== 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
;
461 while(len
-- && flag
< 2) {
471 name
= "Invalid Character";
481 /* Return (to be called later when we have more data)
482 * if we don't have an entire header. */
487 * Parse all the headers.
489 fr
->parseHeader
= SCAN_CGI_FINISHED
;
490 hasContentType
= hasStatus
= hasLocation
= FALSE
;
491 next
= (char *)fr
->header
->elts
;
493 next
= get_header_line(name
= next
, TRUE
);
497 if ((p
= strchr(name
, ':')) == NULL
) {
501 while (p
!= name
&& isspace((unsigned char)*(p
- 1))) {
508 if (strpbrk(name
, " \t") != NULL
) {
512 while (isspace((unsigned char)*value
)) {
516 if (strcasecmp(name
, "Status") == 0) {
517 int statusValue
= strtol(value
, NULL
, 10);
520 goto DuplicateNotAllowed
;
522 if (statusValue
< 0) {
523 fr
->parseHeader
= SCAN_CGI_BAD_HEADER
;
524 return ap_psprintf(r
->pool
, "invalid Status '%s'", value
);
527 r
->status
= statusValue
;
528 r
->status_line
= ap_pstrdup(r
->pool
, value
);
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
);
542 if (strcasecmp(name
, "Location") == 0) {
544 goto DuplicateNotAllowed
;
547 ap_table_set(r
->headers_out
, "Location", value
);
551 /* If the script wants them merged, it can do it */
552 ap_table_add(r
->err_headers_out
, name
, value
);
556 ap_table_add(fr
->authHeaders
, name
, value
);
560 if (fr
->role
!= FCGI_RESPONDER
)
564 * Who responds, this handler or Apache?
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
581 fr
->parseHeader
= SCAN_CGI_INT_REDIRECT
;
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
;
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
);
607 len
= fr
->header
->nelts
- (next
- fr
->header
->elts
);
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
);
615 int sent
= fcgi_buf_add_block(fr
->clientOutputBuffer
, next
, len
);
616 ap_assert(sent
== len
);
621 /* Log first line of a multi-line header */
622 if ((p
= strpbrk(name
, "\r\n")) != NULL
)
624 fr
->parseHeader
= SCAN_CGI_BAD_HEADER
;
625 return ap_psprintf(r
->pool
, "malformed header '%s'", name
);
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
639 static int read_from_client_n_queue(fcgi_request
*fr
)
645 while (BufferFree(fr
->clientInputBuffer
) > 0 || BufferFree(fr
->serverOutputBuffer
) > 0) {
646 fcgi_protocol_queue_client_buffer(fr
);
648 if (fr
->expectingClientContent
<= 0)
651 fcgi_buf_get_free_block_info(fr
->clientInputBuffer
, &end
, &count
);
655 if ((countRead
= ap_get_client_block(fr
->r
, end
, count
)) < 0)
658 if (countRead
== 0) {
659 fr
->expectingClientContent
= 0;
662 fcgi_buf_add_update(fr
->clientInputBuffer
, countRead
);
663 ap_reset_timeout(fr
->r
);
669 static int write_to_client(fcgi_request
*fr
)
674 fcgi_buf_get_block_info(fr
->clientOutputBuffer
, &begin
, &count
);
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");
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");
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");
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");
724 ap_reset_timeout(fr
->r
);
727 fcgi_buf_toss(fr
->clientOutputBuffer
, count
);
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
) {
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, '/');
748 *user
= memcpy(ap_pcalloc(r
->pool
, end
- r
->uri
), r
->uri
+ 1, end
- r
->uri
- 1);
750 *user
= ap_pstrdup(r
->pool
, r
->uri
+ 1);
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
,
770 qtime
.tv_sec
* 1000000 + qtime
.tv_usec
,
771 rtime
.tv_sec
* 1000000 + rtime
.tv_usec
);
777 static int set_nonblocking(const fcgi_request
* fr
, int nonblocking
)
779 if (fr
->using_npipe_io
)
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");
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");
809 static int set_nonblocking(const fcgi_request
* fr
, int nonblocking
)
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)
820 #elif defined(FNDELAY)
823 #error "TODO - don't read from app until all data from client is posted."
826 fd_flags
= (nonblocking
) ? (fd_flags
| nb_flag
) : (fd_flags
& ~nb_flag
);
828 return fcntl(fr
->fd
, F_SETFL
, fd_flags
);
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
)
841 if (fr
->fd
!= INVALID_SOCKET
)
843 set_nonblocking(fr
, FALSE
);
845 if (fr
->using_npipe_io
)
847 CloseHandle((HANDLE
) fr
->fd
);
851 /* abort the connection entirely */
852 struct linger linger
= {0, 0};
853 setsockopt(fr
->fd
, SOL_SOCKET
, SO_LINGER
, (void *) &linger
, sizeof(linger
));
857 fr
->fd
= INVALID_SOCKET
;
863 struct linger linger
= {0, 0};
864 set_nonblocking(fr
, FALSE
);
865 /* abort the connection entirely */
866 setsockopt(fr
->fd
, SOL_SOCKET
, SO_LINGER
, &linger
, sizeof(linger
));
872 if (fr
->dynamic
&& fr
->keepReadingFromFcgiApp
== FALSE
)
874 /* XXX FCGI_REQUEST_COMPLETE_JOB is only sent for requests which complete
875 * normally WRT the fcgi app. There is no data sent for
876 * connect() timeouts or requests which complete abnormally.
877 * KillDynamicProcs() and RemoveRecords() need to be looked at
878 * to be sure they can reasonably handle these cases before
879 * sending these sort of stats - theres some funk in there.
881 if (fcgi_util_ticks(&fr
->completeTime
) < 0)
883 /* there's no point to aborting the request, just log it */
884 ap_log_error(FCGI_LOG_ERR
, fr
->r
->server
, "FastCGI: can't get time of day");
890 /*******************************************************************************
891 * Connect to the FastCGI server.
893 static int open_connection_to_fs(fcgi_request
*fr
)
896 fd_set write_fds
, read_fds
;
898 request_rec
* const r
= fr
->r
;
899 pool
* const rp
= r
->pool
;
900 const char *socket_path
= NULL
;
901 struct sockaddr
*socket_addr
= NULL
;
902 int socket_addr_len
= 0;
904 const char *err
= NULL
;
907 /* Create the connection point */
910 socket_path
= fcgi_util_socket_hash_filename(rp
, fr
->fs_path
, fr
->user
, fr
->group
);
911 socket_path
= fcgi_util_socket_make_path_absolute(rp
, socket_path
, 1);
914 err
= fcgi_util_socket_make_domain_addr(rp
, (struct sockaddr_un
**)&socket_addr
,
915 &socket_addr_len
, socket_path
);
917 ap_log_rerror(FCGI_LOG_ERR
, r
,
918 "FastCGI: failed to connect to server \"%s\": "
919 "%s", fr
->fs_path
, err
);
927 if (fr
->fs
->dest_addr
!= NULL
) {
928 socket_addr
= fr
->fs
->dest_addr
;
930 else if (fr
->fs
->socket_addr
) {
931 socket_addr
= fr
->fs
->socket_addr
;
934 socket_path
= fr
->fs
->socket_path
;
937 socket_addr
= fr
->fs
->socket_addr
;
939 socket_addr_len
= fr
->fs
->socket_addr_len
;
945 if (fr
->fs
&& fr
->fs
->restartTime
)
947 struct stat sock_stat
;
949 if (stat(socket_path
, &sock_stat
) == 0)
953 if (dynamicAutoUpdate
)
955 struct stat app_stat
;
957 /* TODO: follow sym links */
959 if (stat(fr
->fs_path
, &app_stat
) == 0)
962 if (fr
->fs
->restartTime
< app_stat
.st_mtime
)
964 if (sock_stat
.st_mtime
< app_stat
.st_mtime
)
968 struct timeval tv
= {1, 0};
971 * There's a newer one, request a restart.
973 send_to_pm(FCGI_SERVER_RESTART_JOB
, fr
->fs_path
, fr
->user
, fr
->group
, 0, 0);
978 /* Avoid sleep/alarm interactions */
979 ap_select(0, NULL
, NULL
, NULL
, &tv
);
987 send_to_pm(FCGI_SERVER_START_JOB
, fr
->fs_path
, fr
->user
, fr
->group
, 0, 0);
989 /* Wait until it looks like its running */
996 fr
->fs
= fcgi_util_fs_get_by_id(fr
->fs_path
, 0, 0);
998 if (fr
->fs
&& fr
->fs
->restartTime
)
1000 struct timeval tv
= {1, 0};
1002 /* Avoid sleep/alarm interactions */
1003 ap_select(0, NULL
, NULL
, NULL
, &tv
);
1005 if (stat(socket_path
, &sock_stat
) == 0)
1020 HANDLE wait_npipe_mutex
;
1022 DWORD max_connect_time
= FCGI_NAMED_PIPE_CONNECT_TIMEOUT
;
1024 fr
->using_npipe_io
= TRUE
;
1028 interval
= dynamicPleaseStartDelay
* 1000;
1030 if (dynamicAppConnectTimeout
) {
1031 max_connect_time
= dynamicAppConnectTimeout
;
1036 interval
= FCGI_NAMED_PIPE_CONNECT_TIMEOUT
* 1000;
1038 if (fr
->fs
->appConnectTimeout
) {
1039 max_connect_time
= fr
->fs
->appConnectTimeout
;
1043 fcgi_util_ticks(&fr
->startTime
);
1046 // xxx this handle should live somewhere (see CloseHandle()s below too)
1047 char * wait_npipe_mutex_name
, * cp
;
1048 wait_npipe_mutex_name
= cp
= ap_pstrdup(rp
, socket_path
);
1049 while ((cp
= strchr(cp
, '\\'))) *cp
= '/';
1051 wait_npipe_mutex
= CreateMutex(NULL
, FALSE
, wait_npipe_mutex_name
);
1054 if (wait_npipe_mutex
== NULL
)
1056 ap_log_rerror(FCGI_LOG_ERR
, r
,
1057 "FastCGI: failed to connect to server \"%s\": "
1058 "can't create the WaitNamedPipe mutex", fr
->fs_path
);
1062 SetLastError(ERROR_SUCCESS
);
1064 rv
= WaitForSingleObject(wait_npipe_mutex
, max_connect_time
* 1000);
1066 if (rv
== WAIT_TIMEOUT
|| rv
== WAIT_FAILED
)
1070 send_to_pm(FCGI_REQUEST_TIMEOUT_JOB
, fr
->fs_path
, fr
->user
, fr
->group
, 0, 0);
1072 ap_log_rerror(FCGI_LOG_ERR_NOERRNO
, r
,
1073 "FastCGI: failed to connect to server \"%s\": "
1074 "wait for a npipe instance failed", fr
->fs_path
);
1075 FCGIDBG3("interval=%d, max_connect_time=%d", interval
, max_connect_time
);
1076 CloseHandle(wait_npipe_mutex
);
1080 fcgi_util_ticks(&fr
->queueTime
);
1082 connect_time
= fr
->queueTime
.tv_sec
- fr
->startTime
.tv_sec
;
1086 if (connect_time
>= interval
)
1088 send_to_pm(FCGI_REQUEST_TIMEOUT_JOB
, fr
->fs_path
, fr
->user
, fr
->group
, 0, 0);
1089 FCGIDBG4("connect_time=%d, interval=%d, max_connect_time=%d", connect_time
, interval
, max_connect_time
);
1091 if (max_connect_time
- connect_time
< interval
)
1093 interval
= max_connect_time
- connect_time
;
1098 interval
-= connect_time
* 1000;
1103 ready
= WaitNamedPipe(socket_path
, interval
);
1107 fr
->fd
= (SOCKET
) CreateFile(socket_path
,
1108 GENERIC_READ
| GENERIC_WRITE
,
1109 FILE_SHARE_READ
| FILE_SHARE_WRITE
,
1110 NULL
, // no security attributes
1111 OPEN_EXISTING
, // opens existing pipe
1112 FILE_FLAG_OVERLAPPED
,
1113 NULL
); // no template file
1115 if (fr
->fd
!= (SOCKET
) INVALID_HANDLE_VALUE
)
1117 ReleaseMutex(wait_npipe_mutex
);
1118 CloseHandle(wait_npipe_mutex
);
1119 fcgi_util_ticks(&fr
->queueTime
);
1120 FCGIDBG2("got npipe connect: %s", fr
->fs_path
);
1124 if (GetLastError() != ERROR_PIPE_BUSY
1125 && GetLastError() != ERROR_FILE_NOT_FOUND
)
1127 ap_log_rerror(FCGI_LOG_ERR
, r
,
1128 "FastCGI: failed to connect to server \"%s\": "
1129 "CreateFile() failed", fr
->fs_path
);
1133 FCGIDBG2("missed npipe connect: %s", fr
->fs_path
);
1138 send_to_pm(FCGI_REQUEST_TIMEOUT_JOB
, fr
->fs_path
, fr
->user
, fr
->group
, 0, 0);
1141 fcgi_util_ticks(&fr
->queueTime
);
1143 connect_time
= fr
->queueTime
.tv_sec
- fr
->startTime
.tv_sec
;
1145 FCGIDBG5("interval=%d, max_connect_time=%d, connect_time=%d, ready=%d", interval
, max_connect_time
, connect_time
, ready
);
1147 if (connect_time
>= max_connect_time
)
1149 ap_log_rerror(FCGI_LOG_ERR
, r
,
1150 "FastCGI: failed to connect to server \"%s\": "
1151 "CreateFile()/WaitNamedPipe() timed out", fr
->fs_path
);
1156 ReleaseMutex(wait_npipe_mutex
);
1157 CloseHandle(wait_npipe_mutex
);
1158 fr
->fd
= INVALID_SOCKET
;
1164 /* Create the socket */
1165 fr
->fd
= socket(socket_addr
->sa_family
, SOCK_STREAM
, 0);
1168 if (fr
->fd
== INVALID_SOCKET
) {
1169 errno
= WSAGetLastError(); // Not sure this is going to work as expected
1173 ap_log_rerror(FCGI_LOG_ERR_ERRNO
, r
,
1174 "FastCGI: failed to connect to server \"%s\": "
1175 "socket() failed", fr
->fs_path
);
1180 if (fr
->fd
>= FD_SETSIZE
) {
1181 ap_log_rerror(FCGI_LOG_ERR
, r
,
1182 "FastCGI: failed to connect to server \"%s\": "
1183 "socket file descriptor (%u) is larger than "
1184 "FD_SETSIZE (%u), you probably need to rebuild Apache with a "
1185 "larger FD_SETSIZE", fr
->fs_path
, fr
->fd
, FD_SETSIZE
);
1190 /* If appConnectTimeout is non-zero, setup do a non-blocking connect */
1191 if ((fr
->dynamic
&& dynamicAppConnectTimeout
) || (!fr
->dynamic
&& fr
->fs
->appConnectTimeout
)) {
1192 set_nonblocking(fr
, TRUE
);
1196 fcgi_util_ticks(&fr
->startTime
);
1200 if (connect(fr
->fd
, (struct sockaddr
*)socket_addr
, socket_addr_len
) == 0)
1201 goto ConnectionComplete
;
1205 errno
= WSAGetLastError();
1206 if (errno
!= WSAEWOULDBLOCK
) {
1207 ap_log_rerror(FCGI_LOG_ERR_ERRNO
, r
,
1208 "FastCGI: failed to connect to server \"%s\": "
1209 "connect() failed", fr
->fs_path
);
1215 /* ECONNREFUSED means the listen queue is full (or there isn't one).
1216 * With dynamic I can at least make sure the PM knows this is occuring */
1217 if (fr
->dynamic
&& errno
== ECONNREFUSED
) {
1218 /* @@@ This might be better as some other "kind" of message */
1219 send_to_pm(FCGI_REQUEST_TIMEOUT_JOB
, fr
->fs_path
, fr
->user
, fr
->group
, 0, 0);
1221 errno
= ECONNREFUSED
;
1224 if (errno
!= EINPROGRESS
) {
1225 ap_log_rerror(FCGI_LOG_ERR
, r
,
1226 "FastCGI: failed to connect to server \"%s\": "
1227 "connect() failed", fr
->fs_path
);
1233 /* The connect() is non-blocking */
1239 FD_ZERO(&write_fds
);
1240 FD_SET(fr
->fd
, &write_fds
);
1241 read_fds
= write_fds
;
1242 tval
.tv_sec
= dynamicPleaseStartDelay
;
1245 status
= ap_select((fr
->fd
+1), &read_fds
, &write_fds
, NULL
, &tval
);
1249 fcgi_util_ticks(&fr
->queueTime
);
1254 /* select() timed out */
1255 send_to_pm(FCGI_REQUEST_TIMEOUT_JOB
, fr
->fs_path
, fr
->user
, fr
->group
, 0, 0);
1256 } while ((fr
->queueTime
.tv_sec
- fr
->startTime
.tv_sec
) < (int)dynamicAppConnectTimeout
);
1258 /* XXX These can be moved down when dynamic vars live is a struct */
1260 ap_log_rerror(FCGI_LOG_ERR_NOERRNO
, r
,
1261 "FastCGI: failed to connect to server \"%s\": "
1262 "connect() timed out (appConnTimeout=%dsec)",
1263 fr
->fs_path
, dynamicAppConnectTimeout
);
1268 tval
.tv_sec
= fr
->fs
->appConnectTimeout
;
1270 FD_ZERO(&write_fds
);
1271 FD_SET(fr
->fd
, &write_fds
);
1272 read_fds
= write_fds
;
1274 status
= ap_select((fr
->fd
+1), &read_fds
, &write_fds
, NULL
, &tval
);
1277 ap_log_rerror(FCGI_LOG_ERR_NOERRNO
, r
,
1278 "FastCGI: failed to connect to server \"%s\": "
1279 "connect() timed out (appConnTimeout=%dsec)",
1280 fr
->fs_path
, dynamicAppConnectTimeout
);
1287 errno
= WSAGetLastError();
1289 ap_log_rerror(FCGI_LOG_ERR_ERRNO
, r
,
1290 "FastCGI: failed to connect to server \"%s\": "
1291 "select() failed", fr
->fs_path
);
1295 if (FD_ISSET(fr
->fd
, &write_fds
) || FD_ISSET(fr
->fd
, &read_fds
)) {
1297 NET_SIZE_T len
= sizeof(error
);
1299 if (getsockopt(fr
->fd
, SOL_SOCKET
, SO_ERROR
, (char *)&error
, &len
) < 0) {
1300 /* Solaris pending error */
1302 errno
= WSAGetLastError();
1304 ap_log_rerror(FCGI_LOG_ERR_ERRNO
, r
,
1305 "FastCGI: failed to connect to server \"%s\": "
1306 "select() failed (Solaris pending error)", fr
->fs_path
);
1311 /* Berkeley-derived pending error */
1313 ap_log_rerror(FCGI_LOG_ERR_ERRNO
, r
,
1314 "FastCGI: failed to connect to server \"%s\": "
1315 "select() failed (pending error)", fr
->fs_path
);
1321 errno
= WSAGetLastError();
1323 ap_log_rerror(FCGI_LOG_ERR_ERRNO
, r
,
1324 "FastCGI: failed to connect to server \"%s\": "
1325 "select() error - THIS CAN'T HAPPEN!", fr
->fs_path
);
1330 /* Return to blocking mode if it was set up */
1331 if ((fr
->dynamic
&& dynamicAppConnectTimeout
) || (!fr
->dynamic
&& fr
->fs
->appConnectTimeout
)) {
1332 set_nonblocking(fr
, FALSE
);
1336 if (socket_addr
->sa_family
== AF_INET
) {
1337 /* We shouldn't be sending small packets and there's no application
1338 * level ack of the data we send, so disable Nagle */
1340 setsockopt(fr
->fd
, IPPROTO_TCP
, TCP_NODELAY
, (char *)&set
, sizeof(set
));
1347 static void sink_client_data(fcgi_request
*fr
)
1352 fcgi_buf_reset(fr
->clientInputBuffer
);
1353 fcgi_buf_get_free_block_info(fr
->clientInputBuffer
, &base
, &size
);
1354 while (ap_get_client_block(fr
->r
, base
, size
) > 0);
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
);
1375 static int npipe_io(fcgi_request
* const fr
)
1377 request_rec
* const r
= fr
->r
;
1388 state
= STATE_ENV_SEND
;
1389 env_status env_status
;
1391 int dynamic_first_recv
= fr
->dynamic
;
1392 int idle_timeout
= fr
->dynamic
? dynamic_idle_timeout
: fr
->fs
->idle_timeout
;
1393 int send_pending
= 0;
1394 int recv_pending
= 0;
1395 int client_send
= 0;
1400 struct timeval timeout
;
1401 struct timeval dynamic_last_io_time
= {0, 0};
1403 pool
* const rp
= r
->pool
;
1405 DWORD recv_count
= 0;
1407 if (fr
->role
== FCGI_RESPONDER
)
1409 client_recv
= (fr
->expectingClientContent
!= 0);
1412 idle_timeout
= fr
->dynamic
? dynamic_idle_timeout
: fr
->fs
->idle_timeout
;
1414 env_status
.envp
= NULL
;
1416 events
[0] = CreateEvent(NULL
, TRUE
, FALSE
, NULL
);
1417 events
[1] = CreateEvent(NULL
, TRUE
, FALSE
, NULL
);
1418 sov
.hEvent
= events
[0];
1419 rov
.hEvent
= events
[1];
1423 dynamic_last_io_time
= fr
->startTime
;
1425 if (dynamicAppConnectTimeout
)
1427 struct timeval qwait
;
1428 timersub(&fr
->queueTime
, &fr
->startTime
, &qwait
);
1429 dynamic_first_recv
= qwait
.tv_sec
/ dynamicPleaseStartDelay
+ 1;
1433 ap_hard_timeout("FastCGI request processing", r
);
1435 while (state
!= STATE_CLIENT_SEND
)
1441 case STATE_ENV_SEND
:
1443 if (fcgi_protocol_queue_env(r
, fr
, &env_status
) == 0)
1448 state
= STATE_CLIENT_RECV
;
1452 case STATE_CLIENT_RECV
:
1454 if (read_from_client_n_queue(fr
) != OK
)
1456 state
= STATE_CLIENT_ERROR
;
1462 state
= STATE_SERVER_SEND
;
1469 case STATE_SERVER_SEND
:
1471 if (! send_pending
&& BufferLength(fr
->serverOutputBuffer
))
1473 Buffer
* b
= fr
->serverOutputBuffer
;
1476 len
= min(b
->length
, b
->data
+ b
->size
- b
->begin
);
1478 if (WriteFile((HANDLE
) fr
->fd
, b
->begin
, len
, &sent
, &sov
))
1480 fcgi_buf_removed(b
, sent
);
1481 ResetEvent(sov
.hEvent
);
1483 else if (GetLastError() == ERROR_IO_PENDING
)
1489 ap_log_rerror(FCGI_LOG_ERR
, r
, "FastCGI: comm with server "
1490 "\"%s\" aborted: WriteFile() failed", fr
->fs_path
);
1491 state
= STATE_ERROR
;
1498 case STATE_SERVER_RECV
:
1500 if (! recv_pending
&& BufferFree(fr
->serverInputBuffer
))
1502 Buffer
* b
= fr
->serverInputBuffer
;
1505 len
= min(b
->size
- b
->length
, b
->data
+ b
->size
- b
->end
);
1507 if (ReadFile((HANDLE
) fr
->fd
, b
->end
, len
, &rcvd
, &rov
))
1509 fcgi_buf_added(b
, rcvd
);
1511 ResetEvent(rov
.hEvent
);
1512 if (dynamic_first_recv
)
1514 dynamic_first_recv
= 0;
1517 else if (GetLastError() == ERROR_IO_PENDING
)
1521 else if (GetLastError() == ERROR_HANDLE_EOF
)
1523 fr
->keepReadingFromFcgiApp
= FALSE
;
1524 state
= STATE_CLIENT_SEND
;
1525 ResetEvent(rov
.hEvent
);
1528 else if (GetLastError() == ERROR_NO_DATA
)
1534 ap_log_rerror(FCGI_LOG_ERR
, r
, "FastCGI: comm with server "
1535 "\"%s\" aborted: ReadFile() failed", fr
->fs_path
);
1536 state
= STATE_ERROR
;
1543 case STATE_CLIENT_SEND
:
1545 if (client_send
|| ! BufferFree(fr
->clientOutputBuffer
))
1547 if (write_to_client(fr
))
1549 state
= STATE_CLIENT_ERROR
;
1563 if (state
== STATE_CLIENT_ERROR
|| state
== STATE_ERROR
)
1568 /* setup the io timeout */
1570 if (BufferLength(fr
->clientOutputBuffer
))
1572 /* don't let client data sit too long, it might be a push */
1574 timeout
.tv_usec
= 100000;
1576 else if (dynamic_first_recv
)
1579 struct timeval qwait
;
1581 fcgi_util_ticks(&fr
->queueTime
);
1585 /* a send() succeeded last pass */
1586 dynamic_last_io_time
= fr
->queueTime
;
1590 /* timed out last pass */
1591 struct timeval idle_time
;
1593 timersub(&fr
->queueTime
, &dynamic_last_io_time
, &idle_time
);
1595 if (idle_time
.tv_sec
> idle_timeout
)
1597 send_to_pm(FCGI_REQUEST_TIMEOUT_JOB
, fr
->fs_path
, fr
->user
, fr
->group
, 0, 0);
1598 ap_log_rerror(FCGI_LOG_ERR_NOERRNO
, r
, "FastCGI: comm "
1599 "with (dynamic) server \"%s\" aborted: (first read) "
1600 "idle timeout (%d sec)", fr
->fs_path
, idle_timeout
);
1601 state
= STATE_ERROR
;
1606 timersub(&fr
->queueTime
, &fr
->startTime
, &qwait
);
1608 delay
= dynamic_first_recv
* dynamicPleaseStartDelay
;
1610 if (qwait
.tv_sec
< delay
)
1612 timeout
.tv_sec
= delay
;
1613 timeout
.tv_usec
= 100000; /* fudge for select() slop */
1614 timersub(&timeout
, &qwait
, &timeout
);
1618 /* Killed time somewhere.. client read? */
1619 send_to_pm(FCGI_REQUEST_TIMEOUT_JOB
, fr
->fs_path
, fr
->user
, fr
->group
, 0, 0);
1620 dynamic_first_recv
= qwait
.tv_sec
/ dynamicPleaseStartDelay
+ 1;
1621 timeout
.tv_sec
= dynamic_first_recv
* dynamicPleaseStartDelay
;
1622 timeout
.tv_usec
= 100000; /* fudge for select() slop */
1623 timersub(&timeout
, &qwait
, &timeout
);
1628 timeout
.tv_sec
= idle_timeout
;
1629 timeout
.tv_usec
= 0;
1632 /* require a pended recv otherwise the app can deadlock */
1635 msec_timeout
= timeout
.tv_sec
* 1000 + timeout
.tv_usec
/ 1000;
1637 rv
= WaitForMultipleObjects(2, events
, FALSE
, msec_timeout
);
1639 if (rv
== WAIT_TIMEOUT
)
1643 if (BufferLength(fr
->clientOutputBuffer
))
1647 else if (dynamic_first_recv
)
1649 struct timeval qwait
;
1651 fcgi_util_ticks(&fr
->queueTime
);
1652 timersub(&fr
->queueTime
, &fr
->startTime
, &qwait
);
1654 send_to_pm(FCGI_REQUEST_TIMEOUT_JOB
, fr
->fs_path
, fr
->user
, fr
->group
, 0, 0);
1656 dynamic_first_recv
= qwait
.tv_sec
/ dynamicPleaseStartDelay
+ 1;
1660 ap_log_rerror(FCGI_LOG_ERR_NOERRNO
, r
, "FastCGI: comm with "
1661 "server \"%s\" aborted: idle timeout (%d sec)",
1662 fr
->fs_path
, idle_timeout
);
1663 state
= STATE_ERROR
;
1669 int i
= rv
- WAIT_OBJECT_0
;
1677 if (GetOverlappedResult((HANDLE
) fr
->fd
, &sov
, &sent
, FALSE
))
1680 ResetEvent(sov
.hEvent
);
1681 fcgi_buf_removed(fr
->serverOutputBuffer
, sent
);
1685 ap_log_rerror(FCGI_LOG_ERR
, r
, "FastCGI: comm with server "
1686 "\"%s\" aborted: GetOverlappedResult() failed", fr
->fs_path
);
1687 state
= STATE_ERROR
;
1698 ResetEvent(rov
.hEvent
);
1700 if (GetOverlappedResult((HANDLE
) fr
->fd
, &rov
, &rcvd
, FALSE
))
1702 fcgi_buf_added(fr
->serverInputBuffer
, rcvd
);
1703 if (dynamic_first_recv
)
1705 dynamic_first_recv
= 0;
1710 ap_log_rerror(FCGI_LOG_ERR
, r
, "FastCGI: comm with server "
1711 "\"%s\" aborted: GetOverlappedResult() failed", fr
->fs_path
);
1712 state
= STATE_ERROR
;
1719 if (fcgi_protocol_dequeue(rp
, fr
))
1721 state
= STATE_ERROR
;
1725 if (fr
->parseHeader
== SCAN_CGI_READING_HEADERS
)
1727 const char * err
= process_headers(r
, fr
);
1730 ap_log_rerror(FCGI_LOG_ERR_NOERRNO
, r
,
1731 "FastCGI: comm with server \"%s\" aborted: "
1732 "error parsing headers: %s", fr
->fs_path
, err
);
1733 state
= STATE_ERROR
;
1738 if (fr
->exitStatusSet
)
1740 fr
->keepReadingFromFcgiApp
= FALSE
;
1741 state
= STATE_CLIENT_SEND
;
1746 if (! fr
->exitStatusSet
|| ! fr
->eofSent
)
1748 CancelIo((HANDLE
) fr
->fd
);
1751 CloseHandle(rov
.hEvent
);
1752 CloseHandle(sov
.hEvent
);
1754 return (state
== STATE_ERROR
);
1758 static int socket_io(fcgi_request
* const fr
)
1768 STATE_SERVER_SEND_ERROR
,
1771 state
= STATE_ENV_SEND
;
1773 request_rec
* const r
= fr
->r
;
1775 struct timeval timeout
;
1776 struct timeval dynamic_last_io_time
= {0, 0};
1779 int nfds
= fr
->fd
+ 1;
1780 int select_status
= 1;
1783 int dynamic_first_recv
= fr
->dynamic
? 1 : 0;
1784 int client_send
= FALSE
;
1785 int client_recv
= FALSE
;
1789 if (fr
->role
== FCGI_RESPONDER
)
1791 client_recv
= (fr
->expectingClientContent
!= 0);
1794 idle_timeout
= fr
->dynamic
? dynamic_idle_timeout
: fr
->fs
->idle_timeout
;
1800 dynamic_last_io_time
= fr
->startTime
;
1802 if (dynamicAppConnectTimeout
)
1804 struct timeval qwait
;
1805 timersub(&fr
->queueTime
, &fr
->startTime
, &qwait
);
1806 dynamic_first_recv
= qwait
.tv_sec
/ dynamicPleaseStartDelay
+ 1;
1810 ap_hard_timeout("FastCGI request processing", r
);
1812 set_nonblocking(fr
, TRUE
);
1817 FD_ZERO(&write_set
);
1821 case STATE_ENV_SEND
:
1823 if (fcgi_protocol_queue_env(r
, fr
, &env
) == 0)
1828 state
= STATE_CLIENT_RECV
;
1832 case STATE_CLIENT_RECV
:
1834 if (read_from_client_n_queue(fr
))
1836 state
= STATE_CLIENT_ERROR
;
1842 state
= STATE_SERVER_SEND
;
1849 case STATE_SERVER_SEND
:
1851 if (BufferLength(fr
->serverOutputBuffer
))
1853 FD_SET(fr
->fd
, &write_set
);
1857 ap_assert(fr
->eofSent
);
1858 state
= STATE_SERVER_RECV
;
1863 case STATE_SERVER_RECV
:
1864 case STATE_SERVER_SEND_ERROR
:
1866 FD_SET(fr
->fd
, &read_set
);
1870 case STATE_CLIENT_SEND
:
1872 if (client_send
|| ! BufferFree(fr
->clientOutputBuffer
))
1874 if (write_to_client(fr
))
1876 state
= STATE_CLIENT_ERROR
;
1890 if (state
== STATE_CLIENT_ERROR
)
1895 /* setup the io timeout */
1897 if (BufferLength(fr
->clientOutputBuffer
))
1899 /* don't let client data sit too long, it might be a push */
1901 timeout
.tv_usec
= 100000;
1903 else if (dynamic_first_recv
)
1906 struct timeval qwait
;
1908 fcgi_util_ticks(&fr
->queueTime
);
1912 /* a send() succeeded last pass */
1913 dynamic_last_io_time
= fr
->queueTime
;
1917 /* timed out last pass */
1918 struct timeval idle_time
;
1920 timersub(&fr
->queueTime
, &dynamic_last_io_time
, &idle_time
);
1922 if (idle_time
.tv_sec
> idle_timeout
)
1924 send_to_pm(FCGI_REQUEST_TIMEOUT_JOB
, fr
->fs_path
, fr
->user
, fr
->group
, 0, 0);
1925 ap_log_rerror(FCGI_LOG_ERR_NOERRNO
, r
, "FastCGI: comm "
1926 "with (dynamic) server \"%s\" aborted: (first read) "
1927 "idle timeout (%d sec)", fr
->fs_path
, idle_timeout
);
1928 state
= STATE_ERROR
;
1933 timersub(&fr
->queueTime
, &fr
->startTime
, &qwait
);
1935 delay
= dynamic_first_recv
* dynamicPleaseStartDelay
;
1937 FCGIDBG5("qwait=%ld.%06ld delay=%d first_recv=%d", qwait
.tv_sec
, qwait
.tv_usec
, delay
, dynamic_first_recv
);
1939 if (qwait
.tv_sec
< delay
)
1941 timeout
.tv_sec
= delay
;
1942 timeout
.tv_usec
= 100000; /* fudge for select() slop */
1943 timersub(&timeout
, &qwait
, &timeout
);
1947 /* Killed time somewhere.. client read? */
1948 send_to_pm(FCGI_REQUEST_TIMEOUT_JOB
, fr
->fs_path
, fr
->user
, fr
->group
, 0, 0);
1949 dynamic_first_recv
= qwait
.tv_sec
/ dynamicPleaseStartDelay
+ 1;
1950 timeout
.tv_sec
= dynamic_first_recv
* dynamicPleaseStartDelay
;
1951 timeout
.tv_usec
= 100000; /* fudge for select() slop */
1952 timersub(&timeout
, &qwait
, &timeout
);
1957 timeout
.tv_sec
= idle_timeout
;
1958 timeout
.tv_usec
= 0;
1961 /* wait on the socket */
1962 select_status
= ap_select(nfds
, &read_set
, &write_set
, NULL
, &timeout
);
1964 if (select_status
< 0)
1966 ap_log_rerror(FCGI_LOG_ERR_ERRNO
, r
, "FastCGI: comm with server "
1967 "\"%s\" aborted: select() failed", fr
->fs_path
);
1968 state
= STATE_ERROR
;
1972 if (select_status
== 0)
1974 /* select() timeout */
1976 if (BufferLength(fr
->clientOutputBuffer
))
1978 if (fr
->role
== FCGI_RESPONDER
)
1983 else if (dynamic_first_recv
)
1985 struct timeval qwait
;
1987 fcgi_util_ticks(&fr
->queueTime
);
1988 timersub(&fr
->queueTime
, &fr
->startTime
, &qwait
);
1990 send_to_pm(FCGI_REQUEST_TIMEOUT_JOB
, fr
->fs_path
, fr
->user
, fr
->group
, 0, 0);
1992 dynamic_first_recv
= qwait
.tv_sec
/ dynamicPleaseStartDelay
+ 1;
1997 ap_log_rerror(FCGI_LOG_ERR_NOERRNO
, r
, "FastCGI: comm with "
1998 "server \"%s\" aborted: idle timeout (%d sec)",
1999 fr
->fs_path
, idle_timeout
);
2000 state
= STATE_SERVER_SEND_ERROR
;
2004 if (FD_ISSET(fr
->fd
, &write_set
))
2006 /* send to the server */
2008 rv
= fcgi_buf_socket_send(fr
->serverOutputBuffer
, fr
->fd
);
2012 ap_log_rerror(FCGI_LOG_ERR
, r
, "FastCGI: comm with server "
2013 "\"%s\" aborted: write failed", fr
->fs_path
);
2014 state
= STATE_ERROR
;
2019 if (FD_ISSET(fr
->fd
, &read_set
))
2021 /* recv from the server */
2023 if (dynamic_first_recv
)
2025 dynamic_first_recv
= 0;
2026 fcgi_util_ticks(&fr
->queueTime
);
2029 rv
= fcgi_buf_socket_recv(fr
->serverInputBuffer
, fr
->fd
);
2033 ap_log_rerror(FCGI_LOG_ERR
, r
, "FastCGI: comm with server "
2034 "\"%s\" aborted: read failed", fr
->fs_path
);
2035 state
= STATE_ERROR
;
2041 fr
->keepReadingFromFcgiApp
= FALSE
;
2042 state
= STATE_CLIENT_SEND
;
2047 if (fcgi_protocol_dequeue(rp
, fr
))
2049 state
= STATE_ERROR
;
2053 if (fr
->parseHeader
== SCAN_CGI_READING_HEADERS
)
2055 const char * err
= process_headers(r
, fr
);
2058 ap_log_rerror(FCGI_LOG_ERR_NOERRNO
, r
,
2059 "FastCGI: comm with server \"%s\" aborted: "
2060 "error parsing headers: %s", fr
->fs_path
, err
);
2061 state
= STATE_ERROR
;
2066 if (fr
->exitStatusSet
)
2068 fr
->keepReadingFromFcgiApp
= FALSE
;
2069 state
= STATE_CLIENT_SEND
;
2074 return (state
== STATE_ERROR
);
2078 /*----------------------------------------------------------------------
2079 * This is the core routine for moving data between the FastCGI
2080 * application and the Web server's client.
2082 static int do_work(request_rec
* const r
, fcgi_request
* const fr
)
2087 fcgi_protocol_queue_begin_request(fr
);
2089 if (fr
->role
== FCGI_RESPONDER
)
2091 rv
= ap_setup_client_block(r
, REQUEST_CHUNKED_ERROR
);
2098 fr
->expectingClientContent
= ap_should_client_block(r
);
2102 ap_register_cleanup(rp
, (void *)fr
, cleanup
, ap_null_cleanup
);
2103 ap_unblock_alarms();
2105 /* Connect to the FastCGI Application */
2106 ap_hard_timeout("connect() to FastCGI server", r
);
2107 if (open_connection_to_fs(fr
) != FCGI_OK
)
2110 return SERVER_ERROR
;
2114 if (fr
->using_npipe_io
)
2124 /* comm with the server is done */
2125 close_connection_to_fs(fr
);
2127 if (fr
->role
== FCGI_RESPONDER
)
2129 sink_client_data(fr
);
2132 while (rv
== 0 && BufferLength(fr
->serverInputBuffer
) || BufferLength(fr
->clientOutputBuffer
))
2134 if (fcgi_protocol_dequeue(rp
, fr
))
2139 if (fr
->parseHeader
== SCAN_CGI_READING_HEADERS
)
2141 const char * err
= process_headers(r
, fr
);
2144 ap_log_rerror(FCGI_LOG_ERR_NOERRNO
, r
,
2145 "FastCGI: comm with server \"%s\" aborted: "
2146 "error parsing headers: %s", fr
->fs_path
, err
);
2151 if (fr
->role
== FCGI_RESPONDER
)
2153 if (write_to_client(fr
))
2160 fcgi_buf_reset(fr
->clientOutputBuffer
);
2164 switch (fr
->parseHeader
)
2166 case SCAN_CGI_FINISHED
:
2168 if (fr
->role
== FCGI_RESPONDER
)
2170 /* RUSSIAN_APACHE requires rflush() over bflush() */
2172 ap_bgetopt(r
->connection
->client
, BO_BYTECT
, &r
->bytes_sent
);
2177 case SCAN_CGI_INT_REDIRECT
:
2178 case SCAN_CGI_SRV_REDIRECT
:
2182 case SCAN_CGI_READING_HEADERS
:
2184 ap_log_rerror(FCGI_LOG_ERR_NOERRNO
, r
, "FastCGI: incomplete headers "
2185 "(%d bytes) received from server \"%s\"", fr
->header
->nelts
, fr
->fs_path
);
2189 case SCAN_CGI_BAD_HEADER
:
2204 static fcgi_request
*create_fcgi_request(request_rec
* const r
, const char *fs_path
)
2206 struct stat
*my_finfo
;
2207 pool
* const p
= r
->pool
;
2209 fcgi_request
* const fr
= (fcgi_request
*)ap_pcalloc(p
, sizeof(fcgi_request
));
2212 my_finfo
= (struct stat
*)ap_palloc(p
, sizeof(struct stat
));
2213 if (stat(fs_path
, my_finfo
) < 0) {
2214 ap_log_rerror(FCGI_LOG_ERR_ERRNO
, r
,
2215 "FastCGI: stat() of \"%s\" failed", fs_path
);
2220 my_finfo
= &r
->finfo
;
2221 fs_path
= r
->filename
;
2224 fs
= fcgi_util_fs_get_by_id(fs_path
, r
->server
->server_uid
, r
->server
->server_gid
);
2226 /* Its a request for a dynamic FastCGI application */
2227 const char * const err
=
2228 fcgi_util_fs_is_path_ok(p
, fs_path
, my_finfo
);
2231 ap_log_rerror(FCGI_LOG_ERR_NOERRNO
, r
, "FastCGI: invalid (dynamic) server \"%s\": %s", fs_path
, err
);
2236 fr
->serverInputBuffer
= fcgi_buf_new(p
, SERVER_BUFSIZE
);
2237 fr
->serverOutputBuffer
= fcgi_buf_new(p
, SERVER_BUFSIZE
);
2238 fr
->clientInputBuffer
= fcgi_buf_new(p
, SERVER_BUFSIZE
);
2239 fr
->clientOutputBuffer
= fcgi_buf_new(p
, SERVER_BUFSIZE
);
2240 fr
->erBufPtr
= fcgi_buf_new(p
, sizeof(FCGI_EndRequestBody
) + 1);
2241 fr
->gotHeader
= FALSE
;
2242 fr
->parseHeader
= SCAN_CGI_READING_HEADERS
;
2243 fr
->header
= ap_make_array(p
, 1, 1);
2244 fr
->fs_stderr
= NULL
;
2246 fr
->readingEndRequestBody
= FALSE
;
2248 fr
->exitStatusSet
= FALSE
;
2249 fr
->requestId
= 1; /* anything but zero is OK here */
2250 fr
->eofSent
= FALSE
;
2251 fr
->role
= FCGI_RESPONDER
;
2252 fr
->expectingClientContent
= FALSE
;
2253 fr
->keepReadingFromFcgiApp
= TRUE
;
2255 fr
->fs_path
= fs_path
;
2256 fr
->authHeaders
= ap_make_table(p
, 10);
2258 fr
->fd
= INVALID_SOCKET
;
2259 fr
->dynamic
= ((fs
== NULL
) || (fs
->directive
== APP_CLASS_DYNAMIC
)) ? TRUE
: FALSE
;
2260 fr
->using_npipe_io
= FALSE
;
2262 fr
->dynamic
= (fs
== NULL
) ? TRUE
: FALSE
;
2266 set_uid_n_gid(r
, &fr
->user
, &fr
->group
);
2272 *----------------------------------------------------------------------
2276 * This routine gets called for a request that corresponds to
2277 * a FastCGI connection. It performs the request synchronously.
2280 * Final status of request: OK or NOT_FOUND or SERVER_ERROR.
2283 * Request performed.
2285 *----------------------------------------------------------------------
2288 /* Stolen from mod_cgi.c..
2289 * KLUDGE --- for back-combatibility, we don't have to check ExecCGI
2290 * in ScriptAliased directories, which means we need to know if this
2291 * request came through ScriptAlias or not... so the Alias module
2292 * leaves a note for us.
2294 static int apache_is_scriptaliased(request_rec
*r
)
2296 const char *t
= ap_table_get(r
->notes
, "alias-forced-type");
2297 return t
&& (!strcasecmp(t
, "cgi-script"));
2300 /* If a script wants to produce its own Redirect body, it now
2301 * has to explicitly *say* "Status: 302". If it wants to use
2302 * Apache redirects say "Status: 200". See process_headers().
2304 static int post_process_for_redirects(request_rec
* const r
,
2305 const fcgi_request
* const fr
)
2307 switch(fr
->parseHeader
) {
2308 case SCAN_CGI_INT_REDIRECT
:
2310 /* @@@ There are still differences between the handling in
2311 * mod_cgi and mod_fastcgi. This needs to be revisited.
2313 /* We already read the message body (if any), so don't allow
2314 * the redirected request to think it has one. We can ignore
2315 * Transfer-Encoding, since we used REQUEST_CHUNKED_ERROR.
2318 r
->method_number
= M_GET
;
2319 ap_table_unset(r
->headers_in
, "Content-length");
2321 ap_internal_redirect_handler(ap_table_get(r
->headers_out
, "Location"), r
);
2324 case SCAN_CGI_SRV_REDIRECT
:
2332 /******************************************************************************
2333 * Process fastcgi-script requests. Based on mod_cgi::cgi_handler().
2335 static int content_handler(request_rec
*r
)
2337 fcgi_request
*fr
= NULL
;
2340 /* Setup a new FastCGI request */
2341 if ((fr
= create_fcgi_request(r
, NULL
)) == NULL
)
2342 return SERVER_ERROR
;
2344 /* If its a dynamic invocation, make sure scripts are OK here */
2345 if (fr
->dynamic
&& !(ap_allow_options(r
) & OPT_EXECCGI
) && !apache_is_scriptaliased(r
)) {
2346 ap_log_rerror(FCGI_LOG_ERR_NOERRNO
, r
,
2347 "FastCGI: \"ExecCGI Option\" is off in this directory: %s", r
->uri
);
2348 return SERVER_ERROR
;
2351 /* Process the fastcgi-script request */
2352 if ((ret
= do_work(r
, fr
)) != OK
)
2355 /* Special case redirects */
2356 ret
= post_process_for_redirects(r
, fr
);
2362 static int post_process_auth_passed_header(table
*t
, const char *key
, const char * const val
)
2364 if (strncasecmp(key
, "Variable-", 9) == 0)
2367 ap_table_setn(t
, key
, val
);
2371 static int post_process_auth_passed_compat_header(table
*t
, const char *key
, const char * const val
)
2373 if (strncasecmp(key
, "Variable-", 9) == 0)
2374 ap_table_setn(t
, key
+ 9, val
);
2379 static int post_process_auth_failed_header(table
* const t
, const char * const key
, const char * const val
)
2381 ap_table_setn(t
, key
, val
);
2385 static void post_process_auth(fcgi_request
* const fr
, const int passed
)
2387 request_rec
* const r
= fr
->r
;
2389 /* Restore the saved subprocess_env because we muddied ours up */
2390 r
->subprocess_env
= fr
->saved_subprocess_env
;
2393 if (fr
->auth_compat
) {
2394 ap_table_do((int (*)(void *, const char *, const char *))post_process_auth_passed_compat_header
,
2395 (void *)r
->subprocess_env
, fr
->authHeaders
, NULL
);
2398 ap_table_do((int (*)(void *, const char *, const char *))post_process_auth_passed_header
,
2399 (void *)r
->subprocess_env
, fr
->authHeaders
, NULL
);
2403 ap_table_do((int (*)(void *, const char *, const char *))post_process_auth_failed_header
,
2404 (void *)r
->err_headers_out
, fr
->authHeaders
, NULL
);
2407 /* @@@ Restore these.. its a hack until I rewrite the header handling */
2408 r
->status
= HTTP_OK
;
2409 r
->status_line
= NULL
;
2412 static int check_user_authentication(request_rec
*r
)
2414 int res
, authenticated
= 0;
2415 const char *password
;
2417 const fcgi_dir_config
* const dir_config
=
2418 (const fcgi_dir_config
*)ap_get_module_config(r
->per_dir_config
, &fastcgi_module
);
2420 if (dir_config
->authenticator
== NULL
)
2423 /* Get the user password */
2424 if ((res
= ap_get_basic_auth_pw(r
, &password
)) != OK
)
2427 if ((fr
= create_fcgi_request(r
, dir_config
->authenticator
)) == NULL
)
2428 return SERVER_ERROR
;
2430 /* Save the existing subprocess_env, because we're gonna muddy it up */
2431 fr
->saved_subprocess_env
= ap_copy_table(r
->pool
, r
->subprocess_env
);
2433 ap_table_setn(r
->subprocess_env
, "REMOTE_PASSWD", password
);
2434 ap_table_setn(r
->subprocess_env
, "FCGI_APACHE_ROLE", "AUTHENTICATOR");
2436 /* The FastCGI Protocol doesn't differentiate authentication */
2437 fr
->role
= FCGI_AUTHORIZER
;
2439 /* Do we need compatibility mode? */
2440 fr
->auth_compat
= (dir_config
->authenticator_options
& FCGI_COMPAT
);
2442 if ((res
= do_work(r
, fr
)) != OK
)
2443 goto AuthenticationFailed
;
2445 authenticated
= (r
->status
== 200);
2446 post_process_auth(fr
, authenticated
);
2448 /* A redirect shouldn't be allowed during the authentication phase */
2449 if (ap_table_get(r
->headers_out
, "Location") != NULL
) {
2450 ap_log_rerror(FCGI_LOG_ERR_NOERRNO
, r
,
2451 "FastCGI: FastCgiAuthenticator \"%s\" redirected (not allowed)",
2452 dir_config
->authenticator
);
2453 goto AuthenticationFailed
;
2459 AuthenticationFailed
:
2460 if (!(dir_config
->authenticator_options
& FCGI_AUTHORITATIVE
))
2463 /* @@@ Probably should support custom_responses */
2464 ap_note_basic_auth_failure(r
);
2465 ap_log_rerror(FCGI_LOG_ERR_NOERRNO
, r
,
2466 "FastCGI: authentication failed for user \"%s\": %s", r
->connection
->user
, r
->uri
);
2467 return (res
== OK
) ? AUTH_REQUIRED
: res
;
2470 static int check_user_authorization(request_rec
*r
)
2472 int res
, authorized
= 0;
2474 const fcgi_dir_config
* const dir_config
=
2475 (const fcgi_dir_config
*)ap_get_module_config(r
->per_dir_config
, &fastcgi_module
);
2477 if (dir_config
->authorizer
== NULL
)
2480 /* @@@ We should probably honor the existing parameters to the require directive
2481 * as well as allow the definition of new ones (or use the basename of the
2482 * FastCGI server and pass the rest of the directive line), but for now keep
2485 if ((fr
= create_fcgi_request(r
, dir_config
->authorizer
)) == NULL
)
2486 return SERVER_ERROR
;
2488 /* Save the existing subprocess_env, because we're gonna muddy it up */
2489 fr
->saved_subprocess_env
= ap_copy_table(r
->pool
, r
->subprocess_env
);
2491 ap_table_setn(r
->subprocess_env
, "FCGI_APACHE_ROLE", "AUTHORIZER");
2493 fr
->role
= FCGI_AUTHORIZER
;
2495 /* Do we need compatibility mode? */
2496 fr
->auth_compat
= (dir_config
->authenticator_options
& FCGI_COMPAT
);
2498 if ((res
= do_work(r
, fr
)) != OK
)
2499 goto AuthorizationFailed
;
2501 authorized
= (r
->status
== 200);
2502 post_process_auth(fr
, authorized
);
2504 /* A redirect shouldn't be allowed during the authorization phase */
2505 if (ap_table_get(r
->headers_out
, "Location") != NULL
) {
2506 ap_log_rerror(FCGI_LOG_ERR_NOERRNO
, r
,
2507 "FastCGI: FastCgiAuthorizer \"%s\" redirected (not allowed)",
2508 dir_config
->authorizer
);
2509 goto AuthorizationFailed
;
2515 AuthorizationFailed
:
2516 if (!(dir_config
->authorizer_options
& FCGI_AUTHORITATIVE
))
2519 /* @@@ Probably should support custom_responses */
2520 ap_note_basic_auth_failure(r
);
2521 ap_log_rerror(FCGI_LOG_ERR_NOERRNO
, r
,
2522 "FastCGI: authorization failed for user \"%s\": %s", r
->connection
->user
, r
->uri
);
2523 return (res
== OK
) ? AUTH_REQUIRED
: res
;
2526 static int check_access(request_rec
*r
)
2528 int res
, access_allowed
= 0;
2530 const fcgi_dir_config
* const dir_config
=
2531 (fcgi_dir_config
*)ap_get_module_config(r
->per_dir_config
, &fastcgi_module
);
2533 if (dir_config
== NULL
|| dir_config
->access_checker
== NULL
)
2536 if ((fr
= create_fcgi_request(r
, dir_config
->access_checker
)) == NULL
)
2537 return SERVER_ERROR
;
2539 /* Save the existing subprocess_env, because we're gonna muddy it up */
2540 fr
->saved_subprocess_env
= ap_copy_table(r
->pool
, r
->subprocess_env
);
2542 ap_table_setn(r
->subprocess_env
, "FCGI_APACHE_ROLE", "ACCESS_CHECKER");
2544 /* The FastCGI Protocol doesn't differentiate access control */
2545 fr
->role
= FCGI_AUTHORIZER
;
2547 /* Do we need compatibility mode? */
2548 fr
->auth_compat
= (dir_config
->authenticator_options
& FCGI_COMPAT
);
2550 if ((res
= do_work(r
, fr
)) != OK
)
2553 access_allowed
= (r
->status
== 200);
2554 post_process_auth(fr
, access_allowed
);
2556 /* A redirect shouldn't be allowed during the access check phase */
2557 if (ap_table_get(r
->headers_out
, "Location") != NULL
) {
2558 ap_log_rerror(FCGI_LOG_ERR_NOERRNO
, r
,
2559 "FastCGI: FastCgiAccessChecker \"%s\" redirected (not allowed)",
2560 dir_config
->access_checker
);
2568 if (!(dir_config
->access_checker_options
& FCGI_AUTHORITATIVE
))
2571 /* @@@ Probably should support custom_responses */
2572 ap_log_rerror(FCGI_LOG_ERR_NOERRNO
, r
, "FastCGI: access denied: %s", r
->uri
);
2573 return (res
== OK
) ? FORBIDDEN
: res
;
2576 command_rec fastcgi_cmds
[] = {
2577 { "AppClass", fcgi_config_new_static_server
, NULL
, RSRC_CONF
, RAW_ARGS
, NULL
},
2578 { "FastCgiServer", fcgi_config_new_static_server
, NULL
, RSRC_CONF
, RAW_ARGS
, NULL
},
2580 { "ExternalAppClass", fcgi_config_new_external_server
, NULL
, RSRC_CONF
, RAW_ARGS
, NULL
},
2581 { "FastCgiExternalServer", fcgi_config_new_external_server
, NULL
, RSRC_CONF
, RAW_ARGS
, NULL
},
2583 { "FastCgiIpcDir", fcgi_config_set_socket_dir
, NULL
, RSRC_CONF
, TAKE1
, NULL
},
2585 { "FastCgiSuexec", fcgi_config_set_wrapper
, NULL
, RSRC_CONF
, TAKE1
, NULL
},
2586 { "FastCgiWrapper", fcgi_config_set_wrapper
, NULL
, RSRC_CONF
, TAKE1
, NULL
},
2588 { "FCGIConfig", fcgi_config_set_config
, NULL
, RSRC_CONF
, RAW_ARGS
, NULL
},
2589 { "FastCgiConfig", fcgi_config_set_config
, NULL
, RSRC_CONF
, RAW_ARGS
, NULL
},
2591 { "FastCgiAuthenticator", fcgi_config_new_auth_server
,
2592 (void *)FCGI_AUTH_TYPE_AUTHENTICATOR
, ACCESS_CONF
, TAKE12
,
2593 "a fastcgi-script path (absolute or relative to ServerRoot) followed by an optional -compat" },
2594 { "FastCgiAuthenticatorAuthoritative", fcgi_config_set_authoritative_slot
,
2595 (void *)XtOffsetOf(fcgi_dir_config
, authenticator_options
), ACCESS_CONF
, FLAG
,
2596 "Set to 'off' to allow authentication to be passed along to lower modules upon failure" },
2598 { "FastCgiAuthorizer", fcgi_config_new_auth_server
,
2599 (void *)FCGI_AUTH_TYPE_AUTHORIZER
, ACCESS_CONF
, TAKE12
,
2600 "a fastcgi-script path (absolute or relative to ServerRoot) followed by an optional -compat" },
2601 { "FastCgiAuthorizerAuthoritative", fcgi_config_set_authoritative_slot
,
2602 (void *)XtOffsetOf(fcgi_dir_config
, authorizer_options
), ACCESS_CONF
, FLAG
,
2603 "Set to 'off' to allow authorization to be passed along to lower modules upon failure" },
2605 { "FastCgiAccessChecker", fcgi_config_new_auth_server
,
2606 (void *)FCGI_AUTH_TYPE_ACCESS_CHECKER
, ACCESS_CONF
, TAKE12
,
2607 "a fastcgi-script path (absolute or relative to ServerRoot) followed by an optional -compat" },
2608 { "FastCgiAccessCheckerAuthoritative", fcgi_config_set_authoritative_slot
,
2609 (void *)XtOffsetOf(fcgi_dir_config
, access_checker_options
), ACCESS_CONF
, FLAG
,
2610 "Set to 'off' to allow access control to be passed along to lower modules upon failure" },
2615 handler_rec fastcgi_handlers
[] = {
2616 { FCGI_MAGIC_TYPE
, content_handler
},
2617 { "fastcgi-script", content_handler
},
2622 module MODULE_VAR_EXPORT fastcgi_module
= {
2623 STANDARD_MODULE_STUFF
,
2624 init_module
, /* initializer */
2625 fcgi_config_create_dir_config
, /* per-dir config creator */
2626 NULL
, /* per-dir config merger (default: override) */
2627 NULL
, /* per-server config creator */
2628 NULL
, /* per-server config merger (default: override) */
2629 fastcgi_cmds
, /* command table */
2630 fastcgi_handlers
, /* [9] content handlers */
2631 NULL
, /* [2] URI-to-filename translation */
2632 check_user_authentication
, /* [5] authenticate user_id */
2633 check_user_authorization
, /* [6] authorize user_id */
2634 check_access
, /* [4] check access (based on src & http headers) */
2635 NULL
, /* [7] check/set MIME type */
2636 NULL
, /* [8] fixups */
2637 NULL
, /* [10] logger */
2638 NULL
, /* [3] header-parser */
2639 fcgi_child_init
, /* process initialization */
2640 fcgi_child_exit
, /* process exit/cleanup */
2641 NULL
/* [1] post read-request handling */