4 * Apache server module for FastCGI.
6 * $Id: mod_fastcgi.c,v 1.145 2002/10/22 01:02:18 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.
87 #define timersub(a, b, result) \
89 (result)->tv_sec = (a)->tv_sec - (b)->tv_sec; \
90 (result)->tv_usec = (a)->tv_usec - (b)->tv_usec; \
91 if ((result)->tv_usec < 0) { \
93 (result)->tv_usec += 1000000; \
102 pool
*fcgi_config_pool
; /* the config pool */
103 server_rec
*fcgi_apache_main_server
;
105 const char *fcgi_wrapper
= NULL
; /* wrapper path */
106 uid_t fcgi_user_id
; /* the run uid of Apache & PM */
107 gid_t fcgi_group_id
; /* the run gid of Apache & PM */
109 fcgi_server
*fcgi_servers
= NULL
; /* AppClasses */
111 char *fcgi_socket_dir
= NULL
; /* default FastCgiIpcDir */
113 char *fcgi_dynamic_dir
= NULL
; /* directory for the dynamic
114 * fastcgi apps' sockets */
118 #pragma warning( disable : 4706 4100 4127)
119 fcgi_pm_job
*fcgi_dynamic_mbox
= NULL
;
120 HANDLE
*fcgi_dynamic_mbox_mutex
= NULL
;
121 HANDLE fcgi_pm_thread
= INVALID_HANDLE_VALUE
;
125 int fcgi_pm_pipe
[2] = { -1, -1 };
126 pid_t fcgi_pm_pid
= -1;
130 char *fcgi_empty_env
= NULL
;
132 u_int dynamicMaxProcs
= FCGI_DEFAULT_MAX_PROCS
;
133 int dynamicMinProcs
= FCGI_DEFAULT_MIN_PROCS
;
134 int dynamicMaxClassProcs
= FCGI_DEFAULT_MAX_CLASS_PROCS
;
135 u_int dynamicKillInterval
= FCGI_DEFAULT_KILL_INTERVAL
;
136 u_int dynamicUpdateInterval
= FCGI_DEFAULT_UPDATE_INTERVAL
;
137 float dynamicGain
= FCGI_DEFAULT_GAIN
;
138 int dynamicThreshold1
= FCGI_DEFAULT_THRESHOLD_1
;
139 int dynamicThresholdN
= FCGI_DEFAULT_THRESHOLD_N
;
140 u_int dynamicPleaseStartDelay
= FCGI_DEFAULT_START_PROCESS_DELAY
;
141 u_int dynamicAppConnectTimeout
= FCGI_DEFAULT_APP_CONN_TIMEOUT
;
142 char **dynamicEnvp
= &fcgi_empty_env
;
143 u_int dynamicProcessSlack
= FCGI_DEFAULT_PROCESS_SLACK
;
144 int dynamicAutoRestart
= FCGI_DEFAULT_RESTART_DYNAMIC
;
145 int dynamicAutoUpdate
= FCGI_DEFAULT_AUTOUPDATE
;
146 int dynamicFlush
= FCGI_FLUSH
;
147 u_int dynamicListenQueueDepth
= FCGI_DEFAULT_LISTEN_Q
;
148 u_int dynamicInitStartDelay
= DEFAULT_INIT_START_DELAY
;
149 u_int dynamicRestartDelay
= FCGI_DEFAULT_RESTART_DELAY
;
150 array_header
*dynamic_pass_headers
= NULL
;
151 u_int dynamic_idle_timeout
= FCGI_DEFAULT_IDLE_TIMEOUT
;
153 /*******************************************************************************
154 * Construct a message and write it to the pm_pipe.
156 static void send_to_pm(const char id
, const char * const fs_path
,
157 const char *user
, const char * const group
, const unsigned long q_usec
,
158 const unsigned long req_usec
)
161 fcgi_pm_job
*job
= NULL
;
163 if (!(job
= (fcgi_pm_job
*) malloc(sizeof(fcgi_pm_job
))))
166 static int failed_count
= 0;
168 char buf
[FCGI_MAX_MSG_LEN
];
171 if (strlen(fs_path
) > FCGI_MAXPATH
) {
172 ap_log_error(FCGI_LOG_ERR_NOERRNO
, fcgi_apache_main_server
,
173 "FastCGI: the path \"%s\" is too long (>%d) for a dynamic server", fs_path
, FCGI_MAXPATH
);
179 case FCGI_SERVER_START_JOB
:
180 case FCGI_SERVER_RESTART_JOB
:
183 job
->fs_path
= strdup(fs_path
);
184 job
->user
= strdup(user
);
185 job
->group
= strdup(group
);
187 job
->start_time
= 0L;
189 buflen
= sprintf(buf
, "%c %s %s %s*", id
, fs_path
, user
, group
);
193 case FCGI_REQUEST_TIMEOUT_JOB
:
196 job
->fs_path
= strdup(fs_path
);
197 job
->user
= strdup(user
);
198 job
->group
= strdup(group
);
200 job
->start_time
= 0L;
202 buflen
= sprintf(buf
, "%c %s %s %s*", id
, fs_path
, user
, group
);
206 case FCGI_REQUEST_COMPLETE_JOB
:
209 job
->fs_path
= strdup(fs_path
);
211 job
->start_time
= req_usec
;
212 job
->user
= strdup(user
);
213 job
->group
= strdup(group
);
215 buflen
= sprintf(buf
, "%c %s %s %s %lu %lu*", id
, fs_path
, user
, group
, q_usec
, req_usec
);
221 if (fcgi_pm_add_job(job
)) return;
223 SetEvent(fcgi_event_handles
[MBOX_EVENT
]);
225 ap_assert(buflen
<= FCGI_MAX_MSG_LEN
);
227 /* There is no apache flag or function that can be used to id
228 * restart/shutdown pending so ignore the first few failures as
229 * once it breaks it will stay broke */
230 if (write(fcgi_pm_pipe
[1], (const void *)buf
, buflen
) != buflen
231 && failed_count
++ > 10)
233 ap_log_error(FCGI_LOG_WARN
, fcgi_apache_main_server
,
234 "FastCGI: write() to PM failed (ignore if a restart or shutdown is pending)");
240 *----------------------------------------------------------------------
244 * An Apache module initializer, called by the Apache core
245 * after reading the server config.
247 * Start the process manager no matter what, since there may be a
248 * request for dynamic FastCGI applications without any being
249 * configured as static applications. Also, check for the existence
250 * and create if necessary a subdirectory into which all dynamic
253 *----------------------------------------------------------------------
256 static apcb_t
init_module(apr_pool_t
* p
, apr_pool_t
* plog
,
257 apr_pool_t
* tp
, server_rec
* s
)
259 static apcb_t
init_module(server_rec
*s
, pool
*p
)
266 /* Register to reset to default values when the config pool is cleaned */
268 ap_register_cleanup(p
, NULL
, fcgi_config_reset_globals
, ap_null_cleanup
);
272 ap_add_version_component(p
, "mod_fastcgi/" MOD_FASTCGI_VERSION
);
274 ap_add_version_component("mod_fastcgi/" MOD_FASTCGI_VERSION
);
277 fcgi_config_set_fcgi_uid_n_gid(1);
279 /* keep these handy */
280 fcgi_config_pool
= p
;
281 fcgi_apache_main_server
= s
;
284 if (fcgi_socket_dir
== NULL
)
285 fcgi_socket_dir
= DEFAULT_SOCK_DIR
;
286 fcgi_dynamic_dir
= ap_pstrcat(p
, fcgi_socket_dir
, "dynamic", NULL
);
289 if (fcgi_socket_dir
== NULL
)
290 fcgi_socket_dir
= ap_server_root_relative(p
, DEFAULT_SOCK_DIR
);
292 /* Create Unix/Domain socket directory */
293 if ((err
= fcgi_config_make_dir(p
, fcgi_socket_dir
)))
294 ap_log_error(FCGI_LOG_ERR
, s
, "FastCGI: %s", err
);
296 /* Create Dynamic directory */
297 if ((err
= fcgi_config_make_dynamic_dir(p
, 1)))
298 ap_log_error(FCGI_LOG_ERR
, s
, "FastCGI: %s", err
);
300 /* Spawn the PM only once. Under Unix, Apache calls init() routines
301 * twice, once before detach() and once after. Win32 doesn't detach.
302 * Under DSO, DSO modules are unloaded between the two init() calls.
303 * Under Unix, the -X switch causes two calls to init() but no detach
304 * (but all subprocesses are wacked so the PM is toasted anyway)! */
309 apr_pool_userdata_get(&first_pass
, "mod_fastcgi", s
->process
->pool
);
310 if (first_pass
== NULL
)
312 apr_pool_userdata_set((const void *)1, "mod_fastcgi",
313 apr_pool_cleanup_null
, s
->process
->pool
);
319 if (ap_standalone
&& ap_restart_time
== 0)
324 /* Create the pipe for comm with the PM */
325 if (pipe(fcgi_pm_pipe
) < 0) {
326 ap_log_error(FCGI_LOG_ERR
, s
, "FastCGI: pipe() failed");
329 /* Start the Process Manager */
333 apr_proc_t
* proc
= apr_palloc(p
, sizeof(*proc
));
336 rv
= apr_proc_fork(proc
, tp
);
338 if (rv
== APR_INCHILD
)
344 else if (rv
!= APR_INPARENT
)
351 apr_pool_note_subprocess(p
, proc
, APR_KILL_ONLY_ONCE
);
355 fcgi_pm_pid
= ap_spawn_child(p
, fcgi_pm_main
, NULL
, kill_only_once
, NULL
, NULL
, NULL
);
356 if (fcgi_pm_pid
<= 0) {
357 ap_log_error(FCGI_LOG_ALERT
, s
,
358 "FastCGI: can't start the process manager, spawn_child() failed");
361 #endif /* !APACHE2 */
363 close(fcgi_pm_pipe
[0]);
372 static apcb_t
fcgi_child_exit(void * dc
)
374 static apcb_t
fcgi_child_exit(server_rec
*dc0
, pool
*dc1
)
377 /* Signal the PM thread to exit*/
378 SetEvent(fcgi_event_handles
[TERM_EVENT
]);
380 /* Waiting on pm thread to exit */
381 WaitForSingleObject(fcgi_pm_thread
, INFINITE
);
388 static void fcgi_child_init(apr_pool_t
* p
, server_rec
* dc
)
390 static void fcgi_child_init(server_rec
*dc
, pool
*p
)
394 /* Create the MBOX, TERM, and WAKE event handlers */
395 fcgi_event_handles
[0] = CreateEvent(NULL
, FALSE
, FALSE
, NULL
);
396 if (fcgi_event_handles
[0] == NULL
) {
397 ap_log_error(FCGI_LOG_ALERT
, fcgi_apache_main_server
,
398 "FastCGI: CreateEvent() failed");
400 fcgi_event_handles
[1] = CreateEvent(NULL
, FALSE
, FALSE
, NULL
);
401 if (fcgi_event_handles
[1] == NULL
) {
402 ap_log_error(FCGI_LOG_ALERT
, fcgi_apache_main_server
,
403 "FastCGI: CreateEvent() failed");
405 fcgi_event_handles
[2] = CreateEvent(NULL
, FALSE
, FALSE
, NULL
);
406 if (fcgi_event_handles
[2] == NULL
) {
407 ap_log_error(FCGI_LOG_ALERT
, fcgi_apache_main_server
,
408 "FastCGI: CreateEvent() failed");
411 /* Create the mbox mutex (PM - request threads) */
412 fcgi_dynamic_mbox_mutex
= CreateMutex(NULL
, FALSE
, NULL
);
413 if (fcgi_dynamic_mbox_mutex
== NULL
) {
414 ap_log_error(FCGI_LOG_ALERT
, fcgi_apache_main_server
,
415 "FastCGI: CreateMutex() failed");
418 /* Spawn of the process manager thread */
419 fcgi_pm_thread
= (HANDLE
) _beginthread(fcgi_pm_main
, 0, NULL
);
420 if (fcgi_pm_thread
== (HANDLE
) -1) {
421 ap_log_error(FCGI_LOG_ALERT
, fcgi_apache_main_server
,
422 "_beginthread() failed to spawn the process manager");
426 apr_pool_cleanup_register(p
, NULL
, fcgi_child_exit
, fcgi_child_exit
);
432 *----------------------------------------------------------------------
436 * Terminate a line: scan to the next newline, scan back to the
437 * first non-space character and store a terminating zero. Return
438 * the next character past the end of the newline.
440 * If the end of the string is reached, ASSERT!
442 * If the FIRST character(s) in the line are '\n' or "\r\n", the
443 * first character is replaced with a NULL and next character
444 * past the newline is returned. NOTE: this condition supercedes
445 * the processing of RFC-822 continuation lines.
447 * If continuation is set to 'TRUE', then it parses a (possible)
448 * sequence of RFC-822 continuation lines.
454 * Termination byte stored in string.
456 *----------------------------------------------------------------------
458 static char *get_header_line(char *start
, int continuation
)
463 if(p
[0] == '\r' && p
[1] == '\n') { /* If EOL in 1st 2 chars */
464 p
++; /* point to \n and stop */
465 } else if(*p
!= '\n') {
468 if(*p
== '\n' && p
[1] != ' ' && p
[1] != '\t')
473 while(*p
!= '\0' && *p
!= '\n') {
479 ap_assert(*p
!= '\0');
484 * Trim any trailing whitespace.
486 while(isspace((unsigned char)p
[-1]) && p
> start
) {
496 static int set_nonblocking(const fcgi_request
* fr
, int nonblocking
)
498 if (fr
->using_npipe_io
)
502 DWORD mode
= PIPE_NOWAIT
| PIPE_READMODE_BYTE
;
503 if (SetNamedPipeHandleState((HANDLE
) fr
->fd
, &mode
, NULL
, NULL
) == 0)
505 ap_log_rerror(FCGI_LOG_ERR
, fr
->r
,
506 "FastCGI: SetNamedPipeHandleState() failed");
513 unsigned long ioctl_arg
= (nonblocking
) ? 1 : 0;
514 if (ioctlsocket(fr
->fd
, FIONBIO
, &ioctl_arg
) != 0)
516 errno
= WSAGetLastError();
517 ap_log_rerror(FCGI_LOG_ERR_ERRNO
, fr
->r
,
518 "FastCGI: ioctlsocket() failed");
528 static int set_nonblocking(const fcgi_request
* fr
, int nonblocking
)
531 int fd_flags
= fcntl(fr
->fd
, F_GETFL
, 0);
533 if (fd_flags
< 0) return -1;
535 #if defined(O_NONBLOCK)
536 nb_flag
= O_NONBLOCK
;
537 #elif defined(O_NDELAY)
539 #elif defined(FNDELAY)
542 #error "TODO - don't read from app until all data from client is posted."
545 fd_flags
= (nonblocking
) ? (fd_flags
| nb_flag
) : (fd_flags
& ~nb_flag
);
547 return fcntl(fr
->fd
, F_SETFL
, fd_flags
);
552 /*******************************************************************************
553 * Close the connection to the FastCGI server. This is normally called by
554 * do_work(), but may also be called as in request pool cleanup.
556 static void close_connection_to_fs(fcgi_request
*fr
)
560 if (fr
->fd
!= INVALID_SOCKET
)
562 set_nonblocking(fr
, FALSE
);
564 if (fr
->using_npipe_io
)
566 CloseHandle((HANDLE
) fr
->fd
);
570 /* abort the connection entirely */
571 struct linger linger
= {0, 0};
572 setsockopt(fr
->fd
, SOL_SOCKET
, SO_LINGER
, (void *) &linger
, sizeof(linger
));
576 fr
->fd
= INVALID_SOCKET
;
582 struct linger linger
= {0, 0};
583 set_nonblocking(fr
, FALSE
);
584 /* abort the connection entirely */
585 setsockopt(fr
->fd
, SOL_SOCKET
, SO_LINGER
, &linger
, sizeof(linger
));
591 if (fr
->dynamic
&& fr
->keepReadingFromFcgiApp
== FALSE
)
593 /* XXX FCGI_REQUEST_COMPLETE_JOB is only sent for requests which complete
594 * normally WRT the fcgi app. There is no data sent for
595 * connect() timeouts or requests which complete abnormally.
596 * KillDynamicProcs() and RemoveRecords() need to be looked at
597 * to be sure they can reasonably handle these cases before
598 * sending these sort of stats - theres some funk in there.
600 if (fcgi_util_ticks(&fr
->completeTime
) < 0)
602 /* there's no point to aborting the request, just log it */
603 ap_log_error(FCGI_LOG_ERR
, fr
->r
->server
, "FastCGI: can't get time of day");
611 *----------------------------------------------------------------------
615 * Call with r->parseHeader == SCAN_CGI_READING_HEADERS
616 * and initial script output in fr->header.
618 * If the initial script output does not include the header
619 * terminator ("\r\n\r\n") process_headers returns with no side
620 * effects, to be called again when more script output
621 * has been appended to fr->header.
623 * If the initial script output includes the header terminator,
624 * process_headers parses the headers and determines whether or
625 * not the remaining script output will be sent to the client.
626 * If so, process_headers sends the HTTP response headers to the
627 * client and copies any non-header script output to the output
634 * May set r->parseHeader to:
635 * SCAN_CGI_FINISHED -- headers parsed, returning script response
636 * SCAN_CGI_BAD_HEADER -- malformed header from script
637 * SCAN_CGI_INT_REDIRECT -- handler should perform internal redirect
638 * SCAN_CGI_SRV_REDIRECT -- handler should return REDIRECT
640 *----------------------------------------------------------------------
643 static const char *process_headers(request_rec
*r
, fcgi_request
*fr
)
645 char *p
, *next
, *name
, *value
;
647 int hasContentType
, hasStatus
, hasLocation
;
649 ap_assert(fr
->parseHeader
== SCAN_CGI_READING_HEADERS
);
651 if (fr
->header
== NULL
)
655 * Do we have the entire header? Scan for the blank line that
656 * terminates the header.
658 p
= (char *)fr
->header
->elts
;
659 len
= fr
->header
->nelts
;
661 while(len
-- && flag
< 2) {
671 name
= "Invalid Character";
681 /* Return (to be called later when we have more data)
682 * if we don't have an entire header. */
687 * Parse all the headers.
689 fr
->parseHeader
= SCAN_CGI_FINISHED
;
690 hasContentType
= hasStatus
= hasLocation
= FALSE
;
691 next
= (char *)fr
->header
->elts
;
693 next
= get_header_line(name
= next
, TRUE
);
697 if ((p
= strchr(name
, ':')) == NULL
) {
701 while (p
!= name
&& isspace((unsigned char)*(p
- 1))) {
708 if (strpbrk(name
, " \t") != NULL
) {
712 while (isspace((unsigned char)*value
)) {
716 if (strcasecmp(name
, "Status") == 0) {
717 int statusValue
= strtol(value
, NULL
, 10);
720 goto DuplicateNotAllowed
;
722 if (statusValue
< 0) {
723 fr
->parseHeader
= SCAN_CGI_BAD_HEADER
;
724 return ap_psprintf(r
->pool
, "invalid Status '%s'", value
);
727 r
->status
= statusValue
;
728 r
->status_line
= ap_pstrdup(r
->pool
, value
);
732 if (fr
->role
== FCGI_RESPONDER
) {
733 if (strcasecmp(name
, "Content-type") == 0) {
734 if (hasContentType
) {
735 goto DuplicateNotAllowed
;
737 hasContentType
= TRUE
;
738 r
->content_type
= ap_pstrdup(r
->pool
, value
);
742 if (strcasecmp(name
, "Location") == 0) {
744 goto DuplicateNotAllowed
;
747 ap_table_set(r
->headers_out
, "Location", value
);
751 /* If the script wants them merged, it can do it */
752 ap_table_add(r
->err_headers_out
, name
, value
);
756 ap_table_add(fr
->authHeaders
, name
, value
);
760 if (fr
->role
!= FCGI_RESPONDER
)
764 * Who responds, this handler or Apache?
767 const char *location
= ap_table_get(r
->headers_out
, "Location");
769 * Based on internal redirect handling in mod_cgi.c...
771 * If a script wants to produce its own Redirect
772 * body, it now has to explicitly *say* "Status: 302"
774 if (r
->status
== 200) {
775 if(location
[0] == '/') {
777 * Location is an relative path. This handler will
778 * consume all script output, then have Apache perform an
781 fr
->parseHeader
= SCAN_CGI_INT_REDIRECT
;
785 * Location is an absolute URL. If the script didn't
786 * produce a Content-type header, this handler will
787 * consume all script output and then have Apache generate
788 * its standard redirect response. Otherwise this handler
789 * will transmit the script's response.
791 fr
->parseHeader
= SCAN_CGI_SRV_REDIRECT
;
797 * We're responding. Send headers, buffer excess script output.
799 ap_send_http_header(r
);
801 /* We need to reinstate our timeout, send_http_header() kill()s it */
802 ap_hard_timeout("FastCGI request processing", r
);
804 if (r
->header_only
) {
805 /* we've got all we want from the server */
806 close_connection_to_fs(fr
);
807 fr
->exitStatusSet
= 1;
808 fcgi_buf_reset(fr
->clientOutputBuffer
);
809 fcgi_buf_reset(fr
->serverOutputBuffer
);
813 len
= fr
->header
->nelts
- (next
- fr
->header
->elts
);
815 ap_assert(BufferLength(fr
->clientOutputBuffer
) == 0);
816 if (BufferFree(fr
->clientOutputBuffer
) < len
) {
817 fr
->clientOutputBuffer
= fcgi_buf_new(r
->pool
, len
);
819 ap_assert(BufferFree(fr
->clientOutputBuffer
) >= len
);
821 int sent
= fcgi_buf_add_block(fr
->clientOutputBuffer
, next
, len
);
822 ap_assert(sent
== len
);
827 /* Log first line of a multi-line header */
828 if ((p
= strpbrk(name
, "\r\n")) != NULL
)
830 fr
->parseHeader
= SCAN_CGI_BAD_HEADER
;
831 return ap_psprintf(r
->pool
, "malformed header '%s'", name
);
834 fr
->parseHeader
= SCAN_CGI_BAD_HEADER
;
835 return ap_psprintf(r
->pool
, "duplicate header '%s'", name
);
839 * Read from the client filling both the FastCGI server buffer and the
840 * client buffer with the hopes of buffering the client data before
841 * making the connect() to the FastCGI server. This prevents slow
842 * clients from keeping the FastCGI server in processing longer than is
845 static int read_from_client_n_queue(fcgi_request
*fr
)
851 while (BufferFree(fr
->clientInputBuffer
) > 0 || BufferFree(fr
->serverOutputBuffer
) > 0) {
852 fcgi_protocol_queue_client_buffer(fr
);
854 if (fr
->expectingClientContent
<= 0)
857 fcgi_buf_get_free_block_info(fr
->clientInputBuffer
, &end
, &count
);
861 if ((countRead
= ap_get_client_block(fr
->r
, end
, count
)) < 0)
864 if (countRead
== 0) {
865 fr
->expectingClientContent
= 0;
868 fcgi_buf_add_update(fr
->clientInputBuffer
, countRead
);
869 ap_reset_timeout(fr
->r
);
875 static int write_to_client(fcgi_request
*fr
)
882 apr_bucket_brigade
* bde
;
883 apr_bucket_alloc_t
* const bkt_alloc
= fr
->r
->connection
->bucket_alloc
;
886 fcgi_buf_get_block_info(fr
->clientOutputBuffer
, &begin
, &count
);
890 /* If fewer than count bytes are written, an error occured.
891 * ap_bwrite() typically forces a flushed write to the client, this
892 * effectively results in a block (and short packets) - it should
893 * be fixed, but I didn't win much support for the idea on new-httpd.
894 * So, without patching Apache, the best way to deal with this is
895 * to size the fcgi_bufs to hold all of the script output (within
896 * reason) so the script can be released from having to wait around
897 * for the transmission to the client to complete. */
901 bde
= apr_brigade_create(fr
->r
->pool
, bkt_alloc
);
902 bkt
= apr_bucket_transient_create(begin
, count
, bkt_alloc
);
903 APR_BRIGADE_INSERT_TAIL(bde
, bkt
);
905 if (fr
->fs
? fr
->fs
->flush
: dynamicFlush
)
907 bkt
= apr_bucket_flush_create(bkt_alloc
);
908 APR_BRIGADE_INSERT_TAIL(bde
, bkt
);
911 rv
= ap_pass_brigade(fr
->r
->output_filters
, bde
);
913 #elif defined(RUSSIAN_APACHE)
915 rv
= (ap_rwrite(begin
, count
, fr
->r
) != count
);
919 rv
= (ap_bwrite(fr
->r
->connection
->client
, begin
, count
) != count
);
925 ap_log_rerror(FCGI_LOG_INFO_NOERRNO
, fr
->r
,
926 "FastCGI: client stopped connection before send body completed");
932 ap_reset_timeout(fr
->r
);
934 /* Don't bother with a wrapped buffer, limiting exposure to slow
935 * clients. The BUFF routines don't allow a writev from above,
936 * and don't always memcpy to minimize small write()s, this should
937 * be fixed, but I didn't win much support for the idea on
938 * new-httpd - I'll have to _prove_ its a problem first.. */
940 /* The default behaviour used to be to flush with every write, but this
941 * can tie up the FastCGI server longer than is necessary so its an option now */
943 if (fr
->fs
? fr
->fs
->flush
: dynamicFlush
)
945 #ifdef RUSSIAN_APACHE
946 rv
= ap_rflush(fr
->r
);
948 rv
= ap_bflush(fr
->r
->connection
->client
);
953 ap_log_rerror(FCGI_LOG_INFO_NOERRNO
, fr
->r
,
954 "FastCGI: client stopped connection before send body completed");
958 ap_reset_timeout(fr
->r
);
961 #endif /* !APACHE2 */
963 fcgi_buf_toss(fr
->clientOutputBuffer
, count
);
967 /*******************************************************************************
968 * Determine the user and group the wrapper should be called with.
969 * Based on code in Apache's create_argv_cmd() (util_script.c).
971 static void set_uid_n_gid(request_rec
*r
, const char **user
, const char **group
)
973 if (fcgi_wrapper
== NULL
) {
979 if (strncmp("/~", r
->uri
, 2) == 0) {
980 /* its a user dir uri, just send the ~user, and leave it to the PM */
981 char *end
= strchr(r
->uri
+ 2, '/');
984 *user
= memcpy(ap_pcalloc(r
->pool
, end
- r
->uri
), r
->uri
+ 1, end
- r
->uri
- 1);
986 *user
= ap_pstrdup(r
->pool
, r
->uri
+ 1);
990 *user
= ap_psprintf(r
->pool
, "%ld", (long) fcgi_util_get_server_uid(r
->server
));
991 *group
= ap_psprintf(r
->pool
, "%ld", (long) fcgi_util_get_server_gid(r
->server
));
995 static void send_request_complete(fcgi_request
*fr
)
997 if (fr
->completeTime
.tv_sec
)
999 struct timeval qtime
, rtime
;
1001 timersub(&fr
->queueTime
, &fr
->startTime
, &qtime
);
1002 timersub(&fr
->completeTime
, &fr
->queueTime
, &rtime
);
1004 send_to_pm(FCGI_REQUEST_COMPLETE_JOB
, fr
->fs_path
,
1005 fr
->user
, fr
->group
,
1006 qtime
.tv_sec
* 1000000 + qtime
.tv_usec
,
1007 rtime
.tv_sec
* 1000000 + rtime
.tv_usec
);
1012 /*******************************************************************************
1013 * Connect to the FastCGI server.
1015 static int open_connection_to_fs(fcgi_request
*fr
)
1017 struct timeval tval
;
1018 fd_set write_fds
, read_fds
;
1020 request_rec
* const r
= fr
->r
;
1021 pool
* const rp
= r
->pool
;
1022 const char *socket_path
= NULL
;
1023 struct sockaddr
*socket_addr
= NULL
;
1024 int socket_addr_len
= 0;
1026 const char *err
= NULL
;
1029 /* Create the connection point */
1032 socket_path
= fcgi_util_socket_hash_filename(rp
, fr
->fs_path
, fr
->user
, fr
->group
);
1033 socket_path
= fcgi_util_socket_make_path_absolute(rp
, socket_path
, 1);
1036 err
= fcgi_util_socket_make_domain_addr(rp
, (struct sockaddr_un
**)&socket_addr
,
1037 &socket_addr_len
, socket_path
);
1039 ap_log_rerror(FCGI_LOG_ERR
, r
,
1040 "FastCGI: failed to connect to (dynamic) server \"%s\": "
1041 "%s", fr
->fs_path
, err
);
1049 if (fr
->fs
->dest_addr
!= NULL
) {
1050 socket_addr
= fr
->fs
->dest_addr
;
1052 else if (fr
->fs
->socket_addr
) {
1053 socket_addr
= fr
->fs
->socket_addr
;
1056 socket_path
= fr
->fs
->socket_path
;
1059 socket_addr
= fr
->fs
->socket_addr
;
1061 socket_addr_len
= fr
->fs
->socket_addr_len
;
1067 if (fr
->fs
&& fr
->fs
->restartTime
)
1069 struct stat sock_stat
;
1071 if (stat(socket_path
, &sock_stat
) == 0)
1075 if (dynamicAutoUpdate
)
1077 struct stat app_stat
;
1079 /* TODO: follow sym links */
1081 if (stat(fr
->fs_path
, &app_stat
) == 0)
1084 if (fr
->fs
->startTime
< app_stat
.st_mtime
)
1086 if (sock_stat
.st_mtime
< app_stat
.st_mtime
)
1090 struct timeval tv
= {1, 0};
1093 * There's a newer one, request a restart.
1095 send_to_pm(FCGI_SERVER_RESTART_JOB
, fr
->fs_path
, fr
->user
, fr
->group
, 0, 0);
1100 /* Avoid sleep/alarm interactions */
1101 ap_select(0, NULL
, NULL
, NULL
, &tv
);
1111 send_to_pm(FCGI_SERVER_START_JOB
, fr
->fs_path
, fr
->user
, fr
->group
, 0, 0);
1113 /* wait until it looks like its running - this shouldn't take
1114 * very long at all - the exception is when the sockets are
1115 * removed out from under a running application - the loop
1116 * limit addresses this (preventing spinning) */
1118 for (i
= 10; i
> 0; i
--)
1123 fr
->fs
= fcgi_util_fs_get_by_id(fr
->fs_path
, 0, 0);
1125 if (fr
->fs
&& fr
->fs
->restartTime
)
1127 struct timeval tv
= {0, 500000};
1129 /* Avoid sleep/alarm interactions */
1130 ap_select(0, NULL
, NULL
, NULL
, &tv
);
1132 if (stat(socket_path
, &sock_stat
) == 0)
1141 ap_log_rerror(FCGI_LOG_ALERT
, r
,
1142 "FastCGI: failed to connect to (dynamic) server \"%s\": "
1143 "something is seriously wrong, any chance the "
1144 "socket/named_pipe directory was removed?, see the "
1145 "FastCgiIpcDir directive", fr
->fs_path
);
1157 HANDLE wait_npipe_mutex
;
1159 DWORD max_connect_time
= FCGI_NAMED_PIPE_CONNECT_TIMEOUT
;
1161 fr
->using_npipe_io
= TRUE
;
1165 interval
= dynamicPleaseStartDelay
* 1000;
1167 if (dynamicAppConnectTimeout
) {
1168 max_connect_time
= dynamicAppConnectTimeout
;
1173 interval
= FCGI_NAMED_PIPE_CONNECT_TIMEOUT
* 1000;
1175 if (fr
->fs
->appConnectTimeout
) {
1176 max_connect_time
= fr
->fs
->appConnectTimeout
;
1180 fcgi_util_ticks(&fr
->startTime
);
1183 // xxx this handle should live somewhere (see CloseHandle()s below too)
1184 char * wait_npipe_mutex_name
, * cp
;
1185 wait_npipe_mutex_name
= cp
= ap_pstrdup(rp
, socket_path
);
1186 while ((cp
= strchr(cp
, '\\'))) *cp
= '/';
1188 wait_npipe_mutex
= CreateMutex(NULL
, FALSE
, wait_npipe_mutex_name
);
1191 if (wait_npipe_mutex
== NULL
)
1193 ap_log_rerror(FCGI_LOG_ERR
, r
,
1194 "FastCGI: failed to connect to server \"%s\": "
1195 "can't create the WaitNamedPipe mutex", fr
->fs_path
);
1199 SetLastError(ERROR_SUCCESS
);
1201 rv
= WaitForSingleObject(wait_npipe_mutex
, max_connect_time
* 1000);
1203 if (rv
== WAIT_TIMEOUT
|| rv
== WAIT_FAILED
)
1207 send_to_pm(FCGI_REQUEST_TIMEOUT_JOB
, fr
->fs_path
, fr
->user
, fr
->group
, 0, 0);
1209 ap_log_rerror(FCGI_LOG_ERR_NOERRNO
, r
,
1210 "FastCGI: failed to connect to server \"%s\": "
1211 "wait for a npipe instance failed", fr
->fs_path
);
1212 FCGIDBG3("interval=%d, max_connect_time=%d", interval
, max_connect_time
);
1213 CloseHandle(wait_npipe_mutex
);
1217 fcgi_util_ticks(&fr
->queueTime
);
1219 connect_time
= fr
->queueTime
.tv_sec
- fr
->startTime
.tv_sec
;
1223 if (connect_time
>= interval
)
1225 send_to_pm(FCGI_REQUEST_TIMEOUT_JOB
, fr
->fs_path
, fr
->user
, fr
->group
, 0, 0);
1226 FCGIDBG4("connect_time=%d, interval=%d, max_connect_time=%d", connect_time
, interval
, max_connect_time
);
1228 if (max_connect_time
- connect_time
< interval
)
1230 interval
= max_connect_time
- connect_time
;
1235 interval
-= connect_time
* 1000;
1240 ready
= WaitNamedPipe(socket_path
, interval
);
1244 fr
->fd
= (SOCKET
) CreateFile(socket_path
,
1245 GENERIC_READ
| GENERIC_WRITE
,
1246 FILE_SHARE_READ
| FILE_SHARE_WRITE
,
1247 NULL
, // no security attributes
1248 OPEN_EXISTING
, // opens existing pipe
1249 FILE_FLAG_OVERLAPPED
,
1250 NULL
); // no template file
1252 if (fr
->fd
!= (SOCKET
) INVALID_HANDLE_VALUE
)
1254 ReleaseMutex(wait_npipe_mutex
);
1255 CloseHandle(wait_npipe_mutex
);
1256 fcgi_util_ticks(&fr
->queueTime
);
1257 FCGIDBG2("got npipe connect: %s", fr
->fs_path
);
1261 if (GetLastError() != ERROR_PIPE_BUSY
1262 && GetLastError() != ERROR_FILE_NOT_FOUND
)
1264 ap_log_rerror(FCGI_LOG_ERR
, r
,
1265 "FastCGI: failed to connect to server \"%s\": "
1266 "CreateFile() failed", fr
->fs_path
);
1270 FCGIDBG2("missed npipe connect: %s", fr
->fs_path
);
1275 send_to_pm(FCGI_REQUEST_TIMEOUT_JOB
, fr
->fs_path
, fr
->user
, fr
->group
, 0, 0);
1278 fcgi_util_ticks(&fr
->queueTime
);
1280 connect_time
= fr
->queueTime
.tv_sec
- fr
->startTime
.tv_sec
;
1282 FCGIDBG5("interval=%d, max_connect_time=%d, connect_time=%d, ready=%d", interval
, max_connect_time
, connect_time
, ready
);
1284 if (connect_time
>= max_connect_time
)
1286 ap_log_rerror(FCGI_LOG_ERR
, r
,
1287 "FastCGI: failed to connect to server \"%s\": "
1288 "CreateFile()/WaitNamedPipe() timed out", fr
->fs_path
);
1293 ReleaseMutex(wait_npipe_mutex
);
1294 CloseHandle(wait_npipe_mutex
);
1295 fr
->fd
= INVALID_SOCKET
;
1301 /* Create the socket */
1302 fr
->fd
= socket(socket_addr
->sa_family
, SOCK_STREAM
, 0);
1305 if (fr
->fd
== INVALID_SOCKET
) {
1306 errno
= WSAGetLastError(); // Not sure this is going to work as expected
1310 ap_log_rerror(FCGI_LOG_ERR_ERRNO
, r
,
1311 "FastCGI: failed to connect to server \"%s\": "
1312 "socket() failed", fr
->fs_path
);
1317 if (fr
->fd
>= FD_SETSIZE
) {
1318 ap_log_rerror(FCGI_LOG_ERR
, r
,
1319 "FastCGI: failed to connect to server \"%s\": "
1320 "socket file descriptor (%u) is larger than "
1321 "FD_SETSIZE (%u), you probably need to rebuild Apache with a "
1322 "larger FD_SETSIZE", fr
->fs_path
, fr
->fd
, FD_SETSIZE
);
1327 /* If appConnectTimeout is non-zero, setup do a non-blocking connect */
1328 if ((fr
->dynamic
&& dynamicAppConnectTimeout
) || (!fr
->dynamic
&& fr
->fs
->appConnectTimeout
)) {
1329 set_nonblocking(fr
, TRUE
);
1333 fcgi_util_ticks(&fr
->startTime
);
1337 if (connect(fr
->fd
, (struct sockaddr
*)socket_addr
, socket_addr_len
) == 0)
1338 goto ConnectionComplete
;
1342 errno
= WSAGetLastError();
1343 if (errno
!= WSAEWOULDBLOCK
) {
1344 ap_log_rerror(FCGI_LOG_ERR_ERRNO
, r
,
1345 "FastCGI: failed to connect to server \"%s\": "
1346 "connect() failed", fr
->fs_path
);
1352 /* ECONNREFUSED means the listen queue is full (or there isn't one).
1353 * With dynamic I can at least make sure the PM knows this is occuring */
1354 if (fr
->dynamic
&& errno
== ECONNREFUSED
) {
1355 /* @@@ This might be better as some other "kind" of message */
1356 send_to_pm(FCGI_REQUEST_TIMEOUT_JOB
, fr
->fs_path
, fr
->user
, fr
->group
, 0, 0);
1358 errno
= ECONNREFUSED
;
1361 if (errno
!= EINPROGRESS
) {
1362 ap_log_rerror(FCGI_LOG_ERR
, r
,
1363 "FastCGI: failed to connect to server \"%s\": "
1364 "connect() failed", fr
->fs_path
);
1370 /* The connect() is non-blocking */
1376 FD_ZERO(&write_fds
);
1377 FD_SET(fr
->fd
, &write_fds
);
1378 read_fds
= write_fds
;
1379 tval
.tv_sec
= dynamicPleaseStartDelay
;
1382 status
= ap_select((fr
->fd
+1), &read_fds
, &write_fds
, NULL
, &tval
);
1386 fcgi_util_ticks(&fr
->queueTime
);
1391 /* select() timed out */
1392 send_to_pm(FCGI_REQUEST_TIMEOUT_JOB
, fr
->fs_path
, fr
->user
, fr
->group
, 0, 0);
1393 } while ((fr
->queueTime
.tv_sec
- fr
->startTime
.tv_sec
) < (int)dynamicAppConnectTimeout
);
1395 /* XXX These can be moved down when dynamic vars live is a struct */
1397 ap_log_rerror(FCGI_LOG_ERR_NOERRNO
, r
,
1398 "FastCGI: failed to connect to server \"%s\": "
1399 "connect() timed out (appConnTimeout=%dsec)",
1400 fr
->fs_path
, dynamicAppConnectTimeout
);
1405 tval
.tv_sec
= fr
->fs
->appConnectTimeout
;
1407 FD_ZERO(&write_fds
);
1408 FD_SET(fr
->fd
, &write_fds
);
1409 read_fds
= write_fds
;
1411 status
= ap_select((fr
->fd
+1), &read_fds
, &write_fds
, NULL
, &tval
);
1414 ap_log_rerror(FCGI_LOG_ERR_NOERRNO
, r
,
1415 "FastCGI: failed to connect to server \"%s\": "
1416 "connect() timed out (appConnTimeout=%dsec)",
1417 fr
->fs_path
, dynamicAppConnectTimeout
);
1424 errno
= WSAGetLastError();
1426 ap_log_rerror(FCGI_LOG_ERR_ERRNO
, r
,
1427 "FastCGI: failed to connect to server \"%s\": "
1428 "select() failed", fr
->fs_path
);
1432 if (FD_ISSET(fr
->fd
, &write_fds
) || FD_ISSET(fr
->fd
, &read_fds
)) {
1434 NET_SIZE_T len
= sizeof(error
);
1436 if (getsockopt(fr
->fd
, SOL_SOCKET
, SO_ERROR
, (char *)&error
, &len
) < 0) {
1437 /* Solaris pending error */
1439 errno
= WSAGetLastError();
1441 ap_log_rerror(FCGI_LOG_ERR_ERRNO
, r
,
1442 "FastCGI: failed to connect to server \"%s\": "
1443 "select() failed (Solaris pending error)", fr
->fs_path
);
1448 /* Berkeley-derived pending error */
1450 ap_log_rerror(FCGI_LOG_ERR_ERRNO
, r
,
1451 "FastCGI: failed to connect to server \"%s\": "
1452 "select() failed (pending error)", fr
->fs_path
);
1458 errno
= WSAGetLastError();
1460 ap_log_rerror(FCGI_LOG_ERR_ERRNO
, r
,
1461 "FastCGI: failed to connect to server \"%s\": "
1462 "select() error - THIS CAN'T HAPPEN!", fr
->fs_path
);
1467 /* Return to blocking mode if it was set up */
1468 if ((fr
->dynamic
&& dynamicAppConnectTimeout
) || (!fr
->dynamic
&& fr
->fs
->appConnectTimeout
)) {
1469 set_nonblocking(fr
, FALSE
);
1473 if (socket_addr
->sa_family
== AF_INET
) {
1474 /* We shouldn't be sending small packets and there's no application
1475 * level ack of the data we send, so disable Nagle */
1477 setsockopt(fr
->fd
, IPPROTO_TCP
, TCP_NODELAY
, (char *)&set
, sizeof(set
));
1484 static void sink_client_data(fcgi_request
*fr
)
1489 fcgi_buf_reset(fr
->clientInputBuffer
);
1490 fcgi_buf_get_free_block_info(fr
->clientInputBuffer
, &base
, &size
);
1491 while (ap_get_client_block(fr
->r
, base
, size
) > 0);
1494 static apcb_t
cleanup(void *data
)
1496 fcgi_request
* const fr
= (fcgi_request
*) data
;
1498 if (fr
== NULL
) return APCB_OK
;
1500 /* its more than likely already run, but... */
1501 close_connection_to_fs(fr
);
1503 send_request_complete(fr
);
1505 if (fr
->fs_stderr_len
) {
1506 ap_log_rerror(FCGI_LOG_ERR_NOERRNO
, fr
->r
,
1507 "FastCGI: server \"%s\" stderr: %s", fr
->fs_path
, fr
->fs_stderr
);
1514 static int npipe_io(fcgi_request
* const fr
)
1516 request_rec
* const r
= fr
->r
;
1527 state
= STATE_ENV_SEND
;
1528 env_status env_status
;
1530 int dynamic_first_recv
= fr
->dynamic
;
1531 int idle_timeout
= fr
->dynamic
? dynamic_idle_timeout
: fr
->fs
->idle_timeout
;
1532 int send_pending
= 0;
1533 int recv_pending
= 0;
1534 int client_send
= 0;
1536 OVERLAPPED rov
= { 0 };
1537 OVERLAPPED sov
= { 0 };
1539 struct timeval timeout
;
1540 struct timeval dynamic_last_io_time
= {0, 0};
1542 pool
* const rp
= r
->pool
;
1544 DWORD recv_count
= 0;
1546 if (fr
->role
== FCGI_RESPONDER
)
1548 client_recv
= (fr
->expectingClientContent
!= 0);
1551 idle_timeout
= fr
->dynamic
? dynamic_idle_timeout
: fr
->fs
->idle_timeout
;
1553 env_status
.envp
= NULL
;
1555 events
[0] = CreateEvent(NULL
, TRUE
, FALSE
, NULL
);
1556 events
[1] = CreateEvent(NULL
, TRUE
, FALSE
, NULL
);
1557 sov
.hEvent
= events
[0];
1558 rov
.hEvent
= events
[1];
1562 dynamic_last_io_time
= fr
->startTime
;
1564 if (dynamicAppConnectTimeout
)
1566 struct timeval qwait
;
1567 timersub(&fr
->queueTime
, &fr
->startTime
, &qwait
);
1568 dynamic_first_recv
= qwait
.tv_sec
/ dynamicPleaseStartDelay
+ 1;
1572 ap_hard_timeout("FastCGI request processing", r
);
1574 while (state
!= STATE_CLIENT_SEND
)
1580 case STATE_ENV_SEND
:
1582 if (fcgi_protocol_queue_env(r
, fr
, &env_status
) == 0)
1587 state
= STATE_CLIENT_RECV
;
1591 case STATE_CLIENT_RECV
:
1593 if (read_from_client_n_queue(fr
) != OK
)
1595 state
= STATE_CLIENT_ERROR
;
1601 state
= STATE_SERVER_SEND
;
1608 case STATE_SERVER_SEND
:
1610 if (! send_pending
&& BufferLength(fr
->serverOutputBuffer
))
1612 Buffer
* b
= fr
->serverOutputBuffer
;
1615 len
= min(b
->length
, b
->data
+ b
->size
- b
->begin
);
1617 if (WriteFile((HANDLE
) fr
->fd
, b
->begin
, len
, &sent
, &sov
))
1619 fcgi_buf_removed(b
, sent
);
1620 ResetEvent(sov
.hEvent
);
1622 else if (GetLastError() == ERROR_IO_PENDING
)
1628 ap_log_rerror(FCGI_LOG_ERR
, r
, "FastCGI: comm with server "
1629 "\"%s\" aborted: WriteFile() failed", fr
->fs_path
);
1630 state
= STATE_ERROR
;
1637 case STATE_SERVER_RECV
:
1640 * Only get more data when the serverInputBuffer is empty.
1641 * Otherwise we may already have the END_REQUEST buffered
1642 * (but not processed) and a read on a closed named pipe
1643 * results in an error that is normally abnormal.
1645 if (! recv_pending
&& BufferLength(fr
->serverInputBuffer
) == 0)
1647 Buffer
* b
= fr
->serverInputBuffer
;
1650 len
= min(b
->size
- b
->length
, b
->data
+ b
->size
- b
->end
);
1652 if (ReadFile((HANDLE
) fr
->fd
, b
->end
, len
, &rcvd
, &rov
))
1654 fcgi_buf_added(b
, rcvd
);
1656 ResetEvent(rov
.hEvent
);
1657 if (dynamic_first_recv
)
1659 dynamic_first_recv
= 0;
1662 else if (GetLastError() == ERROR_IO_PENDING
)
1666 else if (GetLastError() == ERROR_HANDLE_EOF
)
1668 fr
->keepReadingFromFcgiApp
= FALSE
;
1669 state
= STATE_CLIENT_SEND
;
1670 ResetEvent(rov
.hEvent
);
1673 else if (GetLastError() == ERROR_NO_DATA
)
1679 ap_log_rerror(FCGI_LOG_ERR
, r
, "FastCGI: comm with server "
1680 "\"%s\" aborted: ReadFile() failed", fr
->fs_path
);
1681 state
= STATE_ERROR
;
1688 case STATE_CLIENT_SEND
:
1690 if (client_send
|| ! BufferFree(fr
->clientOutputBuffer
))
1692 if (write_to_client(fr
))
1694 state
= STATE_CLIENT_ERROR
;
1708 if (state
== STATE_CLIENT_ERROR
|| state
== STATE_ERROR
)
1713 /* setup the io timeout */
1715 if (BufferLength(fr
->clientOutputBuffer
))
1717 /* don't let client data sit too long, it might be a push */
1719 timeout
.tv_usec
= 100000;
1721 else if (dynamic_first_recv
)
1724 struct timeval qwait
;
1726 fcgi_util_ticks(&fr
->queueTime
);
1730 /* a send() succeeded last pass */
1731 dynamic_last_io_time
= fr
->queueTime
;
1735 /* timed out last pass */
1736 struct timeval idle_time
;
1738 timersub(&fr
->queueTime
, &dynamic_last_io_time
, &idle_time
);
1740 if (idle_time
.tv_sec
> idle_timeout
)
1742 send_to_pm(FCGI_REQUEST_TIMEOUT_JOB
, fr
->fs_path
, fr
->user
, fr
->group
, 0, 0);
1743 ap_log_rerror(FCGI_LOG_ERR_NOERRNO
, r
, "FastCGI: comm "
1744 "with (dynamic) server \"%s\" aborted: (first read) "
1745 "idle timeout (%d sec)", fr
->fs_path
, idle_timeout
);
1746 state
= STATE_ERROR
;
1751 timersub(&fr
->queueTime
, &fr
->startTime
, &qwait
);
1753 delay
= dynamic_first_recv
* dynamicPleaseStartDelay
;
1755 if (qwait
.tv_sec
< delay
)
1757 timeout
.tv_sec
= delay
;
1758 timeout
.tv_usec
= 100000; /* fudge for select() slop */
1759 timersub(&timeout
, &qwait
, &timeout
);
1763 /* Killed time somewhere.. client read? */
1764 send_to_pm(FCGI_REQUEST_TIMEOUT_JOB
, fr
->fs_path
, fr
->user
, fr
->group
, 0, 0);
1765 dynamic_first_recv
= qwait
.tv_sec
/ dynamicPleaseStartDelay
+ 1;
1766 timeout
.tv_sec
= dynamic_first_recv
* dynamicPleaseStartDelay
;
1767 timeout
.tv_usec
= 100000; /* fudge for select() slop */
1768 timersub(&timeout
, &qwait
, &timeout
);
1773 timeout
.tv_sec
= idle_timeout
;
1774 timeout
.tv_usec
= 0;
1777 /* require a pended recv otherwise the app can deadlock */
1780 msec_timeout
= timeout
.tv_sec
* 1000 + timeout
.tv_usec
/ 1000;
1782 rv
= WaitForMultipleObjects(2, events
, FALSE
, msec_timeout
);
1784 if (rv
== WAIT_TIMEOUT
)
1788 if (BufferLength(fr
->clientOutputBuffer
))
1792 else if (dynamic_first_recv
)
1794 struct timeval qwait
;
1796 fcgi_util_ticks(&fr
->queueTime
);
1797 timersub(&fr
->queueTime
, &fr
->startTime
, &qwait
);
1799 send_to_pm(FCGI_REQUEST_TIMEOUT_JOB
, fr
->fs_path
, fr
->user
, fr
->group
, 0, 0);
1801 dynamic_first_recv
= qwait
.tv_sec
/ dynamicPleaseStartDelay
+ 1;
1805 ap_log_rerror(FCGI_LOG_ERR_NOERRNO
, r
, "FastCGI: comm with "
1806 "server \"%s\" aborted: idle timeout (%d sec)",
1807 fr
->fs_path
, idle_timeout
);
1808 state
= STATE_ERROR
;
1814 int i
= rv
- WAIT_OBJECT_0
;
1822 if (GetOverlappedResult((HANDLE
) fr
->fd
, &sov
, &sent
, FALSE
))
1825 ResetEvent(sov
.hEvent
);
1826 fcgi_buf_removed(fr
->serverOutputBuffer
, sent
);
1830 ap_log_rerror(FCGI_LOG_ERR
, r
, "FastCGI: comm with server "
1831 "\"%s\" aborted: GetOverlappedResult() failed", fr
->fs_path
);
1832 state
= STATE_ERROR
;
1843 ResetEvent(rov
.hEvent
);
1845 if (GetOverlappedResult((HANDLE
) fr
->fd
, &rov
, &rcvd
, FALSE
))
1847 fcgi_buf_added(fr
->serverInputBuffer
, rcvd
);
1848 if (dynamic_first_recv
)
1850 dynamic_first_recv
= 0;
1855 ap_log_rerror(FCGI_LOG_ERR
, r
, "FastCGI: comm with server "
1856 "\"%s\" aborted: GetOverlappedResult() failed", fr
->fs_path
);
1857 state
= STATE_ERROR
;
1864 if (fcgi_protocol_dequeue(rp
, fr
))
1866 state
= STATE_ERROR
;
1870 if (fr
->parseHeader
== SCAN_CGI_READING_HEADERS
)
1872 const char * err
= process_headers(r
, fr
);
1875 ap_log_rerror(FCGI_LOG_ERR_NOERRNO
, r
,
1876 "FastCGI: comm with server \"%s\" aborted: "
1877 "error parsing headers: %s", fr
->fs_path
, err
);
1878 state
= STATE_ERROR
;
1883 if (fr
->exitStatusSet
)
1885 fr
->keepReadingFromFcgiApp
= FALSE
;
1886 state
= STATE_CLIENT_SEND
;
1891 if (! fr
->exitStatusSet
|| ! fr
->eofSent
)
1893 CancelIo((HANDLE
) fr
->fd
);
1896 CloseHandle(rov
.hEvent
);
1897 CloseHandle(sov
.hEvent
);
1899 return (state
== STATE_ERROR
);
1903 static int socket_io(fcgi_request
* const fr
)
1916 state
= STATE_ENV_SEND
;
1918 request_rec
* const r
= fr
->r
;
1920 struct timeval timeout
;
1921 struct timeval dynamic_last_io_time
= {0, 0};
1924 int nfds
= fr
->fd
+ 1;
1925 int select_status
= 1;
1928 int dynamic_first_recv
= fr
->dynamic
? 1 : 0;
1929 int client_send
= FALSE
;
1930 int client_recv
= FALSE
;
1934 if (fr
->role
== FCGI_RESPONDER
)
1936 client_recv
= (fr
->expectingClientContent
!= 0);
1939 idle_timeout
= fr
->dynamic
? dynamic_idle_timeout
: fr
->fs
->idle_timeout
;
1945 dynamic_last_io_time
= fr
->startTime
;
1947 if (dynamicAppConnectTimeout
)
1949 struct timeval qwait
;
1950 timersub(&fr
->queueTime
, &fr
->startTime
, &qwait
);
1951 dynamic_first_recv
= qwait
.tv_sec
/ dynamicPleaseStartDelay
+ 1;
1955 ap_hard_timeout("FastCGI request processing", r
);
1957 set_nonblocking(fr
, TRUE
);
1962 FD_ZERO(&write_set
);
1966 case STATE_ENV_SEND
:
1968 if (fcgi_protocol_queue_env(r
, fr
, &env
) == 0)
1973 state
= STATE_CLIENT_RECV
;
1977 case STATE_CLIENT_RECV
:
1979 if (read_from_client_n_queue(fr
))
1981 state
= STATE_CLIENT_ERROR
;
1987 state
= STATE_SERVER_SEND
;
1994 case STATE_SERVER_SEND
:
1996 if (BufferLength(fr
->serverOutputBuffer
))
1998 FD_SET(fr
->fd
, &write_set
);
2002 ap_assert(fr
->eofSent
);
2003 state
= STATE_SERVER_RECV
;
2008 case STATE_SERVER_RECV
:
2010 FD_SET(fr
->fd
, &read_set
);
2014 case STATE_CLIENT_SEND
:
2016 if (client_send
|| ! BufferFree(fr
->clientOutputBuffer
))
2018 if (write_to_client(fr
))
2020 state
= STATE_CLIENT_ERROR
;
2030 case STATE_CLIENT_ERROR
:
2039 if (state
== STATE_CLIENT_ERROR
|| state
== STATE_ERROR
)
2044 /* setup the io timeout */
2046 if (BufferLength(fr
->clientOutputBuffer
))
2048 /* don't let client data sit too long, it might be a push */
2050 timeout
.tv_usec
= 100000;
2052 else if (dynamic_first_recv
)
2055 struct timeval qwait
;
2057 fcgi_util_ticks(&fr
->queueTime
);
2061 /* a send() succeeded last pass */
2062 dynamic_last_io_time
= fr
->queueTime
;
2066 /* timed out last pass */
2067 struct timeval idle_time
;
2069 timersub(&fr
->queueTime
, &dynamic_last_io_time
, &idle_time
);
2071 if (idle_time
.tv_sec
> idle_timeout
)
2073 send_to_pm(FCGI_REQUEST_TIMEOUT_JOB
, fr
->fs_path
, fr
->user
, fr
->group
, 0, 0);
2074 ap_log_rerror(FCGI_LOG_ERR_NOERRNO
, r
, "FastCGI: comm "
2075 "with (dynamic) server \"%s\" aborted: (first read) "
2076 "idle timeout (%d sec)", fr
->fs_path
, idle_timeout
);
2077 state
= STATE_ERROR
;
2082 timersub(&fr
->queueTime
, &fr
->startTime
, &qwait
);
2084 delay
= dynamic_first_recv
* dynamicPleaseStartDelay
;
2086 FCGIDBG5("qwait=%ld.%06ld delay=%d first_recv=%d", qwait
.tv_sec
, qwait
.tv_usec
, delay
, dynamic_first_recv
);
2088 if (qwait
.tv_sec
< delay
)
2090 timeout
.tv_sec
= delay
;
2091 timeout
.tv_usec
= 100000; /* fudge for select() slop */
2092 timersub(&timeout
, &qwait
, &timeout
);
2096 /* Killed time somewhere.. client read? */
2097 send_to_pm(FCGI_REQUEST_TIMEOUT_JOB
, fr
->fs_path
, fr
->user
, fr
->group
, 0, 0);
2098 dynamic_first_recv
= qwait
.tv_sec
/ dynamicPleaseStartDelay
+ 1;
2099 timeout
.tv_sec
= dynamic_first_recv
* dynamicPleaseStartDelay
;
2100 timeout
.tv_usec
= 100000; /* fudge for select() slop */
2101 timersub(&timeout
, &qwait
, &timeout
);
2106 timeout
.tv_sec
= idle_timeout
;
2107 timeout
.tv_usec
= 0;
2110 /* wait on the socket */
2111 select_status
= ap_select(nfds
, &read_set
, &write_set
, NULL
, &timeout
);
2113 if (select_status
< 0)
2115 ap_log_rerror(FCGI_LOG_ERR_ERRNO
, r
, "FastCGI: comm with server "
2116 "\"%s\" aborted: select() failed", fr
->fs_path
);
2117 state
= STATE_ERROR
;
2121 if (select_status
== 0)
2123 /* select() timeout */
2125 if (BufferLength(fr
->clientOutputBuffer
))
2127 if (fr
->role
== FCGI_RESPONDER
)
2132 else if (dynamic_first_recv
)
2134 struct timeval qwait
;
2136 fcgi_util_ticks(&fr
->queueTime
);
2137 timersub(&fr
->queueTime
, &fr
->startTime
, &qwait
);
2139 send_to_pm(FCGI_REQUEST_TIMEOUT_JOB
, fr
->fs_path
, fr
->user
, fr
->group
, 0, 0);
2141 dynamic_first_recv
= qwait
.tv_sec
/ dynamicPleaseStartDelay
+ 1;
2146 ap_log_rerror(FCGI_LOG_ERR_NOERRNO
, r
, "FastCGI: comm with "
2147 "server \"%s\" aborted: idle timeout (%d sec)",
2148 fr
->fs_path
, idle_timeout
);
2149 state
= STATE_ERROR
;
2153 if (FD_ISSET(fr
->fd
, &write_set
))
2155 /* send to the server */
2157 rv
= fcgi_buf_socket_send(fr
->serverOutputBuffer
, fr
->fd
);
2161 ap_log_rerror(FCGI_LOG_ERR
, r
, "FastCGI: comm with server "
2162 "\"%s\" aborted: write failed", fr
->fs_path
);
2163 state
= STATE_ERROR
;
2168 if (FD_ISSET(fr
->fd
, &read_set
))
2170 /* recv from the server */
2172 if (dynamic_first_recv
)
2174 dynamic_first_recv
= 0;
2175 fcgi_util_ticks(&fr
->queueTime
);
2178 rv
= fcgi_buf_socket_recv(fr
->serverInputBuffer
, fr
->fd
);
2182 ap_log_rerror(FCGI_LOG_ERR
, r
, "FastCGI: comm with server "
2183 "\"%s\" aborted: read failed", fr
->fs_path
);
2184 state
= STATE_ERROR
;
2190 fr
->keepReadingFromFcgiApp
= FALSE
;
2191 state
= STATE_CLIENT_SEND
;
2196 if (fcgi_protocol_dequeue(rp
, fr
))
2198 state
= STATE_ERROR
;
2202 if (fr
->parseHeader
== SCAN_CGI_READING_HEADERS
)
2204 const char * err
= process_headers(r
, fr
);
2207 ap_log_rerror(FCGI_LOG_ERR_NOERRNO
, r
,
2208 "FastCGI: comm with server \"%s\" aborted: "
2209 "error parsing headers: %s", fr
->fs_path
, err
);
2210 state
= STATE_ERROR
;
2215 if (fr
->exitStatusSet
)
2217 fr
->keepReadingFromFcgiApp
= FALSE
;
2218 state
= STATE_CLIENT_SEND
;
2223 return (state
== STATE_ERROR
);
2227 /*----------------------------------------------------------------------
2228 * This is the core routine for moving data between the FastCGI
2229 * application and the Web server's client.
2231 static int do_work(request_rec
* const r
, fcgi_request
* const fr
)
2236 fcgi_protocol_queue_begin_request(fr
);
2238 if (fr
->role
== FCGI_RESPONDER
)
2240 rv
= ap_setup_client_block(r
, REQUEST_CHUNKED_ERROR
);
2247 fr
->expectingClientContent
= ap_should_client_block(r
);
2251 ap_register_cleanup(rp
, (void *)fr
, cleanup
, ap_null_cleanup
);
2252 ap_unblock_alarms();
2254 ap_hard_timeout("connect() to FastCGI server", r
);
2256 /* Connect to the FastCGI Application */
2257 if (open_connection_to_fs(fr
) != FCGI_OK
)
2260 return HTTP_INTERNAL_SERVER_ERROR
;
2264 if (fr
->using_npipe_io
)
2274 /* comm with the server is done */
2275 close_connection_to_fs(fr
);
2277 if (fr
->role
== FCGI_RESPONDER
)
2279 sink_client_data(fr
);
2282 while (rv
== 0 && (BufferLength(fr
->serverInputBuffer
) || BufferLength(fr
->clientOutputBuffer
)))
2284 if (fcgi_protocol_dequeue(rp
, fr
))
2286 rv
= HTTP_INTERNAL_SERVER_ERROR
;
2289 if (fr
->parseHeader
== SCAN_CGI_READING_HEADERS
)
2291 const char * err
= process_headers(r
, fr
);
2294 ap_log_rerror(FCGI_LOG_ERR_NOERRNO
, r
,
2295 "FastCGI: comm with server \"%s\" aborted: "
2296 "error parsing headers: %s", fr
->fs_path
, err
);
2297 rv
= HTTP_INTERNAL_SERVER_ERROR
;
2301 if (fr
->role
== FCGI_RESPONDER
)
2303 if (write_to_client(fr
))
2310 fcgi_buf_reset(fr
->clientOutputBuffer
);
2314 switch (fr
->parseHeader
)
2316 case SCAN_CGI_FINISHED
:
2318 if (fr
->role
== FCGI_RESPONDER
)
2320 /* RUSSIAN_APACHE requires rflush() over bflush() */
2323 ap_bgetopt(r
->connection
->client
, BO_BYTECT
, &r
->bytes_sent
);
2329 case SCAN_CGI_INT_REDIRECT
:
2330 case SCAN_CGI_SRV_REDIRECT
:
2334 case SCAN_CGI_READING_HEADERS
:
2336 ap_log_rerror(FCGI_LOG_ERR_NOERRNO
, r
, "FastCGI: incomplete headers "
2337 "(%d bytes) received from server \"%s\"", fr
->header
->nelts
, fr
->fs_path
);
2341 case SCAN_CGI_BAD_HEADER
:
2343 rv
= HTTP_INTERNAL_SERVER_ERROR
;
2349 rv
= HTTP_INTERNAL_SERVER_ERROR
;
2356 static fcgi_request
*create_fcgi_request(request_rec
* const r
, const char *path
)
2358 const char *fs_path
;
2359 pool
* const p
= r
->pool
;
2361 fcgi_request
* const fr
= (fcgi_request
*)ap_pcalloc(p
, sizeof(fcgi_request
));
2363 fs_path
= path
? path
: r
->filename
;
2365 fs
= fcgi_util_fs_get_by_id(fs_path
, fcgi_util_get_server_uid(r
->server
),
2366 fcgi_util_get_server_gid(r
->server
));
2370 struct stat
*my_finfo
;
2377 /* AP2: its bogus that we don't make use of r->finfo, but
2378 * its an apr_finfo_t and there is no apr_os_finfo_get() */
2380 my_finfo
= &r
->finfo
;
2385 my_finfo
= (struct stat
*) ap_palloc(p
, sizeof(struct stat
));
2387 if (stat(fs_path
, my_finfo
) < 0)
2389 ap_log_rerror(FCGI_LOG_ERR_ERRNO
, r
,
2390 "FastCGI: stat() of \"%s\" failed", fs_path
);
2395 err
= fcgi_util_fs_is_path_ok(p
, fs_path
, my_finfo
);
2399 ap_log_rerror(FCGI_LOG_ERR_NOERRNO
, r
,
2400 "FastCGI: invalid (dynamic) server \"%s\": %s", fs_path
, err
);
2405 fr
->serverInputBuffer
= fcgi_buf_new(p
, SERVER_BUFSIZE
);
2406 fr
->serverOutputBuffer
= fcgi_buf_new(p
, SERVER_BUFSIZE
);
2407 fr
->clientInputBuffer
= fcgi_buf_new(p
, SERVER_BUFSIZE
);
2408 fr
->clientOutputBuffer
= fcgi_buf_new(p
, SERVER_BUFSIZE
);
2409 fr
->erBufPtr
= fcgi_buf_new(p
, sizeof(FCGI_EndRequestBody
) + 1);
2410 fr
->gotHeader
= FALSE
;
2411 fr
->parseHeader
= SCAN_CGI_READING_HEADERS
;
2412 fr
->header
= ap_make_array(p
, 1, 1);
2413 fr
->fs_stderr
= NULL
;
2415 fr
->readingEndRequestBody
= FALSE
;
2417 fr
->exitStatusSet
= FALSE
;
2418 fr
->requestId
= 1; /* anything but zero is OK here */
2419 fr
->eofSent
= FALSE
;
2420 fr
->role
= FCGI_RESPONDER
;
2421 fr
->expectingClientContent
= FALSE
;
2422 fr
->keepReadingFromFcgiApp
= TRUE
;
2424 fr
->fs_path
= fs_path
;
2425 fr
->authHeaders
= ap_make_table(p
, 10);
2427 fr
->fd
= INVALID_SOCKET
;
2428 fr
->dynamic
= ((fs
== NULL
) || (fs
->directive
== APP_CLASS_DYNAMIC
)) ? TRUE
: FALSE
;
2429 fr
->using_npipe_io
= FALSE
;
2431 fr
->dynamic
= (fs
== NULL
) ? TRUE
: FALSE
;
2435 set_uid_n_gid(r
, &fr
->user
, &fr
->group
);
2441 *----------------------------------------------------------------------
2445 * This routine gets called for a request that corresponds to
2446 * a FastCGI connection. It performs the request synchronously.
2449 * Final status of request: OK or NOT_FOUND or HTTP_INTERNAL_SERVER_ERROR.
2452 * Request performed.
2454 *----------------------------------------------------------------------
2457 /* Stolen from mod_cgi.c..
2458 * KLUDGE --- for back-combatibility, we don't have to check ExecCGI
2459 * in ScriptAliased directories, which means we need to know if this
2460 * request came through ScriptAlias or not... so the Alias module
2461 * leaves a note for us.
2463 static int apache_is_scriptaliased(request_rec
*r
)
2465 const char *t
= ap_table_get(r
->notes
, "alias-forced-type");
2466 return t
&& (!strcasecmp(t
, "cgi-script"));
2469 /* If a script wants to produce its own Redirect body, it now
2470 * has to explicitly *say* "Status: 302". If it wants to use
2471 * Apache redirects say "Status: 200". See process_headers().
2473 static int post_process_for_redirects(request_rec
* const r
,
2474 const fcgi_request
* const fr
)
2476 switch(fr
->parseHeader
) {
2477 case SCAN_CGI_INT_REDIRECT
:
2479 /* @@@ There are still differences between the handling in
2480 * mod_cgi and mod_fastcgi. This needs to be revisited.
2482 /* We already read the message body (if any), so don't allow
2483 * the redirected request to think it has one. We can ignore
2484 * Transfer-Encoding, since we used REQUEST_CHUNKED_ERROR.
2487 r
->method_number
= M_GET
;
2488 ap_table_unset(r
->headers_in
, "Content-length");
2490 ap_internal_redirect_handler(ap_table_get(r
->headers_out
, "Location"), r
);
2493 case SCAN_CGI_SRV_REDIRECT
:
2494 return HTTP_MOVED_TEMPORARILY
;
2501 /******************************************************************************
2502 * Process fastcgi-script requests. Based on mod_cgi::cgi_handler().
2504 static int content_handler(request_rec
*r
)
2506 fcgi_request
*fr
= NULL
;
2510 if (strcmp(r
->handler
, FASTCGI_HANDLER_NAME
))
2514 /* Setup a new FastCGI request */
2515 if ((fr
= create_fcgi_request(r
, NULL
)) == NULL
)
2516 return HTTP_INTERNAL_SERVER_ERROR
;
2518 /* If its a dynamic invocation, make sure scripts are OK here */
2519 if (fr
->dynamic
&& !(ap_allow_options(r
) & OPT_EXECCGI
) && !apache_is_scriptaliased(r
)) {
2520 ap_log_rerror(FCGI_LOG_ERR_NOERRNO
, r
,
2521 "FastCGI: \"ExecCGI Option\" is off in this directory: %s", r
->uri
);
2522 return HTTP_INTERNAL_SERVER_ERROR
;
2525 /* Process the fastcgi-script request */
2526 if ((ret
= do_work(r
, fr
)) != OK
)
2529 /* Special case redirects */
2530 ret
= post_process_for_redirects(r
, fr
);
2536 static int post_process_auth_passed_header(table
*t
, const char *key
, const char * const val
)
2538 if (strncasecmp(key
, "Variable-", 9) == 0)
2541 ap_table_setn(t
, key
, val
);
2545 static int post_process_auth_passed_compat_header(table
*t
, const char *key
, const char * const val
)
2547 if (strncasecmp(key
, "Variable-", 9) == 0)
2548 ap_table_setn(t
, key
+ 9, val
);
2553 static int post_process_auth_failed_header(table
* const t
, const char * const key
, const char * const val
)
2555 ap_table_setn(t
, key
, val
);
2559 static void post_process_auth(fcgi_request
* const fr
, const int passed
)
2561 request_rec
* const r
= fr
->r
;
2563 /* Restore the saved subprocess_env because we muddied ours up */
2564 r
->subprocess_env
= fr
->saved_subprocess_env
;
2567 if (fr
->auth_compat
) {
2568 ap_table_do((int (*)(void *, const char *, const char *))post_process_auth_passed_compat_header
,
2569 (void *)r
->subprocess_env
, fr
->authHeaders
, NULL
);
2572 ap_table_do((int (*)(void *, const char *, const char *))post_process_auth_passed_header
,
2573 (void *)r
->subprocess_env
, fr
->authHeaders
, NULL
);
2577 ap_table_do((int (*)(void *, const char *, const char *))post_process_auth_failed_header
,
2578 (void *)r
->err_headers_out
, fr
->authHeaders
, NULL
);
2581 /* @@@ Restore these.. its a hack until I rewrite the header handling */
2582 r
->status
= HTTP_OK
;
2583 r
->status_line
= NULL
;
2586 static int check_user_authentication(request_rec
*r
)
2588 int res
, authenticated
= 0;
2589 const char *password
;
2591 const fcgi_dir_config
* const dir_config
=
2592 (const fcgi_dir_config
*)ap_get_module_config(r
->per_dir_config
, &fastcgi_module
);
2594 if (dir_config
->authenticator
== NULL
)
2597 /* Get the user password */
2598 if ((res
= ap_get_basic_auth_pw(r
, &password
)) != OK
)
2601 if ((fr
= create_fcgi_request(r
, dir_config
->authenticator
)) == NULL
)
2602 return HTTP_INTERNAL_SERVER_ERROR
;
2604 /* Save the existing subprocess_env, because we're gonna muddy it up */
2605 fr
->saved_subprocess_env
= ap_copy_table(r
->pool
, r
->subprocess_env
);
2607 ap_table_setn(r
->subprocess_env
, "REMOTE_PASSWD", password
);
2608 ap_table_setn(r
->subprocess_env
, "FCGI_APACHE_ROLE", "AUTHENTICATOR");
2610 /* The FastCGI Protocol doesn't differentiate authentication */
2611 fr
->role
= FCGI_AUTHORIZER
;
2613 /* Do we need compatibility mode? */
2614 fr
->auth_compat
= (dir_config
->authenticator_options
& FCGI_COMPAT
);
2616 if ((res
= do_work(r
, fr
)) != OK
)
2617 goto AuthenticationFailed
;
2619 authenticated
= (r
->status
== 200);
2620 post_process_auth(fr
, authenticated
);
2622 /* A redirect shouldn't be allowed during the authentication phase */
2623 if (ap_table_get(r
->headers_out
, "Location") != NULL
) {
2624 ap_log_rerror(FCGI_LOG_ERR_NOERRNO
, r
,
2625 "FastCGI: FastCgiAuthenticator \"%s\" redirected (not allowed)",
2626 dir_config
->authenticator
);
2627 goto AuthenticationFailed
;
2633 AuthenticationFailed
:
2634 if (!(dir_config
->authenticator_options
& FCGI_AUTHORITATIVE
))
2637 /* @@@ Probably should support custom_responses */
2638 ap_note_basic_auth_failure(r
);
2639 ap_log_rerror(FCGI_LOG_ERR_NOERRNO
, r
,
2640 "FastCGI: authentication failed for user \"%s\": %s",
2644 r
->connection
->user
, r
->uri
);
2647 return (res
== OK
) ? HTTP_UNAUTHORIZED
: res
;
2650 static int check_user_authorization(request_rec
*r
)
2652 int res
, authorized
= 0;
2654 const fcgi_dir_config
* const dir_config
=
2655 (const fcgi_dir_config
*)ap_get_module_config(r
->per_dir_config
, &fastcgi_module
);
2657 if (dir_config
->authorizer
== NULL
)
2660 /* @@@ We should probably honor the existing parameters to the require directive
2661 * as well as allow the definition of new ones (or use the basename of the
2662 * FastCGI server and pass the rest of the directive line), but for now keep
2665 if ((fr
= create_fcgi_request(r
, dir_config
->authorizer
)) == NULL
)
2666 return HTTP_INTERNAL_SERVER_ERROR
;
2668 /* Save the existing subprocess_env, because we're gonna muddy it up */
2669 fr
->saved_subprocess_env
= ap_copy_table(r
->pool
, r
->subprocess_env
);
2671 ap_table_setn(r
->subprocess_env
, "FCGI_APACHE_ROLE", "AUTHORIZER");
2673 fr
->role
= FCGI_AUTHORIZER
;
2675 /* Do we need compatibility mode? */
2676 fr
->auth_compat
= (dir_config
->authorizer_options
& FCGI_COMPAT
);
2678 if ((res
= do_work(r
, fr
)) != OK
)
2679 goto AuthorizationFailed
;
2681 authorized
= (r
->status
== 200);
2682 post_process_auth(fr
, authorized
);
2684 /* A redirect shouldn't be allowed during the authorization phase */
2685 if (ap_table_get(r
->headers_out
, "Location") != NULL
) {
2686 ap_log_rerror(FCGI_LOG_ERR_NOERRNO
, r
,
2687 "FastCGI: FastCgiAuthorizer \"%s\" redirected (not allowed)",
2688 dir_config
->authorizer
);
2689 goto AuthorizationFailed
;
2695 AuthorizationFailed
:
2696 if (!(dir_config
->authorizer_options
& FCGI_AUTHORITATIVE
))
2699 /* @@@ Probably should support custom_responses */
2700 ap_note_basic_auth_failure(r
);
2701 ap_log_rerror(FCGI_LOG_ERR_NOERRNO
, r
,
2702 "FastCGI: authorization failed for user \"%s\": %s",
2706 r
->connection
->user
, r
->uri
);
2709 return (res
== OK
) ? HTTP_UNAUTHORIZED
: res
;
2712 static int check_access(request_rec
*r
)
2714 int res
, access_allowed
= 0;
2716 const fcgi_dir_config
* const dir_config
=
2717 (fcgi_dir_config
*)ap_get_module_config(r
->per_dir_config
, &fastcgi_module
);
2719 if (dir_config
== NULL
|| dir_config
->access_checker
== NULL
)
2722 if ((fr
= create_fcgi_request(r
, dir_config
->access_checker
)) == NULL
)
2723 return HTTP_INTERNAL_SERVER_ERROR
;
2725 /* Save the existing subprocess_env, because we're gonna muddy it up */
2726 fr
->saved_subprocess_env
= ap_copy_table(r
->pool
, r
->subprocess_env
);
2728 ap_table_setn(r
->subprocess_env
, "FCGI_APACHE_ROLE", "ACCESS_CHECKER");
2730 /* The FastCGI Protocol doesn't differentiate access control */
2731 fr
->role
= FCGI_AUTHORIZER
;
2733 /* Do we need compatibility mode? */
2734 fr
->auth_compat
= (dir_config
->access_checker_options
& FCGI_COMPAT
);
2736 if ((res
= do_work(r
, fr
)) != OK
)
2739 access_allowed
= (r
->status
== 200);
2740 post_process_auth(fr
, access_allowed
);
2742 /* A redirect shouldn't be allowed during the access check phase */
2743 if (ap_table_get(r
->headers_out
, "Location") != NULL
) {
2744 ap_log_rerror(FCGI_LOG_ERR_NOERRNO
, r
,
2745 "FastCGI: FastCgiAccessChecker \"%s\" redirected (not allowed)",
2746 dir_config
->access_checker
);
2754 if (!(dir_config
->access_checker_options
& FCGI_AUTHORITATIVE
))
2757 /* @@@ Probably should support custom_responses */
2758 ap_log_rerror(FCGI_LOG_ERR_NOERRNO
, r
, "FastCGI: access denied: %s", r
->uri
);
2759 return (res
== OK
) ? HTTP_FORBIDDEN
: res
;
2763 fixups(request_rec
* r
)
2765 if (fcgi_util_fs_get_by_id(r
->filename
,
2766 fcgi_util_get_server_uid(r
->server
),
2767 fcgi_util_get_server_gid(r
->server
)))
2769 r
->handler
= FASTCGI_HANDLER_NAME
;
2778 # define AP_INIT_RAW_ARGS(directive, func, mconfig, where, help) \
2779 { directive, func, mconfig, where, RAW_ARGS, help }
2780 # define AP_INIT_TAKE1(directive, func, mconfig, where, help) \
2781 { directive, func, mconfig, where, TAKE1, help }
2782 # define AP_INIT_TAKE12(directive, func, mconfig, where, help) \
2783 { directive, func, mconfig, where, TAKE12, help }
2784 # define AP_INIT_FLAG(directive, func, mconfig, where, help) \
2785 { directive, func, mconfig, where, FLAG, help }
2789 static const command_rec fastcgi_cmds
[] =
2791 AP_INIT_RAW_ARGS("AppClass", fcgi_config_new_static_server
, NULL
, RSRC_CONF
, NULL
),
2792 AP_INIT_RAW_ARGS("FastCgiServer", fcgi_config_new_static_server
, NULL
, RSRC_CONF
, NULL
),
2794 AP_INIT_RAW_ARGS("ExternalAppClass", fcgi_config_new_external_server
, NULL
, RSRC_CONF
, NULL
),
2795 AP_INIT_RAW_ARGS("FastCgiExternalServer", fcgi_config_new_external_server
, NULL
, RSRC_CONF
, NULL
),
2797 AP_INIT_TAKE1("FastCgiIpcDir", fcgi_config_set_socket_dir
, NULL
, RSRC_CONF
, NULL
),
2799 AP_INIT_TAKE1("FastCgiSuexec", fcgi_config_set_wrapper
, NULL
, RSRC_CONF
, NULL
),
2800 AP_INIT_TAKE1("FastCgiWrapper", fcgi_config_set_wrapper
, NULL
, RSRC_CONF
, NULL
),
2802 AP_INIT_RAW_ARGS("FCGIConfig", fcgi_config_set_config
, NULL
, RSRC_CONF
, NULL
),
2803 AP_INIT_RAW_ARGS("FastCgiConfig", fcgi_config_set_config
, NULL
, RSRC_CONF
, NULL
),
2805 AP_INIT_TAKE12("FastCgiAuthenticator", fcgi_config_new_auth_server
,
2806 (void *)FCGI_AUTH_TYPE_AUTHENTICATOR
, ACCESS_CONF
,
2807 "a fastcgi-script path (absolute or relative to ServerRoot) followed by an optional -compat"),
2808 AP_INIT_FLAG("FastCgiAuthenticatorAuthoritative", fcgi_config_set_authoritative_slot
,
2809 (void *)XtOffsetOf(fcgi_dir_config
, authenticator_options
), ACCESS_CONF
,
2810 "Set to 'off' to allow authentication to be passed along to lower modules upon failure"),
2812 AP_INIT_TAKE12("FastCgiAuthorizer", fcgi_config_new_auth_server
,
2813 (void *)FCGI_AUTH_TYPE_AUTHORIZER
, ACCESS_CONF
,
2814 "a fastcgi-script path (absolute or relative to ServerRoot) followed by an optional -compat"),
2815 AP_INIT_FLAG("FastCgiAuthorizerAuthoritative", fcgi_config_set_authoritative_slot
,
2816 (void *)XtOffsetOf(fcgi_dir_config
, authorizer_options
), ACCESS_CONF
,
2817 "Set to 'off' to allow authorization to be passed along to lower modules upon failure"),
2819 AP_INIT_TAKE12("FastCgiAccessChecker", fcgi_config_new_auth_server
,
2820 (void *)FCGI_AUTH_TYPE_ACCESS_CHECKER
, ACCESS_CONF
,
2821 "a fastcgi-script path (absolute or relative to ServerRoot) followed by an optional -compat"),
2822 AP_INIT_FLAG("FastCgiAccessCheckerAuthoritative", fcgi_config_set_authoritative_slot
,
2823 (void *)XtOffsetOf(fcgi_dir_config
, access_checker_options
), ACCESS_CONF
,
2824 "Set to 'off' to allow access control to be passed along to lower modules upon failure"),
2830 static void register_hooks(apr_pool_t
* p
)
2832 // ap_hook_pre_config(x_pre_config, NULL, NULL, APR_HOOK_MIDDLE);
2833 ap_hook_post_config(init_module
, NULL
, NULL
, APR_HOOK_MIDDLE
);
2834 ap_hook_child_init(fcgi_child_init
, NULL
, NULL
, APR_HOOK_MIDDLE
);
2835 ap_hook_handler(content_handler
, NULL
, NULL
, APR_HOOK_MIDDLE
);
2836 ap_hook_check_user_id(check_user_authentication
, NULL
, NULL
, APR_HOOK_MIDDLE
);
2837 ap_hook_access_checker(check_access
, NULL
, NULL
, APR_HOOK_MIDDLE
);
2838 ap_hook_auth_checker(check_user_authorization
, NULL
, NULL
, APR_HOOK_MIDDLE
);
2839 ap_hook_fixups(fixups
, NULL
, NULL
, APR_HOOK_MIDDLE
);
2842 module AP_MODULE_DECLARE_DATA fastcgi_module
=
2844 STANDARD20_MODULE_STUFF
,
2845 fcgi_config_create_dir_config
, /* per-directory config creator */
2846 NULL
, /* dir config merger */
2847 NULL
, /* server config creator */
2848 NULL
, /* server config merger */
2849 fastcgi_cmds
, /* command table */
2850 register_hooks
, /* set up other request processing hooks */
2853 #else /* !APACHE2 */
2855 handler_rec fastcgi_handlers
[] = {
2856 { FCGI_MAGIC_TYPE
, content_handler
},
2857 { FASTCGI_HANDLER_NAME
, content_handler
},
2861 module MODULE_VAR_EXPORT fastcgi_module
= {
2862 STANDARD_MODULE_STUFF
,
2863 init_module
, /* initializer */
2864 fcgi_config_create_dir_config
, /* per-dir config creator */
2865 NULL
, /* per-dir config merger (default: override) */
2866 NULL
, /* per-server config creator */
2867 NULL
, /* per-server config merger (default: override) */
2868 fastcgi_cmds
, /* command table */
2869 fastcgi_handlers
, /* [9] content handlers */
2870 NULL
, /* [2] URI-to-filename translation */
2871 check_user_authentication
, /* [5] authenticate user_id */
2872 check_user_authorization
, /* [6] authorize user_id */
2873 check_access
, /* [4] check access (based on src & http headers) */
2874 NULL
, /* [7] check/set MIME type */
2875 fixups
, /* [8] fixups */
2876 NULL
, /* [10] logger */
2877 NULL
, /* [3] header-parser */
2878 fcgi_child_init
, /* process initialization */
2880 fcgi_child_exit
, /* process exit/cleanup */
2884 NULL
/* [1] post read-request handling */
2887 #endif /* !APACHE2 */