4 * Apache server module for FastCGI.
6 * $Id: mod_fastcgi.c,v 1.130 2002/03/13 18:32:34 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
);
1374 static int npipe_io(fcgi_request
* const fr
)
1376 request_rec
* const r
= fr
->r
;
1387 state
= STATE_ENV_SEND
;
1388 env_status env_status
;
1390 int dynamic_first_recv
= fr
->dynamic
;
1391 int idle_timeout
= fr
->dynamic
? dynamic_idle_timeout
: fr
->fs
->idle_timeout
;
1392 int send_pending
= 0;
1393 int recv_pending
= 0;
1394 int client_send
= 0;
1399 struct timeval timeout
;
1400 struct timeval dynamic_last_io_time
= {0, 0};
1402 pool
* const rp
= r
->pool
;
1404 DWORD recv_count
= 0;
1406 if (fr
->role
== FCGI_RESPONDER
)
1408 client_recv
= (fr
->expectingClientContent
!= 0);
1411 idle_timeout
= fr
->dynamic
? dynamic_idle_timeout
: fr
->fs
->idle_timeout
;
1413 env_status
.envp
= NULL
;
1415 events
[0] = CreateEvent(NULL
, TRUE
, FALSE
, NULL
);
1416 events
[1] = CreateEvent(NULL
, TRUE
, FALSE
, NULL
);
1417 sov
.hEvent
= events
[0];
1418 rov
.hEvent
= events
[1];
1422 dynamic_last_io_time
= fr
->startTime
;
1424 if (dynamicAppConnectTimeout
)
1426 struct timeval qwait
;
1427 timersub(&fr
->queueTime
, &fr
->startTime
, &qwait
);
1428 dynamic_first_recv
= qwait
.tv_sec
/ dynamicPleaseStartDelay
+ 1;
1432 ap_hard_timeout("FastCGI request processing", r
);
1434 while (state
!= STATE_CLIENT_SEND
)
1440 case STATE_ENV_SEND
:
1442 if (fcgi_protocol_queue_env(r
, fr
, &env_status
) == 0)
1447 state
= STATE_CLIENT_RECV
;
1451 case STATE_CLIENT_RECV
:
1453 if (read_from_client_n_queue(fr
) != OK
)
1455 state
= STATE_CLIENT_ERROR
;
1461 state
= STATE_SERVER_SEND
;
1468 case STATE_SERVER_SEND
:
1470 if (! send_pending
&& BufferLength(fr
->serverOutputBuffer
))
1472 Buffer
* b
= fr
->serverOutputBuffer
;
1475 len
= min(b
->length
, b
->data
+ b
->size
- b
->begin
);
1477 if (WriteFile((HANDLE
) fr
->fd
, b
->begin
, len
, &sent
, &sov
))
1479 fcgi_buf_removed(b
, sent
);
1480 ResetEvent(sov
.hEvent
);
1482 else if (GetLastError() == ERROR_IO_PENDING
)
1488 ap_log_rerror(FCGI_LOG_ERR
, r
, "FastCGI: comm with server "
1489 "\"%s\" aborted: WriteFile() failed", fr
->fs_path
);
1490 state
= STATE_ERROR
;
1497 case STATE_SERVER_RECV
:
1499 if (! recv_pending
&& BufferFree(fr
->serverInputBuffer
))
1501 Buffer
* b
= fr
->serverInputBuffer
;
1504 len
= min(b
->size
- b
->length
, b
->data
+ b
->size
- b
->end
);
1506 if (ReadFile((HANDLE
) fr
->fd
, b
->end
, len
, &rcvd
, &rov
))
1508 fcgi_buf_added(b
, rcvd
);
1510 ResetEvent(rov
.hEvent
);
1511 if (dynamic_first_recv
)
1513 dynamic_first_recv
= 0;
1516 else if (GetLastError() == ERROR_IO_PENDING
)
1520 else if (GetLastError() == ERROR_HANDLE_EOF
)
1522 fr
->keepReadingFromFcgiApp
= FALSE
;
1523 state
= STATE_CLIENT_SEND
;
1524 ResetEvent(rov
.hEvent
);
1527 else if (GetLastError() == ERROR_NO_DATA
)
1533 ap_log_rerror(FCGI_LOG_ERR
, r
, "FastCGI: comm with server "
1534 "\"%s\" aborted: ReadFile() failed", fr
->fs_path
);
1535 state
= STATE_ERROR
;
1542 case STATE_CLIENT_SEND
:
1544 if (client_send
|| ! BufferFree(fr
->clientOutputBuffer
))
1546 if (write_to_client(fr
))
1548 state
= STATE_CLIENT_ERROR
;
1562 if (state
== STATE_CLIENT_ERROR
|| state
== STATE_ERROR
)
1567 /* setup the io timeout */
1569 if (BufferLength(fr
->clientOutputBuffer
))
1571 /* don't let client data sit too long, it might be a push */
1573 timeout
.tv_usec
= 100000;
1575 else if (dynamic_first_recv
)
1578 struct timeval qwait
;
1580 fcgi_util_ticks(&fr
->queueTime
);
1584 /* a send() succeeded last pass */
1585 dynamic_last_io_time
= fr
->queueTime
;
1589 /* timed out last pass */
1590 struct timeval idle_time
;
1592 timersub(&fr
->queueTime
, &dynamic_last_io_time
, &idle_time
);
1594 if (idle_time
.tv_sec
> idle_timeout
)
1596 send_to_pm(FCGI_REQUEST_TIMEOUT_JOB
, fr
->fs_path
, fr
->user
, fr
->group
, 0, 0);
1597 ap_log_rerror(FCGI_LOG_ERR_NOERRNO
, r
, "FastCGI: comm "
1598 "with (dynamic) server \"%s\" aborted: (first read) "
1599 "idle timeout (%d sec)", fr
->fs_path
, idle_timeout
);
1600 state
= STATE_ERROR
;
1605 timersub(&fr
->queueTime
, &fr
->startTime
, &qwait
);
1607 delay
= dynamic_first_recv
* dynamicPleaseStartDelay
;
1609 if (qwait
.tv_sec
< delay
)
1611 timeout
.tv_sec
= delay
;
1612 timeout
.tv_usec
= 100000; /* fudge for select() slop */
1613 timersub(&timeout
, &qwait
, &timeout
);
1617 /* Killed time somewhere.. client read? */
1618 send_to_pm(FCGI_REQUEST_TIMEOUT_JOB
, fr
->fs_path
, fr
->user
, fr
->group
, 0, 0);
1619 dynamic_first_recv
= qwait
.tv_sec
/ dynamicPleaseStartDelay
+ 1;
1620 timeout
.tv_sec
= dynamic_first_recv
* dynamicPleaseStartDelay
;
1621 timeout
.tv_usec
= 100000; /* fudge for select() slop */
1622 timersub(&timeout
, &qwait
, &timeout
);
1627 timeout
.tv_sec
= idle_timeout
;
1628 timeout
.tv_usec
= 0;
1631 /* require a pended recv otherwise the app can deadlock */
1634 msec_timeout
= timeout
.tv_sec
* 1000 + timeout
.tv_usec
/ 1000;
1636 rv
= WaitForMultipleObjects(2, events
, FALSE
, msec_timeout
);
1638 if (rv
== WAIT_TIMEOUT
)
1642 if (BufferLength(fr
->clientOutputBuffer
))
1646 else if (dynamic_first_recv
)
1648 struct timeval qwait
;
1650 fcgi_util_ticks(&fr
->queueTime
);
1651 timersub(&fr
->queueTime
, &fr
->startTime
, &qwait
);
1653 send_to_pm(FCGI_REQUEST_TIMEOUT_JOB
, fr
->fs_path
, fr
->user
, fr
->group
, 0, 0);
1655 dynamic_first_recv
= qwait
.tv_sec
/ dynamicPleaseStartDelay
+ 1;
1659 ap_log_rerror(FCGI_LOG_ERR_NOERRNO
, r
, "FastCGI: comm with "
1660 "server \"%s\" aborted: idle timeout (%d sec)",
1661 fr
->fs_path
, idle_timeout
);
1662 state
= STATE_ERROR
;
1668 int i
= rv
- WAIT_OBJECT_0
;
1676 if (GetOverlappedResult((HANDLE
) fr
->fd
, &sov
, &sent
, FALSE
))
1679 ResetEvent(sov
.hEvent
);
1680 fcgi_buf_removed(fr
->serverOutputBuffer
, sent
);
1684 ap_log_rerror(FCGI_LOG_ERR
, r
, "FastCGI: comm with server "
1685 "\"%s\" aborted: GetOverlappedResult() failed", fr
->fs_path
);
1686 state
= STATE_ERROR
;
1697 ResetEvent(rov
.hEvent
);
1699 if (GetOverlappedResult((HANDLE
) fr
->fd
, &rov
, &rcvd
, FALSE
))
1701 fcgi_buf_added(fr
->serverInputBuffer
, rcvd
);
1702 if (dynamic_first_recv
)
1704 dynamic_first_recv
= 0;
1709 ap_log_rerror(FCGI_LOG_ERR
, r
, "FastCGI: comm with server "
1710 "\"%s\" aborted: GetOverlappedResult() failed", fr
->fs_path
);
1711 state
= STATE_ERROR
;
1718 if (fcgi_protocol_dequeue(rp
, fr
))
1720 state
= STATE_ERROR
;
1724 if (fr
->parseHeader
== SCAN_CGI_READING_HEADERS
)
1726 const char * err
= process_headers(r
, fr
);
1729 ap_log_rerror(FCGI_LOG_ERR_NOERRNO
, r
,
1730 "FastCGI: comm with server \"%s\" aborted: "
1731 "error parsing headers: %s", fr
->fs_path
, err
);
1732 state
= STATE_ERROR
;
1737 if (fr
->exitStatusSet
)
1739 fr
->keepReadingFromFcgiApp
= FALSE
;
1740 state
= STATE_CLIENT_SEND
;
1745 if (! fr
->exitStatusSet
|| ! fr
->eofSent
)
1747 CancelIo((HANDLE
) fr
->fd
);
1750 CloseHandle(rov
.hEvent
);
1751 CloseHandle(sov
.hEvent
);
1753 return (state
== STATE_ERROR
);
1756 static int socket_io(fcgi_request
* const fr
)
1766 STATE_SERVER_SEND_ERROR
,
1769 state
= STATE_ENV_SEND
;
1771 request_rec
* const r
= fr
->r
;
1773 struct timeval timeout
;
1774 struct timeval dynamic_last_io_time
= {0, 0};
1777 int nfds
= fr
->fd
+ 1;
1778 int select_status
= 1;
1781 int dynamic_first_recv
= fr
->dynamic
? 1 : 0;
1782 int client_send
= FALSE
;
1783 int client_recv
= FALSE
;
1787 if (fr
->role
== FCGI_RESPONDER
)
1789 client_recv
= (fr
->expectingClientContent
!= 0);
1792 idle_timeout
= fr
->dynamic
? dynamic_idle_timeout
: fr
->fs
->idle_timeout
;
1798 dynamic_last_io_time
= fr
->startTime
;
1800 if (dynamicAppConnectTimeout
)
1802 struct timeval qwait
;
1803 timersub(&fr
->queueTime
, &fr
->startTime
, &qwait
);
1804 dynamic_first_recv
= qwait
.tv_sec
/ dynamicPleaseStartDelay
+ 1;
1808 ap_hard_timeout("FastCGI request processing", r
);
1810 set_nonblocking(fr
, TRUE
);
1815 FD_ZERO(&write_set
);
1819 case STATE_ENV_SEND
:
1821 if (fcgi_protocol_queue_env(r
, fr
, &env
) == 0)
1826 state
= STATE_CLIENT_RECV
;
1830 case STATE_CLIENT_RECV
:
1832 if (read_from_client_n_queue(fr
))
1834 state
= STATE_CLIENT_ERROR
;
1840 state
= STATE_SERVER_SEND
;
1847 case STATE_SERVER_SEND
:
1849 if (BufferLength(fr
->serverOutputBuffer
))
1851 FD_SET(fr
->fd
, &write_set
);
1855 ap_assert(fr
->eofSent
);
1856 state
= STATE_SERVER_RECV
;
1861 case STATE_SERVER_RECV
:
1862 case STATE_SERVER_SEND_ERROR
:
1864 FD_SET(fr
->fd
, &read_set
);
1868 case STATE_CLIENT_SEND
:
1870 if (client_send
|| ! BufferFree(fr
->clientOutputBuffer
))
1872 if (write_to_client(fr
))
1874 state
= STATE_CLIENT_ERROR
;
1888 if (state
== STATE_CLIENT_ERROR
)
1893 /* setup the io timeout */
1895 if (BufferLength(fr
->clientOutputBuffer
))
1897 /* don't let client data sit too long, it might be a push */
1899 timeout
.tv_usec
= 100000;
1901 else if (dynamic_first_recv
)
1904 struct timeval qwait
;
1906 fcgi_util_ticks(&fr
->queueTime
);
1910 /* a send() succeeded last pass */
1911 dynamic_last_io_time
= fr
->queueTime
;
1915 /* timed out last pass */
1916 struct timeval idle_time
;
1918 timersub(&fr
->queueTime
, &dynamic_last_io_time
, &idle_time
);
1920 if (idle_time
.tv_sec
> idle_timeout
)
1922 send_to_pm(FCGI_REQUEST_TIMEOUT_JOB
, fr
->fs_path
, fr
->user
, fr
->group
, 0, 0);
1923 ap_log_rerror(FCGI_LOG_ERR_NOERRNO
, r
, "FastCGI: comm "
1924 "with (dynamic) server \"%s\" aborted: (first read) "
1925 "idle timeout (%d sec)", fr
->fs_path
, idle_timeout
);
1926 state
= STATE_ERROR
;
1931 timersub(&fr
->queueTime
, &fr
->startTime
, &qwait
);
1933 delay
= dynamic_first_recv
* dynamicPleaseStartDelay
;
1935 if (qwait
.tv_sec
< delay
)
1937 timeout
.tv_sec
= delay
;
1938 timeout
.tv_usec
= 100000; /* fudge for select() slop */
1939 timersub(&timeout
, &qwait
, &timeout
);
1943 /* Killed time somewhere.. client read? */
1944 send_to_pm(FCGI_REQUEST_TIMEOUT_JOB
, fr
->fs_path
, fr
->user
, fr
->group
, 0, 0);
1945 dynamic_first_recv
= qwait
.tv_sec
/ dynamicPleaseStartDelay
+ 1;
1946 timeout
.tv_sec
= dynamic_first_recv
* dynamicPleaseStartDelay
;
1947 timeout
.tv_usec
= 100000; /* fudge for select() slop */
1948 timersub(&timeout
, &qwait
, &timeout
);
1953 timeout
.tv_sec
= idle_timeout
;
1954 timeout
.tv_usec
= 0;
1957 /* wait on the socket */
1958 select_status
= ap_select(nfds
, &read_set
, &write_set
, NULL
, &timeout
);
1960 if (select_status
< 0)
1962 ap_log_rerror(FCGI_LOG_ERR_ERRNO
, r
, "FastCGI: comm with server "
1963 "\"%s\" aborted: select() failed", fr
->fs_path
);
1964 state
= STATE_ERROR
;
1968 if (select_status
== 0)
1970 /* select() timeout */
1972 if (BufferLength(fr
->clientOutputBuffer
))
1974 if (fr
->role
== FCGI_RESPONDER
)
1979 else if (dynamic_first_recv
)
1981 struct timeval qwait
;
1983 fcgi_util_ticks(&fr
->queueTime
);
1984 timersub(&fr
->queueTime
, &fr
->startTime
, &qwait
);
1986 send_to_pm(FCGI_REQUEST_TIMEOUT_JOB
, fr
->fs_path
, fr
->user
, fr
->group
, 0, 0);
1988 dynamic_first_recv
= qwait
.tv_sec
/ dynamicPleaseStartDelay
+ 1;
1993 ap_log_rerror(FCGI_LOG_ERR_NOERRNO
, r
, "FastCGI: comm with "
1994 "server \"%s\" aborted: idle timeout (%d sec)",
1995 fr
->fs_path
, idle_timeout
);
1996 state
= STATE_SERVER_SEND_ERROR
;
2000 if (FD_ISSET(fr
->fd
, &write_set
))
2002 /* send to the server */
2004 rv
= fcgi_buf_socket_send(fr
->serverOutputBuffer
, fr
->fd
);
2008 ap_log_rerror(FCGI_LOG_ERR
, r
, "FastCGI: comm with server "
2009 "\"%s\" aborted: write failed", fr
->fs_path
);
2010 state
= STATE_ERROR
;
2015 if (FD_ISSET(fr
->fd
, &read_set
))
2017 /* recv from the server */
2019 if (dynamic_first_recv
)
2021 dynamic_first_recv
= 0;
2022 fcgi_util_ticks(&fr
->queueTime
);
2025 rv
= fcgi_buf_socket_recv(fr
->serverInputBuffer
, fr
->fd
);
2029 ap_log_rerror(FCGI_LOG_ERR
, r
, "FastCGI: comm with server "
2030 "\"%s\" aborted: read failed", fr
->fs_path
);
2031 state
= STATE_ERROR
;
2037 fr
->keepReadingFromFcgiApp
= FALSE
;
2038 state
= STATE_CLIENT_SEND
;
2043 if (fcgi_protocol_dequeue(rp
, fr
))
2045 state
= STATE_ERROR
;
2049 if (fr
->parseHeader
== SCAN_CGI_READING_HEADERS
)
2051 const char * err
= process_headers(r
, fr
);
2054 ap_log_rerror(FCGI_LOG_ERR_NOERRNO
, r
,
2055 "FastCGI: comm with server \"%s\" aborted: "
2056 "error parsing headers: %s", fr
->fs_path
, err
);
2057 state
= STATE_ERROR
;
2062 if (fr
->exitStatusSet
)
2064 fr
->keepReadingFromFcgiApp
= FALSE
;
2065 state
= STATE_CLIENT_SEND
;
2070 return (state
== STATE_ERROR
);
2074 /*----------------------------------------------------------------------
2075 * This is the core routine for moving data between the FastCGI
2076 * application and the Web server's client.
2078 static int do_work(request_rec
* const r
, fcgi_request
* const fr
)
2083 fcgi_protocol_queue_begin_request(fr
);
2085 if (fr
->role
== FCGI_RESPONDER
)
2087 rv
= ap_setup_client_block(r
, REQUEST_CHUNKED_ERROR
);
2094 fr
->expectingClientContent
= ap_should_client_block(r
);
2098 ap_register_cleanup(rp
, (void *)fr
, cleanup
, ap_null_cleanup
);
2099 ap_unblock_alarms();
2101 /* Connect to the FastCGI Application */
2102 ap_hard_timeout("connect() to FastCGI server", r
);
2103 if (open_connection_to_fs(fr
) != FCGI_OK
)
2106 return SERVER_ERROR
;
2110 if (fr
->using_npipe_io
)
2120 /* comm with the server is done */
2121 close_connection_to_fs(fr
);
2123 if (fr
->role
== FCGI_RESPONDER
)
2125 sink_client_data(fr
);
2128 while (rv
== 0 && BufferLength(fr
->serverInputBuffer
) || BufferLength(fr
->clientOutputBuffer
))
2130 if (fcgi_protocol_dequeue(rp
, fr
))
2135 if (fr
->parseHeader
== SCAN_CGI_READING_HEADERS
)
2137 const char * err
= process_headers(r
, fr
);
2140 ap_log_rerror(FCGI_LOG_ERR_NOERRNO
, r
,
2141 "FastCGI: comm with server \"%s\" aborted: "
2142 "error parsing headers: %s", fr
->fs_path
, err
);
2147 if (fr
->role
== FCGI_RESPONDER
)
2149 if (write_to_client(fr
))
2156 fcgi_buf_reset(fr
->clientOutputBuffer
);
2160 switch (fr
->parseHeader
)
2162 case SCAN_CGI_FINISHED
:
2164 if (fr
->role
== FCGI_RESPONDER
)
2166 /* RUSSIAN_APACHE requires rflush() over bflush() */
2168 ap_bgetopt(r
->connection
->client
, BO_BYTECT
, &r
->bytes_sent
);
2173 case SCAN_CGI_INT_REDIRECT
:
2174 case SCAN_CGI_SRV_REDIRECT
:
2178 case SCAN_CGI_READING_HEADERS
:
2180 ap_log_rerror(FCGI_LOG_ERR_NOERRNO
, r
, "FastCGI: incomplete headers "
2181 "(%d bytes) received from server \"%s\"", fr
->header
->nelts
, fr
->fs_path
);
2185 case SCAN_CGI_BAD_HEADER
:
2200 static fcgi_request
*create_fcgi_request(request_rec
* const r
, const char *fs_path
)
2202 struct stat
*my_finfo
;
2203 pool
* const p
= r
->pool
;
2205 fcgi_request
* const fr
= (fcgi_request
*)ap_pcalloc(p
, sizeof(fcgi_request
));
2208 my_finfo
= (struct stat
*)ap_palloc(p
, sizeof(struct stat
));
2209 if (stat(fs_path
, my_finfo
) < 0) {
2210 ap_log_rerror(FCGI_LOG_ERR_ERRNO
, r
,
2211 "FastCGI: stat() of \"%s\" failed", fs_path
);
2216 my_finfo
= &r
->finfo
;
2217 fs_path
= r
->filename
;
2220 fs
= fcgi_util_fs_get_by_id(fs_path
, r
->server
->server_uid
, r
->server
->server_gid
);
2222 /* Its a request for a dynamic FastCGI application */
2223 const char * const err
=
2224 fcgi_util_fs_is_path_ok(p
, fs_path
, my_finfo
);
2227 ap_log_rerror(FCGI_LOG_ERR_NOERRNO
, r
, "FastCGI: invalid (dynamic) server \"%s\": %s", fs_path
, err
);
2232 fr
->serverInputBuffer
= fcgi_buf_new(p
, SERVER_BUFSIZE
);
2233 fr
->serverOutputBuffer
= fcgi_buf_new(p
, SERVER_BUFSIZE
);
2234 fr
->clientInputBuffer
= fcgi_buf_new(p
, SERVER_BUFSIZE
);
2235 fr
->clientOutputBuffer
= fcgi_buf_new(p
, SERVER_BUFSIZE
);
2236 fr
->erBufPtr
= fcgi_buf_new(p
, sizeof(FCGI_EndRequestBody
) + 1);
2237 fr
->gotHeader
= FALSE
;
2238 fr
->parseHeader
= SCAN_CGI_READING_HEADERS
;
2239 fr
->header
= ap_make_array(p
, 1, 1);
2240 fr
->fs_stderr
= NULL
;
2242 fr
->readingEndRequestBody
= FALSE
;
2244 fr
->exitStatusSet
= FALSE
;
2245 fr
->requestId
= 1; /* anything but zero is OK here */
2246 fr
->eofSent
= FALSE
;
2247 fr
->role
= FCGI_RESPONDER
;
2248 fr
->expectingClientContent
= FALSE
;
2249 fr
->keepReadingFromFcgiApp
= TRUE
;
2251 fr
->fs_path
= fs_path
;
2252 fr
->authHeaders
= ap_make_table(p
, 10);
2254 fr
->fd
= INVALID_SOCKET
;
2255 fr
->dynamic
= ((fs
== NULL
) || (fs
->directive
== APP_CLASS_DYNAMIC
)) ? TRUE
: FALSE
;
2256 fr
->using_npipe_io
= FALSE
;
2258 fr
->dynamic
= (fs
== NULL
) ? TRUE
: FALSE
;
2262 set_uid_n_gid(r
, &fr
->user
, &fr
->group
);
2268 *----------------------------------------------------------------------
2272 * This routine gets called for a request that corresponds to
2273 * a FastCGI connection. It performs the request synchronously.
2276 * Final status of request: OK or NOT_FOUND or SERVER_ERROR.
2279 * Request performed.
2281 *----------------------------------------------------------------------
2284 /* Stolen from mod_cgi.c..
2285 * KLUDGE --- for back-combatibility, we don't have to check ExecCGI
2286 * in ScriptAliased directories, which means we need to know if this
2287 * request came through ScriptAlias or not... so the Alias module
2288 * leaves a note for us.
2290 static int apache_is_scriptaliased(request_rec
*r
)
2292 const char *t
= ap_table_get(r
->notes
, "alias-forced-type");
2293 return t
&& (!strcasecmp(t
, "cgi-script"));
2296 /* If a script wants to produce its own Redirect body, it now
2297 * has to explicitly *say* "Status: 302". If it wants to use
2298 * Apache redirects say "Status: 200". See process_headers().
2300 static int post_process_for_redirects(request_rec
* const r
,
2301 const fcgi_request
* const fr
)
2303 switch(fr
->parseHeader
) {
2304 case SCAN_CGI_INT_REDIRECT
:
2306 /* @@@ There are still differences between the handling in
2307 * mod_cgi and mod_fastcgi. This needs to be revisited.
2309 /* We already read the message body (if any), so don't allow
2310 * the redirected request to think it has one. We can ignore
2311 * Transfer-Encoding, since we used REQUEST_CHUNKED_ERROR.
2314 r
->method_number
= M_GET
;
2315 ap_table_unset(r
->headers_in
, "Content-length");
2317 ap_internal_redirect_handler(ap_table_get(r
->headers_out
, "Location"), r
);
2320 case SCAN_CGI_SRV_REDIRECT
:
2328 /******************************************************************************
2329 * Process fastcgi-script requests. Based on mod_cgi::cgi_handler().
2331 static int content_handler(request_rec
*r
)
2333 fcgi_request
*fr
= NULL
;
2336 /* Setup a new FastCGI request */
2337 if ((fr
= create_fcgi_request(r
, NULL
)) == NULL
)
2338 return SERVER_ERROR
;
2340 /* If its a dynamic invocation, make sure scripts are OK here */
2341 if (fr
->dynamic
&& !(ap_allow_options(r
) & OPT_EXECCGI
) && !apache_is_scriptaliased(r
)) {
2342 ap_log_rerror(FCGI_LOG_ERR_NOERRNO
, r
,
2343 "FastCGI: \"ExecCGI Option\" is off in this directory: %s", r
->uri
);
2344 return SERVER_ERROR
;
2347 /* Process the fastcgi-script request */
2348 if ((ret
= do_work(r
, fr
)) != OK
)
2351 /* Special case redirects */
2352 ret
= post_process_for_redirects(r
, fr
);
2358 static int post_process_auth_passed_header(table
*t
, const char *key
, const char * const val
)
2360 if (strncasecmp(key
, "Variable-", 9) == 0)
2363 ap_table_setn(t
, key
, val
);
2367 static int post_process_auth_passed_compat_header(table
*t
, const char *key
, const char * const val
)
2369 if (strncasecmp(key
, "Variable-", 9) == 0)
2370 ap_table_setn(t
, key
+ 9, val
);
2375 static int post_process_auth_failed_header(table
* const t
, const char * const key
, const char * const val
)
2377 ap_table_setn(t
, key
, val
);
2381 static void post_process_auth(fcgi_request
* const fr
, const int passed
)
2383 request_rec
* const r
= fr
->r
;
2385 /* Restore the saved subprocess_env because we muddied ours up */
2386 r
->subprocess_env
= fr
->saved_subprocess_env
;
2389 if (fr
->auth_compat
) {
2390 ap_table_do((int (*)(void *, const char *, const char *))post_process_auth_passed_compat_header
,
2391 (void *)r
->subprocess_env
, fr
->authHeaders
, NULL
);
2394 ap_table_do((int (*)(void *, const char *, const char *))post_process_auth_passed_header
,
2395 (void *)r
->subprocess_env
, fr
->authHeaders
, NULL
);
2399 ap_table_do((int (*)(void *, const char *, const char *))post_process_auth_failed_header
,
2400 (void *)r
->err_headers_out
, fr
->authHeaders
, NULL
);
2403 /* @@@ Restore these.. its a hack until I rewrite the header handling */
2404 r
->status
= HTTP_OK
;
2405 r
->status_line
= NULL
;
2408 static int check_user_authentication(request_rec
*r
)
2410 int res
, authenticated
= 0;
2411 const char *password
;
2413 const fcgi_dir_config
* const dir_config
=
2414 (const fcgi_dir_config
*)ap_get_module_config(r
->per_dir_config
, &fastcgi_module
);
2416 if (dir_config
->authenticator
== NULL
)
2419 /* Get the user password */
2420 if ((res
= ap_get_basic_auth_pw(r
, &password
)) != OK
)
2423 if ((fr
= create_fcgi_request(r
, dir_config
->authenticator
)) == NULL
)
2424 return SERVER_ERROR
;
2426 /* Save the existing subprocess_env, because we're gonna muddy it up */
2427 fr
->saved_subprocess_env
= ap_copy_table(r
->pool
, r
->subprocess_env
);
2429 ap_table_setn(r
->subprocess_env
, "REMOTE_PASSWD", password
);
2430 ap_table_setn(r
->subprocess_env
, "FCGI_APACHE_ROLE", "AUTHENTICATOR");
2432 /* The FastCGI Protocol doesn't differentiate authentication */
2433 fr
->role
= FCGI_AUTHORIZER
;
2435 /* Do we need compatibility mode? */
2436 fr
->auth_compat
= (dir_config
->authenticator_options
& FCGI_COMPAT
);
2438 if ((res
= do_work(r
, fr
)) != OK
)
2439 goto AuthenticationFailed
;
2441 authenticated
= (r
->status
== 200);
2442 post_process_auth(fr
, authenticated
);
2444 /* A redirect shouldn't be allowed during the authentication phase */
2445 if (ap_table_get(r
->headers_out
, "Location") != NULL
) {
2446 ap_log_rerror(FCGI_LOG_ERR_NOERRNO
, r
,
2447 "FastCGI: FastCgiAuthenticator \"%s\" redirected (not allowed)",
2448 dir_config
->authenticator
);
2449 goto AuthenticationFailed
;
2455 AuthenticationFailed
:
2456 if (!(dir_config
->authenticator_options
& FCGI_AUTHORITATIVE
))
2459 /* @@@ Probably should support custom_responses */
2460 ap_note_basic_auth_failure(r
);
2461 ap_log_rerror(FCGI_LOG_ERR_NOERRNO
, r
,
2462 "FastCGI: authentication failed for user \"%s\": %s", r
->connection
->user
, r
->uri
);
2463 return (res
== OK
) ? AUTH_REQUIRED
: res
;
2466 static int check_user_authorization(request_rec
*r
)
2468 int res
, authorized
= 0;
2470 const fcgi_dir_config
* const dir_config
=
2471 (const fcgi_dir_config
*)ap_get_module_config(r
->per_dir_config
, &fastcgi_module
);
2473 if (dir_config
->authorizer
== NULL
)
2476 /* @@@ We should probably honor the existing parameters to the require directive
2477 * as well as allow the definition of new ones (or use the basename of the
2478 * FastCGI server and pass the rest of the directive line), but for now keep
2481 if ((fr
= create_fcgi_request(r
, dir_config
->authorizer
)) == NULL
)
2482 return SERVER_ERROR
;
2484 /* Save the existing subprocess_env, because we're gonna muddy it up */
2485 fr
->saved_subprocess_env
= ap_copy_table(r
->pool
, r
->subprocess_env
);
2487 ap_table_setn(r
->subprocess_env
, "FCGI_APACHE_ROLE", "AUTHORIZER");
2489 fr
->role
= FCGI_AUTHORIZER
;
2491 /* Do we need compatibility mode? */
2492 fr
->auth_compat
= (dir_config
->authenticator_options
& FCGI_COMPAT
);
2494 if ((res
= do_work(r
, fr
)) != OK
)
2495 goto AuthorizationFailed
;
2497 authorized
= (r
->status
== 200);
2498 post_process_auth(fr
, authorized
);
2500 /* A redirect shouldn't be allowed during the authorization phase */
2501 if (ap_table_get(r
->headers_out
, "Location") != NULL
) {
2502 ap_log_rerror(FCGI_LOG_ERR_NOERRNO
, r
,
2503 "FastCGI: FastCgiAuthorizer \"%s\" redirected (not allowed)",
2504 dir_config
->authorizer
);
2505 goto AuthorizationFailed
;
2511 AuthorizationFailed
:
2512 if (!(dir_config
->authorizer_options
& FCGI_AUTHORITATIVE
))
2515 /* @@@ Probably should support custom_responses */
2516 ap_note_basic_auth_failure(r
);
2517 ap_log_rerror(FCGI_LOG_ERR_NOERRNO
, r
,
2518 "FastCGI: authorization failed for user \"%s\": %s", r
->connection
->user
, r
->uri
);
2519 return (res
== OK
) ? AUTH_REQUIRED
: res
;
2522 static int check_access(request_rec
*r
)
2524 int res
, access_allowed
= 0;
2526 const fcgi_dir_config
* const dir_config
=
2527 (fcgi_dir_config
*)ap_get_module_config(r
->per_dir_config
, &fastcgi_module
);
2529 if (dir_config
== NULL
|| dir_config
->access_checker
== NULL
)
2532 if ((fr
= create_fcgi_request(r
, dir_config
->access_checker
)) == NULL
)
2533 return SERVER_ERROR
;
2535 /* Save the existing subprocess_env, because we're gonna muddy it up */
2536 fr
->saved_subprocess_env
= ap_copy_table(r
->pool
, r
->subprocess_env
);
2538 ap_table_setn(r
->subprocess_env
, "FCGI_APACHE_ROLE", "ACCESS_CHECKER");
2540 /* The FastCGI Protocol doesn't differentiate access control */
2541 fr
->role
= FCGI_AUTHORIZER
;
2543 /* Do we need compatibility mode? */
2544 fr
->auth_compat
= (dir_config
->authenticator_options
& FCGI_COMPAT
);
2546 if ((res
= do_work(r
, fr
)) != OK
)
2549 access_allowed
= (r
->status
== 200);
2550 post_process_auth(fr
, access_allowed
);
2552 /* A redirect shouldn't be allowed during the access check phase */
2553 if (ap_table_get(r
->headers_out
, "Location") != NULL
) {
2554 ap_log_rerror(FCGI_LOG_ERR_NOERRNO
, r
,
2555 "FastCGI: FastCgiAccessChecker \"%s\" redirected (not allowed)",
2556 dir_config
->access_checker
);
2564 if (!(dir_config
->access_checker_options
& FCGI_AUTHORITATIVE
))
2567 /* @@@ Probably should support custom_responses */
2568 ap_log_rerror(FCGI_LOG_ERR_NOERRNO
, r
, "FastCGI: access denied: %s", r
->uri
);
2569 return (res
== OK
) ? FORBIDDEN
: res
;
2572 command_rec fastcgi_cmds
[] = {
2573 { "AppClass", fcgi_config_new_static_server
, NULL
, RSRC_CONF
, RAW_ARGS
, NULL
},
2574 { "FastCgiServer", fcgi_config_new_static_server
, NULL
, RSRC_CONF
, RAW_ARGS
, NULL
},
2576 { "ExternalAppClass", fcgi_config_new_external_server
, NULL
, RSRC_CONF
, RAW_ARGS
, NULL
},
2577 { "FastCgiExternalServer", fcgi_config_new_external_server
, NULL
, RSRC_CONF
, RAW_ARGS
, NULL
},
2579 { "FastCgiIpcDir", fcgi_config_set_socket_dir
, NULL
, RSRC_CONF
, TAKE1
, NULL
},
2581 { "FastCgiSuexec", fcgi_config_set_wrapper
, NULL
, RSRC_CONF
, TAKE1
, NULL
},
2582 { "FastCgiWrapper", fcgi_config_set_wrapper
, NULL
, RSRC_CONF
, TAKE1
, NULL
},
2584 { "FCGIConfig", fcgi_config_set_config
, NULL
, RSRC_CONF
, RAW_ARGS
, NULL
},
2585 { "FastCgiConfig", fcgi_config_set_config
, NULL
, RSRC_CONF
, RAW_ARGS
, NULL
},
2587 { "FastCgiAuthenticator", fcgi_config_new_auth_server
,
2588 (void *)FCGI_AUTH_TYPE_AUTHENTICATOR
, ACCESS_CONF
, TAKE12
,
2589 "a fastcgi-script path (absolute or relative to ServerRoot) followed by an optional -compat" },
2590 { "FastCgiAuthenticatorAuthoritative", fcgi_config_set_authoritative_slot
,
2591 (void *)XtOffsetOf(fcgi_dir_config
, authenticator_options
), ACCESS_CONF
, FLAG
,
2592 "Set to 'off' to allow authentication to be passed along to lower modules upon failure" },
2594 { "FastCgiAuthorizer", fcgi_config_new_auth_server
,
2595 (void *)FCGI_AUTH_TYPE_AUTHORIZER
, ACCESS_CONF
, TAKE12
,
2596 "a fastcgi-script path (absolute or relative to ServerRoot) followed by an optional -compat" },
2597 { "FastCgiAuthorizerAuthoritative", fcgi_config_set_authoritative_slot
,
2598 (void *)XtOffsetOf(fcgi_dir_config
, authorizer_options
), ACCESS_CONF
, FLAG
,
2599 "Set to 'off' to allow authorization to be passed along to lower modules upon failure" },
2601 { "FastCgiAccessChecker", fcgi_config_new_auth_server
,
2602 (void *)FCGI_AUTH_TYPE_ACCESS_CHECKER
, ACCESS_CONF
, TAKE12
,
2603 "a fastcgi-script path (absolute or relative to ServerRoot) followed by an optional -compat" },
2604 { "FastCgiAccessCheckerAuthoritative", fcgi_config_set_authoritative_slot
,
2605 (void *)XtOffsetOf(fcgi_dir_config
, access_checker_options
), ACCESS_CONF
, FLAG
,
2606 "Set to 'off' to allow access control to be passed along to lower modules upon failure" },
2611 handler_rec fastcgi_handlers
[] = {
2612 { FCGI_MAGIC_TYPE
, content_handler
},
2613 { "fastcgi-script", content_handler
},
2618 module MODULE_VAR_EXPORT fastcgi_module
= {
2619 STANDARD_MODULE_STUFF
,
2620 init_module
, /* initializer */
2621 fcgi_config_create_dir_config
, /* per-dir config creator */
2622 NULL
, /* per-dir config merger (default: override) */
2623 NULL
, /* per-server config creator */
2624 NULL
, /* per-server config merger (default: override) */
2625 fastcgi_cmds
, /* command table */
2626 fastcgi_handlers
, /* [9] content handlers */
2627 NULL
, /* [2] URI-to-filename translation */
2628 check_user_authentication
, /* [5] authenticate user_id */
2629 check_user_authorization
, /* [6] authorize user_id */
2630 check_access
, /* [4] check access (based on src & http headers) */
2631 NULL
, /* [7] check/set MIME type */
2632 NULL
, /* [8] fixups */
2633 NULL
, /* [10] logger */
2634 NULL
, /* [3] header-parser */
2635 fcgi_child_init
, /* process initialization */
2636 fcgi_child_exit
, /* process exit/cleanup */
2637 NULL
/* [1] post read-request handling */