4 * Apache server module for FastCGI.
6 * $Id: mod_fastcgi.c,v 1.135 2002/07/26 03:10:54 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
);
311 close(fcgi_pm_pipe
[1]);
312 dup2(fcgi_pm_pipe
[0], 0);
313 close(fcgi_pm_pipe
[0]);
322 apr_pool_note_subprocess(p
, proc
, APR_KILL_ONLY_ONCE
);
326 fcgi_pm_pid
= ap_spawn_child(p
, fcgi_pm_main
, NULL
, kill_only_once
, NULL
, NULL
, NULL
);
327 if (fcgi_pm_pid
<= 0) {
328 ap_log_error(FCGI_LOG_ALERT
, s
,
329 "FastCGI: can't start the process manager, spawn_child() failed");
332 #endif /* !APACHE2 */
334 close(fcgi_pm_pipe
[0]);
342 static apcb_t
fcgi_child_exit(void * dc
)
344 static apcb_t
fcgi_child_exit(server_rec
*dc0
, pool
*dc1
)
348 /* Signal the PM thread to exit*/
349 SetEvent(fcgi_event_handles
[TERM_EVENT
]);
351 /* Waiting on pm thread to exit */
352 WaitForSingleObject(fcgi_pm_thread
, INFINITE
);
359 static void fcgi_child_init(apr_pool_t
* p
, server_rec
* dc
)
361 static void fcgi_child_init(server_rec
*dc
, pool
*p
)
365 /* Create the MBOX, TERM, and WAKE event handlers */
366 fcgi_event_handles
[0] = CreateEvent(NULL
, FALSE
, FALSE
, NULL
);
367 if (fcgi_event_handles
[0] == NULL
) {
368 ap_log_error(FCGI_LOG_ALERT
, fcgi_apache_main_server
,
369 "FastCGI: CreateEvent() failed");
371 fcgi_event_handles
[1] = CreateEvent(NULL
, FALSE
, FALSE
, NULL
);
372 if (fcgi_event_handles
[1] == NULL
) {
373 ap_log_error(FCGI_LOG_ALERT
, fcgi_apache_main_server
,
374 "FastCGI: CreateEvent() failed");
376 fcgi_event_handles
[2] = CreateEvent(NULL
, FALSE
, FALSE
, NULL
);
377 if (fcgi_event_handles
[2] == NULL
) {
378 ap_log_error(FCGI_LOG_ALERT
, fcgi_apache_main_server
,
379 "FastCGI: CreateEvent() failed");
382 /* Create the mbox mutex (PM - request threads) */
383 fcgi_dynamic_mbox_mutex
= CreateMutex(NULL
, FALSE
, NULL
);
384 if (fcgi_dynamic_mbox_mutex
== NULL
) {
385 ap_log_error(FCGI_LOG_ALERT
, fcgi_apache_main_server
,
386 "FastCGI: CreateMutex() failed");
389 /* Spawn of the process manager thread */
390 fcgi_pm_thread
= (HANDLE
) _beginthread(fcgi_pm_main
, 0, NULL
);
391 if (fcgi_pm_thread
== (HANDLE
) -1) {
392 ap_log_error(FCGI_LOG_ALERT
, fcgi_apache_main_server
,
393 "_beginthread() failed to spawn the process manager");
397 apr_pool_cleanup_register(p
, NULL
, fcgi_child_exit
, fcgi_child_exit
);
403 *----------------------------------------------------------------------
407 * Terminate a line: scan to the next newline, scan back to the
408 * first non-space character and store a terminating zero. Return
409 * the next character past the end of the newline.
411 * If the end of the string is reached, ASSERT!
413 * If the FIRST character(s) in the line are '\n' or "\r\n", the
414 * first character is replaced with a NULL and next character
415 * past the newline is returned. NOTE: this condition supercedes
416 * the processing of RFC-822 continuation lines.
418 * If continuation is set to 'TRUE', then it parses a (possible)
419 * sequence of RFC-822 continuation lines.
425 * Termination byte stored in string.
427 *----------------------------------------------------------------------
429 static char *get_header_line(char *start
, int continuation
)
434 if(p
[0] == '\r' && p
[1] == '\n') { /* If EOL in 1st 2 chars */
435 p
++; /* point to \n and stop */
436 } else if(*p
!= '\n') {
439 if(*p
== '\n' && p
[1] != ' ' && p
[1] != '\t')
444 while(*p
!= '\0' && *p
!= '\n') {
450 ap_assert(*p
!= '\0');
455 * Trim any trailing whitespace.
457 while(isspace((unsigned char)p
[-1]) && p
> start
) {
466 *----------------------------------------------------------------------
470 * Call with r->parseHeader == SCAN_CGI_READING_HEADERS
471 * and initial script output in fr->header.
473 * If the initial script output does not include the header
474 * terminator ("\r\n\r\n") process_headers returns with no side
475 * effects, to be called again when more script output
476 * has been appended to fr->header.
478 * If the initial script output includes the header terminator,
479 * process_headers parses the headers and determines whether or
480 * not the remaining script output will be sent to the client.
481 * If so, process_headers sends the HTTP response headers to the
482 * client and copies any non-header script output to the output
489 * May set r->parseHeader to:
490 * SCAN_CGI_FINISHED -- headers parsed, returning script response
491 * SCAN_CGI_BAD_HEADER -- malformed header from script
492 * SCAN_CGI_INT_REDIRECT -- handler should perform internal redirect
493 * SCAN_CGI_SRV_REDIRECT -- handler should return REDIRECT
495 *----------------------------------------------------------------------
498 static const char *process_headers(request_rec
*r
, fcgi_request
*fr
)
500 char *p
, *next
, *name
, *value
;
502 int hasContentType
, hasStatus
, hasLocation
;
504 ap_assert(fr
->parseHeader
== SCAN_CGI_READING_HEADERS
);
506 if (fr
->header
== NULL
)
510 * Do we have the entire header? Scan for the blank line that
511 * terminates the header.
513 p
= (char *)fr
->header
->elts
;
514 len
= fr
->header
->nelts
;
516 while(len
-- && flag
< 2) {
526 name
= "Invalid Character";
536 /* Return (to be called later when we have more data)
537 * if we don't have an entire header. */
542 * Parse all the headers.
544 fr
->parseHeader
= SCAN_CGI_FINISHED
;
545 hasContentType
= hasStatus
= hasLocation
= FALSE
;
546 next
= (char *)fr
->header
->elts
;
548 next
= get_header_line(name
= next
, TRUE
);
552 if ((p
= strchr(name
, ':')) == NULL
) {
556 while (p
!= name
&& isspace((unsigned char)*(p
- 1))) {
563 if (strpbrk(name
, " \t") != NULL
) {
567 while (isspace((unsigned char)*value
)) {
571 if (strcasecmp(name
, "Status") == 0) {
572 int statusValue
= strtol(value
, NULL
, 10);
575 goto DuplicateNotAllowed
;
577 if (statusValue
< 0) {
578 fr
->parseHeader
= SCAN_CGI_BAD_HEADER
;
579 return ap_psprintf(r
->pool
, "invalid Status '%s'", value
);
582 r
->status
= statusValue
;
583 r
->status_line
= ap_pstrdup(r
->pool
, value
);
587 if (fr
->role
== FCGI_RESPONDER
) {
588 if (strcasecmp(name
, "Content-type") == 0) {
589 if (hasContentType
) {
590 goto DuplicateNotAllowed
;
592 hasContentType
= TRUE
;
593 r
->content_type
= ap_pstrdup(r
->pool
, value
);
597 if (strcasecmp(name
, "Location") == 0) {
599 goto DuplicateNotAllowed
;
602 ap_table_set(r
->headers_out
, "Location", value
);
606 /* If the script wants them merged, it can do it */
607 ap_table_add(r
->err_headers_out
, name
, value
);
611 ap_table_add(fr
->authHeaders
, name
, value
);
615 if (fr
->role
!= FCGI_RESPONDER
)
619 * Who responds, this handler or Apache?
622 const char *location
= ap_table_get(r
->headers_out
, "Location");
624 * Based on internal redirect handling in mod_cgi.c...
626 * If a script wants to produce its own Redirect
627 * body, it now has to explicitly *say* "Status: 302"
629 if (r
->status
== 200) {
630 if(location
[0] == '/') {
632 * Location is an relative path. This handler will
633 * consume all script output, then have Apache perform an
636 fr
->parseHeader
= SCAN_CGI_INT_REDIRECT
;
640 * Location is an absolute URL. If the script didn't
641 * produce a Content-type header, this handler will
642 * consume all script output and then have Apache generate
643 * its standard redirect response. Otherwise this handler
644 * will transmit the script's response.
646 fr
->parseHeader
= SCAN_CGI_SRV_REDIRECT
;
652 * We're responding. Send headers, buffer excess script output.
654 ap_send_http_header(r
);
656 /* We need to reinstate our timeout, send_http_header() kill()s it */
657 ap_hard_timeout("FastCGI request processing", r
);
662 len
= fr
->header
->nelts
- (next
- fr
->header
->elts
);
664 ap_assert(BufferLength(fr
->clientOutputBuffer
) == 0);
665 if (BufferFree(fr
->clientOutputBuffer
) < len
) {
666 fr
->clientOutputBuffer
= fcgi_buf_new(r
->pool
, len
);
668 ap_assert(BufferFree(fr
->clientOutputBuffer
) >= len
);
670 int sent
= fcgi_buf_add_block(fr
->clientOutputBuffer
, next
, len
);
671 ap_assert(sent
== len
);
676 /* Log first line of a multi-line header */
677 if ((p
= strpbrk(name
, "\r\n")) != NULL
)
679 fr
->parseHeader
= SCAN_CGI_BAD_HEADER
;
680 return ap_psprintf(r
->pool
, "malformed header '%s'", name
);
683 fr
->parseHeader
= SCAN_CGI_BAD_HEADER
;
684 return ap_psprintf(r
->pool
, "duplicate header '%s'", name
);
688 * Read from the client filling both the FastCGI server buffer and the
689 * client buffer with the hopes of buffering the client data before
690 * making the connect() to the FastCGI server. This prevents slow
691 * clients from keeping the FastCGI server in processing longer than is
694 static int read_from_client_n_queue(fcgi_request
*fr
)
700 while (BufferFree(fr
->clientInputBuffer
) > 0 || BufferFree(fr
->serverOutputBuffer
) > 0) {
701 fcgi_protocol_queue_client_buffer(fr
);
703 if (fr
->expectingClientContent
<= 0)
706 fcgi_buf_get_free_block_info(fr
->clientInputBuffer
, &end
, &count
);
710 if ((countRead
= ap_get_client_block(fr
->r
, end
, count
)) < 0)
713 if (countRead
== 0) {
714 fr
->expectingClientContent
= 0;
717 fcgi_buf_add_update(fr
->clientInputBuffer
, countRead
);
718 ap_reset_timeout(fr
->r
);
724 static int write_to_client(fcgi_request
*fr
)
731 apr_bucket_brigade
* bde
;
732 apr_bucket_alloc_t
* const bkt_alloc
= fr
->r
->connection
->bucket_alloc
;
735 fcgi_buf_get_block_info(fr
->clientOutputBuffer
, &begin
, &count
);
739 /* If fewer than count bytes are written, an error occured.
740 * ap_bwrite() typically forces a flushed write to the client, this
741 * effectively results in a block (and short packets) - it should
742 * be fixed, but I didn't win much support for the idea on new-httpd.
743 * So, without patching Apache, the best way to deal with this is
744 * to size the fcgi_bufs to hold all of the script output (within
745 * reason) so the script can be released from having to wait around
746 * for the transmission to the client to complete. */
750 bde
= apr_brigade_create(fr
->r
->pool
, bkt_alloc
);
751 bkt
= apr_bucket_transient_create(begin
, count
, bkt_alloc
);
752 APR_BRIGADE_INSERT_TAIL(bde
, bkt
);
754 if (fr
->fs
? fr
->fs
->flush
: dynamicFlush
)
756 bkt
= apr_bucket_flush_create(bkt_alloc
);
757 APR_BRIGADE_INSERT_TAIL(bde
, bkt
);
760 rv
= ap_pass_brigade(fr
->r
->output_filters
, bde
);
762 #elif defined(RUSSIAN_APACHE)
764 rv
= (ap_rwrite(begin
, count
, fr
->r
) != count
);
768 rv
= (ap_bwrite(fr
->r
->connection
->client
, begin
, count
) != count
);
774 ap_log_rerror(FCGI_LOG_INFO_NOERRNO
, fr
->r
,
775 "FastCGI: client stopped connection before send body completed");
781 ap_reset_timeout(fr
->r
);
783 /* Don't bother with a wrapped buffer, limiting exposure to slow
784 * clients. The BUFF routines don't allow a writev from above,
785 * and don't always memcpy to minimize small write()s, this should
786 * be fixed, but I didn't win much support for the idea on
787 * new-httpd - I'll have to _prove_ its a problem first.. */
789 /* The default behaviour used to be to flush with every write, but this
790 * can tie up the FastCGI server longer than is necessary so its an option now */
792 if (fr
->fs
? fr
->fs
->flush
: dynamicFlush
)
794 #ifdef RUSSIAN_APACHE
795 rv
= ap_rflush(fr
->r
);
797 rv
= ap_bflush(fr
->r
->connection
->client
);
802 ap_log_rerror(FCGI_LOG_INFO_NOERRNO
, fr
->r
,
803 "FastCGI: client stopped connection before send body completed");
807 ap_reset_timeout(fr
->r
);
810 #endif /* !APACHE2 */
812 fcgi_buf_toss(fr
->clientOutputBuffer
, count
);
816 /*******************************************************************************
817 * Determine the user and group the wrapper should be called with.
818 * Based on code in Apache's create_argv_cmd() (util_script.c).
820 static void set_uid_n_gid(request_rec
*r
, const char **user
, const char **group
)
822 if (fcgi_wrapper
== NULL
) {
828 if (strncmp("/~", r
->uri
, 2) == 0) {
829 /* its a user dir uri, just send the ~user, and leave it to the PM */
830 char *end
= strchr(r
->uri
+ 2, '/');
833 *user
= memcpy(ap_pcalloc(r
->pool
, end
- r
->uri
), r
->uri
+ 1, end
- r
->uri
- 1);
835 *user
= ap_pstrdup(r
->pool
, r
->uri
+ 1);
839 *user
= ap_psprintf(r
->pool
, "%ld", (long) fcgi_util_get_server_uid(r
->server
));
840 *group
= ap_psprintf(r
->pool
, "%ld", (long) fcgi_util_get_server_gid(r
->server
));
844 static void send_request_complete(fcgi_request
*fr
)
846 if (fr
->completeTime
.tv_sec
)
848 struct timeval qtime
, rtime
;
850 timersub(&fr
->queueTime
, &fr
->startTime
, &qtime
);
851 timersub(&fr
->completeTime
, &fr
->queueTime
, &rtime
);
853 send_to_pm(FCGI_REQUEST_COMPLETE_JOB
, fr
->fs_path
,
855 qtime
.tv_sec
* 1000000 + qtime
.tv_usec
,
856 rtime
.tv_sec
* 1000000 + rtime
.tv_usec
);
862 static int set_nonblocking(const fcgi_request
* fr
, int nonblocking
)
864 if (fr
->using_npipe_io
)
868 DWORD mode
= PIPE_NOWAIT
| PIPE_READMODE_BYTE
;
869 if (SetNamedPipeHandleState((HANDLE
) fr
->fd
, &mode
, NULL
, NULL
) == 0)
871 ap_log_rerror(FCGI_LOG_ERR
, fr
->r
,
872 "FastCGI: SetNamedPipeHandleState() failed");
879 unsigned long ioctl_arg
= (nonblocking
) ? 1 : 0;
880 if (ioctlsocket(fr
->fd
, FIONBIO
, &ioctl_arg
) != 0)
882 errno
= WSAGetLastError();
883 ap_log_rerror(FCGI_LOG_ERR_ERRNO
, fr
->r
,
884 "FastCGI: ioctlsocket() failed");
894 static int set_nonblocking(const fcgi_request
* fr
, int nonblocking
)
897 int fd_flags
= fcntl(fr
->fd
, F_GETFL
, 0);
899 if (fd_flags
< 0) return -1;
901 #if defined(O_NONBLOCK)
902 nb_flag
= O_NONBLOCK
;
903 #elif defined(O_NDELAY)
905 #elif defined(FNDELAY)
908 #error "TODO - don't read from app until all data from client is posted."
911 fd_flags
= (nonblocking
) ? (fd_flags
| nb_flag
) : (fd_flags
& ~nb_flag
);
913 return fcntl(fr
->fd
, F_SETFL
, fd_flags
);
918 /*******************************************************************************
919 * Close the connection to the FastCGI server. This is normally called by
920 * do_work(), but may also be called as in request pool cleanup.
922 static void close_connection_to_fs(fcgi_request
*fr
)
926 if (fr
->fd
!= INVALID_SOCKET
)
928 set_nonblocking(fr
, FALSE
);
930 if (fr
->using_npipe_io
)
932 CloseHandle((HANDLE
) fr
->fd
);
936 /* abort the connection entirely */
937 struct linger linger
= {0, 0};
938 setsockopt(fr
->fd
, SOL_SOCKET
, SO_LINGER
, (void *) &linger
, sizeof(linger
));
942 fr
->fd
= INVALID_SOCKET
;
948 struct linger linger
= {0, 0};
949 set_nonblocking(fr
, FALSE
);
950 /* abort the connection entirely */
951 setsockopt(fr
->fd
, SOL_SOCKET
, SO_LINGER
, &linger
, sizeof(linger
));
957 if (fr
->dynamic
&& fr
->keepReadingFromFcgiApp
== FALSE
)
959 /* XXX FCGI_REQUEST_COMPLETE_JOB is only sent for requests which complete
960 * normally WRT the fcgi app. There is no data sent for
961 * connect() timeouts or requests which complete abnormally.
962 * KillDynamicProcs() and RemoveRecords() need to be looked at
963 * to be sure they can reasonably handle these cases before
964 * sending these sort of stats - theres some funk in there.
966 if (fcgi_util_ticks(&fr
->completeTime
) < 0)
968 /* there's no point to aborting the request, just log it */
969 ap_log_error(FCGI_LOG_ERR
, fr
->r
->server
, "FastCGI: can't get time of day");
975 /*******************************************************************************
976 * Connect to the FastCGI server.
978 static int open_connection_to_fs(fcgi_request
*fr
)
981 fd_set write_fds
, read_fds
;
983 request_rec
* const r
= fr
->r
;
984 pool
* const rp
= r
->pool
;
985 const char *socket_path
= NULL
;
986 struct sockaddr
*socket_addr
= NULL
;
987 int socket_addr_len
= 0;
989 const char *err
= NULL
;
992 /* Create the connection point */
995 socket_path
= fcgi_util_socket_hash_filename(rp
, fr
->fs_path
, fr
->user
, fr
->group
);
996 socket_path
= fcgi_util_socket_make_path_absolute(rp
, socket_path
, 1);
999 err
= fcgi_util_socket_make_domain_addr(rp
, (struct sockaddr_un
**)&socket_addr
,
1000 &socket_addr_len
, socket_path
);
1002 ap_log_rerror(FCGI_LOG_ERR
, r
,
1003 "FastCGI: failed to connect to server \"%s\": "
1004 "%s", fr
->fs_path
, err
);
1012 if (fr
->fs
->dest_addr
!= NULL
) {
1013 socket_addr
= fr
->fs
->dest_addr
;
1015 else if (fr
->fs
->socket_addr
) {
1016 socket_addr
= fr
->fs
->socket_addr
;
1019 socket_path
= fr
->fs
->socket_path
;
1022 socket_addr
= fr
->fs
->socket_addr
;
1024 socket_addr_len
= fr
->fs
->socket_addr_len
;
1030 if (fr
->fs
&& fr
->fs
->restartTime
)
1032 struct stat sock_stat
;
1034 if (stat(socket_path
, &sock_stat
) == 0)
1038 if (dynamicAutoUpdate
)
1040 struct stat app_stat
;
1042 /* TODO: follow sym links */
1044 if (stat(fr
->fs_path
, &app_stat
) == 0)
1047 if (fr
->fs
->startTime
< app_stat
.st_mtime
)
1049 if (sock_stat
.st_mtime
< app_stat
.st_mtime
)
1053 struct timeval tv
= {1, 0};
1056 * There's a newer one, request a restart.
1058 send_to_pm(FCGI_SERVER_RESTART_JOB
, fr
->fs_path
, fr
->user
, fr
->group
, 0, 0);
1063 /* Avoid sleep/alarm interactions */
1064 ap_select(0, NULL
, NULL
, NULL
, &tv
);
1072 send_to_pm(FCGI_SERVER_START_JOB
, fr
->fs_path
, fr
->user
, fr
->group
, 0, 0);
1074 /* Wait until it looks like its running */
1081 fr
->fs
= fcgi_util_fs_get_by_id(fr
->fs_path
, 0, 0);
1083 if (fr
->fs
&& fr
->fs
->restartTime
)
1085 struct timeval tv
= {1, 0};
1087 /* Avoid sleep/alarm interactions */
1088 ap_select(0, NULL
, NULL
, NULL
, &tv
);
1090 if (stat(socket_path
, &sock_stat
) == 0)
1105 HANDLE wait_npipe_mutex
;
1107 DWORD max_connect_time
= FCGI_NAMED_PIPE_CONNECT_TIMEOUT
;
1109 fr
->using_npipe_io
= TRUE
;
1113 interval
= dynamicPleaseStartDelay
* 1000;
1115 if (dynamicAppConnectTimeout
) {
1116 max_connect_time
= dynamicAppConnectTimeout
;
1121 interval
= FCGI_NAMED_PIPE_CONNECT_TIMEOUT
* 1000;
1123 if (fr
->fs
->appConnectTimeout
) {
1124 max_connect_time
= fr
->fs
->appConnectTimeout
;
1128 fcgi_util_ticks(&fr
->startTime
);
1131 // xxx this handle should live somewhere (see CloseHandle()s below too)
1132 char * wait_npipe_mutex_name
, * cp
;
1133 wait_npipe_mutex_name
= cp
= ap_pstrdup(rp
, socket_path
);
1134 while ((cp
= strchr(cp
, '\\'))) *cp
= '/';
1136 wait_npipe_mutex
= CreateMutex(NULL
, FALSE
, wait_npipe_mutex_name
);
1139 if (wait_npipe_mutex
== NULL
)
1141 ap_log_rerror(FCGI_LOG_ERR
, r
,
1142 "FastCGI: failed to connect to server \"%s\": "
1143 "can't create the WaitNamedPipe mutex", fr
->fs_path
);
1147 SetLastError(ERROR_SUCCESS
);
1149 rv
= WaitForSingleObject(wait_npipe_mutex
, max_connect_time
* 1000);
1151 if (rv
== WAIT_TIMEOUT
|| rv
== WAIT_FAILED
)
1155 send_to_pm(FCGI_REQUEST_TIMEOUT_JOB
, fr
->fs_path
, fr
->user
, fr
->group
, 0, 0);
1157 ap_log_rerror(FCGI_LOG_ERR_NOERRNO
, r
,
1158 "FastCGI: failed to connect to server \"%s\": "
1159 "wait for a npipe instance failed", fr
->fs_path
);
1160 FCGIDBG3("interval=%d, max_connect_time=%d", interval
, max_connect_time
);
1161 CloseHandle(wait_npipe_mutex
);
1165 fcgi_util_ticks(&fr
->queueTime
);
1167 connect_time
= fr
->queueTime
.tv_sec
- fr
->startTime
.tv_sec
;
1171 if (connect_time
>= interval
)
1173 send_to_pm(FCGI_REQUEST_TIMEOUT_JOB
, fr
->fs_path
, fr
->user
, fr
->group
, 0, 0);
1174 FCGIDBG4("connect_time=%d, interval=%d, max_connect_time=%d", connect_time
, interval
, max_connect_time
);
1176 if (max_connect_time
- connect_time
< interval
)
1178 interval
= max_connect_time
- connect_time
;
1183 interval
-= connect_time
* 1000;
1188 ready
= WaitNamedPipe(socket_path
, interval
);
1192 fr
->fd
= (SOCKET
) CreateFile(socket_path
,
1193 GENERIC_READ
| GENERIC_WRITE
,
1194 FILE_SHARE_READ
| FILE_SHARE_WRITE
,
1195 NULL
, // no security attributes
1196 OPEN_EXISTING
, // opens existing pipe
1197 FILE_FLAG_OVERLAPPED
,
1198 NULL
); // no template file
1200 if (fr
->fd
!= (SOCKET
) INVALID_HANDLE_VALUE
)
1202 ReleaseMutex(wait_npipe_mutex
);
1203 CloseHandle(wait_npipe_mutex
);
1204 fcgi_util_ticks(&fr
->queueTime
);
1205 FCGIDBG2("got npipe connect: %s", fr
->fs_path
);
1209 if (GetLastError() != ERROR_PIPE_BUSY
1210 && GetLastError() != ERROR_FILE_NOT_FOUND
)
1212 ap_log_rerror(FCGI_LOG_ERR
, r
,
1213 "FastCGI: failed to connect to server \"%s\": "
1214 "CreateFile() failed", fr
->fs_path
);
1218 FCGIDBG2("missed npipe connect: %s", fr
->fs_path
);
1223 send_to_pm(FCGI_REQUEST_TIMEOUT_JOB
, fr
->fs_path
, fr
->user
, fr
->group
, 0, 0);
1226 fcgi_util_ticks(&fr
->queueTime
);
1228 connect_time
= fr
->queueTime
.tv_sec
- fr
->startTime
.tv_sec
;
1230 FCGIDBG5("interval=%d, max_connect_time=%d, connect_time=%d, ready=%d", interval
, max_connect_time
, connect_time
, ready
);
1232 if (connect_time
>= max_connect_time
)
1234 ap_log_rerror(FCGI_LOG_ERR
, r
,
1235 "FastCGI: failed to connect to server \"%s\": "
1236 "CreateFile()/WaitNamedPipe() timed out", fr
->fs_path
);
1241 ReleaseMutex(wait_npipe_mutex
);
1242 CloseHandle(wait_npipe_mutex
);
1243 fr
->fd
= INVALID_SOCKET
;
1249 /* Create the socket */
1250 fr
->fd
= socket(socket_addr
->sa_family
, SOCK_STREAM
, 0);
1253 if (fr
->fd
== INVALID_SOCKET
) {
1254 errno
= WSAGetLastError(); // Not sure this is going to work as expected
1258 ap_log_rerror(FCGI_LOG_ERR_ERRNO
, r
,
1259 "FastCGI: failed to connect to server \"%s\": "
1260 "socket() failed", fr
->fs_path
);
1265 if (fr
->fd
>= FD_SETSIZE
) {
1266 ap_log_rerror(FCGI_LOG_ERR
, r
,
1267 "FastCGI: failed to connect to server \"%s\": "
1268 "socket file descriptor (%u) is larger than "
1269 "FD_SETSIZE (%u), you probably need to rebuild Apache with a "
1270 "larger FD_SETSIZE", fr
->fs_path
, fr
->fd
, FD_SETSIZE
);
1275 /* If appConnectTimeout is non-zero, setup do a non-blocking connect */
1276 if ((fr
->dynamic
&& dynamicAppConnectTimeout
) || (!fr
->dynamic
&& fr
->fs
->appConnectTimeout
)) {
1277 set_nonblocking(fr
, TRUE
);
1281 fcgi_util_ticks(&fr
->startTime
);
1285 if (connect(fr
->fd
, (struct sockaddr
*)socket_addr
, socket_addr_len
) == 0)
1286 goto ConnectionComplete
;
1290 errno
= WSAGetLastError();
1291 if (errno
!= WSAEWOULDBLOCK
) {
1292 ap_log_rerror(FCGI_LOG_ERR_ERRNO
, r
,
1293 "FastCGI: failed to connect to server \"%s\": "
1294 "connect() failed", fr
->fs_path
);
1300 /* ECONNREFUSED means the listen queue is full (or there isn't one).
1301 * With dynamic I can at least make sure the PM knows this is occuring */
1302 if (fr
->dynamic
&& errno
== ECONNREFUSED
) {
1303 /* @@@ This might be better as some other "kind" of message */
1304 send_to_pm(FCGI_REQUEST_TIMEOUT_JOB
, fr
->fs_path
, fr
->user
, fr
->group
, 0, 0);
1306 errno
= ECONNREFUSED
;
1309 if (errno
!= EINPROGRESS
) {
1310 ap_log_rerror(FCGI_LOG_ERR
, r
,
1311 "FastCGI: failed to connect to server \"%s\": "
1312 "connect() failed", fr
->fs_path
);
1318 /* The connect() is non-blocking */
1324 FD_ZERO(&write_fds
);
1325 FD_SET(fr
->fd
, &write_fds
);
1326 read_fds
= write_fds
;
1327 tval
.tv_sec
= dynamicPleaseStartDelay
;
1330 status
= ap_select((fr
->fd
+1), &read_fds
, &write_fds
, NULL
, &tval
);
1334 fcgi_util_ticks(&fr
->queueTime
);
1339 /* select() timed out */
1340 send_to_pm(FCGI_REQUEST_TIMEOUT_JOB
, fr
->fs_path
, fr
->user
, fr
->group
, 0, 0);
1341 } while ((fr
->queueTime
.tv_sec
- fr
->startTime
.tv_sec
) < (int)dynamicAppConnectTimeout
);
1343 /* XXX These can be moved down when dynamic vars live is a struct */
1345 ap_log_rerror(FCGI_LOG_ERR_NOERRNO
, r
,
1346 "FastCGI: failed to connect to server \"%s\": "
1347 "connect() timed out (appConnTimeout=%dsec)",
1348 fr
->fs_path
, dynamicAppConnectTimeout
);
1353 tval
.tv_sec
= fr
->fs
->appConnectTimeout
;
1355 FD_ZERO(&write_fds
);
1356 FD_SET(fr
->fd
, &write_fds
);
1357 read_fds
= write_fds
;
1359 status
= ap_select((fr
->fd
+1), &read_fds
, &write_fds
, NULL
, &tval
);
1362 ap_log_rerror(FCGI_LOG_ERR_NOERRNO
, r
,
1363 "FastCGI: failed to connect to server \"%s\": "
1364 "connect() timed out (appConnTimeout=%dsec)",
1365 fr
->fs_path
, dynamicAppConnectTimeout
);
1372 errno
= WSAGetLastError();
1374 ap_log_rerror(FCGI_LOG_ERR_ERRNO
, r
,
1375 "FastCGI: failed to connect to server \"%s\": "
1376 "select() failed", fr
->fs_path
);
1380 if (FD_ISSET(fr
->fd
, &write_fds
) || FD_ISSET(fr
->fd
, &read_fds
)) {
1382 NET_SIZE_T len
= sizeof(error
);
1384 if (getsockopt(fr
->fd
, SOL_SOCKET
, SO_ERROR
, (char *)&error
, &len
) < 0) {
1385 /* Solaris pending error */
1387 errno
= WSAGetLastError();
1389 ap_log_rerror(FCGI_LOG_ERR_ERRNO
, r
,
1390 "FastCGI: failed to connect to server \"%s\": "
1391 "select() failed (Solaris pending error)", fr
->fs_path
);
1396 /* Berkeley-derived pending error */
1398 ap_log_rerror(FCGI_LOG_ERR_ERRNO
, r
,
1399 "FastCGI: failed to connect to server \"%s\": "
1400 "select() failed (pending error)", fr
->fs_path
);
1406 errno
= WSAGetLastError();
1408 ap_log_rerror(FCGI_LOG_ERR_ERRNO
, r
,
1409 "FastCGI: failed to connect to server \"%s\": "
1410 "select() error - THIS CAN'T HAPPEN!", fr
->fs_path
);
1415 /* Return to blocking mode if it was set up */
1416 if ((fr
->dynamic
&& dynamicAppConnectTimeout
) || (!fr
->dynamic
&& fr
->fs
->appConnectTimeout
)) {
1417 set_nonblocking(fr
, FALSE
);
1421 if (socket_addr
->sa_family
== AF_INET
) {
1422 /* We shouldn't be sending small packets and there's no application
1423 * level ack of the data we send, so disable Nagle */
1425 setsockopt(fr
->fd
, IPPROTO_TCP
, TCP_NODELAY
, (char *)&set
, sizeof(set
));
1432 static void sink_client_data(fcgi_request
*fr
)
1437 fcgi_buf_reset(fr
->clientInputBuffer
);
1438 fcgi_buf_get_free_block_info(fr
->clientInputBuffer
, &base
, &size
);
1439 while (ap_get_client_block(fr
->r
, base
, size
) > 0);
1442 static apcb_t
cleanup(void *data
)
1444 fcgi_request
* const fr
= (fcgi_request
*) data
;
1446 if (fr
== NULL
) return APCB_OK
;
1448 /* its more than likely already run, but... */
1449 close_connection_to_fs(fr
);
1451 send_request_complete(fr
);
1453 if (fr
->fs_stderr_len
) {
1454 ap_log_rerror(FCGI_LOG_ERR_NOERRNO
, fr
->r
,
1455 "FastCGI: server \"%s\" stderr: %s", fr
->fs_path
, fr
->fs_stderr
);
1462 static int npipe_io(fcgi_request
* const fr
)
1464 request_rec
* const r
= fr
->r
;
1475 state
= STATE_ENV_SEND
;
1476 env_status env_status
;
1478 int dynamic_first_recv
= fr
->dynamic
;
1479 int idle_timeout
= fr
->dynamic
? dynamic_idle_timeout
: fr
->fs
->idle_timeout
;
1480 int send_pending
= 0;
1481 int recv_pending
= 0;
1482 int client_send
= 0;
1487 struct timeval timeout
;
1488 struct timeval dynamic_last_io_time
= {0, 0};
1490 pool
* const rp
= r
->pool
;
1492 DWORD recv_count
= 0;
1494 if (fr
->role
== FCGI_RESPONDER
)
1496 client_recv
= (fr
->expectingClientContent
!= 0);
1499 idle_timeout
= fr
->dynamic
? dynamic_idle_timeout
: fr
->fs
->idle_timeout
;
1501 env_status
.envp
= NULL
;
1503 events
[0] = CreateEvent(NULL
, TRUE
, FALSE
, NULL
);
1504 events
[1] = CreateEvent(NULL
, TRUE
, FALSE
, NULL
);
1505 sov
.hEvent
= events
[0];
1506 rov
.hEvent
= events
[1];
1510 dynamic_last_io_time
= fr
->startTime
;
1512 if (dynamicAppConnectTimeout
)
1514 struct timeval qwait
;
1515 timersub(&fr
->queueTime
, &fr
->startTime
, &qwait
);
1516 dynamic_first_recv
= qwait
.tv_sec
/ dynamicPleaseStartDelay
+ 1;
1520 ap_hard_timeout("FastCGI request processing", r
);
1522 while (state
!= STATE_CLIENT_SEND
)
1528 case STATE_ENV_SEND
:
1530 if (fcgi_protocol_queue_env(r
, fr
, &env_status
) == 0)
1535 state
= STATE_CLIENT_RECV
;
1539 case STATE_CLIENT_RECV
:
1541 if (read_from_client_n_queue(fr
) != OK
)
1543 state
= STATE_CLIENT_ERROR
;
1549 state
= STATE_SERVER_SEND
;
1556 case STATE_SERVER_SEND
:
1558 if (! send_pending
&& BufferLength(fr
->serverOutputBuffer
))
1560 Buffer
* b
= fr
->serverOutputBuffer
;
1563 len
= min(b
->length
, b
->data
+ b
->size
- b
->begin
);
1565 if (WriteFile((HANDLE
) fr
->fd
, b
->begin
, len
, &sent
, &sov
))
1567 fcgi_buf_removed(b
, sent
);
1568 ResetEvent(sov
.hEvent
);
1570 else if (GetLastError() == ERROR_IO_PENDING
)
1576 ap_log_rerror(FCGI_LOG_ERR
, r
, "FastCGI: comm with server "
1577 "\"%s\" aborted: WriteFile() failed", fr
->fs_path
);
1578 state
= STATE_ERROR
;
1585 case STATE_SERVER_RECV
:
1588 * Only get more data when the serverInputBuffer is empty.
1589 * Otherwise we may already have the END_REQUEST buffered
1590 * (but not processed) and a read on a closed named pipe
1591 * results in an error that is normally abnormal.
1593 if (! recv_pending
&& BufferLength(fr
->serverInputBuffer
) == 0)
1595 Buffer
* b
= fr
->serverInputBuffer
;
1598 len
= min(b
->size
- b
->length
, b
->data
+ b
->size
- b
->end
);
1600 if (ReadFile((HANDLE
) fr
->fd
, b
->end
, len
, &rcvd
, &rov
))
1602 fcgi_buf_added(b
, rcvd
);
1604 ResetEvent(rov
.hEvent
);
1605 if (dynamic_first_recv
)
1607 dynamic_first_recv
= 0;
1610 else if (GetLastError() == ERROR_IO_PENDING
)
1614 else if (GetLastError() == ERROR_HANDLE_EOF
)
1616 fr
->keepReadingFromFcgiApp
= FALSE
;
1617 state
= STATE_CLIENT_SEND
;
1618 ResetEvent(rov
.hEvent
);
1621 else if (GetLastError() == ERROR_NO_DATA
)
1627 ap_log_rerror(FCGI_LOG_ERR
, r
, "FastCGI: comm with server "
1628 "\"%s\" aborted: ReadFile() failed", fr
->fs_path
);
1629 state
= STATE_ERROR
;
1636 case STATE_CLIENT_SEND
:
1638 if (client_send
|| ! BufferFree(fr
->clientOutputBuffer
))
1640 if (write_to_client(fr
))
1642 state
= STATE_CLIENT_ERROR
;
1656 if (state
== STATE_CLIENT_ERROR
|| state
== STATE_ERROR
)
1661 /* setup the io timeout */
1663 if (BufferLength(fr
->clientOutputBuffer
))
1665 /* don't let client data sit too long, it might be a push */
1667 timeout
.tv_usec
= 100000;
1669 else if (dynamic_first_recv
)
1672 struct timeval qwait
;
1674 fcgi_util_ticks(&fr
->queueTime
);
1678 /* a send() succeeded last pass */
1679 dynamic_last_io_time
= fr
->queueTime
;
1683 /* timed out last pass */
1684 struct timeval idle_time
;
1686 timersub(&fr
->queueTime
, &dynamic_last_io_time
, &idle_time
);
1688 if (idle_time
.tv_sec
> idle_timeout
)
1690 send_to_pm(FCGI_REQUEST_TIMEOUT_JOB
, fr
->fs_path
, fr
->user
, fr
->group
, 0, 0);
1691 ap_log_rerror(FCGI_LOG_ERR_NOERRNO
, r
, "FastCGI: comm "
1692 "with (dynamic) server \"%s\" aborted: (first read) "
1693 "idle timeout (%d sec)", fr
->fs_path
, idle_timeout
);
1694 state
= STATE_ERROR
;
1699 timersub(&fr
->queueTime
, &fr
->startTime
, &qwait
);
1701 delay
= dynamic_first_recv
* dynamicPleaseStartDelay
;
1703 if (qwait
.tv_sec
< delay
)
1705 timeout
.tv_sec
= delay
;
1706 timeout
.tv_usec
= 100000; /* fudge for select() slop */
1707 timersub(&timeout
, &qwait
, &timeout
);
1711 /* Killed time somewhere.. client read? */
1712 send_to_pm(FCGI_REQUEST_TIMEOUT_JOB
, fr
->fs_path
, fr
->user
, fr
->group
, 0, 0);
1713 dynamic_first_recv
= qwait
.tv_sec
/ dynamicPleaseStartDelay
+ 1;
1714 timeout
.tv_sec
= dynamic_first_recv
* dynamicPleaseStartDelay
;
1715 timeout
.tv_usec
= 100000; /* fudge for select() slop */
1716 timersub(&timeout
, &qwait
, &timeout
);
1721 timeout
.tv_sec
= idle_timeout
;
1722 timeout
.tv_usec
= 0;
1725 /* require a pended recv otherwise the app can deadlock */
1728 msec_timeout
= timeout
.tv_sec
* 1000 + timeout
.tv_usec
/ 1000;
1730 rv
= WaitForMultipleObjects(2, events
, FALSE
, msec_timeout
);
1732 if (rv
== WAIT_TIMEOUT
)
1736 if (BufferLength(fr
->clientOutputBuffer
))
1740 else if (dynamic_first_recv
)
1742 struct timeval qwait
;
1744 fcgi_util_ticks(&fr
->queueTime
);
1745 timersub(&fr
->queueTime
, &fr
->startTime
, &qwait
);
1747 send_to_pm(FCGI_REQUEST_TIMEOUT_JOB
, fr
->fs_path
, fr
->user
, fr
->group
, 0, 0);
1749 dynamic_first_recv
= qwait
.tv_sec
/ dynamicPleaseStartDelay
+ 1;
1753 ap_log_rerror(FCGI_LOG_ERR_NOERRNO
, r
, "FastCGI: comm with "
1754 "server \"%s\" aborted: idle timeout (%d sec)",
1755 fr
->fs_path
, idle_timeout
);
1756 state
= STATE_ERROR
;
1762 int i
= rv
- WAIT_OBJECT_0
;
1770 if (GetOverlappedResult((HANDLE
) fr
->fd
, &sov
, &sent
, FALSE
))
1773 ResetEvent(sov
.hEvent
);
1774 fcgi_buf_removed(fr
->serverOutputBuffer
, sent
);
1778 ap_log_rerror(FCGI_LOG_ERR
, r
, "FastCGI: comm with server "
1779 "\"%s\" aborted: GetOverlappedResult() failed", fr
->fs_path
);
1780 state
= STATE_ERROR
;
1791 ResetEvent(rov
.hEvent
);
1793 if (GetOverlappedResult((HANDLE
) fr
->fd
, &rov
, &rcvd
, FALSE
))
1795 fcgi_buf_added(fr
->serverInputBuffer
, rcvd
);
1796 if (dynamic_first_recv
)
1798 dynamic_first_recv
= 0;
1803 ap_log_rerror(FCGI_LOG_ERR
, r
, "FastCGI: comm with server "
1804 "\"%s\" aborted: GetOverlappedResult() failed", fr
->fs_path
);
1805 state
= STATE_ERROR
;
1812 if (fcgi_protocol_dequeue(rp
, fr
))
1814 state
= STATE_ERROR
;
1818 if (fr
->parseHeader
== SCAN_CGI_READING_HEADERS
)
1820 const char * err
= process_headers(r
, fr
);
1823 ap_log_rerror(FCGI_LOG_ERR_NOERRNO
, r
,
1824 "FastCGI: comm with server \"%s\" aborted: "
1825 "error parsing headers: %s", fr
->fs_path
, err
);
1826 state
= STATE_ERROR
;
1831 if (fr
->exitStatusSet
)
1833 fr
->keepReadingFromFcgiApp
= FALSE
;
1834 state
= STATE_CLIENT_SEND
;
1839 if (! fr
->exitStatusSet
|| ! fr
->eofSent
)
1841 CancelIo((HANDLE
) fr
->fd
);
1844 CloseHandle(rov
.hEvent
);
1845 CloseHandle(sov
.hEvent
);
1847 return (state
== STATE_ERROR
);
1851 static int socket_io(fcgi_request
* const fr
)
1864 state
= STATE_ENV_SEND
;
1866 request_rec
* const r
= fr
->r
;
1868 struct timeval timeout
;
1869 struct timeval dynamic_last_io_time
= {0, 0};
1872 int nfds
= fr
->fd
+ 1;
1873 int select_status
= 1;
1876 int dynamic_first_recv
= fr
->dynamic
? 1 : 0;
1877 int client_send
= FALSE
;
1878 int client_recv
= FALSE
;
1882 if (fr
->role
== FCGI_RESPONDER
)
1884 client_recv
= (fr
->expectingClientContent
!= 0);
1887 idle_timeout
= fr
->dynamic
? dynamic_idle_timeout
: fr
->fs
->idle_timeout
;
1893 dynamic_last_io_time
= fr
->startTime
;
1895 if (dynamicAppConnectTimeout
)
1897 struct timeval qwait
;
1898 timersub(&fr
->queueTime
, &fr
->startTime
, &qwait
);
1899 dynamic_first_recv
= qwait
.tv_sec
/ dynamicPleaseStartDelay
+ 1;
1903 ap_hard_timeout("FastCGI request processing", r
);
1905 set_nonblocking(fr
, TRUE
);
1910 FD_ZERO(&write_set
);
1914 case STATE_ENV_SEND
:
1916 if (fcgi_protocol_queue_env(r
, fr
, &env
) == 0)
1921 state
= STATE_CLIENT_RECV
;
1925 case STATE_CLIENT_RECV
:
1927 if (read_from_client_n_queue(fr
))
1929 state
= STATE_CLIENT_ERROR
;
1935 state
= STATE_SERVER_SEND
;
1942 case STATE_SERVER_SEND
:
1944 if (BufferLength(fr
->serverOutputBuffer
))
1946 FD_SET(fr
->fd
, &write_set
);
1950 ap_assert(fr
->eofSent
);
1951 state
= STATE_SERVER_RECV
;
1956 case STATE_SERVER_RECV
:
1958 FD_SET(fr
->fd
, &read_set
);
1962 case STATE_CLIENT_SEND
:
1964 if (client_send
|| ! BufferFree(fr
->clientOutputBuffer
))
1966 if (write_to_client(fr
))
1968 state
= STATE_CLIENT_ERROR
;
1978 case STATE_CLIENT_ERROR
:
1987 if (state
== STATE_CLIENT_ERROR
|| state
== STATE_ERROR
)
1992 /* setup the io timeout */
1994 if (BufferLength(fr
->clientOutputBuffer
))
1996 /* don't let client data sit too long, it might be a push */
1998 timeout
.tv_usec
= 100000;
2000 else if (dynamic_first_recv
)
2003 struct timeval qwait
;
2005 fcgi_util_ticks(&fr
->queueTime
);
2009 /* a send() succeeded last pass */
2010 dynamic_last_io_time
= fr
->queueTime
;
2014 /* timed out last pass */
2015 struct timeval idle_time
;
2017 timersub(&fr
->queueTime
, &dynamic_last_io_time
, &idle_time
);
2019 if (idle_time
.tv_sec
> idle_timeout
)
2021 send_to_pm(FCGI_REQUEST_TIMEOUT_JOB
, fr
->fs_path
, fr
->user
, fr
->group
, 0, 0);
2022 ap_log_rerror(FCGI_LOG_ERR_NOERRNO
, r
, "FastCGI: comm "
2023 "with (dynamic) server \"%s\" aborted: (first read) "
2024 "idle timeout (%d sec)", fr
->fs_path
, idle_timeout
);
2025 state
= STATE_ERROR
;
2030 timersub(&fr
->queueTime
, &fr
->startTime
, &qwait
);
2032 delay
= dynamic_first_recv
* dynamicPleaseStartDelay
;
2034 FCGIDBG5("qwait=%ld.%06ld delay=%d first_recv=%d", qwait
.tv_sec
, qwait
.tv_usec
, delay
, dynamic_first_recv
);
2036 if (qwait
.tv_sec
< delay
)
2038 timeout
.tv_sec
= delay
;
2039 timeout
.tv_usec
= 100000; /* fudge for select() slop */
2040 timersub(&timeout
, &qwait
, &timeout
);
2044 /* Killed time somewhere.. client read? */
2045 send_to_pm(FCGI_REQUEST_TIMEOUT_JOB
, fr
->fs_path
, fr
->user
, fr
->group
, 0, 0);
2046 dynamic_first_recv
= qwait
.tv_sec
/ dynamicPleaseStartDelay
+ 1;
2047 timeout
.tv_sec
= dynamic_first_recv
* dynamicPleaseStartDelay
;
2048 timeout
.tv_usec
= 100000; /* fudge for select() slop */
2049 timersub(&timeout
, &qwait
, &timeout
);
2054 timeout
.tv_sec
= idle_timeout
;
2055 timeout
.tv_usec
= 0;
2058 /* wait on the socket */
2059 select_status
= ap_select(nfds
, &read_set
, &write_set
, NULL
, &timeout
);
2061 if (select_status
< 0)
2063 ap_log_rerror(FCGI_LOG_ERR_ERRNO
, r
, "FastCGI: comm with server "
2064 "\"%s\" aborted: select() failed", fr
->fs_path
);
2065 state
= STATE_ERROR
;
2069 if (select_status
== 0)
2071 /* select() timeout */
2073 if (BufferLength(fr
->clientOutputBuffer
))
2075 if (fr
->role
== FCGI_RESPONDER
)
2080 else if (dynamic_first_recv
)
2082 struct timeval qwait
;
2084 fcgi_util_ticks(&fr
->queueTime
);
2085 timersub(&fr
->queueTime
, &fr
->startTime
, &qwait
);
2087 send_to_pm(FCGI_REQUEST_TIMEOUT_JOB
, fr
->fs_path
, fr
->user
, fr
->group
, 0, 0);
2089 dynamic_first_recv
= qwait
.tv_sec
/ dynamicPleaseStartDelay
+ 1;
2094 ap_log_rerror(FCGI_LOG_ERR_NOERRNO
, r
, "FastCGI: comm with "
2095 "server \"%s\" aborted: idle timeout (%d sec)",
2096 fr
->fs_path
, idle_timeout
);
2097 state
= STATE_ERROR
;
2101 if (FD_ISSET(fr
->fd
, &write_set
))
2103 /* send to the server */
2105 rv
= fcgi_buf_socket_send(fr
->serverOutputBuffer
, fr
->fd
);
2109 ap_log_rerror(FCGI_LOG_ERR
, r
, "FastCGI: comm with server "
2110 "\"%s\" aborted: write failed", fr
->fs_path
);
2111 state
= STATE_ERROR
;
2116 if (FD_ISSET(fr
->fd
, &read_set
))
2118 /* recv from the server */
2120 if (dynamic_first_recv
)
2122 dynamic_first_recv
= 0;
2123 fcgi_util_ticks(&fr
->queueTime
);
2126 rv
= fcgi_buf_socket_recv(fr
->serverInputBuffer
, fr
->fd
);
2130 ap_log_rerror(FCGI_LOG_ERR
, r
, "FastCGI: comm with server "
2131 "\"%s\" aborted: read failed", fr
->fs_path
);
2132 state
= STATE_ERROR
;
2138 fr
->keepReadingFromFcgiApp
= FALSE
;
2139 state
= STATE_CLIENT_SEND
;
2144 if (fcgi_protocol_dequeue(rp
, fr
))
2146 state
= STATE_ERROR
;
2150 if (fr
->parseHeader
== SCAN_CGI_READING_HEADERS
)
2152 const char * err
= process_headers(r
, fr
);
2155 ap_log_rerror(FCGI_LOG_ERR_NOERRNO
, r
,
2156 "FastCGI: comm with server \"%s\" aborted: "
2157 "error parsing headers: %s", fr
->fs_path
, err
);
2158 state
= STATE_ERROR
;
2163 if (fr
->exitStatusSet
)
2165 fr
->keepReadingFromFcgiApp
= FALSE
;
2166 state
= STATE_CLIENT_SEND
;
2171 return (state
== STATE_ERROR
);
2175 /*----------------------------------------------------------------------
2176 * This is the core routine for moving data between the FastCGI
2177 * application and the Web server's client.
2179 static int do_work(request_rec
* const r
, fcgi_request
* const fr
)
2184 fcgi_protocol_queue_begin_request(fr
);
2186 if (fr
->role
== FCGI_RESPONDER
)
2188 rv
= ap_setup_client_block(r
, REQUEST_CHUNKED_ERROR
);
2195 fr
->expectingClientContent
= ap_should_client_block(r
);
2199 ap_register_cleanup(rp
, (void *)fr
, cleanup
, ap_null_cleanup
);
2200 ap_unblock_alarms();
2202 ap_hard_timeout("connect() to FastCGI server", r
);
2204 /* Connect to the FastCGI Application */
2205 if (open_connection_to_fs(fr
) != FCGI_OK
)
2208 return HTTP_INTERNAL_SERVER_ERROR
;
2212 if (fr
->using_npipe_io
)
2222 /* comm with the server is done */
2223 close_connection_to_fs(fr
);
2225 if (fr
->role
== FCGI_RESPONDER
)
2227 sink_client_data(fr
);
2230 while (rv
== 0 && BufferLength(fr
->serverInputBuffer
) || BufferLength(fr
->clientOutputBuffer
))
2232 if (fcgi_protocol_dequeue(rp
, fr
))
2234 rv
= HTTP_INTERNAL_SERVER_ERROR
;
2237 if (fr
->parseHeader
== SCAN_CGI_READING_HEADERS
)
2239 const char * err
= process_headers(r
, fr
);
2242 ap_log_rerror(FCGI_LOG_ERR_NOERRNO
, r
,
2243 "FastCGI: comm with server \"%s\" aborted: "
2244 "error parsing headers: %s", fr
->fs_path
, err
);
2245 rv
= HTTP_INTERNAL_SERVER_ERROR
;
2249 if (fr
->role
== FCGI_RESPONDER
)
2251 if (write_to_client(fr
))
2258 fcgi_buf_reset(fr
->clientOutputBuffer
);
2262 switch (fr
->parseHeader
)
2264 case SCAN_CGI_FINISHED
:
2266 if (fr
->role
== FCGI_RESPONDER
)
2268 /* RUSSIAN_APACHE requires rflush() over bflush() */
2271 ap_bgetopt(r
->connection
->client
, BO_BYTECT
, &r
->bytes_sent
);
2277 case SCAN_CGI_INT_REDIRECT
:
2278 case SCAN_CGI_SRV_REDIRECT
:
2282 case SCAN_CGI_READING_HEADERS
:
2284 ap_log_rerror(FCGI_LOG_ERR_NOERRNO
, r
, "FastCGI: incomplete headers "
2285 "(%d bytes) received from server \"%s\"", fr
->header
->nelts
, fr
->fs_path
);
2289 case SCAN_CGI_BAD_HEADER
:
2291 rv
= HTTP_INTERNAL_SERVER_ERROR
;
2297 rv
= HTTP_INTERNAL_SERVER_ERROR
;
2304 static fcgi_request
*create_fcgi_request(request_rec
* const r
, const char *fs_path
)
2306 struct stat
*my_finfo
;
2307 pool
* const p
= r
->pool
;
2309 fcgi_request
* const fr
= (fcgi_request
*)ap_pcalloc(p
, sizeof(fcgi_request
));
2315 my_finfo
= (struct stat
*)ap_palloc(p
, sizeof(struct stat
));
2316 if (stat(fs_path
, my_finfo
) < 0) {
2317 ap_log_rerror(FCGI_LOG_ERR_ERRNO
, r
,
2318 "FastCGI: stat() of \"%s\" failed", fs_path
);
2324 my_finfo
= &r
->finfo
;
2325 fs_path
= r
->filename
;
2329 fs
= fcgi_util_fs_get_by_id(fs_path
, fcgi_util_get_server_uid(r
->server
),
2330 fcgi_util_get_server_gid(r
->server
));
2332 /* Its a request for a dynamic FastCGI application */
2333 const char * const err
=
2334 fcgi_util_fs_is_path_ok(p
, fs_path
, my_finfo
);
2337 ap_log_rerror(FCGI_LOG_ERR_NOERRNO
, r
, "FastCGI: invalid (dynamic) server \"%s\": %s", fs_path
, err
);
2342 fr
->serverInputBuffer
= fcgi_buf_new(p
, SERVER_BUFSIZE
);
2343 fr
->serverOutputBuffer
= fcgi_buf_new(p
, SERVER_BUFSIZE
);
2344 fr
->clientInputBuffer
= fcgi_buf_new(p
, SERVER_BUFSIZE
);
2345 fr
->clientOutputBuffer
= fcgi_buf_new(p
, SERVER_BUFSIZE
);
2346 fr
->erBufPtr
= fcgi_buf_new(p
, sizeof(FCGI_EndRequestBody
) + 1);
2347 fr
->gotHeader
= FALSE
;
2348 fr
->parseHeader
= SCAN_CGI_READING_HEADERS
;
2349 fr
->header
= ap_make_array(p
, 1, 1);
2350 fr
->fs_stderr
= NULL
;
2352 fr
->readingEndRequestBody
= FALSE
;
2354 fr
->exitStatusSet
= FALSE
;
2355 fr
->requestId
= 1; /* anything but zero is OK here */
2356 fr
->eofSent
= FALSE
;
2357 fr
->role
= FCGI_RESPONDER
;
2358 fr
->expectingClientContent
= FALSE
;
2359 fr
->keepReadingFromFcgiApp
= TRUE
;
2361 fr
->fs_path
= fs_path
;
2362 fr
->authHeaders
= ap_make_table(p
, 10);
2364 fr
->fd
= INVALID_SOCKET
;
2365 fr
->dynamic
= ((fs
== NULL
) || (fs
->directive
== APP_CLASS_DYNAMIC
)) ? TRUE
: FALSE
;
2366 fr
->using_npipe_io
= FALSE
;
2368 fr
->dynamic
= (fs
== NULL
) ? TRUE
: FALSE
;
2372 set_uid_n_gid(r
, &fr
->user
, &fr
->group
);
2378 *----------------------------------------------------------------------
2382 * This routine gets called for a request that corresponds to
2383 * a FastCGI connection. It performs the request synchronously.
2386 * Final status of request: OK or NOT_FOUND or HTTP_INTERNAL_SERVER_ERROR.
2389 * Request performed.
2391 *----------------------------------------------------------------------
2394 /* Stolen from mod_cgi.c..
2395 * KLUDGE --- for back-combatibility, we don't have to check ExecCGI
2396 * in ScriptAliased directories, which means we need to know if this
2397 * request came through ScriptAlias or not... so the Alias module
2398 * leaves a note for us.
2400 static int apache_is_scriptaliased(request_rec
*r
)
2402 const char *t
= ap_table_get(r
->notes
, "alias-forced-type");
2403 return t
&& (!strcasecmp(t
, "cgi-script"));
2406 /* If a script wants to produce its own Redirect body, it now
2407 * has to explicitly *say* "Status: 302". If it wants to use
2408 * Apache redirects say "Status: 200". See process_headers().
2410 static int post_process_for_redirects(request_rec
* const r
,
2411 const fcgi_request
* const fr
)
2413 switch(fr
->parseHeader
) {
2414 case SCAN_CGI_INT_REDIRECT
:
2416 /* @@@ There are still differences between the handling in
2417 * mod_cgi and mod_fastcgi. This needs to be revisited.
2419 /* We already read the message body (if any), so don't allow
2420 * the redirected request to think it has one. We can ignore
2421 * Transfer-Encoding, since we used REQUEST_CHUNKED_ERROR.
2424 r
->method_number
= M_GET
;
2425 ap_table_unset(r
->headers_in
, "Content-length");
2427 ap_internal_redirect_handler(ap_table_get(r
->headers_out
, "Location"), r
);
2430 case SCAN_CGI_SRV_REDIRECT
:
2431 return HTTP_MOVED_TEMPORARILY
;
2438 /******************************************************************************
2439 * Process fastcgi-script requests. Based on mod_cgi::cgi_handler().
2441 static int content_handler(request_rec
*r
)
2443 fcgi_request
*fr
= NULL
;
2448 if (strcmp(r
->handler
, "fastcgi-script"))
2451 /* Setup a new FastCGI request */
2452 if ((fr
= create_fcgi_request(r
, r
->filename
)) == NULL
)
2453 return HTTP_INTERNAL_SERVER_ERROR
;
2457 /* Setup a new FastCGI request */
2458 if ((fr
= create_fcgi_request(r
, NULL
)) == NULL
)
2459 return HTTP_INTERNAL_SERVER_ERROR
;
2463 /* If its a dynamic invocation, make sure scripts are OK here */
2464 if (fr
->dynamic
&& !(ap_allow_options(r
) & OPT_EXECCGI
) && !apache_is_scriptaliased(r
)) {
2465 ap_log_rerror(FCGI_LOG_ERR_NOERRNO
, r
,
2466 "FastCGI: \"ExecCGI Option\" is off in this directory: %s", r
->uri
);
2467 return HTTP_INTERNAL_SERVER_ERROR
;
2470 /* Process the fastcgi-script request */
2471 if ((ret
= do_work(r
, fr
)) != OK
)
2474 /* Special case redirects */
2475 ret
= post_process_for_redirects(r
, fr
);
2481 static int post_process_auth_passed_header(table
*t
, const char *key
, const char * const val
)
2483 if (strncasecmp(key
, "Variable-", 9) == 0)
2486 ap_table_setn(t
, key
, val
);
2490 static int post_process_auth_passed_compat_header(table
*t
, const char *key
, const char * const val
)
2492 if (strncasecmp(key
, "Variable-", 9) == 0)
2493 ap_table_setn(t
, key
+ 9, val
);
2498 static int post_process_auth_failed_header(table
* const t
, const char * const key
, const char * const val
)
2500 ap_table_setn(t
, key
, val
);
2504 static void post_process_auth(fcgi_request
* const fr
, const int passed
)
2506 request_rec
* const r
= fr
->r
;
2508 /* Restore the saved subprocess_env because we muddied ours up */
2509 r
->subprocess_env
= fr
->saved_subprocess_env
;
2512 if (fr
->auth_compat
) {
2513 ap_table_do((int (*)(void *, const char *, const char *))post_process_auth_passed_compat_header
,
2514 (void *)r
->subprocess_env
, fr
->authHeaders
, NULL
);
2517 ap_table_do((int (*)(void *, const char *, const char *))post_process_auth_passed_header
,
2518 (void *)r
->subprocess_env
, fr
->authHeaders
, NULL
);
2522 ap_table_do((int (*)(void *, const char *, const char *))post_process_auth_failed_header
,
2523 (void *)r
->err_headers_out
, fr
->authHeaders
, NULL
);
2526 /* @@@ Restore these.. its a hack until I rewrite the header handling */
2527 r
->status
= HTTP_OK
;
2528 r
->status_line
= NULL
;
2531 static int check_user_authentication(request_rec
*r
)
2533 int res
, authenticated
= 0;
2534 const char *password
;
2536 const fcgi_dir_config
* const dir_config
=
2537 (const fcgi_dir_config
*)ap_get_module_config(r
->per_dir_config
, &fastcgi_module
);
2539 if (dir_config
->authenticator
== NULL
)
2542 /* Get the user password */
2543 if ((res
= ap_get_basic_auth_pw(r
, &password
)) != OK
)
2546 if ((fr
= create_fcgi_request(r
, dir_config
->authenticator
)) == NULL
)
2547 return HTTP_INTERNAL_SERVER_ERROR
;
2549 /* Save the existing subprocess_env, because we're gonna muddy it up */
2550 fr
->saved_subprocess_env
= ap_copy_table(r
->pool
, r
->subprocess_env
);
2552 ap_table_setn(r
->subprocess_env
, "REMOTE_PASSWD", password
);
2553 ap_table_setn(r
->subprocess_env
, "FCGI_APACHE_ROLE", "AUTHENTICATOR");
2555 /* The FastCGI Protocol doesn't differentiate authentication */
2556 fr
->role
= FCGI_AUTHORIZER
;
2558 /* Do we need compatibility mode? */
2559 fr
->auth_compat
= (dir_config
->authenticator_options
& FCGI_COMPAT
);
2561 if ((res
= do_work(r
, fr
)) != OK
)
2562 goto AuthenticationFailed
;
2564 authenticated
= (r
->status
== 200);
2565 post_process_auth(fr
, authenticated
);
2567 /* A redirect shouldn't be allowed during the authentication phase */
2568 if (ap_table_get(r
->headers_out
, "Location") != NULL
) {
2569 ap_log_rerror(FCGI_LOG_ERR_NOERRNO
, r
,
2570 "FastCGI: FastCgiAuthenticator \"%s\" redirected (not allowed)",
2571 dir_config
->authenticator
);
2572 goto AuthenticationFailed
;
2578 AuthenticationFailed
:
2579 if (!(dir_config
->authenticator_options
& FCGI_AUTHORITATIVE
))
2582 /* @@@ Probably should support custom_responses */
2583 ap_note_basic_auth_failure(r
);
2584 ap_log_rerror(FCGI_LOG_ERR_NOERRNO
, r
,
2585 "FastCGI: authentication failed for user \"%s\": %s",
2589 r
->connection
->user
, r
->uri
);
2592 return (res
== OK
) ? HTTP_UNAUTHORIZED
: res
;
2595 static int check_user_authorization(request_rec
*r
)
2597 int res
, authorized
= 0;
2599 const fcgi_dir_config
* const dir_config
=
2600 (const fcgi_dir_config
*)ap_get_module_config(r
->per_dir_config
, &fastcgi_module
);
2602 if (dir_config
->authorizer
== NULL
)
2605 /* @@@ We should probably honor the existing parameters to the require directive
2606 * as well as allow the definition of new ones (or use the basename of the
2607 * FastCGI server and pass the rest of the directive line), but for now keep
2610 if ((fr
= create_fcgi_request(r
, dir_config
->authorizer
)) == NULL
)
2611 return HTTP_INTERNAL_SERVER_ERROR
;
2613 /* Save the existing subprocess_env, because we're gonna muddy it up */
2614 fr
->saved_subprocess_env
= ap_copy_table(r
->pool
, r
->subprocess_env
);
2616 ap_table_setn(r
->subprocess_env
, "FCGI_APACHE_ROLE", "AUTHORIZER");
2618 fr
->role
= FCGI_AUTHORIZER
;
2620 /* Do we need compatibility mode? */
2621 fr
->auth_compat
= (dir_config
->authenticator_options
& FCGI_COMPAT
);
2623 if ((res
= do_work(r
, fr
)) != OK
)
2624 goto AuthorizationFailed
;
2626 authorized
= (r
->status
== 200);
2627 post_process_auth(fr
, authorized
);
2629 /* A redirect shouldn't be allowed during the authorization phase */
2630 if (ap_table_get(r
->headers_out
, "Location") != NULL
) {
2631 ap_log_rerror(FCGI_LOG_ERR_NOERRNO
, r
,
2632 "FastCGI: FastCgiAuthorizer \"%s\" redirected (not allowed)",
2633 dir_config
->authorizer
);
2634 goto AuthorizationFailed
;
2640 AuthorizationFailed
:
2641 if (!(dir_config
->authorizer_options
& FCGI_AUTHORITATIVE
))
2644 /* @@@ Probably should support custom_responses */
2645 ap_note_basic_auth_failure(r
);
2646 ap_log_rerror(FCGI_LOG_ERR_NOERRNO
, r
,
2647 "FastCGI: authorization failed for user \"%s\": %s",
2651 r
->connection
->user
, r
->uri
);
2654 return (res
== OK
) ? HTTP_UNAUTHORIZED
: res
;
2657 static int check_access(request_rec
*r
)
2659 int res
, access_allowed
= 0;
2661 const fcgi_dir_config
* const dir_config
=
2662 (fcgi_dir_config
*)ap_get_module_config(r
->per_dir_config
, &fastcgi_module
);
2664 if (dir_config
== NULL
|| dir_config
->access_checker
== NULL
)
2667 if ((fr
= create_fcgi_request(r
, dir_config
->access_checker
)) == NULL
)
2668 return HTTP_INTERNAL_SERVER_ERROR
;
2670 /* Save the existing subprocess_env, because we're gonna muddy it up */
2671 fr
->saved_subprocess_env
= ap_copy_table(r
->pool
, r
->subprocess_env
);
2673 ap_table_setn(r
->subprocess_env
, "FCGI_APACHE_ROLE", "ACCESS_CHECKER");
2675 /* The FastCGI Protocol doesn't differentiate access control */
2676 fr
->role
= FCGI_AUTHORIZER
;
2678 /* Do we need compatibility mode? */
2679 fr
->auth_compat
= (dir_config
->authenticator_options
& FCGI_COMPAT
);
2681 if ((res
= do_work(r
, fr
)) != OK
)
2684 access_allowed
= (r
->status
== 200);
2685 post_process_auth(fr
, access_allowed
);
2687 /* A redirect shouldn't be allowed during the access check phase */
2688 if (ap_table_get(r
->headers_out
, "Location") != NULL
) {
2689 ap_log_rerror(FCGI_LOG_ERR_NOERRNO
, r
,
2690 "FastCGI: FastCgiAccessChecker \"%s\" redirected (not allowed)",
2691 dir_config
->access_checker
);
2699 if (!(dir_config
->access_checker_options
& FCGI_AUTHORITATIVE
))
2702 /* @@@ Probably should support custom_responses */
2703 ap_log_rerror(FCGI_LOG_ERR_NOERRNO
, r
, "FastCGI: access denied: %s", r
->uri
);
2704 return (res
== OK
) ? HTTP_FORBIDDEN
: res
;
2709 # define AP_INIT_RAW_ARGS(directive, func, mconfig, where, help) \
2710 { directive, func, mconfig, where, RAW_ARGS, help }
2711 # define AP_INIT_TAKE1(directive, func, mconfig, where, help) \
2712 { directive, func, mconfig, where, TAKE1, help }
2713 # define AP_INIT_TAKE12(directive, func, mconfig, where, help) \
2714 { directive, func, mconfig, where, TAKE12, help }
2715 # define AP_INIT_FLAG(directive, func, mconfig, where, help) \
2716 { directive, func, mconfig, where, FLAG, help }
2720 static const command_rec fastcgi_cmds
[] =
2722 AP_INIT_RAW_ARGS("AppClass", fcgi_config_new_static_server
, NULL
, RSRC_CONF
, NULL
),
2723 AP_INIT_RAW_ARGS("FastCgiServer", fcgi_config_new_static_server
, NULL
, RSRC_CONF
, NULL
),
2725 AP_INIT_RAW_ARGS("ExternalAppClass", fcgi_config_new_external_server
, NULL
, RSRC_CONF
, NULL
),
2726 AP_INIT_RAW_ARGS("FastCgiExternalServer", fcgi_config_new_external_server
, NULL
, RSRC_CONF
, NULL
),
2728 AP_INIT_TAKE1("FastCgiIpcDir", fcgi_config_set_socket_dir
, NULL
, RSRC_CONF
, NULL
),
2730 AP_INIT_TAKE1("FastCgiSuexec", fcgi_config_set_wrapper
, NULL
, RSRC_CONF
, NULL
),
2731 AP_INIT_TAKE1("FastCgiWrapper", fcgi_config_set_wrapper
, NULL
, RSRC_CONF
, NULL
),
2733 AP_INIT_RAW_ARGS("FCGIConfig", fcgi_config_set_config
, NULL
, RSRC_CONF
, NULL
),
2734 AP_INIT_RAW_ARGS("FastCgiConfig", fcgi_config_set_config
, NULL
, RSRC_CONF
, NULL
),
2736 AP_INIT_TAKE12("FastCgiAuthenticator", fcgi_config_new_auth_server
,
2737 (void *)FCGI_AUTH_TYPE_AUTHENTICATOR
, ACCESS_CONF
,
2738 "a fastcgi-script path (absolute or relative to ServerRoot) followed by an optional -compat"),
2739 AP_INIT_FLAG("FastCgiAuthenticatorAuthoritative", fcgi_config_set_authoritative_slot
,
2740 (void *)XtOffsetOf(fcgi_dir_config
, authenticator_options
), ACCESS_CONF
,
2741 "Set to 'off' to allow authentication to be passed along to lower modules upon failure"),
2743 AP_INIT_TAKE12("FastCgiAuthorizer", fcgi_config_new_auth_server
,
2744 (void *)FCGI_AUTH_TYPE_AUTHORIZER
, ACCESS_CONF
,
2745 "a fastcgi-script path (absolute or relative to ServerRoot) followed by an optional -compat"),
2746 AP_INIT_FLAG("FastCgiAuthorizerAuthoritative", fcgi_config_set_authoritative_slot
,
2747 (void *)XtOffsetOf(fcgi_dir_config
, authorizer_options
), ACCESS_CONF
,
2748 "Set to 'off' to allow authorization to be passed along to lower modules upon failure"),
2750 AP_INIT_TAKE12("FastCgiAccessChecker", fcgi_config_new_auth_server
,
2751 (void *)FCGI_AUTH_TYPE_ACCESS_CHECKER
, ACCESS_CONF
,
2752 "a fastcgi-script path (absolute or relative to ServerRoot) followed by an optional -compat"),
2753 AP_INIT_FLAG("FastCgiAccessCheckerAuthoritative", fcgi_config_set_authoritative_slot
,
2754 (void *)XtOffsetOf(fcgi_dir_config
, access_checker_options
), ACCESS_CONF
,
2755 "Set to 'off' to allow access control to be passed along to lower modules upon failure"),
2761 static void register_hooks(apr_pool_t
* p
)
2763 // ap_hook_pre_config(x_pre_config, NULL, NULL, APR_HOOK_MIDDLE);
2764 ap_hook_post_config(init_module
, NULL
, NULL
, APR_HOOK_MIDDLE
);
2765 ap_hook_child_init(fcgi_child_init
, NULL
, NULL
, APR_HOOK_MIDDLE
);
2766 ap_hook_handler(content_handler
, NULL
, NULL
, APR_HOOK_MIDDLE
);
2767 ap_hook_check_user_id(check_user_authentication
, NULL
, NULL
, APR_HOOK_MIDDLE
);
2768 ap_hook_access_checker(check_access
, NULL
, NULL
, APR_HOOK_MIDDLE
);
2769 ap_hook_auth_checker(check_user_authorization
, NULL
, NULL
, APR_HOOK_MIDDLE
);
2772 module AP_MODULE_DECLARE_DATA fastcgi_module
=
2774 STANDARD20_MODULE_STUFF
,
2775 fcgi_config_create_dir_config
, /* per-directory config creator */
2776 NULL
, /* dir config merger */
2777 NULL
, /* server config creator */
2778 NULL
, /* server config merger */
2779 fastcgi_cmds
, /* command table */
2780 register_hooks
, /* set up other request processing hooks */
2783 #else /* !APACHE2 */
2785 handler_rec fastcgi_handlers
[] = {
2786 { FCGI_MAGIC_TYPE
, content_handler
},
2787 { "fastcgi-script", content_handler
},
2791 module MODULE_VAR_EXPORT fastcgi_module
= {
2792 STANDARD_MODULE_STUFF
,
2793 init_module
, /* initializer */
2794 fcgi_config_create_dir_config
, /* per-dir config creator */
2795 NULL
, /* per-dir config merger (default: override) */
2796 NULL
, /* per-server config creator */
2797 NULL
, /* per-server config merger (default: override) */
2798 fastcgi_cmds
, /* command table */
2799 fastcgi_handlers
, /* [9] content handlers */
2800 NULL
, /* [2] URI-to-filename translation */
2801 check_user_authentication
, /* [5] authenticate user_id */
2802 check_user_authorization
, /* [6] authorize user_id */
2803 check_access
, /* [4] check access (based on src & http headers) */
2804 NULL
, /* [7] check/set MIME type */
2805 NULL
, /* [8] fixups */
2806 NULL
, /* [10] logger */
2807 NULL
, /* [3] header-parser */
2808 fcgi_child_init
, /* process initialization */
2809 fcgi_child_exit
, /* process exit/cleanup */
2810 NULL
/* [1] post read-request handling */
2813 #endif /* !APACHE2 */