4 * Apache server module for FastCGI.
6 * $Id: mod_fastcgi.c,v 1.144 2002/10/19 02:09:29 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
)
254 /* Register to reset to default values when the config pool is cleaned */
256 ap_register_cleanup(p
, NULL
, fcgi_config_reset_globals
, ap_null_cleanup
);
260 ap_add_version_component(p
, "mod_fastcgi/" MOD_FASTCGI_VERSION
);
262 ap_add_version_component("mod_fastcgi/" MOD_FASTCGI_VERSION
);
265 fcgi_config_set_fcgi_uid_n_gid(1);
267 /* keep these handy */
268 fcgi_config_pool
= p
;
269 fcgi_apache_main_server
= s
;
272 if (fcgi_socket_dir
== NULL
)
273 fcgi_socket_dir
= DEFAULT_SOCK_DIR
;
274 fcgi_dynamic_dir
= ap_pstrcat(p
, fcgi_socket_dir
, "dynamic", NULL
);
277 if (fcgi_socket_dir
== NULL
)
278 fcgi_socket_dir
= ap_server_root_relative(p
, DEFAULT_SOCK_DIR
);
280 /* Create Unix/Domain socket directory */
281 if ((err
= fcgi_config_make_dir(p
, fcgi_socket_dir
)))
282 ap_log_error(FCGI_LOG_ERR
, s
, "FastCGI: %s", err
);
284 /* Create Dynamic directory */
285 if ((err
= fcgi_config_make_dynamic_dir(p
, 1)))
286 ap_log_error(FCGI_LOG_ERR
, s
, "FastCGI: %s", err
);
288 /* Spawn the PM only once. Under Unix, Apache calls init() routines
289 * twice, once before detach() and once after. Win32 doesn't detach.
290 * Under DSO, DSO modules are unloaded between the two init() calls.
291 * Under Unix, the -X switch causes two calls to init() but no detach
292 * (but all subprocesses are wacked so the PM is toasted anyway)! */
297 apr_pool_userdata_get(&first_pass
, "mod_fastcgi", s
->process
->pool
);
298 if (first_pass
== NULL
)
300 apr_pool_userdata_set((const void *)1, "mod_fastcgi",
301 apr_pool_cleanup_null
, s
->process
->pool
);
307 if (ap_standalone
&& ap_restart_time
== 0)
312 /* Create the pipe for comm with the PM */
313 if (pipe(fcgi_pm_pipe
) < 0) {
314 ap_log_error(FCGI_LOG_ERR
, s
, "FastCGI: pipe() failed");
317 /* Start the Process Manager */
321 apr_proc_t
* proc
= apr_palloc(p
, sizeof(*proc
));
324 rv
= apr_proc_fork(proc
, tp
);
326 if (rv
== APR_INCHILD
)
332 else if (rv
!= APR_INPARENT
)
339 apr_pool_note_subprocess(p
, proc
, APR_KILL_ONLY_ONCE
);
343 fcgi_pm_pid
= ap_spawn_child(p
, fcgi_pm_main
, NULL
, kill_only_once
, NULL
, NULL
, NULL
);
344 if (fcgi_pm_pid
<= 0) {
345 ap_log_error(FCGI_LOG_ALERT
, s
,
346 "FastCGI: can't start the process manager, spawn_child() failed");
349 #endif /* !APACHE2 */
351 close(fcgi_pm_pipe
[0]);
359 static apcb_t
fcgi_child_exit(void * dc
)
361 static apcb_t
fcgi_child_exit(server_rec
*dc0
, pool
*dc1
)
365 /* Signal the PM thread to exit*/
366 SetEvent(fcgi_event_handles
[TERM_EVENT
]);
368 /* Waiting on pm thread to exit */
369 WaitForSingleObject(fcgi_pm_thread
, INFINITE
);
376 static void fcgi_child_init(apr_pool_t
* p
, server_rec
* dc
)
378 static void fcgi_child_init(server_rec
*dc
, pool
*p
)
382 /* Create the MBOX, TERM, and WAKE event handlers */
383 fcgi_event_handles
[0] = CreateEvent(NULL
, FALSE
, FALSE
, NULL
);
384 if (fcgi_event_handles
[0] == NULL
) {
385 ap_log_error(FCGI_LOG_ALERT
, fcgi_apache_main_server
,
386 "FastCGI: CreateEvent() failed");
388 fcgi_event_handles
[1] = CreateEvent(NULL
, FALSE
, FALSE
, NULL
);
389 if (fcgi_event_handles
[1] == NULL
) {
390 ap_log_error(FCGI_LOG_ALERT
, fcgi_apache_main_server
,
391 "FastCGI: CreateEvent() failed");
393 fcgi_event_handles
[2] = CreateEvent(NULL
, FALSE
, FALSE
, NULL
);
394 if (fcgi_event_handles
[2] == NULL
) {
395 ap_log_error(FCGI_LOG_ALERT
, fcgi_apache_main_server
,
396 "FastCGI: CreateEvent() failed");
399 /* Create the mbox mutex (PM - request threads) */
400 fcgi_dynamic_mbox_mutex
= CreateMutex(NULL
, FALSE
, NULL
);
401 if (fcgi_dynamic_mbox_mutex
== NULL
) {
402 ap_log_error(FCGI_LOG_ALERT
, fcgi_apache_main_server
,
403 "FastCGI: CreateMutex() failed");
406 /* Spawn of the process manager thread */
407 fcgi_pm_thread
= (HANDLE
) _beginthread(fcgi_pm_main
, 0, NULL
);
408 if (fcgi_pm_thread
== (HANDLE
) -1) {
409 ap_log_error(FCGI_LOG_ALERT
, fcgi_apache_main_server
,
410 "_beginthread() failed to spawn the process manager");
414 apr_pool_cleanup_register(p
, NULL
, fcgi_child_exit
, fcgi_child_exit
);
420 *----------------------------------------------------------------------
424 * Terminate a line: scan to the next newline, scan back to the
425 * first non-space character and store a terminating zero. Return
426 * the next character past the end of the newline.
428 * If the end of the string is reached, ASSERT!
430 * If the FIRST character(s) in the line are '\n' or "\r\n", the
431 * first character is replaced with a NULL and next character
432 * past the newline is returned. NOTE: this condition supercedes
433 * the processing of RFC-822 continuation lines.
435 * If continuation is set to 'TRUE', then it parses a (possible)
436 * sequence of RFC-822 continuation lines.
442 * Termination byte stored in string.
444 *----------------------------------------------------------------------
446 static char *get_header_line(char *start
, int continuation
)
451 if(p
[0] == '\r' && p
[1] == '\n') { /* If EOL in 1st 2 chars */
452 p
++; /* point to \n and stop */
453 } else if(*p
!= '\n') {
456 if(*p
== '\n' && p
[1] != ' ' && p
[1] != '\t')
461 while(*p
!= '\0' && *p
!= '\n') {
467 ap_assert(*p
!= '\0');
472 * Trim any trailing whitespace.
474 while(isspace((unsigned char)p
[-1]) && p
> start
) {
484 static int set_nonblocking(const fcgi_request
* fr
, int nonblocking
)
486 if (fr
->using_npipe_io
)
490 DWORD mode
= PIPE_NOWAIT
| PIPE_READMODE_BYTE
;
491 if (SetNamedPipeHandleState((HANDLE
) fr
->fd
, &mode
, NULL
, NULL
) == 0)
493 ap_log_rerror(FCGI_LOG_ERR
, fr
->r
,
494 "FastCGI: SetNamedPipeHandleState() failed");
501 unsigned long ioctl_arg
= (nonblocking
) ? 1 : 0;
502 if (ioctlsocket(fr
->fd
, FIONBIO
, &ioctl_arg
) != 0)
504 errno
= WSAGetLastError();
505 ap_log_rerror(FCGI_LOG_ERR_ERRNO
, fr
->r
,
506 "FastCGI: ioctlsocket() failed");
516 static int set_nonblocking(const fcgi_request
* fr
, int nonblocking
)
519 int fd_flags
= fcntl(fr
->fd
, F_GETFL
, 0);
521 if (fd_flags
< 0) return -1;
523 #if defined(O_NONBLOCK)
524 nb_flag
= O_NONBLOCK
;
525 #elif defined(O_NDELAY)
527 #elif defined(FNDELAY)
530 #error "TODO - don't read from app until all data from client is posted."
533 fd_flags
= (nonblocking
) ? (fd_flags
| nb_flag
) : (fd_flags
& ~nb_flag
);
535 return fcntl(fr
->fd
, F_SETFL
, fd_flags
);
540 /*******************************************************************************
541 * Close the connection to the FastCGI server. This is normally called by
542 * do_work(), but may also be called as in request pool cleanup.
544 static void close_connection_to_fs(fcgi_request
*fr
)
548 if (fr
->fd
!= INVALID_SOCKET
)
550 set_nonblocking(fr
, FALSE
);
552 if (fr
->using_npipe_io
)
554 CloseHandle((HANDLE
) fr
->fd
);
558 /* abort the connection entirely */
559 struct linger linger
= {0, 0};
560 setsockopt(fr
->fd
, SOL_SOCKET
, SO_LINGER
, (void *) &linger
, sizeof(linger
));
564 fr
->fd
= INVALID_SOCKET
;
570 struct linger linger
= {0, 0};
571 set_nonblocking(fr
, FALSE
);
572 /* abort the connection entirely */
573 setsockopt(fr
->fd
, SOL_SOCKET
, SO_LINGER
, &linger
, sizeof(linger
));
579 if (fr
->dynamic
&& fr
->keepReadingFromFcgiApp
== FALSE
)
581 /* XXX FCGI_REQUEST_COMPLETE_JOB is only sent for requests which complete
582 * normally WRT the fcgi app. There is no data sent for
583 * connect() timeouts or requests which complete abnormally.
584 * KillDynamicProcs() and RemoveRecords() need to be looked at
585 * to be sure they can reasonably handle these cases before
586 * sending these sort of stats - theres some funk in there.
588 if (fcgi_util_ticks(&fr
->completeTime
) < 0)
590 /* there's no point to aborting the request, just log it */
591 ap_log_error(FCGI_LOG_ERR
, fr
->r
->server
, "FastCGI: can't get time of day");
599 *----------------------------------------------------------------------
603 * Call with r->parseHeader == SCAN_CGI_READING_HEADERS
604 * and initial script output in fr->header.
606 * If the initial script output does not include the header
607 * terminator ("\r\n\r\n") process_headers returns with no side
608 * effects, to be called again when more script output
609 * has been appended to fr->header.
611 * If the initial script output includes the header terminator,
612 * process_headers parses the headers and determines whether or
613 * not the remaining script output will be sent to the client.
614 * If so, process_headers sends the HTTP response headers to the
615 * client and copies any non-header script output to the output
622 * May set r->parseHeader to:
623 * SCAN_CGI_FINISHED -- headers parsed, returning script response
624 * SCAN_CGI_BAD_HEADER -- malformed header from script
625 * SCAN_CGI_INT_REDIRECT -- handler should perform internal redirect
626 * SCAN_CGI_SRV_REDIRECT -- handler should return REDIRECT
628 *----------------------------------------------------------------------
631 static const char *process_headers(request_rec
*r
, fcgi_request
*fr
)
633 char *p
, *next
, *name
, *value
;
635 int hasContentType
, hasStatus
, hasLocation
;
637 ap_assert(fr
->parseHeader
== SCAN_CGI_READING_HEADERS
);
639 if (fr
->header
== NULL
)
643 * Do we have the entire header? Scan for the blank line that
644 * terminates the header.
646 p
= (char *)fr
->header
->elts
;
647 len
= fr
->header
->nelts
;
649 while(len
-- && flag
< 2) {
659 name
= "Invalid Character";
669 /* Return (to be called later when we have more data)
670 * if we don't have an entire header. */
675 * Parse all the headers.
677 fr
->parseHeader
= SCAN_CGI_FINISHED
;
678 hasContentType
= hasStatus
= hasLocation
= FALSE
;
679 next
= (char *)fr
->header
->elts
;
681 next
= get_header_line(name
= next
, TRUE
);
685 if ((p
= strchr(name
, ':')) == NULL
) {
689 while (p
!= name
&& isspace((unsigned char)*(p
- 1))) {
696 if (strpbrk(name
, " \t") != NULL
) {
700 while (isspace((unsigned char)*value
)) {
704 if (strcasecmp(name
, "Status") == 0) {
705 int statusValue
= strtol(value
, NULL
, 10);
708 goto DuplicateNotAllowed
;
710 if (statusValue
< 0) {
711 fr
->parseHeader
= SCAN_CGI_BAD_HEADER
;
712 return ap_psprintf(r
->pool
, "invalid Status '%s'", value
);
715 r
->status
= statusValue
;
716 r
->status_line
= ap_pstrdup(r
->pool
, value
);
720 if (fr
->role
== FCGI_RESPONDER
) {
721 if (strcasecmp(name
, "Content-type") == 0) {
722 if (hasContentType
) {
723 goto DuplicateNotAllowed
;
725 hasContentType
= TRUE
;
726 r
->content_type
= ap_pstrdup(r
->pool
, value
);
730 if (strcasecmp(name
, "Location") == 0) {
732 goto DuplicateNotAllowed
;
735 ap_table_set(r
->headers_out
, "Location", value
);
739 /* If the script wants them merged, it can do it */
740 ap_table_add(r
->err_headers_out
, name
, value
);
744 ap_table_add(fr
->authHeaders
, name
, value
);
748 if (fr
->role
!= FCGI_RESPONDER
)
752 * Who responds, this handler or Apache?
755 const char *location
= ap_table_get(r
->headers_out
, "Location");
757 * Based on internal redirect handling in mod_cgi.c...
759 * If a script wants to produce its own Redirect
760 * body, it now has to explicitly *say* "Status: 302"
762 if (r
->status
== 200) {
763 if(location
[0] == '/') {
765 * Location is an relative path. This handler will
766 * consume all script output, then have Apache perform an
769 fr
->parseHeader
= SCAN_CGI_INT_REDIRECT
;
773 * Location is an absolute URL. If the script didn't
774 * produce a Content-type header, this handler will
775 * consume all script output and then have Apache generate
776 * its standard redirect response. Otherwise this handler
777 * will transmit the script's response.
779 fr
->parseHeader
= SCAN_CGI_SRV_REDIRECT
;
785 * We're responding. Send headers, buffer excess script output.
787 ap_send_http_header(r
);
789 /* We need to reinstate our timeout, send_http_header() kill()s it */
790 ap_hard_timeout("FastCGI request processing", r
);
792 if (r
->header_only
) {
793 /* we've got all we want from the server */
794 close_connection_to_fs(fr
);
795 fr
->exitStatusSet
= 1;
796 fcgi_buf_reset(fr
->clientOutputBuffer
);
797 fcgi_buf_reset(fr
->serverOutputBuffer
);
801 len
= fr
->header
->nelts
- (next
- fr
->header
->elts
);
803 ap_assert(BufferLength(fr
->clientOutputBuffer
) == 0);
804 if (BufferFree(fr
->clientOutputBuffer
) < len
) {
805 fr
->clientOutputBuffer
= fcgi_buf_new(r
->pool
, len
);
807 ap_assert(BufferFree(fr
->clientOutputBuffer
) >= len
);
809 int sent
= fcgi_buf_add_block(fr
->clientOutputBuffer
, next
, len
);
810 ap_assert(sent
== len
);
815 /* Log first line of a multi-line header */
816 if ((p
= strpbrk(name
, "\r\n")) != NULL
)
818 fr
->parseHeader
= SCAN_CGI_BAD_HEADER
;
819 return ap_psprintf(r
->pool
, "malformed header '%s'", name
);
822 fr
->parseHeader
= SCAN_CGI_BAD_HEADER
;
823 return ap_psprintf(r
->pool
, "duplicate header '%s'", name
);
827 * Read from the client filling both the FastCGI server buffer and the
828 * client buffer with the hopes of buffering the client data before
829 * making the connect() to the FastCGI server. This prevents slow
830 * clients from keeping the FastCGI server in processing longer than is
833 static int read_from_client_n_queue(fcgi_request
*fr
)
839 while (BufferFree(fr
->clientInputBuffer
) > 0 || BufferFree(fr
->serverOutputBuffer
) > 0) {
840 fcgi_protocol_queue_client_buffer(fr
);
842 if (fr
->expectingClientContent
<= 0)
845 fcgi_buf_get_free_block_info(fr
->clientInputBuffer
, &end
, &count
);
849 if ((countRead
= ap_get_client_block(fr
->r
, end
, count
)) < 0)
852 if (countRead
== 0) {
853 fr
->expectingClientContent
= 0;
856 fcgi_buf_add_update(fr
->clientInputBuffer
, countRead
);
857 ap_reset_timeout(fr
->r
);
863 static int write_to_client(fcgi_request
*fr
)
870 apr_bucket_brigade
* bde
;
871 apr_bucket_alloc_t
* const bkt_alloc
= fr
->r
->connection
->bucket_alloc
;
874 fcgi_buf_get_block_info(fr
->clientOutputBuffer
, &begin
, &count
);
878 /* If fewer than count bytes are written, an error occured.
879 * ap_bwrite() typically forces a flushed write to the client, this
880 * effectively results in a block (and short packets) - it should
881 * be fixed, but I didn't win much support for the idea on new-httpd.
882 * So, without patching Apache, the best way to deal with this is
883 * to size the fcgi_bufs to hold all of the script output (within
884 * reason) so the script can be released from having to wait around
885 * for the transmission to the client to complete. */
889 bde
= apr_brigade_create(fr
->r
->pool
, bkt_alloc
);
890 bkt
= apr_bucket_transient_create(begin
, count
, bkt_alloc
);
891 APR_BRIGADE_INSERT_TAIL(bde
, bkt
);
893 if (fr
->fs
? fr
->fs
->flush
: dynamicFlush
)
895 bkt
= apr_bucket_flush_create(bkt_alloc
);
896 APR_BRIGADE_INSERT_TAIL(bde
, bkt
);
899 rv
= ap_pass_brigade(fr
->r
->output_filters
, bde
);
901 #elif defined(RUSSIAN_APACHE)
903 rv
= (ap_rwrite(begin
, count
, fr
->r
) != count
);
907 rv
= (ap_bwrite(fr
->r
->connection
->client
, begin
, count
) != count
);
913 ap_log_rerror(FCGI_LOG_INFO_NOERRNO
, fr
->r
,
914 "FastCGI: client stopped connection before send body completed");
920 ap_reset_timeout(fr
->r
);
922 /* Don't bother with a wrapped buffer, limiting exposure to slow
923 * clients. The BUFF routines don't allow a writev from above,
924 * and don't always memcpy to minimize small write()s, this should
925 * be fixed, but I didn't win much support for the idea on
926 * new-httpd - I'll have to _prove_ its a problem first.. */
928 /* The default behaviour used to be to flush with every write, but this
929 * can tie up the FastCGI server longer than is necessary so its an option now */
931 if (fr
->fs
? fr
->fs
->flush
: dynamicFlush
)
933 #ifdef RUSSIAN_APACHE
934 rv
= ap_rflush(fr
->r
);
936 rv
= ap_bflush(fr
->r
->connection
->client
);
941 ap_log_rerror(FCGI_LOG_INFO_NOERRNO
, fr
->r
,
942 "FastCGI: client stopped connection before send body completed");
946 ap_reset_timeout(fr
->r
);
949 #endif /* !APACHE2 */
951 fcgi_buf_toss(fr
->clientOutputBuffer
, count
);
955 /*******************************************************************************
956 * Determine the user and group the wrapper should be called with.
957 * Based on code in Apache's create_argv_cmd() (util_script.c).
959 static void set_uid_n_gid(request_rec
*r
, const char **user
, const char **group
)
961 if (fcgi_wrapper
== NULL
) {
967 if (strncmp("/~", r
->uri
, 2) == 0) {
968 /* its a user dir uri, just send the ~user, and leave it to the PM */
969 char *end
= strchr(r
->uri
+ 2, '/');
972 *user
= memcpy(ap_pcalloc(r
->pool
, end
- r
->uri
), r
->uri
+ 1, end
- r
->uri
- 1);
974 *user
= ap_pstrdup(r
->pool
, r
->uri
+ 1);
978 *user
= ap_psprintf(r
->pool
, "%ld", (long) fcgi_util_get_server_uid(r
->server
));
979 *group
= ap_psprintf(r
->pool
, "%ld", (long) fcgi_util_get_server_gid(r
->server
));
983 static void send_request_complete(fcgi_request
*fr
)
985 if (fr
->completeTime
.tv_sec
)
987 struct timeval qtime
, rtime
;
989 timersub(&fr
->queueTime
, &fr
->startTime
, &qtime
);
990 timersub(&fr
->completeTime
, &fr
->queueTime
, &rtime
);
992 send_to_pm(FCGI_REQUEST_COMPLETE_JOB
, fr
->fs_path
,
994 qtime
.tv_sec
* 1000000 + qtime
.tv_usec
,
995 rtime
.tv_sec
* 1000000 + rtime
.tv_usec
);
1000 /*******************************************************************************
1001 * Connect to the FastCGI server.
1003 static int open_connection_to_fs(fcgi_request
*fr
)
1005 struct timeval tval
;
1006 fd_set write_fds
, read_fds
;
1008 request_rec
* const r
= fr
->r
;
1009 pool
* const rp
= r
->pool
;
1010 const char *socket_path
= NULL
;
1011 struct sockaddr
*socket_addr
= NULL
;
1012 int socket_addr_len
= 0;
1014 const char *err
= NULL
;
1017 /* Create the connection point */
1020 socket_path
= fcgi_util_socket_hash_filename(rp
, fr
->fs_path
, fr
->user
, fr
->group
);
1021 socket_path
= fcgi_util_socket_make_path_absolute(rp
, socket_path
, 1);
1024 err
= fcgi_util_socket_make_domain_addr(rp
, (struct sockaddr_un
**)&socket_addr
,
1025 &socket_addr_len
, socket_path
);
1027 ap_log_rerror(FCGI_LOG_ERR
, r
,
1028 "FastCGI: failed to connect to (dynamic) server \"%s\": "
1029 "%s", fr
->fs_path
, err
);
1037 if (fr
->fs
->dest_addr
!= NULL
) {
1038 socket_addr
= fr
->fs
->dest_addr
;
1040 else if (fr
->fs
->socket_addr
) {
1041 socket_addr
= fr
->fs
->socket_addr
;
1044 socket_path
= fr
->fs
->socket_path
;
1047 socket_addr
= fr
->fs
->socket_addr
;
1049 socket_addr_len
= fr
->fs
->socket_addr_len
;
1055 if (fr
->fs
&& fr
->fs
->restartTime
)
1057 struct stat sock_stat
;
1059 if (stat(socket_path
, &sock_stat
) == 0)
1063 if (dynamicAutoUpdate
)
1065 struct stat app_stat
;
1067 /* TODO: follow sym links */
1069 if (stat(fr
->fs_path
, &app_stat
) == 0)
1072 if (fr
->fs
->startTime
< app_stat
.st_mtime
)
1074 if (sock_stat
.st_mtime
< app_stat
.st_mtime
)
1078 struct timeval tv
= {1, 0};
1081 * There's a newer one, request a restart.
1083 send_to_pm(FCGI_SERVER_RESTART_JOB
, fr
->fs_path
, fr
->user
, fr
->group
, 0, 0);
1088 /* Avoid sleep/alarm interactions */
1089 ap_select(0, NULL
, NULL
, NULL
, &tv
);
1099 send_to_pm(FCGI_SERVER_START_JOB
, fr
->fs_path
, fr
->user
, fr
->group
, 0, 0);
1101 /* wait until it looks like its running - this shouldn't take
1102 * very long at all - the exception is when the sockets are
1103 * removed out from under a running application - the loop
1104 * limit addresses this (preventing spinning) */
1106 for (i
= 10; i
> 0; i
--)
1111 fr
->fs
= fcgi_util_fs_get_by_id(fr
->fs_path
, 0, 0);
1113 if (fr
->fs
&& fr
->fs
->restartTime
)
1115 struct timeval tv
= {0, 500000};
1117 /* Avoid sleep/alarm interactions */
1118 ap_select(0, NULL
, NULL
, NULL
, &tv
);
1120 if (stat(socket_path
, &sock_stat
) == 0)
1129 ap_log_rerror(FCGI_LOG_ALERT
, r
,
1130 "FastCGI: failed to connect to (dynamic) server \"%s\": "
1131 "something is seriously wrong, any chance the "
1132 "socket/named_pipe directory was removed?, see the "
1133 "FastCgiIpcDir directive", fr
->fs_path
);
1145 HANDLE wait_npipe_mutex
;
1147 DWORD max_connect_time
= FCGI_NAMED_PIPE_CONNECT_TIMEOUT
;
1149 fr
->using_npipe_io
= TRUE
;
1153 interval
= dynamicPleaseStartDelay
* 1000;
1155 if (dynamicAppConnectTimeout
) {
1156 max_connect_time
= dynamicAppConnectTimeout
;
1161 interval
= FCGI_NAMED_PIPE_CONNECT_TIMEOUT
* 1000;
1163 if (fr
->fs
->appConnectTimeout
) {
1164 max_connect_time
= fr
->fs
->appConnectTimeout
;
1168 fcgi_util_ticks(&fr
->startTime
);
1171 // xxx this handle should live somewhere (see CloseHandle()s below too)
1172 char * wait_npipe_mutex_name
, * cp
;
1173 wait_npipe_mutex_name
= cp
= ap_pstrdup(rp
, socket_path
);
1174 while ((cp
= strchr(cp
, '\\'))) *cp
= '/';
1176 wait_npipe_mutex
= CreateMutex(NULL
, FALSE
, wait_npipe_mutex_name
);
1179 if (wait_npipe_mutex
== NULL
)
1181 ap_log_rerror(FCGI_LOG_ERR
, r
,
1182 "FastCGI: failed to connect to server \"%s\": "
1183 "can't create the WaitNamedPipe mutex", fr
->fs_path
);
1187 SetLastError(ERROR_SUCCESS
);
1189 rv
= WaitForSingleObject(wait_npipe_mutex
, max_connect_time
* 1000);
1191 if (rv
== WAIT_TIMEOUT
|| rv
== WAIT_FAILED
)
1195 send_to_pm(FCGI_REQUEST_TIMEOUT_JOB
, fr
->fs_path
, fr
->user
, fr
->group
, 0, 0);
1197 ap_log_rerror(FCGI_LOG_ERR_NOERRNO
, r
,
1198 "FastCGI: failed to connect to server \"%s\": "
1199 "wait for a npipe instance failed", fr
->fs_path
);
1200 FCGIDBG3("interval=%d, max_connect_time=%d", interval
, max_connect_time
);
1201 CloseHandle(wait_npipe_mutex
);
1205 fcgi_util_ticks(&fr
->queueTime
);
1207 connect_time
= fr
->queueTime
.tv_sec
- fr
->startTime
.tv_sec
;
1211 if (connect_time
>= interval
)
1213 send_to_pm(FCGI_REQUEST_TIMEOUT_JOB
, fr
->fs_path
, fr
->user
, fr
->group
, 0, 0);
1214 FCGIDBG4("connect_time=%d, interval=%d, max_connect_time=%d", connect_time
, interval
, max_connect_time
);
1216 if (max_connect_time
- connect_time
< interval
)
1218 interval
= max_connect_time
- connect_time
;
1223 interval
-= connect_time
* 1000;
1228 ready
= WaitNamedPipe(socket_path
, interval
);
1232 fr
->fd
= (SOCKET
) CreateFile(socket_path
,
1233 GENERIC_READ
| GENERIC_WRITE
,
1234 FILE_SHARE_READ
| FILE_SHARE_WRITE
,
1235 NULL
, // no security attributes
1236 OPEN_EXISTING
, // opens existing pipe
1237 FILE_FLAG_OVERLAPPED
,
1238 NULL
); // no template file
1240 if (fr
->fd
!= (SOCKET
) INVALID_HANDLE_VALUE
)
1242 ReleaseMutex(wait_npipe_mutex
);
1243 CloseHandle(wait_npipe_mutex
);
1244 fcgi_util_ticks(&fr
->queueTime
);
1245 FCGIDBG2("got npipe connect: %s", fr
->fs_path
);
1249 if (GetLastError() != ERROR_PIPE_BUSY
1250 && GetLastError() != ERROR_FILE_NOT_FOUND
)
1252 ap_log_rerror(FCGI_LOG_ERR
, r
,
1253 "FastCGI: failed to connect to server \"%s\": "
1254 "CreateFile() failed", fr
->fs_path
);
1258 FCGIDBG2("missed npipe connect: %s", fr
->fs_path
);
1263 send_to_pm(FCGI_REQUEST_TIMEOUT_JOB
, fr
->fs_path
, fr
->user
, fr
->group
, 0, 0);
1266 fcgi_util_ticks(&fr
->queueTime
);
1268 connect_time
= fr
->queueTime
.tv_sec
- fr
->startTime
.tv_sec
;
1270 FCGIDBG5("interval=%d, max_connect_time=%d, connect_time=%d, ready=%d", interval
, max_connect_time
, connect_time
, ready
);
1272 if (connect_time
>= max_connect_time
)
1274 ap_log_rerror(FCGI_LOG_ERR
, r
,
1275 "FastCGI: failed to connect to server \"%s\": "
1276 "CreateFile()/WaitNamedPipe() timed out", fr
->fs_path
);
1281 ReleaseMutex(wait_npipe_mutex
);
1282 CloseHandle(wait_npipe_mutex
);
1283 fr
->fd
= INVALID_SOCKET
;
1289 /* Create the socket */
1290 fr
->fd
= socket(socket_addr
->sa_family
, SOCK_STREAM
, 0);
1293 if (fr
->fd
== INVALID_SOCKET
) {
1294 errno
= WSAGetLastError(); // Not sure this is going to work as expected
1298 ap_log_rerror(FCGI_LOG_ERR_ERRNO
, r
,
1299 "FastCGI: failed to connect to server \"%s\": "
1300 "socket() failed", fr
->fs_path
);
1305 if (fr
->fd
>= FD_SETSIZE
) {
1306 ap_log_rerror(FCGI_LOG_ERR
, r
,
1307 "FastCGI: failed to connect to server \"%s\": "
1308 "socket file descriptor (%u) is larger than "
1309 "FD_SETSIZE (%u), you probably need to rebuild Apache with a "
1310 "larger FD_SETSIZE", fr
->fs_path
, fr
->fd
, FD_SETSIZE
);
1315 /* If appConnectTimeout is non-zero, setup do a non-blocking connect */
1316 if ((fr
->dynamic
&& dynamicAppConnectTimeout
) || (!fr
->dynamic
&& fr
->fs
->appConnectTimeout
)) {
1317 set_nonblocking(fr
, TRUE
);
1321 fcgi_util_ticks(&fr
->startTime
);
1325 if (connect(fr
->fd
, (struct sockaddr
*)socket_addr
, socket_addr_len
) == 0)
1326 goto ConnectionComplete
;
1330 errno
= WSAGetLastError();
1331 if (errno
!= WSAEWOULDBLOCK
) {
1332 ap_log_rerror(FCGI_LOG_ERR_ERRNO
, r
,
1333 "FastCGI: failed to connect to server \"%s\": "
1334 "connect() failed", fr
->fs_path
);
1340 /* ECONNREFUSED means the listen queue is full (or there isn't one).
1341 * With dynamic I can at least make sure the PM knows this is occuring */
1342 if (fr
->dynamic
&& errno
== ECONNREFUSED
) {
1343 /* @@@ This might be better as some other "kind" of message */
1344 send_to_pm(FCGI_REQUEST_TIMEOUT_JOB
, fr
->fs_path
, fr
->user
, fr
->group
, 0, 0);
1346 errno
= ECONNREFUSED
;
1349 if (errno
!= EINPROGRESS
) {
1350 ap_log_rerror(FCGI_LOG_ERR
, r
,
1351 "FastCGI: failed to connect to server \"%s\": "
1352 "connect() failed", fr
->fs_path
);
1358 /* The connect() is non-blocking */
1364 FD_ZERO(&write_fds
);
1365 FD_SET(fr
->fd
, &write_fds
);
1366 read_fds
= write_fds
;
1367 tval
.tv_sec
= dynamicPleaseStartDelay
;
1370 status
= ap_select((fr
->fd
+1), &read_fds
, &write_fds
, NULL
, &tval
);
1374 fcgi_util_ticks(&fr
->queueTime
);
1379 /* select() timed out */
1380 send_to_pm(FCGI_REQUEST_TIMEOUT_JOB
, fr
->fs_path
, fr
->user
, fr
->group
, 0, 0);
1381 } while ((fr
->queueTime
.tv_sec
- fr
->startTime
.tv_sec
) < (int)dynamicAppConnectTimeout
);
1383 /* XXX These can be moved down when dynamic vars live is a struct */
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
);
1393 tval
.tv_sec
= fr
->fs
->appConnectTimeout
;
1395 FD_ZERO(&write_fds
);
1396 FD_SET(fr
->fd
, &write_fds
);
1397 read_fds
= write_fds
;
1399 status
= ap_select((fr
->fd
+1), &read_fds
, &write_fds
, NULL
, &tval
);
1402 ap_log_rerror(FCGI_LOG_ERR_NOERRNO
, r
,
1403 "FastCGI: failed to connect to server \"%s\": "
1404 "connect() timed out (appConnTimeout=%dsec)",
1405 fr
->fs_path
, dynamicAppConnectTimeout
);
1412 errno
= WSAGetLastError();
1414 ap_log_rerror(FCGI_LOG_ERR_ERRNO
, r
,
1415 "FastCGI: failed to connect to server \"%s\": "
1416 "select() failed", fr
->fs_path
);
1420 if (FD_ISSET(fr
->fd
, &write_fds
) || FD_ISSET(fr
->fd
, &read_fds
)) {
1422 NET_SIZE_T len
= sizeof(error
);
1424 if (getsockopt(fr
->fd
, SOL_SOCKET
, SO_ERROR
, (char *)&error
, &len
) < 0) {
1425 /* Solaris pending error */
1427 errno
= WSAGetLastError();
1429 ap_log_rerror(FCGI_LOG_ERR_ERRNO
, r
,
1430 "FastCGI: failed to connect to server \"%s\": "
1431 "select() failed (Solaris pending error)", fr
->fs_path
);
1436 /* Berkeley-derived pending error */
1438 ap_log_rerror(FCGI_LOG_ERR_ERRNO
, r
,
1439 "FastCGI: failed to connect to server \"%s\": "
1440 "select() failed (pending error)", fr
->fs_path
);
1446 errno
= WSAGetLastError();
1448 ap_log_rerror(FCGI_LOG_ERR_ERRNO
, r
,
1449 "FastCGI: failed to connect to server \"%s\": "
1450 "select() error - THIS CAN'T HAPPEN!", fr
->fs_path
);
1455 /* Return to blocking mode if it was set up */
1456 if ((fr
->dynamic
&& dynamicAppConnectTimeout
) || (!fr
->dynamic
&& fr
->fs
->appConnectTimeout
)) {
1457 set_nonblocking(fr
, FALSE
);
1461 if (socket_addr
->sa_family
== AF_INET
) {
1462 /* We shouldn't be sending small packets and there's no application
1463 * level ack of the data we send, so disable Nagle */
1465 setsockopt(fr
->fd
, IPPROTO_TCP
, TCP_NODELAY
, (char *)&set
, sizeof(set
));
1472 static void sink_client_data(fcgi_request
*fr
)
1477 fcgi_buf_reset(fr
->clientInputBuffer
);
1478 fcgi_buf_get_free_block_info(fr
->clientInputBuffer
, &base
, &size
);
1479 while (ap_get_client_block(fr
->r
, base
, size
) > 0);
1482 static apcb_t
cleanup(void *data
)
1484 fcgi_request
* const fr
= (fcgi_request
*) data
;
1486 if (fr
== NULL
) return APCB_OK
;
1488 /* its more than likely already run, but... */
1489 close_connection_to_fs(fr
);
1491 send_request_complete(fr
);
1493 if (fr
->fs_stderr_len
) {
1494 ap_log_rerror(FCGI_LOG_ERR_NOERRNO
, fr
->r
,
1495 "FastCGI: server \"%s\" stderr: %s", fr
->fs_path
, fr
->fs_stderr
);
1502 static int npipe_io(fcgi_request
* const fr
)
1504 request_rec
* const r
= fr
->r
;
1515 state
= STATE_ENV_SEND
;
1516 env_status env_status
;
1518 int dynamic_first_recv
= fr
->dynamic
;
1519 int idle_timeout
= fr
->dynamic
? dynamic_idle_timeout
: fr
->fs
->idle_timeout
;
1520 int send_pending
= 0;
1521 int recv_pending
= 0;
1522 int client_send
= 0;
1524 OVERLAPPED rov
= { 0 };
1525 OVERLAPPED sov
= { 0 };
1527 struct timeval timeout
;
1528 struct timeval dynamic_last_io_time
= {0, 0};
1530 pool
* const rp
= r
->pool
;
1532 DWORD recv_count
= 0;
1534 if (fr
->role
== FCGI_RESPONDER
)
1536 client_recv
= (fr
->expectingClientContent
!= 0);
1539 idle_timeout
= fr
->dynamic
? dynamic_idle_timeout
: fr
->fs
->idle_timeout
;
1541 env_status
.envp
= NULL
;
1543 events
[0] = CreateEvent(NULL
, TRUE
, FALSE
, NULL
);
1544 events
[1] = CreateEvent(NULL
, TRUE
, FALSE
, NULL
);
1545 sov
.hEvent
= events
[0];
1546 rov
.hEvent
= events
[1];
1550 dynamic_last_io_time
= fr
->startTime
;
1552 if (dynamicAppConnectTimeout
)
1554 struct timeval qwait
;
1555 timersub(&fr
->queueTime
, &fr
->startTime
, &qwait
);
1556 dynamic_first_recv
= qwait
.tv_sec
/ dynamicPleaseStartDelay
+ 1;
1560 ap_hard_timeout("FastCGI request processing", r
);
1562 while (state
!= STATE_CLIENT_SEND
)
1568 case STATE_ENV_SEND
:
1570 if (fcgi_protocol_queue_env(r
, fr
, &env_status
) == 0)
1575 state
= STATE_CLIENT_RECV
;
1579 case STATE_CLIENT_RECV
:
1581 if (read_from_client_n_queue(fr
) != OK
)
1583 state
= STATE_CLIENT_ERROR
;
1589 state
= STATE_SERVER_SEND
;
1596 case STATE_SERVER_SEND
:
1598 if (! send_pending
&& BufferLength(fr
->serverOutputBuffer
))
1600 Buffer
* b
= fr
->serverOutputBuffer
;
1603 len
= min(b
->length
, b
->data
+ b
->size
- b
->begin
);
1605 if (WriteFile((HANDLE
) fr
->fd
, b
->begin
, len
, &sent
, &sov
))
1607 fcgi_buf_removed(b
, sent
);
1608 ResetEvent(sov
.hEvent
);
1610 else if (GetLastError() == ERROR_IO_PENDING
)
1616 ap_log_rerror(FCGI_LOG_ERR
, r
, "FastCGI: comm with server "
1617 "\"%s\" aborted: WriteFile() failed", fr
->fs_path
);
1618 state
= STATE_ERROR
;
1625 case STATE_SERVER_RECV
:
1628 * Only get more data when the serverInputBuffer is empty.
1629 * Otherwise we may already have the END_REQUEST buffered
1630 * (but not processed) and a read on a closed named pipe
1631 * results in an error that is normally abnormal.
1633 if (! recv_pending
&& BufferLength(fr
->serverInputBuffer
) == 0)
1635 Buffer
* b
= fr
->serverInputBuffer
;
1638 len
= min(b
->size
- b
->length
, b
->data
+ b
->size
- b
->end
);
1640 if (ReadFile((HANDLE
) fr
->fd
, b
->end
, len
, &rcvd
, &rov
))
1642 fcgi_buf_added(b
, rcvd
);
1644 ResetEvent(rov
.hEvent
);
1645 if (dynamic_first_recv
)
1647 dynamic_first_recv
= 0;
1650 else if (GetLastError() == ERROR_IO_PENDING
)
1654 else if (GetLastError() == ERROR_HANDLE_EOF
)
1656 fr
->keepReadingFromFcgiApp
= FALSE
;
1657 state
= STATE_CLIENT_SEND
;
1658 ResetEvent(rov
.hEvent
);
1661 else if (GetLastError() == ERROR_NO_DATA
)
1667 ap_log_rerror(FCGI_LOG_ERR
, r
, "FastCGI: comm with server "
1668 "\"%s\" aborted: ReadFile() failed", fr
->fs_path
);
1669 state
= STATE_ERROR
;
1676 case STATE_CLIENT_SEND
:
1678 if (client_send
|| ! BufferFree(fr
->clientOutputBuffer
))
1680 if (write_to_client(fr
))
1682 state
= STATE_CLIENT_ERROR
;
1696 if (state
== STATE_CLIENT_ERROR
|| state
== STATE_ERROR
)
1701 /* setup the io timeout */
1703 if (BufferLength(fr
->clientOutputBuffer
))
1705 /* don't let client data sit too long, it might be a push */
1707 timeout
.tv_usec
= 100000;
1709 else if (dynamic_first_recv
)
1712 struct timeval qwait
;
1714 fcgi_util_ticks(&fr
->queueTime
);
1718 /* a send() succeeded last pass */
1719 dynamic_last_io_time
= fr
->queueTime
;
1723 /* timed out last pass */
1724 struct timeval idle_time
;
1726 timersub(&fr
->queueTime
, &dynamic_last_io_time
, &idle_time
);
1728 if (idle_time
.tv_sec
> idle_timeout
)
1730 send_to_pm(FCGI_REQUEST_TIMEOUT_JOB
, fr
->fs_path
, fr
->user
, fr
->group
, 0, 0);
1731 ap_log_rerror(FCGI_LOG_ERR_NOERRNO
, r
, "FastCGI: comm "
1732 "with (dynamic) server \"%s\" aborted: (first read) "
1733 "idle timeout (%d sec)", fr
->fs_path
, idle_timeout
);
1734 state
= STATE_ERROR
;
1739 timersub(&fr
->queueTime
, &fr
->startTime
, &qwait
);
1741 delay
= dynamic_first_recv
* dynamicPleaseStartDelay
;
1743 if (qwait
.tv_sec
< delay
)
1745 timeout
.tv_sec
= delay
;
1746 timeout
.tv_usec
= 100000; /* fudge for select() slop */
1747 timersub(&timeout
, &qwait
, &timeout
);
1751 /* Killed time somewhere.. client read? */
1752 send_to_pm(FCGI_REQUEST_TIMEOUT_JOB
, fr
->fs_path
, fr
->user
, fr
->group
, 0, 0);
1753 dynamic_first_recv
= qwait
.tv_sec
/ dynamicPleaseStartDelay
+ 1;
1754 timeout
.tv_sec
= dynamic_first_recv
* dynamicPleaseStartDelay
;
1755 timeout
.tv_usec
= 100000; /* fudge for select() slop */
1756 timersub(&timeout
, &qwait
, &timeout
);
1761 timeout
.tv_sec
= idle_timeout
;
1762 timeout
.tv_usec
= 0;
1765 /* require a pended recv otherwise the app can deadlock */
1768 msec_timeout
= timeout
.tv_sec
* 1000 + timeout
.tv_usec
/ 1000;
1770 rv
= WaitForMultipleObjects(2, events
, FALSE
, msec_timeout
);
1772 if (rv
== WAIT_TIMEOUT
)
1776 if (BufferLength(fr
->clientOutputBuffer
))
1780 else if (dynamic_first_recv
)
1782 struct timeval qwait
;
1784 fcgi_util_ticks(&fr
->queueTime
);
1785 timersub(&fr
->queueTime
, &fr
->startTime
, &qwait
);
1787 send_to_pm(FCGI_REQUEST_TIMEOUT_JOB
, fr
->fs_path
, fr
->user
, fr
->group
, 0, 0);
1789 dynamic_first_recv
= qwait
.tv_sec
/ dynamicPleaseStartDelay
+ 1;
1793 ap_log_rerror(FCGI_LOG_ERR_NOERRNO
, r
, "FastCGI: comm with "
1794 "server \"%s\" aborted: idle timeout (%d sec)",
1795 fr
->fs_path
, idle_timeout
);
1796 state
= STATE_ERROR
;
1802 int i
= rv
- WAIT_OBJECT_0
;
1810 if (GetOverlappedResult((HANDLE
) fr
->fd
, &sov
, &sent
, FALSE
))
1813 ResetEvent(sov
.hEvent
);
1814 fcgi_buf_removed(fr
->serverOutputBuffer
, sent
);
1818 ap_log_rerror(FCGI_LOG_ERR
, r
, "FastCGI: comm with server "
1819 "\"%s\" aborted: GetOverlappedResult() failed", fr
->fs_path
);
1820 state
= STATE_ERROR
;
1831 ResetEvent(rov
.hEvent
);
1833 if (GetOverlappedResult((HANDLE
) fr
->fd
, &rov
, &rcvd
, FALSE
))
1835 fcgi_buf_added(fr
->serverInputBuffer
, rcvd
);
1836 if (dynamic_first_recv
)
1838 dynamic_first_recv
= 0;
1843 ap_log_rerror(FCGI_LOG_ERR
, r
, "FastCGI: comm with server "
1844 "\"%s\" aborted: GetOverlappedResult() failed", fr
->fs_path
);
1845 state
= STATE_ERROR
;
1852 if (fcgi_protocol_dequeue(rp
, fr
))
1854 state
= STATE_ERROR
;
1858 if (fr
->parseHeader
== SCAN_CGI_READING_HEADERS
)
1860 const char * err
= process_headers(r
, fr
);
1863 ap_log_rerror(FCGI_LOG_ERR_NOERRNO
, r
,
1864 "FastCGI: comm with server \"%s\" aborted: "
1865 "error parsing headers: %s", fr
->fs_path
, err
);
1866 state
= STATE_ERROR
;
1871 if (fr
->exitStatusSet
)
1873 fr
->keepReadingFromFcgiApp
= FALSE
;
1874 state
= STATE_CLIENT_SEND
;
1879 if (! fr
->exitStatusSet
|| ! fr
->eofSent
)
1881 CancelIo((HANDLE
) fr
->fd
);
1884 CloseHandle(rov
.hEvent
);
1885 CloseHandle(sov
.hEvent
);
1887 return (state
== STATE_ERROR
);
1891 static int socket_io(fcgi_request
* const fr
)
1904 state
= STATE_ENV_SEND
;
1906 request_rec
* const r
= fr
->r
;
1908 struct timeval timeout
;
1909 struct timeval dynamic_last_io_time
= {0, 0};
1912 int nfds
= fr
->fd
+ 1;
1913 int select_status
= 1;
1916 int dynamic_first_recv
= fr
->dynamic
? 1 : 0;
1917 int client_send
= FALSE
;
1918 int client_recv
= FALSE
;
1922 if (fr
->role
== FCGI_RESPONDER
)
1924 client_recv
= (fr
->expectingClientContent
!= 0);
1927 idle_timeout
= fr
->dynamic
? dynamic_idle_timeout
: fr
->fs
->idle_timeout
;
1933 dynamic_last_io_time
= fr
->startTime
;
1935 if (dynamicAppConnectTimeout
)
1937 struct timeval qwait
;
1938 timersub(&fr
->queueTime
, &fr
->startTime
, &qwait
);
1939 dynamic_first_recv
= qwait
.tv_sec
/ dynamicPleaseStartDelay
+ 1;
1943 ap_hard_timeout("FastCGI request processing", r
);
1945 set_nonblocking(fr
, TRUE
);
1950 FD_ZERO(&write_set
);
1954 case STATE_ENV_SEND
:
1956 if (fcgi_protocol_queue_env(r
, fr
, &env
) == 0)
1961 state
= STATE_CLIENT_RECV
;
1965 case STATE_CLIENT_RECV
:
1967 if (read_from_client_n_queue(fr
))
1969 state
= STATE_CLIENT_ERROR
;
1975 state
= STATE_SERVER_SEND
;
1982 case STATE_SERVER_SEND
:
1984 if (BufferLength(fr
->serverOutputBuffer
))
1986 FD_SET(fr
->fd
, &write_set
);
1990 ap_assert(fr
->eofSent
);
1991 state
= STATE_SERVER_RECV
;
1996 case STATE_SERVER_RECV
:
1998 FD_SET(fr
->fd
, &read_set
);
2002 case STATE_CLIENT_SEND
:
2004 if (client_send
|| ! BufferFree(fr
->clientOutputBuffer
))
2006 if (write_to_client(fr
))
2008 state
= STATE_CLIENT_ERROR
;
2018 case STATE_CLIENT_ERROR
:
2027 if (state
== STATE_CLIENT_ERROR
|| state
== STATE_ERROR
)
2032 /* setup the io timeout */
2034 if (BufferLength(fr
->clientOutputBuffer
))
2036 /* don't let client data sit too long, it might be a push */
2038 timeout
.tv_usec
= 100000;
2040 else if (dynamic_first_recv
)
2043 struct timeval qwait
;
2045 fcgi_util_ticks(&fr
->queueTime
);
2049 /* a send() succeeded last pass */
2050 dynamic_last_io_time
= fr
->queueTime
;
2054 /* timed out last pass */
2055 struct timeval idle_time
;
2057 timersub(&fr
->queueTime
, &dynamic_last_io_time
, &idle_time
);
2059 if (idle_time
.tv_sec
> idle_timeout
)
2061 send_to_pm(FCGI_REQUEST_TIMEOUT_JOB
, fr
->fs_path
, fr
->user
, fr
->group
, 0, 0);
2062 ap_log_rerror(FCGI_LOG_ERR_NOERRNO
, r
, "FastCGI: comm "
2063 "with (dynamic) server \"%s\" aborted: (first read) "
2064 "idle timeout (%d sec)", fr
->fs_path
, idle_timeout
);
2065 state
= STATE_ERROR
;
2070 timersub(&fr
->queueTime
, &fr
->startTime
, &qwait
);
2072 delay
= dynamic_first_recv
* dynamicPleaseStartDelay
;
2074 FCGIDBG5("qwait=%ld.%06ld delay=%d first_recv=%d", qwait
.tv_sec
, qwait
.tv_usec
, delay
, dynamic_first_recv
);
2076 if (qwait
.tv_sec
< delay
)
2078 timeout
.tv_sec
= delay
;
2079 timeout
.tv_usec
= 100000; /* fudge for select() slop */
2080 timersub(&timeout
, &qwait
, &timeout
);
2084 /* Killed time somewhere.. client read? */
2085 send_to_pm(FCGI_REQUEST_TIMEOUT_JOB
, fr
->fs_path
, fr
->user
, fr
->group
, 0, 0);
2086 dynamic_first_recv
= qwait
.tv_sec
/ dynamicPleaseStartDelay
+ 1;
2087 timeout
.tv_sec
= dynamic_first_recv
* dynamicPleaseStartDelay
;
2088 timeout
.tv_usec
= 100000; /* fudge for select() slop */
2089 timersub(&timeout
, &qwait
, &timeout
);
2094 timeout
.tv_sec
= idle_timeout
;
2095 timeout
.tv_usec
= 0;
2098 /* wait on the socket */
2099 select_status
= ap_select(nfds
, &read_set
, &write_set
, NULL
, &timeout
);
2101 if (select_status
< 0)
2103 ap_log_rerror(FCGI_LOG_ERR_ERRNO
, r
, "FastCGI: comm with server "
2104 "\"%s\" aborted: select() failed", fr
->fs_path
);
2105 state
= STATE_ERROR
;
2109 if (select_status
== 0)
2111 /* select() timeout */
2113 if (BufferLength(fr
->clientOutputBuffer
))
2115 if (fr
->role
== FCGI_RESPONDER
)
2120 else if (dynamic_first_recv
)
2122 struct timeval qwait
;
2124 fcgi_util_ticks(&fr
->queueTime
);
2125 timersub(&fr
->queueTime
, &fr
->startTime
, &qwait
);
2127 send_to_pm(FCGI_REQUEST_TIMEOUT_JOB
, fr
->fs_path
, fr
->user
, fr
->group
, 0, 0);
2129 dynamic_first_recv
= qwait
.tv_sec
/ dynamicPleaseStartDelay
+ 1;
2134 ap_log_rerror(FCGI_LOG_ERR_NOERRNO
, r
, "FastCGI: comm with "
2135 "server \"%s\" aborted: idle timeout (%d sec)",
2136 fr
->fs_path
, idle_timeout
);
2137 state
= STATE_ERROR
;
2141 if (FD_ISSET(fr
->fd
, &write_set
))
2143 /* send to the server */
2145 rv
= fcgi_buf_socket_send(fr
->serverOutputBuffer
, fr
->fd
);
2149 ap_log_rerror(FCGI_LOG_ERR
, r
, "FastCGI: comm with server "
2150 "\"%s\" aborted: write failed", fr
->fs_path
);
2151 state
= STATE_ERROR
;
2156 if (FD_ISSET(fr
->fd
, &read_set
))
2158 /* recv from the server */
2160 if (dynamic_first_recv
)
2162 dynamic_first_recv
= 0;
2163 fcgi_util_ticks(&fr
->queueTime
);
2166 rv
= fcgi_buf_socket_recv(fr
->serverInputBuffer
, fr
->fd
);
2170 ap_log_rerror(FCGI_LOG_ERR
, r
, "FastCGI: comm with server "
2171 "\"%s\" aborted: read failed", fr
->fs_path
);
2172 state
= STATE_ERROR
;
2178 fr
->keepReadingFromFcgiApp
= FALSE
;
2179 state
= STATE_CLIENT_SEND
;
2184 if (fcgi_protocol_dequeue(rp
, fr
))
2186 state
= STATE_ERROR
;
2190 if (fr
->parseHeader
== SCAN_CGI_READING_HEADERS
)
2192 const char * err
= process_headers(r
, fr
);
2195 ap_log_rerror(FCGI_LOG_ERR_NOERRNO
, r
,
2196 "FastCGI: comm with server \"%s\" aborted: "
2197 "error parsing headers: %s", fr
->fs_path
, err
);
2198 state
= STATE_ERROR
;
2203 if (fr
->exitStatusSet
)
2205 fr
->keepReadingFromFcgiApp
= FALSE
;
2206 state
= STATE_CLIENT_SEND
;
2211 return (state
== STATE_ERROR
);
2215 /*----------------------------------------------------------------------
2216 * This is the core routine for moving data between the FastCGI
2217 * application and the Web server's client.
2219 static int do_work(request_rec
* const r
, fcgi_request
* const fr
)
2224 fcgi_protocol_queue_begin_request(fr
);
2226 if (fr
->role
== FCGI_RESPONDER
)
2228 rv
= ap_setup_client_block(r
, REQUEST_CHUNKED_ERROR
);
2235 fr
->expectingClientContent
= ap_should_client_block(r
);
2239 ap_register_cleanup(rp
, (void *)fr
, cleanup
, ap_null_cleanup
);
2240 ap_unblock_alarms();
2242 ap_hard_timeout("connect() to FastCGI server", r
);
2244 /* Connect to the FastCGI Application */
2245 if (open_connection_to_fs(fr
) != FCGI_OK
)
2248 return HTTP_INTERNAL_SERVER_ERROR
;
2252 if (fr
->using_npipe_io
)
2262 /* comm with the server is done */
2263 close_connection_to_fs(fr
);
2265 if (fr
->role
== FCGI_RESPONDER
)
2267 sink_client_data(fr
);
2270 while (rv
== 0 && BufferLength(fr
->serverInputBuffer
) || BufferLength(fr
->clientOutputBuffer
))
2272 if (fcgi_protocol_dequeue(rp
, fr
))
2274 rv
= HTTP_INTERNAL_SERVER_ERROR
;
2277 if (fr
->parseHeader
== SCAN_CGI_READING_HEADERS
)
2279 const char * err
= process_headers(r
, fr
);
2282 ap_log_rerror(FCGI_LOG_ERR_NOERRNO
, r
,
2283 "FastCGI: comm with server \"%s\" aborted: "
2284 "error parsing headers: %s", fr
->fs_path
, err
);
2285 rv
= HTTP_INTERNAL_SERVER_ERROR
;
2289 if (fr
->role
== FCGI_RESPONDER
)
2291 if (write_to_client(fr
))
2298 fcgi_buf_reset(fr
->clientOutputBuffer
);
2302 switch (fr
->parseHeader
)
2304 case SCAN_CGI_FINISHED
:
2306 if (fr
->role
== FCGI_RESPONDER
)
2308 /* RUSSIAN_APACHE requires rflush() over bflush() */
2311 ap_bgetopt(r
->connection
->client
, BO_BYTECT
, &r
->bytes_sent
);
2317 case SCAN_CGI_INT_REDIRECT
:
2318 case SCAN_CGI_SRV_REDIRECT
:
2322 case SCAN_CGI_READING_HEADERS
:
2324 ap_log_rerror(FCGI_LOG_ERR_NOERRNO
, r
, "FastCGI: incomplete headers "
2325 "(%d bytes) received from server \"%s\"", fr
->header
->nelts
, fr
->fs_path
);
2329 case SCAN_CGI_BAD_HEADER
:
2331 rv
= HTTP_INTERNAL_SERVER_ERROR
;
2337 rv
= HTTP_INTERNAL_SERVER_ERROR
;
2344 static fcgi_request
*create_fcgi_request(request_rec
* const r
, const char *path
)
2346 const char *fs_path
;
2347 pool
* const p
= r
->pool
;
2349 fcgi_request
* const fr
= (fcgi_request
*)ap_pcalloc(p
, sizeof(fcgi_request
));
2351 fs_path
= path
? path
: r
->filename
;
2353 fs
= fcgi_util_fs_get_by_id(fs_path
, fcgi_util_get_server_uid(r
->server
),
2354 fcgi_util_get_server_gid(r
->server
));
2358 struct stat
*my_finfo
;
2365 /* AP2: its bogus that we don't make use of r->finfo, but
2366 * its an apr_finfo_t and there is no apr_os_finfo_get() */
2368 my_finfo
= &r
->finfo
;
2373 my_finfo
= (struct stat
*) ap_palloc(p
, sizeof(struct stat
));
2375 if (stat(fs_path
, my_finfo
) < 0)
2377 ap_log_rerror(FCGI_LOG_ERR_ERRNO
, r
,
2378 "FastCGI: stat() of \"%s\" failed", fs_path
);
2383 err
= fcgi_util_fs_is_path_ok(p
, fs_path
, my_finfo
);
2387 ap_log_rerror(FCGI_LOG_ERR_NOERRNO
, r
,
2388 "FastCGI: invalid (dynamic) server \"%s\": %s", fs_path
, err
);
2393 fr
->serverInputBuffer
= fcgi_buf_new(p
, SERVER_BUFSIZE
);
2394 fr
->serverOutputBuffer
= fcgi_buf_new(p
, SERVER_BUFSIZE
);
2395 fr
->clientInputBuffer
= fcgi_buf_new(p
, SERVER_BUFSIZE
);
2396 fr
->clientOutputBuffer
= fcgi_buf_new(p
, SERVER_BUFSIZE
);
2397 fr
->erBufPtr
= fcgi_buf_new(p
, sizeof(FCGI_EndRequestBody
) + 1);
2398 fr
->gotHeader
= FALSE
;
2399 fr
->parseHeader
= SCAN_CGI_READING_HEADERS
;
2400 fr
->header
= ap_make_array(p
, 1, 1);
2401 fr
->fs_stderr
= NULL
;
2403 fr
->readingEndRequestBody
= FALSE
;
2405 fr
->exitStatusSet
= FALSE
;
2406 fr
->requestId
= 1; /* anything but zero is OK here */
2407 fr
->eofSent
= FALSE
;
2408 fr
->role
= FCGI_RESPONDER
;
2409 fr
->expectingClientContent
= FALSE
;
2410 fr
->keepReadingFromFcgiApp
= TRUE
;
2412 fr
->fs_path
= fs_path
;
2413 fr
->authHeaders
= ap_make_table(p
, 10);
2415 fr
->fd
= INVALID_SOCKET
;
2416 fr
->dynamic
= ((fs
== NULL
) || (fs
->directive
== APP_CLASS_DYNAMIC
)) ? TRUE
: FALSE
;
2417 fr
->using_npipe_io
= FALSE
;
2419 fr
->dynamic
= (fs
== NULL
) ? TRUE
: FALSE
;
2423 set_uid_n_gid(r
, &fr
->user
, &fr
->group
);
2429 *----------------------------------------------------------------------
2433 * This routine gets called for a request that corresponds to
2434 * a FastCGI connection. It performs the request synchronously.
2437 * Final status of request: OK or NOT_FOUND or HTTP_INTERNAL_SERVER_ERROR.
2440 * Request performed.
2442 *----------------------------------------------------------------------
2445 /* Stolen from mod_cgi.c..
2446 * KLUDGE --- for back-combatibility, we don't have to check ExecCGI
2447 * in ScriptAliased directories, which means we need to know if this
2448 * request came through ScriptAlias or not... so the Alias module
2449 * leaves a note for us.
2451 static int apache_is_scriptaliased(request_rec
*r
)
2453 const char *t
= ap_table_get(r
->notes
, "alias-forced-type");
2454 return t
&& (!strcasecmp(t
, "cgi-script"));
2457 /* If a script wants to produce its own Redirect body, it now
2458 * has to explicitly *say* "Status: 302". If it wants to use
2459 * Apache redirects say "Status: 200". See process_headers().
2461 static int post_process_for_redirects(request_rec
* const r
,
2462 const fcgi_request
* const fr
)
2464 switch(fr
->parseHeader
) {
2465 case SCAN_CGI_INT_REDIRECT
:
2467 /* @@@ There are still differences between the handling in
2468 * mod_cgi and mod_fastcgi. This needs to be revisited.
2470 /* We already read the message body (if any), so don't allow
2471 * the redirected request to think it has one. We can ignore
2472 * Transfer-Encoding, since we used REQUEST_CHUNKED_ERROR.
2475 r
->method_number
= M_GET
;
2476 ap_table_unset(r
->headers_in
, "Content-length");
2478 ap_internal_redirect_handler(ap_table_get(r
->headers_out
, "Location"), r
);
2481 case SCAN_CGI_SRV_REDIRECT
:
2482 return HTTP_MOVED_TEMPORARILY
;
2489 /******************************************************************************
2490 * Process fastcgi-script requests. Based on mod_cgi::cgi_handler().
2492 static int content_handler(request_rec
*r
)
2494 fcgi_request
*fr
= NULL
;
2498 if (strcmp(r
->handler
, FASTCGI_HANDLER_NAME
))
2502 /* Setup a new FastCGI request */
2503 if ((fr
= create_fcgi_request(r
, NULL
)) == NULL
)
2504 return HTTP_INTERNAL_SERVER_ERROR
;
2506 /* If its a dynamic invocation, make sure scripts are OK here */
2507 if (fr
->dynamic
&& !(ap_allow_options(r
) & OPT_EXECCGI
) && !apache_is_scriptaliased(r
)) {
2508 ap_log_rerror(FCGI_LOG_ERR_NOERRNO
, r
,
2509 "FastCGI: \"ExecCGI Option\" is off in this directory: %s", r
->uri
);
2510 return HTTP_INTERNAL_SERVER_ERROR
;
2513 /* Process the fastcgi-script request */
2514 if ((ret
= do_work(r
, fr
)) != OK
)
2517 /* Special case redirects */
2518 ret
= post_process_for_redirects(r
, fr
);
2524 static int post_process_auth_passed_header(table
*t
, const char *key
, const char * const val
)
2526 if (strncasecmp(key
, "Variable-", 9) == 0)
2529 ap_table_setn(t
, key
, val
);
2533 static int post_process_auth_passed_compat_header(table
*t
, const char *key
, const char * const val
)
2535 if (strncasecmp(key
, "Variable-", 9) == 0)
2536 ap_table_setn(t
, key
+ 9, val
);
2541 static int post_process_auth_failed_header(table
* const t
, const char * const key
, const char * const val
)
2543 ap_table_setn(t
, key
, val
);
2547 static void post_process_auth(fcgi_request
* const fr
, const int passed
)
2549 request_rec
* const r
= fr
->r
;
2551 /* Restore the saved subprocess_env because we muddied ours up */
2552 r
->subprocess_env
= fr
->saved_subprocess_env
;
2555 if (fr
->auth_compat
) {
2556 ap_table_do((int (*)(void *, const char *, const char *))post_process_auth_passed_compat_header
,
2557 (void *)r
->subprocess_env
, fr
->authHeaders
, NULL
);
2560 ap_table_do((int (*)(void *, const char *, const char *))post_process_auth_passed_header
,
2561 (void *)r
->subprocess_env
, fr
->authHeaders
, NULL
);
2565 ap_table_do((int (*)(void *, const char *, const char *))post_process_auth_failed_header
,
2566 (void *)r
->err_headers_out
, fr
->authHeaders
, NULL
);
2569 /* @@@ Restore these.. its a hack until I rewrite the header handling */
2570 r
->status
= HTTP_OK
;
2571 r
->status_line
= NULL
;
2574 static int check_user_authentication(request_rec
*r
)
2576 int res
, authenticated
= 0;
2577 const char *password
;
2579 const fcgi_dir_config
* const dir_config
=
2580 (const fcgi_dir_config
*)ap_get_module_config(r
->per_dir_config
, &fastcgi_module
);
2582 if (dir_config
->authenticator
== NULL
)
2585 /* Get the user password */
2586 if ((res
= ap_get_basic_auth_pw(r
, &password
)) != OK
)
2589 if ((fr
= create_fcgi_request(r
, dir_config
->authenticator
)) == NULL
)
2590 return HTTP_INTERNAL_SERVER_ERROR
;
2592 /* Save the existing subprocess_env, because we're gonna muddy it up */
2593 fr
->saved_subprocess_env
= ap_copy_table(r
->pool
, r
->subprocess_env
);
2595 ap_table_setn(r
->subprocess_env
, "REMOTE_PASSWD", password
);
2596 ap_table_setn(r
->subprocess_env
, "FCGI_APACHE_ROLE", "AUTHENTICATOR");
2598 /* The FastCGI Protocol doesn't differentiate authentication */
2599 fr
->role
= FCGI_AUTHORIZER
;
2601 /* Do we need compatibility mode? */
2602 fr
->auth_compat
= (dir_config
->authenticator_options
& FCGI_COMPAT
);
2604 if ((res
= do_work(r
, fr
)) != OK
)
2605 goto AuthenticationFailed
;
2607 authenticated
= (r
->status
== 200);
2608 post_process_auth(fr
, authenticated
);
2610 /* A redirect shouldn't be allowed during the authentication phase */
2611 if (ap_table_get(r
->headers_out
, "Location") != NULL
) {
2612 ap_log_rerror(FCGI_LOG_ERR_NOERRNO
, r
,
2613 "FastCGI: FastCgiAuthenticator \"%s\" redirected (not allowed)",
2614 dir_config
->authenticator
);
2615 goto AuthenticationFailed
;
2621 AuthenticationFailed
:
2622 if (!(dir_config
->authenticator_options
& FCGI_AUTHORITATIVE
))
2625 /* @@@ Probably should support custom_responses */
2626 ap_note_basic_auth_failure(r
);
2627 ap_log_rerror(FCGI_LOG_ERR_NOERRNO
, r
,
2628 "FastCGI: authentication failed for user \"%s\": %s",
2632 r
->connection
->user
, r
->uri
);
2635 return (res
== OK
) ? HTTP_UNAUTHORIZED
: res
;
2638 static int check_user_authorization(request_rec
*r
)
2640 int res
, authorized
= 0;
2642 const fcgi_dir_config
* const dir_config
=
2643 (const fcgi_dir_config
*)ap_get_module_config(r
->per_dir_config
, &fastcgi_module
);
2645 if (dir_config
->authorizer
== NULL
)
2648 /* @@@ We should probably honor the existing parameters to the require directive
2649 * as well as allow the definition of new ones (or use the basename of the
2650 * FastCGI server and pass the rest of the directive line), but for now keep
2653 if ((fr
= create_fcgi_request(r
, dir_config
->authorizer
)) == NULL
)
2654 return HTTP_INTERNAL_SERVER_ERROR
;
2656 /* Save the existing subprocess_env, because we're gonna muddy it up */
2657 fr
->saved_subprocess_env
= ap_copy_table(r
->pool
, r
->subprocess_env
);
2659 ap_table_setn(r
->subprocess_env
, "FCGI_APACHE_ROLE", "AUTHORIZER");
2661 fr
->role
= FCGI_AUTHORIZER
;
2663 /* Do we need compatibility mode? */
2664 fr
->auth_compat
= (dir_config
->authorizer_options
& FCGI_COMPAT
);
2666 if ((res
= do_work(r
, fr
)) != OK
)
2667 goto AuthorizationFailed
;
2669 authorized
= (r
->status
== 200);
2670 post_process_auth(fr
, authorized
);
2672 /* A redirect shouldn't be allowed during the authorization phase */
2673 if (ap_table_get(r
->headers_out
, "Location") != NULL
) {
2674 ap_log_rerror(FCGI_LOG_ERR_NOERRNO
, r
,
2675 "FastCGI: FastCgiAuthorizer \"%s\" redirected (not allowed)",
2676 dir_config
->authorizer
);
2677 goto AuthorizationFailed
;
2683 AuthorizationFailed
:
2684 if (!(dir_config
->authorizer_options
& FCGI_AUTHORITATIVE
))
2687 /* @@@ Probably should support custom_responses */
2688 ap_note_basic_auth_failure(r
);
2689 ap_log_rerror(FCGI_LOG_ERR_NOERRNO
, r
,
2690 "FastCGI: authorization failed for user \"%s\": %s",
2694 r
->connection
->user
, r
->uri
);
2697 return (res
== OK
) ? HTTP_UNAUTHORIZED
: res
;
2700 static int check_access(request_rec
*r
)
2702 int res
, access_allowed
= 0;
2704 const fcgi_dir_config
* const dir_config
=
2705 (fcgi_dir_config
*)ap_get_module_config(r
->per_dir_config
, &fastcgi_module
);
2707 if (dir_config
== NULL
|| dir_config
->access_checker
== NULL
)
2710 if ((fr
= create_fcgi_request(r
, dir_config
->access_checker
)) == NULL
)
2711 return HTTP_INTERNAL_SERVER_ERROR
;
2713 /* Save the existing subprocess_env, because we're gonna muddy it up */
2714 fr
->saved_subprocess_env
= ap_copy_table(r
->pool
, r
->subprocess_env
);
2716 ap_table_setn(r
->subprocess_env
, "FCGI_APACHE_ROLE", "ACCESS_CHECKER");
2718 /* The FastCGI Protocol doesn't differentiate access control */
2719 fr
->role
= FCGI_AUTHORIZER
;
2721 /* Do we need compatibility mode? */
2722 fr
->auth_compat
= (dir_config
->access_checker_options
& FCGI_COMPAT
);
2724 if ((res
= do_work(r
, fr
)) != OK
)
2727 access_allowed
= (r
->status
== 200);
2728 post_process_auth(fr
, access_allowed
);
2730 /* A redirect shouldn't be allowed during the access check phase */
2731 if (ap_table_get(r
->headers_out
, "Location") != NULL
) {
2732 ap_log_rerror(FCGI_LOG_ERR_NOERRNO
, r
,
2733 "FastCGI: FastCgiAccessChecker \"%s\" redirected (not allowed)",
2734 dir_config
->access_checker
);
2742 if (!(dir_config
->access_checker_options
& FCGI_AUTHORITATIVE
))
2745 /* @@@ Probably should support custom_responses */
2746 ap_log_rerror(FCGI_LOG_ERR_NOERRNO
, r
, "FastCGI: access denied: %s", r
->uri
);
2747 return (res
== OK
) ? HTTP_FORBIDDEN
: res
;
2751 fixups(request_rec
* r
)
2753 if (fcgi_util_fs_get_by_id(r
->filename
,
2754 fcgi_util_get_server_uid(r
->server
),
2755 fcgi_util_get_server_gid(r
->server
)))
2757 r
->handler
= FASTCGI_HANDLER_NAME
;
2766 # define AP_INIT_RAW_ARGS(directive, func, mconfig, where, help) \
2767 { directive, func, mconfig, where, RAW_ARGS, help }
2768 # define AP_INIT_TAKE1(directive, func, mconfig, where, help) \
2769 { directive, func, mconfig, where, TAKE1, help }
2770 # define AP_INIT_TAKE12(directive, func, mconfig, where, help) \
2771 { directive, func, mconfig, where, TAKE12, help }
2772 # define AP_INIT_FLAG(directive, func, mconfig, where, help) \
2773 { directive, func, mconfig, where, FLAG, help }
2777 static const command_rec fastcgi_cmds
[] =
2779 AP_INIT_RAW_ARGS("AppClass", fcgi_config_new_static_server
, NULL
, RSRC_CONF
, NULL
),
2780 AP_INIT_RAW_ARGS("FastCgiServer", fcgi_config_new_static_server
, NULL
, RSRC_CONF
, NULL
),
2782 AP_INIT_RAW_ARGS("ExternalAppClass", fcgi_config_new_external_server
, NULL
, RSRC_CONF
, NULL
),
2783 AP_INIT_RAW_ARGS("FastCgiExternalServer", fcgi_config_new_external_server
, NULL
, RSRC_CONF
, NULL
),
2785 AP_INIT_TAKE1("FastCgiIpcDir", fcgi_config_set_socket_dir
, NULL
, RSRC_CONF
, NULL
),
2787 AP_INIT_TAKE1("FastCgiSuexec", fcgi_config_set_wrapper
, NULL
, RSRC_CONF
, NULL
),
2788 AP_INIT_TAKE1("FastCgiWrapper", fcgi_config_set_wrapper
, NULL
, RSRC_CONF
, NULL
),
2790 AP_INIT_RAW_ARGS("FCGIConfig", fcgi_config_set_config
, NULL
, RSRC_CONF
, NULL
),
2791 AP_INIT_RAW_ARGS("FastCgiConfig", fcgi_config_set_config
, NULL
, RSRC_CONF
, NULL
),
2793 AP_INIT_TAKE12("FastCgiAuthenticator", fcgi_config_new_auth_server
,
2794 (void *)FCGI_AUTH_TYPE_AUTHENTICATOR
, ACCESS_CONF
,
2795 "a fastcgi-script path (absolute or relative to ServerRoot) followed by an optional -compat"),
2796 AP_INIT_FLAG("FastCgiAuthenticatorAuthoritative", fcgi_config_set_authoritative_slot
,
2797 (void *)XtOffsetOf(fcgi_dir_config
, authenticator_options
), ACCESS_CONF
,
2798 "Set to 'off' to allow authentication to be passed along to lower modules upon failure"),
2800 AP_INIT_TAKE12("FastCgiAuthorizer", fcgi_config_new_auth_server
,
2801 (void *)FCGI_AUTH_TYPE_AUTHORIZER
, ACCESS_CONF
,
2802 "a fastcgi-script path (absolute or relative to ServerRoot) followed by an optional -compat"),
2803 AP_INIT_FLAG("FastCgiAuthorizerAuthoritative", fcgi_config_set_authoritative_slot
,
2804 (void *)XtOffsetOf(fcgi_dir_config
, authorizer_options
), ACCESS_CONF
,
2805 "Set to 'off' to allow authorization to be passed along to lower modules upon failure"),
2807 AP_INIT_TAKE12("FastCgiAccessChecker", fcgi_config_new_auth_server
,
2808 (void *)FCGI_AUTH_TYPE_ACCESS_CHECKER
, ACCESS_CONF
,
2809 "a fastcgi-script path (absolute or relative to ServerRoot) followed by an optional -compat"),
2810 AP_INIT_FLAG("FastCgiAccessCheckerAuthoritative", fcgi_config_set_authoritative_slot
,
2811 (void *)XtOffsetOf(fcgi_dir_config
, access_checker_options
), ACCESS_CONF
,
2812 "Set to 'off' to allow access control to be passed along to lower modules upon failure"),
2818 static void register_hooks(apr_pool_t
* p
)
2820 // ap_hook_pre_config(x_pre_config, NULL, NULL, APR_HOOK_MIDDLE);
2821 ap_hook_post_config(init_module
, NULL
, NULL
, APR_HOOK_MIDDLE
);
2822 ap_hook_child_init(fcgi_child_init
, NULL
, NULL
, APR_HOOK_MIDDLE
);
2823 ap_hook_handler(content_handler
, NULL
, NULL
, APR_HOOK_MIDDLE
);
2824 ap_hook_check_user_id(check_user_authentication
, NULL
, NULL
, APR_HOOK_MIDDLE
);
2825 ap_hook_access_checker(check_access
, NULL
, NULL
, APR_HOOK_MIDDLE
);
2826 ap_hook_auth_checker(check_user_authorization
, NULL
, NULL
, APR_HOOK_MIDDLE
);
2827 ap_hook_fixups(fixups
, NULL
, NULL
, APR_HOOK_MIDDLE
);
2830 module AP_MODULE_DECLARE_DATA fastcgi_module
=
2832 STANDARD20_MODULE_STUFF
,
2833 fcgi_config_create_dir_config
, /* per-directory config creator */
2834 NULL
, /* dir config merger */
2835 NULL
, /* server config creator */
2836 NULL
, /* server config merger */
2837 fastcgi_cmds
, /* command table */
2838 register_hooks
, /* set up other request processing hooks */
2841 #else /* !APACHE2 */
2843 handler_rec fastcgi_handlers
[] = {
2844 { FCGI_MAGIC_TYPE
, content_handler
},
2845 { FASTCGI_HANDLER_NAME
, content_handler
},
2849 module MODULE_VAR_EXPORT fastcgi_module
= {
2850 STANDARD_MODULE_STUFF
,
2851 init_module
, /* initializer */
2852 fcgi_config_create_dir_config
, /* per-dir config creator */
2853 NULL
, /* per-dir config merger (default: override) */
2854 NULL
, /* per-server config creator */
2855 NULL
, /* per-server config merger (default: override) */
2856 fastcgi_cmds
, /* command table */
2857 fastcgi_handlers
, /* [9] content handlers */
2858 NULL
, /* [2] URI-to-filename translation */
2859 check_user_authentication
, /* [5] authenticate user_id */
2860 check_user_authorization
, /* [6] authorize user_id */
2861 check_access
, /* [4] check access (based on src & http headers) */
2862 NULL
, /* [7] check/set MIME type */
2863 fixups
, /* [8] fixups */
2864 NULL
, /* [10] logger */
2865 NULL
, /* [3] header-parser */
2866 fcgi_child_init
, /* process initialization */
2867 fcgi_child_exit
, /* process exit/cleanup */
2868 NULL
/* [1] post read-request handling */
2871 #endif /* !APACHE2 */