4 * Apache server module for FastCGI.
6 * $Id: mod_fastcgi.c,v 1.147 2002/12/05 03:02:05 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)
863 /* set the header scan state to done to prevent logging an error
864 * - hokey approach - probably should be using a unique value */
865 fr
->parseHeader
= SCAN_CGI_FINISHED
;
869 if (countRead
== 0) {
870 fr
->expectingClientContent
= 0;
873 fcgi_buf_add_update(fr
->clientInputBuffer
, countRead
);
874 ap_reset_timeout(fr
->r
);
880 static int write_to_client(fcgi_request
*fr
)
887 apr_bucket_brigade
* bde
;
888 apr_bucket_alloc_t
* const bkt_alloc
= fr
->r
->connection
->bucket_alloc
;
891 fcgi_buf_get_block_info(fr
->clientOutputBuffer
, &begin
, &count
);
895 /* If fewer than count bytes are written, an error occured.
896 * ap_bwrite() typically forces a flushed write to the client, this
897 * effectively results in a block (and short packets) - it should
898 * be fixed, but I didn't win much support for the idea on new-httpd.
899 * So, without patching Apache, the best way to deal with this is
900 * to size the fcgi_bufs to hold all of the script output (within
901 * reason) so the script can be released from having to wait around
902 * for the transmission to the client to complete. */
906 bde
= apr_brigade_create(fr
->r
->pool
, bkt_alloc
);
907 bkt
= apr_bucket_transient_create(begin
, count
, bkt_alloc
);
908 APR_BRIGADE_INSERT_TAIL(bde
, bkt
);
910 if (fr
->fs
? fr
->fs
->flush
: dynamicFlush
)
912 bkt
= apr_bucket_flush_create(bkt_alloc
);
913 APR_BRIGADE_INSERT_TAIL(bde
, bkt
);
916 rv
= ap_pass_brigade(fr
->r
->output_filters
, bde
);
918 #elif defined(RUSSIAN_APACHE)
920 rv
= (ap_rwrite(begin
, count
, fr
->r
) != count
);
924 rv
= (ap_bwrite(fr
->r
->connection
->client
, begin
, count
) != count
);
930 ap_log_rerror(FCGI_LOG_INFO_NOERRNO
, fr
->r
,
931 "FastCGI: client stopped connection before send body completed");
937 ap_reset_timeout(fr
->r
);
939 /* Don't bother with a wrapped buffer, limiting exposure to slow
940 * clients. The BUFF routines don't allow a writev from above,
941 * and don't always memcpy to minimize small write()s, this should
942 * be fixed, but I didn't win much support for the idea on
943 * new-httpd - I'll have to _prove_ its a problem first.. */
945 /* The default behaviour used to be to flush with every write, but this
946 * can tie up the FastCGI server longer than is necessary so its an option now */
948 if (fr
->fs
? fr
->fs
->flush
: dynamicFlush
)
950 #ifdef RUSSIAN_APACHE
951 rv
= ap_rflush(fr
->r
);
953 rv
= ap_bflush(fr
->r
->connection
->client
);
958 ap_log_rerror(FCGI_LOG_INFO_NOERRNO
, fr
->r
,
959 "FastCGI: client stopped connection before send body completed");
963 ap_reset_timeout(fr
->r
);
966 #endif /* !APACHE2 */
968 fcgi_buf_toss(fr
->clientOutputBuffer
, count
);
972 /*******************************************************************************
973 * Determine the user and group the wrapper should be called with.
974 * Based on code in Apache's create_argv_cmd() (util_script.c).
976 static void set_uid_n_gid(request_rec
*r
, const char **user
, const char **group
)
978 if (fcgi_wrapper
== NULL
) {
984 if (strncmp("/~", r
->uri
, 2) == 0) {
985 /* its a user dir uri, just send the ~user, and leave it to the PM */
986 char *end
= strchr(r
->uri
+ 2, '/');
989 *user
= memcpy(ap_pcalloc(r
->pool
, end
- r
->uri
), r
->uri
+ 1, end
- r
->uri
- 1);
991 *user
= ap_pstrdup(r
->pool
, r
->uri
+ 1);
995 *user
= ap_psprintf(r
->pool
, "%ld", (long) fcgi_util_get_server_uid(r
->server
));
996 *group
= ap_psprintf(r
->pool
, "%ld", (long) fcgi_util_get_server_gid(r
->server
));
1000 static void send_request_complete(fcgi_request
*fr
)
1002 if (fr
->completeTime
.tv_sec
)
1004 struct timeval qtime
, rtime
;
1006 timersub(&fr
->queueTime
, &fr
->startTime
, &qtime
);
1007 timersub(&fr
->completeTime
, &fr
->queueTime
, &rtime
);
1009 send_to_pm(FCGI_REQUEST_COMPLETE_JOB
, fr
->fs_path
,
1010 fr
->user
, fr
->group
,
1011 qtime
.tv_sec
* 1000000 + qtime
.tv_usec
,
1012 rtime
.tv_sec
* 1000000 + rtime
.tv_usec
);
1017 /*******************************************************************************
1018 * Connect to the FastCGI server.
1020 static int open_connection_to_fs(fcgi_request
*fr
)
1022 struct timeval tval
;
1023 fd_set write_fds
, read_fds
;
1025 request_rec
* const r
= fr
->r
;
1026 pool
* const rp
= r
->pool
;
1027 const char *socket_path
= NULL
;
1028 struct sockaddr
*socket_addr
= NULL
;
1029 int socket_addr_len
= 0;
1031 const char *err
= NULL
;
1034 /* Create the connection point */
1037 socket_path
= fcgi_util_socket_hash_filename(rp
, fr
->fs_path
, fr
->user
, fr
->group
);
1038 socket_path
= fcgi_util_socket_make_path_absolute(rp
, socket_path
, 1);
1041 err
= fcgi_util_socket_make_domain_addr(rp
, (struct sockaddr_un
**)&socket_addr
,
1042 &socket_addr_len
, socket_path
);
1044 ap_log_rerror(FCGI_LOG_ERR
, r
,
1045 "FastCGI: failed to connect to (dynamic) server \"%s\": "
1046 "%s", fr
->fs_path
, err
);
1054 if (fr
->fs
->dest_addr
!= NULL
) {
1055 socket_addr
= fr
->fs
->dest_addr
;
1057 else if (fr
->fs
->socket_addr
) {
1058 socket_addr
= fr
->fs
->socket_addr
;
1061 socket_path
= fr
->fs
->socket_path
;
1064 socket_addr
= fr
->fs
->socket_addr
;
1066 socket_addr_len
= fr
->fs
->socket_addr_len
;
1072 if (fr
->fs
&& fr
->fs
->restartTime
)
1074 struct stat sock_stat
;
1076 if (stat(socket_path
, &sock_stat
) == 0)
1080 if (dynamicAutoUpdate
)
1082 struct stat app_stat
;
1084 /* TODO: follow sym links */
1086 if (stat(fr
->fs_path
, &app_stat
) == 0)
1089 if (fr
->fs
->startTime
< app_stat
.st_mtime
)
1091 if (sock_stat
.st_mtime
< app_stat
.st_mtime
)
1095 struct timeval tv
= {1, 0};
1098 * There's a newer one, request a restart.
1100 send_to_pm(FCGI_SERVER_RESTART_JOB
, fr
->fs_path
, fr
->user
, fr
->group
, 0, 0);
1105 /* Avoid sleep/alarm interactions */
1106 ap_select(0, NULL
, NULL
, NULL
, &tv
);
1116 send_to_pm(FCGI_SERVER_START_JOB
, fr
->fs_path
, fr
->user
, fr
->group
, 0, 0);
1118 /* wait until it looks like its running - this shouldn't take
1119 * very long at all - the exception is when the sockets are
1120 * removed out from under a running application - the loop
1121 * limit addresses this (preventing spinning) */
1123 for (i
= 10; i
> 0; i
--)
1128 fr
->fs
= fcgi_util_fs_get_by_id(fr
->fs_path
, 0, 0);
1130 if (fr
->fs
&& fr
->fs
->restartTime
)
1132 struct timeval tv
= {0, 500000};
1134 /* Avoid sleep/alarm interactions */
1135 ap_select(0, NULL
, NULL
, NULL
, &tv
);
1137 if (stat(socket_path
, &sock_stat
) == 0)
1146 ap_log_rerror(FCGI_LOG_ALERT
, r
,
1147 "FastCGI: failed to connect to (dynamic) server \"%s\": "
1148 "something is seriously wrong, any chance the "
1149 "socket/named_pipe directory was removed?, see the "
1150 "FastCgiIpcDir directive", fr
->fs_path
);
1162 HANDLE wait_npipe_mutex
;
1164 DWORD max_connect_time
= FCGI_NAMED_PIPE_CONNECT_TIMEOUT
;
1166 fr
->using_npipe_io
= TRUE
;
1170 interval
= dynamicPleaseStartDelay
* 1000;
1172 if (dynamicAppConnectTimeout
) {
1173 max_connect_time
= dynamicAppConnectTimeout
;
1178 interval
= FCGI_NAMED_PIPE_CONNECT_TIMEOUT
* 1000;
1180 if (fr
->fs
->appConnectTimeout
) {
1181 max_connect_time
= fr
->fs
->appConnectTimeout
;
1185 fcgi_util_ticks(&fr
->startTime
);
1188 // xxx this handle should live somewhere (see CloseHandle()s below too)
1189 char * wait_npipe_mutex_name
, * cp
;
1190 wait_npipe_mutex_name
= cp
= ap_pstrdup(rp
, socket_path
);
1191 while ((cp
= strchr(cp
, '\\'))) *cp
= '/';
1193 wait_npipe_mutex
= CreateMutex(NULL
, FALSE
, wait_npipe_mutex_name
);
1196 if (wait_npipe_mutex
== NULL
)
1198 ap_log_rerror(FCGI_LOG_ERR
, r
,
1199 "FastCGI: failed to connect to server \"%s\": "
1200 "can't create the WaitNamedPipe mutex", fr
->fs_path
);
1204 SetLastError(ERROR_SUCCESS
);
1206 rv
= WaitForSingleObject(wait_npipe_mutex
, max_connect_time
* 1000);
1208 if (rv
== WAIT_TIMEOUT
|| rv
== WAIT_FAILED
)
1212 send_to_pm(FCGI_REQUEST_TIMEOUT_JOB
, fr
->fs_path
, fr
->user
, fr
->group
, 0, 0);
1214 ap_log_rerror(FCGI_LOG_ERR_NOERRNO
, r
,
1215 "FastCGI: failed to connect to server \"%s\": "
1216 "wait for a npipe instance failed", fr
->fs_path
);
1217 FCGIDBG3("interval=%d, max_connect_time=%d", interval
, max_connect_time
);
1218 CloseHandle(wait_npipe_mutex
);
1222 fcgi_util_ticks(&fr
->queueTime
);
1224 connect_time
= fr
->queueTime
.tv_sec
- fr
->startTime
.tv_sec
;
1228 if (connect_time
>= interval
)
1230 send_to_pm(FCGI_REQUEST_TIMEOUT_JOB
, fr
->fs_path
, fr
->user
, fr
->group
, 0, 0);
1231 FCGIDBG4("connect_time=%d, interval=%d, max_connect_time=%d", connect_time
, interval
, max_connect_time
);
1233 if (max_connect_time
- connect_time
< interval
)
1235 interval
= max_connect_time
- connect_time
;
1240 interval
-= connect_time
* 1000;
1245 ready
= WaitNamedPipe(socket_path
, interval
);
1249 fr
->fd
= (SOCKET
) CreateFile(socket_path
,
1250 GENERIC_READ
| GENERIC_WRITE
,
1251 FILE_SHARE_READ
| FILE_SHARE_WRITE
,
1252 NULL
, // no security attributes
1253 OPEN_EXISTING
, // opens existing pipe
1254 FILE_FLAG_OVERLAPPED
,
1255 NULL
); // no template file
1257 if (fr
->fd
!= (SOCKET
) INVALID_HANDLE_VALUE
)
1259 ReleaseMutex(wait_npipe_mutex
);
1260 CloseHandle(wait_npipe_mutex
);
1261 fcgi_util_ticks(&fr
->queueTime
);
1262 FCGIDBG2("got npipe connect: %s", fr
->fs_path
);
1266 if (GetLastError() != ERROR_PIPE_BUSY
1267 && GetLastError() != ERROR_FILE_NOT_FOUND
)
1269 ap_log_rerror(FCGI_LOG_ERR
, r
,
1270 "FastCGI: failed to connect to server \"%s\": "
1271 "CreateFile() failed", fr
->fs_path
);
1275 FCGIDBG2("missed npipe connect: %s", fr
->fs_path
);
1280 send_to_pm(FCGI_REQUEST_TIMEOUT_JOB
, fr
->fs_path
, fr
->user
, fr
->group
, 0, 0);
1283 fcgi_util_ticks(&fr
->queueTime
);
1285 connect_time
= fr
->queueTime
.tv_sec
- fr
->startTime
.tv_sec
;
1287 FCGIDBG5("interval=%d, max_connect_time=%d, connect_time=%d, ready=%d", interval
, max_connect_time
, connect_time
, ready
);
1289 if (connect_time
>= max_connect_time
)
1291 ap_log_rerror(FCGI_LOG_ERR
, r
,
1292 "FastCGI: failed to connect to server \"%s\": "
1293 "CreateFile()/WaitNamedPipe() timed out", fr
->fs_path
);
1298 ReleaseMutex(wait_npipe_mutex
);
1299 CloseHandle(wait_npipe_mutex
);
1300 fr
->fd
= INVALID_SOCKET
;
1306 /* Create the socket */
1307 fr
->fd
= socket(socket_addr
->sa_family
, SOCK_STREAM
, 0);
1310 if (fr
->fd
== INVALID_SOCKET
) {
1311 errno
= WSAGetLastError(); // Not sure this is going to work as expected
1315 ap_log_rerror(FCGI_LOG_ERR_ERRNO
, r
,
1316 "FastCGI: failed to connect to server \"%s\": "
1317 "socket() failed", fr
->fs_path
);
1322 if (fr
->fd
>= FD_SETSIZE
) {
1323 ap_log_rerror(FCGI_LOG_ERR
, r
,
1324 "FastCGI: failed to connect to server \"%s\": "
1325 "socket file descriptor (%u) is larger than "
1326 "FD_SETSIZE (%u), you probably need to rebuild Apache with a "
1327 "larger FD_SETSIZE", fr
->fs_path
, fr
->fd
, FD_SETSIZE
);
1332 /* If appConnectTimeout is non-zero, setup do a non-blocking connect */
1333 if ((fr
->dynamic
&& dynamicAppConnectTimeout
) || (!fr
->dynamic
&& fr
->fs
->appConnectTimeout
)) {
1334 set_nonblocking(fr
, TRUE
);
1338 fcgi_util_ticks(&fr
->startTime
);
1342 if (connect(fr
->fd
, (struct sockaddr
*)socket_addr
, socket_addr_len
) == 0)
1343 goto ConnectionComplete
;
1347 errno
= WSAGetLastError();
1348 if (errno
!= WSAEWOULDBLOCK
) {
1349 ap_log_rerror(FCGI_LOG_ERR_ERRNO
, r
,
1350 "FastCGI: failed to connect to server \"%s\": "
1351 "connect() failed", fr
->fs_path
);
1357 /* ECONNREFUSED means the listen queue is full (or there isn't one).
1358 * With dynamic I can at least make sure the PM knows this is occuring */
1359 if (fr
->dynamic
&& errno
== ECONNREFUSED
) {
1360 /* @@@ This might be better as some other "kind" of message */
1361 send_to_pm(FCGI_REQUEST_TIMEOUT_JOB
, fr
->fs_path
, fr
->user
, fr
->group
, 0, 0);
1363 errno
= ECONNREFUSED
;
1366 if (errno
!= EINPROGRESS
) {
1367 ap_log_rerror(FCGI_LOG_ERR
, r
,
1368 "FastCGI: failed to connect to server \"%s\": "
1369 "connect() failed", fr
->fs_path
);
1375 /* The connect() is non-blocking */
1381 FD_ZERO(&write_fds
);
1382 FD_SET(fr
->fd
, &write_fds
);
1383 read_fds
= write_fds
;
1384 tval
.tv_sec
= dynamicPleaseStartDelay
;
1387 status
= ap_select((fr
->fd
+1), &read_fds
, &write_fds
, NULL
, &tval
);
1391 fcgi_util_ticks(&fr
->queueTime
);
1396 /* select() timed out */
1397 send_to_pm(FCGI_REQUEST_TIMEOUT_JOB
, fr
->fs_path
, fr
->user
, fr
->group
, 0, 0);
1398 } while ((fr
->queueTime
.tv_sec
- fr
->startTime
.tv_sec
) < (int)dynamicAppConnectTimeout
);
1400 /* XXX These can be moved down when dynamic vars live is a struct */
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
);
1410 tval
.tv_sec
= fr
->fs
->appConnectTimeout
;
1412 FD_ZERO(&write_fds
);
1413 FD_SET(fr
->fd
, &write_fds
);
1414 read_fds
= write_fds
;
1416 status
= ap_select((fr
->fd
+1), &read_fds
, &write_fds
, NULL
, &tval
);
1419 ap_log_rerror(FCGI_LOG_ERR_NOERRNO
, r
,
1420 "FastCGI: failed to connect to server \"%s\": "
1421 "connect() timed out (appConnTimeout=%dsec)",
1422 fr
->fs_path
, dynamicAppConnectTimeout
);
1429 errno
= WSAGetLastError();
1431 ap_log_rerror(FCGI_LOG_ERR_ERRNO
, r
,
1432 "FastCGI: failed to connect to server \"%s\": "
1433 "select() failed", fr
->fs_path
);
1437 if (FD_ISSET(fr
->fd
, &write_fds
) || FD_ISSET(fr
->fd
, &read_fds
)) {
1439 NET_SIZE_T len
= sizeof(error
);
1441 if (getsockopt(fr
->fd
, SOL_SOCKET
, SO_ERROR
, (char *)&error
, &len
) < 0) {
1442 /* Solaris pending error */
1444 errno
= WSAGetLastError();
1446 ap_log_rerror(FCGI_LOG_ERR_ERRNO
, r
,
1447 "FastCGI: failed to connect to server \"%s\": "
1448 "select() failed (Solaris pending error)", fr
->fs_path
);
1453 /* Berkeley-derived pending error */
1455 ap_log_rerror(FCGI_LOG_ERR_ERRNO
, r
,
1456 "FastCGI: failed to connect to server \"%s\": "
1457 "select() failed (pending error)", fr
->fs_path
);
1463 errno
= WSAGetLastError();
1465 ap_log_rerror(FCGI_LOG_ERR_ERRNO
, r
,
1466 "FastCGI: failed to connect to server \"%s\": "
1467 "select() error - THIS CAN'T HAPPEN!", fr
->fs_path
);
1472 /* Return to blocking mode if it was set up */
1473 if ((fr
->dynamic
&& dynamicAppConnectTimeout
) || (!fr
->dynamic
&& fr
->fs
->appConnectTimeout
)) {
1474 set_nonblocking(fr
, FALSE
);
1478 if (socket_addr
->sa_family
== AF_INET
) {
1479 /* We shouldn't be sending small packets and there's no application
1480 * level ack of the data we send, so disable Nagle */
1482 setsockopt(fr
->fd
, IPPROTO_TCP
, TCP_NODELAY
, (char *)&set
, sizeof(set
));
1489 static void sink_client_data(fcgi_request
*fr
)
1494 fcgi_buf_reset(fr
->clientInputBuffer
);
1495 fcgi_buf_get_free_block_info(fr
->clientInputBuffer
, &base
, &size
);
1496 while (ap_get_client_block(fr
->r
, base
, size
) > 0);
1499 static apcb_t
cleanup(void *data
)
1501 fcgi_request
* const fr
= (fcgi_request
*) data
;
1503 if (fr
== NULL
) return APCB_OK
;
1505 /* its more than likely already run, but... */
1506 close_connection_to_fs(fr
);
1508 send_request_complete(fr
);
1510 if (fr
->fs_stderr_len
) {
1511 ap_log_rerror(FCGI_LOG_ERR_NOERRNO
, fr
->r
,
1512 "FastCGI: server \"%s\" stderr: %s", fr
->fs_path
, fr
->fs_stderr
);
1519 static int npipe_io(fcgi_request
* const fr
)
1521 request_rec
* const r
= fr
->r
;
1531 state
= STATE_ENV_SEND
;
1532 env_status env_status
;
1534 int dynamic_first_recv
= fr
->dynamic
;
1535 int idle_timeout
= fr
->dynamic
? dynamic_idle_timeout
: fr
->fs
->idle_timeout
;
1536 int send_pending
= 0;
1537 int recv_pending
= 0;
1538 int client_send
= 0;
1540 OVERLAPPED rov
= { 0 };
1541 OVERLAPPED sov
= { 0 };
1543 struct timeval timeout
;
1544 struct timeval dynamic_last_io_time
= {0, 0};
1546 pool
* const rp
= r
->pool
;
1548 DWORD recv_count
= 0;
1550 if (fr
->role
== FCGI_RESPONDER
)
1552 client_recv
= (fr
->expectingClientContent
!= 0);
1555 idle_timeout
= fr
->dynamic
? dynamic_idle_timeout
: fr
->fs
->idle_timeout
;
1557 env_status
.envp
= NULL
;
1559 events
[0] = CreateEvent(NULL
, TRUE
, FALSE
, NULL
);
1560 events
[1] = CreateEvent(NULL
, TRUE
, FALSE
, NULL
);
1561 sov
.hEvent
= events
[0];
1562 rov
.hEvent
= events
[1];
1566 dynamic_last_io_time
= fr
->startTime
;
1568 if (dynamicAppConnectTimeout
)
1570 struct timeval qwait
;
1571 timersub(&fr
->queueTime
, &fr
->startTime
, &qwait
);
1572 dynamic_first_recv
= qwait
.tv_sec
/ dynamicPleaseStartDelay
+ 1;
1576 ap_hard_timeout("FastCGI request processing", r
);
1578 while (state
!= STATE_CLIENT_SEND
)
1584 case STATE_ENV_SEND
:
1586 if (fcgi_protocol_queue_env(r
, fr
, &env_status
) == 0)
1591 state
= STATE_CLIENT_RECV
;
1595 case STATE_CLIENT_RECV
:
1597 if (read_from_client_n_queue(fr
) != OK
)
1599 state
= STATE_ERROR
;
1605 state
= STATE_SERVER_SEND
;
1612 case STATE_SERVER_SEND
:
1614 if (! send_pending
&& BufferLength(fr
->serverOutputBuffer
))
1616 Buffer
* b
= fr
->serverOutputBuffer
;
1619 len
= min(b
->length
, b
->data
+ b
->size
- b
->begin
);
1621 if (WriteFile((HANDLE
) fr
->fd
, b
->begin
, len
, &sent
, &sov
))
1623 /* sov.hEvent is set */
1624 fcgi_buf_removed(b
, sent
);
1626 else if (GetLastError() == ERROR_IO_PENDING
)
1632 ap_log_rerror(FCGI_LOG_ERR
, r
, "FastCGI: comm with server "
1633 "\"%s\" aborted: WriteFile() failed", fr
->fs_path
);
1634 state
= STATE_ERROR
;
1641 case STATE_SERVER_RECV
:
1644 * Only get more data when the serverInputBuffer is empty.
1645 * Otherwise we may already have the END_REQUEST buffered
1646 * (but not processed) and a read on a closed named pipe
1647 * results in an error that is normally abnormal.
1649 if (! recv_pending
&& BufferLength(fr
->serverInputBuffer
) == 0)
1651 Buffer
* b
= fr
->serverInputBuffer
;
1654 len
= min(b
->size
- b
->length
, b
->data
+ b
->size
- b
->end
);
1656 if (ReadFile((HANDLE
) fr
->fd
, b
->end
, len
, &rcvd
, &rov
))
1658 fcgi_buf_added(b
, rcvd
);
1660 ResetEvent(rov
.hEvent
);
1661 if (dynamic_first_recv
)
1663 dynamic_first_recv
= 0;
1666 else if (GetLastError() == ERROR_IO_PENDING
)
1670 else if (GetLastError() == ERROR_HANDLE_EOF
)
1672 fr
->keepReadingFromFcgiApp
= FALSE
;
1673 state
= STATE_CLIENT_SEND
;
1674 ResetEvent(rov
.hEvent
);
1677 else if (GetLastError() == ERROR_NO_DATA
)
1683 ap_log_rerror(FCGI_LOG_ERR
, r
, "FastCGI: comm with server "
1684 "\"%s\" aborted: ReadFile() failed", fr
->fs_path
);
1685 state
= STATE_ERROR
;
1692 case STATE_CLIENT_SEND
:
1694 if (client_send
|| ! BufferFree(fr
->clientOutputBuffer
))
1696 if (write_to_client(fr
))
1698 state
= STATE_ERROR
;
1712 if (state
== STATE_ERROR
)
1717 /* setup the io timeout */
1719 if (BufferLength(fr
->clientOutputBuffer
))
1721 /* don't let client data sit too long, it might be a push */
1723 timeout
.tv_usec
= 100000;
1725 else if (dynamic_first_recv
)
1728 struct timeval qwait
;
1730 fcgi_util_ticks(&fr
->queueTime
);
1734 /* a send() succeeded last pass */
1735 dynamic_last_io_time
= fr
->queueTime
;
1739 /* timed out last pass */
1740 struct timeval idle_time
;
1742 timersub(&fr
->queueTime
, &dynamic_last_io_time
, &idle_time
);
1744 if (idle_time
.tv_sec
> idle_timeout
)
1746 send_to_pm(FCGI_REQUEST_TIMEOUT_JOB
, fr
->fs_path
, fr
->user
, fr
->group
, 0, 0);
1747 ap_log_rerror(FCGI_LOG_ERR_NOERRNO
, r
, "FastCGI: comm "
1748 "with (dynamic) server \"%s\" aborted: (first read) "
1749 "idle timeout (%d sec)", fr
->fs_path
, idle_timeout
);
1750 state
= STATE_ERROR
;
1755 timersub(&fr
->queueTime
, &fr
->startTime
, &qwait
);
1757 delay
= dynamic_first_recv
* dynamicPleaseStartDelay
;
1759 if (qwait
.tv_sec
< delay
)
1761 timeout
.tv_sec
= delay
;
1762 timeout
.tv_usec
= 100000; /* fudge for select() slop */
1763 timersub(&timeout
, &qwait
, &timeout
);
1767 /* Killed time somewhere.. client read? */
1768 send_to_pm(FCGI_REQUEST_TIMEOUT_JOB
, fr
->fs_path
, fr
->user
, fr
->group
, 0, 0);
1769 dynamic_first_recv
= qwait
.tv_sec
/ dynamicPleaseStartDelay
+ 1;
1770 timeout
.tv_sec
= dynamic_first_recv
* dynamicPleaseStartDelay
;
1771 timeout
.tv_usec
= 100000; /* fudge for select() slop */
1772 timersub(&timeout
, &qwait
, &timeout
);
1777 timeout
.tv_sec
= idle_timeout
;
1778 timeout
.tv_usec
= 0;
1781 /* require a pended recv otherwise the app can deadlock */
1784 msec_timeout
= timeout
.tv_sec
* 1000 + timeout
.tv_usec
/ 1000;
1786 rv
= WaitForMultipleObjects(2, events
, FALSE
, msec_timeout
);
1788 if (rv
== WAIT_TIMEOUT
)
1792 if (BufferLength(fr
->clientOutputBuffer
))
1796 else if (dynamic_first_recv
)
1798 struct timeval qwait
;
1800 fcgi_util_ticks(&fr
->queueTime
);
1801 timersub(&fr
->queueTime
, &fr
->startTime
, &qwait
);
1803 send_to_pm(FCGI_REQUEST_TIMEOUT_JOB
, fr
->fs_path
, fr
->user
, fr
->group
, 0, 0);
1805 dynamic_first_recv
= qwait
.tv_sec
/ dynamicPleaseStartDelay
+ 1;
1809 ap_log_rerror(FCGI_LOG_ERR_NOERRNO
, r
, "FastCGI: comm with "
1810 "server \"%s\" aborted: idle timeout (%d sec)",
1811 fr
->fs_path
, idle_timeout
);
1812 state
= STATE_ERROR
;
1818 int i
= rv
- WAIT_OBJECT_0
;
1828 if (GetOverlappedResult((HANDLE
) fr
->fd
, &sov
, &sent
, FALSE
))
1831 fcgi_buf_removed(fr
->serverOutputBuffer
, sent
);
1835 ap_log_rerror(FCGI_LOG_ERR
, r
, "FastCGI: comm with server "
1836 "\"%s\" aborted: GetOverlappedResult() failed", fr
->fs_path
);
1837 state
= STATE_ERROR
;
1842 ResetEvent(sov
.hEvent
);
1851 ResetEvent(rov
.hEvent
);
1853 if (GetOverlappedResult((HANDLE
) fr
->fd
, &rov
, &rcvd
, FALSE
))
1855 fcgi_buf_added(fr
->serverInputBuffer
, rcvd
);
1856 if (dynamic_first_recv
)
1858 dynamic_first_recv
= 0;
1863 ap_log_rerror(FCGI_LOG_ERR
, r
, "FastCGI: comm with server "
1864 "\"%s\" aborted: GetOverlappedResult() failed", fr
->fs_path
);
1865 state
= STATE_ERROR
;
1872 if (fcgi_protocol_dequeue(rp
, fr
))
1874 state
= STATE_ERROR
;
1878 if (fr
->parseHeader
== SCAN_CGI_READING_HEADERS
)
1880 const char * err
= process_headers(r
, fr
);
1883 ap_log_rerror(FCGI_LOG_ERR_NOERRNO
, r
,
1884 "FastCGI: comm with server \"%s\" aborted: "
1885 "error parsing headers: %s", fr
->fs_path
, err
);
1886 state
= STATE_ERROR
;
1891 if (fr
->exitStatusSet
)
1893 fr
->keepReadingFromFcgiApp
= FALSE
;
1894 state
= STATE_CLIENT_SEND
;
1899 if (! fr
->exitStatusSet
|| ! fr
->eofSent
)
1901 CancelIo((HANDLE
) fr
->fd
);
1904 CloseHandle(rov
.hEvent
);
1905 CloseHandle(sov
.hEvent
);
1907 return (state
== STATE_ERROR
);
1911 static int socket_io(fcgi_request
* const fr
)
1924 state
= STATE_ENV_SEND
;
1926 request_rec
* const r
= fr
->r
;
1928 struct timeval timeout
;
1929 struct timeval dynamic_last_io_time
= {0, 0};
1932 int nfds
= fr
->fd
+ 1;
1933 int select_status
= 1;
1936 int dynamic_first_recv
= fr
->dynamic
? 1 : 0;
1937 int client_send
= FALSE
;
1938 int client_recv
= FALSE
;
1942 if (fr
->role
== FCGI_RESPONDER
)
1944 client_recv
= (fr
->expectingClientContent
!= 0);
1947 idle_timeout
= fr
->dynamic
? dynamic_idle_timeout
: fr
->fs
->idle_timeout
;
1953 dynamic_last_io_time
= fr
->startTime
;
1955 if (dynamicAppConnectTimeout
)
1957 struct timeval qwait
;
1958 timersub(&fr
->queueTime
, &fr
->startTime
, &qwait
);
1959 dynamic_first_recv
= qwait
.tv_sec
/ dynamicPleaseStartDelay
+ 1;
1963 ap_hard_timeout("FastCGI request processing", r
);
1965 set_nonblocking(fr
, TRUE
);
1970 FD_ZERO(&write_set
);
1974 case STATE_ENV_SEND
:
1976 if (fcgi_protocol_queue_env(r
, fr
, &env
) == 0)
1981 state
= STATE_CLIENT_RECV
;
1985 case STATE_CLIENT_RECV
:
1987 if (read_from_client_n_queue(fr
))
1989 state
= STATE_CLIENT_ERROR
;
1995 state
= STATE_SERVER_SEND
;
2002 case STATE_SERVER_SEND
:
2004 if (BufferLength(fr
->serverOutputBuffer
))
2006 FD_SET(fr
->fd
, &write_set
);
2010 ap_assert(fr
->eofSent
);
2011 state
= STATE_SERVER_RECV
;
2016 case STATE_SERVER_RECV
:
2018 FD_SET(fr
->fd
, &read_set
);
2022 case STATE_CLIENT_SEND
:
2024 if (client_send
|| ! BufferFree(fr
->clientOutputBuffer
))
2026 if (write_to_client(fr
))
2028 state
= STATE_CLIENT_ERROR
;
2038 case STATE_CLIENT_ERROR
:
2047 if (state
== STATE_CLIENT_ERROR
|| state
== STATE_ERROR
)
2052 /* setup the io timeout */
2054 if (BufferLength(fr
->clientOutputBuffer
))
2056 /* don't let client data sit too long, it might be a push */
2058 timeout
.tv_usec
= 100000;
2060 else if (dynamic_first_recv
)
2063 struct timeval qwait
;
2065 fcgi_util_ticks(&fr
->queueTime
);
2069 /* a send() succeeded last pass */
2070 dynamic_last_io_time
= fr
->queueTime
;
2074 /* timed out last pass */
2075 struct timeval idle_time
;
2077 timersub(&fr
->queueTime
, &dynamic_last_io_time
, &idle_time
);
2079 if (idle_time
.tv_sec
> idle_timeout
)
2081 send_to_pm(FCGI_REQUEST_TIMEOUT_JOB
, fr
->fs_path
, fr
->user
, fr
->group
, 0, 0);
2082 ap_log_rerror(FCGI_LOG_ERR_NOERRNO
, r
, "FastCGI: comm "
2083 "with (dynamic) server \"%s\" aborted: (first read) "
2084 "idle timeout (%d sec)", fr
->fs_path
, idle_timeout
);
2085 state
= STATE_ERROR
;
2090 timersub(&fr
->queueTime
, &fr
->startTime
, &qwait
);
2092 delay
= dynamic_first_recv
* dynamicPleaseStartDelay
;
2094 FCGIDBG5("qwait=%ld.%06ld delay=%d first_recv=%d", qwait
.tv_sec
, qwait
.tv_usec
, delay
, dynamic_first_recv
);
2096 if (qwait
.tv_sec
< delay
)
2098 timeout
.tv_sec
= delay
;
2099 timeout
.tv_usec
= 100000; /* fudge for select() slop */
2100 timersub(&timeout
, &qwait
, &timeout
);
2104 /* Killed time somewhere.. client read? */
2105 send_to_pm(FCGI_REQUEST_TIMEOUT_JOB
, fr
->fs_path
, fr
->user
, fr
->group
, 0, 0);
2106 dynamic_first_recv
= qwait
.tv_sec
/ dynamicPleaseStartDelay
+ 1;
2107 timeout
.tv_sec
= dynamic_first_recv
* dynamicPleaseStartDelay
;
2108 timeout
.tv_usec
= 100000; /* fudge for select() slop */
2109 timersub(&timeout
, &qwait
, &timeout
);
2114 timeout
.tv_sec
= idle_timeout
;
2115 timeout
.tv_usec
= 0;
2118 /* wait on the socket */
2119 select_status
= ap_select(nfds
, &read_set
, &write_set
, NULL
, &timeout
);
2121 if (select_status
< 0)
2123 ap_log_rerror(FCGI_LOG_ERR_ERRNO
, r
, "FastCGI: comm with server "
2124 "\"%s\" aborted: select() failed", fr
->fs_path
);
2125 state
= STATE_ERROR
;
2129 if (select_status
== 0)
2131 /* select() timeout */
2133 if (BufferLength(fr
->clientOutputBuffer
))
2135 if (fr
->role
== FCGI_RESPONDER
)
2140 else if (dynamic_first_recv
)
2142 struct timeval qwait
;
2144 fcgi_util_ticks(&fr
->queueTime
);
2145 timersub(&fr
->queueTime
, &fr
->startTime
, &qwait
);
2147 send_to_pm(FCGI_REQUEST_TIMEOUT_JOB
, fr
->fs_path
, fr
->user
, fr
->group
, 0, 0);
2149 dynamic_first_recv
= qwait
.tv_sec
/ dynamicPleaseStartDelay
+ 1;
2154 ap_log_rerror(FCGI_LOG_ERR_NOERRNO
, r
, "FastCGI: comm with "
2155 "server \"%s\" aborted: idle timeout (%d sec)",
2156 fr
->fs_path
, idle_timeout
);
2157 state
= STATE_ERROR
;
2161 if (FD_ISSET(fr
->fd
, &write_set
))
2163 /* send to the server */
2165 rv
= fcgi_buf_socket_send(fr
->serverOutputBuffer
, fr
->fd
);
2169 ap_log_rerror(FCGI_LOG_ERR
, r
, "FastCGI: comm with server "
2170 "\"%s\" aborted: write failed", fr
->fs_path
);
2171 state
= STATE_ERROR
;
2176 if (FD_ISSET(fr
->fd
, &read_set
))
2178 /* recv from the server */
2180 if (dynamic_first_recv
)
2182 dynamic_first_recv
= 0;
2183 fcgi_util_ticks(&fr
->queueTime
);
2186 rv
= fcgi_buf_socket_recv(fr
->serverInputBuffer
, fr
->fd
);
2190 ap_log_rerror(FCGI_LOG_ERR
, r
, "FastCGI: comm with server "
2191 "\"%s\" aborted: read failed", fr
->fs_path
);
2192 state
= STATE_ERROR
;
2198 fr
->keepReadingFromFcgiApp
= FALSE
;
2199 state
= STATE_CLIENT_SEND
;
2204 if (fcgi_protocol_dequeue(rp
, fr
))
2206 state
= STATE_ERROR
;
2210 if (fr
->parseHeader
== SCAN_CGI_READING_HEADERS
)
2212 const char * err
= process_headers(r
, fr
);
2215 ap_log_rerror(FCGI_LOG_ERR_NOERRNO
, r
,
2216 "FastCGI: comm with server \"%s\" aborted: "
2217 "error parsing headers: %s", fr
->fs_path
, err
);
2218 state
= STATE_ERROR
;
2223 if (fr
->exitStatusSet
)
2225 fr
->keepReadingFromFcgiApp
= FALSE
;
2226 state
= STATE_CLIENT_SEND
;
2231 return (state
== STATE_ERROR
);
2235 /*----------------------------------------------------------------------
2236 * This is the core routine for moving data between the FastCGI
2237 * application and the Web server's client.
2239 static int do_work(request_rec
* const r
, fcgi_request
* const fr
)
2244 fcgi_protocol_queue_begin_request(fr
);
2246 if (fr
->role
== FCGI_RESPONDER
)
2248 rv
= ap_setup_client_block(r
, REQUEST_CHUNKED_ERROR
);
2255 fr
->expectingClientContent
= ap_should_client_block(r
);
2259 ap_register_cleanup(rp
, (void *)fr
, cleanup
, ap_null_cleanup
);
2260 ap_unblock_alarms();
2262 ap_hard_timeout("connect() to FastCGI server", r
);
2264 /* Connect to the FastCGI Application */
2265 if (open_connection_to_fs(fr
) != FCGI_OK
)
2268 return HTTP_INTERNAL_SERVER_ERROR
;
2272 if (fr
->using_npipe_io
)
2282 /* comm with the server is done */
2283 close_connection_to_fs(fr
);
2285 if (fr
->role
== FCGI_RESPONDER
)
2287 sink_client_data(fr
);
2290 while (rv
== 0 && (BufferLength(fr
->serverInputBuffer
) || BufferLength(fr
->clientOutputBuffer
)))
2292 if (fcgi_protocol_dequeue(rp
, fr
))
2294 rv
= HTTP_INTERNAL_SERVER_ERROR
;
2297 if (fr
->parseHeader
== SCAN_CGI_READING_HEADERS
)
2299 const char * err
= process_headers(r
, fr
);
2302 ap_log_rerror(FCGI_LOG_ERR_NOERRNO
, r
,
2303 "FastCGI: comm with server \"%s\" aborted: "
2304 "error parsing headers: %s", fr
->fs_path
, err
);
2305 rv
= HTTP_INTERNAL_SERVER_ERROR
;
2309 if (fr
->role
== FCGI_RESPONDER
)
2311 if (write_to_client(fr
))
2318 fcgi_buf_reset(fr
->clientOutputBuffer
);
2322 switch (fr
->parseHeader
)
2324 case SCAN_CGI_FINISHED
:
2326 if (fr
->role
== FCGI_RESPONDER
)
2328 /* RUSSIAN_APACHE requires rflush() over bflush() */
2331 ap_bgetopt(r
->connection
->client
, BO_BYTECT
, &r
->bytes_sent
);
2337 case SCAN_CGI_INT_REDIRECT
:
2338 case SCAN_CGI_SRV_REDIRECT
:
2342 case SCAN_CGI_READING_HEADERS
:
2344 ap_log_rerror(FCGI_LOG_ERR_NOERRNO
, r
, "FastCGI: incomplete headers "
2345 "(%d bytes) received from server \"%s\"", fr
->header
->nelts
, fr
->fs_path
);
2349 case SCAN_CGI_BAD_HEADER
:
2351 rv
= HTTP_INTERNAL_SERVER_ERROR
;
2357 rv
= HTTP_INTERNAL_SERVER_ERROR
;
2364 static fcgi_request
*create_fcgi_request(request_rec
* const r
, const char *path
)
2366 const char *fs_path
;
2367 pool
* const p
= r
->pool
;
2369 fcgi_request
* const fr
= (fcgi_request
*)ap_pcalloc(p
, sizeof(fcgi_request
));
2371 fs_path
= path
? path
: r
->filename
;
2373 fs
= fcgi_util_fs_get_by_id(fs_path
, fcgi_util_get_server_uid(r
->server
),
2374 fcgi_util_get_server_gid(r
->server
));
2378 struct stat
*my_finfo
;
2385 /* AP2: its bogus that we don't make use of r->finfo, but
2386 * its an apr_finfo_t and there is no apr_os_finfo_get() */
2388 my_finfo
= &r
->finfo
;
2393 my_finfo
= (struct stat
*) ap_palloc(p
, sizeof(struct stat
));
2395 if (stat(fs_path
, my_finfo
) < 0)
2397 ap_log_rerror(FCGI_LOG_ERR_ERRNO
, r
,
2398 "FastCGI: stat() of \"%s\" failed", fs_path
);
2403 err
= fcgi_util_fs_is_path_ok(p
, fs_path
, my_finfo
);
2407 ap_log_rerror(FCGI_LOG_ERR_NOERRNO
, r
,
2408 "FastCGI: invalid (dynamic) server \"%s\": %s", fs_path
, err
);
2413 fr
->serverInputBuffer
= fcgi_buf_new(p
, SERVER_BUFSIZE
);
2414 fr
->serverOutputBuffer
= fcgi_buf_new(p
, SERVER_BUFSIZE
);
2415 fr
->clientInputBuffer
= fcgi_buf_new(p
, SERVER_BUFSIZE
);
2416 fr
->clientOutputBuffer
= fcgi_buf_new(p
, SERVER_BUFSIZE
);
2417 fr
->erBufPtr
= fcgi_buf_new(p
, sizeof(FCGI_EndRequestBody
) + 1);
2418 fr
->gotHeader
= FALSE
;
2419 fr
->parseHeader
= SCAN_CGI_READING_HEADERS
;
2420 fr
->header
= ap_make_array(p
, 1, 1);
2421 fr
->fs_stderr
= NULL
;
2423 fr
->readingEndRequestBody
= FALSE
;
2425 fr
->exitStatusSet
= FALSE
;
2426 fr
->requestId
= 1; /* anything but zero is OK here */
2427 fr
->eofSent
= FALSE
;
2428 fr
->role
= FCGI_RESPONDER
;
2429 fr
->expectingClientContent
= FALSE
;
2430 fr
->keepReadingFromFcgiApp
= TRUE
;
2432 fr
->fs_path
= fs_path
;
2433 fr
->authHeaders
= ap_make_table(p
, 10);
2435 fr
->fd
= INVALID_SOCKET
;
2436 fr
->dynamic
= ((fs
== NULL
) || (fs
->directive
== APP_CLASS_DYNAMIC
)) ? TRUE
: FALSE
;
2437 fr
->using_npipe_io
= FALSE
;
2439 fr
->dynamic
= (fs
== NULL
) ? TRUE
: FALSE
;
2443 set_uid_n_gid(r
, &fr
->user
, &fr
->group
);
2449 *----------------------------------------------------------------------
2453 * This routine gets called for a request that corresponds to
2454 * a FastCGI connection. It performs the request synchronously.
2457 * Final status of request: OK or NOT_FOUND or HTTP_INTERNAL_SERVER_ERROR.
2460 * Request performed.
2462 *----------------------------------------------------------------------
2465 /* Stolen from mod_cgi.c..
2466 * KLUDGE --- for back-combatibility, we don't have to check ExecCGI
2467 * in ScriptAliased directories, which means we need to know if this
2468 * request came through ScriptAlias or not... so the Alias module
2469 * leaves a note for us.
2471 static int apache_is_scriptaliased(request_rec
*r
)
2473 const char *t
= ap_table_get(r
->notes
, "alias-forced-type");
2474 return t
&& (!strcasecmp(t
, "cgi-script"));
2477 /* If a script wants to produce its own Redirect body, it now
2478 * has to explicitly *say* "Status: 302". If it wants to use
2479 * Apache redirects say "Status: 200". See process_headers().
2481 static int post_process_for_redirects(request_rec
* const r
,
2482 const fcgi_request
* const fr
)
2484 switch(fr
->parseHeader
) {
2485 case SCAN_CGI_INT_REDIRECT
:
2487 /* @@@ There are still differences between the handling in
2488 * mod_cgi and mod_fastcgi. This needs to be revisited.
2490 /* We already read the message body (if any), so don't allow
2491 * the redirected request to think it has one. We can ignore
2492 * Transfer-Encoding, since we used REQUEST_CHUNKED_ERROR.
2495 r
->method_number
= M_GET
;
2496 ap_table_unset(r
->headers_in
, "Content-length");
2498 ap_internal_redirect_handler(ap_table_get(r
->headers_out
, "Location"), r
);
2501 case SCAN_CGI_SRV_REDIRECT
:
2502 return HTTP_MOVED_TEMPORARILY
;
2509 /******************************************************************************
2510 * Process fastcgi-script requests. Based on mod_cgi::cgi_handler().
2512 static int content_handler(request_rec
*r
)
2514 fcgi_request
*fr
= NULL
;
2518 if (strcmp(r
->handler
, FASTCGI_HANDLER_NAME
))
2522 /* Setup a new FastCGI request */
2523 if ((fr
= create_fcgi_request(r
, NULL
)) == NULL
)
2524 return HTTP_INTERNAL_SERVER_ERROR
;
2526 /* If its a dynamic invocation, make sure scripts are OK here */
2527 if (fr
->dynamic
&& !(ap_allow_options(r
) & OPT_EXECCGI
) && !apache_is_scriptaliased(r
)) {
2528 ap_log_rerror(FCGI_LOG_ERR_NOERRNO
, r
,
2529 "FastCGI: \"ExecCGI Option\" is off in this directory: %s", r
->uri
);
2530 return HTTP_INTERNAL_SERVER_ERROR
;
2533 /* Process the fastcgi-script request */
2534 if ((ret
= do_work(r
, fr
)) != OK
)
2537 /* Special case redirects */
2538 ret
= post_process_for_redirects(r
, fr
);
2544 static int post_process_auth_passed_header(table
*t
, const char *key
, const char * const val
)
2546 if (strncasecmp(key
, "Variable-", 9) == 0)
2549 ap_table_setn(t
, key
, val
);
2553 static int post_process_auth_passed_compat_header(table
*t
, const char *key
, const char * const val
)
2555 if (strncasecmp(key
, "Variable-", 9) == 0)
2556 ap_table_setn(t
, key
+ 9, val
);
2561 static int post_process_auth_failed_header(table
* const t
, const char * const key
, const char * const val
)
2563 ap_table_setn(t
, key
, val
);
2567 static void post_process_auth(fcgi_request
* const fr
, const int passed
)
2569 request_rec
* const r
= fr
->r
;
2571 /* Restore the saved subprocess_env because we muddied ours up */
2572 r
->subprocess_env
= fr
->saved_subprocess_env
;
2575 if (fr
->auth_compat
) {
2576 ap_table_do((int (*)(void *, const char *, const char *))post_process_auth_passed_compat_header
,
2577 (void *)r
->subprocess_env
, fr
->authHeaders
, NULL
);
2580 ap_table_do((int (*)(void *, const char *, const char *))post_process_auth_passed_header
,
2581 (void *)r
->subprocess_env
, fr
->authHeaders
, NULL
);
2585 ap_table_do((int (*)(void *, const char *, const char *))post_process_auth_failed_header
,
2586 (void *)r
->err_headers_out
, fr
->authHeaders
, NULL
);
2589 /* @@@ Restore these.. its a hack until I rewrite the header handling */
2590 r
->status
= HTTP_OK
;
2591 r
->status_line
= NULL
;
2594 static int check_user_authentication(request_rec
*r
)
2596 int res
, authenticated
= 0;
2597 const char *password
;
2599 const fcgi_dir_config
* const dir_config
=
2600 (const fcgi_dir_config
*)ap_get_module_config(r
->per_dir_config
, &fastcgi_module
);
2602 if (dir_config
->authenticator
== NULL
)
2605 /* Get the user password */
2606 if ((res
= ap_get_basic_auth_pw(r
, &password
)) != OK
)
2609 if ((fr
= create_fcgi_request(r
, dir_config
->authenticator
)) == NULL
)
2610 return HTTP_INTERNAL_SERVER_ERROR
;
2612 /* Save the existing subprocess_env, because we're gonna muddy it up */
2613 fr
->saved_subprocess_env
= ap_copy_table(r
->pool
, r
->subprocess_env
);
2615 ap_table_setn(r
->subprocess_env
, "REMOTE_PASSWD", password
);
2616 ap_table_setn(r
->subprocess_env
, "FCGI_APACHE_ROLE", "AUTHENTICATOR");
2618 /* The FastCGI Protocol doesn't differentiate authentication */
2619 fr
->role
= FCGI_AUTHORIZER
;
2621 /* Do we need compatibility mode? */
2622 fr
->auth_compat
= (dir_config
->authenticator_options
& FCGI_COMPAT
);
2624 if ((res
= do_work(r
, fr
)) != OK
)
2625 goto AuthenticationFailed
;
2627 authenticated
= (r
->status
== 200);
2628 post_process_auth(fr
, authenticated
);
2630 /* A redirect shouldn't be allowed during the authentication phase */
2631 if (ap_table_get(r
->headers_out
, "Location") != NULL
) {
2632 ap_log_rerror(FCGI_LOG_ERR_NOERRNO
, r
,
2633 "FastCGI: FastCgiAuthenticator \"%s\" redirected (not allowed)",
2634 dir_config
->authenticator
);
2635 goto AuthenticationFailed
;
2641 AuthenticationFailed
:
2642 if (!(dir_config
->authenticator_options
& FCGI_AUTHORITATIVE
))
2645 /* @@@ Probably should support custom_responses */
2646 ap_note_basic_auth_failure(r
);
2647 ap_log_rerror(FCGI_LOG_ERR_NOERRNO
, r
,
2648 "FastCGI: authentication failed for user \"%s\": %s",
2652 r
->connection
->user
, r
->uri
);
2655 return (res
== OK
) ? HTTP_UNAUTHORIZED
: res
;
2658 static int check_user_authorization(request_rec
*r
)
2660 int res
, authorized
= 0;
2662 const fcgi_dir_config
* const dir_config
=
2663 (const fcgi_dir_config
*)ap_get_module_config(r
->per_dir_config
, &fastcgi_module
);
2665 if (dir_config
->authorizer
== NULL
)
2668 /* @@@ We should probably honor the existing parameters to the require directive
2669 * as well as allow the definition of new ones (or use the basename of the
2670 * FastCGI server and pass the rest of the directive line), but for now keep
2673 if ((fr
= create_fcgi_request(r
, dir_config
->authorizer
)) == NULL
)
2674 return HTTP_INTERNAL_SERVER_ERROR
;
2676 /* Save the existing subprocess_env, because we're gonna muddy it up */
2677 fr
->saved_subprocess_env
= ap_copy_table(r
->pool
, r
->subprocess_env
);
2679 ap_table_setn(r
->subprocess_env
, "FCGI_APACHE_ROLE", "AUTHORIZER");
2681 fr
->role
= FCGI_AUTHORIZER
;
2683 /* Do we need compatibility mode? */
2684 fr
->auth_compat
= (dir_config
->authorizer_options
& FCGI_COMPAT
);
2686 if ((res
= do_work(r
, fr
)) != OK
)
2687 goto AuthorizationFailed
;
2689 authorized
= (r
->status
== 200);
2690 post_process_auth(fr
, authorized
);
2692 /* A redirect shouldn't be allowed during the authorization phase */
2693 if (ap_table_get(r
->headers_out
, "Location") != NULL
) {
2694 ap_log_rerror(FCGI_LOG_ERR_NOERRNO
, r
,
2695 "FastCGI: FastCgiAuthorizer \"%s\" redirected (not allowed)",
2696 dir_config
->authorizer
);
2697 goto AuthorizationFailed
;
2703 AuthorizationFailed
:
2704 if (!(dir_config
->authorizer_options
& FCGI_AUTHORITATIVE
))
2707 /* @@@ Probably should support custom_responses */
2708 ap_note_basic_auth_failure(r
);
2709 ap_log_rerror(FCGI_LOG_ERR_NOERRNO
, r
,
2710 "FastCGI: authorization failed for user \"%s\": %s",
2714 r
->connection
->user
, r
->uri
);
2717 return (res
== OK
) ? HTTP_UNAUTHORIZED
: res
;
2720 static int check_access(request_rec
*r
)
2722 int res
, access_allowed
= 0;
2724 const fcgi_dir_config
* const dir_config
=
2725 (fcgi_dir_config
*)ap_get_module_config(r
->per_dir_config
, &fastcgi_module
);
2727 if (dir_config
== NULL
|| dir_config
->access_checker
== NULL
)
2730 if ((fr
= create_fcgi_request(r
, dir_config
->access_checker
)) == NULL
)
2731 return HTTP_INTERNAL_SERVER_ERROR
;
2733 /* Save the existing subprocess_env, because we're gonna muddy it up */
2734 fr
->saved_subprocess_env
= ap_copy_table(r
->pool
, r
->subprocess_env
);
2736 ap_table_setn(r
->subprocess_env
, "FCGI_APACHE_ROLE", "ACCESS_CHECKER");
2738 /* The FastCGI Protocol doesn't differentiate access control */
2739 fr
->role
= FCGI_AUTHORIZER
;
2741 /* Do we need compatibility mode? */
2742 fr
->auth_compat
= (dir_config
->access_checker_options
& FCGI_COMPAT
);
2744 if ((res
= do_work(r
, fr
)) != OK
)
2747 access_allowed
= (r
->status
== 200);
2748 post_process_auth(fr
, access_allowed
);
2750 /* A redirect shouldn't be allowed during the access check phase */
2751 if (ap_table_get(r
->headers_out
, "Location") != NULL
) {
2752 ap_log_rerror(FCGI_LOG_ERR_NOERRNO
, r
,
2753 "FastCGI: FastCgiAccessChecker \"%s\" redirected (not allowed)",
2754 dir_config
->access_checker
);
2762 if (!(dir_config
->access_checker_options
& FCGI_AUTHORITATIVE
))
2765 /* @@@ Probably should support custom_responses */
2766 ap_log_rerror(FCGI_LOG_ERR_NOERRNO
, r
, "FastCGI: access denied: %s", r
->uri
);
2767 return (res
== OK
) ? HTTP_FORBIDDEN
: res
;
2771 fixups(request_rec
* r
)
2773 if (fcgi_util_fs_get_by_id(r
->filename
,
2774 fcgi_util_get_server_uid(r
->server
),
2775 fcgi_util_get_server_gid(r
->server
)))
2777 r
->handler
= FASTCGI_HANDLER_NAME
;
2786 # define AP_INIT_RAW_ARGS(directive, func, mconfig, where, help) \
2787 { directive, func, mconfig, where, RAW_ARGS, help }
2788 # define AP_INIT_TAKE1(directive, func, mconfig, where, help) \
2789 { directive, func, mconfig, where, TAKE1, help }
2790 # define AP_INIT_TAKE12(directive, func, mconfig, where, help) \
2791 { directive, func, mconfig, where, TAKE12, help }
2792 # define AP_INIT_FLAG(directive, func, mconfig, where, help) \
2793 { directive, func, mconfig, where, FLAG, help }
2797 static const command_rec fastcgi_cmds
[] =
2799 AP_INIT_RAW_ARGS("AppClass", fcgi_config_new_static_server
, NULL
, RSRC_CONF
, NULL
),
2800 AP_INIT_RAW_ARGS("FastCgiServer", fcgi_config_new_static_server
, NULL
, RSRC_CONF
, NULL
),
2802 AP_INIT_RAW_ARGS("ExternalAppClass", fcgi_config_new_external_server
, NULL
, RSRC_CONF
, NULL
),
2803 AP_INIT_RAW_ARGS("FastCgiExternalServer", fcgi_config_new_external_server
, NULL
, RSRC_CONF
, NULL
),
2805 AP_INIT_TAKE1("FastCgiIpcDir", fcgi_config_set_socket_dir
, NULL
, RSRC_CONF
, NULL
),
2807 AP_INIT_TAKE1("FastCgiSuexec", fcgi_config_set_wrapper
, NULL
, RSRC_CONF
, NULL
),
2808 AP_INIT_TAKE1("FastCgiWrapper", fcgi_config_set_wrapper
, NULL
, RSRC_CONF
, NULL
),
2810 AP_INIT_RAW_ARGS("FCGIConfig", fcgi_config_set_config
, NULL
, RSRC_CONF
, NULL
),
2811 AP_INIT_RAW_ARGS("FastCgiConfig", fcgi_config_set_config
, NULL
, RSRC_CONF
, NULL
),
2813 AP_INIT_TAKE12("FastCgiAuthenticator", fcgi_config_new_auth_server
,
2814 (void *)FCGI_AUTH_TYPE_AUTHENTICATOR
, ACCESS_CONF
,
2815 "a fastcgi-script path (absolute or relative to ServerRoot) followed by an optional -compat"),
2816 AP_INIT_FLAG("FastCgiAuthenticatorAuthoritative", fcgi_config_set_authoritative_slot
,
2817 (void *)XtOffsetOf(fcgi_dir_config
, authenticator_options
), ACCESS_CONF
,
2818 "Set to 'off' to allow authentication to be passed along to lower modules upon failure"),
2820 AP_INIT_TAKE12("FastCgiAuthorizer", fcgi_config_new_auth_server
,
2821 (void *)FCGI_AUTH_TYPE_AUTHORIZER
, ACCESS_CONF
,
2822 "a fastcgi-script path (absolute or relative to ServerRoot) followed by an optional -compat"),
2823 AP_INIT_FLAG("FastCgiAuthorizerAuthoritative", fcgi_config_set_authoritative_slot
,
2824 (void *)XtOffsetOf(fcgi_dir_config
, authorizer_options
), ACCESS_CONF
,
2825 "Set to 'off' to allow authorization to be passed along to lower modules upon failure"),
2827 AP_INIT_TAKE12("FastCgiAccessChecker", fcgi_config_new_auth_server
,
2828 (void *)FCGI_AUTH_TYPE_ACCESS_CHECKER
, ACCESS_CONF
,
2829 "a fastcgi-script path (absolute or relative to ServerRoot) followed by an optional -compat"),
2830 AP_INIT_FLAG("FastCgiAccessCheckerAuthoritative", fcgi_config_set_authoritative_slot
,
2831 (void *)XtOffsetOf(fcgi_dir_config
, access_checker_options
), ACCESS_CONF
,
2832 "Set to 'off' to allow access control to be passed along to lower modules upon failure"),
2838 static void register_hooks(apr_pool_t
* p
)
2840 // ap_hook_pre_config(x_pre_config, NULL, NULL, APR_HOOK_MIDDLE);
2841 ap_hook_post_config(init_module
, NULL
, NULL
, APR_HOOK_MIDDLE
);
2842 ap_hook_child_init(fcgi_child_init
, NULL
, NULL
, APR_HOOK_MIDDLE
);
2843 ap_hook_handler(content_handler
, NULL
, NULL
, APR_HOOK_MIDDLE
);
2844 ap_hook_check_user_id(check_user_authentication
, NULL
, NULL
, APR_HOOK_MIDDLE
);
2845 ap_hook_access_checker(check_access
, NULL
, NULL
, APR_HOOK_MIDDLE
);
2846 ap_hook_auth_checker(check_user_authorization
, NULL
, NULL
, APR_HOOK_MIDDLE
);
2847 ap_hook_fixups(fixups
, NULL
, NULL
, APR_HOOK_MIDDLE
);
2850 module AP_MODULE_DECLARE_DATA fastcgi_module
=
2852 STANDARD20_MODULE_STUFF
,
2853 fcgi_config_create_dir_config
, /* per-directory config creator */
2854 NULL
, /* dir config merger */
2855 NULL
, /* server config creator */
2856 NULL
, /* server config merger */
2857 fastcgi_cmds
, /* command table */
2858 register_hooks
, /* set up other request processing hooks */
2861 #else /* !APACHE2 */
2863 handler_rec fastcgi_handlers
[] = {
2864 { FCGI_MAGIC_TYPE
, content_handler
},
2865 { FASTCGI_HANDLER_NAME
, content_handler
},
2869 module MODULE_VAR_EXPORT fastcgi_module
= {
2870 STANDARD_MODULE_STUFF
,
2871 init_module
, /* initializer */
2872 fcgi_config_create_dir_config
, /* per-dir config creator */
2873 NULL
, /* per-dir config merger (default: override) */
2874 NULL
, /* per-server config creator */
2875 NULL
, /* per-server config merger (default: override) */
2876 fastcgi_cmds
, /* command table */
2877 fastcgi_handlers
, /* [9] content handlers */
2878 NULL
, /* [2] URI-to-filename translation */
2879 check_user_authentication
, /* [5] authenticate user_id */
2880 check_user_authorization
, /* [6] authorize user_id */
2881 check_access
, /* [4] check access (based on src & http headers) */
2882 NULL
, /* [7] check/set MIME type */
2883 fixups
, /* [8] fixups */
2884 NULL
, /* [10] logger */
2885 NULL
, /* [3] header-parser */
2886 fcgi_child_init
, /* process initialization */
2888 fcgi_child_exit
, /* process exit/cleanup */
2892 NULL
/* [1] post read-request handling */
2895 #endif /* !APACHE2 */