4 * Apache server module for FastCGI.
6 * $Id: mod_fastcgi.c,v 1.109 2001/03/27 14:07:53 robs Exp $
8 * Copyright (c) 1995-1996 Open Market, Inc.
10 * See the file "LICENSE.TERMS" for information on usage and redistribution
11 * of this file, and for a DISCLAIMER OF ALL WARRANTIES.
14 * Patches for Apache-1.1 provided by
18 * Patches for Linux provided by
20 * <langles@vote-smart.org>
22 * Patches for suexec handling by
23 * Brian Grossman <brian@SoftHome.net> and
24 * Rob Saccoccio <robs@ipass.net>
28 * Module design notes.
32 * mod_fastcgi spawns several processes: one process manager process
33 * and several application processes. None of these processes
34 * handle SIGHUP, so they just go away when the Web server performs
35 * a restart (as Apache does every time it starts.)
37 * In order to allow the process manager to properly cleanup the
38 * running fastcgi processes (without being disturbed by Apache),
39 * an intermediate process was introduced. The diagram is as follows;
41 * ApacheWS --> MiddleProc --> ProcMgr --> FCGI processes
43 * On a restart, ApacheWS sends a SIGKILL to MiddleProc and then
44 * collects it via waitpid(). The ProcMgr periodically checks for
45 * its parent (via getppid()) and if it does not have one, as in
46 * case when MiddleProc has terminated, ProcMgr issues a SIGTERM
47 * to all FCGI processes, waitpid()s on them and then exits, so it
48 * can be collected by init(1). Doing it any other way (short of
49 * changing Apache API), results either in inconsistent results or
50 * in generation of zombie processes.
52 * XXX: How does Apache 1.2 implement "gentle" restart
53 * that does not disrupt current connections? How does
54 * gentle restart interact with restart cleanup?
56 * 2. Request timeouts.
58 * Earlier versions of this module used ap_soft_timeout() rather than
59 * ap_hard_timeout() and ate FastCGI server output until it completed.
60 * This precluded the FastCGI server from having to implement a
61 * SIGPIPE handler, but meant hanging the application longer than
62 * necessary. SIGPIPE handler now must be installed in ALL FastCGI
63 * applications. The handler should abort further processing and go
64 * back into the accept() loop.
66 * Although using ap_soft_timeout() is better than ap_hard_timeout()
67 * we have to be more careful about SIGINT handling and subsequent
68 * processing, so, for now, make it hard.
75 #define timersub(a, b, result) \
77 (result)->tv_sec = (a)->tv_sec - (b)->tv_sec; \
78 (result)->tv_usec = (a)->tv_usec - (b)->tv_usec; \
79 if ((result)->tv_usec < 0) { \
81 (result)->tv_usec += 1000000; \
90 pool
*fcgi_config_pool
; /* the config pool */
91 server_rec
*fcgi_apache_main_server
;
93 const char *fcgi_wrapper
= NULL
; /* wrapper path */
94 uid_t fcgi_user_id
; /* the run uid of Apache & PM */
95 gid_t fcgi_group_id
; /* the run gid of Apache & PM */
97 fcgi_server
*fcgi_servers
= NULL
; /* AppClasses */
99 char *fcgi_socket_dir
= DEFAULT_SOCK_DIR
; /* default FastCgiIpcDir */
102 pid_t fcgi_pm_pid
= -1;
104 char *fcgi_dynamic_dir
= NULL
; /* directory for the dynamic
105 * fastcgi apps' sockets */
108 #pragma warning( disable : 4706 4100 4127)
109 fcgi_pm_job
*fcgi_dynamic_mbox
= NULL
;
110 HANDLE
*fcgi_dynamic_mbox_mutex
= NULL
;
111 HANDLE fcgi_pm_thread
= INVALID_HANDLE_VALUE
;
114 char *fcgi_empty_env
= NULL
;
116 u_int dynamicMaxProcs
= FCGI_DEFAULT_MAX_PROCS
;
117 int dynamicMinProcs
= FCGI_DEFAULT_MIN_PROCS
;
118 int dynamicMaxClassProcs
= FCGI_DEFAULT_MAX_CLASS_PROCS
;
119 u_int dynamicKillInterval
= FCGI_DEFAULT_KILL_INTERVAL
;
120 u_int dynamicUpdateInterval
= FCGI_DEFAULT_UPDATE_INTERVAL
;
121 float dynamicGain
= FCGI_DEFAULT_GAIN
;
122 int dynamicThreshold1
= FCGI_DEFAULT_THRESHOLD_1
;
123 int dynamicThresholdN
= FCGI_DEFAULT_THRESHOLD_N
;
124 u_int dynamicPleaseStartDelay
= FCGI_DEFAULT_START_PROCESS_DELAY
;
125 u_int dynamicAppConnectTimeout
= FCGI_DEFAULT_APP_CONN_TIMEOUT
;
126 char **dynamicEnvp
= &fcgi_empty_env
;
127 u_int dynamicProcessSlack
= FCGI_DEFAULT_PROCESS_SLACK
;
128 int dynamicAutoRestart
= FCGI_DEFAULT_RESTART_DYNAMIC
;
129 int dynamicAutoUpdate
= FCGI_DEFAULT_AUTOUPDATE
;
130 u_int dynamicListenQueueDepth
= FCGI_DEFAULT_LISTEN_Q
;
131 u_int dynamicInitStartDelay
= DEFAULT_INIT_START_DELAY
;
132 u_int dynamicRestartDelay
= FCGI_DEFAULT_RESTART_DELAY
;
133 array_header
*dynamic_pass_headers
= NULL
;
134 u_int dynamic_idle_timeout
= FCGI_DEFAULT_IDLE_TIMEOUT
;
136 /*******************************************************************************
137 * Construct a message and write it to the pm_pipe.
139 static void send_to_pm(const char id
, const char * const fs_path
,
140 const char *user
, const char * const group
, const unsigned long q_usec
,
141 const unsigned long req_usec
)
144 fcgi_pm_job
*job
= NULL
;
146 if (!(job
= (fcgi_pm_job
*) malloc(sizeof(fcgi_pm_job
))))
150 char buf
[FCGI_MAX_MSG_LEN
];
153 if (strlen(fs_path
) > FCGI_MAXPATH
) {
154 ap_log_error(FCGI_LOG_ERR_NOERRNO
, fcgi_apache_main_server
,
155 "FastCGI: the path \"%s\" is too long (>%d) for a dynamic server", fs_path
, FCGI_MAXPATH
);
164 job
->fs_path
= strdup(fs_path
);
165 job
->user
= strdup(user
);
166 job
->group
= strdup(group
);
168 job
->start_time
= 0L;
170 buflen
= sprintf(buf
, "%c %s %s %s*", id
, fs_path
, user
, group
);
177 job
->fs_path
= strdup(fs_path
);
178 job
->user
= strdup(user
);
179 job
->group
= strdup(group
);
181 job
->start_time
= 0L;
183 buflen
= sprintf(buf
, "%c %s %s %s*", id
, fs_path
, user
, group
);
190 job
->fs_path
= strdup(fs_path
);
192 job
->start_time
= req_usec
;
193 job
->user
= strdup(user
);
194 job
->group
= strdup(group
);
196 buflen
= sprintf(buf
, "%c %s %s %s %lu %lu*", id
, fs_path
, user
, group
, q_usec
, req_usec
);
202 if (fcgi_pm_add_job(job
) == 0)
205 SetEvent(fcgi_event_handles
[MBOX_EVENT
]);
207 ap_assert(buflen
<= FCGI_MAX_MSG_LEN
);
209 if (write(fcgi_pm_pipe
[1], (const void *)buf
, buflen
) != buflen
) {
210 ap_log_error(FCGI_LOG_WARN
, fcgi_apache_main_server
,
211 "FastCGI: write() to PM failed");
217 *----------------------------------------------------------------------
221 * An Apache module initializer, called by the Apache core
222 * after reading the server config.
224 * Start the process manager no matter what, since there may be a
225 * request for dynamic FastCGI applications without any being
226 * configured as static applications. Also, check for the existence
227 * and create if necessary a subdirectory into which all dynamic
230 *----------------------------------------------------------------------
232 static void init_module(server_rec
*s
, pool
*p
)
236 /* Register to reset to default values when the config pool is cleaned */
238 ap_register_cleanup(p
, NULL
, fcgi_config_reset_globals
, ap_null_cleanup
);
241 ap_add_version_component("mod_fastcgi/" MOD_FASTCGI_VERSION
);
243 fcgi_config_set_fcgi_uid_n_gid(1);
245 /* keep these handy */
246 fcgi_config_pool
= p
;
247 fcgi_apache_main_server
= s
;
250 /* Create Unix/Domain socket directory */
251 if ((err
= fcgi_config_make_dir(p
, fcgi_socket_dir
)))
252 ap_log_error(FCGI_LOG_ERR
, s
, "FastCGI: %s", err
);
255 /* Create Dynamic directory */
256 if ((err
= fcgi_config_make_dynamic_dir(p
, 1)))
257 ap_log_error(FCGI_LOG_ERR
, s
, "FastCGI: %s", err
);
260 /* Create the pipe for comm with the PM */
261 if (pipe(fcgi_pm_pipe
) < 0) {
262 ap_log_error(FCGI_LOG_ERR
, s
, "FastCGI: pipe() failed");
265 /* Spawn the PM only once. Under Unix, Apache calls init() routines
266 * twice, once before detach() and once after. Win32 doesn't detach.
267 * Under DSO, DSO modules are unloaded between the two init() calls.
268 * Under Unix, the -X switch causes two calls to init() but no detach
269 * (but all subprocesses are wacked so the PM is toasted anyway)! */
271 if (ap_standalone
&& getppid() != 1)
274 /* Start the Process Manager */
275 fcgi_pm_pid
= ap_spawn_child(p
, fcgi_pm_main
, NULL
, kill_only_once
, NULL
, NULL
, NULL
);
276 if (fcgi_pm_pid
<= 0) {
277 ap_log_error(FCGI_LOG_ALERT
, s
,
278 "FastCGI: can't start the process manager, spawn_child() failed");
281 close(fcgi_pm_pipe
[0]);
285 static void fcgi_child_init(server_rec
*dc0
, pool
*dc1
)
288 /* Create the Event Handlers */
289 fcgi_event_handles
[0] = CreateEvent(NULL
, FALSE
, FALSE
, NULL
);
290 fcgi_event_handles
[1] = CreateEvent(NULL
, FALSE
, FALSE
, NULL
);
291 fcgi_event_handles
[2] = CreateEvent(NULL
, FALSE
, FALSE
, NULL
);
292 fcgi_dynamic_mbox_mutex
= ap_create_mutex("fcgi_dynamic_mbox_mutex");
294 /* Spawn of the process manager thread */
295 fcgi_pm_thread
= CreateThread(NULL
, 0, (LPTHREAD_START_ROUTINE
)fcgi_pm_main
, NULL
, 0, NULL
);
300 static void fcgi_child_exit(server_rec
*dc0
, pool
*dc1
)
303 /* Signaling the PM thread tp exit*/
304 SetEvent(fcgi_event_handles
[TERM_EVENT
]);
306 /* Waiting on pm thread to exit */
307 WaitForSingleObject(fcgi_pm_thread
, INFINITE
);
314 *----------------------------------------------------------------------
318 * Terminate a line: scan to the next newline, scan back to the
319 * first non-space character and store a terminating zero. Return
320 * the next character past the end of the newline.
322 * If the end of the string is reached, ASSERT!
324 * If the FIRST character(s) in the line are '\n' or "\r\n", the
325 * first character is replaced with a NULL and next character
326 * past the newline is returned. NOTE: this condition supercedes
327 * the processing of RFC-822 continuation lines.
329 * If continuation is set to 'TRUE', then it parses a (possible)
330 * sequence of RFC-822 continuation lines.
336 * Termination byte stored in string.
338 *----------------------------------------------------------------------
340 static char *get_header_line(char *start
, int continuation
)
345 if(p
[0] == '\r' && p
[1] == '\n') { /* If EOL in 1st 2 chars */
346 p
++; /* point to \n and stop */
347 } else if(*p
!= '\n') {
350 if(*p
== '\n' && p
[1] != ' ' && p
[1] != '\t')
355 while(*p
!= '\0' && *p
!= '\n') {
361 ap_assert(*p
!= '\0');
366 * Trim any trailing whitespace.
368 while(isspace((unsigned char)p
[-1]) && p
> start
) {
377 *----------------------------------------------------------------------
381 * Call with r->parseHeader == SCAN_CGI_READING_HEADERS
382 * and initial script output in fr->header.
384 * If the initial script output does not include the header
385 * terminator ("\r\n\r\n") process_headers returns with no side
386 * effects, to be called again when more script output
387 * has been appended to fr->header.
389 * If the initial script output includes the header terminator,
390 * process_headers parses the headers and determines whether or
391 * not the remaining script output will be sent to the client.
392 * If so, process_headers sends the HTTP response headers to the
393 * client and copies any non-header script output to the output
400 * May set r->parseHeader to:
401 * SCAN_CGI_FINISHED -- headers parsed, returning script response
402 * SCAN_CGI_BAD_HEADER -- malformed header from script
403 * SCAN_CGI_INT_REDIRECT -- handler should perform internal redirect
404 * SCAN_CGI_SRV_REDIRECT -- handler should return REDIRECT
406 *----------------------------------------------------------------------
409 static const char *process_headers(request_rec
*r
, fcgi_request
*fr
)
411 char *p
, *next
, *name
, *value
;
413 int hasContentType
, hasStatus
, hasLocation
;
415 ap_assert(fr
->parseHeader
== SCAN_CGI_READING_HEADERS
);
417 if (fr
->header
== NULL
)
421 * Do we have the entire header? Scan for the blank line that
422 * terminates the header.
424 p
= (char *)fr
->header
->elts
;
425 len
= fr
->header
->nelts
;
427 while(len
-- && flag
< 2) {
437 name
= "Invalid Character";
447 /* Return (to be called later when we have more data)
448 * if we don't have an entire header. */
453 * Parse all the headers.
455 fr
->parseHeader
= SCAN_CGI_FINISHED
;
456 hasContentType
= hasStatus
= hasLocation
= FALSE
;
457 next
= (char *)fr
->header
->elts
;
459 next
= get_header_line(name
= next
, TRUE
);
463 if ((p
= strchr(name
, ':')) == NULL
) {
467 while (p
!= name
&& isspace((unsigned char)*(p
- 1))) {
474 if (strpbrk(name
, " \t") != NULL
) {
478 while (isspace((unsigned char)*value
)) {
482 if (strcasecmp(name
, "Status") == 0) {
483 int statusValue
= strtol(value
, NULL
, 10);
486 goto DuplicateNotAllowed
;
488 if (statusValue
< 0) {
489 fr
->parseHeader
= SCAN_CGI_BAD_HEADER
;
490 return ap_psprintf(r
->pool
, "invalid Status '%s'", value
);
493 r
->status
= statusValue
;
494 r
->status_line
= ap_pstrdup(r
->pool
, value
);
498 if (fr
->role
== FCGI_RESPONDER
) {
499 if (strcasecmp(name
, "Content-type") == 0) {
500 if (hasContentType
) {
501 goto DuplicateNotAllowed
;
503 hasContentType
= TRUE
;
504 r
->content_type
= ap_pstrdup(r
->pool
, value
);
508 if (strcasecmp(name
, "Location") == 0) {
510 goto DuplicateNotAllowed
;
513 ap_table_set(r
->headers_out
, "Location", value
);
517 /* If the script wants them merged, it can do it */
518 ap_table_add(r
->err_headers_out
, name
, value
);
522 ap_table_add(fr
->authHeaders
, name
, value
);
526 if (fr
->role
!= FCGI_RESPONDER
)
530 * Who responds, this handler or Apache?
533 const char *location
= ap_table_get(r
->headers_out
, "Location");
535 * Based on internal redirect handling in mod_cgi.c...
537 * If a script wants to produce its own Redirect
538 * body, it now has to explicitly *say* "Status: 302"
540 if (r
->status
== 200) {
541 if(location
[0] == '/') {
543 * Location is an relative path. This handler will
544 * consume all script output, then have Apache perform an
547 fr
->parseHeader
= SCAN_CGI_INT_REDIRECT
;
551 * Location is an absolute URL. If the script didn't
552 * produce a Content-type header, this handler will
553 * consume all script output and then have Apache generate
554 * its standard redirect response. Otherwise this handler
555 * will transmit the script's response.
557 fr
->parseHeader
= SCAN_CGI_SRV_REDIRECT
;
563 * We're responding. Send headers, buffer excess script output.
565 ap_send_http_header(r
);
567 /* We need to reinstate our timeout, send_http_header() kill()s it */
568 ap_hard_timeout("FastCGI request processing", r
);
573 len
= fr
->header
->nelts
- (next
- fr
->header
->elts
);
575 ap_assert(BufferLength(fr
->clientOutputBuffer
) == 0);
576 if (BufferFree(fr
->clientOutputBuffer
) < len
) {
577 fr
->clientOutputBuffer
= fcgi_buf_new(r
->pool
, len
);
579 ap_assert(BufferFree(fr
->clientOutputBuffer
) >= len
);
581 int sent
= fcgi_buf_add_block(fr
->clientOutputBuffer
, next
, len
);
582 ap_assert(sent
== len
);
587 /* Log first line of a multi-line header */
588 if ((p
= strpbrk(name
, "\r\n")) != NULL
)
590 fr
->parseHeader
= SCAN_CGI_BAD_HEADER
;
591 return ap_psprintf(r
->pool
, "malformed header '%s'", name
);
594 fr
->parseHeader
= SCAN_CGI_BAD_HEADER
;
595 return ap_psprintf(r
->pool
, "duplicate header '%s'", name
);
599 * Read from the client filling both the FastCGI server buffer and the
600 * client buffer with the hopes of buffering the client data before
601 * making the connect() to the FastCGI server. This prevents slow
602 * clients from keeping the FastCGI server in processing longer than is
605 static int read_from_client_n_queue(fcgi_request
*fr
)
611 while (BufferFree(fr
->clientInputBuffer
) > 0 || BufferFree(fr
->serverOutputBuffer
) > 0) {
612 fcgi_protocol_queue_client_buffer(fr
);
614 if (fr
->expectingClientContent
<= 0)
617 fcgi_buf_get_free_block_info(fr
->clientInputBuffer
, &end
, &count
);
621 if ((countRead
= ap_get_client_block(fr
->r
, end
, count
)) < 0)
624 if (countRead
== 0) {
625 fr
->expectingClientContent
= 0;
628 fcgi_buf_add_update(fr
->clientInputBuffer
, countRead
);
629 ap_reset_timeout(fr
->r
);
635 static int write_to_client(fcgi_request
*fr
)
640 fcgi_buf_get_block_info(fr
->clientOutputBuffer
, &begin
, &count
);
644 /* If fewer than count bytes are written, an error occured.
645 * ap_bwrite() typically forces a flushed write to the client, this
646 * effectively results in a block (and short packets) - it should
647 * be fixed, but I didn't win much support for the idea on new-httpd.
648 * So, without patching Apache, the best way to deal with this is
649 * to size the fcgi_bufs to hold all of the script output (within
650 * reason) so the script can be released from having to wait around
651 * for the transmission to the client to complete. */
652 #ifdef RUSSIAN_APACHE
653 if (ap_rwrite(begin
, count
, fr
->r
) != count
) {
654 ap_log_rerror(FCGI_LOG_INFO_NOERRNO
, fr
->r
,
655 "FastCGI: client stopped connection before send body completed");
659 if (ap_bwrite(fr
->r
->connection
->client
, begin
, count
) != (int) count
) {
660 ap_log_rerror(FCGI_LOG_INFO_NOERRNO
, fr
->r
,
661 "FastCGI: client stopped connection before send body completed");
666 ap_reset_timeout(fr
->r
);
668 /* Don't bother with a wrapped buffer, limiting exposure to slow
669 * clients. The BUFF routines don't allow a writev from above,
670 * and don't always memcpy to minimize small write()s, this should
671 * be fixed, but I didn't win much support for the idea on
672 * new-httpd - I'll have to _prove_ its a problem first.. */
674 /* The default behaviour used to be to flush with every write, but this
675 * can tie up the FastCGI server longer than is necessary so its an option now */
676 if (fr
->fs
&& fr
->fs
->flush
) {
677 #ifdef RUSSIAN_APACHE
678 if (ap_rflush(fr
->r
)) {
679 ap_log_rerror(FCGI_LOG_INFO_NOERRNO
, fr
->r
,
680 "FastCGI: client stopped connection before send body completed");
684 if (ap_bflush(fr
->r
->connection
->client
)) {
685 ap_log_rerror(FCGI_LOG_INFO_NOERRNO
, fr
->r
,
686 "FastCGI: client stopped connection before send body completed");
690 ap_reset_timeout(fr
->r
);
693 fcgi_buf_toss(fr
->clientOutputBuffer
, count
);
697 /*******************************************************************************
698 * Determine the user and group the wrapper should be called with.
699 * Based on code in Apache's create_argv_cmd() (util_script.c).
701 static void set_uid_n_gid(request_rec
*r
, const char **user
, const char **group
)
703 if (fcgi_wrapper
== NULL
) {
709 if (strncmp("/~", r
->uri
, 2) == 0) {
710 /* its a user dir uri, just send the ~user, and leave it to the PM */
711 char *end
= strchr(r
->uri
+ 2, '/');
714 *user
= memcpy(ap_pcalloc(r
->pool
, end
- r
->uri
), r
->uri
+ 1, end
- r
->uri
- 1);
716 *user
= ap_pstrdup(r
->pool
, r
->uri
+ 1);
720 *user
= ap_psprintf(r
->pool
, "%ld", (long)r
->server
->server_uid
);
721 *group
= ap_psprintf(r
->pool
, "%ld", (long)r
->server
->server_gid
);
725 /*******************************************************************************
726 * Close the connection to the FastCGI server. This is normally called by
727 * do_work(), but may also be called as in request pool cleanup.
729 static void close_connection_to_fs(fcgi_request
*fr
)
731 pool
*rp
= fr
->r
->pool
;
734 ap_pclosesocket(rp
, fr
->fd
);
739 if (fr
->keepReadingFromFcgiApp
== FALSE
) {
740 /* XXX REQ_COMPLETE is only sent for requests which complete
741 * normally WRT the fcgi app. There is no data sent for
742 * connect() timeouts or requests which complete abnormally.
743 * KillDynamicProcs() and RemoveRecords() need to be looked at
744 * to be sure they can reasonably handle these cases before
745 * sending these sort of stats - theres some funk in there.
746 * XXX We should do something special when this a pool cleanup.
748 if (fcgi_util_gettimeofday(&fr
->completeTime
) < 0) {
749 /* there's no point to aborting the request, just log it */
750 ap_log_error(FCGI_LOG_ERR
, fr
->r
->server
, "FastCGI: can't get time of day");
752 struct timeval qtime
, rtime
;
754 timersub(&fr
->queueTime
, &fr
->startTime
, &qtime
);
755 timersub(&fr
->completeTime
, &fr
->queueTime
, &rtime
);
757 send_to_pm(FCGI_COMPLETE
, fr
->fs_path
,
759 qtime
.tv_sec
* 1000000 + qtime
.tv_usec
,
760 rtime
.tv_sec
* 1000000 + rtime
.tv_usec
);
768 static int set_nonblocking(SOCKET fd
, int nonblocking
)
770 unsigned long ioctl_arg
= (nonblocking
) ? 1 : 0;
771 return ioctlsocket(fd
, FIONBIO
, &ioctl_arg
);
776 static int set_nonblocking(int fd
, int nonblocking
)
779 int fd_flags
= fcntl(fd
, F_GETFL
, 0);
781 if (fd_flags
< 0) return -1;
783 #if defined(O_NONBLOCK)
784 nb_flag
= O_NONBLOCK
;
785 #elif defined(O_NDELAY)
787 #elif defined(FNDELAY)
790 #error "TODO - don't read from app until all data from client is posted."
793 fd_flags
= (nonblocking
) ? (fd_flags
| nb_flag
) : (fd_flags
& ~nb_flag
);
795 return fcntl(fd
, F_SETFL
, fd_flags
);
800 /*******************************************************************************
801 * Connect to the FastCGI server.
803 static int open_connection_to_fs(fcgi_request
*fr
)
806 fd_set write_fds
, read_fds
;
808 request_rec
* const r
= fr
->r
;
809 pool
* const rp
= r
->pool
;
810 const char *socket_path
= NULL
;
811 struct sockaddr
*socket_addr
= NULL
;
812 int socket_addr_len
= 0;
814 const char *err
= NULL
;
817 /* Create the connection point */
820 socket_path
= fcgi_util_socket_hash_filename(rp
, fr
->fs_path
, fr
->user
, fr
->group
);
821 socket_path
= fcgi_util_socket_make_path_absolute(rp
, socket_path
, 1);
824 err
= fcgi_util_socket_make_domain_addr(rp
, (struct sockaddr_un
**)&socket_addr
,
825 &socket_addr_len
, socket_path
);
827 ap_log_rerror(FCGI_LOG_ERR
, r
,
828 "FastCGI: failed to connect to server \"%s\": "
829 "%s", fr
->fs_path
, err
);
837 if (fr
->fs
->dest_addr
!= NULL
) {
838 socket_addr
= fr
->fs
->dest_addr
;
840 else if (fr
->fs
->socket_addr
) {
841 socket_addr
= fr
->fs
->socket_addr
;
844 socket_path
= fr
->fs
->socket_path
;
847 socket_addr
= fr
->fs
->socket_addr
;
849 socket_addr_len
= fr
->fs
->socket_addr_len
;
855 if (fr
->fs
&& fr
->fs
->restartTime
)
857 struct stat sock_stat
;
859 if (stat(socket_path
, &sock_stat
) == 0)
863 if (dynamicAutoUpdate
)
865 struct stat app_stat
;
867 /* TODO: follow sym links */
869 if (stat(fr
->fs_path
, &app_stat
) == 0)
872 if (fr
->fs
->restartTime
< app_stat
.st_mtime
)
874 if (sock_stat
.st_mtime
< app_stat
.st_mtime
)
878 struct timeval tv
= {1, 0};
881 * There's a newer one, request a restart.
883 send_to_pm(FCGI_RESTART
, fr
->fs_path
, fr
->user
, fr
->group
, 0, 0);
888 /* Avoid sleep/alarm interactions */
889 ap_select(0, NULL
, NULL
, NULL
, &tv
);
897 send_to_pm(FCGI_START
, fr
->fs_path
, fr
->user
, fr
->group
, 0, 0);
899 /* Wait until it looks like its running */
906 fr
->fs
= fcgi_util_fs_get_by_id(fr
->fs_path
, 0, 0);
908 if (fr
->fs
&& fr
->fs
->restartTime
)
910 struct timeval tv
= {1, 0};
912 /* Avoid sleep/alarm interactions */
913 ap_select(0, NULL
, NULL
, NULL
, &tv
);
915 if (stat(socket_path
, &sock_stat
) == 0)
931 int max_connect_time
= FCGI_NAMED_PIPE_CONNECT_TIMEOUT
;
933 fr
->using_npipe_io
= TRUE
;
937 interval
= dynamicPleaseStartDelay
* 1000;
939 if (dynamicAppConnectTimeout
) {
940 max_connect_time
= dynamicAppConnectTimeout
;
945 interval
= FCGI_NAMED_PIPE_CONNECT_TIMEOUT
* 1000;
947 if (fr
->fs
->appConnectTimeout
) {
948 max_connect_time
= fr
->fs
->appConnectTimeout
;
952 if (fcgi_util_gettimeofday(&fr
->startTime
) < 0) {
953 ap_log_rerror(FCGI_LOG_ERR
, r
,
954 "FastCGI: failed to connect to server \"%s\": "
955 "can't get time of day", fr
->fs_path
);
961 fr
->fd
= (SOCKET
) CreateFile(socket_path
,
962 GENERIC_READ
| GENERIC_WRITE
,
963 FILE_SHARE_READ
| FILE_SHARE_WRITE
,
964 NULL
, // no security attributes
965 OPEN_EXISTING
, // opens existing pipe
966 FILE_ATTRIBUTE_NORMAL
, // default attributes
967 NULL
); // no template file
969 if (fr
->fd
!= (SOCKET
) INVALID_HANDLE_VALUE
) {
973 if (GetLastError() != ERROR_PIPE_BUSY
974 && GetLastError() != ERROR_FILE_NOT_FOUND
)
976 ap_log_rerror(FCGI_LOG_ERR
, r
,
977 "FastCGI: failed to connect to server \"%s\": "
978 "CreateFile() failed", fr
->fs_path
);
982 // All pipe instances are busy, so wait
983 ready
= WaitNamedPipe(socket_path
, interval
);
985 if (fr
->dynamic
&& !ready
) {
986 send_to_pm(FCGI_TIMEOUT
, fr
->fs_path
, fr
->user
, fr
->group
, 0, 0);
989 if (fcgi_util_gettimeofday(&fr
->queueTime
) < 0) {
990 ap_log_rerror(FCGI_LOG_ERR
, r
,
991 "FastCGI: failed to connect to server \"%s\": "
992 "can't get time of day", fr
->fs_path
);
996 connect_time
= fr
->queueTime
.tv_sec
- fr
->startTime
.tv_sec
;
998 FCGIDBG5("interval=%d, max_connect_time=%d, connect_time=%d, ready=%d", interval
, max_connect_time
, connect_time
, ready
);
1000 } while (connect_time
< max_connect_time
);
1002 if (fr
->fd
== (SOCKET
) INVALID_HANDLE_VALUE
) {
1003 ap_log_rerror(FCGI_LOG_ERR
, r
,
1004 "FastCGI: failed to connect to server \"%s\": "
1005 "CreateFile()/WaitNamedPipe() timed out", fr
->fs_path
);
1009 FCGIDBG2("got_named_pipe_connect: %s", fr
->fs_path
);
1012 ap_note_cleanups_for_h(rp
, (HANDLE
) fr
->fd
);
1013 ap_unblock_alarms();
1019 /* Create the socket */
1020 fr
->fd
= ap_psocket(rp
, socket_addr
->sa_family
, SOCK_STREAM
, 0);
1024 errno
= WSAGetLastError(); // Not sure this is going to work as expected
1026 ap_log_rerror(FCGI_LOG_ERR_ERRNO
, r
,
1027 "FastCGI: failed to connect to server \"%s\": "
1028 "ap_psocket() failed", fr
->fs_path
);
1033 if (fr
->fd
>= FD_SETSIZE
) {
1034 ap_log_rerror(FCGI_LOG_ERR
, r
,
1035 "FastCGI: failed to connect to server \"%s\": "
1036 "socket file descriptor (%u) is larger than "
1037 "FD_SETSIZE (%u), you probably need to rebuild Apache with a "
1038 "larger FD_SETSIZE", fr
->fs_path
, fr
->fd
, FD_SETSIZE
);
1043 /* If appConnectTimeout is non-zero, setup do a non-blocking connect */
1044 if ((fr
->dynamic
&& dynamicAppConnectTimeout
) || (!fr
->dynamic
&& fr
->fs
->appConnectTimeout
)) {
1045 set_nonblocking(fr
->fd
, TRUE
);
1048 if (fr
->dynamic
&& fcgi_util_gettimeofday(&fr
->startTime
) < 0) {
1049 ap_log_rerror(FCGI_LOG_ERR
, r
,
1050 "FastCGI: failed to connect to server \"%s\": "
1051 "can't get time of day", fr
->fs_path
);
1056 if (connect(fr
->fd
, (struct sockaddr
*)socket_addr
, socket_addr_len
) == 0)
1057 goto ConnectionComplete
;
1061 errno
= WSAGetLastError();
1062 if (errno
!= WSAEWOULDBLOCK
) {
1063 ap_log_rerror(FCGI_LOG_ERR_ERRNO
, r
,
1064 "FastCGI: failed to connect to server \"%s\": "
1065 "connect() failed", fr
->fs_path
);
1071 /* ECONNREFUSED means the listen queue is full (or there isn't one).
1072 * With dynamic I can at least make sure the PM knows this is occuring */
1073 if (fr
->dynamic
&& errno
== ECONNREFUSED
) {
1074 /* @@@ This might be better as some other "kind" of message */
1075 send_to_pm(rp
, CONN_TIMEOUT
, fr
->fs_path
, fr
->user
, fr
->group
, 0, 0);
1077 errno
= ECONNREFUSED
;
1080 if (errno
!= EINPROGRESS
) {
1081 ap_log_rerror(FCGI_LOG_ERR
, r
,
1082 "FastCGI: failed to connect to server \"%s\": "
1083 "connect() failed", fr
->fs_path
);
1089 /* The connect() is non-blocking */
1095 FD_ZERO(&write_fds
);
1096 FD_SET(fr
->fd
, &write_fds
);
1097 read_fds
= write_fds
;
1098 tval
.tv_sec
= dynamicPleaseStartDelay
;
1101 status
= ap_select((fr
->fd
+1), &read_fds
, &write_fds
, NULL
, &tval
);
1105 if (fcgi_util_gettimeofday(&fr
->queueTime
) < 0) {
1106 ap_log_rerror(FCGI_LOG_ERR
, r
,
1107 "FastCGI: failed to connect to server \"%s\": "
1108 "can't get time of day", fr
->fs_path
);
1115 /* select() timed out */
1116 send_to_pm(FCGI_TIMEOUT
, fr
->fs_path
, fr
->user
, fr
->group
, 0, 0);
1117 } while ((fr
->queueTime
.tv_sec
- fr
->startTime
.tv_sec
) < (int)dynamicAppConnectTimeout
);
1119 /* XXX These can be moved down when dynamic vars live is a struct */
1121 ap_log_rerror(FCGI_LOG_ERR_NOERRNO
, r
,
1122 "FastCGI: failed to connect to server \"%s\": "
1123 "connect() timed out (appConnTimeout=%dsec)",
1124 fr
->fs_path
, dynamicAppConnectTimeout
);
1129 tval
.tv_sec
= fr
->fs
->appConnectTimeout
;
1131 FD_ZERO(&write_fds
);
1132 FD_SET(fr
->fd
, &write_fds
);
1133 read_fds
= write_fds
;
1135 status
= ap_select((fr
->fd
+1), &read_fds
, &write_fds
, NULL
, &tval
);
1138 ap_log_rerror(FCGI_LOG_ERR_NOERRNO
, r
,
1139 "FastCGI: failed to connect to server \"%s\": "
1140 "connect() timed out (appConnTimeout=%dsec)",
1141 fr
->fs_path
, dynamicAppConnectTimeout
);
1148 errno
= WSAGetLastError();
1150 ap_log_rerror(FCGI_LOG_ERR_ERRNO
, r
,
1151 "FastCGI: failed to connect to server \"%s\": "
1152 "select() failed", fr
->fs_path
);
1156 if (FD_ISSET(fr
->fd
, &write_fds
) || FD_ISSET(fr
->fd
, &read_fds
)) {
1158 NET_SIZE_T len
= sizeof(error
);
1160 if (getsockopt(fr
->fd
, SOL_SOCKET
, SO_ERROR
, (char *)&error
, &len
) < 0) {
1161 /* Solaris pending error */
1163 errno
= WSAGetLastError();
1165 ap_log_rerror(FCGI_LOG_ERR_ERRNO
, r
,
1166 "FastCGI: failed to connect to server \"%s\": "
1167 "select() failed (Solaris pending error)", fr
->fs_path
);
1172 /* Berkeley-derived pending error */
1174 ap_log_rerror(FCGI_LOG_ERR_ERRNO
, r
,
1175 "FastCGI: failed to connect to server \"%s\": "
1176 "select() failed (pending error)", fr
->fs_path
);
1182 errno
= WSAGetLastError();
1184 ap_log_rerror(FCGI_LOG_ERR_ERRNO
, r
,
1185 "FastCGI: failed to connect to server \"%s\": "
1186 "select() error - THIS CAN'T HAPPEN!", fr
->fs_path
);
1191 /* Return to blocking mode if it was set up */
1192 if ((fr
->dynamic
&& dynamicAppConnectTimeout
) || (!fr
->dynamic
&& fr
->fs
->appConnectTimeout
)) {
1193 set_nonblocking(fr
->fd
, FALSE
);
1197 if (socket_addr
->sa_family
== AF_INET
) {
1198 /* We shouldn't be sending small packets and there's no application
1199 * level ack of the data we send, so disable Nagle */
1201 setsockopt(fr
->fd
, IPPROTO_TCP
, TCP_NODELAY
, (char *)&set
, sizeof(set
));
1208 static int server_error(fcgi_request
*fr
)
1210 #if defined(SIGPIPE) && MODULE_MAGIC_NUMBER < 19990320
1211 /* Make sure we leave with Apache's sigpipe_handler in place */
1212 if (fr
->apache_sigpipe_handler
!= NULL
)
1213 signal(SIGPIPE
, fr
->apache_sigpipe_handler
);
1215 close_connection_to_fs(fr
);
1216 ap_kill_timeout(fr
->r
);
1217 return SERVER_ERROR
;
1220 static void cleanup(void *data
)
1222 const fcgi_request
* const fr
= (fcgi_request
*)data
;
1228 set_nonblocking(fr
->fd
, FALSE
);
1231 if (fr
->fs_stderr_len
) {
1232 ap_log_rerror(FCGI_LOG_ERR_NOERRNO
, fr
->r
,
1233 "FastCGI: server \"%s\" stderr: %s", fr
->fs_path
, fr
->fs_stderr
);
1237 /*----------------------------------------------------------------------
1238 * This is the core routine for moving data between the FastCGI
1239 * application and the Web server's client.
1241 static int do_work(request_rec
*r
, fcgi_request
*fr
)
1243 struct timeval timeOut
, dynamic_last_activity_time
= {0, 0};
1244 fd_set read_set
, write_set
;
1245 int status
= 0, idle_timeout
;
1246 int numFDs
, dynamic_first_read
= fr
->dynamic
? 1 : 0;
1248 int envSent
= FALSE
; /* has the complete ENV been buffered? */
1251 const char *err
= NULL
;
1254 FD_ZERO(&write_set
);
1256 fcgi_protocol_queue_begin_request(fr
);
1258 /* Buffer as much of the environment as we can fit */
1260 envSent
= fcgi_protocol_queue_env(r
, fr
, &env
);
1262 /* Start the Apache dropdead timer. See comments at top of file. */
1263 ap_hard_timeout("buffering of FastCGI client data", r
);
1265 /* Read as much as possible from the client. */
1266 if (fr
->role
== FCGI_RESPONDER
) {
1267 status
= ap_setup_client_block(r
, REQUEST_CHUNKED_ERROR
);
1272 fr
->expectingClientContent
= (ap_should_client_block(r
) != 0);
1274 if (read_from_client_n_queue(fr
) != OK
)
1275 return server_error(fr
);
1278 /* Connect to the FastCGI Application */
1279 ap_hard_timeout("connect() to FastCGI server", r
);
1280 if (open_connection_to_fs(fr
) != FCGI_OK
) {
1281 return server_error(fr
);
1284 numFDs
= fr
->fd
+ 1;
1285 idle_timeout
= fr
->dynamic
? dynamic_idle_timeout
: fr
->fs
->idle_timeout
;
1287 if (dynamic_first_read
) {
1288 dynamic_last_activity_time
= fr
->startTime
;
1290 if (dynamicAppConnectTimeout
) {
1291 struct timeval qwait
;
1292 timersub(&fr
->queueTime
, &fr
->startTime
, &qwait
);
1293 dynamic_first_read
= qwait
.tv_sec
/ dynamicPleaseStartDelay
+ 1;
1297 /* @@@ We never reset the timer in this loop, most folks don't mess w/
1298 * Timeout directive which means we've got the 5 min default which is way
1299 * to long to tie up a fs. We need a better/configurable solution that
1300 * uses the select */
1301 ap_hard_timeout("FastCGI request processing", r
);
1303 /* Register to get the script's stderr logged at the end of the request */
1305 ap_register_cleanup(rp
, (void *)fr
, cleanup
, ap_null_cleanup
);
1306 ap_unblock_alarms();
1308 /* Before we do any writing, set the connection non-blocking */
1310 if (fr
->using_npipe_io
) {
1311 DWORD mode
= PIPE_NOWAIT
| PIPE_READMODE_BYTE
;
1312 SetNamedPipeHandleState((HANDLE
) fr
->fd
, &mode
, NULL
, NULL
);
1317 set_nonblocking(fr
->fd
, TRUE
);
1319 /* The socket is writeable, so get the first write out of the way */
1320 if (fcgi_buf_get_to_fd(fr
->serverOutputBuffer
, fr
->fd
) < 0) {
1322 if (! fr
->using_npipe_io
)
1323 ap_log_rerror(FCGI_LOG_ERR_ERRNO
, r
,
1324 "FastCGI: comm with server \"%s\" aborted: write failed", fr
->fs_path
);
1327 ap_log_rerror(FCGI_LOG_ERR
, r
,
1328 "FastCGI: comm with server \"%s\" aborted: write failed", fr
->fs_path
);
1329 return server_error(fr
);
1332 while (fr
->keepReadingFromFcgiApp
1333 || BufferLength(fr
->serverInputBuffer
) > 0
1334 || BufferLength(fr
->clientOutputBuffer
) > 0) {
1336 /* If we didn't buffer all of the environment yet, buffer some more */
1338 envSent
= fcgi_protocol_queue_env(r
, fr
, &env
);
1340 /* Read as much as possible from the client. */
1341 if (fr
->role
== FCGI_RESPONDER
&& !fr
->eofSent
&& envSent
) {
1343 /* ap_get_client_block() (called in read_from_client_n_queue()
1344 * can't handle a non-blocking fd, its a bummer. We might be
1345 * able to completely bypass the Apache BUFF routines in still
1346 * do it, but thats a major hassle. Apache 2.X will handle it,
1347 * and then so will we. */
1349 if (read_from_client_n_queue(fr
) != OK
)
1350 return server_error(fr
);
1353 /* To avoid deadlock, don't do a blocking select to write to
1354 * the FastCGI application without selecting to read from the
1355 * FastCGI application.
1357 doClientWrite
= FALSE
;
1358 if (fr
->keepReadingFromFcgiApp
&& BufferFree(fr
->serverInputBuffer
) > 0) {
1361 DWORD bytesavail
= 0;
1363 if (!fr
->using_npipe_io
) {
1365 FD_SET(fr
->fd
, &read_set
);
1367 /* Is data buffered for output to the FastCGI server? */
1368 if (BufferLength(fr
->serverOutputBuffer
) > 0) {
1369 FD_SET(fr
->fd
, &write_set
);
1371 FD_CLR(fr
->fd
, &write_set
);
1377 * If there's data buffered to send to the client, don't
1378 * wait indefinitely for the FastCGI app; the app might
1379 * be doing server push.
1381 if (BufferLength(fr
->clientOutputBuffer
) > 0) {
1383 timeOut
.tv_usec
= 100000; /* 0.1 sec */
1385 else if (dynamic_first_read
) {
1387 struct timeval qwait
;
1389 if (fcgi_util_gettimeofday(&fr
->queueTime
) < 0) {
1390 ap_log_rerror(FCGI_LOG_ERR
, r
, "FastCGI: can't get time of day");
1391 return server_error(fr
);
1394 /* Check for idle_timeout */
1396 dynamic_last_activity_time
= fr
->queueTime
;
1399 struct timeval idle_time
;
1400 timersub(&fr
->queueTime
, &dynamic_last_activity_time
, &idle_time
);
1401 if (idle_time
.tv_sec
> idle_timeout
) {
1402 send_to_pm(FCGI_TIMEOUT
, fr
->fs_path
, fr
->user
, fr
->group
, 0, 0);
1403 ap_log_rerror(FCGI_LOG_ERR_NOERRNO
, r
,
1404 "FastCGI: comm with (dynamic) server \"%s\" aborted: (first read) idle timeout (%d sec)",
1405 fr
->fs_path
, idle_timeout
);
1406 return server_error(fr
);
1410 timersub(&fr
->queueTime
, &fr
->startTime
, &qwait
);
1412 delay
= dynamic_first_read
* dynamicPleaseStartDelay
;
1413 if (qwait
.tv_sec
< delay
) {
1414 timeOut
.tv_sec
= delay
;
1415 timeOut
.tv_usec
= 100000; /* fudge for select() slop */
1416 timersub(&timeOut
, &qwait
, &timeOut
);
1419 /* Killed time somewhere.. client read? */
1420 send_to_pm(FCGI_TIMEOUT
, fr
->fs_path
, fr
->user
, fr
->group
, 0, 0);
1421 dynamic_first_read
= qwait
.tv_sec
/ dynamicPleaseStartDelay
+ 1;
1422 timeOut
.tv_sec
= dynamic_first_read
* dynamicPleaseStartDelay
;
1423 timeOut
.tv_usec
= 100000; /* fudge for select() slop */
1424 timersub(&timeOut
, &qwait
, &timeOut
);
1428 timeOut
.tv_sec
= idle_timeout
;
1429 timeOut
.tv_usec
= 0;
1433 if (!fr
->using_npipe_io
) {
1435 if ((status
= ap_select(numFDs
, &read_set
, &write_set
, NULL
, &timeOut
)) < 0) {
1437 errno
= WSAGetLastError();
1439 ap_log_rerror(FCGI_LOG_ERR_ERRNO
, r
,
1440 "FastCGI: comm with server \"%s\" aborted: select() failed", fr
->fs_path
);
1441 return server_error(fr
);
1446 int stopTime
= time(NULL
) + timeOut
.tv_sec
;
1448 if (BufferLength(fr
->serverOutputBuffer
) == 0)
1452 while ((timeOut
.tv_sec
!= 0) && (time(NULL
) <= stopTime
))
1454 BOOL ok
= PeekNamedPipe((HANDLE
) fr
->fd
,NULL
, 0, NULL
, &bytesavail
, NULL
);
1457 ap_log_rerror(FCGI_LOG_ERR
, r
,
1458 "FastCGI: comm with sever \"%s\" aborted: PeekNamedPipe() failed",
1460 return server_error(fr
);
1477 if (BufferLength(fr
->clientOutputBuffer
) > 0) {
1478 doClientWrite
= TRUE
;
1480 else if (dynamic_first_read
) {
1481 struct timeval qwait
;
1483 if (fcgi_util_gettimeofday(&fr
->queueTime
) < 0) {
1484 ap_log_rerror(FCGI_LOG_ERR
, r
, "FastCGI: can't get time of day");
1485 return server_error(fr
);
1488 timersub(&fr
->queueTime
, &fr
->startTime
, &qwait
);
1490 send_to_pm(FCGI_TIMEOUT
, fr
->fs_path
, fr
->user
, fr
->group
, 0, 0);
1492 dynamic_first_read
= qwait
.tv_sec
/ dynamicPleaseStartDelay
+ 1;
1495 ap_log_rerror(FCGI_LOG_ERR_NOERRNO
, r
,
1496 "FastCGI: comm with server \"%s\" aborted: idle timeout (%d sec)",
1497 fr
->fs_path
, idle_timeout
);
1498 return server_error(fr
);
1502 #if defined(SIGPIPE) && MODULE_MAGIC_NUMBER < 19990320
1503 /* Disable Apache's SIGPIPE handler */
1504 fr
->apache_sigpipe_handler
= signal(SIGPIPE
, SIG_IGN
);
1507 /* Read from the FastCGI server */
1509 if ((fr
->using_npipe_io
1510 && (BufferFree(fr
->serverInputBuffer
) > 0)
1511 && PeekNamedPipe((HANDLE
) fr
->fd
, NULL
, 0, NULL
, &bytesavail
, NULL
)
1512 && (bytesavail
> 0))
1513 || FD_ISSET(fr
->fd
, &read_set
)) {
1515 if (FD_ISSET(fr
->fd
, &read_set
)) {
1517 if (dynamic_first_read
) {
1518 dynamic_first_read
= 0;
1519 if (fcgi_util_gettimeofday(&fr
->queueTime
) < 0) {
1520 ap_log_rerror(FCGI_LOG_ERR
, r
, "FastCGI: can't get time of day");
1521 return server_error(fr
);
1525 if ((status
= fcgi_buf_add_fd(fr
->serverInputBuffer
, fr
->fd
)) < 0) {
1527 if (! fr
->using_npipe_io
)
1528 ap_log_rerror(FCGI_LOG_ERR_ERRNO
, r
,
1529 "FastCGI: comm with server \"%s\" aborted: read failed", fr
->fs_path
);
1532 ap_log_rerror(FCGI_LOG_ERR
, r
,
1533 "FastCGI: comm with server \"%s\" aborted: read failed", fr
->fs_path
);
1534 return server_error(fr
);
1538 fr
->keepReadingFromFcgiApp
= FALSE
;
1539 close_connection_to_fs(fr
);
1543 /* Write to the FastCGI server */
1545 if ((fr
->using_npipe_io
&& (BufferLength(fr
->serverOutputBuffer
) > 0))
1546 || FD_ISSET(fr
->fd
, &write_set
)) {
1548 if (FD_ISSET(fr
->fd
, &write_set
)) {
1551 if (fcgi_buf_get_to_fd(fr
->serverOutputBuffer
, fr
->fd
) < 0) {
1553 if (! fr
->using_npipe_io
)
1554 ap_log_rerror(FCGI_LOG_ERR_ERRNO
, r
,
1555 "FastCGI: comm with server \"%s\" aborted: write failed", fr
->fs_path
);
1558 ap_log_rerror(FCGI_LOG_ERR
, r
,
1559 "FastCGI: comm with server \"%s\" aborted: write failed", fr
->fs_path
);
1560 return server_error(fr
);
1564 #if defined(SIGPIPE) && MODULE_MAGIC_NUMBER < 19990320
1565 /* Reinstall Apache's SIGPIPE handler */
1566 signal(SIGPIPE
, fr
->apache_sigpipe_handler
);
1570 doClientWrite
= TRUE
;
1573 if (fr
->role
== FCGI_RESPONDER
&& doClientWrite
) {
1575 if (write_to_client(fr
) != OK
) {
1576 #if defined(SIGPIPE) && MODULE_MAGIC_NUMBER < 19990320
1577 /* Make sure we leave with Apache's sigpipe_handler in place */
1578 if (fr
->apache_sigpipe_handler
!= NULL
)
1579 signal(SIGPIPE
, fr
->apache_sigpipe_handler
);
1581 close_connection_to_fs(fr
);
1582 ap_kill_timeout(fr
->r
);
1587 if (fcgi_protocol_dequeue(rp
, fr
) != OK
)
1588 return server_error(fr
);
1590 if (fr
->keepReadingFromFcgiApp
&& fr
->exitStatusSet
) {
1591 /* we're done talking to the fcgi app */
1592 fr
->keepReadingFromFcgiApp
= FALSE
;
1593 close_connection_to_fs(fr
);
1596 if (fr
->parseHeader
== SCAN_CGI_READING_HEADERS
) {
1597 if ((err
= process_headers(r
, fr
))) {
1598 ap_log_rerror(FCGI_LOG_ERR_NOERRNO
, r
,
1599 "FastCGI: comm with server \"%s\" aborted: error parsing headers: %s", fr
->fs_path
, err
);
1600 return server_error(fr
);
1606 switch (fr
->parseHeader
) {
1608 case SCAN_CGI_FINISHED
:
1609 if (fr
->role
== FCGI_RESPONDER
) {
1610 #ifdef RUSSIAN_APACHE
1613 ap_bflush(r
->connection
->client
);
1615 ap_bgetopt(r
->connection
->client
, BO_BYTECT
, &r
->bytes_sent
);
1619 case SCAN_CGI_READING_HEADERS
:
1620 ap_log_rerror(FCGI_LOG_ERR_NOERRNO
, r
,
1621 "FastCGI: incomplete headers (%d bytes) received from server \"%s\"",
1622 fr
->header
->nelts
, fr
->fs_path
);
1623 return server_error(fr
);
1625 case SCAN_CGI_BAD_HEADER
:
1626 return server_error(fr
);
1628 case SCAN_CGI_INT_REDIRECT
:
1629 case SCAN_CGI_SRV_REDIRECT
:
1631 * XXX We really should be soaking all client input
1632 * and all script output. See mod_cgi.c.
1633 * There's other differences we need to pick up here as well!
1634 * This has to be revisited.
1646 static fcgi_request
*create_fcgi_request(request_rec
* const r
, const char *fs_path
)
1648 struct stat
*my_finfo
;
1649 pool
* const p
= r
->pool
;
1651 fcgi_request
* const fr
= (fcgi_request
*)ap_pcalloc(p
, sizeof(fcgi_request
));
1654 my_finfo
= (struct stat
*)ap_palloc(p
, sizeof(struct stat
));
1655 if (stat(fs_path
, my_finfo
) < 0) {
1656 ap_log_rerror(FCGI_LOG_ERR_ERRNO
, r
,
1657 "FastCGI: stat() of \"%s\" failed", fs_path
);
1662 my_finfo
= &r
->finfo
;
1663 fs_path
= r
->filename
;
1666 fs
= fcgi_util_fs_get_by_id(fs_path
, r
->server
->server_uid
, r
->server
->server_gid
);
1668 /* Its a request for a dynamic FastCGI application */
1669 const char * const err
=
1670 fcgi_util_fs_is_path_ok(p
, fs_path
, my_finfo
);
1673 ap_log_rerror(FCGI_LOG_ERR_NOERRNO
, r
, "FastCGI: invalid (dynamic) server \"%s\": %s", fs_path
, err
);
1678 fr
->serverInputBuffer
= fcgi_buf_new(p
, SERVER_BUFSIZE
);
1679 fr
->serverOutputBuffer
= fcgi_buf_new(p
, SERVER_BUFSIZE
);
1680 fr
->clientInputBuffer
= fcgi_buf_new(p
, SERVER_BUFSIZE
);
1681 fr
->clientOutputBuffer
= fcgi_buf_new(p
, SERVER_BUFSIZE
);
1682 fr
->erBufPtr
= fcgi_buf_new(p
, sizeof(FCGI_EndRequestBody
) + 1);
1683 fr
->gotHeader
= FALSE
;
1684 fr
->parseHeader
= SCAN_CGI_READING_HEADERS
;
1685 fr
->header
= ap_make_array(p
, 1, 1);
1686 fr
->fs_stderr
= NULL
;
1688 fr
->readingEndRequestBody
= FALSE
;
1690 fr
->exitStatusSet
= FALSE
;
1691 fr
->requestId
= 1; /* anything but zero is OK here */
1692 fr
->eofSent
= FALSE
;
1693 fr
->role
= FCGI_RESPONDER
;
1694 fr
->expectingClientContent
= FALSE
;
1695 fr
->keepReadingFromFcgiApp
= TRUE
;
1697 fr
->fs_path
= fs_path
;
1698 fr
->authHeaders
= ap_make_table(p
, 10);
1700 fr
->fd
= INVALID_SOCKET
;
1701 fr
->dynamic
= ((fs
== NULL
) || (fs
->directive
== APP_CLASS_DYNAMIC
)) ? TRUE
: FALSE
;
1702 fr
->using_npipe_io
= FALSE
;
1704 fr
->dynamic
= (fs
== NULL
) ? TRUE
: FALSE
;
1709 set_uid_n_gid(r
, &fr
->user
, &fr
->group
);
1715 *----------------------------------------------------------------------
1719 * This routine gets called for a request that corresponds to
1720 * a FastCGI connection. It performs the request synchronously.
1723 * Final status of request: OK or NOT_FOUND or SERVER_ERROR.
1726 * Request performed.
1728 *----------------------------------------------------------------------
1731 /* Stolen from mod_cgi.c..
1732 * KLUDGE --- for back-combatibility, we don't have to check ExecCGI
1733 * in ScriptAliased directories, which means we need to know if this
1734 * request came through ScriptAlias or not... so the Alias module
1735 * leaves a note for us.
1737 static int apache_is_scriptaliased(request_rec
*r
)
1739 const char *t
= ap_table_get(r
->notes
, "alias-forced-type");
1740 return t
&& (!strcasecmp(t
, "cgi-script"));
1743 /* If a script wants to produce its own Redirect body, it now
1744 * has to explicitly *say* "Status: 302". If it wants to use
1745 * Apache redirects say "Status: 200". See process_headers().
1747 static int post_process_for_redirects(request_rec
* const r
,
1748 const fcgi_request
* const fr
)
1750 switch(fr
->parseHeader
) {
1751 case SCAN_CGI_INT_REDIRECT
:
1753 /* @@@ There are still differences between the handling in
1754 * mod_cgi and mod_fastcgi. This needs to be revisited.
1756 /* We already read the message body (if any), so don't allow
1757 * the redirected request to think it has one. We can ignore
1758 * Transfer-Encoding, since we used REQUEST_CHUNKED_ERROR.
1761 r
->method_number
= M_GET
;
1762 ap_table_unset(r
->headers_in
, "Content-length");
1764 ap_internal_redirect_handler(ap_table_get(r
->headers_out
, "Location"), r
);
1767 case SCAN_CGI_SRV_REDIRECT
:
1775 /******************************************************************************
1776 * Process fastcgi-script requests. Based on mod_cgi::cgi_handler().
1778 static int content_handler(request_rec
*r
)
1780 fcgi_request
*fr
= NULL
;
1783 /* Setup a new FastCGI request */
1784 if ((fr
= create_fcgi_request(r
, NULL
)) == NULL
)
1785 return SERVER_ERROR
;
1787 /* If its a dynamic invocation, make sure scripts are OK here */
1788 if (fr
->dynamic
&& !(ap_allow_options(r
) & OPT_EXECCGI
) && !apache_is_scriptaliased(r
)) {
1789 ap_log_rerror(FCGI_LOG_ERR_NOERRNO
, r
,
1790 "FastCGI: \"ExecCGI Option\" is off in this directory: %s", r
->uri
);
1791 return SERVER_ERROR
;
1794 /* Process the fastcgi-script request */
1795 if ((ret
= do_work(r
, fr
)) != OK
)
1798 /* Special case redirects */
1799 return post_process_for_redirects(r
, fr
);
1803 static int post_process_auth_passed_header(table
*t
, const char *key
, const char * const val
)
1805 if (strncasecmp(key
, "Variable-", 9) == 0)
1808 ap_table_setn(t
, key
, val
);
1812 static int post_process_auth_passed_compat_header(table
*t
, const char *key
, const char * const val
)
1814 if (strncasecmp(key
, "Variable-", 9) == 0)
1815 ap_table_setn(t
, key
+ 9, val
);
1820 static int post_process_auth_failed_header(table
* const t
, const char * const key
, const char * const val
)
1822 ap_table_setn(t
, key
, val
);
1826 static void post_process_auth(fcgi_request
* const fr
, const int passed
)
1828 request_rec
* const r
= fr
->r
;
1830 /* Restore the saved subprocess_env because we muddied ours up */
1831 r
->subprocess_env
= fr
->saved_subprocess_env
;
1834 if (fr
->auth_compat
) {
1835 ap_table_do((int (*)(void *, const char *, const char *))post_process_auth_passed_compat_header
,
1836 (void *)r
->subprocess_env
, fr
->authHeaders
, NULL
);
1839 ap_table_do((int (*)(void *, const char *, const char *))post_process_auth_passed_header
,
1840 (void *)r
->subprocess_env
, fr
->authHeaders
, NULL
);
1844 ap_table_do((int (*)(void *, const char *, const char *))post_process_auth_failed_header
,
1845 (void *)r
->err_headers_out
, fr
->authHeaders
, NULL
);
1848 /* @@@ Restore these.. its a hack until I rewrite the header handling */
1849 r
->status
= HTTP_OK
;
1850 r
->status_line
= NULL
;
1853 static int check_user_authentication(request_rec
*r
)
1855 int res
, authenticated
= 0;
1856 const char *password
;
1858 const fcgi_dir_config
* const dir_config
=
1859 (const fcgi_dir_config
*)ap_get_module_config(r
->per_dir_config
, &fastcgi_module
);
1861 if (dir_config
->authenticator
== NULL
)
1864 /* Get the user password */
1865 if ((res
= ap_get_basic_auth_pw(r
, &password
)) != OK
)
1868 if ((fr
= create_fcgi_request(r
, dir_config
->authenticator
)) == NULL
)
1869 return SERVER_ERROR
;
1871 /* Save the existing subprocess_env, because we're gonna muddy it up */
1872 fr
->saved_subprocess_env
= ap_copy_table(r
->pool
, r
->subprocess_env
);
1874 ap_table_setn(r
->subprocess_env
, "REMOTE_PASSWD", password
);
1875 ap_table_setn(r
->subprocess_env
, "FCGI_APACHE_ROLE", "AUTHENTICATOR");
1877 /* The FastCGI Protocol doesn't differentiate authentication */
1878 fr
->role
= FCGI_AUTHORIZER
;
1880 /* Do we need compatibility mode? */
1881 fr
->auth_compat
= (dir_config
->authenticator_options
& FCGI_COMPAT
);
1883 if ((res
= do_work(r
, fr
)) != OK
)
1884 goto AuthenticationFailed
;
1886 authenticated
= (r
->status
== 200);
1887 post_process_auth(fr
, authenticated
);
1889 /* A redirect shouldn't be allowed during the authentication phase */
1890 if (ap_table_get(r
->headers_out
, "Location") != NULL
) {
1891 ap_log_rerror(FCGI_LOG_ERR_NOERRNO
, r
,
1892 "FastCGI: FastCgiAuthenticator \"%s\" redirected (not allowed)",
1893 dir_config
->authenticator
);
1894 goto AuthenticationFailed
;
1900 AuthenticationFailed
:
1901 if (!(dir_config
->authenticator_options
& FCGI_AUTHORITATIVE
))
1904 /* @@@ Probably should support custom_responses */
1905 ap_note_basic_auth_failure(r
);
1906 ap_log_rerror(FCGI_LOG_ERR_NOERRNO
, r
,
1907 "FastCGI: authentication failed for user \"%s\": %s", r
->connection
->user
, r
->uri
);
1908 return (res
== OK
) ? AUTH_REQUIRED
: res
;
1911 static int check_user_authorization(request_rec
*r
)
1913 int res
, authorized
= 0;
1915 const fcgi_dir_config
* const dir_config
=
1916 (const fcgi_dir_config
*)ap_get_module_config(r
->per_dir_config
, &fastcgi_module
);
1918 if (dir_config
->authorizer
== NULL
)
1921 /* @@@ We should probably honor the existing parameters to the require directive
1922 * as well as allow the definition of new ones (or use the basename of the
1923 * FastCGI server and pass the rest of the directive line), but for now keep
1926 if ((fr
= create_fcgi_request(r
, dir_config
->authorizer
)) == NULL
)
1927 return SERVER_ERROR
;
1929 /* Save the existing subprocess_env, because we're gonna muddy it up */
1930 fr
->saved_subprocess_env
= ap_copy_table(r
->pool
, r
->subprocess_env
);
1932 ap_table_setn(r
->subprocess_env
, "FCGI_APACHE_ROLE", "AUTHORIZER");
1934 fr
->role
= FCGI_AUTHORIZER
;
1936 /* Do we need compatibility mode? */
1937 fr
->auth_compat
= (dir_config
->authenticator_options
& FCGI_COMPAT
);
1939 if ((res
= do_work(r
, fr
)) != OK
)
1940 goto AuthorizationFailed
;
1942 authorized
= (r
->status
== 200);
1943 post_process_auth(fr
, authorized
);
1945 /* A redirect shouldn't be allowed during the authorization phase */
1946 if (ap_table_get(r
->headers_out
, "Location") != NULL
) {
1947 ap_log_rerror(FCGI_LOG_ERR_NOERRNO
, r
,
1948 "FastCGI: FastCgiAuthorizer \"%s\" redirected (not allowed)",
1949 dir_config
->authorizer
);
1950 goto AuthorizationFailed
;
1956 AuthorizationFailed
:
1957 if (!(dir_config
->authorizer_options
& FCGI_AUTHORITATIVE
))
1960 /* @@@ Probably should support custom_responses */
1961 ap_note_basic_auth_failure(r
);
1962 ap_log_rerror(FCGI_LOG_ERR_NOERRNO
, r
,
1963 "FastCGI: authorization failed for user \"%s\": %s", r
->connection
->user
, r
->uri
);
1964 return (res
== OK
) ? AUTH_REQUIRED
: res
;
1967 static int check_access(request_rec
*r
)
1969 int res
, access_allowed
= 0;
1971 const fcgi_dir_config
* const dir_config
=
1972 (fcgi_dir_config
*)ap_get_module_config(r
->per_dir_config
, &fastcgi_module
);
1974 if (dir_config
== NULL
|| dir_config
->access_checker
== NULL
)
1977 if ((fr
= create_fcgi_request(r
, dir_config
->access_checker
)) == NULL
)
1978 return SERVER_ERROR
;
1980 /* Save the existing subprocess_env, because we're gonna muddy it up */
1981 fr
->saved_subprocess_env
= ap_copy_table(r
->pool
, r
->subprocess_env
);
1983 ap_table_setn(r
->subprocess_env
, "FCGI_APACHE_ROLE", "ACCESS_CHECKER");
1985 /* The FastCGI Protocol doesn't differentiate access control */
1986 fr
->role
= FCGI_AUTHORIZER
;
1988 /* Do we need compatibility mode? */
1989 fr
->auth_compat
= (dir_config
->authenticator_options
& FCGI_COMPAT
);
1991 if ((res
= do_work(r
, fr
)) != OK
)
1994 access_allowed
= (r
->status
== 200);
1995 post_process_auth(fr
, access_allowed
);
1997 /* A redirect shouldn't be allowed during the access check phase */
1998 if (ap_table_get(r
->headers_out
, "Location") != NULL
) {
1999 ap_log_rerror(FCGI_LOG_ERR_NOERRNO
, r
,
2000 "FastCGI: FastCgiAccessChecker \"%s\" redirected (not allowed)",
2001 dir_config
->access_checker
);
2009 if (!(dir_config
->access_checker_options
& FCGI_AUTHORITATIVE
))
2012 /* @@@ Probably should support custom_responses */
2013 ap_log_rerror(FCGI_LOG_ERR_NOERRNO
, r
, "FastCGI: access denied: %s", r
->uri
);
2014 return (res
== OK
) ? FORBIDDEN
: res
;
2017 command_rec fastcgi_cmds
[] = {
2018 { "AppClass", fcgi_config_new_static_server
, NULL
, RSRC_CONF
, RAW_ARGS
, NULL
},
2019 { "FastCgiServer", fcgi_config_new_static_server
, NULL
, RSRC_CONF
, RAW_ARGS
, NULL
},
2021 { "ExternalAppClass", fcgi_config_new_external_server
, NULL
, RSRC_CONF
, RAW_ARGS
, NULL
},
2022 { "FastCgiExternalServer", fcgi_config_new_external_server
, NULL
, RSRC_CONF
, RAW_ARGS
, NULL
},
2024 { "FastCgiIpcDir", fcgi_config_set_socket_dir
, NULL
, RSRC_CONF
, TAKE1
, NULL
},
2026 { "FastCgiSuexec", fcgi_config_set_wrapper
, NULL
, RSRC_CONF
, TAKE1
, NULL
},
2027 { "FastCgiWrapper", fcgi_config_set_wrapper
, NULL
, RSRC_CONF
, TAKE1
, NULL
},
2029 { "FCGIConfig", fcgi_config_set_config
, NULL
, RSRC_CONF
, RAW_ARGS
, NULL
},
2030 { "FastCgiConfig", fcgi_config_set_config
, NULL
, RSRC_CONF
, RAW_ARGS
, NULL
},
2032 { "FastCgiAuthenticator", fcgi_config_new_auth_server
,
2033 (void *)FCGI_AUTH_TYPE_AUTHENTICATOR
, ACCESS_CONF
, TAKE12
,
2034 "a fastcgi-script path (absolute or relative to ServerRoot) followed by an optional -compat" },
2035 { "FastCgiAuthenticatorAuthoritative", fcgi_config_set_authoritative_slot
,
2036 (void *)XtOffsetOf(fcgi_dir_config
, authenticator_options
), ACCESS_CONF
, FLAG
,
2037 "Set to 'off' to allow authentication to be passed along to lower modules upon failure" },
2039 { "FastCgiAuthorizer", fcgi_config_new_auth_server
,
2040 (void *)FCGI_AUTH_TYPE_AUTHORIZER
, ACCESS_CONF
, TAKE12
,
2041 "a fastcgi-script path (absolute or relative to ServerRoot) followed by an optional -compat" },
2042 { "FastCgiAuthorizerAuthoritative", fcgi_config_set_authoritative_slot
,
2043 (void *)XtOffsetOf(fcgi_dir_config
, authorizer_options
), ACCESS_CONF
, FLAG
,
2044 "Set to 'off' to allow authorization to be passed along to lower modules upon failure" },
2046 { "FastCgiAccessChecker", fcgi_config_new_auth_server
,
2047 (void *)FCGI_AUTH_TYPE_ACCESS_CHECKER
, ACCESS_CONF
, TAKE12
,
2048 "a fastcgi-script path (absolute or relative to ServerRoot) followed by an optional -compat" },
2049 { "FastCgiAccessCheckerAuthoritative", fcgi_config_set_authoritative_slot
,
2050 (void *)XtOffsetOf(fcgi_dir_config
, access_checker_options
), ACCESS_CONF
, FLAG
,
2051 "Set to 'off' to allow access control to be passed along to lower modules upon failure" },
2056 handler_rec fastcgi_handlers
[] = {
2057 { FCGI_MAGIC_TYPE
, content_handler
},
2058 { "fastcgi-script", content_handler
},
2063 module MODULE_VAR_EXPORT fastcgi_module
= {
2064 STANDARD_MODULE_STUFF
,
2065 init_module
, /* initializer */
2066 fcgi_config_create_dir_config
, /* per-dir config creator */
2067 NULL
, /* per-dir config merger (default: override) */
2068 NULL
, /* per-server config creator */
2069 NULL
, /* per-server config merger (default: override) */
2070 fastcgi_cmds
, /* command table */
2071 fastcgi_handlers
, /* [9] content handlers */
2072 NULL
, /* [2] URI-to-filename translation */
2073 check_user_authentication
, /* [5] authenticate user_id */
2074 check_user_authorization
, /* [6] authorize user_id */
2075 check_access
, /* [4] check access (based on src & http headers) */
2076 NULL
, /* [7] check/set MIME type */
2077 NULL
, /* [8] fixups */
2078 NULL
, /* [10] logger */
2079 NULL
, /* [3] header-parser */
2080 fcgi_child_init
, /* process initialization */
2081 fcgi_child_exit
, /* process exit/cleanup */
2082 NULL
/* [1] post read-request handling */