4 * Apache server module for FastCGI.
6 * $Id: mod_fastcgi.c,v 1.114 2001/05/03 22:11:57 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 */
101 char *fcgi_dynamic_dir
= NULL
; /* directory for the dynamic
102 * fastcgi apps' sockets */
106 #pragma warning( disable : 4706 4100 4127)
107 fcgi_pm_job
*fcgi_dynamic_mbox
= NULL
;
108 HANDLE
*fcgi_dynamic_mbox_mutex
= NULL
;
109 HANDLE fcgi_pm_thread
= INVALID_HANDLE_VALUE
;
113 int fcgi_pm_pipe
[2] = { -1, -1 };
114 pid_t fcgi_pm_pid
= -1;
118 char *fcgi_empty_env
= NULL
;
120 u_int dynamicMaxProcs
= FCGI_DEFAULT_MAX_PROCS
;
121 int dynamicMinProcs
= FCGI_DEFAULT_MIN_PROCS
;
122 int dynamicMaxClassProcs
= FCGI_DEFAULT_MAX_CLASS_PROCS
;
123 u_int dynamicKillInterval
= FCGI_DEFAULT_KILL_INTERVAL
;
124 u_int dynamicUpdateInterval
= FCGI_DEFAULT_UPDATE_INTERVAL
;
125 float dynamicGain
= FCGI_DEFAULT_GAIN
;
126 int dynamicThreshold1
= FCGI_DEFAULT_THRESHOLD_1
;
127 int dynamicThresholdN
= FCGI_DEFAULT_THRESHOLD_N
;
128 u_int dynamicPleaseStartDelay
= FCGI_DEFAULT_START_PROCESS_DELAY
;
129 u_int dynamicAppConnectTimeout
= FCGI_DEFAULT_APP_CONN_TIMEOUT
;
130 char **dynamicEnvp
= &fcgi_empty_env
;
131 u_int dynamicProcessSlack
= FCGI_DEFAULT_PROCESS_SLACK
;
132 int dynamicAutoRestart
= FCGI_DEFAULT_RESTART_DYNAMIC
;
133 int dynamicAutoUpdate
= FCGI_DEFAULT_AUTOUPDATE
;
134 u_int dynamicListenQueueDepth
= FCGI_DEFAULT_LISTEN_Q
;
135 u_int dynamicInitStartDelay
= DEFAULT_INIT_START_DELAY
;
136 u_int dynamicRestartDelay
= FCGI_DEFAULT_RESTART_DELAY
;
137 array_header
*dynamic_pass_headers
= NULL
;
138 u_int dynamic_idle_timeout
= FCGI_DEFAULT_IDLE_TIMEOUT
;
140 /*******************************************************************************
141 * Construct a message and write it to the pm_pipe.
143 static void send_to_pm(const char id
, const char * const fs_path
,
144 const char *user
, const char * const group
, const unsigned long q_usec
,
145 const unsigned long req_usec
)
148 fcgi_pm_job
*job
= NULL
;
150 if (!(job
= (fcgi_pm_job
*) malloc(sizeof(fcgi_pm_job
))))
154 char buf
[FCGI_MAX_MSG_LEN
];
157 if (strlen(fs_path
) > FCGI_MAXPATH
) {
158 ap_log_error(FCGI_LOG_ERR_NOERRNO
, fcgi_apache_main_server
,
159 "FastCGI: the path \"%s\" is too long (>%d) for a dynamic server", fs_path
, FCGI_MAXPATH
);
165 case FCGI_SERVER_START_JOB
:
168 job
->fs_path
= strdup(fs_path
);
169 job
->user
= strdup(user
);
170 job
->group
= strdup(group
);
172 job
->start_time
= 0L;
174 buflen
= sprintf(buf
, "%c %s %s %s*", id
, fs_path
, user
, group
);
178 case FCGI_REQUEST_TIMEOUT_JOB
:
181 job
->fs_path
= strdup(fs_path
);
182 job
->user
= strdup(user
);
183 job
->group
= strdup(group
);
185 job
->start_time
= 0L;
187 buflen
= sprintf(buf
, "%c %s %s %s*", id
, fs_path
, user
, group
);
191 case FCGI_REQUEST_COMPLETE_JOB
:
194 job
->fs_path
= strdup(fs_path
);
196 job
->start_time
= req_usec
;
197 job
->user
= strdup(user
);
198 job
->group
= strdup(group
);
200 buflen
= sprintf(buf
, "%c %s %s %s %lu %lu*", id
, fs_path
, user
, group
, q_usec
, req_usec
);
206 if (fcgi_pm_add_job(job
) == 0)
209 SetEvent(fcgi_event_handles
[MBOX_EVENT
]);
211 ap_assert(buflen
<= FCGI_MAX_MSG_LEN
);
213 if (write(fcgi_pm_pipe
[1], (const void *)buf
, buflen
) != buflen
) {
214 ap_log_error(FCGI_LOG_WARN
, fcgi_apache_main_server
,
215 "FastCGI: write() to PM failed");
221 *----------------------------------------------------------------------
225 * An Apache module initializer, called by the Apache core
226 * after reading the server config.
228 * Start the process manager no matter what, since there may be a
229 * request for dynamic FastCGI applications without any being
230 * configured as static applications. Also, check for the existence
231 * and create if necessary a subdirectory into which all dynamic
234 *----------------------------------------------------------------------
236 static void init_module(server_rec
*s
, pool
*p
)
240 /* Register to reset to default values when the config pool is cleaned */
242 ap_register_cleanup(p
, NULL
, fcgi_config_reset_globals
, ap_null_cleanup
);
245 ap_add_version_component("mod_fastcgi/" MOD_FASTCGI_VERSION
);
247 fcgi_config_set_fcgi_uid_n_gid(1);
249 /* keep these handy */
250 fcgi_config_pool
= p
;
251 fcgi_apache_main_server
= s
;
254 /* Create Unix/Domain socket directory */
255 if ((err
= fcgi_config_make_dir(p
, fcgi_socket_dir
)))
256 ap_log_error(FCGI_LOG_ERR
, s
, "FastCGI: %s", err
);
259 /* Create Dynamic directory */
260 if ((err
= fcgi_config_make_dynamic_dir(p
, 1)))
261 ap_log_error(FCGI_LOG_ERR
, s
, "FastCGI: %s", err
);
264 /* Spawn the PM only once. Under Unix, Apache calls init() routines
265 * twice, once before detach() and once after. Win32 doesn't detach.
266 * Under DSO, DSO modules are unloaded between the two init() calls.
267 * Under Unix, the -X switch causes two calls to init() but no detach
268 * (but all subprocesses are wacked so the PM is toasted anyway)! */
270 if (ap_standalone
&& getppid() != 1)
273 /* Create the pipe for comm with the PM */
274 if (pipe(fcgi_pm_pipe
) < 0) {
275 ap_log_error(FCGI_LOG_ERR
, s
, "FastCGI: pipe() failed");
278 /* Start the Process Manager */
279 fcgi_pm_pid
= ap_spawn_child(p
, fcgi_pm_main
, NULL
, kill_only_once
, NULL
, NULL
, NULL
);
280 if (fcgi_pm_pid
<= 0) {
281 ap_log_error(FCGI_LOG_ALERT
, s
,
282 "FastCGI: can't start the process manager, spawn_child() failed");
285 close(fcgi_pm_pipe
[0]);
289 static void fcgi_child_init(server_rec
*dc0
, pool
*dc1
)
292 /* Create the Event Handlers */
293 fcgi_event_handles
[0] = CreateEvent(NULL
, FALSE
, FALSE
, NULL
);
294 fcgi_event_handles
[1] = CreateEvent(NULL
, FALSE
, FALSE
, NULL
);
295 fcgi_event_handles
[2] = CreateEvent(NULL
, FALSE
, FALSE
, NULL
);
296 fcgi_dynamic_mbox_mutex
= ap_create_mutex("fcgi_dynamic_mbox_mutex");
298 /* Spawn of the process manager thread */
299 fcgi_pm_thread
= CreateThread(NULL
, 0, (LPTHREAD_START_ROUTINE
)fcgi_pm_main
, NULL
, 0, NULL
);
304 static void fcgi_child_exit(server_rec
*dc0
, pool
*dc1
)
307 /* Signaling the PM thread tp exit*/
308 SetEvent(fcgi_event_handles
[TERM_EVENT
]);
310 /* Waiting on pm thread to exit */
311 WaitForSingleObject(fcgi_pm_thread
, INFINITE
);
318 *----------------------------------------------------------------------
322 * Terminate a line: scan to the next newline, scan back to the
323 * first non-space character and store a terminating zero. Return
324 * the next character past the end of the newline.
326 * If the end of the string is reached, ASSERT!
328 * If the FIRST character(s) in the line are '\n' or "\r\n", the
329 * first character is replaced with a NULL and next character
330 * past the newline is returned. NOTE: this condition supercedes
331 * the processing of RFC-822 continuation lines.
333 * If continuation is set to 'TRUE', then it parses a (possible)
334 * sequence of RFC-822 continuation lines.
340 * Termination byte stored in string.
342 *----------------------------------------------------------------------
344 static char *get_header_line(char *start
, int continuation
)
349 if(p
[0] == '\r' && p
[1] == '\n') { /* If EOL in 1st 2 chars */
350 p
++; /* point to \n and stop */
351 } else if(*p
!= '\n') {
354 if(*p
== '\n' && p
[1] != ' ' && p
[1] != '\t')
359 while(*p
!= '\0' && *p
!= '\n') {
365 ap_assert(*p
!= '\0');
370 * Trim any trailing whitespace.
372 while(isspace((unsigned char)p
[-1]) && p
> start
) {
381 *----------------------------------------------------------------------
385 * Call with r->parseHeader == SCAN_CGI_READING_HEADERS
386 * and initial script output in fr->header.
388 * If the initial script output does not include the header
389 * terminator ("\r\n\r\n") process_headers returns with no side
390 * effects, to be called again when more script output
391 * has been appended to fr->header.
393 * If the initial script output includes the header terminator,
394 * process_headers parses the headers and determines whether or
395 * not the remaining script output will be sent to the client.
396 * If so, process_headers sends the HTTP response headers to the
397 * client and copies any non-header script output to the output
404 * May set r->parseHeader to:
405 * SCAN_CGI_FINISHED -- headers parsed, returning script response
406 * SCAN_CGI_BAD_HEADER -- malformed header from script
407 * SCAN_CGI_INT_REDIRECT -- handler should perform internal redirect
408 * SCAN_CGI_SRV_REDIRECT -- handler should return REDIRECT
410 *----------------------------------------------------------------------
413 static const char *process_headers(request_rec
*r
, fcgi_request
*fr
)
415 char *p
, *next
, *name
, *value
;
417 int hasContentType
, hasStatus
, hasLocation
;
419 ap_assert(fr
->parseHeader
== SCAN_CGI_READING_HEADERS
);
421 if (fr
->header
== NULL
)
425 * Do we have the entire header? Scan for the blank line that
426 * terminates the header.
428 p
= (char *)fr
->header
->elts
;
429 len
= fr
->header
->nelts
;
431 while(len
-- && flag
< 2) {
441 name
= "Invalid Character";
451 /* Return (to be called later when we have more data)
452 * if we don't have an entire header. */
457 * Parse all the headers.
459 fr
->parseHeader
= SCAN_CGI_FINISHED
;
460 hasContentType
= hasStatus
= hasLocation
= FALSE
;
461 next
= (char *)fr
->header
->elts
;
463 next
= get_header_line(name
= next
, TRUE
);
467 if ((p
= strchr(name
, ':')) == NULL
) {
471 while (p
!= name
&& isspace((unsigned char)*(p
- 1))) {
478 if (strpbrk(name
, " \t") != NULL
) {
482 while (isspace((unsigned char)*value
)) {
486 if (strcasecmp(name
, "Status") == 0) {
487 int statusValue
= strtol(value
, NULL
, 10);
490 goto DuplicateNotAllowed
;
492 if (statusValue
< 0) {
493 fr
->parseHeader
= SCAN_CGI_BAD_HEADER
;
494 return ap_psprintf(r
->pool
, "invalid Status '%s'", value
);
497 r
->status
= statusValue
;
498 r
->status_line
= ap_pstrdup(r
->pool
, value
);
502 if (fr
->role
== FCGI_RESPONDER
) {
503 if (strcasecmp(name
, "Content-type") == 0) {
504 if (hasContentType
) {
505 goto DuplicateNotAllowed
;
507 hasContentType
= TRUE
;
508 r
->content_type
= ap_pstrdup(r
->pool
, value
);
512 if (strcasecmp(name
, "Location") == 0) {
514 goto DuplicateNotAllowed
;
517 ap_table_set(r
->headers_out
, "Location", value
);
521 /* If the script wants them merged, it can do it */
522 ap_table_add(r
->err_headers_out
, name
, value
);
526 ap_table_add(fr
->authHeaders
, name
, value
);
530 if (fr
->role
!= FCGI_RESPONDER
)
534 * Who responds, this handler or Apache?
537 const char *location
= ap_table_get(r
->headers_out
, "Location");
539 * Based on internal redirect handling in mod_cgi.c...
541 * If a script wants to produce its own Redirect
542 * body, it now has to explicitly *say* "Status: 302"
544 if (r
->status
== 200) {
545 if(location
[0] == '/') {
547 * Location is an relative path. This handler will
548 * consume all script output, then have Apache perform an
551 fr
->parseHeader
= SCAN_CGI_INT_REDIRECT
;
555 * Location is an absolute URL. If the script didn't
556 * produce a Content-type header, this handler will
557 * consume all script output and then have Apache generate
558 * its standard redirect response. Otherwise this handler
559 * will transmit the script's response.
561 fr
->parseHeader
= SCAN_CGI_SRV_REDIRECT
;
567 * We're responding. Send headers, buffer excess script output.
569 ap_send_http_header(r
);
571 /* We need to reinstate our timeout, send_http_header() kill()s it */
572 ap_hard_timeout("FastCGI request processing", r
);
577 len
= fr
->header
->nelts
- (next
- fr
->header
->elts
);
579 ap_assert(BufferLength(fr
->clientOutputBuffer
) == 0);
580 if (BufferFree(fr
->clientOutputBuffer
) < len
) {
581 fr
->clientOutputBuffer
= fcgi_buf_new(r
->pool
, len
);
583 ap_assert(BufferFree(fr
->clientOutputBuffer
) >= len
);
585 int sent
= fcgi_buf_add_block(fr
->clientOutputBuffer
, next
, len
);
586 ap_assert(sent
== len
);
591 /* Log first line of a multi-line header */
592 if ((p
= strpbrk(name
, "\r\n")) != NULL
)
594 fr
->parseHeader
= SCAN_CGI_BAD_HEADER
;
595 return ap_psprintf(r
->pool
, "malformed header '%s'", name
);
598 fr
->parseHeader
= SCAN_CGI_BAD_HEADER
;
599 return ap_psprintf(r
->pool
, "duplicate header '%s'", name
);
603 * Read from the client filling both the FastCGI server buffer and the
604 * client buffer with the hopes of buffering the client data before
605 * making the connect() to the FastCGI server. This prevents slow
606 * clients from keeping the FastCGI server in processing longer than is
609 static int read_from_client_n_queue(fcgi_request
*fr
)
615 while (BufferFree(fr
->clientInputBuffer
) > 0 || BufferFree(fr
->serverOutputBuffer
) > 0) {
616 fcgi_protocol_queue_client_buffer(fr
);
618 if (fr
->expectingClientContent
<= 0)
621 fcgi_buf_get_free_block_info(fr
->clientInputBuffer
, &end
, &count
);
625 if ((countRead
= ap_get_client_block(fr
->r
, end
, count
)) < 0)
628 if (countRead
== 0) {
629 fr
->expectingClientContent
= 0;
632 fcgi_buf_add_update(fr
->clientInputBuffer
, countRead
);
633 ap_reset_timeout(fr
->r
);
639 static int write_to_client(fcgi_request
*fr
)
644 fcgi_buf_get_block_info(fr
->clientOutputBuffer
, &begin
, &count
);
648 /* If fewer than count bytes are written, an error occured.
649 * ap_bwrite() typically forces a flushed write to the client, this
650 * effectively results in a block (and short packets) - it should
651 * be fixed, but I didn't win much support for the idea on new-httpd.
652 * So, without patching Apache, the best way to deal with this is
653 * to size the fcgi_bufs to hold all of the script output (within
654 * reason) so the script can be released from having to wait around
655 * for the transmission to the client to complete. */
656 #ifdef RUSSIAN_APACHE
657 if (ap_rwrite(begin
, count
, fr
->r
) != count
) {
658 ap_log_rerror(FCGI_LOG_INFO_NOERRNO
, fr
->r
,
659 "FastCGI: client stopped connection before send body completed");
663 if (ap_bwrite(fr
->r
->connection
->client
, begin
, count
) != (int) count
) {
664 ap_log_rerror(FCGI_LOG_INFO_NOERRNO
, fr
->r
,
665 "FastCGI: client stopped connection before send body completed");
670 ap_reset_timeout(fr
->r
);
672 /* Don't bother with a wrapped buffer, limiting exposure to slow
673 * clients. The BUFF routines don't allow a writev from above,
674 * and don't always memcpy to minimize small write()s, this should
675 * be fixed, but I didn't win much support for the idea on
676 * new-httpd - I'll have to _prove_ its a problem first.. */
678 /* The default behaviour used to be to flush with every write, but this
679 * can tie up the FastCGI server longer than is necessary so its an option now */
680 if (fr
->fs
&& fr
->fs
->flush
) {
681 #ifdef RUSSIAN_APACHE
682 if (ap_rflush(fr
->r
)) {
683 ap_log_rerror(FCGI_LOG_INFO_NOERRNO
, fr
->r
,
684 "FastCGI: client stopped connection before send body completed");
688 if (ap_bflush(fr
->r
->connection
->client
)) {
689 ap_log_rerror(FCGI_LOG_INFO_NOERRNO
, fr
->r
,
690 "FastCGI: client stopped connection before send body completed");
694 ap_reset_timeout(fr
->r
);
697 fcgi_buf_toss(fr
->clientOutputBuffer
, count
);
701 /*******************************************************************************
702 * Determine the user and group the wrapper should be called with.
703 * Based on code in Apache's create_argv_cmd() (util_script.c).
705 static void set_uid_n_gid(request_rec
*r
, const char **user
, const char **group
)
707 if (fcgi_wrapper
== NULL
) {
713 if (strncmp("/~", r
->uri
, 2) == 0) {
714 /* its a user dir uri, just send the ~user, and leave it to the PM */
715 char *end
= strchr(r
->uri
+ 2, '/');
718 *user
= memcpy(ap_pcalloc(r
->pool
, end
- r
->uri
), r
->uri
+ 1, end
- r
->uri
- 1);
720 *user
= ap_pstrdup(r
->pool
, r
->uri
+ 1);
724 *user
= ap_psprintf(r
->pool
, "%ld", (long)r
->server
->server_uid
);
725 *group
= ap_psprintf(r
->pool
, "%ld", (long)r
->server
->server_gid
);
729 /*******************************************************************************
730 * Close the connection to the FastCGI server. This is normally called by
731 * do_work(), but may also be called as in request pool cleanup.
733 static void close_connection_to_fs(fcgi_request
*fr
)
735 pool
*rp
= fr
->r
->pool
;
738 ap_pclosesocket(rp
, fr
->fd
);
743 if (fr
->keepReadingFromFcgiApp
== FALSE
) {
744 /* XXX FCGI_REQUEST_COMPLETE_JOB is only sent for requests which complete
745 * normally WRT the fcgi app. There is no data sent for
746 * connect() timeouts or requests which complete abnormally.
747 * KillDynamicProcs() and RemoveRecords() need to be looked at
748 * to be sure they can reasonably handle these cases before
749 * sending these sort of stats - theres some funk in there.
750 * XXX We should do something special when this a pool cleanup.
752 if (fcgi_util_gettimeofday(&fr
->completeTime
) < 0) {
753 /* there's no point to aborting the request, just log it */
754 ap_log_error(FCGI_LOG_ERR
, fr
->r
->server
, "FastCGI: can't get time of day");
756 struct timeval qtime
, rtime
;
758 timersub(&fr
->queueTime
, &fr
->startTime
, &qtime
);
759 timersub(&fr
->completeTime
, &fr
->queueTime
, &rtime
);
761 send_to_pm(FCGI_REQUEST_COMPLETE_JOB
, fr
->fs_path
,
763 qtime
.tv_sec
* 1000000 + qtime
.tv_usec
,
764 rtime
.tv_sec
* 1000000 + rtime
.tv_usec
);
772 static int set_nonblocking(SOCKET fd
, int nonblocking
)
774 unsigned long ioctl_arg
= (nonblocking
) ? 1 : 0;
775 return ioctlsocket(fd
, FIONBIO
, &ioctl_arg
);
780 static int set_nonblocking(int fd
, int nonblocking
)
783 int fd_flags
= fcntl(fd
, F_GETFL
, 0);
785 if (fd_flags
< 0) return -1;
787 #if defined(O_NONBLOCK)
788 nb_flag
= O_NONBLOCK
;
789 #elif defined(O_NDELAY)
791 #elif defined(FNDELAY)
794 #error "TODO - don't read from app until all data from client is posted."
797 fd_flags
= (nonblocking
) ? (fd_flags
| nb_flag
) : (fd_flags
& ~nb_flag
);
799 return fcntl(fd
, F_SETFL
, fd_flags
);
804 /*******************************************************************************
805 * Connect to the FastCGI server.
807 static int open_connection_to_fs(fcgi_request
*fr
)
810 fd_set write_fds
, read_fds
;
812 request_rec
* const r
= fr
->r
;
813 pool
* const rp
= r
->pool
;
814 const char *socket_path
= NULL
;
815 struct sockaddr
*socket_addr
= NULL
;
816 int socket_addr_len
= 0;
818 const char *err
= NULL
;
821 /* Create the connection point */
824 socket_path
= fcgi_util_socket_hash_filename(rp
, fr
->fs_path
, fr
->user
, fr
->group
);
825 socket_path
= fcgi_util_socket_make_path_absolute(rp
, socket_path
, 1);
828 err
= fcgi_util_socket_make_domain_addr(rp
, (struct sockaddr_un
**)&socket_addr
,
829 &socket_addr_len
, socket_path
);
831 ap_log_rerror(FCGI_LOG_ERR
, r
,
832 "FastCGI: failed to connect to server \"%s\": "
833 "%s", fr
->fs_path
, err
);
841 if (fr
->fs
->dest_addr
!= NULL
) {
842 socket_addr
= fr
->fs
->dest_addr
;
844 else if (fr
->fs
->socket_addr
) {
845 socket_addr
= fr
->fs
->socket_addr
;
848 socket_path
= fr
->fs
->socket_path
;
851 socket_addr
= fr
->fs
->socket_addr
;
853 socket_addr_len
= fr
->fs
->socket_addr_len
;
859 if (fr
->fs
&& fr
->fs
->restartTime
)
861 struct stat sock_stat
;
863 if (stat(socket_path
, &sock_stat
) == 0)
867 if (dynamicAutoUpdate
)
869 struct stat app_stat
;
871 /* TODO: follow sym links */
873 if (stat(fr
->fs_path
, &app_stat
) == 0)
876 if (fr
->fs
->restartTime
< app_stat
.st_mtime
)
878 if (sock_stat
.st_mtime
< app_stat
.st_mtime
)
882 struct timeval tv
= {1, 0};
885 * There's a newer one, request a restart.
887 send_to_pm(FCGI_SERVER_RESTART_JOB
, fr
->fs_path
, fr
->user
, fr
->group
, 0, 0);
892 /* Avoid sleep/alarm interactions */
893 ap_select(0, NULL
, NULL
, NULL
, &tv
);
901 send_to_pm(FCGI_SERVER_START_JOB
, fr
->fs_path
, fr
->user
, fr
->group
, 0, 0);
903 /* Wait until it looks like its running */
910 fr
->fs
= fcgi_util_fs_get_by_id(fr
->fs_path
, 0, 0);
912 if (fr
->fs
&& fr
->fs
->restartTime
)
914 struct timeval tv
= {1, 0};
916 /* Avoid sleep/alarm interactions */
917 ap_select(0, NULL
, NULL
, NULL
, &tv
);
919 if (stat(socket_path
, &sock_stat
) == 0)
935 int max_connect_time
= FCGI_NAMED_PIPE_CONNECT_TIMEOUT
;
937 fr
->using_npipe_io
= TRUE
;
941 interval
= dynamicPleaseStartDelay
* 1000;
943 if (dynamicAppConnectTimeout
) {
944 max_connect_time
= dynamicAppConnectTimeout
;
949 interval
= FCGI_NAMED_PIPE_CONNECT_TIMEOUT
* 1000;
951 if (fr
->fs
->appConnectTimeout
) {
952 max_connect_time
= fr
->fs
->appConnectTimeout
;
956 if (fcgi_util_gettimeofday(&fr
->startTime
) < 0) {
957 ap_log_rerror(FCGI_LOG_ERR
, r
,
958 "FastCGI: failed to connect to server \"%s\": "
959 "can't get time of day", fr
->fs_path
);
965 fr
->fd
= (SOCKET
) CreateFile(socket_path
,
966 GENERIC_READ
| GENERIC_WRITE
,
967 FILE_SHARE_READ
| FILE_SHARE_WRITE
,
968 NULL
, // no security attributes
969 OPEN_EXISTING
, // opens existing pipe
970 FILE_ATTRIBUTE_NORMAL
, // default attributes
971 NULL
); // no template file
973 if (fr
->fd
!= (SOCKET
) INVALID_HANDLE_VALUE
) {
977 if (GetLastError() != ERROR_PIPE_BUSY
978 && GetLastError() != ERROR_FILE_NOT_FOUND
)
980 ap_log_rerror(FCGI_LOG_ERR
, r
,
981 "FastCGI: failed to connect to server \"%s\": "
982 "CreateFile() failed", fr
->fs_path
);
986 // All pipe instances are busy, so wait
987 ready
= WaitNamedPipe(socket_path
, interval
);
989 if (fr
->dynamic
&& !ready
) {
990 send_to_pm(FCGI_REQUEST_TIMEOUT_JOB
, fr
->fs_path
, fr
->user
, fr
->group
, 0, 0);
993 if (fcgi_util_gettimeofday(&fr
->queueTime
) < 0) {
994 ap_log_rerror(FCGI_LOG_ERR
, r
,
995 "FastCGI: failed to connect to server \"%s\": "
996 "can't get time of day", fr
->fs_path
);
1000 connect_time
= fr
->queueTime
.tv_sec
- fr
->startTime
.tv_sec
;
1002 FCGIDBG5("interval=%d, max_connect_time=%d, connect_time=%d, ready=%d", interval
, max_connect_time
, connect_time
, ready
);
1004 } while (connect_time
< max_connect_time
);
1006 if (fr
->fd
== (SOCKET
) INVALID_HANDLE_VALUE
) {
1007 ap_log_rerror(FCGI_LOG_ERR
, r
,
1008 "FastCGI: failed to connect to server \"%s\": "
1009 "CreateFile()/WaitNamedPipe() timed out", fr
->fs_path
);
1013 FCGIDBG2("got_named_pipe_connect: %s", fr
->fs_path
);
1016 ap_note_cleanups_for_h(rp
, (HANDLE
) fr
->fd
);
1017 ap_unblock_alarms();
1023 /* Create the socket */
1024 fr
->fd
= ap_psocket(rp
, socket_addr
->sa_family
, SOCK_STREAM
, 0);
1028 errno
= WSAGetLastError(); // Not sure this is going to work as expected
1030 ap_log_rerror(FCGI_LOG_ERR_ERRNO
, r
,
1031 "FastCGI: failed to connect to server \"%s\": "
1032 "ap_psocket() failed", fr
->fs_path
);
1037 if (fr
->fd
>= FD_SETSIZE
) {
1038 ap_log_rerror(FCGI_LOG_ERR
, r
,
1039 "FastCGI: failed to connect to server \"%s\": "
1040 "socket file descriptor (%u) is larger than "
1041 "FD_SETSIZE (%u), you probably need to rebuild Apache with a "
1042 "larger FD_SETSIZE", fr
->fs_path
, fr
->fd
, FD_SETSIZE
);
1047 /* If appConnectTimeout is non-zero, setup do a non-blocking connect */
1048 if ((fr
->dynamic
&& dynamicAppConnectTimeout
) || (!fr
->dynamic
&& fr
->fs
->appConnectTimeout
)) {
1049 set_nonblocking(fr
->fd
, TRUE
);
1052 if (fr
->dynamic
&& fcgi_util_gettimeofday(&fr
->startTime
) < 0) {
1053 ap_log_rerror(FCGI_LOG_ERR
, r
,
1054 "FastCGI: failed to connect to server \"%s\": "
1055 "can't get time of day", fr
->fs_path
);
1060 if (connect(fr
->fd
, (struct sockaddr
*)socket_addr
, socket_addr_len
) == 0)
1061 goto ConnectionComplete
;
1065 errno
= WSAGetLastError();
1066 if (errno
!= WSAEWOULDBLOCK
) {
1067 ap_log_rerror(FCGI_LOG_ERR_ERRNO
, r
,
1068 "FastCGI: failed to connect to server \"%s\": "
1069 "connect() failed", fr
->fs_path
);
1075 /* ECONNREFUSED means the listen queue is full (or there isn't one).
1076 * With dynamic I can at least make sure the PM knows this is occuring */
1077 if (fr
->dynamic
&& errno
== ECONNREFUSED
) {
1078 /* @@@ This might be better as some other "kind" of message */
1079 send_to_pm(FCGI_REQUEST_TIMEOUT_JOB
, fr
->fs_path
, fr
->user
, fr
->group
, 0, 0);
1081 errno
= ECONNREFUSED
;
1084 if (errno
!= EINPROGRESS
) {
1085 ap_log_rerror(FCGI_LOG_ERR
, r
,
1086 "FastCGI: failed to connect to server \"%s\": "
1087 "connect() failed", fr
->fs_path
);
1093 /* The connect() is non-blocking */
1099 FD_ZERO(&write_fds
);
1100 FD_SET(fr
->fd
, &write_fds
);
1101 read_fds
= write_fds
;
1102 tval
.tv_sec
= dynamicPleaseStartDelay
;
1105 status
= ap_select((fr
->fd
+1), &read_fds
, &write_fds
, NULL
, &tval
);
1109 if (fcgi_util_gettimeofday(&fr
->queueTime
) < 0) {
1110 ap_log_rerror(FCGI_LOG_ERR
, r
,
1111 "FastCGI: failed to connect to server \"%s\": "
1112 "can't get time of day", fr
->fs_path
);
1119 /* select() timed out */
1120 send_to_pm(FCGI_REQUEST_TIMEOUT_JOB
, fr
->fs_path
, fr
->user
, fr
->group
, 0, 0);
1121 } while ((fr
->queueTime
.tv_sec
- fr
->startTime
.tv_sec
) < (int)dynamicAppConnectTimeout
);
1123 /* XXX These can be moved down when dynamic vars live is a struct */
1125 ap_log_rerror(FCGI_LOG_ERR_NOERRNO
, r
,
1126 "FastCGI: failed to connect to server \"%s\": "
1127 "connect() timed out (appConnTimeout=%dsec)",
1128 fr
->fs_path
, dynamicAppConnectTimeout
);
1133 tval
.tv_sec
= fr
->fs
->appConnectTimeout
;
1135 FD_ZERO(&write_fds
);
1136 FD_SET(fr
->fd
, &write_fds
);
1137 read_fds
= write_fds
;
1139 status
= ap_select((fr
->fd
+1), &read_fds
, &write_fds
, NULL
, &tval
);
1142 ap_log_rerror(FCGI_LOG_ERR_NOERRNO
, r
,
1143 "FastCGI: failed to connect to server \"%s\": "
1144 "connect() timed out (appConnTimeout=%dsec)",
1145 fr
->fs_path
, dynamicAppConnectTimeout
);
1152 errno
= WSAGetLastError();
1154 ap_log_rerror(FCGI_LOG_ERR_ERRNO
, r
,
1155 "FastCGI: failed to connect to server \"%s\": "
1156 "select() failed", fr
->fs_path
);
1160 if (FD_ISSET(fr
->fd
, &write_fds
) || FD_ISSET(fr
->fd
, &read_fds
)) {
1162 NET_SIZE_T len
= sizeof(error
);
1164 if (getsockopt(fr
->fd
, SOL_SOCKET
, SO_ERROR
, (char *)&error
, &len
) < 0) {
1165 /* Solaris pending error */
1167 errno
= WSAGetLastError();
1169 ap_log_rerror(FCGI_LOG_ERR_ERRNO
, r
,
1170 "FastCGI: failed to connect to server \"%s\": "
1171 "select() failed (Solaris pending error)", fr
->fs_path
);
1176 /* Berkeley-derived pending error */
1178 ap_log_rerror(FCGI_LOG_ERR_ERRNO
, r
,
1179 "FastCGI: failed to connect to server \"%s\": "
1180 "select() failed (pending error)", fr
->fs_path
);
1186 errno
= WSAGetLastError();
1188 ap_log_rerror(FCGI_LOG_ERR_ERRNO
, r
,
1189 "FastCGI: failed to connect to server \"%s\": "
1190 "select() error - THIS CAN'T HAPPEN!", fr
->fs_path
);
1195 /* Return to blocking mode if it was set up */
1196 if ((fr
->dynamic
&& dynamicAppConnectTimeout
) || (!fr
->dynamic
&& fr
->fs
->appConnectTimeout
)) {
1197 set_nonblocking(fr
->fd
, FALSE
);
1201 if (socket_addr
->sa_family
== AF_INET
) {
1202 /* We shouldn't be sending small packets and there's no application
1203 * level ack of the data we send, so disable Nagle */
1205 setsockopt(fr
->fd
, IPPROTO_TCP
, TCP_NODELAY
, (char *)&set
, sizeof(set
));
1212 static int server_error(fcgi_request
*fr
)
1214 #if defined(SIGPIPE) && MODULE_MAGIC_NUMBER < 19990320
1215 /* Make sure we leave with Apache's sigpipe_handler in place */
1216 if (fr
->apache_sigpipe_handler
!= NULL
)
1217 signal(SIGPIPE
, fr
->apache_sigpipe_handler
);
1219 close_connection_to_fs(fr
);
1220 ap_kill_timeout(fr
->r
);
1221 return SERVER_ERROR
;
1224 static void cleanup(void *data
)
1226 const fcgi_request
* const fr
= (fcgi_request
*)data
;
1232 set_nonblocking(fr
->fd
, FALSE
);
1235 if (fr
->fs_stderr_len
) {
1236 ap_log_rerror(FCGI_LOG_ERR_NOERRNO
, fr
->r
,
1237 "FastCGI: server \"%s\" stderr: %s", fr
->fs_path
, fr
->fs_stderr
);
1241 /*----------------------------------------------------------------------
1242 * This is the core routine for moving data between the FastCGI
1243 * application and the Web server's client.
1245 static int do_work(request_rec
*r
, fcgi_request
*fr
)
1247 struct timeval timeOut
, dynamic_last_activity_time
= {0, 0};
1248 fd_set read_set
, write_set
;
1249 int status
= 0, idle_timeout
;
1250 int numFDs
, dynamic_first_read
= fr
->dynamic
? 1 : 0;
1252 int envSent
= FALSE
; /* has the complete ENV been buffered? */
1255 const char *err
= NULL
;
1258 FD_ZERO(&write_set
);
1260 fcgi_protocol_queue_begin_request(fr
);
1262 /* Buffer as much of the environment as we can fit */
1264 envSent
= fcgi_protocol_queue_env(r
, fr
, &env
);
1266 /* Start the Apache dropdead timer. See comments at top of file. */
1267 ap_hard_timeout("buffering of FastCGI client data", r
);
1269 /* Read as much as possible from the client. */
1270 if (fr
->role
== FCGI_RESPONDER
) {
1271 status
= ap_setup_client_block(r
, REQUEST_CHUNKED_ERROR
);
1276 fr
->expectingClientContent
= (ap_should_client_block(r
) != 0);
1278 if (read_from_client_n_queue(fr
) != OK
)
1279 return server_error(fr
);
1282 /* Connect to the FastCGI Application */
1283 ap_hard_timeout("connect() to FastCGI server", r
);
1284 if (open_connection_to_fs(fr
) != FCGI_OK
) {
1285 return server_error(fr
);
1288 numFDs
= fr
->fd
+ 1;
1289 idle_timeout
= fr
->dynamic
? dynamic_idle_timeout
: fr
->fs
->idle_timeout
;
1291 if (dynamic_first_read
) {
1292 dynamic_last_activity_time
= fr
->startTime
;
1294 if (dynamicAppConnectTimeout
) {
1295 struct timeval qwait
;
1296 timersub(&fr
->queueTime
, &fr
->startTime
, &qwait
);
1297 dynamic_first_read
= qwait
.tv_sec
/ dynamicPleaseStartDelay
+ 1;
1301 /* @@@ We never reset the timer in this loop, most folks don't mess w/
1302 * Timeout directive which means we've got the 5 min default which is way
1303 * to long to tie up a fs. We need a better/configurable solution that
1304 * uses the select */
1305 ap_hard_timeout("FastCGI request processing", r
);
1307 /* Register to get the script's stderr logged at the end of the request */
1309 ap_register_cleanup(rp
, (void *)fr
, cleanup
, ap_null_cleanup
);
1310 ap_unblock_alarms();
1312 /* Before we do any writing, set the connection non-blocking */
1314 if (fr
->using_npipe_io
) {
1315 DWORD mode
= PIPE_NOWAIT
| PIPE_READMODE_BYTE
;
1316 SetNamedPipeHandleState((HANDLE
) fr
->fd
, &mode
, NULL
, NULL
);
1321 set_nonblocking(fr
->fd
, TRUE
);
1323 /* The socket is writeable, so get the first write out of the way */
1324 if (fcgi_buf_get_to_fd(fr
->serverOutputBuffer
, fr
->fd
) < 0) {
1326 if (! fr
->using_npipe_io
)
1327 ap_log_rerror(FCGI_LOG_ERR_ERRNO
, r
,
1328 "FastCGI: comm with server \"%s\" aborted: write failed", fr
->fs_path
);
1331 ap_log_rerror(FCGI_LOG_ERR
, r
,
1332 "FastCGI: comm with server \"%s\" aborted: write failed", fr
->fs_path
);
1333 return server_error(fr
);
1336 while (fr
->keepReadingFromFcgiApp
1337 || BufferLength(fr
->serverInputBuffer
) > 0
1338 || BufferLength(fr
->clientOutputBuffer
) > 0) {
1340 /* If we didn't buffer all of the environment yet, buffer some more */
1342 envSent
= fcgi_protocol_queue_env(r
, fr
, &env
);
1344 /* Read as much as possible from the client. */
1345 if (fr
->role
== FCGI_RESPONDER
&& !fr
->eofSent
&& envSent
) {
1347 /* ap_get_client_block() (called in read_from_client_n_queue()
1348 * can't handle a non-blocking fd, its a bummer. We might be
1349 * able to completely bypass the Apache BUFF routines in still
1350 * do it, but thats a major hassle. Apache 2.X will handle it,
1351 * and then so will we. */
1353 if (read_from_client_n_queue(fr
) != OK
)
1354 return server_error(fr
);
1357 /* To avoid deadlock, don't do a blocking select to write to
1358 * the FastCGI application without selecting to read from the
1359 * FastCGI application.
1361 doClientWrite
= FALSE
;
1362 if (fr
->keepReadingFromFcgiApp
&& BufferFree(fr
->serverInputBuffer
) > 0) {
1365 DWORD bytesavail
= 0;
1367 if (!fr
->using_npipe_io
) {
1369 FD_SET(fr
->fd
, &read_set
);
1371 /* Is data buffered for output to the FastCGI server? */
1372 if (BufferLength(fr
->serverOutputBuffer
) > 0) {
1373 FD_SET(fr
->fd
, &write_set
);
1375 FD_CLR(fr
->fd
, &write_set
);
1381 * If there's data buffered to send to the client, don't
1382 * wait indefinitely for the FastCGI app; the app might
1383 * be doing server push.
1385 if (BufferLength(fr
->clientOutputBuffer
) > 0) {
1387 timeOut
.tv_usec
= 100000; /* 0.1 sec */
1389 else if (dynamic_first_read
) {
1391 struct timeval qwait
;
1393 if (fcgi_util_gettimeofday(&fr
->queueTime
) < 0) {
1394 ap_log_rerror(FCGI_LOG_ERR
, r
, "FastCGI: can't get time of day");
1395 return server_error(fr
);
1398 /* Check for idle_timeout */
1400 dynamic_last_activity_time
= fr
->queueTime
;
1403 struct timeval idle_time
;
1404 timersub(&fr
->queueTime
, &dynamic_last_activity_time
, &idle_time
);
1405 if (idle_time
.tv_sec
> idle_timeout
) {
1406 send_to_pm(FCGI_REQUEST_TIMEOUT_JOB
, fr
->fs_path
, fr
->user
, fr
->group
, 0, 0);
1407 ap_log_rerror(FCGI_LOG_ERR_NOERRNO
, r
,
1408 "FastCGI: comm with (dynamic) server \"%s\" aborted: (first read) idle timeout (%d sec)",
1409 fr
->fs_path
, idle_timeout
);
1410 return server_error(fr
);
1414 timersub(&fr
->queueTime
, &fr
->startTime
, &qwait
);
1416 delay
= dynamic_first_read
* dynamicPleaseStartDelay
;
1417 if (qwait
.tv_sec
< delay
) {
1418 timeOut
.tv_sec
= delay
;
1419 timeOut
.tv_usec
= 100000; /* fudge for select() slop */
1420 timersub(&timeOut
, &qwait
, &timeOut
);
1423 /* Killed time somewhere.. client read? */
1424 send_to_pm(FCGI_REQUEST_TIMEOUT_JOB
, fr
->fs_path
, fr
->user
, fr
->group
, 0, 0);
1425 dynamic_first_read
= qwait
.tv_sec
/ dynamicPleaseStartDelay
+ 1;
1426 timeOut
.tv_sec
= dynamic_first_read
* dynamicPleaseStartDelay
;
1427 timeOut
.tv_usec
= 100000; /* fudge for select() slop */
1428 timersub(&timeOut
, &qwait
, &timeOut
);
1432 timeOut
.tv_sec
= idle_timeout
;
1433 timeOut
.tv_usec
= 0;
1437 if (!fr
->using_npipe_io
) {
1439 if ((status
= ap_select(numFDs
, &read_set
, &write_set
, NULL
, &timeOut
)) < 0) {
1441 errno
= WSAGetLastError();
1443 ap_log_rerror(FCGI_LOG_ERR_ERRNO
, r
,
1444 "FastCGI: comm with server \"%s\" aborted: select() failed", fr
->fs_path
);
1445 return server_error(fr
);
1450 int stopTime
= time(NULL
) + timeOut
.tv_sec
;
1452 if (BufferLength(fr
->serverOutputBuffer
) == 0)
1456 while ((timeOut
.tv_sec
!= 0) && (time(NULL
) <= stopTime
))
1458 BOOL ok
= PeekNamedPipe((HANDLE
) fr
->fd
,NULL
, 0, NULL
, &bytesavail
, NULL
);
1461 ap_log_rerror(FCGI_LOG_ERR
, r
,
1462 "FastCGI: comm with sever \"%s\" aborted: PeekNamedPipe() failed",
1464 return server_error(fr
);
1481 if (BufferLength(fr
->clientOutputBuffer
) > 0) {
1482 doClientWrite
= TRUE
;
1484 else if (dynamic_first_read
) {
1485 struct timeval qwait
;
1487 if (fcgi_util_gettimeofday(&fr
->queueTime
) < 0) {
1488 ap_log_rerror(FCGI_LOG_ERR
, r
, "FastCGI: can't get time of day");
1489 return server_error(fr
);
1492 timersub(&fr
->queueTime
, &fr
->startTime
, &qwait
);
1494 send_to_pm(FCGI_REQUEST_TIMEOUT_JOB
, fr
->fs_path
, fr
->user
, fr
->group
, 0, 0);
1496 dynamic_first_read
= qwait
.tv_sec
/ dynamicPleaseStartDelay
+ 1;
1499 ap_log_rerror(FCGI_LOG_ERR_NOERRNO
, r
,
1500 "FastCGI: comm with server \"%s\" aborted: idle timeout (%d sec)",
1501 fr
->fs_path
, idle_timeout
);
1502 return server_error(fr
);
1506 #if defined(SIGPIPE) && MODULE_MAGIC_NUMBER < 19990320
1507 /* Disable Apache's SIGPIPE handler */
1508 fr
->apache_sigpipe_handler
= signal(SIGPIPE
, SIG_IGN
);
1511 /* Read from the FastCGI server */
1513 if ((fr
->using_npipe_io
1514 && (BufferFree(fr
->serverInputBuffer
) > 0)
1515 && PeekNamedPipe((HANDLE
) fr
->fd
, NULL
, 0, NULL
, &bytesavail
, NULL
)
1516 && (bytesavail
> 0))
1517 || FD_ISSET(fr
->fd
, &read_set
)) {
1519 if (FD_ISSET(fr
->fd
, &read_set
)) {
1521 if (dynamic_first_read
) {
1522 dynamic_first_read
= 0;
1523 if (fcgi_util_gettimeofday(&fr
->queueTime
) < 0) {
1524 ap_log_rerror(FCGI_LOG_ERR
, r
, "FastCGI: can't get time of day");
1525 return server_error(fr
);
1529 if ((status
= fcgi_buf_add_fd(fr
->serverInputBuffer
, fr
->fd
)) < 0) {
1531 if (! fr
->using_npipe_io
)
1532 ap_log_rerror(FCGI_LOG_ERR_ERRNO
, r
,
1533 "FastCGI: comm with server \"%s\" aborted: read failed", fr
->fs_path
);
1536 ap_log_rerror(FCGI_LOG_ERR
, r
,
1537 "FastCGI: comm with server \"%s\" aborted: read failed", fr
->fs_path
);
1538 return server_error(fr
);
1542 fr
->keepReadingFromFcgiApp
= FALSE
;
1543 close_connection_to_fs(fr
);
1547 /* Write to the FastCGI server */
1549 if ((fr
->using_npipe_io
&& (BufferLength(fr
->serverOutputBuffer
) > 0))
1550 || FD_ISSET(fr
->fd
, &write_set
)) {
1552 if (FD_ISSET(fr
->fd
, &write_set
)) {
1555 if (fcgi_buf_get_to_fd(fr
->serverOutputBuffer
, fr
->fd
) < 0) {
1557 if (! fr
->using_npipe_io
)
1558 ap_log_rerror(FCGI_LOG_ERR_ERRNO
, r
,
1559 "FastCGI: comm with server \"%s\" aborted: write failed", fr
->fs_path
);
1562 ap_log_rerror(FCGI_LOG_ERR
, r
,
1563 "FastCGI: comm with server \"%s\" aborted: write failed", fr
->fs_path
);
1564 return server_error(fr
);
1568 #if defined(SIGPIPE) && MODULE_MAGIC_NUMBER < 19990320
1569 /* Reinstall Apache's SIGPIPE handler */
1570 signal(SIGPIPE
, fr
->apache_sigpipe_handler
);
1574 doClientWrite
= TRUE
;
1577 if (fr
->role
== FCGI_RESPONDER
&& doClientWrite
) {
1579 if (write_to_client(fr
) != OK
) {
1580 #if defined(SIGPIPE) && MODULE_MAGIC_NUMBER < 19990320
1581 /* Make sure we leave with Apache's sigpipe_handler in place */
1582 if (fr
->apache_sigpipe_handler
!= NULL
)
1583 signal(SIGPIPE
, fr
->apache_sigpipe_handler
);
1585 close_connection_to_fs(fr
);
1586 ap_kill_timeout(fr
->r
);
1591 if (fcgi_protocol_dequeue(rp
, fr
) != OK
)
1592 return server_error(fr
);
1594 if (fr
->keepReadingFromFcgiApp
&& fr
->exitStatusSet
) {
1595 /* we're done talking to the fcgi app */
1596 fr
->keepReadingFromFcgiApp
= FALSE
;
1597 close_connection_to_fs(fr
);
1600 if (fr
->parseHeader
== SCAN_CGI_READING_HEADERS
) {
1601 if ((err
= process_headers(r
, fr
))) {
1602 ap_log_rerror(FCGI_LOG_ERR_NOERRNO
, r
,
1603 "FastCGI: comm with server \"%s\" aborted: error parsing headers: %s", fr
->fs_path
, err
);
1604 return server_error(fr
);
1610 switch (fr
->parseHeader
) {
1612 case SCAN_CGI_FINISHED
:
1613 if (fr
->role
== FCGI_RESPONDER
) {
1614 #ifdef RUSSIAN_APACHE
1617 ap_bflush(r
->connection
->client
);
1619 ap_bgetopt(r
->connection
->client
, BO_BYTECT
, &r
->bytes_sent
);
1623 case SCAN_CGI_READING_HEADERS
:
1624 ap_log_rerror(FCGI_LOG_ERR_NOERRNO
, r
,
1625 "FastCGI: incomplete headers (%d bytes) received from server \"%s\"",
1626 fr
->header
->nelts
, fr
->fs_path
);
1627 return server_error(fr
);
1629 case SCAN_CGI_BAD_HEADER
:
1630 return server_error(fr
);
1632 case SCAN_CGI_INT_REDIRECT
:
1633 case SCAN_CGI_SRV_REDIRECT
:
1635 * XXX We really should be soaking all client input
1636 * and all script output. See mod_cgi.c.
1637 * There's other differences we need to pick up here as well!
1638 * This has to be revisited.
1650 static fcgi_request
*create_fcgi_request(request_rec
* const r
, const char *fs_path
)
1652 struct stat
*my_finfo
;
1653 pool
* const p
= r
->pool
;
1655 fcgi_request
* const fr
= (fcgi_request
*)ap_pcalloc(p
, sizeof(fcgi_request
));
1658 my_finfo
= (struct stat
*)ap_palloc(p
, sizeof(struct stat
));
1659 if (stat(fs_path
, my_finfo
) < 0) {
1660 ap_log_rerror(FCGI_LOG_ERR_ERRNO
, r
,
1661 "FastCGI: stat() of \"%s\" failed", fs_path
);
1666 my_finfo
= &r
->finfo
;
1667 fs_path
= r
->filename
;
1670 fs
= fcgi_util_fs_get_by_id(fs_path
, r
->server
->server_uid
, r
->server
->server_gid
);
1672 /* Its a request for a dynamic FastCGI application */
1673 const char * const err
=
1674 fcgi_util_fs_is_path_ok(p
, fs_path
, my_finfo
);
1677 ap_log_rerror(FCGI_LOG_ERR_NOERRNO
, r
, "FastCGI: invalid (dynamic) server \"%s\": %s", fs_path
, err
);
1682 fr
->serverInputBuffer
= fcgi_buf_new(p
, SERVER_BUFSIZE
);
1683 fr
->serverOutputBuffer
= fcgi_buf_new(p
, SERVER_BUFSIZE
);
1684 fr
->clientInputBuffer
= fcgi_buf_new(p
, SERVER_BUFSIZE
);
1685 fr
->clientOutputBuffer
= fcgi_buf_new(p
, SERVER_BUFSIZE
);
1686 fr
->erBufPtr
= fcgi_buf_new(p
, sizeof(FCGI_EndRequestBody
) + 1);
1687 fr
->gotHeader
= FALSE
;
1688 fr
->parseHeader
= SCAN_CGI_READING_HEADERS
;
1689 fr
->header
= ap_make_array(p
, 1, 1);
1690 fr
->fs_stderr
= NULL
;
1692 fr
->readingEndRequestBody
= FALSE
;
1694 fr
->exitStatusSet
= FALSE
;
1695 fr
->requestId
= 1; /* anything but zero is OK here */
1696 fr
->eofSent
= FALSE
;
1697 fr
->role
= FCGI_RESPONDER
;
1698 fr
->expectingClientContent
= FALSE
;
1699 fr
->keepReadingFromFcgiApp
= TRUE
;
1701 fr
->fs_path
= fs_path
;
1702 fr
->authHeaders
= ap_make_table(p
, 10);
1704 fr
->fd
= INVALID_SOCKET
;
1705 fr
->dynamic
= ((fs
== NULL
) || (fs
->directive
== APP_CLASS_DYNAMIC
)) ? TRUE
: FALSE
;
1706 fr
->using_npipe_io
= FALSE
;
1708 fr
->dynamic
= (fs
== NULL
) ? TRUE
: FALSE
;
1712 set_uid_n_gid(r
, &fr
->user
, &fr
->group
);
1718 *----------------------------------------------------------------------
1722 * This routine gets called for a request that corresponds to
1723 * a FastCGI connection. It performs the request synchronously.
1726 * Final status of request: OK or NOT_FOUND or SERVER_ERROR.
1729 * Request performed.
1731 *----------------------------------------------------------------------
1734 /* Stolen from mod_cgi.c..
1735 * KLUDGE --- for back-combatibility, we don't have to check ExecCGI
1736 * in ScriptAliased directories, which means we need to know if this
1737 * request came through ScriptAlias or not... so the Alias module
1738 * leaves a note for us.
1740 static int apache_is_scriptaliased(request_rec
*r
)
1742 const char *t
= ap_table_get(r
->notes
, "alias-forced-type");
1743 return t
&& (!strcasecmp(t
, "cgi-script"));
1746 /* If a script wants to produce its own Redirect body, it now
1747 * has to explicitly *say* "Status: 302". If it wants to use
1748 * Apache redirects say "Status: 200". See process_headers().
1750 static int post_process_for_redirects(request_rec
* const r
,
1751 const fcgi_request
* const fr
)
1753 switch(fr
->parseHeader
) {
1754 case SCAN_CGI_INT_REDIRECT
:
1756 /* @@@ There are still differences between the handling in
1757 * mod_cgi and mod_fastcgi. This needs to be revisited.
1759 /* We already read the message body (if any), so don't allow
1760 * the redirected request to think it has one. We can ignore
1761 * Transfer-Encoding, since we used REQUEST_CHUNKED_ERROR.
1764 r
->method_number
= M_GET
;
1765 ap_table_unset(r
->headers_in
, "Content-length");
1767 ap_internal_redirect_handler(ap_table_get(r
->headers_out
, "Location"), r
);
1770 case SCAN_CGI_SRV_REDIRECT
:
1778 /******************************************************************************
1779 * Process fastcgi-script requests. Based on mod_cgi::cgi_handler().
1781 static int content_handler(request_rec
*r
)
1783 fcgi_request
*fr
= NULL
;
1786 /* Setup a new FastCGI request */
1787 if ((fr
= create_fcgi_request(r
, NULL
)) == NULL
)
1788 return SERVER_ERROR
;
1790 /* If its a dynamic invocation, make sure scripts are OK here */
1791 if (fr
->dynamic
&& !(ap_allow_options(r
) & OPT_EXECCGI
) && !apache_is_scriptaliased(r
)) {
1792 ap_log_rerror(FCGI_LOG_ERR_NOERRNO
, r
,
1793 "FastCGI: \"ExecCGI Option\" is off in this directory: %s", r
->uri
);
1794 return SERVER_ERROR
;
1797 /* Process the fastcgi-script request */
1798 if ((ret
= do_work(r
, fr
)) != OK
)
1801 /* Special case redirects */
1802 return post_process_for_redirects(r
, fr
);
1806 static int post_process_auth_passed_header(table
*t
, const char *key
, const char * const val
)
1808 if (strncasecmp(key
, "Variable-", 9) == 0)
1811 ap_table_setn(t
, key
, val
);
1815 static int post_process_auth_passed_compat_header(table
*t
, const char *key
, const char * const val
)
1817 if (strncasecmp(key
, "Variable-", 9) == 0)
1818 ap_table_setn(t
, key
+ 9, val
);
1823 static int post_process_auth_failed_header(table
* const t
, const char * const key
, const char * const val
)
1825 ap_table_setn(t
, key
, val
);
1829 static void post_process_auth(fcgi_request
* const fr
, const int passed
)
1831 request_rec
* const r
= fr
->r
;
1833 /* Restore the saved subprocess_env because we muddied ours up */
1834 r
->subprocess_env
= fr
->saved_subprocess_env
;
1837 if (fr
->auth_compat
) {
1838 ap_table_do((int (*)(void *, const char *, const char *))post_process_auth_passed_compat_header
,
1839 (void *)r
->subprocess_env
, fr
->authHeaders
, NULL
);
1842 ap_table_do((int (*)(void *, const char *, const char *))post_process_auth_passed_header
,
1843 (void *)r
->subprocess_env
, fr
->authHeaders
, NULL
);
1847 ap_table_do((int (*)(void *, const char *, const char *))post_process_auth_failed_header
,
1848 (void *)r
->err_headers_out
, fr
->authHeaders
, NULL
);
1851 /* @@@ Restore these.. its a hack until I rewrite the header handling */
1852 r
->status
= HTTP_OK
;
1853 r
->status_line
= NULL
;
1856 static int check_user_authentication(request_rec
*r
)
1858 int res
, authenticated
= 0;
1859 const char *password
;
1861 const fcgi_dir_config
* const dir_config
=
1862 (const fcgi_dir_config
*)ap_get_module_config(r
->per_dir_config
, &fastcgi_module
);
1864 if (dir_config
->authenticator
== NULL
)
1867 /* Get the user password */
1868 if ((res
= ap_get_basic_auth_pw(r
, &password
)) != OK
)
1871 if ((fr
= create_fcgi_request(r
, dir_config
->authenticator
)) == NULL
)
1872 return SERVER_ERROR
;
1874 /* Save the existing subprocess_env, because we're gonna muddy it up */
1875 fr
->saved_subprocess_env
= ap_copy_table(r
->pool
, r
->subprocess_env
);
1877 ap_table_setn(r
->subprocess_env
, "REMOTE_PASSWD", password
);
1878 ap_table_setn(r
->subprocess_env
, "FCGI_APACHE_ROLE", "AUTHENTICATOR");
1880 /* The FastCGI Protocol doesn't differentiate authentication */
1881 fr
->role
= FCGI_AUTHORIZER
;
1883 /* Do we need compatibility mode? */
1884 fr
->auth_compat
= (dir_config
->authenticator_options
& FCGI_COMPAT
);
1886 if ((res
= do_work(r
, fr
)) != OK
)
1887 goto AuthenticationFailed
;
1889 authenticated
= (r
->status
== 200);
1890 post_process_auth(fr
, authenticated
);
1892 /* A redirect shouldn't be allowed during the authentication phase */
1893 if (ap_table_get(r
->headers_out
, "Location") != NULL
) {
1894 ap_log_rerror(FCGI_LOG_ERR_NOERRNO
, r
,
1895 "FastCGI: FastCgiAuthenticator \"%s\" redirected (not allowed)",
1896 dir_config
->authenticator
);
1897 goto AuthenticationFailed
;
1903 AuthenticationFailed
:
1904 if (!(dir_config
->authenticator_options
& FCGI_AUTHORITATIVE
))
1907 /* @@@ Probably should support custom_responses */
1908 ap_note_basic_auth_failure(r
);
1909 ap_log_rerror(FCGI_LOG_ERR_NOERRNO
, r
,
1910 "FastCGI: authentication failed for user \"%s\": %s", r
->connection
->user
, r
->uri
);
1911 return (res
== OK
) ? AUTH_REQUIRED
: res
;
1914 static int check_user_authorization(request_rec
*r
)
1916 int res
, authorized
= 0;
1918 const fcgi_dir_config
* const dir_config
=
1919 (const fcgi_dir_config
*)ap_get_module_config(r
->per_dir_config
, &fastcgi_module
);
1921 if (dir_config
->authorizer
== NULL
)
1924 /* @@@ We should probably honor the existing parameters to the require directive
1925 * as well as allow the definition of new ones (or use the basename of the
1926 * FastCGI server and pass the rest of the directive line), but for now keep
1929 if ((fr
= create_fcgi_request(r
, dir_config
->authorizer
)) == NULL
)
1930 return SERVER_ERROR
;
1932 /* Save the existing subprocess_env, because we're gonna muddy it up */
1933 fr
->saved_subprocess_env
= ap_copy_table(r
->pool
, r
->subprocess_env
);
1935 ap_table_setn(r
->subprocess_env
, "FCGI_APACHE_ROLE", "AUTHORIZER");
1937 fr
->role
= FCGI_AUTHORIZER
;
1939 /* Do we need compatibility mode? */
1940 fr
->auth_compat
= (dir_config
->authenticator_options
& FCGI_COMPAT
);
1942 if ((res
= do_work(r
, fr
)) != OK
)
1943 goto AuthorizationFailed
;
1945 authorized
= (r
->status
== 200);
1946 post_process_auth(fr
, authorized
);
1948 /* A redirect shouldn't be allowed during the authorization phase */
1949 if (ap_table_get(r
->headers_out
, "Location") != NULL
) {
1950 ap_log_rerror(FCGI_LOG_ERR_NOERRNO
, r
,
1951 "FastCGI: FastCgiAuthorizer \"%s\" redirected (not allowed)",
1952 dir_config
->authorizer
);
1953 goto AuthorizationFailed
;
1959 AuthorizationFailed
:
1960 if (!(dir_config
->authorizer_options
& FCGI_AUTHORITATIVE
))
1963 /* @@@ Probably should support custom_responses */
1964 ap_note_basic_auth_failure(r
);
1965 ap_log_rerror(FCGI_LOG_ERR_NOERRNO
, r
,
1966 "FastCGI: authorization failed for user \"%s\": %s", r
->connection
->user
, r
->uri
);
1967 return (res
== OK
) ? AUTH_REQUIRED
: res
;
1970 static int check_access(request_rec
*r
)
1972 int res
, access_allowed
= 0;
1974 const fcgi_dir_config
* const dir_config
=
1975 (fcgi_dir_config
*)ap_get_module_config(r
->per_dir_config
, &fastcgi_module
);
1977 if (dir_config
== NULL
|| dir_config
->access_checker
== NULL
)
1980 if ((fr
= create_fcgi_request(r
, dir_config
->access_checker
)) == NULL
)
1981 return SERVER_ERROR
;
1983 /* Save the existing subprocess_env, because we're gonna muddy it up */
1984 fr
->saved_subprocess_env
= ap_copy_table(r
->pool
, r
->subprocess_env
);
1986 ap_table_setn(r
->subprocess_env
, "FCGI_APACHE_ROLE", "ACCESS_CHECKER");
1988 /* The FastCGI Protocol doesn't differentiate access control */
1989 fr
->role
= FCGI_AUTHORIZER
;
1991 /* Do we need compatibility mode? */
1992 fr
->auth_compat
= (dir_config
->authenticator_options
& FCGI_COMPAT
);
1994 if ((res
= do_work(r
, fr
)) != OK
)
1997 access_allowed
= (r
->status
== 200);
1998 post_process_auth(fr
, access_allowed
);
2000 /* A redirect shouldn't be allowed during the access check phase */
2001 if (ap_table_get(r
->headers_out
, "Location") != NULL
) {
2002 ap_log_rerror(FCGI_LOG_ERR_NOERRNO
, r
,
2003 "FastCGI: FastCgiAccessChecker \"%s\" redirected (not allowed)",
2004 dir_config
->access_checker
);
2012 if (!(dir_config
->access_checker_options
& FCGI_AUTHORITATIVE
))
2015 /* @@@ Probably should support custom_responses */
2016 ap_log_rerror(FCGI_LOG_ERR_NOERRNO
, r
, "FastCGI: access denied: %s", r
->uri
);
2017 return (res
== OK
) ? FORBIDDEN
: res
;
2020 command_rec fastcgi_cmds
[] = {
2021 { "AppClass", fcgi_config_new_static_server
, NULL
, RSRC_CONF
, RAW_ARGS
, NULL
},
2022 { "FastCgiServer", fcgi_config_new_static_server
, NULL
, RSRC_CONF
, RAW_ARGS
, NULL
},
2024 { "ExternalAppClass", fcgi_config_new_external_server
, NULL
, RSRC_CONF
, RAW_ARGS
, NULL
},
2025 { "FastCgiExternalServer", fcgi_config_new_external_server
, NULL
, RSRC_CONF
, RAW_ARGS
, NULL
},
2027 { "FastCgiIpcDir", fcgi_config_set_socket_dir
, NULL
, RSRC_CONF
, TAKE1
, NULL
},
2029 { "FastCgiSuexec", fcgi_config_set_wrapper
, NULL
, RSRC_CONF
, TAKE1
, NULL
},
2030 { "FastCgiWrapper", fcgi_config_set_wrapper
, NULL
, RSRC_CONF
, TAKE1
, NULL
},
2032 { "FCGIConfig", fcgi_config_set_config
, NULL
, RSRC_CONF
, RAW_ARGS
, NULL
},
2033 { "FastCgiConfig", fcgi_config_set_config
, NULL
, RSRC_CONF
, RAW_ARGS
, NULL
},
2035 { "FastCgiAuthenticator", fcgi_config_new_auth_server
,
2036 (void *)FCGI_AUTH_TYPE_AUTHENTICATOR
, ACCESS_CONF
, TAKE12
,
2037 "a fastcgi-script path (absolute or relative to ServerRoot) followed by an optional -compat" },
2038 { "FastCgiAuthenticatorAuthoritative", fcgi_config_set_authoritative_slot
,
2039 (void *)XtOffsetOf(fcgi_dir_config
, authenticator_options
), ACCESS_CONF
, FLAG
,
2040 "Set to 'off' to allow authentication to be passed along to lower modules upon failure" },
2042 { "FastCgiAuthorizer", fcgi_config_new_auth_server
,
2043 (void *)FCGI_AUTH_TYPE_AUTHORIZER
, ACCESS_CONF
, TAKE12
,
2044 "a fastcgi-script path (absolute or relative to ServerRoot) followed by an optional -compat" },
2045 { "FastCgiAuthorizerAuthoritative", fcgi_config_set_authoritative_slot
,
2046 (void *)XtOffsetOf(fcgi_dir_config
, authorizer_options
), ACCESS_CONF
, FLAG
,
2047 "Set to 'off' to allow authorization to be passed along to lower modules upon failure" },
2049 { "FastCgiAccessChecker", fcgi_config_new_auth_server
,
2050 (void *)FCGI_AUTH_TYPE_ACCESS_CHECKER
, ACCESS_CONF
, TAKE12
,
2051 "a fastcgi-script path (absolute or relative to ServerRoot) followed by an optional -compat" },
2052 { "FastCgiAccessCheckerAuthoritative", fcgi_config_set_authoritative_slot
,
2053 (void *)XtOffsetOf(fcgi_dir_config
, access_checker_options
), ACCESS_CONF
, FLAG
,
2054 "Set to 'off' to allow access control to be passed along to lower modules upon failure" },
2059 handler_rec fastcgi_handlers
[] = {
2060 { FCGI_MAGIC_TYPE
, content_handler
},
2061 { "fastcgi-script", content_handler
},
2066 module MODULE_VAR_EXPORT fastcgi_module
= {
2067 STANDARD_MODULE_STUFF
,
2068 init_module
, /* initializer */
2069 fcgi_config_create_dir_config
, /* per-dir config creator */
2070 NULL
, /* per-dir config merger (default: override) */
2071 NULL
, /* per-server config creator */
2072 NULL
, /* per-server config merger (default: override) */
2073 fastcgi_cmds
, /* command table */
2074 fastcgi_handlers
, /* [9] content handlers */
2075 NULL
, /* [2] URI-to-filename translation */
2076 check_user_authentication
, /* [5] authenticate user_id */
2077 check_user_authorization
, /* [6] authorize user_id */
2078 check_access
, /* [4] check access (based on src & http headers) */
2079 NULL
, /* [7] check/set MIME type */
2080 NULL
, /* [8] fixups */
2081 NULL
, /* [10] logger */
2082 NULL
, /* [3] header-parser */
2083 fcgi_child_init
, /* process initialization */
2084 fcgi_child_exit
, /* process exit/cleanup */
2085 NULL
/* [1] post read-request handling */