4 * Apache server module for FastCGI.
6 * $Id: mod_fastcgi.c,v 1.142 2002/10/12 01:52:22 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
= NULL
; /* 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
;
271 if (fcgi_socket_dir
== NULL
)
272 fcgi_socket_dir
= ap_server_root_relative(p
, DEFAULT_SOCK_DIR
);
274 /* Create Unix/Domain socket directory */
275 if ((err
= fcgi_config_make_dir(p
, fcgi_socket_dir
)))
276 ap_log_error(FCGI_LOG_ERR
, s
, "FastCGI: %s", err
);
279 /* Create Dynamic directory */
280 if ((err
= fcgi_config_make_dynamic_dir(p
, 1)))
281 ap_log_error(FCGI_LOG_ERR
, s
, "FastCGI: %s", err
);
284 /* Spawn the PM only once. Under Unix, Apache calls init() routines
285 * twice, once before detach() and once after. Win32 doesn't detach.
286 * Under DSO, DSO modules are unloaded between the two init() calls.
287 * Under Unix, the -X switch causes two calls to init() but no detach
288 * (but all subprocesses are wacked so the PM is toasted anyway)! */
291 if (ap_standalone
&& ap_restart_time
== 0)
295 /* Create the pipe for comm with the PM */
296 if (pipe(fcgi_pm_pipe
) < 0) {
297 ap_log_error(FCGI_LOG_ERR
, s
, "FastCGI: pipe() failed");
300 /* Start the Process Manager */
304 apr_proc_t
* proc
= apr_palloc(p
, sizeof(*proc
));
307 rv
= apr_proc_fork(proc
, tp
);
309 if (rv
== APR_INCHILD
)
315 else if (rv
!= APR_INPARENT
)
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
) {
467 static int set_nonblocking(const fcgi_request
* fr
, int nonblocking
)
469 if (fr
->using_npipe_io
)
473 DWORD mode
= PIPE_NOWAIT
| PIPE_READMODE_BYTE
;
474 if (SetNamedPipeHandleState((HANDLE
) fr
->fd
, &mode
, NULL
, NULL
) == 0)
476 ap_log_rerror(FCGI_LOG_ERR
, fr
->r
,
477 "FastCGI: SetNamedPipeHandleState() failed");
484 unsigned long ioctl_arg
= (nonblocking
) ? 1 : 0;
485 if (ioctlsocket(fr
->fd
, FIONBIO
, &ioctl_arg
) != 0)
487 errno
= WSAGetLastError();
488 ap_log_rerror(FCGI_LOG_ERR_ERRNO
, fr
->r
,
489 "FastCGI: ioctlsocket() failed");
499 static int set_nonblocking(const fcgi_request
* fr
, int nonblocking
)
502 int fd_flags
= fcntl(fr
->fd
, F_GETFL
, 0);
504 if (fd_flags
< 0) return -1;
506 #if defined(O_NONBLOCK)
507 nb_flag
= O_NONBLOCK
;
508 #elif defined(O_NDELAY)
510 #elif defined(FNDELAY)
513 #error "TODO - don't read from app until all data from client is posted."
516 fd_flags
= (nonblocking
) ? (fd_flags
| nb_flag
) : (fd_flags
& ~nb_flag
);
518 return fcntl(fr
->fd
, F_SETFL
, fd_flags
);
523 /*******************************************************************************
524 * Close the connection to the FastCGI server. This is normally called by
525 * do_work(), but may also be called as in request pool cleanup.
527 static void close_connection_to_fs(fcgi_request
*fr
)
531 if (fr
->fd
!= INVALID_SOCKET
)
533 set_nonblocking(fr
, FALSE
);
535 if (fr
->using_npipe_io
)
537 CloseHandle((HANDLE
) fr
->fd
);
541 /* abort the connection entirely */
542 struct linger linger
= {0, 0};
543 setsockopt(fr
->fd
, SOL_SOCKET
, SO_LINGER
, (void *) &linger
, sizeof(linger
));
547 fr
->fd
= INVALID_SOCKET
;
553 struct linger linger
= {0, 0};
554 set_nonblocking(fr
, FALSE
);
555 /* abort the connection entirely */
556 setsockopt(fr
->fd
, SOL_SOCKET
, SO_LINGER
, &linger
, sizeof(linger
));
562 if (fr
->dynamic
&& fr
->keepReadingFromFcgiApp
== FALSE
)
564 /* XXX FCGI_REQUEST_COMPLETE_JOB is only sent for requests which complete
565 * normally WRT the fcgi app. There is no data sent for
566 * connect() timeouts or requests which complete abnormally.
567 * KillDynamicProcs() and RemoveRecords() need to be looked at
568 * to be sure they can reasonably handle these cases before
569 * sending these sort of stats - theres some funk in there.
571 if (fcgi_util_ticks(&fr
->completeTime
) < 0)
573 /* there's no point to aborting the request, just log it */
574 ap_log_error(FCGI_LOG_ERR
, fr
->r
->server
, "FastCGI: can't get time of day");
582 *----------------------------------------------------------------------
586 * Call with r->parseHeader == SCAN_CGI_READING_HEADERS
587 * and initial script output in fr->header.
589 * If the initial script output does not include the header
590 * terminator ("\r\n\r\n") process_headers returns with no side
591 * effects, to be called again when more script output
592 * has been appended to fr->header.
594 * If the initial script output includes the header terminator,
595 * process_headers parses the headers and determines whether or
596 * not the remaining script output will be sent to the client.
597 * If so, process_headers sends the HTTP response headers to the
598 * client and copies any non-header script output to the output
605 * May set r->parseHeader to:
606 * SCAN_CGI_FINISHED -- headers parsed, returning script response
607 * SCAN_CGI_BAD_HEADER -- malformed header from script
608 * SCAN_CGI_INT_REDIRECT -- handler should perform internal redirect
609 * SCAN_CGI_SRV_REDIRECT -- handler should return REDIRECT
611 *----------------------------------------------------------------------
614 static const char *process_headers(request_rec
*r
, fcgi_request
*fr
)
616 char *p
, *next
, *name
, *value
;
618 int hasContentType
, hasStatus
, hasLocation
;
620 ap_assert(fr
->parseHeader
== SCAN_CGI_READING_HEADERS
);
622 if (fr
->header
== NULL
)
626 * Do we have the entire header? Scan for the blank line that
627 * terminates the header.
629 p
= (char *)fr
->header
->elts
;
630 len
= fr
->header
->nelts
;
632 while(len
-- && flag
< 2) {
642 name
= "Invalid Character";
652 /* Return (to be called later when we have more data)
653 * if we don't have an entire header. */
658 * Parse all the headers.
660 fr
->parseHeader
= SCAN_CGI_FINISHED
;
661 hasContentType
= hasStatus
= hasLocation
= FALSE
;
662 next
= (char *)fr
->header
->elts
;
664 next
= get_header_line(name
= next
, TRUE
);
668 if ((p
= strchr(name
, ':')) == NULL
) {
672 while (p
!= name
&& isspace((unsigned char)*(p
- 1))) {
679 if (strpbrk(name
, " \t") != NULL
) {
683 while (isspace((unsigned char)*value
)) {
687 if (strcasecmp(name
, "Status") == 0) {
688 int statusValue
= strtol(value
, NULL
, 10);
691 goto DuplicateNotAllowed
;
693 if (statusValue
< 0) {
694 fr
->parseHeader
= SCAN_CGI_BAD_HEADER
;
695 return ap_psprintf(r
->pool
, "invalid Status '%s'", value
);
698 r
->status
= statusValue
;
699 r
->status_line
= ap_pstrdup(r
->pool
, value
);
703 if (fr
->role
== FCGI_RESPONDER
) {
704 if (strcasecmp(name
, "Content-type") == 0) {
705 if (hasContentType
) {
706 goto DuplicateNotAllowed
;
708 hasContentType
= TRUE
;
709 r
->content_type
= ap_pstrdup(r
->pool
, value
);
713 if (strcasecmp(name
, "Location") == 0) {
715 goto DuplicateNotAllowed
;
718 ap_table_set(r
->headers_out
, "Location", value
);
722 /* If the script wants them merged, it can do it */
723 ap_table_add(r
->err_headers_out
, name
, value
);
727 ap_table_add(fr
->authHeaders
, name
, value
);
731 if (fr
->role
!= FCGI_RESPONDER
)
735 * Who responds, this handler or Apache?
738 const char *location
= ap_table_get(r
->headers_out
, "Location");
740 * Based on internal redirect handling in mod_cgi.c...
742 * If a script wants to produce its own Redirect
743 * body, it now has to explicitly *say* "Status: 302"
745 if (r
->status
== 200) {
746 if(location
[0] == '/') {
748 * Location is an relative path. This handler will
749 * consume all script output, then have Apache perform an
752 fr
->parseHeader
= SCAN_CGI_INT_REDIRECT
;
756 * Location is an absolute URL. If the script didn't
757 * produce a Content-type header, this handler will
758 * consume all script output and then have Apache generate
759 * its standard redirect response. Otherwise this handler
760 * will transmit the script's response.
762 fr
->parseHeader
= SCAN_CGI_SRV_REDIRECT
;
768 * We're responding. Send headers, buffer excess script output.
770 ap_send_http_header(r
);
772 /* We need to reinstate our timeout, send_http_header() kill()s it */
773 ap_hard_timeout("FastCGI request processing", r
);
775 if (r
->header_only
) {
776 /* we've got all we want from the server */
777 close_connection_to_fs(fr
);
778 fr
->exitStatusSet
= 1;
779 fcgi_buf_reset(fr
->clientOutputBuffer
);
780 fcgi_buf_reset(fr
->serverOutputBuffer
);
784 len
= fr
->header
->nelts
- (next
- fr
->header
->elts
);
786 ap_assert(BufferLength(fr
->clientOutputBuffer
) == 0);
787 if (BufferFree(fr
->clientOutputBuffer
) < len
) {
788 fr
->clientOutputBuffer
= fcgi_buf_new(r
->pool
, len
);
790 ap_assert(BufferFree(fr
->clientOutputBuffer
) >= len
);
792 int sent
= fcgi_buf_add_block(fr
->clientOutputBuffer
, next
, len
);
793 ap_assert(sent
== len
);
798 /* Log first line of a multi-line header */
799 if ((p
= strpbrk(name
, "\r\n")) != NULL
)
801 fr
->parseHeader
= SCAN_CGI_BAD_HEADER
;
802 return ap_psprintf(r
->pool
, "malformed header '%s'", name
);
805 fr
->parseHeader
= SCAN_CGI_BAD_HEADER
;
806 return ap_psprintf(r
->pool
, "duplicate header '%s'", name
);
810 * Read from the client filling both the FastCGI server buffer and the
811 * client buffer with the hopes of buffering the client data before
812 * making the connect() to the FastCGI server. This prevents slow
813 * clients from keeping the FastCGI server in processing longer than is
816 static int read_from_client_n_queue(fcgi_request
*fr
)
822 while (BufferFree(fr
->clientInputBuffer
) > 0 || BufferFree(fr
->serverOutputBuffer
) > 0) {
823 fcgi_protocol_queue_client_buffer(fr
);
825 if (fr
->expectingClientContent
<= 0)
828 fcgi_buf_get_free_block_info(fr
->clientInputBuffer
, &end
, &count
);
832 if ((countRead
= ap_get_client_block(fr
->r
, end
, count
)) < 0)
835 if (countRead
== 0) {
836 fr
->expectingClientContent
= 0;
839 fcgi_buf_add_update(fr
->clientInputBuffer
, countRead
);
840 ap_reset_timeout(fr
->r
);
846 static int write_to_client(fcgi_request
*fr
)
853 apr_bucket_brigade
* bde
;
854 apr_bucket_alloc_t
* const bkt_alloc
= fr
->r
->connection
->bucket_alloc
;
857 fcgi_buf_get_block_info(fr
->clientOutputBuffer
, &begin
, &count
);
861 /* If fewer than count bytes are written, an error occured.
862 * ap_bwrite() typically forces a flushed write to the client, this
863 * effectively results in a block (and short packets) - it should
864 * be fixed, but I didn't win much support for the idea on new-httpd.
865 * So, without patching Apache, the best way to deal with this is
866 * to size the fcgi_bufs to hold all of the script output (within
867 * reason) so the script can be released from having to wait around
868 * for the transmission to the client to complete. */
872 bde
= apr_brigade_create(fr
->r
->pool
, bkt_alloc
);
873 bkt
= apr_bucket_transient_create(begin
, count
, bkt_alloc
);
874 APR_BRIGADE_INSERT_TAIL(bde
, bkt
);
876 if (fr
->fs
? fr
->fs
->flush
: dynamicFlush
)
878 bkt
= apr_bucket_flush_create(bkt_alloc
);
879 APR_BRIGADE_INSERT_TAIL(bde
, bkt
);
882 rv
= ap_pass_brigade(fr
->r
->output_filters
, bde
);
884 #elif defined(RUSSIAN_APACHE)
886 rv
= (ap_rwrite(begin
, count
, fr
->r
) != count
);
890 rv
= (ap_bwrite(fr
->r
->connection
->client
, begin
, count
) != count
);
896 ap_log_rerror(FCGI_LOG_INFO_NOERRNO
, fr
->r
,
897 "FastCGI: client stopped connection before send body completed");
903 ap_reset_timeout(fr
->r
);
905 /* Don't bother with a wrapped buffer, limiting exposure to slow
906 * clients. The BUFF routines don't allow a writev from above,
907 * and don't always memcpy to minimize small write()s, this should
908 * be fixed, but I didn't win much support for the idea on
909 * new-httpd - I'll have to _prove_ its a problem first.. */
911 /* The default behaviour used to be to flush with every write, but this
912 * can tie up the FastCGI server longer than is necessary so its an option now */
914 if (fr
->fs
? fr
->fs
->flush
: dynamicFlush
)
916 #ifdef RUSSIAN_APACHE
917 rv
= ap_rflush(fr
->r
);
919 rv
= ap_bflush(fr
->r
->connection
->client
);
924 ap_log_rerror(FCGI_LOG_INFO_NOERRNO
, fr
->r
,
925 "FastCGI: client stopped connection before send body completed");
929 ap_reset_timeout(fr
->r
);
932 #endif /* !APACHE2 */
934 fcgi_buf_toss(fr
->clientOutputBuffer
, count
);
938 /*******************************************************************************
939 * Determine the user and group the wrapper should be called with.
940 * Based on code in Apache's create_argv_cmd() (util_script.c).
942 static void set_uid_n_gid(request_rec
*r
, const char **user
, const char **group
)
944 if (fcgi_wrapper
== NULL
) {
950 if (strncmp("/~", r
->uri
, 2) == 0) {
951 /* its a user dir uri, just send the ~user, and leave it to the PM */
952 char *end
= strchr(r
->uri
+ 2, '/');
955 *user
= memcpy(ap_pcalloc(r
->pool
, end
- r
->uri
), r
->uri
+ 1, end
- r
->uri
- 1);
957 *user
= ap_pstrdup(r
->pool
, r
->uri
+ 1);
961 *user
= ap_psprintf(r
->pool
, "%ld", (long) fcgi_util_get_server_uid(r
->server
));
962 *group
= ap_psprintf(r
->pool
, "%ld", (long) fcgi_util_get_server_gid(r
->server
));
966 static void send_request_complete(fcgi_request
*fr
)
968 if (fr
->completeTime
.tv_sec
)
970 struct timeval qtime
, rtime
;
972 timersub(&fr
->queueTime
, &fr
->startTime
, &qtime
);
973 timersub(&fr
->completeTime
, &fr
->queueTime
, &rtime
);
975 send_to_pm(FCGI_REQUEST_COMPLETE_JOB
, fr
->fs_path
,
977 qtime
.tv_sec
* 1000000 + qtime
.tv_usec
,
978 rtime
.tv_sec
* 1000000 + rtime
.tv_usec
);
983 /*******************************************************************************
984 * Connect to the FastCGI server.
986 static int open_connection_to_fs(fcgi_request
*fr
)
989 fd_set write_fds
, read_fds
;
991 request_rec
* const r
= fr
->r
;
992 pool
* const rp
= r
->pool
;
993 const char *socket_path
= NULL
;
994 struct sockaddr
*socket_addr
= NULL
;
995 int socket_addr_len
= 0;
997 const char *err
= NULL
;
1000 /* Create the connection point */
1003 socket_path
= fcgi_util_socket_hash_filename(rp
, fr
->fs_path
, fr
->user
, fr
->group
);
1004 socket_path
= fcgi_util_socket_make_path_absolute(rp
, socket_path
, 1);
1007 err
= fcgi_util_socket_make_domain_addr(rp
, (struct sockaddr_un
**)&socket_addr
,
1008 &socket_addr_len
, socket_path
);
1010 ap_log_rerror(FCGI_LOG_ERR
, r
,
1011 "FastCGI: failed to connect to (dynamic) server \"%s\": "
1012 "%s", fr
->fs_path
, err
);
1020 if (fr
->fs
->dest_addr
!= NULL
) {
1021 socket_addr
= fr
->fs
->dest_addr
;
1023 else if (fr
->fs
->socket_addr
) {
1024 socket_addr
= fr
->fs
->socket_addr
;
1027 socket_path
= fr
->fs
->socket_path
;
1030 socket_addr
= fr
->fs
->socket_addr
;
1032 socket_addr_len
= fr
->fs
->socket_addr_len
;
1038 if (fr
->fs
&& fr
->fs
->restartTime
)
1040 struct stat sock_stat
;
1042 if (stat(socket_path
, &sock_stat
) == 0)
1046 if (dynamicAutoUpdate
)
1048 struct stat app_stat
;
1050 /* TODO: follow sym links */
1052 if (stat(fr
->fs_path
, &app_stat
) == 0)
1055 if (fr
->fs
->startTime
< app_stat
.st_mtime
)
1057 if (sock_stat
.st_mtime
< app_stat
.st_mtime
)
1061 struct timeval tv
= {1, 0};
1064 * There's a newer one, request a restart.
1066 send_to_pm(FCGI_SERVER_RESTART_JOB
, fr
->fs_path
, fr
->user
, fr
->group
, 0, 0);
1071 /* Avoid sleep/alarm interactions */
1072 ap_select(0, NULL
, NULL
, NULL
, &tv
);
1082 send_to_pm(FCGI_SERVER_START_JOB
, fr
->fs_path
, fr
->user
, fr
->group
, 0, 0);
1084 /* wait until it looks like its running - this shouldn't take
1085 * very long at all - the exception is when the sockets are
1086 * removed out from under a running application - the loop
1087 * limit addresses this (preventing spinning) */
1089 for (i
= 10; i
> 0; i
--)
1094 fr
->fs
= fcgi_util_fs_get_by_id(fr
->fs_path
, 0, 0);
1096 if (fr
->fs
&& fr
->fs
->restartTime
)
1098 struct timeval tv
= {0, 500000};
1100 /* Avoid sleep/alarm interactions */
1101 ap_select(0, NULL
, NULL
, NULL
, &tv
);
1103 if (stat(socket_path
, &sock_stat
) == 0)
1112 ap_log_rerror(FCGI_LOG_ALERT
, r
,
1113 "FastCGI: failed to connect to (dynamic) server \"%s\": "
1114 "something is seriously wrong, any chance the "
1115 "socket/named_pipe directory was removed?, see the "
1116 "FastCgiIpcDir directive", fr
->fs_path
);
1128 HANDLE wait_npipe_mutex
;
1130 DWORD max_connect_time
= FCGI_NAMED_PIPE_CONNECT_TIMEOUT
;
1132 fr
->using_npipe_io
= TRUE
;
1136 interval
= dynamicPleaseStartDelay
* 1000;
1138 if (dynamicAppConnectTimeout
) {
1139 max_connect_time
= dynamicAppConnectTimeout
;
1144 interval
= FCGI_NAMED_PIPE_CONNECT_TIMEOUT
* 1000;
1146 if (fr
->fs
->appConnectTimeout
) {
1147 max_connect_time
= fr
->fs
->appConnectTimeout
;
1151 fcgi_util_ticks(&fr
->startTime
);
1154 // xxx this handle should live somewhere (see CloseHandle()s below too)
1155 char * wait_npipe_mutex_name
, * cp
;
1156 wait_npipe_mutex_name
= cp
= ap_pstrdup(rp
, socket_path
);
1157 while ((cp
= strchr(cp
, '\\'))) *cp
= '/';
1159 wait_npipe_mutex
= CreateMutex(NULL
, FALSE
, wait_npipe_mutex_name
);
1162 if (wait_npipe_mutex
== NULL
)
1164 ap_log_rerror(FCGI_LOG_ERR
, r
,
1165 "FastCGI: failed to connect to server \"%s\": "
1166 "can't create the WaitNamedPipe mutex", fr
->fs_path
);
1170 SetLastError(ERROR_SUCCESS
);
1172 rv
= WaitForSingleObject(wait_npipe_mutex
, max_connect_time
* 1000);
1174 if (rv
== WAIT_TIMEOUT
|| rv
== WAIT_FAILED
)
1178 send_to_pm(FCGI_REQUEST_TIMEOUT_JOB
, fr
->fs_path
, fr
->user
, fr
->group
, 0, 0);
1180 ap_log_rerror(FCGI_LOG_ERR_NOERRNO
, r
,
1181 "FastCGI: failed to connect to server \"%s\": "
1182 "wait for a npipe instance failed", fr
->fs_path
);
1183 FCGIDBG3("interval=%d, max_connect_time=%d", interval
, max_connect_time
);
1184 CloseHandle(wait_npipe_mutex
);
1188 fcgi_util_ticks(&fr
->queueTime
);
1190 connect_time
= fr
->queueTime
.tv_sec
- fr
->startTime
.tv_sec
;
1194 if (connect_time
>= interval
)
1196 send_to_pm(FCGI_REQUEST_TIMEOUT_JOB
, fr
->fs_path
, fr
->user
, fr
->group
, 0, 0);
1197 FCGIDBG4("connect_time=%d, interval=%d, max_connect_time=%d", connect_time
, interval
, max_connect_time
);
1199 if (max_connect_time
- connect_time
< interval
)
1201 interval
= max_connect_time
- connect_time
;
1206 interval
-= connect_time
* 1000;
1211 ready
= WaitNamedPipe(socket_path
, interval
);
1215 fr
->fd
= (SOCKET
) CreateFile(socket_path
,
1216 GENERIC_READ
| GENERIC_WRITE
,
1217 FILE_SHARE_READ
| FILE_SHARE_WRITE
,
1218 NULL
, // no security attributes
1219 OPEN_EXISTING
, // opens existing pipe
1220 FILE_FLAG_OVERLAPPED
,
1221 NULL
); // no template file
1223 if (fr
->fd
!= (SOCKET
) INVALID_HANDLE_VALUE
)
1225 ReleaseMutex(wait_npipe_mutex
);
1226 CloseHandle(wait_npipe_mutex
);
1227 fcgi_util_ticks(&fr
->queueTime
);
1228 FCGIDBG2("got npipe connect: %s", fr
->fs_path
);
1232 if (GetLastError() != ERROR_PIPE_BUSY
1233 && GetLastError() != ERROR_FILE_NOT_FOUND
)
1235 ap_log_rerror(FCGI_LOG_ERR
, r
,
1236 "FastCGI: failed to connect to server \"%s\": "
1237 "CreateFile() failed", fr
->fs_path
);
1241 FCGIDBG2("missed npipe connect: %s", fr
->fs_path
);
1246 send_to_pm(FCGI_REQUEST_TIMEOUT_JOB
, fr
->fs_path
, fr
->user
, fr
->group
, 0, 0);
1249 fcgi_util_ticks(&fr
->queueTime
);
1251 connect_time
= fr
->queueTime
.tv_sec
- fr
->startTime
.tv_sec
;
1253 FCGIDBG5("interval=%d, max_connect_time=%d, connect_time=%d, ready=%d", interval
, max_connect_time
, connect_time
, ready
);
1255 if (connect_time
>= max_connect_time
)
1257 ap_log_rerror(FCGI_LOG_ERR
, r
,
1258 "FastCGI: failed to connect to server \"%s\": "
1259 "CreateFile()/WaitNamedPipe() timed out", fr
->fs_path
);
1264 ReleaseMutex(wait_npipe_mutex
);
1265 CloseHandle(wait_npipe_mutex
);
1266 fr
->fd
= INVALID_SOCKET
;
1272 /* Create the socket */
1273 fr
->fd
= socket(socket_addr
->sa_family
, SOCK_STREAM
, 0);
1276 if (fr
->fd
== INVALID_SOCKET
) {
1277 errno
= WSAGetLastError(); // Not sure this is going to work as expected
1281 ap_log_rerror(FCGI_LOG_ERR_ERRNO
, r
,
1282 "FastCGI: failed to connect to server \"%s\": "
1283 "socket() failed", fr
->fs_path
);
1288 if (fr
->fd
>= FD_SETSIZE
) {
1289 ap_log_rerror(FCGI_LOG_ERR
, r
,
1290 "FastCGI: failed to connect to server \"%s\": "
1291 "socket file descriptor (%u) is larger than "
1292 "FD_SETSIZE (%u), you probably need to rebuild Apache with a "
1293 "larger FD_SETSIZE", fr
->fs_path
, fr
->fd
, FD_SETSIZE
);
1298 /* If appConnectTimeout is non-zero, setup do a non-blocking connect */
1299 if ((fr
->dynamic
&& dynamicAppConnectTimeout
) || (!fr
->dynamic
&& fr
->fs
->appConnectTimeout
)) {
1300 set_nonblocking(fr
, TRUE
);
1304 fcgi_util_ticks(&fr
->startTime
);
1308 if (connect(fr
->fd
, (struct sockaddr
*)socket_addr
, socket_addr_len
) == 0)
1309 goto ConnectionComplete
;
1313 errno
= WSAGetLastError();
1314 if (errno
!= WSAEWOULDBLOCK
) {
1315 ap_log_rerror(FCGI_LOG_ERR_ERRNO
, r
,
1316 "FastCGI: failed to connect to server \"%s\": "
1317 "connect() failed", fr
->fs_path
);
1323 /* ECONNREFUSED means the listen queue is full (or there isn't one).
1324 * With dynamic I can at least make sure the PM knows this is occuring */
1325 if (fr
->dynamic
&& errno
== ECONNREFUSED
) {
1326 /* @@@ This might be better as some other "kind" of message */
1327 send_to_pm(FCGI_REQUEST_TIMEOUT_JOB
, fr
->fs_path
, fr
->user
, fr
->group
, 0, 0);
1329 errno
= ECONNREFUSED
;
1332 if (errno
!= EINPROGRESS
) {
1333 ap_log_rerror(FCGI_LOG_ERR
, r
,
1334 "FastCGI: failed to connect to server \"%s\": "
1335 "connect() failed", fr
->fs_path
);
1341 /* The connect() is non-blocking */
1347 FD_ZERO(&write_fds
);
1348 FD_SET(fr
->fd
, &write_fds
);
1349 read_fds
= write_fds
;
1350 tval
.tv_sec
= dynamicPleaseStartDelay
;
1353 status
= ap_select((fr
->fd
+1), &read_fds
, &write_fds
, NULL
, &tval
);
1357 fcgi_util_ticks(&fr
->queueTime
);
1362 /* select() timed out */
1363 send_to_pm(FCGI_REQUEST_TIMEOUT_JOB
, fr
->fs_path
, fr
->user
, fr
->group
, 0, 0);
1364 } while ((fr
->queueTime
.tv_sec
- fr
->startTime
.tv_sec
) < (int)dynamicAppConnectTimeout
);
1366 /* XXX These can be moved down when dynamic vars live is a struct */
1368 ap_log_rerror(FCGI_LOG_ERR_NOERRNO
, r
,
1369 "FastCGI: failed to connect to server \"%s\": "
1370 "connect() timed out (appConnTimeout=%dsec)",
1371 fr
->fs_path
, dynamicAppConnectTimeout
);
1376 tval
.tv_sec
= fr
->fs
->appConnectTimeout
;
1378 FD_ZERO(&write_fds
);
1379 FD_SET(fr
->fd
, &write_fds
);
1380 read_fds
= write_fds
;
1382 status
= ap_select((fr
->fd
+1), &read_fds
, &write_fds
, NULL
, &tval
);
1385 ap_log_rerror(FCGI_LOG_ERR_NOERRNO
, r
,
1386 "FastCGI: failed to connect to server \"%s\": "
1387 "connect() timed out (appConnTimeout=%dsec)",
1388 fr
->fs_path
, dynamicAppConnectTimeout
);
1395 errno
= WSAGetLastError();
1397 ap_log_rerror(FCGI_LOG_ERR_ERRNO
, r
,
1398 "FastCGI: failed to connect to server \"%s\": "
1399 "select() failed", fr
->fs_path
);
1403 if (FD_ISSET(fr
->fd
, &write_fds
) || FD_ISSET(fr
->fd
, &read_fds
)) {
1405 NET_SIZE_T len
= sizeof(error
);
1407 if (getsockopt(fr
->fd
, SOL_SOCKET
, SO_ERROR
, (char *)&error
, &len
) < 0) {
1408 /* Solaris pending error */
1410 errno
= WSAGetLastError();
1412 ap_log_rerror(FCGI_LOG_ERR_ERRNO
, r
,
1413 "FastCGI: failed to connect to server \"%s\": "
1414 "select() failed (Solaris pending error)", fr
->fs_path
);
1419 /* Berkeley-derived pending error */
1421 ap_log_rerror(FCGI_LOG_ERR_ERRNO
, r
,
1422 "FastCGI: failed to connect to server \"%s\": "
1423 "select() failed (pending error)", fr
->fs_path
);
1429 errno
= WSAGetLastError();
1431 ap_log_rerror(FCGI_LOG_ERR_ERRNO
, r
,
1432 "FastCGI: failed to connect to server \"%s\": "
1433 "select() error - THIS CAN'T HAPPEN!", fr
->fs_path
);
1438 /* Return to blocking mode if it was set up */
1439 if ((fr
->dynamic
&& dynamicAppConnectTimeout
) || (!fr
->dynamic
&& fr
->fs
->appConnectTimeout
)) {
1440 set_nonblocking(fr
, FALSE
);
1444 if (socket_addr
->sa_family
== AF_INET
) {
1445 /* We shouldn't be sending small packets and there's no application
1446 * level ack of the data we send, so disable Nagle */
1448 setsockopt(fr
->fd
, IPPROTO_TCP
, TCP_NODELAY
, (char *)&set
, sizeof(set
));
1455 static void sink_client_data(fcgi_request
*fr
)
1460 fcgi_buf_reset(fr
->clientInputBuffer
);
1461 fcgi_buf_get_free_block_info(fr
->clientInputBuffer
, &base
, &size
);
1462 while (ap_get_client_block(fr
->r
, base
, size
) > 0);
1465 static apcb_t
cleanup(void *data
)
1467 fcgi_request
* const fr
= (fcgi_request
*) data
;
1469 if (fr
== NULL
) return APCB_OK
;
1471 /* its more than likely already run, but... */
1472 close_connection_to_fs(fr
);
1474 send_request_complete(fr
);
1476 if (fr
->fs_stderr_len
) {
1477 ap_log_rerror(FCGI_LOG_ERR_NOERRNO
, fr
->r
,
1478 "FastCGI: server \"%s\" stderr: %s", fr
->fs_path
, fr
->fs_stderr
);
1485 static int npipe_io(fcgi_request
* const fr
)
1487 request_rec
* const r
= fr
->r
;
1498 state
= STATE_ENV_SEND
;
1499 env_status env_status
;
1501 int dynamic_first_recv
= fr
->dynamic
;
1502 int idle_timeout
= fr
->dynamic
? dynamic_idle_timeout
: fr
->fs
->idle_timeout
;
1503 int send_pending
= 0;
1504 int recv_pending
= 0;
1505 int client_send
= 0;
1507 OVERLAPPED rov
= { 0 };
1508 OVERLAPPED sov
= { 0 };
1510 struct timeval timeout
;
1511 struct timeval dynamic_last_io_time
= {0, 0};
1513 pool
* const rp
= r
->pool
;
1515 DWORD recv_count
= 0;
1517 if (fr
->role
== FCGI_RESPONDER
)
1519 client_recv
= (fr
->expectingClientContent
!= 0);
1522 idle_timeout
= fr
->dynamic
? dynamic_idle_timeout
: fr
->fs
->idle_timeout
;
1524 env_status
.envp
= NULL
;
1526 events
[0] = CreateEvent(NULL
, TRUE
, FALSE
, NULL
);
1527 events
[1] = CreateEvent(NULL
, TRUE
, FALSE
, NULL
);
1528 sov
.hEvent
= events
[0];
1529 rov
.hEvent
= events
[1];
1533 dynamic_last_io_time
= fr
->startTime
;
1535 if (dynamicAppConnectTimeout
)
1537 struct timeval qwait
;
1538 timersub(&fr
->queueTime
, &fr
->startTime
, &qwait
);
1539 dynamic_first_recv
= qwait
.tv_sec
/ dynamicPleaseStartDelay
+ 1;
1543 ap_hard_timeout("FastCGI request processing", r
);
1545 while (state
!= STATE_CLIENT_SEND
)
1551 case STATE_ENV_SEND
:
1553 if (fcgi_protocol_queue_env(r
, fr
, &env_status
) == 0)
1558 state
= STATE_CLIENT_RECV
;
1562 case STATE_CLIENT_RECV
:
1564 if (read_from_client_n_queue(fr
) != OK
)
1566 state
= STATE_CLIENT_ERROR
;
1572 state
= STATE_SERVER_SEND
;
1579 case STATE_SERVER_SEND
:
1581 if (! send_pending
&& BufferLength(fr
->serverOutputBuffer
))
1583 Buffer
* b
= fr
->serverOutputBuffer
;
1586 len
= min(b
->length
, b
->data
+ b
->size
- b
->begin
);
1588 if (WriteFile((HANDLE
) fr
->fd
, b
->begin
, len
, &sent
, &sov
))
1590 fcgi_buf_removed(b
, sent
);
1591 ResetEvent(sov
.hEvent
);
1593 else if (GetLastError() == ERROR_IO_PENDING
)
1599 ap_log_rerror(FCGI_LOG_ERR
, r
, "FastCGI: comm with server "
1600 "\"%s\" aborted: WriteFile() failed", fr
->fs_path
);
1601 state
= STATE_ERROR
;
1608 case STATE_SERVER_RECV
:
1611 * Only get more data when the serverInputBuffer is empty.
1612 * Otherwise we may already have the END_REQUEST buffered
1613 * (but not processed) and a read on a closed named pipe
1614 * results in an error that is normally abnormal.
1616 if (! recv_pending
&& BufferLength(fr
->serverInputBuffer
) == 0)
1618 Buffer
* b
= fr
->serverInputBuffer
;
1621 len
= min(b
->size
- b
->length
, b
->data
+ b
->size
- b
->end
);
1623 if (ReadFile((HANDLE
) fr
->fd
, b
->end
, len
, &rcvd
, &rov
))
1625 fcgi_buf_added(b
, rcvd
);
1627 ResetEvent(rov
.hEvent
);
1628 if (dynamic_first_recv
)
1630 dynamic_first_recv
= 0;
1633 else if (GetLastError() == ERROR_IO_PENDING
)
1637 else if (GetLastError() == ERROR_HANDLE_EOF
)
1639 fr
->keepReadingFromFcgiApp
= FALSE
;
1640 state
= STATE_CLIENT_SEND
;
1641 ResetEvent(rov
.hEvent
);
1644 else if (GetLastError() == ERROR_NO_DATA
)
1650 ap_log_rerror(FCGI_LOG_ERR
, r
, "FastCGI: comm with server "
1651 "\"%s\" aborted: ReadFile() failed", fr
->fs_path
);
1652 state
= STATE_ERROR
;
1659 case STATE_CLIENT_SEND
:
1661 if (client_send
|| ! BufferFree(fr
->clientOutputBuffer
))
1663 if (write_to_client(fr
))
1665 state
= STATE_CLIENT_ERROR
;
1679 if (state
== STATE_CLIENT_ERROR
|| state
== STATE_ERROR
)
1684 /* setup the io timeout */
1686 if (BufferLength(fr
->clientOutputBuffer
))
1688 /* don't let client data sit too long, it might be a push */
1690 timeout
.tv_usec
= 100000;
1692 else if (dynamic_first_recv
)
1695 struct timeval qwait
;
1697 fcgi_util_ticks(&fr
->queueTime
);
1701 /* a send() succeeded last pass */
1702 dynamic_last_io_time
= fr
->queueTime
;
1706 /* timed out last pass */
1707 struct timeval idle_time
;
1709 timersub(&fr
->queueTime
, &dynamic_last_io_time
, &idle_time
);
1711 if (idle_time
.tv_sec
> idle_timeout
)
1713 send_to_pm(FCGI_REQUEST_TIMEOUT_JOB
, fr
->fs_path
, fr
->user
, fr
->group
, 0, 0);
1714 ap_log_rerror(FCGI_LOG_ERR_NOERRNO
, r
, "FastCGI: comm "
1715 "with (dynamic) server \"%s\" aborted: (first read) "
1716 "idle timeout (%d sec)", fr
->fs_path
, idle_timeout
);
1717 state
= STATE_ERROR
;
1722 timersub(&fr
->queueTime
, &fr
->startTime
, &qwait
);
1724 delay
= dynamic_first_recv
* dynamicPleaseStartDelay
;
1726 if (qwait
.tv_sec
< delay
)
1728 timeout
.tv_sec
= delay
;
1729 timeout
.tv_usec
= 100000; /* fudge for select() slop */
1730 timersub(&timeout
, &qwait
, &timeout
);
1734 /* Killed time somewhere.. client read? */
1735 send_to_pm(FCGI_REQUEST_TIMEOUT_JOB
, fr
->fs_path
, fr
->user
, fr
->group
, 0, 0);
1736 dynamic_first_recv
= qwait
.tv_sec
/ dynamicPleaseStartDelay
+ 1;
1737 timeout
.tv_sec
= dynamic_first_recv
* dynamicPleaseStartDelay
;
1738 timeout
.tv_usec
= 100000; /* fudge for select() slop */
1739 timersub(&timeout
, &qwait
, &timeout
);
1744 timeout
.tv_sec
= idle_timeout
;
1745 timeout
.tv_usec
= 0;
1748 /* require a pended recv otherwise the app can deadlock */
1751 msec_timeout
= timeout
.tv_sec
* 1000 + timeout
.tv_usec
/ 1000;
1753 rv
= WaitForMultipleObjects(2, events
, FALSE
, msec_timeout
);
1755 if (rv
== WAIT_TIMEOUT
)
1759 if (BufferLength(fr
->clientOutputBuffer
))
1763 else if (dynamic_first_recv
)
1765 struct timeval qwait
;
1767 fcgi_util_ticks(&fr
->queueTime
);
1768 timersub(&fr
->queueTime
, &fr
->startTime
, &qwait
);
1770 send_to_pm(FCGI_REQUEST_TIMEOUT_JOB
, fr
->fs_path
, fr
->user
, fr
->group
, 0, 0);
1772 dynamic_first_recv
= qwait
.tv_sec
/ dynamicPleaseStartDelay
+ 1;
1776 ap_log_rerror(FCGI_LOG_ERR_NOERRNO
, r
, "FastCGI: comm with "
1777 "server \"%s\" aborted: idle timeout (%d sec)",
1778 fr
->fs_path
, idle_timeout
);
1779 state
= STATE_ERROR
;
1785 int i
= rv
- WAIT_OBJECT_0
;
1793 if (GetOverlappedResult((HANDLE
) fr
->fd
, &sov
, &sent
, FALSE
))
1796 ResetEvent(sov
.hEvent
);
1797 fcgi_buf_removed(fr
->serverOutputBuffer
, sent
);
1801 ap_log_rerror(FCGI_LOG_ERR
, r
, "FastCGI: comm with server "
1802 "\"%s\" aborted: GetOverlappedResult() failed", fr
->fs_path
);
1803 state
= STATE_ERROR
;
1814 ResetEvent(rov
.hEvent
);
1816 if (GetOverlappedResult((HANDLE
) fr
->fd
, &rov
, &rcvd
, FALSE
))
1818 fcgi_buf_added(fr
->serverInputBuffer
, rcvd
);
1819 if (dynamic_first_recv
)
1821 dynamic_first_recv
= 0;
1826 ap_log_rerror(FCGI_LOG_ERR
, r
, "FastCGI: comm with server "
1827 "\"%s\" aborted: GetOverlappedResult() failed", fr
->fs_path
);
1828 state
= STATE_ERROR
;
1835 if (fcgi_protocol_dequeue(rp
, fr
))
1837 state
= STATE_ERROR
;
1841 if (fr
->parseHeader
== SCAN_CGI_READING_HEADERS
)
1843 const char * err
= process_headers(r
, fr
);
1846 ap_log_rerror(FCGI_LOG_ERR_NOERRNO
, r
,
1847 "FastCGI: comm with server \"%s\" aborted: "
1848 "error parsing headers: %s", fr
->fs_path
, err
);
1849 state
= STATE_ERROR
;
1854 if (fr
->exitStatusSet
)
1856 fr
->keepReadingFromFcgiApp
= FALSE
;
1857 state
= STATE_CLIENT_SEND
;
1862 if (! fr
->exitStatusSet
|| ! fr
->eofSent
)
1864 CancelIo((HANDLE
) fr
->fd
);
1867 CloseHandle(rov
.hEvent
);
1868 CloseHandle(sov
.hEvent
);
1870 return (state
== STATE_ERROR
);
1874 static int socket_io(fcgi_request
* const fr
)
1887 state
= STATE_ENV_SEND
;
1889 request_rec
* const r
= fr
->r
;
1891 struct timeval timeout
;
1892 struct timeval dynamic_last_io_time
= {0, 0};
1895 int nfds
= fr
->fd
+ 1;
1896 int select_status
= 1;
1899 int dynamic_first_recv
= fr
->dynamic
? 1 : 0;
1900 int client_send
= FALSE
;
1901 int client_recv
= FALSE
;
1905 if (fr
->role
== FCGI_RESPONDER
)
1907 client_recv
= (fr
->expectingClientContent
!= 0);
1910 idle_timeout
= fr
->dynamic
? dynamic_idle_timeout
: fr
->fs
->idle_timeout
;
1916 dynamic_last_io_time
= fr
->startTime
;
1918 if (dynamicAppConnectTimeout
)
1920 struct timeval qwait
;
1921 timersub(&fr
->queueTime
, &fr
->startTime
, &qwait
);
1922 dynamic_first_recv
= qwait
.tv_sec
/ dynamicPleaseStartDelay
+ 1;
1926 ap_hard_timeout("FastCGI request processing", r
);
1928 set_nonblocking(fr
, TRUE
);
1933 FD_ZERO(&write_set
);
1937 case STATE_ENV_SEND
:
1939 if (fcgi_protocol_queue_env(r
, fr
, &env
) == 0)
1944 state
= STATE_CLIENT_RECV
;
1948 case STATE_CLIENT_RECV
:
1950 if (read_from_client_n_queue(fr
))
1952 state
= STATE_CLIENT_ERROR
;
1958 state
= STATE_SERVER_SEND
;
1965 case STATE_SERVER_SEND
:
1967 if (BufferLength(fr
->serverOutputBuffer
))
1969 FD_SET(fr
->fd
, &write_set
);
1973 ap_assert(fr
->eofSent
);
1974 state
= STATE_SERVER_RECV
;
1979 case STATE_SERVER_RECV
:
1981 FD_SET(fr
->fd
, &read_set
);
1985 case STATE_CLIENT_SEND
:
1987 if (client_send
|| ! BufferFree(fr
->clientOutputBuffer
))
1989 if (write_to_client(fr
))
1991 state
= STATE_CLIENT_ERROR
;
2001 case STATE_CLIENT_ERROR
:
2010 if (state
== STATE_CLIENT_ERROR
|| state
== STATE_ERROR
)
2015 /* setup the io timeout */
2017 if (BufferLength(fr
->clientOutputBuffer
))
2019 /* don't let client data sit too long, it might be a push */
2021 timeout
.tv_usec
= 100000;
2023 else if (dynamic_first_recv
)
2026 struct timeval qwait
;
2028 fcgi_util_ticks(&fr
->queueTime
);
2032 /* a send() succeeded last pass */
2033 dynamic_last_io_time
= fr
->queueTime
;
2037 /* timed out last pass */
2038 struct timeval idle_time
;
2040 timersub(&fr
->queueTime
, &dynamic_last_io_time
, &idle_time
);
2042 if (idle_time
.tv_sec
> idle_timeout
)
2044 send_to_pm(FCGI_REQUEST_TIMEOUT_JOB
, fr
->fs_path
, fr
->user
, fr
->group
, 0, 0);
2045 ap_log_rerror(FCGI_LOG_ERR_NOERRNO
, r
, "FastCGI: comm "
2046 "with (dynamic) server \"%s\" aborted: (first read) "
2047 "idle timeout (%d sec)", fr
->fs_path
, idle_timeout
);
2048 state
= STATE_ERROR
;
2053 timersub(&fr
->queueTime
, &fr
->startTime
, &qwait
);
2055 delay
= dynamic_first_recv
* dynamicPleaseStartDelay
;
2057 FCGIDBG5("qwait=%ld.%06ld delay=%d first_recv=%d", qwait
.tv_sec
, qwait
.tv_usec
, delay
, dynamic_first_recv
);
2059 if (qwait
.tv_sec
< delay
)
2061 timeout
.tv_sec
= delay
;
2062 timeout
.tv_usec
= 100000; /* fudge for select() slop */
2063 timersub(&timeout
, &qwait
, &timeout
);
2067 /* Killed time somewhere.. client read? */
2068 send_to_pm(FCGI_REQUEST_TIMEOUT_JOB
, fr
->fs_path
, fr
->user
, fr
->group
, 0, 0);
2069 dynamic_first_recv
= qwait
.tv_sec
/ dynamicPleaseStartDelay
+ 1;
2070 timeout
.tv_sec
= dynamic_first_recv
* dynamicPleaseStartDelay
;
2071 timeout
.tv_usec
= 100000; /* fudge for select() slop */
2072 timersub(&timeout
, &qwait
, &timeout
);
2077 timeout
.tv_sec
= idle_timeout
;
2078 timeout
.tv_usec
= 0;
2081 /* wait on the socket */
2082 select_status
= ap_select(nfds
, &read_set
, &write_set
, NULL
, &timeout
);
2084 if (select_status
< 0)
2086 ap_log_rerror(FCGI_LOG_ERR_ERRNO
, r
, "FastCGI: comm with server "
2087 "\"%s\" aborted: select() failed", fr
->fs_path
);
2088 state
= STATE_ERROR
;
2092 if (select_status
== 0)
2094 /* select() timeout */
2096 if (BufferLength(fr
->clientOutputBuffer
))
2098 if (fr
->role
== FCGI_RESPONDER
)
2103 else if (dynamic_first_recv
)
2105 struct timeval qwait
;
2107 fcgi_util_ticks(&fr
->queueTime
);
2108 timersub(&fr
->queueTime
, &fr
->startTime
, &qwait
);
2110 send_to_pm(FCGI_REQUEST_TIMEOUT_JOB
, fr
->fs_path
, fr
->user
, fr
->group
, 0, 0);
2112 dynamic_first_recv
= qwait
.tv_sec
/ dynamicPleaseStartDelay
+ 1;
2117 ap_log_rerror(FCGI_LOG_ERR_NOERRNO
, r
, "FastCGI: comm with "
2118 "server \"%s\" aborted: idle timeout (%d sec)",
2119 fr
->fs_path
, idle_timeout
);
2120 state
= STATE_ERROR
;
2124 if (FD_ISSET(fr
->fd
, &write_set
))
2126 /* send to the server */
2128 rv
= fcgi_buf_socket_send(fr
->serverOutputBuffer
, fr
->fd
);
2132 ap_log_rerror(FCGI_LOG_ERR
, r
, "FastCGI: comm with server "
2133 "\"%s\" aborted: write failed", fr
->fs_path
);
2134 state
= STATE_ERROR
;
2139 if (FD_ISSET(fr
->fd
, &read_set
))
2141 /* recv from the server */
2143 if (dynamic_first_recv
)
2145 dynamic_first_recv
= 0;
2146 fcgi_util_ticks(&fr
->queueTime
);
2149 rv
= fcgi_buf_socket_recv(fr
->serverInputBuffer
, fr
->fd
);
2153 ap_log_rerror(FCGI_LOG_ERR
, r
, "FastCGI: comm with server "
2154 "\"%s\" aborted: read failed", fr
->fs_path
);
2155 state
= STATE_ERROR
;
2161 fr
->keepReadingFromFcgiApp
= FALSE
;
2162 state
= STATE_CLIENT_SEND
;
2167 if (fcgi_protocol_dequeue(rp
, fr
))
2169 state
= STATE_ERROR
;
2173 if (fr
->parseHeader
== SCAN_CGI_READING_HEADERS
)
2175 const char * err
= process_headers(r
, fr
);
2178 ap_log_rerror(FCGI_LOG_ERR_NOERRNO
, r
,
2179 "FastCGI: comm with server \"%s\" aborted: "
2180 "error parsing headers: %s", fr
->fs_path
, err
);
2181 state
= STATE_ERROR
;
2186 if (fr
->exitStatusSet
)
2188 fr
->keepReadingFromFcgiApp
= FALSE
;
2189 state
= STATE_CLIENT_SEND
;
2194 return (state
== STATE_ERROR
);
2198 /*----------------------------------------------------------------------
2199 * This is the core routine for moving data between the FastCGI
2200 * application and the Web server's client.
2202 static int do_work(request_rec
* const r
, fcgi_request
* const fr
)
2207 fcgi_protocol_queue_begin_request(fr
);
2209 if (fr
->role
== FCGI_RESPONDER
)
2211 rv
= ap_setup_client_block(r
, REQUEST_CHUNKED_ERROR
);
2218 fr
->expectingClientContent
= ap_should_client_block(r
);
2222 ap_register_cleanup(rp
, (void *)fr
, cleanup
, ap_null_cleanup
);
2223 ap_unblock_alarms();
2225 ap_hard_timeout("connect() to FastCGI server", r
);
2227 /* Connect to the FastCGI Application */
2228 if (open_connection_to_fs(fr
) != FCGI_OK
)
2231 return HTTP_INTERNAL_SERVER_ERROR
;
2235 if (fr
->using_npipe_io
)
2245 /* comm with the server is done */
2246 close_connection_to_fs(fr
);
2248 if (fr
->role
== FCGI_RESPONDER
)
2250 sink_client_data(fr
);
2253 while (rv
== 0 && BufferLength(fr
->serverInputBuffer
) || BufferLength(fr
->clientOutputBuffer
))
2255 if (fcgi_protocol_dequeue(rp
, fr
))
2257 rv
= HTTP_INTERNAL_SERVER_ERROR
;
2260 if (fr
->parseHeader
== SCAN_CGI_READING_HEADERS
)
2262 const char * err
= process_headers(r
, fr
);
2265 ap_log_rerror(FCGI_LOG_ERR_NOERRNO
, r
,
2266 "FastCGI: comm with server \"%s\" aborted: "
2267 "error parsing headers: %s", fr
->fs_path
, err
);
2268 rv
= HTTP_INTERNAL_SERVER_ERROR
;
2272 if (fr
->role
== FCGI_RESPONDER
)
2274 if (write_to_client(fr
))
2281 fcgi_buf_reset(fr
->clientOutputBuffer
);
2285 switch (fr
->parseHeader
)
2287 case SCAN_CGI_FINISHED
:
2289 if (fr
->role
== FCGI_RESPONDER
)
2291 /* RUSSIAN_APACHE requires rflush() over bflush() */
2294 ap_bgetopt(r
->connection
->client
, BO_BYTECT
, &r
->bytes_sent
);
2300 case SCAN_CGI_INT_REDIRECT
:
2301 case SCAN_CGI_SRV_REDIRECT
:
2305 case SCAN_CGI_READING_HEADERS
:
2307 ap_log_rerror(FCGI_LOG_ERR_NOERRNO
, r
, "FastCGI: incomplete headers "
2308 "(%d bytes) received from server \"%s\"", fr
->header
->nelts
, fr
->fs_path
);
2312 case SCAN_CGI_BAD_HEADER
:
2314 rv
= HTTP_INTERNAL_SERVER_ERROR
;
2320 rv
= HTTP_INTERNAL_SERVER_ERROR
;
2327 static fcgi_request
*create_fcgi_request(request_rec
* const r
, const char *path
)
2329 const char *fs_path
;
2330 pool
* const p
= r
->pool
;
2332 fcgi_request
* const fr
= (fcgi_request
*)ap_pcalloc(p
, sizeof(fcgi_request
));
2334 fs_path
= path
? path
: r
->filename
;
2336 fs
= fcgi_util_fs_get_by_id(fs_path
, fcgi_util_get_server_uid(r
->server
),
2337 fcgi_util_get_server_gid(r
->server
));
2341 struct stat
*my_finfo
;
2348 /* AP2: its bogus that we don't make use of r->finfo, but
2349 * its an apr_finfo_t and there is no apr_os_finfo_get() */
2351 my_finfo
= &r
->finfo
;
2356 my_finfo
= (struct stat
*) ap_palloc(p
, sizeof(struct stat
));
2358 if (stat(fs_path
, my_finfo
) < 0)
2360 ap_log_rerror(FCGI_LOG_ERR_ERRNO
, r
,
2361 "FastCGI: stat() of \"%s\" failed", fs_path
);
2366 err
= fcgi_util_fs_is_path_ok(p
, fs_path
, my_finfo
);
2370 ap_log_rerror(FCGI_LOG_ERR_NOERRNO
, r
,
2371 "FastCGI: invalid (dynamic) server \"%s\": %s", fs_path
, err
);
2376 fr
->serverInputBuffer
= fcgi_buf_new(p
, SERVER_BUFSIZE
);
2377 fr
->serverOutputBuffer
= fcgi_buf_new(p
, SERVER_BUFSIZE
);
2378 fr
->clientInputBuffer
= fcgi_buf_new(p
, SERVER_BUFSIZE
);
2379 fr
->clientOutputBuffer
= fcgi_buf_new(p
, SERVER_BUFSIZE
);
2380 fr
->erBufPtr
= fcgi_buf_new(p
, sizeof(FCGI_EndRequestBody
) + 1);
2381 fr
->gotHeader
= FALSE
;
2382 fr
->parseHeader
= SCAN_CGI_READING_HEADERS
;
2383 fr
->header
= ap_make_array(p
, 1, 1);
2384 fr
->fs_stderr
= NULL
;
2386 fr
->readingEndRequestBody
= FALSE
;
2388 fr
->exitStatusSet
= FALSE
;
2389 fr
->requestId
= 1; /* anything but zero is OK here */
2390 fr
->eofSent
= FALSE
;
2391 fr
->role
= FCGI_RESPONDER
;
2392 fr
->expectingClientContent
= FALSE
;
2393 fr
->keepReadingFromFcgiApp
= TRUE
;
2395 fr
->fs_path
= fs_path
;
2396 fr
->authHeaders
= ap_make_table(p
, 10);
2398 fr
->fd
= INVALID_SOCKET
;
2399 fr
->dynamic
= ((fs
== NULL
) || (fs
->directive
== APP_CLASS_DYNAMIC
)) ? TRUE
: FALSE
;
2400 fr
->using_npipe_io
= FALSE
;
2402 fr
->dynamic
= (fs
== NULL
) ? TRUE
: FALSE
;
2406 set_uid_n_gid(r
, &fr
->user
, &fr
->group
);
2412 *----------------------------------------------------------------------
2416 * This routine gets called for a request that corresponds to
2417 * a FastCGI connection. It performs the request synchronously.
2420 * Final status of request: OK or NOT_FOUND or HTTP_INTERNAL_SERVER_ERROR.
2423 * Request performed.
2425 *----------------------------------------------------------------------
2428 /* Stolen from mod_cgi.c..
2429 * KLUDGE --- for back-combatibility, we don't have to check ExecCGI
2430 * in ScriptAliased directories, which means we need to know if this
2431 * request came through ScriptAlias or not... so the Alias module
2432 * leaves a note for us.
2434 static int apache_is_scriptaliased(request_rec
*r
)
2436 const char *t
= ap_table_get(r
->notes
, "alias-forced-type");
2437 return t
&& (!strcasecmp(t
, "cgi-script"));
2440 /* If a script wants to produce its own Redirect body, it now
2441 * has to explicitly *say* "Status: 302". If it wants to use
2442 * Apache redirects say "Status: 200". See process_headers().
2444 static int post_process_for_redirects(request_rec
* const r
,
2445 const fcgi_request
* const fr
)
2447 switch(fr
->parseHeader
) {
2448 case SCAN_CGI_INT_REDIRECT
:
2450 /* @@@ There are still differences between the handling in
2451 * mod_cgi and mod_fastcgi. This needs to be revisited.
2453 /* We already read the message body (if any), so don't allow
2454 * the redirected request to think it has one. We can ignore
2455 * Transfer-Encoding, since we used REQUEST_CHUNKED_ERROR.
2458 r
->method_number
= M_GET
;
2459 ap_table_unset(r
->headers_in
, "Content-length");
2461 ap_internal_redirect_handler(ap_table_get(r
->headers_out
, "Location"), r
);
2464 case SCAN_CGI_SRV_REDIRECT
:
2465 return HTTP_MOVED_TEMPORARILY
;
2472 /******************************************************************************
2473 * Process fastcgi-script requests. Based on mod_cgi::cgi_handler().
2475 static int content_handler(request_rec
*r
)
2477 fcgi_request
*fr
= NULL
;
2481 if (strcmp(r
->handler
, FASTCGI_HANDLER_NAME
))
2485 /* Setup a new FastCGI request */
2486 if ((fr
= create_fcgi_request(r
, NULL
)) == NULL
)
2487 return HTTP_INTERNAL_SERVER_ERROR
;
2489 /* If its a dynamic invocation, make sure scripts are OK here */
2490 if (fr
->dynamic
&& !(ap_allow_options(r
) & OPT_EXECCGI
) && !apache_is_scriptaliased(r
)) {
2491 ap_log_rerror(FCGI_LOG_ERR_NOERRNO
, r
,
2492 "FastCGI: \"ExecCGI Option\" is off in this directory: %s", r
->uri
);
2493 return HTTP_INTERNAL_SERVER_ERROR
;
2496 /* Process the fastcgi-script request */
2497 if ((ret
= do_work(r
, fr
)) != OK
)
2500 /* Special case redirects */
2501 ret
= post_process_for_redirects(r
, fr
);
2507 static int post_process_auth_passed_header(table
*t
, const char *key
, const char * const val
)
2509 if (strncasecmp(key
, "Variable-", 9) == 0)
2512 ap_table_setn(t
, key
, val
);
2516 static int post_process_auth_passed_compat_header(table
*t
, const char *key
, const char * const val
)
2518 if (strncasecmp(key
, "Variable-", 9) == 0)
2519 ap_table_setn(t
, key
+ 9, val
);
2524 static int post_process_auth_failed_header(table
* const t
, const char * const key
, const char * const val
)
2526 ap_table_setn(t
, key
, val
);
2530 static void post_process_auth(fcgi_request
* const fr
, const int passed
)
2532 request_rec
* const r
= fr
->r
;
2534 /* Restore the saved subprocess_env because we muddied ours up */
2535 r
->subprocess_env
= fr
->saved_subprocess_env
;
2538 if (fr
->auth_compat
) {
2539 ap_table_do((int (*)(void *, const char *, const char *))post_process_auth_passed_compat_header
,
2540 (void *)r
->subprocess_env
, fr
->authHeaders
, NULL
);
2543 ap_table_do((int (*)(void *, const char *, const char *))post_process_auth_passed_header
,
2544 (void *)r
->subprocess_env
, fr
->authHeaders
, NULL
);
2548 ap_table_do((int (*)(void *, const char *, const char *))post_process_auth_failed_header
,
2549 (void *)r
->err_headers_out
, fr
->authHeaders
, NULL
);
2552 /* @@@ Restore these.. its a hack until I rewrite the header handling */
2553 r
->status
= HTTP_OK
;
2554 r
->status_line
= NULL
;
2557 static int check_user_authentication(request_rec
*r
)
2559 int res
, authenticated
= 0;
2560 const char *password
;
2562 const fcgi_dir_config
* const dir_config
=
2563 (const fcgi_dir_config
*)ap_get_module_config(r
->per_dir_config
, &fastcgi_module
);
2565 if (dir_config
->authenticator
== NULL
)
2568 /* Get the user password */
2569 if ((res
= ap_get_basic_auth_pw(r
, &password
)) != OK
)
2572 if ((fr
= create_fcgi_request(r
, dir_config
->authenticator
)) == NULL
)
2573 return HTTP_INTERNAL_SERVER_ERROR
;
2575 /* Save the existing subprocess_env, because we're gonna muddy it up */
2576 fr
->saved_subprocess_env
= ap_copy_table(r
->pool
, r
->subprocess_env
);
2578 ap_table_setn(r
->subprocess_env
, "REMOTE_PASSWD", password
);
2579 ap_table_setn(r
->subprocess_env
, "FCGI_APACHE_ROLE", "AUTHENTICATOR");
2581 /* The FastCGI Protocol doesn't differentiate authentication */
2582 fr
->role
= FCGI_AUTHORIZER
;
2584 /* Do we need compatibility mode? */
2585 fr
->auth_compat
= (dir_config
->authenticator_options
& FCGI_COMPAT
);
2587 if ((res
= do_work(r
, fr
)) != OK
)
2588 goto AuthenticationFailed
;
2590 authenticated
= (r
->status
== 200);
2591 post_process_auth(fr
, authenticated
);
2593 /* A redirect shouldn't be allowed during the authentication phase */
2594 if (ap_table_get(r
->headers_out
, "Location") != NULL
) {
2595 ap_log_rerror(FCGI_LOG_ERR_NOERRNO
, r
,
2596 "FastCGI: FastCgiAuthenticator \"%s\" redirected (not allowed)",
2597 dir_config
->authenticator
);
2598 goto AuthenticationFailed
;
2604 AuthenticationFailed
:
2605 if (!(dir_config
->authenticator_options
& FCGI_AUTHORITATIVE
))
2608 /* @@@ Probably should support custom_responses */
2609 ap_note_basic_auth_failure(r
);
2610 ap_log_rerror(FCGI_LOG_ERR_NOERRNO
, r
,
2611 "FastCGI: authentication failed for user \"%s\": %s",
2615 r
->connection
->user
, r
->uri
);
2618 return (res
== OK
) ? HTTP_UNAUTHORIZED
: res
;
2621 static int check_user_authorization(request_rec
*r
)
2623 int res
, authorized
= 0;
2625 const fcgi_dir_config
* const dir_config
=
2626 (const fcgi_dir_config
*)ap_get_module_config(r
->per_dir_config
, &fastcgi_module
);
2628 if (dir_config
->authorizer
== NULL
)
2631 /* @@@ We should probably honor the existing parameters to the require directive
2632 * as well as allow the definition of new ones (or use the basename of the
2633 * FastCGI server and pass the rest of the directive line), but for now keep
2636 if ((fr
= create_fcgi_request(r
, dir_config
->authorizer
)) == NULL
)
2637 return HTTP_INTERNAL_SERVER_ERROR
;
2639 /* Save the existing subprocess_env, because we're gonna muddy it up */
2640 fr
->saved_subprocess_env
= ap_copy_table(r
->pool
, r
->subprocess_env
);
2642 ap_table_setn(r
->subprocess_env
, "FCGI_APACHE_ROLE", "AUTHORIZER");
2644 fr
->role
= FCGI_AUTHORIZER
;
2646 /* Do we need compatibility mode? */
2647 fr
->auth_compat
= (dir_config
->authorizer_options
& FCGI_COMPAT
);
2649 if ((res
= do_work(r
, fr
)) != OK
)
2650 goto AuthorizationFailed
;
2652 authorized
= (r
->status
== 200);
2653 post_process_auth(fr
, authorized
);
2655 /* A redirect shouldn't be allowed during the authorization phase */
2656 if (ap_table_get(r
->headers_out
, "Location") != NULL
) {
2657 ap_log_rerror(FCGI_LOG_ERR_NOERRNO
, r
,
2658 "FastCGI: FastCgiAuthorizer \"%s\" redirected (not allowed)",
2659 dir_config
->authorizer
);
2660 goto AuthorizationFailed
;
2666 AuthorizationFailed
:
2667 if (!(dir_config
->authorizer_options
& FCGI_AUTHORITATIVE
))
2670 /* @@@ Probably should support custom_responses */
2671 ap_note_basic_auth_failure(r
);
2672 ap_log_rerror(FCGI_LOG_ERR_NOERRNO
, r
,
2673 "FastCGI: authorization failed for user \"%s\": %s",
2677 r
->connection
->user
, r
->uri
);
2680 return (res
== OK
) ? HTTP_UNAUTHORIZED
: res
;
2683 static int check_access(request_rec
*r
)
2685 int res
, access_allowed
= 0;
2687 const fcgi_dir_config
* const dir_config
=
2688 (fcgi_dir_config
*)ap_get_module_config(r
->per_dir_config
, &fastcgi_module
);
2690 if (dir_config
== NULL
|| dir_config
->access_checker
== NULL
)
2693 if ((fr
= create_fcgi_request(r
, dir_config
->access_checker
)) == NULL
)
2694 return HTTP_INTERNAL_SERVER_ERROR
;
2696 /* Save the existing subprocess_env, because we're gonna muddy it up */
2697 fr
->saved_subprocess_env
= ap_copy_table(r
->pool
, r
->subprocess_env
);
2699 ap_table_setn(r
->subprocess_env
, "FCGI_APACHE_ROLE", "ACCESS_CHECKER");
2701 /* The FastCGI Protocol doesn't differentiate access control */
2702 fr
->role
= FCGI_AUTHORIZER
;
2704 /* Do we need compatibility mode? */
2705 fr
->auth_compat
= (dir_config
->access_checker_options
& FCGI_COMPAT
);
2707 if ((res
= do_work(r
, fr
)) != OK
)
2710 access_allowed
= (r
->status
== 200);
2711 post_process_auth(fr
, access_allowed
);
2713 /* A redirect shouldn't be allowed during the access check phase */
2714 if (ap_table_get(r
->headers_out
, "Location") != NULL
) {
2715 ap_log_rerror(FCGI_LOG_ERR_NOERRNO
, r
,
2716 "FastCGI: FastCgiAccessChecker \"%s\" redirected (not allowed)",
2717 dir_config
->access_checker
);
2725 if (!(dir_config
->access_checker_options
& FCGI_AUTHORITATIVE
))
2728 /* @@@ Probably should support custom_responses */
2729 ap_log_rerror(FCGI_LOG_ERR_NOERRNO
, r
, "FastCGI: access denied: %s", r
->uri
);
2730 return (res
== OK
) ? HTTP_FORBIDDEN
: res
;
2734 fixups(request_rec
* r
)
2736 if (fcgi_util_fs_get_by_id(r
->filename
,
2737 fcgi_util_get_server_uid(r
->server
),
2738 fcgi_util_get_server_gid(r
->server
)))
2740 r
->handler
= FASTCGI_HANDLER_NAME
;
2749 # define AP_INIT_RAW_ARGS(directive, func, mconfig, where, help) \
2750 { directive, func, mconfig, where, RAW_ARGS, help }
2751 # define AP_INIT_TAKE1(directive, func, mconfig, where, help) \
2752 { directive, func, mconfig, where, TAKE1, help }
2753 # define AP_INIT_TAKE12(directive, func, mconfig, where, help) \
2754 { directive, func, mconfig, where, TAKE12, help }
2755 # define AP_INIT_FLAG(directive, func, mconfig, where, help) \
2756 { directive, func, mconfig, where, FLAG, help }
2760 static const command_rec fastcgi_cmds
[] =
2762 AP_INIT_RAW_ARGS("AppClass", fcgi_config_new_static_server
, NULL
, RSRC_CONF
, NULL
),
2763 AP_INIT_RAW_ARGS("FastCgiServer", fcgi_config_new_static_server
, NULL
, RSRC_CONF
, NULL
),
2765 AP_INIT_RAW_ARGS("ExternalAppClass", fcgi_config_new_external_server
, NULL
, RSRC_CONF
, NULL
),
2766 AP_INIT_RAW_ARGS("FastCgiExternalServer", fcgi_config_new_external_server
, NULL
, RSRC_CONF
, NULL
),
2768 AP_INIT_TAKE1("FastCgiIpcDir", fcgi_config_set_socket_dir
, NULL
, RSRC_CONF
, NULL
),
2770 AP_INIT_TAKE1("FastCgiSuexec", fcgi_config_set_wrapper
, NULL
, RSRC_CONF
, NULL
),
2771 AP_INIT_TAKE1("FastCgiWrapper", fcgi_config_set_wrapper
, NULL
, RSRC_CONF
, NULL
),
2773 AP_INIT_RAW_ARGS("FCGIConfig", fcgi_config_set_config
, NULL
, RSRC_CONF
, NULL
),
2774 AP_INIT_RAW_ARGS("FastCgiConfig", fcgi_config_set_config
, NULL
, RSRC_CONF
, NULL
),
2776 AP_INIT_TAKE12("FastCgiAuthenticator", fcgi_config_new_auth_server
,
2777 (void *)FCGI_AUTH_TYPE_AUTHENTICATOR
, ACCESS_CONF
,
2778 "a fastcgi-script path (absolute or relative to ServerRoot) followed by an optional -compat"),
2779 AP_INIT_FLAG("FastCgiAuthenticatorAuthoritative", fcgi_config_set_authoritative_slot
,
2780 (void *)XtOffsetOf(fcgi_dir_config
, authenticator_options
), ACCESS_CONF
,
2781 "Set to 'off' to allow authentication to be passed along to lower modules upon failure"),
2783 AP_INIT_TAKE12("FastCgiAuthorizer", fcgi_config_new_auth_server
,
2784 (void *)FCGI_AUTH_TYPE_AUTHORIZER
, ACCESS_CONF
,
2785 "a fastcgi-script path (absolute or relative to ServerRoot) followed by an optional -compat"),
2786 AP_INIT_FLAG("FastCgiAuthorizerAuthoritative", fcgi_config_set_authoritative_slot
,
2787 (void *)XtOffsetOf(fcgi_dir_config
, authorizer_options
), ACCESS_CONF
,
2788 "Set to 'off' to allow authorization to be passed along to lower modules upon failure"),
2790 AP_INIT_TAKE12("FastCgiAccessChecker", fcgi_config_new_auth_server
,
2791 (void *)FCGI_AUTH_TYPE_ACCESS_CHECKER
, ACCESS_CONF
,
2792 "a fastcgi-script path (absolute or relative to ServerRoot) followed by an optional -compat"),
2793 AP_INIT_FLAG("FastCgiAccessCheckerAuthoritative", fcgi_config_set_authoritative_slot
,
2794 (void *)XtOffsetOf(fcgi_dir_config
, access_checker_options
), ACCESS_CONF
,
2795 "Set to 'off' to allow access control to be passed along to lower modules upon failure"),
2801 static void register_hooks(apr_pool_t
* p
)
2803 // ap_hook_pre_config(x_pre_config, NULL, NULL, APR_HOOK_MIDDLE);
2804 ap_hook_post_config(init_module
, NULL
, NULL
, APR_HOOK_MIDDLE
);
2805 ap_hook_child_init(fcgi_child_init
, NULL
, NULL
, APR_HOOK_MIDDLE
);
2806 ap_hook_handler(content_handler
, NULL
, NULL
, APR_HOOK_MIDDLE
);
2807 ap_hook_check_user_id(check_user_authentication
, NULL
, NULL
, APR_HOOK_MIDDLE
);
2808 ap_hook_access_checker(check_access
, NULL
, NULL
, APR_HOOK_MIDDLE
);
2809 ap_hook_auth_checker(check_user_authorization
, NULL
, NULL
, APR_HOOK_MIDDLE
);
2810 ap_hook_fixups(fixups
, NULL
, NULL
, APR_HOOK_MIDDLE
);
2813 module AP_MODULE_DECLARE_DATA fastcgi_module
=
2815 STANDARD20_MODULE_STUFF
,
2816 fcgi_config_create_dir_config
, /* per-directory config creator */
2817 NULL
, /* dir config merger */
2818 NULL
, /* server config creator */
2819 NULL
, /* server config merger */
2820 fastcgi_cmds
, /* command table */
2821 register_hooks
, /* set up other request processing hooks */
2824 #else /* !APACHE2 */
2826 handler_rec fastcgi_handlers
[] = {
2827 { FCGI_MAGIC_TYPE
, content_handler
},
2828 { FASTCGI_HANDLER_NAME
, content_handler
},
2832 module MODULE_VAR_EXPORT fastcgi_module
= {
2833 STANDARD_MODULE_STUFF
,
2834 init_module
, /* initializer */
2835 fcgi_config_create_dir_config
, /* per-dir config creator */
2836 NULL
, /* per-dir config merger (default: override) */
2837 NULL
, /* per-server config creator */
2838 NULL
, /* per-server config merger (default: override) */
2839 fastcgi_cmds
, /* command table */
2840 fastcgi_handlers
, /* [9] content handlers */
2841 NULL
, /* [2] URI-to-filename translation */
2842 check_user_authentication
, /* [5] authenticate user_id */
2843 check_user_authorization
, /* [6] authorize user_id */
2844 check_access
, /* [4] check access (based on src & http headers) */
2845 NULL
, /* [7] check/set MIME type */
2846 fixups
, /* [8] fixups */
2847 NULL
, /* [10] logger */
2848 NULL
, /* [3] header-parser */
2849 fcgi_child_init
, /* process initialization */
2850 fcgi_child_exit
, /* process exit/cleanup */
2851 NULL
/* [1] post read-request handling */
2854 #endif /* !APACHE2 */