4 * Apache server module for FastCGI.
6 * $Id: mod_fastcgi.c,v 1.136 2002/07/29 00:07:28 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 *----------------------------------------------------------------------
244 static apcb_t
init_module(apr_pool_t
* p
, apr_pool_t
* plog
,
245 apr_pool_t
* tp
, server_rec
* s
)
247 static apcb_t
init_module(server_rec
*s
, pool
*p
)
252 /* Register to reset to default values when the config pool is cleaned */
254 ap_register_cleanup(p
, NULL
, fcgi_config_reset_globals
, ap_null_cleanup
);
258 ap_add_version_component(p
, "mod_fastcgi/" MOD_FASTCGI_VERSION
);
260 ap_add_version_component("mod_fastcgi/" MOD_FASTCGI_VERSION
);
263 fcgi_config_set_fcgi_uid_n_gid(1);
265 /* keep these handy */
266 fcgi_config_pool
= p
;
267 fcgi_apache_main_server
= s
;
270 /* Create Unix/Domain socket directory */
271 if ((err
= fcgi_config_make_dir(p
, fcgi_socket_dir
)))
272 ap_log_error(FCGI_LOG_ERR
, s
, "FastCGI: %s", err
);
275 /* Create Dynamic directory */
276 if ((err
= fcgi_config_make_dynamic_dir(p
, 1)))
277 ap_log_error(FCGI_LOG_ERR
, s
, "FastCGI: %s", err
);
280 /* Spawn the PM only once. Under Unix, Apache calls init() routines
281 * twice, once before detach() and once after. Win32 doesn't detach.
282 * Under DSO, DSO modules are unloaded between the two init() calls.
283 * Under Unix, the -X switch causes two calls to init() but no detach
284 * (but all subprocesses are wacked so the PM is toasted anyway)! */
287 if (ap_standalone
&& ap_restart_time
== 0)
291 /* Create the pipe for comm with the PM */
292 if (pipe(fcgi_pm_pipe
) < 0) {
293 ap_log_error(FCGI_LOG_ERR
, s
, "FastCGI: pipe() failed");
296 /* Start the Process Manager */
300 apr_proc_t
* proc
= apr_palloc(p
, sizeof(*proc
));
303 rv
= apr_proc_fork(proc
, tp
);
305 if (rv
== APR_INCHILD
)
311 else if (rv
!= APR_INPARENT
)
318 apr_pool_note_subprocess(p
, proc
, APR_KILL_ONLY_ONCE
);
322 fcgi_pm_pid
= ap_spawn_child(p
, fcgi_pm_main
, NULL
, kill_only_once
, NULL
, NULL
, NULL
);
323 if (fcgi_pm_pid
<= 0) {
324 ap_log_error(FCGI_LOG_ALERT
, s
,
325 "FastCGI: can't start the process manager, spawn_child() failed");
328 #endif /* !APACHE2 */
330 close(fcgi_pm_pipe
[0]);
338 static apcb_t
fcgi_child_exit(void * dc
)
340 static apcb_t
fcgi_child_exit(server_rec
*dc0
, pool
*dc1
)
344 /* Signal the PM thread to exit*/
345 SetEvent(fcgi_event_handles
[TERM_EVENT
]);
347 /* Waiting on pm thread to exit */
348 WaitForSingleObject(fcgi_pm_thread
, INFINITE
);
355 static void fcgi_child_init(apr_pool_t
* p
, server_rec
* dc
)
357 static void fcgi_child_init(server_rec
*dc
, pool
*p
)
361 /* Create the MBOX, TERM, and WAKE event handlers */
362 fcgi_event_handles
[0] = CreateEvent(NULL
, FALSE
, FALSE
, NULL
);
363 if (fcgi_event_handles
[0] == NULL
) {
364 ap_log_error(FCGI_LOG_ALERT
, fcgi_apache_main_server
,
365 "FastCGI: CreateEvent() failed");
367 fcgi_event_handles
[1] = CreateEvent(NULL
, FALSE
, FALSE
, NULL
);
368 if (fcgi_event_handles
[1] == NULL
) {
369 ap_log_error(FCGI_LOG_ALERT
, fcgi_apache_main_server
,
370 "FastCGI: CreateEvent() failed");
372 fcgi_event_handles
[2] = CreateEvent(NULL
, FALSE
, FALSE
, NULL
);
373 if (fcgi_event_handles
[2] == NULL
) {
374 ap_log_error(FCGI_LOG_ALERT
, fcgi_apache_main_server
,
375 "FastCGI: CreateEvent() failed");
378 /* Create the mbox mutex (PM - request threads) */
379 fcgi_dynamic_mbox_mutex
= CreateMutex(NULL
, FALSE
, NULL
);
380 if (fcgi_dynamic_mbox_mutex
== NULL
) {
381 ap_log_error(FCGI_LOG_ALERT
, fcgi_apache_main_server
,
382 "FastCGI: CreateMutex() failed");
385 /* Spawn of the process manager thread */
386 fcgi_pm_thread
= (HANDLE
) _beginthread(fcgi_pm_main
, 0, NULL
);
387 if (fcgi_pm_thread
== (HANDLE
) -1) {
388 ap_log_error(FCGI_LOG_ALERT
, fcgi_apache_main_server
,
389 "_beginthread() failed to spawn the process manager");
393 apr_pool_cleanup_register(p
, NULL
, fcgi_child_exit
, fcgi_child_exit
);
399 *----------------------------------------------------------------------
403 * Terminate a line: scan to the next newline, scan back to the
404 * first non-space character and store a terminating zero. Return
405 * the next character past the end of the newline.
407 * If the end of the string is reached, ASSERT!
409 * If the FIRST character(s) in the line are '\n' or "\r\n", the
410 * first character is replaced with a NULL and next character
411 * past the newline is returned. NOTE: this condition supercedes
412 * the processing of RFC-822 continuation lines.
414 * If continuation is set to 'TRUE', then it parses a (possible)
415 * sequence of RFC-822 continuation lines.
421 * Termination byte stored in string.
423 *----------------------------------------------------------------------
425 static char *get_header_line(char *start
, int continuation
)
430 if(p
[0] == '\r' && p
[1] == '\n') { /* If EOL in 1st 2 chars */
431 p
++; /* point to \n and stop */
432 } else if(*p
!= '\n') {
435 if(*p
== '\n' && p
[1] != ' ' && p
[1] != '\t')
440 while(*p
!= '\0' && *p
!= '\n') {
446 ap_assert(*p
!= '\0');
451 * Trim any trailing whitespace.
453 while(isspace((unsigned char)p
[-1]) && p
> start
) {
462 *----------------------------------------------------------------------
466 * Call with r->parseHeader == SCAN_CGI_READING_HEADERS
467 * and initial script output in fr->header.
469 * If the initial script output does not include the header
470 * terminator ("\r\n\r\n") process_headers returns with no side
471 * effects, to be called again when more script output
472 * has been appended to fr->header.
474 * If the initial script output includes the header terminator,
475 * process_headers parses the headers and determines whether or
476 * not the remaining script output will be sent to the client.
477 * If so, process_headers sends the HTTP response headers to the
478 * client and copies any non-header script output to the output
485 * May set r->parseHeader to:
486 * SCAN_CGI_FINISHED -- headers parsed, returning script response
487 * SCAN_CGI_BAD_HEADER -- malformed header from script
488 * SCAN_CGI_INT_REDIRECT -- handler should perform internal redirect
489 * SCAN_CGI_SRV_REDIRECT -- handler should return REDIRECT
491 *----------------------------------------------------------------------
494 static const char *process_headers(request_rec
*r
, fcgi_request
*fr
)
496 char *p
, *next
, *name
, *value
;
498 int hasContentType
, hasStatus
, hasLocation
;
500 ap_assert(fr
->parseHeader
== SCAN_CGI_READING_HEADERS
);
502 if (fr
->header
== NULL
)
506 * Do we have the entire header? Scan for the blank line that
507 * terminates the header.
509 p
= (char *)fr
->header
->elts
;
510 len
= fr
->header
->nelts
;
512 while(len
-- && flag
< 2) {
522 name
= "Invalid Character";
532 /* Return (to be called later when we have more data)
533 * if we don't have an entire header. */
538 * Parse all the headers.
540 fr
->parseHeader
= SCAN_CGI_FINISHED
;
541 hasContentType
= hasStatus
= hasLocation
= FALSE
;
542 next
= (char *)fr
->header
->elts
;
544 next
= get_header_line(name
= next
, TRUE
);
548 if ((p
= strchr(name
, ':')) == NULL
) {
552 while (p
!= name
&& isspace((unsigned char)*(p
- 1))) {
559 if (strpbrk(name
, " \t") != NULL
) {
563 while (isspace((unsigned char)*value
)) {
567 if (strcasecmp(name
, "Status") == 0) {
568 int statusValue
= strtol(value
, NULL
, 10);
571 goto DuplicateNotAllowed
;
573 if (statusValue
< 0) {
574 fr
->parseHeader
= SCAN_CGI_BAD_HEADER
;
575 return ap_psprintf(r
->pool
, "invalid Status '%s'", value
);
578 r
->status
= statusValue
;
579 r
->status_line
= ap_pstrdup(r
->pool
, value
);
583 if (fr
->role
== FCGI_RESPONDER
) {
584 if (strcasecmp(name
, "Content-type") == 0) {
585 if (hasContentType
) {
586 goto DuplicateNotAllowed
;
588 hasContentType
= TRUE
;
589 r
->content_type
= ap_pstrdup(r
->pool
, value
);
593 if (strcasecmp(name
, "Location") == 0) {
595 goto DuplicateNotAllowed
;
598 ap_table_set(r
->headers_out
, "Location", value
);
602 /* If the script wants them merged, it can do it */
603 ap_table_add(r
->err_headers_out
, name
, value
);
607 ap_table_add(fr
->authHeaders
, name
, value
);
611 if (fr
->role
!= FCGI_RESPONDER
)
615 * Who responds, this handler or Apache?
618 const char *location
= ap_table_get(r
->headers_out
, "Location");
620 * Based on internal redirect handling in mod_cgi.c...
622 * If a script wants to produce its own Redirect
623 * body, it now has to explicitly *say* "Status: 302"
625 if (r
->status
== 200) {
626 if(location
[0] == '/') {
628 * Location is an relative path. This handler will
629 * consume all script output, then have Apache perform an
632 fr
->parseHeader
= SCAN_CGI_INT_REDIRECT
;
636 * Location is an absolute URL. If the script didn't
637 * produce a Content-type header, this handler will
638 * consume all script output and then have Apache generate
639 * its standard redirect response. Otherwise this handler
640 * will transmit the script's response.
642 fr
->parseHeader
= SCAN_CGI_SRV_REDIRECT
;
648 * We're responding. Send headers, buffer excess script output.
650 ap_send_http_header(r
);
652 /* We need to reinstate our timeout, send_http_header() kill()s it */
653 ap_hard_timeout("FastCGI request processing", r
);
658 len
= fr
->header
->nelts
- (next
- fr
->header
->elts
);
660 ap_assert(BufferLength(fr
->clientOutputBuffer
) == 0);
661 if (BufferFree(fr
->clientOutputBuffer
) < len
) {
662 fr
->clientOutputBuffer
= fcgi_buf_new(r
->pool
, len
);
664 ap_assert(BufferFree(fr
->clientOutputBuffer
) >= len
);
666 int sent
= fcgi_buf_add_block(fr
->clientOutputBuffer
, next
, len
);
667 ap_assert(sent
== len
);
672 /* Log first line of a multi-line header */
673 if ((p
= strpbrk(name
, "\r\n")) != NULL
)
675 fr
->parseHeader
= SCAN_CGI_BAD_HEADER
;
676 return ap_psprintf(r
->pool
, "malformed header '%s'", name
);
679 fr
->parseHeader
= SCAN_CGI_BAD_HEADER
;
680 return ap_psprintf(r
->pool
, "duplicate header '%s'", name
);
684 * Read from the client filling both the FastCGI server buffer and the
685 * client buffer with the hopes of buffering the client data before
686 * making the connect() to the FastCGI server. This prevents slow
687 * clients from keeping the FastCGI server in processing longer than is
690 static int read_from_client_n_queue(fcgi_request
*fr
)
696 while (BufferFree(fr
->clientInputBuffer
) > 0 || BufferFree(fr
->serverOutputBuffer
) > 0) {
697 fcgi_protocol_queue_client_buffer(fr
);
699 if (fr
->expectingClientContent
<= 0)
702 fcgi_buf_get_free_block_info(fr
->clientInputBuffer
, &end
, &count
);
706 if ((countRead
= ap_get_client_block(fr
->r
, end
, count
)) < 0)
709 if (countRead
== 0) {
710 fr
->expectingClientContent
= 0;
713 fcgi_buf_add_update(fr
->clientInputBuffer
, countRead
);
714 ap_reset_timeout(fr
->r
);
720 static int write_to_client(fcgi_request
*fr
)
727 apr_bucket_brigade
* bde
;
728 apr_bucket_alloc_t
* const bkt_alloc
= fr
->r
->connection
->bucket_alloc
;
731 fcgi_buf_get_block_info(fr
->clientOutputBuffer
, &begin
, &count
);
735 /* If fewer than count bytes are written, an error occured.
736 * ap_bwrite() typically forces a flushed write to the client, this
737 * effectively results in a block (and short packets) - it should
738 * be fixed, but I didn't win much support for the idea on new-httpd.
739 * So, without patching Apache, the best way to deal with this is
740 * to size the fcgi_bufs to hold all of the script output (within
741 * reason) so the script can be released from having to wait around
742 * for the transmission to the client to complete. */
746 bde
= apr_brigade_create(fr
->r
->pool
, bkt_alloc
);
747 bkt
= apr_bucket_transient_create(begin
, count
, bkt_alloc
);
748 APR_BRIGADE_INSERT_TAIL(bde
, bkt
);
750 if (fr
->fs
? fr
->fs
->flush
: dynamicFlush
)
752 bkt
= apr_bucket_flush_create(bkt_alloc
);
753 APR_BRIGADE_INSERT_TAIL(bde
, bkt
);
756 rv
= ap_pass_brigade(fr
->r
->output_filters
, bde
);
758 #elif defined(RUSSIAN_APACHE)
760 rv
= (ap_rwrite(begin
, count
, fr
->r
) != count
);
764 rv
= (ap_bwrite(fr
->r
->connection
->client
, begin
, count
) != count
);
770 ap_log_rerror(FCGI_LOG_INFO_NOERRNO
, fr
->r
,
771 "FastCGI: client stopped connection before send body completed");
777 ap_reset_timeout(fr
->r
);
779 /* Don't bother with a wrapped buffer, limiting exposure to slow
780 * clients. The BUFF routines don't allow a writev from above,
781 * and don't always memcpy to minimize small write()s, this should
782 * be fixed, but I didn't win much support for the idea on
783 * new-httpd - I'll have to _prove_ its a problem first.. */
785 /* The default behaviour used to be to flush with every write, but this
786 * can tie up the FastCGI server longer than is necessary so its an option now */
788 if (fr
->fs
? fr
->fs
->flush
: dynamicFlush
)
790 #ifdef RUSSIAN_APACHE
791 rv
= ap_rflush(fr
->r
);
793 rv
= ap_bflush(fr
->r
->connection
->client
);
798 ap_log_rerror(FCGI_LOG_INFO_NOERRNO
, fr
->r
,
799 "FastCGI: client stopped connection before send body completed");
803 ap_reset_timeout(fr
->r
);
806 #endif /* !APACHE2 */
808 fcgi_buf_toss(fr
->clientOutputBuffer
, count
);
812 /*******************************************************************************
813 * Determine the user and group the wrapper should be called with.
814 * Based on code in Apache's create_argv_cmd() (util_script.c).
816 static void set_uid_n_gid(request_rec
*r
, const char **user
, const char **group
)
818 if (fcgi_wrapper
== NULL
) {
824 if (strncmp("/~", r
->uri
, 2) == 0) {
825 /* its a user dir uri, just send the ~user, and leave it to the PM */
826 char *end
= strchr(r
->uri
+ 2, '/');
829 *user
= memcpy(ap_pcalloc(r
->pool
, end
- r
->uri
), r
->uri
+ 1, end
- r
->uri
- 1);
831 *user
= ap_pstrdup(r
->pool
, r
->uri
+ 1);
835 *user
= ap_psprintf(r
->pool
, "%ld", (long) fcgi_util_get_server_uid(r
->server
));
836 *group
= ap_psprintf(r
->pool
, "%ld", (long) fcgi_util_get_server_gid(r
->server
));
840 static void send_request_complete(fcgi_request
*fr
)
842 if (fr
->completeTime
.tv_sec
)
844 struct timeval qtime
, rtime
;
846 timersub(&fr
->queueTime
, &fr
->startTime
, &qtime
);
847 timersub(&fr
->completeTime
, &fr
->queueTime
, &rtime
);
849 send_to_pm(FCGI_REQUEST_COMPLETE_JOB
, fr
->fs_path
,
851 qtime
.tv_sec
* 1000000 + qtime
.tv_usec
,
852 rtime
.tv_sec
* 1000000 + rtime
.tv_usec
);
858 static int set_nonblocking(const fcgi_request
* fr
, int nonblocking
)
860 if (fr
->using_npipe_io
)
864 DWORD mode
= PIPE_NOWAIT
| PIPE_READMODE_BYTE
;
865 if (SetNamedPipeHandleState((HANDLE
) fr
->fd
, &mode
, NULL
, NULL
) == 0)
867 ap_log_rerror(FCGI_LOG_ERR
, fr
->r
,
868 "FastCGI: SetNamedPipeHandleState() failed");
875 unsigned long ioctl_arg
= (nonblocking
) ? 1 : 0;
876 if (ioctlsocket(fr
->fd
, FIONBIO
, &ioctl_arg
) != 0)
878 errno
= WSAGetLastError();
879 ap_log_rerror(FCGI_LOG_ERR_ERRNO
, fr
->r
,
880 "FastCGI: ioctlsocket() failed");
890 static int set_nonblocking(const fcgi_request
* fr
, int nonblocking
)
893 int fd_flags
= fcntl(fr
->fd
, F_GETFL
, 0);
895 if (fd_flags
< 0) return -1;
897 #if defined(O_NONBLOCK)
898 nb_flag
= O_NONBLOCK
;
899 #elif defined(O_NDELAY)
901 #elif defined(FNDELAY)
904 #error "TODO - don't read from app until all data from client is posted."
907 fd_flags
= (nonblocking
) ? (fd_flags
| nb_flag
) : (fd_flags
& ~nb_flag
);
909 return fcntl(fr
->fd
, F_SETFL
, fd_flags
);
914 /*******************************************************************************
915 * Close the connection to the FastCGI server. This is normally called by
916 * do_work(), but may also be called as in request pool cleanup.
918 static void close_connection_to_fs(fcgi_request
*fr
)
922 if (fr
->fd
!= INVALID_SOCKET
)
924 set_nonblocking(fr
, FALSE
);
926 if (fr
->using_npipe_io
)
928 CloseHandle((HANDLE
) fr
->fd
);
932 /* abort the connection entirely */
933 struct linger linger
= {0, 0};
934 setsockopt(fr
->fd
, SOL_SOCKET
, SO_LINGER
, (void *) &linger
, sizeof(linger
));
938 fr
->fd
= INVALID_SOCKET
;
944 struct linger linger
= {0, 0};
945 set_nonblocking(fr
, FALSE
);
946 /* abort the connection entirely */
947 setsockopt(fr
->fd
, SOL_SOCKET
, SO_LINGER
, &linger
, sizeof(linger
));
953 if (fr
->dynamic
&& fr
->keepReadingFromFcgiApp
== FALSE
)
955 /* XXX FCGI_REQUEST_COMPLETE_JOB is only sent for requests which complete
956 * normally WRT the fcgi app. There is no data sent for
957 * connect() timeouts or requests which complete abnormally.
958 * KillDynamicProcs() and RemoveRecords() need to be looked at
959 * to be sure they can reasonably handle these cases before
960 * sending these sort of stats - theres some funk in there.
962 if (fcgi_util_ticks(&fr
->completeTime
) < 0)
964 /* there's no point to aborting the request, just log it */
965 ap_log_error(FCGI_LOG_ERR
, fr
->r
->server
, "FastCGI: can't get time of day");
971 /*******************************************************************************
972 * Connect to the FastCGI server.
974 static int open_connection_to_fs(fcgi_request
*fr
)
977 fd_set write_fds
, read_fds
;
979 request_rec
* const r
= fr
->r
;
980 pool
* const rp
= r
->pool
;
981 const char *socket_path
= NULL
;
982 struct sockaddr
*socket_addr
= NULL
;
983 int socket_addr_len
= 0;
985 const char *err
= NULL
;
988 /* Create the connection point */
991 socket_path
= fcgi_util_socket_hash_filename(rp
, fr
->fs_path
, fr
->user
, fr
->group
);
992 socket_path
= fcgi_util_socket_make_path_absolute(rp
, socket_path
, 1);
995 err
= fcgi_util_socket_make_domain_addr(rp
, (struct sockaddr_un
**)&socket_addr
,
996 &socket_addr_len
, socket_path
);
998 ap_log_rerror(FCGI_LOG_ERR
, r
,
999 "FastCGI: failed to connect to server \"%s\": "
1000 "%s", fr
->fs_path
, err
);
1008 if (fr
->fs
->dest_addr
!= NULL
) {
1009 socket_addr
= fr
->fs
->dest_addr
;
1011 else if (fr
->fs
->socket_addr
) {
1012 socket_addr
= fr
->fs
->socket_addr
;
1015 socket_path
= fr
->fs
->socket_path
;
1018 socket_addr
= fr
->fs
->socket_addr
;
1020 socket_addr_len
= fr
->fs
->socket_addr_len
;
1026 if (fr
->fs
&& fr
->fs
->restartTime
)
1028 struct stat sock_stat
;
1030 if (stat(socket_path
, &sock_stat
) == 0)
1034 if (dynamicAutoUpdate
)
1036 struct stat app_stat
;
1038 /* TODO: follow sym links */
1040 if (stat(fr
->fs_path
, &app_stat
) == 0)
1043 if (fr
->fs
->startTime
< app_stat
.st_mtime
)
1045 if (sock_stat
.st_mtime
< app_stat
.st_mtime
)
1049 struct timeval tv
= {1, 0};
1052 * There's a newer one, request a restart.
1054 send_to_pm(FCGI_SERVER_RESTART_JOB
, fr
->fs_path
, fr
->user
, fr
->group
, 0, 0);
1059 /* Avoid sleep/alarm interactions */
1060 ap_select(0, NULL
, NULL
, NULL
, &tv
);
1068 send_to_pm(FCGI_SERVER_START_JOB
, fr
->fs_path
, fr
->user
, fr
->group
, 0, 0);
1070 /* Wait until it looks like its running */
1077 fr
->fs
= fcgi_util_fs_get_by_id(fr
->fs_path
, 0, 0);
1079 if (fr
->fs
&& fr
->fs
->restartTime
)
1081 struct timeval tv
= {1, 0};
1083 /* Avoid sleep/alarm interactions */
1084 ap_select(0, NULL
, NULL
, NULL
, &tv
);
1086 if (stat(socket_path
, &sock_stat
) == 0)
1101 HANDLE wait_npipe_mutex
;
1103 DWORD max_connect_time
= FCGI_NAMED_PIPE_CONNECT_TIMEOUT
;
1105 fr
->using_npipe_io
= TRUE
;
1109 interval
= dynamicPleaseStartDelay
* 1000;
1111 if (dynamicAppConnectTimeout
) {
1112 max_connect_time
= dynamicAppConnectTimeout
;
1117 interval
= FCGI_NAMED_PIPE_CONNECT_TIMEOUT
* 1000;
1119 if (fr
->fs
->appConnectTimeout
) {
1120 max_connect_time
= fr
->fs
->appConnectTimeout
;
1124 fcgi_util_ticks(&fr
->startTime
);
1127 // xxx this handle should live somewhere (see CloseHandle()s below too)
1128 char * wait_npipe_mutex_name
, * cp
;
1129 wait_npipe_mutex_name
= cp
= ap_pstrdup(rp
, socket_path
);
1130 while ((cp
= strchr(cp
, '\\'))) *cp
= '/';
1132 wait_npipe_mutex
= CreateMutex(NULL
, FALSE
, wait_npipe_mutex_name
);
1135 if (wait_npipe_mutex
== NULL
)
1137 ap_log_rerror(FCGI_LOG_ERR
, r
,
1138 "FastCGI: failed to connect to server \"%s\": "
1139 "can't create the WaitNamedPipe mutex", fr
->fs_path
);
1143 SetLastError(ERROR_SUCCESS
);
1145 rv
= WaitForSingleObject(wait_npipe_mutex
, max_connect_time
* 1000);
1147 if (rv
== WAIT_TIMEOUT
|| rv
== WAIT_FAILED
)
1151 send_to_pm(FCGI_REQUEST_TIMEOUT_JOB
, fr
->fs_path
, fr
->user
, fr
->group
, 0, 0);
1153 ap_log_rerror(FCGI_LOG_ERR_NOERRNO
, r
,
1154 "FastCGI: failed to connect to server \"%s\": "
1155 "wait for a npipe instance failed", fr
->fs_path
);
1156 FCGIDBG3("interval=%d, max_connect_time=%d", interval
, max_connect_time
);
1157 CloseHandle(wait_npipe_mutex
);
1161 fcgi_util_ticks(&fr
->queueTime
);
1163 connect_time
= fr
->queueTime
.tv_sec
- fr
->startTime
.tv_sec
;
1167 if (connect_time
>= interval
)
1169 send_to_pm(FCGI_REQUEST_TIMEOUT_JOB
, fr
->fs_path
, fr
->user
, fr
->group
, 0, 0);
1170 FCGIDBG4("connect_time=%d, interval=%d, max_connect_time=%d", connect_time
, interval
, max_connect_time
);
1172 if (max_connect_time
- connect_time
< interval
)
1174 interval
= max_connect_time
- connect_time
;
1179 interval
-= connect_time
* 1000;
1184 ready
= WaitNamedPipe(socket_path
, interval
);
1188 fr
->fd
= (SOCKET
) CreateFile(socket_path
,
1189 GENERIC_READ
| GENERIC_WRITE
,
1190 FILE_SHARE_READ
| FILE_SHARE_WRITE
,
1191 NULL
, // no security attributes
1192 OPEN_EXISTING
, // opens existing pipe
1193 FILE_FLAG_OVERLAPPED
,
1194 NULL
); // no template file
1196 if (fr
->fd
!= (SOCKET
) INVALID_HANDLE_VALUE
)
1198 ReleaseMutex(wait_npipe_mutex
);
1199 CloseHandle(wait_npipe_mutex
);
1200 fcgi_util_ticks(&fr
->queueTime
);
1201 FCGIDBG2("got npipe connect: %s", fr
->fs_path
);
1205 if (GetLastError() != ERROR_PIPE_BUSY
1206 && GetLastError() != ERROR_FILE_NOT_FOUND
)
1208 ap_log_rerror(FCGI_LOG_ERR
, r
,
1209 "FastCGI: failed to connect to server \"%s\": "
1210 "CreateFile() failed", fr
->fs_path
);
1214 FCGIDBG2("missed npipe connect: %s", fr
->fs_path
);
1219 send_to_pm(FCGI_REQUEST_TIMEOUT_JOB
, fr
->fs_path
, fr
->user
, fr
->group
, 0, 0);
1222 fcgi_util_ticks(&fr
->queueTime
);
1224 connect_time
= fr
->queueTime
.tv_sec
- fr
->startTime
.tv_sec
;
1226 FCGIDBG5("interval=%d, max_connect_time=%d, connect_time=%d, ready=%d", interval
, max_connect_time
, connect_time
, ready
);
1228 if (connect_time
>= max_connect_time
)
1230 ap_log_rerror(FCGI_LOG_ERR
, r
,
1231 "FastCGI: failed to connect to server \"%s\": "
1232 "CreateFile()/WaitNamedPipe() timed out", fr
->fs_path
);
1237 ReleaseMutex(wait_npipe_mutex
);
1238 CloseHandle(wait_npipe_mutex
);
1239 fr
->fd
= INVALID_SOCKET
;
1245 /* Create the socket */
1246 fr
->fd
= socket(socket_addr
->sa_family
, SOCK_STREAM
, 0);
1249 if (fr
->fd
== INVALID_SOCKET
) {
1250 errno
= WSAGetLastError(); // Not sure this is going to work as expected
1254 ap_log_rerror(FCGI_LOG_ERR_ERRNO
, r
,
1255 "FastCGI: failed to connect to server \"%s\": "
1256 "socket() failed", fr
->fs_path
);
1261 if (fr
->fd
>= FD_SETSIZE
) {
1262 ap_log_rerror(FCGI_LOG_ERR
, r
,
1263 "FastCGI: failed to connect to server \"%s\": "
1264 "socket file descriptor (%u) is larger than "
1265 "FD_SETSIZE (%u), you probably need to rebuild Apache with a "
1266 "larger FD_SETSIZE", fr
->fs_path
, fr
->fd
, FD_SETSIZE
);
1271 /* If appConnectTimeout is non-zero, setup do a non-blocking connect */
1272 if ((fr
->dynamic
&& dynamicAppConnectTimeout
) || (!fr
->dynamic
&& fr
->fs
->appConnectTimeout
)) {
1273 set_nonblocking(fr
, TRUE
);
1277 fcgi_util_ticks(&fr
->startTime
);
1281 if (connect(fr
->fd
, (struct sockaddr
*)socket_addr
, socket_addr_len
) == 0)
1282 goto ConnectionComplete
;
1286 errno
= WSAGetLastError();
1287 if (errno
!= WSAEWOULDBLOCK
) {
1288 ap_log_rerror(FCGI_LOG_ERR_ERRNO
, r
,
1289 "FastCGI: failed to connect to server \"%s\": "
1290 "connect() failed", fr
->fs_path
);
1296 /* ECONNREFUSED means the listen queue is full (or there isn't one).
1297 * With dynamic I can at least make sure the PM knows this is occuring */
1298 if (fr
->dynamic
&& errno
== ECONNREFUSED
) {
1299 /* @@@ This might be better as some other "kind" of message */
1300 send_to_pm(FCGI_REQUEST_TIMEOUT_JOB
, fr
->fs_path
, fr
->user
, fr
->group
, 0, 0);
1302 errno
= ECONNREFUSED
;
1305 if (errno
!= EINPROGRESS
) {
1306 ap_log_rerror(FCGI_LOG_ERR
, r
,
1307 "FastCGI: failed to connect to server \"%s\": "
1308 "connect() failed", fr
->fs_path
);
1314 /* The connect() is non-blocking */
1320 FD_ZERO(&write_fds
);
1321 FD_SET(fr
->fd
, &write_fds
);
1322 read_fds
= write_fds
;
1323 tval
.tv_sec
= dynamicPleaseStartDelay
;
1326 status
= ap_select((fr
->fd
+1), &read_fds
, &write_fds
, NULL
, &tval
);
1330 fcgi_util_ticks(&fr
->queueTime
);
1335 /* select() timed out */
1336 send_to_pm(FCGI_REQUEST_TIMEOUT_JOB
, fr
->fs_path
, fr
->user
, fr
->group
, 0, 0);
1337 } while ((fr
->queueTime
.tv_sec
- fr
->startTime
.tv_sec
) < (int)dynamicAppConnectTimeout
);
1339 /* XXX These can be moved down when dynamic vars live is a struct */
1341 ap_log_rerror(FCGI_LOG_ERR_NOERRNO
, r
,
1342 "FastCGI: failed to connect to server \"%s\": "
1343 "connect() timed out (appConnTimeout=%dsec)",
1344 fr
->fs_path
, dynamicAppConnectTimeout
);
1349 tval
.tv_sec
= fr
->fs
->appConnectTimeout
;
1351 FD_ZERO(&write_fds
);
1352 FD_SET(fr
->fd
, &write_fds
);
1353 read_fds
= write_fds
;
1355 status
= ap_select((fr
->fd
+1), &read_fds
, &write_fds
, NULL
, &tval
);
1358 ap_log_rerror(FCGI_LOG_ERR_NOERRNO
, r
,
1359 "FastCGI: failed to connect to server \"%s\": "
1360 "connect() timed out (appConnTimeout=%dsec)",
1361 fr
->fs_path
, dynamicAppConnectTimeout
);
1368 errno
= WSAGetLastError();
1370 ap_log_rerror(FCGI_LOG_ERR_ERRNO
, r
,
1371 "FastCGI: failed to connect to server \"%s\": "
1372 "select() failed", fr
->fs_path
);
1376 if (FD_ISSET(fr
->fd
, &write_fds
) || FD_ISSET(fr
->fd
, &read_fds
)) {
1378 NET_SIZE_T len
= sizeof(error
);
1380 if (getsockopt(fr
->fd
, SOL_SOCKET
, SO_ERROR
, (char *)&error
, &len
) < 0) {
1381 /* Solaris pending error */
1383 errno
= WSAGetLastError();
1385 ap_log_rerror(FCGI_LOG_ERR_ERRNO
, r
,
1386 "FastCGI: failed to connect to server \"%s\": "
1387 "select() failed (Solaris pending error)", fr
->fs_path
);
1392 /* Berkeley-derived pending error */
1394 ap_log_rerror(FCGI_LOG_ERR_ERRNO
, r
,
1395 "FastCGI: failed to connect to server \"%s\": "
1396 "select() failed (pending error)", fr
->fs_path
);
1402 errno
= WSAGetLastError();
1404 ap_log_rerror(FCGI_LOG_ERR_ERRNO
, r
,
1405 "FastCGI: failed to connect to server \"%s\": "
1406 "select() error - THIS CAN'T HAPPEN!", fr
->fs_path
);
1411 /* Return to blocking mode if it was set up */
1412 if ((fr
->dynamic
&& dynamicAppConnectTimeout
) || (!fr
->dynamic
&& fr
->fs
->appConnectTimeout
)) {
1413 set_nonblocking(fr
, FALSE
);
1417 if (socket_addr
->sa_family
== AF_INET
) {
1418 /* We shouldn't be sending small packets and there's no application
1419 * level ack of the data we send, so disable Nagle */
1421 setsockopt(fr
->fd
, IPPROTO_TCP
, TCP_NODELAY
, (char *)&set
, sizeof(set
));
1428 static void sink_client_data(fcgi_request
*fr
)
1433 fcgi_buf_reset(fr
->clientInputBuffer
);
1434 fcgi_buf_get_free_block_info(fr
->clientInputBuffer
, &base
, &size
);
1435 while (ap_get_client_block(fr
->r
, base
, size
) > 0);
1438 static apcb_t
cleanup(void *data
)
1440 fcgi_request
* const fr
= (fcgi_request
*) data
;
1442 if (fr
== NULL
) return APCB_OK
;
1444 /* its more than likely already run, but... */
1445 close_connection_to_fs(fr
);
1447 send_request_complete(fr
);
1449 if (fr
->fs_stderr_len
) {
1450 ap_log_rerror(FCGI_LOG_ERR_NOERRNO
, fr
->r
,
1451 "FastCGI: server \"%s\" stderr: %s", fr
->fs_path
, fr
->fs_stderr
);
1458 static int npipe_io(fcgi_request
* const fr
)
1460 request_rec
* const r
= fr
->r
;
1471 state
= STATE_ENV_SEND
;
1472 env_status env_status
;
1474 int dynamic_first_recv
= fr
->dynamic
;
1475 int idle_timeout
= fr
->dynamic
? dynamic_idle_timeout
: fr
->fs
->idle_timeout
;
1476 int send_pending
= 0;
1477 int recv_pending
= 0;
1478 int client_send
= 0;
1483 struct timeval timeout
;
1484 struct timeval dynamic_last_io_time
= {0, 0};
1486 pool
* const rp
= r
->pool
;
1488 DWORD recv_count
= 0;
1490 if (fr
->role
== FCGI_RESPONDER
)
1492 client_recv
= (fr
->expectingClientContent
!= 0);
1495 idle_timeout
= fr
->dynamic
? dynamic_idle_timeout
: fr
->fs
->idle_timeout
;
1497 env_status
.envp
= NULL
;
1499 events
[0] = CreateEvent(NULL
, TRUE
, FALSE
, NULL
);
1500 events
[1] = CreateEvent(NULL
, TRUE
, FALSE
, NULL
);
1501 sov
.hEvent
= events
[0];
1502 rov
.hEvent
= events
[1];
1506 dynamic_last_io_time
= fr
->startTime
;
1508 if (dynamicAppConnectTimeout
)
1510 struct timeval qwait
;
1511 timersub(&fr
->queueTime
, &fr
->startTime
, &qwait
);
1512 dynamic_first_recv
= qwait
.tv_sec
/ dynamicPleaseStartDelay
+ 1;
1516 ap_hard_timeout("FastCGI request processing", r
);
1518 while (state
!= STATE_CLIENT_SEND
)
1524 case STATE_ENV_SEND
:
1526 if (fcgi_protocol_queue_env(r
, fr
, &env_status
) == 0)
1531 state
= STATE_CLIENT_RECV
;
1535 case STATE_CLIENT_RECV
:
1537 if (read_from_client_n_queue(fr
) != OK
)
1539 state
= STATE_CLIENT_ERROR
;
1545 state
= STATE_SERVER_SEND
;
1552 case STATE_SERVER_SEND
:
1554 if (! send_pending
&& BufferLength(fr
->serverOutputBuffer
))
1556 Buffer
* b
= fr
->serverOutputBuffer
;
1559 len
= min(b
->length
, b
->data
+ b
->size
- b
->begin
);
1561 if (WriteFile((HANDLE
) fr
->fd
, b
->begin
, len
, &sent
, &sov
))
1563 fcgi_buf_removed(b
, sent
);
1564 ResetEvent(sov
.hEvent
);
1566 else if (GetLastError() == ERROR_IO_PENDING
)
1572 ap_log_rerror(FCGI_LOG_ERR
, r
, "FastCGI: comm with server "
1573 "\"%s\" aborted: WriteFile() failed", fr
->fs_path
);
1574 state
= STATE_ERROR
;
1581 case STATE_SERVER_RECV
:
1584 * Only get more data when the serverInputBuffer is empty.
1585 * Otherwise we may already have the END_REQUEST buffered
1586 * (but not processed) and a read on a closed named pipe
1587 * results in an error that is normally abnormal.
1589 if (! recv_pending
&& BufferLength(fr
->serverInputBuffer
) == 0)
1591 Buffer
* b
= fr
->serverInputBuffer
;
1594 len
= min(b
->size
- b
->length
, b
->data
+ b
->size
- b
->end
);
1596 if (ReadFile((HANDLE
) fr
->fd
, b
->end
, len
, &rcvd
, &rov
))
1598 fcgi_buf_added(b
, rcvd
);
1600 ResetEvent(rov
.hEvent
);
1601 if (dynamic_first_recv
)
1603 dynamic_first_recv
= 0;
1606 else if (GetLastError() == ERROR_IO_PENDING
)
1610 else if (GetLastError() == ERROR_HANDLE_EOF
)
1612 fr
->keepReadingFromFcgiApp
= FALSE
;
1613 state
= STATE_CLIENT_SEND
;
1614 ResetEvent(rov
.hEvent
);
1617 else if (GetLastError() == ERROR_NO_DATA
)
1623 ap_log_rerror(FCGI_LOG_ERR
, r
, "FastCGI: comm with server "
1624 "\"%s\" aborted: ReadFile() failed", fr
->fs_path
);
1625 state
= STATE_ERROR
;
1632 case STATE_CLIENT_SEND
:
1634 if (client_send
|| ! BufferFree(fr
->clientOutputBuffer
))
1636 if (write_to_client(fr
))
1638 state
= STATE_CLIENT_ERROR
;
1652 if (state
== STATE_CLIENT_ERROR
|| state
== STATE_ERROR
)
1657 /* setup the io timeout */
1659 if (BufferLength(fr
->clientOutputBuffer
))
1661 /* don't let client data sit too long, it might be a push */
1663 timeout
.tv_usec
= 100000;
1665 else if (dynamic_first_recv
)
1668 struct timeval qwait
;
1670 fcgi_util_ticks(&fr
->queueTime
);
1674 /* a send() succeeded last pass */
1675 dynamic_last_io_time
= fr
->queueTime
;
1679 /* timed out last pass */
1680 struct timeval idle_time
;
1682 timersub(&fr
->queueTime
, &dynamic_last_io_time
, &idle_time
);
1684 if (idle_time
.tv_sec
> idle_timeout
)
1686 send_to_pm(FCGI_REQUEST_TIMEOUT_JOB
, fr
->fs_path
, fr
->user
, fr
->group
, 0, 0);
1687 ap_log_rerror(FCGI_LOG_ERR_NOERRNO
, r
, "FastCGI: comm "
1688 "with (dynamic) server \"%s\" aborted: (first read) "
1689 "idle timeout (%d sec)", fr
->fs_path
, idle_timeout
);
1690 state
= STATE_ERROR
;
1695 timersub(&fr
->queueTime
, &fr
->startTime
, &qwait
);
1697 delay
= dynamic_first_recv
* dynamicPleaseStartDelay
;
1699 if (qwait
.tv_sec
< delay
)
1701 timeout
.tv_sec
= delay
;
1702 timeout
.tv_usec
= 100000; /* fudge for select() slop */
1703 timersub(&timeout
, &qwait
, &timeout
);
1707 /* Killed time somewhere.. client read? */
1708 send_to_pm(FCGI_REQUEST_TIMEOUT_JOB
, fr
->fs_path
, fr
->user
, fr
->group
, 0, 0);
1709 dynamic_first_recv
= qwait
.tv_sec
/ dynamicPleaseStartDelay
+ 1;
1710 timeout
.tv_sec
= dynamic_first_recv
* dynamicPleaseStartDelay
;
1711 timeout
.tv_usec
= 100000; /* fudge for select() slop */
1712 timersub(&timeout
, &qwait
, &timeout
);
1717 timeout
.tv_sec
= idle_timeout
;
1718 timeout
.tv_usec
= 0;
1721 /* require a pended recv otherwise the app can deadlock */
1724 msec_timeout
= timeout
.tv_sec
* 1000 + timeout
.tv_usec
/ 1000;
1726 rv
= WaitForMultipleObjects(2, events
, FALSE
, msec_timeout
);
1728 if (rv
== WAIT_TIMEOUT
)
1732 if (BufferLength(fr
->clientOutputBuffer
))
1736 else if (dynamic_first_recv
)
1738 struct timeval qwait
;
1740 fcgi_util_ticks(&fr
->queueTime
);
1741 timersub(&fr
->queueTime
, &fr
->startTime
, &qwait
);
1743 send_to_pm(FCGI_REQUEST_TIMEOUT_JOB
, fr
->fs_path
, fr
->user
, fr
->group
, 0, 0);
1745 dynamic_first_recv
= qwait
.tv_sec
/ dynamicPleaseStartDelay
+ 1;
1749 ap_log_rerror(FCGI_LOG_ERR_NOERRNO
, r
, "FastCGI: comm with "
1750 "server \"%s\" aborted: idle timeout (%d sec)",
1751 fr
->fs_path
, idle_timeout
);
1752 state
= STATE_ERROR
;
1758 int i
= rv
- WAIT_OBJECT_0
;
1766 if (GetOverlappedResult((HANDLE
) fr
->fd
, &sov
, &sent
, FALSE
))
1769 ResetEvent(sov
.hEvent
);
1770 fcgi_buf_removed(fr
->serverOutputBuffer
, sent
);
1774 ap_log_rerror(FCGI_LOG_ERR
, r
, "FastCGI: comm with server "
1775 "\"%s\" aborted: GetOverlappedResult() failed", fr
->fs_path
);
1776 state
= STATE_ERROR
;
1787 ResetEvent(rov
.hEvent
);
1789 if (GetOverlappedResult((HANDLE
) fr
->fd
, &rov
, &rcvd
, FALSE
))
1791 fcgi_buf_added(fr
->serverInputBuffer
, rcvd
);
1792 if (dynamic_first_recv
)
1794 dynamic_first_recv
= 0;
1799 ap_log_rerror(FCGI_LOG_ERR
, r
, "FastCGI: comm with server "
1800 "\"%s\" aborted: GetOverlappedResult() failed", fr
->fs_path
);
1801 state
= STATE_ERROR
;
1808 if (fcgi_protocol_dequeue(rp
, fr
))
1810 state
= STATE_ERROR
;
1814 if (fr
->parseHeader
== SCAN_CGI_READING_HEADERS
)
1816 const char * err
= process_headers(r
, fr
);
1819 ap_log_rerror(FCGI_LOG_ERR_NOERRNO
, r
,
1820 "FastCGI: comm with server \"%s\" aborted: "
1821 "error parsing headers: %s", fr
->fs_path
, err
);
1822 state
= STATE_ERROR
;
1827 if (fr
->exitStatusSet
)
1829 fr
->keepReadingFromFcgiApp
= FALSE
;
1830 state
= STATE_CLIENT_SEND
;
1835 if (! fr
->exitStatusSet
|| ! fr
->eofSent
)
1837 CancelIo((HANDLE
) fr
->fd
);
1840 CloseHandle(rov
.hEvent
);
1841 CloseHandle(sov
.hEvent
);
1843 return (state
== STATE_ERROR
);
1847 static int socket_io(fcgi_request
* const fr
)
1860 state
= STATE_ENV_SEND
;
1862 request_rec
* const r
= fr
->r
;
1864 struct timeval timeout
;
1865 struct timeval dynamic_last_io_time
= {0, 0};
1868 int nfds
= fr
->fd
+ 1;
1869 int select_status
= 1;
1872 int dynamic_first_recv
= fr
->dynamic
? 1 : 0;
1873 int client_send
= FALSE
;
1874 int client_recv
= FALSE
;
1878 if (fr
->role
== FCGI_RESPONDER
)
1880 client_recv
= (fr
->expectingClientContent
!= 0);
1883 idle_timeout
= fr
->dynamic
? dynamic_idle_timeout
: fr
->fs
->idle_timeout
;
1889 dynamic_last_io_time
= fr
->startTime
;
1891 if (dynamicAppConnectTimeout
)
1893 struct timeval qwait
;
1894 timersub(&fr
->queueTime
, &fr
->startTime
, &qwait
);
1895 dynamic_first_recv
= qwait
.tv_sec
/ dynamicPleaseStartDelay
+ 1;
1899 ap_hard_timeout("FastCGI request processing", r
);
1901 set_nonblocking(fr
, TRUE
);
1906 FD_ZERO(&write_set
);
1910 case STATE_ENV_SEND
:
1912 if (fcgi_protocol_queue_env(r
, fr
, &env
) == 0)
1917 state
= STATE_CLIENT_RECV
;
1921 case STATE_CLIENT_RECV
:
1923 if (read_from_client_n_queue(fr
))
1925 state
= STATE_CLIENT_ERROR
;
1931 state
= STATE_SERVER_SEND
;
1938 case STATE_SERVER_SEND
:
1940 if (BufferLength(fr
->serverOutputBuffer
))
1942 FD_SET(fr
->fd
, &write_set
);
1946 ap_assert(fr
->eofSent
);
1947 state
= STATE_SERVER_RECV
;
1952 case STATE_SERVER_RECV
:
1954 FD_SET(fr
->fd
, &read_set
);
1958 case STATE_CLIENT_SEND
:
1960 if (client_send
|| ! BufferFree(fr
->clientOutputBuffer
))
1962 if (write_to_client(fr
))
1964 state
= STATE_CLIENT_ERROR
;
1974 case STATE_CLIENT_ERROR
:
1983 if (state
== STATE_CLIENT_ERROR
|| state
== STATE_ERROR
)
1988 /* setup the io timeout */
1990 if (BufferLength(fr
->clientOutputBuffer
))
1992 /* don't let client data sit too long, it might be a push */
1994 timeout
.tv_usec
= 100000;
1996 else if (dynamic_first_recv
)
1999 struct timeval qwait
;
2001 fcgi_util_ticks(&fr
->queueTime
);
2005 /* a send() succeeded last pass */
2006 dynamic_last_io_time
= fr
->queueTime
;
2010 /* timed out last pass */
2011 struct timeval idle_time
;
2013 timersub(&fr
->queueTime
, &dynamic_last_io_time
, &idle_time
);
2015 if (idle_time
.tv_sec
> idle_timeout
)
2017 send_to_pm(FCGI_REQUEST_TIMEOUT_JOB
, fr
->fs_path
, fr
->user
, fr
->group
, 0, 0);
2018 ap_log_rerror(FCGI_LOG_ERR_NOERRNO
, r
, "FastCGI: comm "
2019 "with (dynamic) server \"%s\" aborted: (first read) "
2020 "idle timeout (%d sec)", fr
->fs_path
, idle_timeout
);
2021 state
= STATE_ERROR
;
2026 timersub(&fr
->queueTime
, &fr
->startTime
, &qwait
);
2028 delay
= dynamic_first_recv
* dynamicPleaseStartDelay
;
2030 FCGIDBG5("qwait=%ld.%06ld delay=%d first_recv=%d", qwait
.tv_sec
, qwait
.tv_usec
, delay
, dynamic_first_recv
);
2032 if (qwait
.tv_sec
< delay
)
2034 timeout
.tv_sec
= delay
;
2035 timeout
.tv_usec
= 100000; /* fudge for select() slop */
2036 timersub(&timeout
, &qwait
, &timeout
);
2040 /* Killed time somewhere.. client read? */
2041 send_to_pm(FCGI_REQUEST_TIMEOUT_JOB
, fr
->fs_path
, fr
->user
, fr
->group
, 0, 0);
2042 dynamic_first_recv
= qwait
.tv_sec
/ dynamicPleaseStartDelay
+ 1;
2043 timeout
.tv_sec
= dynamic_first_recv
* dynamicPleaseStartDelay
;
2044 timeout
.tv_usec
= 100000; /* fudge for select() slop */
2045 timersub(&timeout
, &qwait
, &timeout
);
2050 timeout
.tv_sec
= idle_timeout
;
2051 timeout
.tv_usec
= 0;
2054 /* wait on the socket */
2055 select_status
= ap_select(nfds
, &read_set
, &write_set
, NULL
, &timeout
);
2057 if (select_status
< 0)
2059 ap_log_rerror(FCGI_LOG_ERR_ERRNO
, r
, "FastCGI: comm with server "
2060 "\"%s\" aborted: select() failed", fr
->fs_path
);
2061 state
= STATE_ERROR
;
2065 if (select_status
== 0)
2067 /* select() timeout */
2069 if (BufferLength(fr
->clientOutputBuffer
))
2071 if (fr
->role
== FCGI_RESPONDER
)
2076 else if (dynamic_first_recv
)
2078 struct timeval qwait
;
2080 fcgi_util_ticks(&fr
->queueTime
);
2081 timersub(&fr
->queueTime
, &fr
->startTime
, &qwait
);
2083 send_to_pm(FCGI_REQUEST_TIMEOUT_JOB
, fr
->fs_path
, fr
->user
, fr
->group
, 0, 0);
2085 dynamic_first_recv
= qwait
.tv_sec
/ dynamicPleaseStartDelay
+ 1;
2090 ap_log_rerror(FCGI_LOG_ERR_NOERRNO
, r
, "FastCGI: comm with "
2091 "server \"%s\" aborted: idle timeout (%d sec)",
2092 fr
->fs_path
, idle_timeout
);
2093 state
= STATE_ERROR
;
2097 if (FD_ISSET(fr
->fd
, &write_set
))
2099 /* send to the server */
2101 rv
= fcgi_buf_socket_send(fr
->serverOutputBuffer
, fr
->fd
);
2105 ap_log_rerror(FCGI_LOG_ERR
, r
, "FastCGI: comm with server "
2106 "\"%s\" aborted: write failed", fr
->fs_path
);
2107 state
= STATE_ERROR
;
2112 if (FD_ISSET(fr
->fd
, &read_set
))
2114 /* recv from the server */
2116 if (dynamic_first_recv
)
2118 dynamic_first_recv
= 0;
2119 fcgi_util_ticks(&fr
->queueTime
);
2122 rv
= fcgi_buf_socket_recv(fr
->serverInputBuffer
, fr
->fd
);
2126 ap_log_rerror(FCGI_LOG_ERR
, r
, "FastCGI: comm with server "
2127 "\"%s\" aborted: read failed", fr
->fs_path
);
2128 state
= STATE_ERROR
;
2134 fr
->keepReadingFromFcgiApp
= FALSE
;
2135 state
= STATE_CLIENT_SEND
;
2140 if (fcgi_protocol_dequeue(rp
, fr
))
2142 state
= STATE_ERROR
;
2146 if (fr
->parseHeader
== SCAN_CGI_READING_HEADERS
)
2148 const char * err
= process_headers(r
, fr
);
2151 ap_log_rerror(FCGI_LOG_ERR_NOERRNO
, r
,
2152 "FastCGI: comm with server \"%s\" aborted: "
2153 "error parsing headers: %s", fr
->fs_path
, err
);
2154 state
= STATE_ERROR
;
2159 if (fr
->exitStatusSet
)
2161 fr
->keepReadingFromFcgiApp
= FALSE
;
2162 state
= STATE_CLIENT_SEND
;
2167 return (state
== STATE_ERROR
);
2171 /*----------------------------------------------------------------------
2172 * This is the core routine for moving data between the FastCGI
2173 * application and the Web server's client.
2175 static int do_work(request_rec
* const r
, fcgi_request
* const fr
)
2180 fcgi_protocol_queue_begin_request(fr
);
2182 if (fr
->role
== FCGI_RESPONDER
)
2184 rv
= ap_setup_client_block(r
, REQUEST_CHUNKED_ERROR
);
2191 fr
->expectingClientContent
= ap_should_client_block(r
);
2195 ap_register_cleanup(rp
, (void *)fr
, cleanup
, ap_null_cleanup
);
2196 ap_unblock_alarms();
2198 ap_hard_timeout("connect() to FastCGI server", r
);
2200 /* Connect to the FastCGI Application */
2201 if (open_connection_to_fs(fr
) != FCGI_OK
)
2204 return HTTP_INTERNAL_SERVER_ERROR
;
2208 if (fr
->using_npipe_io
)
2218 /* comm with the server is done */
2219 close_connection_to_fs(fr
);
2221 if (fr
->role
== FCGI_RESPONDER
)
2223 sink_client_data(fr
);
2226 while (rv
== 0 && BufferLength(fr
->serverInputBuffer
) || BufferLength(fr
->clientOutputBuffer
))
2228 if (fcgi_protocol_dequeue(rp
, fr
))
2230 rv
= HTTP_INTERNAL_SERVER_ERROR
;
2233 if (fr
->parseHeader
== SCAN_CGI_READING_HEADERS
)
2235 const char * err
= process_headers(r
, fr
);
2238 ap_log_rerror(FCGI_LOG_ERR_NOERRNO
, r
,
2239 "FastCGI: comm with server \"%s\" aborted: "
2240 "error parsing headers: %s", fr
->fs_path
, err
);
2241 rv
= HTTP_INTERNAL_SERVER_ERROR
;
2245 if (fr
->role
== FCGI_RESPONDER
)
2247 if (write_to_client(fr
))
2254 fcgi_buf_reset(fr
->clientOutputBuffer
);
2258 switch (fr
->parseHeader
)
2260 case SCAN_CGI_FINISHED
:
2262 if (fr
->role
== FCGI_RESPONDER
)
2264 /* RUSSIAN_APACHE requires rflush() over bflush() */
2267 ap_bgetopt(r
->connection
->client
, BO_BYTECT
, &r
->bytes_sent
);
2273 case SCAN_CGI_INT_REDIRECT
:
2274 case SCAN_CGI_SRV_REDIRECT
:
2278 case SCAN_CGI_READING_HEADERS
:
2280 ap_log_rerror(FCGI_LOG_ERR_NOERRNO
, r
, "FastCGI: incomplete headers "
2281 "(%d bytes) received from server \"%s\"", fr
->header
->nelts
, fr
->fs_path
);
2285 case SCAN_CGI_BAD_HEADER
:
2287 rv
= HTTP_INTERNAL_SERVER_ERROR
;
2293 rv
= HTTP_INTERNAL_SERVER_ERROR
;
2300 static fcgi_request
*create_fcgi_request(request_rec
* const r
, const char *fs_path
)
2302 struct stat
*my_finfo
;
2303 pool
* const p
= r
->pool
;
2305 fcgi_request
* const fr
= (fcgi_request
*)ap_pcalloc(p
, sizeof(fcgi_request
));
2311 my_finfo
= (struct stat
*)ap_palloc(p
, sizeof(struct stat
));
2312 if (stat(fs_path
, my_finfo
) < 0) {
2313 ap_log_rerror(FCGI_LOG_ERR_ERRNO
, r
,
2314 "FastCGI: stat() of \"%s\" failed", fs_path
);
2320 my_finfo
= &r
->finfo
;
2321 fs_path
= r
->filename
;
2325 fs
= fcgi_util_fs_get_by_id(fs_path
, fcgi_util_get_server_uid(r
->server
),
2326 fcgi_util_get_server_gid(r
->server
));
2328 /* Its a request for a dynamic FastCGI application */
2329 const char * const err
=
2330 fcgi_util_fs_is_path_ok(p
, fs_path
, my_finfo
);
2333 ap_log_rerror(FCGI_LOG_ERR_NOERRNO
, r
, "FastCGI: invalid (dynamic) server \"%s\": %s", fs_path
, err
);
2338 fr
->serverInputBuffer
= fcgi_buf_new(p
, SERVER_BUFSIZE
);
2339 fr
->serverOutputBuffer
= fcgi_buf_new(p
, SERVER_BUFSIZE
);
2340 fr
->clientInputBuffer
= fcgi_buf_new(p
, SERVER_BUFSIZE
);
2341 fr
->clientOutputBuffer
= fcgi_buf_new(p
, SERVER_BUFSIZE
);
2342 fr
->erBufPtr
= fcgi_buf_new(p
, sizeof(FCGI_EndRequestBody
) + 1);
2343 fr
->gotHeader
= FALSE
;
2344 fr
->parseHeader
= SCAN_CGI_READING_HEADERS
;
2345 fr
->header
= ap_make_array(p
, 1, 1);
2346 fr
->fs_stderr
= NULL
;
2348 fr
->readingEndRequestBody
= FALSE
;
2350 fr
->exitStatusSet
= FALSE
;
2351 fr
->requestId
= 1; /* anything but zero is OK here */
2352 fr
->eofSent
= FALSE
;
2353 fr
->role
= FCGI_RESPONDER
;
2354 fr
->expectingClientContent
= FALSE
;
2355 fr
->keepReadingFromFcgiApp
= TRUE
;
2357 fr
->fs_path
= fs_path
;
2358 fr
->authHeaders
= ap_make_table(p
, 10);
2360 fr
->fd
= INVALID_SOCKET
;
2361 fr
->dynamic
= ((fs
== NULL
) || (fs
->directive
== APP_CLASS_DYNAMIC
)) ? TRUE
: FALSE
;
2362 fr
->using_npipe_io
= FALSE
;
2364 fr
->dynamic
= (fs
== NULL
) ? TRUE
: FALSE
;
2368 set_uid_n_gid(r
, &fr
->user
, &fr
->group
);
2374 *----------------------------------------------------------------------
2378 * This routine gets called for a request that corresponds to
2379 * a FastCGI connection. It performs the request synchronously.
2382 * Final status of request: OK or NOT_FOUND or HTTP_INTERNAL_SERVER_ERROR.
2385 * Request performed.
2387 *----------------------------------------------------------------------
2390 /* Stolen from mod_cgi.c..
2391 * KLUDGE --- for back-combatibility, we don't have to check ExecCGI
2392 * in ScriptAliased directories, which means we need to know if this
2393 * request came through ScriptAlias or not... so the Alias module
2394 * leaves a note for us.
2396 static int apache_is_scriptaliased(request_rec
*r
)
2398 const char *t
= ap_table_get(r
->notes
, "alias-forced-type");
2399 return t
&& (!strcasecmp(t
, "cgi-script"));
2402 /* If a script wants to produce its own Redirect body, it now
2403 * has to explicitly *say* "Status: 302". If it wants to use
2404 * Apache redirects say "Status: 200". See process_headers().
2406 static int post_process_for_redirects(request_rec
* const r
,
2407 const fcgi_request
* const fr
)
2409 switch(fr
->parseHeader
) {
2410 case SCAN_CGI_INT_REDIRECT
:
2412 /* @@@ There are still differences between the handling in
2413 * mod_cgi and mod_fastcgi. This needs to be revisited.
2415 /* We already read the message body (if any), so don't allow
2416 * the redirected request to think it has one. We can ignore
2417 * Transfer-Encoding, since we used REQUEST_CHUNKED_ERROR.
2420 r
->method_number
= M_GET
;
2421 ap_table_unset(r
->headers_in
, "Content-length");
2423 ap_internal_redirect_handler(ap_table_get(r
->headers_out
, "Location"), r
);
2426 case SCAN_CGI_SRV_REDIRECT
:
2427 return HTTP_MOVED_TEMPORARILY
;
2434 /******************************************************************************
2435 * Process fastcgi-script requests. Based on mod_cgi::cgi_handler().
2437 static int content_handler(request_rec
*r
)
2439 fcgi_request
*fr
= NULL
;
2444 if (strcmp(r
->handler
, "fastcgi-script"))
2447 /* Setup a new FastCGI request */
2448 if ((fr
= create_fcgi_request(r
, r
->filename
)) == NULL
)
2449 return HTTP_INTERNAL_SERVER_ERROR
;
2453 /* Setup a new FastCGI request */
2454 if ((fr
= create_fcgi_request(r
, NULL
)) == NULL
)
2455 return HTTP_INTERNAL_SERVER_ERROR
;
2459 /* If its a dynamic invocation, make sure scripts are OK here */
2460 if (fr
->dynamic
&& !(ap_allow_options(r
) & OPT_EXECCGI
) && !apache_is_scriptaliased(r
)) {
2461 ap_log_rerror(FCGI_LOG_ERR_NOERRNO
, r
,
2462 "FastCGI: \"ExecCGI Option\" is off in this directory: %s", r
->uri
);
2463 return HTTP_INTERNAL_SERVER_ERROR
;
2466 /* Process the fastcgi-script request */
2467 if ((ret
= do_work(r
, fr
)) != OK
)
2470 /* Special case redirects */
2471 ret
= post_process_for_redirects(r
, fr
);
2477 static int post_process_auth_passed_header(table
*t
, const char *key
, const char * const val
)
2479 if (strncasecmp(key
, "Variable-", 9) == 0)
2482 ap_table_setn(t
, key
, val
);
2486 static int post_process_auth_passed_compat_header(table
*t
, const char *key
, const char * const val
)
2488 if (strncasecmp(key
, "Variable-", 9) == 0)
2489 ap_table_setn(t
, key
+ 9, val
);
2494 static int post_process_auth_failed_header(table
* const t
, const char * const key
, const char * const val
)
2496 ap_table_setn(t
, key
, val
);
2500 static void post_process_auth(fcgi_request
* const fr
, const int passed
)
2502 request_rec
* const r
= fr
->r
;
2504 /* Restore the saved subprocess_env because we muddied ours up */
2505 r
->subprocess_env
= fr
->saved_subprocess_env
;
2508 if (fr
->auth_compat
) {
2509 ap_table_do((int (*)(void *, const char *, const char *))post_process_auth_passed_compat_header
,
2510 (void *)r
->subprocess_env
, fr
->authHeaders
, NULL
);
2513 ap_table_do((int (*)(void *, const char *, const char *))post_process_auth_passed_header
,
2514 (void *)r
->subprocess_env
, fr
->authHeaders
, NULL
);
2518 ap_table_do((int (*)(void *, const char *, const char *))post_process_auth_failed_header
,
2519 (void *)r
->err_headers_out
, fr
->authHeaders
, NULL
);
2522 /* @@@ Restore these.. its a hack until I rewrite the header handling */
2523 r
->status
= HTTP_OK
;
2524 r
->status_line
= NULL
;
2527 static int check_user_authentication(request_rec
*r
)
2529 int res
, authenticated
= 0;
2530 const char *password
;
2532 const fcgi_dir_config
* const dir_config
=
2533 (const fcgi_dir_config
*)ap_get_module_config(r
->per_dir_config
, &fastcgi_module
);
2535 if (dir_config
->authenticator
== NULL
)
2538 /* Get the user password */
2539 if ((res
= ap_get_basic_auth_pw(r
, &password
)) != OK
)
2542 if ((fr
= create_fcgi_request(r
, dir_config
->authenticator
)) == NULL
)
2543 return HTTP_INTERNAL_SERVER_ERROR
;
2545 /* Save the existing subprocess_env, because we're gonna muddy it up */
2546 fr
->saved_subprocess_env
= ap_copy_table(r
->pool
, r
->subprocess_env
);
2548 ap_table_setn(r
->subprocess_env
, "REMOTE_PASSWD", password
);
2549 ap_table_setn(r
->subprocess_env
, "FCGI_APACHE_ROLE", "AUTHENTICATOR");
2551 /* The FastCGI Protocol doesn't differentiate authentication */
2552 fr
->role
= FCGI_AUTHORIZER
;
2554 /* Do we need compatibility mode? */
2555 fr
->auth_compat
= (dir_config
->authenticator_options
& FCGI_COMPAT
);
2557 if ((res
= do_work(r
, fr
)) != OK
)
2558 goto AuthenticationFailed
;
2560 authenticated
= (r
->status
== 200);
2561 post_process_auth(fr
, authenticated
);
2563 /* A redirect shouldn't be allowed during the authentication phase */
2564 if (ap_table_get(r
->headers_out
, "Location") != NULL
) {
2565 ap_log_rerror(FCGI_LOG_ERR_NOERRNO
, r
,
2566 "FastCGI: FastCgiAuthenticator \"%s\" redirected (not allowed)",
2567 dir_config
->authenticator
);
2568 goto AuthenticationFailed
;
2574 AuthenticationFailed
:
2575 if (!(dir_config
->authenticator_options
& FCGI_AUTHORITATIVE
))
2578 /* @@@ Probably should support custom_responses */
2579 ap_note_basic_auth_failure(r
);
2580 ap_log_rerror(FCGI_LOG_ERR_NOERRNO
, r
,
2581 "FastCGI: authentication failed for user \"%s\": %s",
2585 r
->connection
->user
, r
->uri
);
2588 return (res
== OK
) ? HTTP_UNAUTHORIZED
: res
;
2591 static int check_user_authorization(request_rec
*r
)
2593 int res
, authorized
= 0;
2595 const fcgi_dir_config
* const dir_config
=
2596 (const fcgi_dir_config
*)ap_get_module_config(r
->per_dir_config
, &fastcgi_module
);
2598 if (dir_config
->authorizer
== NULL
)
2601 /* @@@ We should probably honor the existing parameters to the require directive
2602 * as well as allow the definition of new ones (or use the basename of the
2603 * FastCGI server and pass the rest of the directive line), but for now keep
2606 if ((fr
= create_fcgi_request(r
, dir_config
->authorizer
)) == NULL
)
2607 return HTTP_INTERNAL_SERVER_ERROR
;
2609 /* Save the existing subprocess_env, because we're gonna muddy it up */
2610 fr
->saved_subprocess_env
= ap_copy_table(r
->pool
, r
->subprocess_env
);
2612 ap_table_setn(r
->subprocess_env
, "FCGI_APACHE_ROLE", "AUTHORIZER");
2614 fr
->role
= FCGI_AUTHORIZER
;
2616 /* Do we need compatibility mode? */
2617 fr
->auth_compat
= (dir_config
->authenticator_options
& FCGI_COMPAT
);
2619 if ((res
= do_work(r
, fr
)) != OK
)
2620 goto AuthorizationFailed
;
2622 authorized
= (r
->status
== 200);
2623 post_process_auth(fr
, authorized
);
2625 /* A redirect shouldn't be allowed during the authorization phase */
2626 if (ap_table_get(r
->headers_out
, "Location") != NULL
) {
2627 ap_log_rerror(FCGI_LOG_ERR_NOERRNO
, r
,
2628 "FastCGI: FastCgiAuthorizer \"%s\" redirected (not allowed)",
2629 dir_config
->authorizer
);
2630 goto AuthorizationFailed
;
2636 AuthorizationFailed
:
2637 if (!(dir_config
->authorizer_options
& FCGI_AUTHORITATIVE
))
2640 /* @@@ Probably should support custom_responses */
2641 ap_note_basic_auth_failure(r
);
2642 ap_log_rerror(FCGI_LOG_ERR_NOERRNO
, r
,
2643 "FastCGI: authorization failed for user \"%s\": %s",
2647 r
->connection
->user
, r
->uri
);
2650 return (res
== OK
) ? HTTP_UNAUTHORIZED
: res
;
2653 static int check_access(request_rec
*r
)
2655 int res
, access_allowed
= 0;
2657 const fcgi_dir_config
* const dir_config
=
2658 (fcgi_dir_config
*)ap_get_module_config(r
->per_dir_config
, &fastcgi_module
);
2660 if (dir_config
== NULL
|| dir_config
->access_checker
== NULL
)
2663 if ((fr
= create_fcgi_request(r
, dir_config
->access_checker
)) == NULL
)
2664 return HTTP_INTERNAL_SERVER_ERROR
;
2666 /* Save the existing subprocess_env, because we're gonna muddy it up */
2667 fr
->saved_subprocess_env
= ap_copy_table(r
->pool
, r
->subprocess_env
);
2669 ap_table_setn(r
->subprocess_env
, "FCGI_APACHE_ROLE", "ACCESS_CHECKER");
2671 /* The FastCGI Protocol doesn't differentiate access control */
2672 fr
->role
= FCGI_AUTHORIZER
;
2674 /* Do we need compatibility mode? */
2675 fr
->auth_compat
= (dir_config
->authenticator_options
& FCGI_COMPAT
);
2677 if ((res
= do_work(r
, fr
)) != OK
)
2680 access_allowed
= (r
->status
== 200);
2681 post_process_auth(fr
, access_allowed
);
2683 /* A redirect shouldn't be allowed during the access check phase */
2684 if (ap_table_get(r
->headers_out
, "Location") != NULL
) {
2685 ap_log_rerror(FCGI_LOG_ERR_NOERRNO
, r
,
2686 "FastCGI: FastCgiAccessChecker \"%s\" redirected (not allowed)",
2687 dir_config
->access_checker
);
2695 if (!(dir_config
->access_checker_options
& FCGI_AUTHORITATIVE
))
2698 /* @@@ Probably should support custom_responses */
2699 ap_log_rerror(FCGI_LOG_ERR_NOERRNO
, r
, "FastCGI: access denied: %s", r
->uri
);
2700 return (res
== OK
) ? HTTP_FORBIDDEN
: res
;
2705 # define AP_INIT_RAW_ARGS(directive, func, mconfig, where, help) \
2706 { directive, func, mconfig, where, RAW_ARGS, help }
2707 # define AP_INIT_TAKE1(directive, func, mconfig, where, help) \
2708 { directive, func, mconfig, where, TAKE1, help }
2709 # define AP_INIT_TAKE12(directive, func, mconfig, where, help) \
2710 { directive, func, mconfig, where, TAKE12, help }
2711 # define AP_INIT_FLAG(directive, func, mconfig, where, help) \
2712 { directive, func, mconfig, where, FLAG, help }
2716 static const command_rec fastcgi_cmds
[] =
2718 AP_INIT_RAW_ARGS("AppClass", fcgi_config_new_static_server
, NULL
, RSRC_CONF
, NULL
),
2719 AP_INIT_RAW_ARGS("FastCgiServer", fcgi_config_new_static_server
, NULL
, RSRC_CONF
, NULL
),
2721 AP_INIT_RAW_ARGS("ExternalAppClass", fcgi_config_new_external_server
, NULL
, RSRC_CONF
, NULL
),
2722 AP_INIT_RAW_ARGS("FastCgiExternalServer", fcgi_config_new_external_server
, NULL
, RSRC_CONF
, NULL
),
2724 AP_INIT_TAKE1("FastCgiIpcDir", fcgi_config_set_socket_dir
, NULL
, RSRC_CONF
, NULL
),
2726 AP_INIT_TAKE1("FastCgiSuexec", fcgi_config_set_wrapper
, NULL
, RSRC_CONF
, NULL
),
2727 AP_INIT_TAKE1("FastCgiWrapper", fcgi_config_set_wrapper
, NULL
, RSRC_CONF
, NULL
),
2729 AP_INIT_RAW_ARGS("FCGIConfig", fcgi_config_set_config
, NULL
, RSRC_CONF
, NULL
),
2730 AP_INIT_RAW_ARGS("FastCgiConfig", fcgi_config_set_config
, NULL
, RSRC_CONF
, NULL
),
2732 AP_INIT_TAKE12("FastCgiAuthenticator", fcgi_config_new_auth_server
,
2733 (void *)FCGI_AUTH_TYPE_AUTHENTICATOR
, ACCESS_CONF
,
2734 "a fastcgi-script path (absolute or relative to ServerRoot) followed by an optional -compat"),
2735 AP_INIT_FLAG("FastCgiAuthenticatorAuthoritative", fcgi_config_set_authoritative_slot
,
2736 (void *)XtOffsetOf(fcgi_dir_config
, authenticator_options
), ACCESS_CONF
,
2737 "Set to 'off' to allow authentication to be passed along to lower modules upon failure"),
2739 AP_INIT_TAKE12("FastCgiAuthorizer", fcgi_config_new_auth_server
,
2740 (void *)FCGI_AUTH_TYPE_AUTHORIZER
, ACCESS_CONF
,
2741 "a fastcgi-script path (absolute or relative to ServerRoot) followed by an optional -compat"),
2742 AP_INIT_FLAG("FastCgiAuthorizerAuthoritative", fcgi_config_set_authoritative_slot
,
2743 (void *)XtOffsetOf(fcgi_dir_config
, authorizer_options
), ACCESS_CONF
,
2744 "Set to 'off' to allow authorization to be passed along to lower modules upon failure"),
2746 AP_INIT_TAKE12("FastCgiAccessChecker", fcgi_config_new_auth_server
,
2747 (void *)FCGI_AUTH_TYPE_ACCESS_CHECKER
, ACCESS_CONF
,
2748 "a fastcgi-script path (absolute or relative to ServerRoot) followed by an optional -compat"),
2749 AP_INIT_FLAG("FastCgiAccessCheckerAuthoritative", fcgi_config_set_authoritative_slot
,
2750 (void *)XtOffsetOf(fcgi_dir_config
, access_checker_options
), ACCESS_CONF
,
2751 "Set to 'off' to allow access control to be passed along to lower modules upon failure"),
2757 static void register_hooks(apr_pool_t
* p
)
2759 // ap_hook_pre_config(x_pre_config, NULL, NULL, APR_HOOK_MIDDLE);
2760 ap_hook_post_config(init_module
, NULL
, NULL
, APR_HOOK_MIDDLE
);
2761 ap_hook_child_init(fcgi_child_init
, NULL
, NULL
, APR_HOOK_MIDDLE
);
2762 ap_hook_handler(content_handler
, NULL
, NULL
, APR_HOOK_MIDDLE
);
2763 ap_hook_check_user_id(check_user_authentication
, NULL
, NULL
, APR_HOOK_MIDDLE
);
2764 ap_hook_access_checker(check_access
, NULL
, NULL
, APR_HOOK_MIDDLE
);
2765 ap_hook_auth_checker(check_user_authorization
, NULL
, NULL
, APR_HOOK_MIDDLE
);
2768 module AP_MODULE_DECLARE_DATA fastcgi_module
=
2770 STANDARD20_MODULE_STUFF
,
2771 fcgi_config_create_dir_config
, /* per-directory config creator */
2772 NULL
, /* dir config merger */
2773 NULL
, /* server config creator */
2774 NULL
, /* server config merger */
2775 fastcgi_cmds
, /* command table */
2776 register_hooks
, /* set up other request processing hooks */
2779 #else /* !APACHE2 */
2781 handler_rec fastcgi_handlers
[] = {
2782 { FCGI_MAGIC_TYPE
, content_handler
},
2783 { "fastcgi-script", content_handler
},
2787 module MODULE_VAR_EXPORT fastcgi_module
= {
2788 STANDARD_MODULE_STUFF
,
2789 init_module
, /* initializer */
2790 fcgi_config_create_dir_config
, /* per-dir config creator */
2791 NULL
, /* per-dir config merger (default: override) */
2792 NULL
, /* per-server config creator */
2793 NULL
, /* per-server config merger (default: override) */
2794 fastcgi_cmds
, /* command table */
2795 fastcgi_handlers
, /* [9] content handlers */
2796 NULL
, /* [2] URI-to-filename translation */
2797 check_user_authentication
, /* [5] authenticate user_id */
2798 check_user_authorization
, /* [6] authorize user_id */
2799 check_access
, /* [4] check access (based on src & http headers) */
2800 NULL
, /* [7] check/set MIME type */
2801 NULL
, /* [8] fixups */
2802 NULL
, /* [10] logger */
2803 NULL
, /* [3] header-parser */
2804 fcgi_child_init
, /* process initialization */
2805 fcgi_child_exit
, /* process exit/cleanup */
2806 NULL
/* [1] post read-request handling */
2809 #endif /* !APACHE2 */