4 * Apache server module for FastCGI.
6 * $Id: mod_fastcgi.c,v 1.108 2001/03/26 15:35:40 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");
218 *----------------------------------------------------------------------
222 * An Apache module initializer, called by the Apache core
223 * after reading the server config.
225 * Start the process manager no matter what, since there may be a
226 * request for dynamic FastCGI applications without any being
227 * configured as static applications. Also, check for the existence
228 * and create if necessary a subdirectory into which all dynamic
231 *----------------------------------------------------------------------
233 static void init_module(server_rec
*s
, pool
*p
)
237 /* Register to reset to default values when the config pool is cleaned */
239 ap_register_cleanup(p
, NULL
, fcgi_config_reset_globals
, ap_null_cleanup
);
242 ap_add_version_component("mod_fastcgi/" MOD_FASTCGI_VERSION
);
244 fcgi_config_set_fcgi_uid_n_gid(1);
246 /* keep these handy */
247 fcgi_config_pool
= p
;
248 fcgi_apache_main_server
= s
;
251 /* Create Unix/Domain socket directory */
252 if ((err
= fcgi_config_make_dir(p
, fcgi_socket_dir
)))
253 ap_log_error(FCGI_LOG_ERR
, s
, "FastCGI: %s", err
);
256 /* Create Dynamic directory */
257 if ((err
= fcgi_config_make_dynamic_dir(p
, 1)))
258 ap_log_error(FCGI_LOG_ERR
, s
, "FastCGI: %s", err
);
261 /* Create the pipe for comm with the PM */
262 if (pipe(fcgi_pm_pipe
) < 0) {
263 ap_log_error(FCGI_LOG_ERR
, s
, "FastCGI: pipe() failed");
266 /* Spawn the PM only once. Under Unix, Apache calls init() routines
267 * twice, once before detach() and once after. Win32 doesn't detach.
268 * Under DSO, DSO modules are unloaded between the two init() calls.
269 * Under Unix, the -X switch causes two calls to init() but no detach
270 * (but all subprocesses are wacked so the PM is toasted anyway)! */
272 if (ap_standalone
&& getppid() != 1)
275 /* Start the Process Manager */
276 fcgi_pm_pid
= ap_spawn_child(p
, fcgi_pm_main
, NULL
, kill_only_once
, NULL
, NULL
, NULL
);
277 if (fcgi_pm_pid
<= 0) {
278 ap_log_error(FCGI_LOG_ALERT
, s
,
279 "FastCGI: can't start the process manager, spawn_child() failed");
282 close(fcgi_pm_pipe
[0]);
286 static void fcgi_child_init(server_rec
*dc0
, pool
*dc1
)
289 /* Create the Event Handlers */
290 fcgi_event_handles
[0] = CreateEvent(NULL
, FALSE
, FALSE
, NULL
);
291 fcgi_event_handles
[1] = CreateEvent(NULL
, FALSE
, FALSE
, NULL
);
292 fcgi_event_handles
[2] = CreateEvent(NULL
, FALSE
, FALSE
, NULL
);
293 fcgi_dynamic_mbox_mutex
= ap_create_mutex("fcgi_dynamic_mbox_mutex");
295 /* Spawn of the process manager thread */
296 fcgi_pm_thread
= CreateThread(NULL
, 0, (LPTHREAD_START_ROUTINE
)fcgi_pm_main
, NULL
, 0, NULL
);
301 static void fcgi_child_exit(server_rec
*dc0
, pool
*dc1
)
304 /* Signaling the PM thread tp exit*/
305 SetEvent(fcgi_event_handles
[TERM_EVENT
]);
307 /* Waiting on pm thread to exit */
308 WaitForSingleObject(fcgi_pm_thread
, INFINITE
);
315 *----------------------------------------------------------------------
319 * Terminate a line: scan to the next newline, scan back to the
320 * first non-space character and store a terminating zero. Return
321 * the next character past the end of the newline.
323 * If the end of the string is reached, ASSERT!
325 * If the FIRST character(s) in the line are '\n' or "\r\n", the
326 * first character is replaced with a NULL and next character
327 * past the newline is returned. NOTE: this condition supercedes
328 * the processing of RFC-822 continuation lines.
330 * If continuation is set to 'TRUE', then it parses a (possible)
331 * sequence of RFC-822 continuation lines.
337 * Termination byte stored in string.
339 *----------------------------------------------------------------------
341 static char *get_header_line(char *start
, int continuation
)
346 if(p
[0] == '\r' && p
[1] == '\n') { /* If EOL in 1st 2 chars */
347 p
++; /* point to \n and stop */
348 } else if(*p
!= '\n') {
351 if(*p
== '\n' && p
[1] != ' ' && p
[1] != '\t')
356 while(*p
!= '\0' && *p
!= '\n') {
362 ap_assert(*p
!= '\0');
367 * Trim any trailing whitespace.
369 while(isspace((unsigned char)p
[-1]) && p
> start
) {
378 *----------------------------------------------------------------------
382 * Call with r->parseHeader == SCAN_CGI_READING_HEADERS
383 * and initial script output in fr->header.
385 * If the initial script output does not include the header
386 * terminator ("\r\n\r\n") process_headers returns with no side
387 * effects, to be called again when more script output
388 * has been appended to fr->header.
390 * If the initial script output includes the header terminator,
391 * process_headers parses the headers and determines whether or
392 * not the remaining script output will be sent to the client.
393 * If so, process_headers sends the HTTP response headers to the
394 * client and copies any non-header script output to the output
401 * May set r->parseHeader to:
402 * SCAN_CGI_FINISHED -- headers parsed, returning script response
403 * SCAN_CGI_BAD_HEADER -- malformed header from script
404 * SCAN_CGI_INT_REDIRECT -- handler should perform internal redirect
405 * SCAN_CGI_SRV_REDIRECT -- handler should return REDIRECT
407 *----------------------------------------------------------------------
410 static const char *process_headers(request_rec
*r
, fcgi_request
*fr
)
412 char *p
, *next
, *name
, *value
;
414 int hasContentType
, hasStatus
, hasLocation
;
416 ap_assert(fr
->parseHeader
== SCAN_CGI_READING_HEADERS
);
418 if (fr
->header
== NULL
)
422 * Do we have the entire header? Scan for the blank line that
423 * terminates the header.
425 p
= (char *)fr
->header
->elts
;
426 len
= fr
->header
->nelts
;
428 while(len
-- && flag
< 2) {
438 name
= "Invalid Character";
448 /* Return (to be called later when we have more data)
449 * if we don't have an entire header. */
454 * Parse all the headers.
456 fr
->parseHeader
= SCAN_CGI_FINISHED
;
457 hasContentType
= hasStatus
= hasLocation
= FALSE
;
458 next
= (char *)fr
->header
->elts
;
460 next
= get_header_line(name
= next
, TRUE
);
464 if ((p
= strchr(name
, ':')) == NULL
) {
468 while (p
!= name
&& isspace((unsigned char)*(p
- 1))) {
475 if (strpbrk(name
, " \t") != NULL
) {
479 while (isspace((unsigned char)*value
)) {
483 if (strcasecmp(name
, "Status") == 0) {
484 int statusValue
= strtol(value
, NULL
, 10);
487 goto DuplicateNotAllowed
;
489 if (statusValue
< 0) {
490 fr
->parseHeader
= SCAN_CGI_BAD_HEADER
;
491 return ap_psprintf(r
->pool
, "invalid Status '%s'", value
);
494 r
->status
= statusValue
;
495 r
->status_line
= ap_pstrdup(r
->pool
, value
);
499 if (fr
->role
== FCGI_RESPONDER
) {
500 if (strcasecmp(name
, "Content-type") == 0) {
501 if (hasContentType
) {
502 goto DuplicateNotAllowed
;
504 hasContentType
= TRUE
;
505 r
->content_type
= ap_pstrdup(r
->pool
, value
);
509 if (strcasecmp(name
, "Location") == 0) {
511 goto DuplicateNotAllowed
;
514 ap_table_set(r
->headers_out
, "Location", value
);
518 /* If the script wants them merged, it can do it */
519 ap_table_add(r
->err_headers_out
, name
, value
);
523 ap_table_add(fr
->authHeaders
, name
, value
);
527 if (fr
->role
!= FCGI_RESPONDER
)
531 * Who responds, this handler or Apache?
534 const char *location
= ap_table_get(r
->headers_out
, "Location");
536 * Based on internal redirect handling in mod_cgi.c...
538 * If a script wants to produce its own Redirect
539 * body, it now has to explicitly *say* "Status: 302"
541 if (r
->status
== 200) {
542 if(location
[0] == '/') {
544 * Location is an relative path. This handler will
545 * consume all script output, then have Apache perform an
548 fr
->parseHeader
= SCAN_CGI_INT_REDIRECT
;
552 * Location is an absolute URL. If the script didn't
553 * produce a Content-type header, this handler will
554 * consume all script output and then have Apache generate
555 * its standard redirect response. Otherwise this handler
556 * will transmit the script's response.
558 fr
->parseHeader
= SCAN_CGI_SRV_REDIRECT
;
564 * We're responding. Send headers, buffer excess script output.
566 ap_send_http_header(r
);
568 /* We need to reinstate our timeout, send_http_header() kill()s it */
569 ap_hard_timeout("FastCGI request processing", r
);
574 len
= fr
->header
->nelts
- (next
- fr
->header
->elts
);
576 ap_assert(BufferLength(fr
->clientOutputBuffer
) == 0);
577 if (BufferFree(fr
->clientOutputBuffer
) < len
) {
578 fr
->clientOutputBuffer
= fcgi_buf_new(r
->pool
, len
);
580 ap_assert(BufferFree(fr
->clientOutputBuffer
) >= len
);
582 int sent
= fcgi_buf_add_block(fr
->clientOutputBuffer
, next
, len
);
583 ap_assert(sent
== len
);
588 /* Log first line of a multi-line header */
589 if ((p
= strpbrk(name
, "\r\n")) != NULL
)
591 fr
->parseHeader
= SCAN_CGI_BAD_HEADER
;
592 return ap_psprintf(r
->pool
, "malformed header '%s'", name
);
595 fr
->parseHeader
= SCAN_CGI_BAD_HEADER
;
596 return ap_psprintf(r
->pool
, "duplicate header '%s'", name
);
600 * Read from the client filling both the FastCGI server buffer and the
601 * client buffer with the hopes of buffering the client data before
602 * making the connect() to the FastCGI server. This prevents slow
603 * clients from keeping the FastCGI server in processing longer than is
606 static int read_from_client_n_queue(fcgi_request
*fr
)
612 while (BufferFree(fr
->clientInputBuffer
) > 0 || BufferFree(fr
->serverOutputBuffer
) > 0) {
613 fcgi_protocol_queue_client_buffer(fr
);
615 if (fr
->expectingClientContent
<= 0)
618 fcgi_buf_get_free_block_info(fr
->clientInputBuffer
, &end
, &count
);
622 if ((countRead
= ap_get_client_block(fr
->r
, end
, count
)) < 0)
625 if (countRead
== 0) {
626 fr
->expectingClientContent
= 0;
629 fcgi_buf_add_update(fr
->clientInputBuffer
, countRead
);
630 ap_reset_timeout(fr
->r
);
636 static int write_to_client(fcgi_request
*fr
)
641 fcgi_buf_get_block_info(fr
->clientOutputBuffer
, &begin
, &count
);
645 /* If fewer than count bytes are written, an error occured.
646 * ap_bwrite() typically forces a flushed write to the client, this
647 * effectively results in a block (and short packets) - it should
648 * be fixed, but I didn't win much support for the idea on new-httpd.
649 * So, without patching Apache, the best way to deal with this is
650 * to size the fcgi_bufs to hold all of the script output (within
651 * reason) so the script can be released from having to wait around
652 * for the transmission to the client to complete. */
653 #ifdef RUSSIAN_APACHE
654 if (ap_rwrite(begin
, count
, fr
->r
) != count
) {
655 ap_log_rerror(FCGI_LOG_INFO_NOERRNO
, fr
->r
,
656 "FastCGI: client stopped connection before send body completed");
660 if (ap_bwrite(fr
->r
->connection
->client
, begin
, count
) != (int) count
) {
661 ap_log_rerror(FCGI_LOG_INFO_NOERRNO
, fr
->r
,
662 "FastCGI: client stopped connection before send body completed");
667 ap_reset_timeout(fr
->r
);
669 /* Don't bother with a wrapped buffer, limiting exposure to slow
670 * clients. The BUFF routines don't allow a writev from above,
671 * and don't always memcpy to minimize small write()s, this should
672 * be fixed, but I didn't win much support for the idea on
673 * new-httpd - I'll have to _prove_ its a problem first.. */
675 /* The default behaviour used to be to flush with every write, but this
676 * can tie up the FastCGI server longer than is necessary so its an option now */
677 if (fr
->fs
&& fr
->fs
->flush
) {
678 #ifdef RUSSIAN_APACHE
679 if (ap_rflush(fr
->r
)) {
680 ap_log_rerror(FCGI_LOG_INFO_NOERRNO
, fr
->r
,
681 "FastCGI: client stopped connection before send body completed");
685 if (ap_bflush(fr
->r
->connection
->client
)) {
686 ap_log_rerror(FCGI_LOG_INFO_NOERRNO
, fr
->r
,
687 "FastCGI: client stopped connection before send body completed");
691 ap_reset_timeout(fr
->r
);
694 fcgi_buf_toss(fr
->clientOutputBuffer
, count
);
698 /*******************************************************************************
699 * Determine the user and group the wrapper should be called with.
700 * Based on code in Apache's create_argv_cmd() (util_script.c).
702 static void set_uid_n_gid(request_rec
*r
, const char **user
, const char **group
)
704 if (fcgi_wrapper
== NULL
) {
710 if (strncmp("/~", r
->uri
, 2) == 0) {
711 /* its a user dir uri, just send the ~user, and leave it to the PM */
712 char *end
= strchr(r
->uri
+ 2, '/');
715 *user
= memcpy(ap_pcalloc(r
->pool
, end
- r
->uri
), r
->uri
+ 1, end
- r
->uri
- 1);
717 *user
= ap_pstrdup(r
->pool
, r
->uri
+ 1);
721 *user
= ap_psprintf(r
->pool
, "%ld", (long)r
->server
->server_uid
);
722 *group
= ap_psprintf(r
->pool
, "%ld", (long)r
->server
->server_gid
);
726 /*******************************************************************************
727 * Close the connection to the FastCGI server. This is normally called by
728 * do_work(), but may also be called as in request pool cleanup.
730 static void close_connection_to_fs(fcgi_request
*fr
)
732 pool
*rp
= fr
->r
->pool
;
735 ap_pclosesocket(rp
, fr
->fd
);
740 if (fr
->keepReadingFromFcgiApp
== FALSE
) {
741 /* XXX REQ_COMPLETE is only sent for requests which complete
742 * normally WRT the fcgi app. There is no data sent for
743 * connect() timeouts or requests which complete abnormally.
744 * KillDynamicProcs() and RemoveRecords() need to be looked at
745 * to be sure they can reasonably handle these cases before
746 * sending these sort of stats - theres some funk in there.
747 * XXX We should do something special when this a pool cleanup.
749 if (fcgi_util_gettimeofday(&fr
->completeTime
) < 0) {
750 /* there's no point to aborting the request, just log it */
751 ap_log_error(FCGI_LOG_ERR
, fr
->r
->server
, "FastCGI: can't get time of day");
753 struct timeval qtime
, rtime
;
755 timersub(&fr
->queueTime
, &fr
->startTime
, &qtime
);
756 timersub(&fr
->completeTime
, &fr
->queueTime
, &rtime
);
758 send_to_pm(FCGI_COMPLETE
, fr
->fs_path
,
760 qtime
.tv_sec
* 1000000 + qtime
.tv_usec
,
761 rtime
.tv_sec
* 1000000 + rtime
.tv_usec
);
769 static int set_nonblocking(SOCKET fd
, int nonblocking
)
771 unsigned long ioctl_arg
= (nonblocking
) ? 1 : 0;
772 return ioctlsocket(fd
, FIONBIO
, &ioctl_arg
);
777 static int set_nonblocking(int fd
, int nonblocking
)
780 int fd_flags
= fcntl(fd
, F_GETFL
, 0);
782 if (fd_flags
< 0) return -1;
784 #if defined(O_NONBLOCK)
785 nb_flag
= O_NONBLOCK
;
786 #elif defined(O_NDELAY)
788 #elif defined(FNDELAY)
791 #error "TODO - don't read from app until all data from client is posted."
794 fd_flags
= (nonblocking
) ? (fd_flags
| nb_flag
) : (fd_flags
& ~nb_flag
);
796 return fcntl(fd
, F_SETFL
, fd_flags
);
801 /*******************************************************************************
802 * Connect to the FastCGI server.
804 static int open_connection_to_fs(fcgi_request
*fr
)
807 fd_set write_fds
, read_fds
;
809 request_rec
* const r
= fr
->r
;
810 pool
* const rp
= r
->pool
;
811 const char *socket_path
= NULL
;
812 struct sockaddr
*socket_addr
= NULL
;
813 int socket_addr_len
= 0;
815 const char *err
= NULL
;
818 /* Create the connection point */
821 socket_path
= fcgi_util_socket_hash_filename(rp
, fr
->fs_path
, fr
->user
, fr
->group
);
822 socket_path
= fcgi_util_socket_make_path_absolute(rp
, socket_path
, 1);
825 err
= fcgi_util_socket_make_domain_addr(rp
, (struct sockaddr_un
**)&socket_addr
,
826 &socket_addr_len
, socket_path
);
828 ap_log_rerror(FCGI_LOG_ERR
, r
,
829 "FastCGI: failed to connect to server \"%s\": "
830 "%s", fr
->fs_path
, err
);
838 if (fr
->fs
->dest_addr
!= NULL
) {
839 socket_addr
= fr
->fs
->dest_addr
;
841 else if (fr
->fs
->socket_addr
) {
842 socket_addr
= fr
->fs
->socket_addr
;
845 socket_path
= fr
->fs
->socket_path
;
848 socket_addr
= fr
->fs
->socket_addr
;
850 socket_addr_len
= fr
->fs
->socket_addr_len
;
856 if (fr
->fs
&& fr
->fs
->restartTime
)
858 struct stat sock_stat
;
860 if (stat(socket_path
, &sock_stat
) == 0)
864 if (dynamicAutoUpdate
)
866 struct stat app_stat
;
868 /* TODO: follow sym links */
870 if (stat(fr
->fs_path
, &app_stat
) == 0)
873 if (fr
->fs
->restartTime
< app_stat
.st_mtime
)
875 if (sock_stat
.st_mtime
< app_stat
.st_mtime
)
879 struct timeval tv
= {1, 0};
882 * There's a newer one, request a restart.
884 send_to_pm(FCGI_RESTART
, fr
->fs_path
, fr
->user
, fr
->group
, 0, 0);
889 /* Avoid sleep/alarm interactions */
890 ap_select(0, NULL
, NULL
, NULL
, &tv
);
898 send_to_pm(FCGI_START
, fr
->fs_path
, fr
->user
, fr
->group
, 0, 0);
900 /* Wait until it looks like its running */
907 fr
->fs
= fcgi_util_fs_get_by_id(fr
->fs_path
, 0, 0);
909 if (fr
->fs
&& fr
->fs
->restartTime
)
911 struct timeval tv
= {1, 0};
913 /* Avoid sleep/alarm interactions */
914 ap_select(0, NULL
, NULL
, NULL
, &tv
);
916 if (stat(socket_path
, &sock_stat
) == 0)
932 int max_connect_time
= FCGI_NAMED_PIPE_CONNECT_TIMEOUT
;
934 fr
->using_npipe_io
= TRUE
;
938 interval
= dynamicPleaseStartDelay
* 1000;
940 if (dynamicAppConnectTimeout
) {
941 max_connect_time
= dynamicAppConnectTimeout
;
946 interval
= FCGI_NAMED_PIPE_CONNECT_TIMEOUT
* 1000;
948 if (fr
->fs
->appConnectTimeout
) {
949 max_connect_time
= fr
->fs
->appConnectTimeout
;
953 if (fcgi_util_gettimeofday(&fr
->startTime
) < 0) {
954 ap_log_rerror(FCGI_LOG_ERR
, r
,
955 "FastCGI: failed to connect to server \"%s\": "
956 "can't get time of day", fr
->fs_path
);
962 fr
->fd
= (SOCKET
) CreateFile(socket_path
,
963 GENERIC_READ
| GENERIC_WRITE
,
964 FILE_SHARE_READ
| FILE_SHARE_WRITE
,
965 NULL
, // no security attributes
966 OPEN_EXISTING
, // opens existing pipe
967 FILE_ATTRIBUTE_NORMAL
, // default attributes
968 NULL
); // no template file
970 if (fr
->fd
!= (SOCKET
) INVALID_HANDLE_VALUE
) {
974 if (GetLastError() != ERROR_PIPE_BUSY
975 && GetLastError() != ERROR_FILE_NOT_FOUND
)
977 ap_log_rerror(FCGI_LOG_ERR
, r
,
978 "FastCGI: failed to connect to server \"%s\": "
979 "CreateFile() failed", fr
->fs_path
);
983 // All pipe instances are busy, so wait
984 ready
= WaitNamedPipe(socket_path
, interval
);
986 if (fr
->dynamic
&& !ready
) {
987 send_to_pm(FCGI_TIMEOUT
, fr
->fs_path
, fr
->user
, fr
->group
, 0, 0);
990 if (fcgi_util_gettimeofday(&fr
->queueTime
) < 0) {
991 ap_log_rerror(FCGI_LOG_ERR
, r
,
992 "FastCGI: failed to connect to server \"%s\": "
993 "can't get time of day", fr
->fs_path
);
997 connect_time
= fr
->queueTime
.tv_sec
- fr
->startTime
.tv_sec
;
999 FCGIDBG5("interval=%d, max_connect_time=%d, connect_time=%d, ready=%d", interval
, max_connect_time
, connect_time
, ready
);
1001 } while (connect_time
< max_connect_time
);
1003 if (fr
->fd
== (SOCKET
) INVALID_HANDLE_VALUE
) {
1004 ap_log_rerror(FCGI_LOG_ERR
, r
,
1005 "FastCGI: failed to connect to server \"%s\": "
1006 "CreateFile()/WaitNamedPipe() timed out", fr
->fs_path
);
1010 FCGIDBG2("got_named_pipe_connect: %s", fr
->fs_path
);
1013 ap_note_cleanups_for_h(rp
, (HANDLE
) fr
->fd
);
1014 ap_unblock_alarms();
1020 /* Create the socket */
1021 fr
->fd
= ap_psocket(rp
, socket_addr
->sa_family
, SOCK_STREAM
, 0);
1025 errno
= WSAGetLastError(); // Not sure this is going to work as expected
1027 ap_log_rerror(FCGI_LOG_ERR_ERRNO
, r
,
1028 "FastCGI: failed to connect to server \"%s\": "
1029 "ap_psocket() failed", fr
->fs_path
);
1034 if (fr
->fd
>= FD_SETSIZE
) {
1035 ap_log_rerror(FCGI_LOG_ERR
, r
,
1036 "FastCGI: failed to connect to server \"%s\": "
1037 "socket file descriptor (%u) is larger than "
1038 "FD_SETSIZE (%u), you probably need to rebuild Apache with a "
1039 "larger FD_SETSIZE", fr
->fs_path
, fr
->fd
, FD_SETSIZE
);
1044 /* If appConnectTimeout is non-zero, setup do a non-blocking connect */
1045 if ((fr
->dynamic
&& dynamicAppConnectTimeout
) || (!fr
->dynamic
&& fr
->fs
->appConnectTimeout
)) {
1046 set_nonblocking(fr
->fd
, TRUE
);
1049 if (fr
->dynamic
&& fcgi_util_gettimeofday(&fr
->startTime
) < 0) {
1050 ap_log_rerror(FCGI_LOG_ERR
, r
,
1051 "FastCGI: failed to connect to server \"%s\": "
1052 "can't get time of day", fr
->fs_path
);
1057 if (connect(fr
->fd
, (struct sockaddr
*)socket_addr
, socket_addr_len
) == 0)
1058 goto ConnectionComplete
;
1062 errno
= WSAGetLastError();
1063 if (errno
!= WSAEWOULDBLOCK
) {
1064 ap_log_rerror(FCGI_LOG_ERR_ERRNO
, r
,
1065 "FastCGI: failed to connect to server \"%s\": "
1066 "connect() failed", fr
->fs_path
);
1072 /* ECONNREFUSED means the listen queue is full (or there isn't one).
1073 * With dynamic I can at least make sure the PM knows this is occuring */
1074 if (fr
->dynamic
&& errno
== ECONNREFUSED
) {
1075 /* @@@ This might be better as some other "kind" of message */
1076 send_to_pm(rp
, CONN_TIMEOUT
, fr
->fs_path
, fr
->user
, fr
->group
, 0, 0);
1078 errno
= ECONNREFUSED
;
1081 if (errno
!= EINPROGRESS
) {
1082 ap_log_rerror(FCGI_LOG_ERR
, r
,
1083 "FastCGI: failed to connect to server \"%s\": "
1084 "connect() failed", fr
->fs_path
);
1090 /* The connect() is non-blocking */
1096 FD_ZERO(&write_fds
);
1097 FD_SET(fr
->fd
, &write_fds
);
1098 read_fds
= write_fds
;
1099 tval
.tv_sec
= dynamicPleaseStartDelay
;
1102 status
= ap_select((fr
->fd
+1), &read_fds
, &write_fds
, NULL
, &tval
);
1106 if (fcgi_util_gettimeofday(&fr
->queueTime
) < 0) {
1107 ap_log_rerror(FCGI_LOG_ERR
, r
,
1108 "FastCGI: failed to connect to server \"%s\": "
1109 "can't get time of day", fr
->fs_path
);
1116 /* select() timed out */
1117 send_to_pm(FCGI_TIMEOUT
, fr
->fs_path
, fr
->user
, fr
->group
, 0, 0);
1118 } while ((fr
->queueTime
.tv_sec
- fr
->startTime
.tv_sec
) < (int)dynamicAppConnectTimeout
);
1120 /* XXX These can be moved down when dynamic vars live is a struct */
1122 ap_log_rerror(FCGI_LOG_ERR_NOERRNO
, r
,
1123 "FastCGI: failed to connect to server \"%s\": "
1124 "connect() timed out (appConnTimeout=%dsec)",
1125 fr
->fs_path
, dynamicAppConnectTimeout
);
1130 tval
.tv_sec
= fr
->fs
->appConnectTimeout
;
1132 FD_ZERO(&write_fds
);
1133 FD_SET(fr
->fd
, &write_fds
);
1134 read_fds
= write_fds
;
1136 status
= ap_select((fr
->fd
+1), &read_fds
, &write_fds
, NULL
, &tval
);
1139 ap_log_rerror(FCGI_LOG_ERR_NOERRNO
, r
,
1140 "FastCGI: failed to connect to server \"%s\": "
1141 "connect() timed out (appConnTimeout=%dsec)",
1142 fr
->fs_path
, dynamicAppConnectTimeout
);
1149 errno
= WSAGetLastError();
1151 ap_log_rerror(FCGI_LOG_ERR_ERRNO
, r
,
1152 "FastCGI: failed to connect to server \"%s\": "
1153 "select() failed", fr
->fs_path
);
1157 if (FD_ISSET(fr
->fd
, &write_fds
) || FD_ISSET(fr
->fd
, &read_fds
)) {
1159 NET_SIZE_T len
= sizeof(error
);
1161 if (getsockopt(fr
->fd
, SOL_SOCKET
, SO_ERROR
, (char *)&error
, &len
) < 0) {
1162 /* Solaris pending error */
1164 errno
= WSAGetLastError();
1166 ap_log_rerror(FCGI_LOG_ERR_ERRNO
, r
,
1167 "FastCGI: failed to connect to server \"%s\": "
1168 "select() failed (Solaris pending error)", fr
->fs_path
);
1173 /* Berkeley-derived pending error */
1175 ap_log_rerror(FCGI_LOG_ERR_ERRNO
, r
,
1176 "FastCGI: failed to connect to server \"%s\": "
1177 "select() failed (pending error)", fr
->fs_path
);
1183 errno
= WSAGetLastError();
1185 ap_log_rerror(FCGI_LOG_ERR_ERRNO
, r
,
1186 "FastCGI: failed to connect to server \"%s\": "
1187 "select() error - THIS CAN'T HAPPEN!", fr
->fs_path
);
1192 /* Return to blocking mode if it was set up */
1193 if ((fr
->dynamic
&& dynamicAppConnectTimeout
) || (!fr
->dynamic
&& fr
->fs
->appConnectTimeout
)) {
1194 set_nonblocking(fr
->fd
, FALSE
);
1198 if (socket_addr
->sa_family
== AF_INET
) {
1199 /* We shouldn't be sending small packets and there's no application
1200 * level ack of the data we send, so disable Nagle */
1202 setsockopt(fr
->fd
, IPPROTO_TCP
, TCP_NODELAY
, (char *)&set
, sizeof(set
));
1209 static int server_error(fcgi_request
*fr
)
1211 #if defined(SIGPIPE) && MODULE_MAGIC_NUMBER < 19990320
1212 /* Make sure we leave with Apache's sigpipe_handler in place */
1213 if (fr
->apache_sigpipe_handler
!= NULL
)
1214 signal(SIGPIPE
, fr
->apache_sigpipe_handler
);
1216 close_connection_to_fs(fr
);
1217 ap_kill_timeout(fr
->r
);
1218 return SERVER_ERROR
;
1221 static void cleanup(void *data
)
1223 const fcgi_request
* const fr
= (fcgi_request
*)data
;
1229 set_nonblocking(fr
->fd
, FALSE
);
1232 if (fr
->fs_stderr_len
) {
1233 ap_log_rerror(FCGI_LOG_ERR_NOERRNO
, fr
->r
,
1234 "FastCGI: server \"%s\" stderr: %s", fr
->fs_path
, fr
->fs_stderr
);
1238 /*----------------------------------------------------------------------
1239 * This is the core routine for moving data between the FastCGI
1240 * application and the Web server's client.
1242 static int do_work(request_rec
*r
, fcgi_request
*fr
)
1244 struct timeval timeOut
, dynamic_last_activity_time
= {0, 0};
1245 fd_set read_set
, write_set
;
1246 int status
= 0, idle_timeout
;
1247 int numFDs
, dynamic_first_read
= fr
->dynamic
? 1 : 0;
1249 int envSent
= FALSE
; /* has the complete ENV been buffered? */
1252 const char *err
= NULL
;
1255 FD_ZERO(&write_set
);
1257 fcgi_protocol_queue_begin_request(fr
);
1259 /* Buffer as much of the environment as we can fit */
1261 envSent
= fcgi_protocol_queue_env(r
, fr
, &env
);
1263 /* Start the Apache dropdead timer. See comments at top of file. */
1264 ap_hard_timeout("buffering of FastCGI client data", r
);
1266 /* Read as much as possible from the client. */
1267 if (fr
->role
== FCGI_RESPONDER
) {
1268 status
= ap_setup_client_block(r
, REQUEST_CHUNKED_ERROR
);
1273 fr
->expectingClientContent
= (ap_should_client_block(r
) != 0);
1275 if (read_from_client_n_queue(fr
) != OK
)
1276 return server_error(fr
);
1279 /* Connect to the FastCGI Application */
1280 ap_hard_timeout("connect() to FastCGI server", r
);
1281 if (open_connection_to_fs(fr
) != FCGI_OK
) {
1282 return server_error(fr
);
1285 numFDs
= fr
->fd
+ 1;
1286 idle_timeout
= fr
->dynamic
? dynamic_idle_timeout
: fr
->fs
->idle_timeout
;
1288 if (dynamic_first_read
) {
1289 dynamic_last_activity_time
= fr
->startTime
;
1291 if (dynamicAppConnectTimeout
) {
1292 struct timeval qwait
;
1293 timersub(&fr
->queueTime
, &fr
->startTime
, &qwait
);
1294 dynamic_first_read
= qwait
.tv_sec
/ dynamicPleaseStartDelay
+ 1;
1298 /* @@@ We never reset the timer in this loop, most folks don't mess w/
1299 * Timeout directive which means we've got the 5 min default which is way
1300 * to long to tie up a fs. We need a better/configurable solution that
1301 * uses the select */
1302 ap_hard_timeout("FastCGI request processing", r
);
1304 /* Register to get the script's stderr logged at the end of the request */
1306 ap_register_cleanup(rp
, (void *)fr
, cleanup
, ap_null_cleanup
);
1307 ap_unblock_alarms();
1309 /* Before we do any writing, set the connection non-blocking */
1311 if (fr
->using_npipe_io
) {
1312 DWORD mode
= PIPE_NOWAIT
| PIPE_READMODE_BYTE
;
1313 SetNamedPipeHandleState((HANDLE
) fr
->fd
, &mode
, NULL
, NULL
);
1318 set_nonblocking(fr
->fd
, TRUE
);
1320 /* The socket is writeable, so get the first write out of the way */
1321 if (fcgi_buf_get_to_fd(fr
->serverOutputBuffer
, fr
->fd
) < 0) {
1323 if (! fr
->using_npipe_io
)
1324 ap_log_rerror(FCGI_LOG_ERR_ERRNO
, r
,
1325 "FastCGI: comm with server \"%s\" aborted: write failed", fr
->fs_path
);
1328 ap_log_rerror(FCGI_LOG_ERR
, r
,
1329 "FastCGI: comm with server \"%s\" aborted: write failed", fr
->fs_path
);
1330 return server_error(fr
);
1333 while (fr
->keepReadingFromFcgiApp
1334 || BufferLength(fr
->serverInputBuffer
) > 0
1335 || BufferLength(fr
->clientOutputBuffer
) > 0) {
1337 /* If we didn't buffer all of the environment yet, buffer some more */
1339 envSent
= fcgi_protocol_queue_env(r
, fr
, &env
);
1341 /* Read as much as possible from the client. */
1342 if (fr
->role
== FCGI_RESPONDER
&& !fr
->eofSent
&& envSent
) {
1344 /* ap_get_client_block() (called in read_from_client_n_queue()
1345 * can't handle a non-blocking fd, its a bummer. We might be
1346 * able to completely bypass the Apache BUFF routines in still
1347 * do it, but thats a major hassle. Apache 2.X will handle it,
1348 * and then so will we. */
1350 if (read_from_client_n_queue(fr
) != OK
)
1351 return server_error(fr
);
1354 /* To avoid deadlock, don't do a blocking select to write to
1355 * the FastCGI application without selecting to read from the
1356 * FastCGI application.
1358 doClientWrite
= FALSE
;
1359 if (fr
->keepReadingFromFcgiApp
&& BufferFree(fr
->serverInputBuffer
) > 0) {
1362 DWORD bytesavail
= 0;
1364 if (!fr
->using_npipe_io
) {
1366 FD_SET(fr
->fd
, &read_set
);
1368 /* Is data buffered for output to the FastCGI server? */
1369 if (BufferLength(fr
->serverOutputBuffer
) > 0) {
1370 FD_SET(fr
->fd
, &write_set
);
1372 FD_CLR(fr
->fd
, &write_set
);
1378 * If there's data buffered to send to the client, don't
1379 * wait indefinitely for the FastCGI app; the app might
1380 * be doing server push.
1382 if (BufferLength(fr
->clientOutputBuffer
) > 0) {
1384 timeOut
.tv_usec
= 100000; /* 0.1 sec */
1386 else if (dynamic_first_read
) {
1388 struct timeval qwait
;
1390 if (fcgi_util_gettimeofday(&fr
->queueTime
) < 0) {
1391 ap_log_rerror(FCGI_LOG_ERR
, r
, "FastCGI: can't get time of day");
1392 return server_error(fr
);
1395 /* Check for idle_timeout */
1397 dynamic_last_activity_time
= fr
->queueTime
;
1400 struct timeval idle_time
;
1401 timersub(&fr
->queueTime
, &dynamic_last_activity_time
, &idle_time
);
1402 if (idle_time
.tv_sec
> idle_timeout
) {
1403 send_to_pm(FCGI_TIMEOUT
, fr
->fs_path
, fr
->user
, fr
->group
, 0, 0);
1404 ap_log_rerror(FCGI_LOG_ERR_NOERRNO
, r
,
1405 "FastCGI: comm with (dynamic) server \"%s\" aborted: (first read) idle timeout (%d sec)",
1406 fr
->fs_path
, idle_timeout
);
1407 return server_error(fr
);
1411 timersub(&fr
->queueTime
, &fr
->startTime
, &qwait
);
1413 delay
= dynamic_first_read
* dynamicPleaseStartDelay
;
1414 if (qwait
.tv_sec
< delay
) {
1415 timeOut
.tv_sec
= delay
;
1416 timeOut
.tv_usec
= 100000; /* fudge for select() slop */
1417 timersub(&timeOut
, &qwait
, &timeOut
);
1420 /* Killed time somewhere.. client read? */
1421 send_to_pm(FCGI_TIMEOUT
, fr
->fs_path
, fr
->user
, fr
->group
, 0, 0);
1422 dynamic_first_read
= qwait
.tv_sec
/ dynamicPleaseStartDelay
+ 1;
1423 timeOut
.tv_sec
= dynamic_first_read
* dynamicPleaseStartDelay
;
1424 timeOut
.tv_usec
= 100000; /* fudge for select() slop */
1425 timersub(&timeOut
, &qwait
, &timeOut
);
1429 timeOut
.tv_sec
= idle_timeout
;
1430 timeOut
.tv_usec
= 0;
1434 if (!fr
->using_npipe_io
) {
1436 if ((status
= ap_select(numFDs
, &read_set
, &write_set
, NULL
, &timeOut
)) < 0) {
1438 errno
= WSAGetLastError();
1440 ap_log_rerror(FCGI_LOG_ERR_ERRNO
, r
,
1441 "FastCGI: comm with server \"%s\" aborted: select() failed", fr
->fs_path
);
1442 return server_error(fr
);
1447 int stopTime
= time(NULL
) + timeOut
.tv_sec
;
1449 if (BufferLength(fr
->serverOutputBuffer
) == 0)
1453 while ((timeOut
.tv_sec
!= 0) && (time(NULL
) <= stopTime
))
1455 BOOL ok
= PeekNamedPipe((HANDLE
) fr
->fd
,NULL
, 0, NULL
, &bytesavail
, NULL
);
1458 ap_log_rerror(FCGI_LOG_ERR
, r
,
1459 "FastCGI: comm with sever \"%s\" aborted: PeekNamedPipe() failed",
1461 return server_error(fr
);
1478 if (BufferLength(fr
->clientOutputBuffer
) > 0) {
1479 doClientWrite
= TRUE
;
1481 else if (dynamic_first_read
) {
1482 struct timeval qwait
;
1484 if (fcgi_util_gettimeofday(&fr
->queueTime
) < 0) {
1485 ap_log_rerror(FCGI_LOG_ERR
, r
, "FastCGI: can't get time of day");
1486 return server_error(fr
);
1489 timersub(&fr
->queueTime
, &fr
->startTime
, &qwait
);
1491 send_to_pm(FCGI_TIMEOUT
, fr
->fs_path
, fr
->user
, fr
->group
, 0, 0);
1493 dynamic_first_read
= qwait
.tv_sec
/ dynamicPleaseStartDelay
+ 1;
1496 ap_log_rerror(FCGI_LOG_ERR_NOERRNO
, r
,
1497 "FastCGI: comm with server \"%s\" aborted: idle timeout (%d sec)",
1498 fr
->fs_path
, idle_timeout
);
1499 return server_error(fr
);
1503 #if defined(SIGPIPE) && MODULE_MAGIC_NUMBER < 19990320
1504 /* Disable Apache's SIGPIPE handler */
1505 fr
->apache_sigpipe_handler
= signal(SIGPIPE
, SIG_IGN
);
1508 /* Read from the FastCGI server */
1510 if ((fr
->using_npipe_io
1511 && (BufferFree(fr
->serverInputBuffer
) > 0)
1512 && PeekNamedPipe((HANDLE
) fr
->fd
, NULL
, 0, NULL
, &bytesavail
, NULL
)
1513 && (bytesavail
> 0))
1514 || FD_ISSET(fr
->fd
, &read_set
)) {
1516 if (FD_ISSET(fr
->fd
, &read_set
)) {
1518 if (dynamic_first_read
) {
1519 dynamic_first_read
= 0;
1520 if (fcgi_util_gettimeofday(&fr
->queueTime
) < 0) {
1521 ap_log_rerror(FCGI_LOG_ERR
, r
, "FastCGI: can't get time of day");
1522 return server_error(fr
);
1526 if ((status
= fcgi_buf_add_fd(fr
->serverInputBuffer
, fr
->fd
)) < 0) {
1528 if (! fr
->using_npipe_io
)
1529 ap_log_rerror(FCGI_LOG_ERR_ERRNO
, r
,
1530 "FastCGI: comm with server \"%s\" aborted: read failed", fr
->fs_path
);
1533 ap_log_rerror(FCGI_LOG_ERR
, r
,
1534 "FastCGI: comm with server \"%s\" aborted: read failed", fr
->fs_path
);
1535 return server_error(fr
);
1539 fr
->keepReadingFromFcgiApp
= FALSE
;
1540 close_connection_to_fs(fr
);
1544 /* Write to the FastCGI server */
1546 if ((fr
->using_npipe_io
&& (BufferLength(fr
->serverOutputBuffer
) > 0))
1547 || FD_ISSET(fr
->fd
, &write_set
)) {
1549 if (FD_ISSET(fr
->fd
, &write_set
)) {
1552 if (fcgi_buf_get_to_fd(fr
->serverOutputBuffer
, fr
->fd
) < 0) {
1554 if (! fr
->using_npipe_io
)
1555 ap_log_rerror(FCGI_LOG_ERR_ERRNO
, r
,
1556 "FastCGI: comm with server \"%s\" aborted: write failed", fr
->fs_path
);
1559 ap_log_rerror(FCGI_LOG_ERR
, r
,
1560 "FastCGI: comm with server \"%s\" aborted: write failed", fr
->fs_path
);
1561 return server_error(fr
);
1565 #if defined(SIGPIPE) && MODULE_MAGIC_NUMBER < 19990320
1566 /* Reinstall Apache's SIGPIPE handler */
1567 signal(SIGPIPE
, fr
->apache_sigpipe_handler
);
1571 doClientWrite
= TRUE
;
1574 if (fr
->role
== FCGI_RESPONDER
&& doClientWrite
) {
1576 if (write_to_client(fr
) != OK
) {
1577 #if defined(SIGPIPE) && MODULE_MAGIC_NUMBER < 19990320
1578 /* Make sure we leave with Apache's sigpipe_handler in place */
1579 if (fr
->apache_sigpipe_handler
!= NULL
)
1580 signal(SIGPIPE
, fr
->apache_sigpipe_handler
);
1582 close_connection_to_fs(fr
);
1583 ap_kill_timeout(fr
->r
);
1588 if (fcgi_protocol_dequeue(rp
, fr
) != OK
)
1589 return server_error(fr
);
1591 if (fr
->keepReadingFromFcgiApp
&& fr
->exitStatusSet
) {
1592 /* we're done talking to the fcgi app */
1593 fr
->keepReadingFromFcgiApp
= FALSE
;
1594 close_connection_to_fs(fr
);
1597 if (fr
->parseHeader
== SCAN_CGI_READING_HEADERS
) {
1598 if ((err
= process_headers(r
, fr
))) {
1599 ap_log_rerror(FCGI_LOG_ERR_NOERRNO
, r
,
1600 "FastCGI: comm with server \"%s\" aborted: error parsing headers: %s", fr
->fs_path
, err
);
1601 return server_error(fr
);
1607 switch (fr
->parseHeader
) {
1609 case SCAN_CGI_FINISHED
:
1610 if (fr
->role
== FCGI_RESPONDER
) {
1611 #ifdef RUSSIAN_APACHE
1614 ap_bflush(r
->connection
->client
);
1616 ap_bgetopt(r
->connection
->client
, BO_BYTECT
, &r
->bytes_sent
);
1620 case SCAN_CGI_READING_HEADERS
:
1621 ap_log_rerror(FCGI_LOG_ERR_NOERRNO
, r
,
1622 "FastCGI: incomplete headers (%d bytes) received from server \"%s\"",
1623 fr
->header
->nelts
, fr
->fs_path
);
1624 return server_error(fr
);
1626 case SCAN_CGI_BAD_HEADER
:
1627 return server_error(fr
);
1629 case SCAN_CGI_INT_REDIRECT
:
1630 case SCAN_CGI_SRV_REDIRECT
:
1632 * XXX We really should be soaking all client input
1633 * and all script output. See mod_cgi.c.
1634 * There's other differences we need to pick up here as well!
1635 * This has to be revisited.
1648 static fcgi_request
*create_fcgi_request(request_rec
* const r
, const char *fs_path
)
1650 struct stat
*my_finfo
;
1651 pool
* const p
= r
->pool
;
1653 fcgi_request
* const fr
= (fcgi_request
*)ap_pcalloc(p
, sizeof(fcgi_request
));
1656 my_finfo
= (struct stat
*)ap_palloc(p
, sizeof(struct stat
));
1657 if (stat(fs_path
, my_finfo
) < 0) {
1658 ap_log_rerror(FCGI_LOG_ERR_ERRNO
, r
,
1659 "FastCGI: stat() of \"%s\" failed", fs_path
);
1664 my_finfo
= &r
->finfo
;
1665 fs_path
= r
->filename
;
1668 fs
= fcgi_util_fs_get_by_id(fs_path
, r
->server
->server_uid
, r
->server
->server_gid
);
1670 /* Its a request for a dynamic FastCGI application */
1671 const char * const err
=
1672 fcgi_util_fs_is_path_ok(p
, fs_path
, my_finfo
);
1675 ap_log_rerror(FCGI_LOG_ERR_NOERRNO
, r
, "FastCGI: invalid (dynamic) server \"%s\": %s", fs_path
, err
);
1680 fr
->serverInputBuffer
= fcgi_buf_new(p
, SERVER_BUFSIZE
);
1681 fr
->serverOutputBuffer
= fcgi_buf_new(p
, SERVER_BUFSIZE
);
1682 fr
->clientInputBuffer
= fcgi_buf_new(p
, SERVER_BUFSIZE
);
1683 fr
->clientOutputBuffer
= fcgi_buf_new(p
, SERVER_BUFSIZE
);
1684 fr
->erBufPtr
= fcgi_buf_new(p
, sizeof(FCGI_EndRequestBody
) + 1);
1685 fr
->gotHeader
= FALSE
;
1686 fr
->parseHeader
= SCAN_CGI_READING_HEADERS
;
1687 fr
->header
= ap_make_array(p
, 1, 1);
1688 fr
->fs_stderr
= NULL
;
1690 fr
->readingEndRequestBody
= FALSE
;
1692 fr
->exitStatusSet
= FALSE
;
1693 fr
->requestId
= 1; /* anything but zero is OK here */
1694 fr
->eofSent
= FALSE
;
1695 fr
->role
= FCGI_RESPONDER
;
1696 fr
->expectingClientContent
= FALSE
;
1697 fr
->keepReadingFromFcgiApp
= TRUE
;
1699 fr
->fs_path
= fs_path
;
1700 fr
->authHeaders
= ap_make_table(p
, 10);
1702 fr
->fd
= INVALID_SOCKET
;
1703 fr
->dynamic
= ((fs
== NULL
) || (fs
->directive
== APP_CLASS_DYNAMIC
)) ? TRUE
: FALSE
;
1704 fr
->using_npipe_io
= FALSE
;
1706 fr
->dynamic
= (fs
== NULL
) ? TRUE
: FALSE
;
1711 set_uid_n_gid(r
, &fr
->user
, &fr
->group
);
1717 *----------------------------------------------------------------------
1721 * This routine gets called for a request that corresponds to
1722 * a FastCGI connection. It performs the request synchronously.
1725 * Final status of request: OK or NOT_FOUND or SERVER_ERROR.
1728 * Request performed.
1730 *----------------------------------------------------------------------
1733 /* Stolen from mod_cgi.c..
1734 * KLUDGE --- for back-combatibility, we don't have to check ExecCGI
1735 * in ScriptAliased directories, which means we need to know if this
1736 * request came through ScriptAlias or not... so the Alias module
1737 * leaves a note for us.
1739 static int apache_is_scriptaliased(request_rec
*r
)
1741 const char *t
= ap_table_get(r
->notes
, "alias-forced-type");
1742 return t
&& (!strcasecmp(t
, "cgi-script"));
1745 /* If a script wants to produce its own Redirect body, it now
1746 * has to explicitly *say* "Status: 302". If it wants to use
1747 * Apache redirects say "Status: 200". See process_headers().
1749 static int post_process_for_redirects(request_rec
* const r
,
1750 const fcgi_request
* const fr
)
1752 switch(fr
->parseHeader
) {
1753 case SCAN_CGI_INT_REDIRECT
:
1755 /* @@@ There are still differences between the handling in
1756 * mod_cgi and mod_fastcgi. This needs to be revisited.
1758 /* We already read the message body (if any), so don't allow
1759 * the redirected request to think it has one. We can ignore
1760 * Transfer-Encoding, since we used REQUEST_CHUNKED_ERROR.
1763 r
->method_number
= M_GET
;
1764 ap_table_unset(r
->headers_in
, "Content-length");
1766 ap_internal_redirect_handler(ap_table_get(r
->headers_out
, "Location"), r
);
1769 case SCAN_CGI_SRV_REDIRECT
:
1777 /******************************************************************************
1778 * Process fastcgi-script requests. Based on mod_cgi::cgi_handler().
1780 static int content_handler(request_rec
*r
)
1782 fcgi_request
*fr
= NULL
;
1785 /* Setup a new FastCGI request */
1786 if ((fr
= create_fcgi_request(r
, NULL
)) == NULL
)
1787 return SERVER_ERROR
;
1789 /* If its a dynamic invocation, make sure scripts are OK here */
1790 if (fr
->dynamic
&& !(ap_allow_options(r
) & OPT_EXECCGI
) && !apache_is_scriptaliased(r
)) {
1791 ap_log_rerror(FCGI_LOG_ERR_NOERRNO
, r
,
1792 "FastCGI: \"ExecCGI Option\" is off in this directory: %s", r
->uri
);
1793 return SERVER_ERROR
;
1796 /* Process the fastcgi-script request */
1797 if ((ret
= do_work(r
, fr
)) != OK
)
1800 /* Special case redirects */
1801 return post_process_for_redirects(r
, fr
);
1805 static int post_process_auth_passed_header(table
*t
, const char *key
, const char * const val
)
1807 if (strncasecmp(key
, "Variable-", 9) == 0)
1810 ap_table_setn(t
, key
, val
);
1814 static int post_process_auth_passed_compat_header(table
*t
, const char *key
, const char * const val
)
1816 if (strncasecmp(key
, "Variable-", 9) == 0)
1817 ap_table_setn(t
, key
+ 9, val
);
1822 static int post_process_auth_failed_header(table
* const t
, const char * const key
, const char * const val
)
1824 ap_table_setn(t
, key
, val
);
1828 static void post_process_auth(fcgi_request
* const fr
, const int passed
)
1830 request_rec
* const r
= fr
->r
;
1832 /* Restore the saved subprocess_env because we muddied ours up */
1833 r
->subprocess_env
= fr
->saved_subprocess_env
;
1836 if (fr
->auth_compat
) {
1837 ap_table_do((int (*)(void *, const char *, const char *))post_process_auth_passed_compat_header
,
1838 (void *)r
->subprocess_env
, fr
->authHeaders
, NULL
);
1841 ap_table_do((int (*)(void *, const char *, const char *))post_process_auth_passed_header
,
1842 (void *)r
->subprocess_env
, fr
->authHeaders
, NULL
);
1846 ap_table_do((int (*)(void *, const char *, const char *))post_process_auth_failed_header
,
1847 (void *)r
->err_headers_out
, fr
->authHeaders
, NULL
);
1850 /* @@@ Restore these.. its a hack until I rewrite the header handling */
1851 r
->status
= HTTP_OK
;
1852 r
->status_line
= NULL
;
1855 static int check_user_authentication(request_rec
*r
)
1857 int res
, authenticated
= 0;
1858 const char *password
;
1860 const fcgi_dir_config
* const dir_config
=
1861 (const fcgi_dir_config
*)ap_get_module_config(r
->per_dir_config
, &fastcgi_module
);
1863 if (dir_config
->authenticator
== NULL
)
1866 /* Get the user password */
1867 if ((res
= ap_get_basic_auth_pw(r
, &password
)) != OK
)
1870 if ((fr
= create_fcgi_request(r
, dir_config
->authenticator
)) == NULL
)
1871 return SERVER_ERROR
;
1873 /* Save the existing subprocess_env, because we're gonna muddy it up */
1874 fr
->saved_subprocess_env
= ap_copy_table(r
->pool
, r
->subprocess_env
);
1876 ap_table_setn(r
->subprocess_env
, "REMOTE_PASSWD", password
);
1877 ap_table_setn(r
->subprocess_env
, "FCGI_APACHE_ROLE", "AUTHENTICATOR");
1879 /* The FastCGI Protocol doesn't differentiate authentication */
1880 fr
->role
= FCGI_AUTHORIZER
;
1882 /* Do we need compatibility mode? */
1883 fr
->auth_compat
= (dir_config
->authenticator_options
& FCGI_COMPAT
);
1885 if ((res
= do_work(r
, fr
)) != OK
)
1886 goto AuthenticationFailed
;
1888 authenticated
= (r
->status
== 200);
1889 post_process_auth(fr
, authenticated
);
1891 /* A redirect shouldn't be allowed during the authentication phase */
1892 if (ap_table_get(r
->headers_out
, "Location") != NULL
) {
1893 ap_log_rerror(FCGI_LOG_ERR_NOERRNO
, r
,
1894 "FastCGI: FastCgiAuthenticator \"%s\" redirected (not allowed)",
1895 dir_config
->authenticator
);
1896 goto AuthenticationFailed
;
1902 AuthenticationFailed
:
1903 if (!(dir_config
->authenticator_options
& FCGI_AUTHORITATIVE
))
1906 /* @@@ Probably should support custom_responses */
1907 ap_note_basic_auth_failure(r
);
1908 ap_log_rerror(FCGI_LOG_ERR_NOERRNO
, r
,
1909 "FastCGI: authentication failed for user \"%s\": %s", r
->connection
->user
, r
->uri
);
1910 return (res
== OK
) ? AUTH_REQUIRED
: res
;
1913 static int check_user_authorization(request_rec
*r
)
1915 int res
, authorized
= 0;
1917 const fcgi_dir_config
* const dir_config
=
1918 (const fcgi_dir_config
*)ap_get_module_config(r
->per_dir_config
, &fastcgi_module
);
1920 if (dir_config
->authorizer
== NULL
)
1923 /* @@@ We should probably honor the existing parameters to the require directive
1924 * as well as allow the definition of new ones (or use the basename of the
1925 * FastCGI server and pass the rest of the directive line), but for now keep
1928 if ((fr
= create_fcgi_request(r
, dir_config
->authorizer
)) == NULL
)
1929 return SERVER_ERROR
;
1931 /* Save the existing subprocess_env, because we're gonna muddy it up */
1932 fr
->saved_subprocess_env
= ap_copy_table(r
->pool
, r
->subprocess_env
);
1934 ap_table_setn(r
->subprocess_env
, "FCGI_APACHE_ROLE", "AUTHORIZER");
1936 fr
->role
= FCGI_AUTHORIZER
;
1938 /* Do we need compatibility mode? */
1939 fr
->auth_compat
= (dir_config
->authenticator_options
& FCGI_COMPAT
);
1941 if ((res
= do_work(r
, fr
)) != OK
)
1942 goto AuthorizationFailed
;
1944 authorized
= (r
->status
== 200);
1945 post_process_auth(fr
, authorized
);
1947 /* A redirect shouldn't be allowed during the authorization phase */
1948 if (ap_table_get(r
->headers_out
, "Location") != NULL
) {
1949 ap_log_rerror(FCGI_LOG_ERR_NOERRNO
, r
,
1950 "FastCGI: FastCgiAuthorizer \"%s\" redirected (not allowed)",
1951 dir_config
->authorizer
);
1952 goto AuthorizationFailed
;
1958 AuthorizationFailed
:
1959 if (!(dir_config
->authorizer_options
& FCGI_AUTHORITATIVE
))
1962 /* @@@ Probably should support custom_responses */
1963 ap_note_basic_auth_failure(r
);
1964 ap_log_rerror(FCGI_LOG_ERR_NOERRNO
, r
,
1965 "FastCGI: authorization failed for user \"%s\": %s", r
->connection
->user
, r
->uri
);
1966 return (res
== OK
) ? AUTH_REQUIRED
: res
;
1969 static int check_access(request_rec
*r
)
1971 int res
, access_allowed
= 0;
1973 const fcgi_dir_config
* const dir_config
=
1974 (fcgi_dir_config
*)ap_get_module_config(r
->per_dir_config
, &fastcgi_module
);
1976 if (dir_config
== NULL
|| dir_config
->access_checker
== NULL
)
1979 if ((fr
= create_fcgi_request(r
, dir_config
->access_checker
)) == NULL
)
1980 return SERVER_ERROR
;
1982 /* Save the existing subprocess_env, because we're gonna muddy it up */
1983 fr
->saved_subprocess_env
= ap_copy_table(r
->pool
, r
->subprocess_env
);
1985 ap_table_setn(r
->subprocess_env
, "FCGI_APACHE_ROLE", "ACCESS_CHECKER");
1987 /* The FastCGI Protocol doesn't differentiate access control */
1988 fr
->role
= FCGI_AUTHORIZER
;
1990 /* Do we need compatibility mode? */
1991 fr
->auth_compat
= (dir_config
->authenticator_options
& FCGI_COMPAT
);
1993 if ((res
= do_work(r
, fr
)) != OK
)
1996 access_allowed
= (r
->status
== 200);
1997 post_process_auth(fr
, access_allowed
);
1999 /* A redirect shouldn't be allowed during the access check phase */
2000 if (ap_table_get(r
->headers_out
, "Location") != NULL
) {
2001 ap_log_rerror(FCGI_LOG_ERR_NOERRNO
, r
,
2002 "FastCGI: FastCgiAccessChecker \"%s\" redirected (not allowed)",
2003 dir_config
->access_checker
);
2011 if (!(dir_config
->access_checker_options
& FCGI_AUTHORITATIVE
))
2014 /* @@@ Probably should support custom_responses */
2015 ap_log_rerror(FCGI_LOG_ERR_NOERRNO
, r
, "FastCGI: access denied: %s", r
->uri
);
2016 return (res
== OK
) ? FORBIDDEN
: res
;
2021 command_rec fastcgi_cmds
[] = {
2022 { "AppClass", fcgi_config_new_static_server
, NULL
, RSRC_CONF
, RAW_ARGS
, NULL
},
2023 { "FastCgiServer", fcgi_config_new_static_server
, NULL
, RSRC_CONF
, RAW_ARGS
, NULL
},
2025 { "ExternalAppClass", fcgi_config_new_external_server
, NULL
, RSRC_CONF
, RAW_ARGS
, NULL
},
2026 { "FastCgiExternalServer", fcgi_config_new_external_server
, NULL
, RSRC_CONF
, RAW_ARGS
, NULL
},
2028 { "FastCgiIpcDir", fcgi_config_set_socket_dir
, NULL
, RSRC_CONF
, TAKE1
, NULL
},
2030 { "FastCgiSuexec", fcgi_config_set_wrapper
, NULL
, RSRC_CONF
, TAKE1
, NULL
},
2031 { "FastCgiWrapper", fcgi_config_set_wrapper
, NULL
, RSRC_CONF
, TAKE1
, NULL
},
2033 { "FCGIConfig", fcgi_config_set_config
, NULL
, RSRC_CONF
, RAW_ARGS
, NULL
},
2034 { "FastCgiConfig", fcgi_config_set_config
, NULL
, RSRC_CONF
, RAW_ARGS
, NULL
},
2036 { "FastCgiAuthenticator", fcgi_config_new_auth_server
,
2037 (void *)FCGI_AUTH_TYPE_AUTHENTICATOR
, ACCESS_CONF
, TAKE12
,
2038 "a fastcgi-script path (absolute or relative to ServerRoot) followed by an optional -compat" },
2039 { "FastCgiAuthenticatorAuthoritative", fcgi_config_set_authoritative_slot
,
2040 (void *)XtOffsetOf(fcgi_dir_config
, authenticator_options
), ACCESS_CONF
, FLAG
,
2041 "Set to 'off' to allow authentication to be passed along to lower modules upon failure" },
2043 { "FastCgiAuthorizer", fcgi_config_new_auth_server
,
2044 (void *)FCGI_AUTH_TYPE_AUTHORIZER
, ACCESS_CONF
, TAKE12
,
2045 "a fastcgi-script path (absolute or relative to ServerRoot) followed by an optional -compat" },
2046 { "FastCgiAuthorizerAuthoritative", fcgi_config_set_authoritative_slot
,
2047 (void *)XtOffsetOf(fcgi_dir_config
, authorizer_options
), ACCESS_CONF
, FLAG
,
2048 "Set to 'off' to allow authorization to be passed along to lower modules upon failure" },
2050 { "FastCgiAccessChecker", fcgi_config_new_auth_server
,
2051 (void *)FCGI_AUTH_TYPE_ACCESS_CHECKER
, ACCESS_CONF
, TAKE12
,
2052 "a fastcgi-script path (absolute or relative to ServerRoot) followed by an optional -compat" },
2053 { "FastCgiAccessCheckerAuthoritative", fcgi_config_set_authoritative_slot
,
2054 (void *)XtOffsetOf(fcgi_dir_config
, access_checker_options
), ACCESS_CONF
, FLAG
,
2055 "Set to 'off' to allow access control to be passed along to lower modules upon failure" },
2060 handler_rec fastcgi_handlers
[] = {
2061 { FCGI_MAGIC_TYPE
, content_handler
},
2062 { "fastcgi-script", content_handler
},
2067 module MODULE_VAR_EXPORT fastcgi_module
= {
2068 STANDARD_MODULE_STUFF
,
2069 init_module
, /* initializer */
2070 fcgi_config_create_dir_config
, /* per-dir config creator */
2071 NULL
, /* per-dir config merger (default: override) */
2072 NULL
, /* per-server config creator */
2073 NULL
, /* per-server config merger (default: override) */
2074 fastcgi_cmds
, /* command table */
2075 fastcgi_handlers
, /* [9] content handlers */
2076 NULL
, /* [2] URI-to-filename translation */
2077 check_user_authentication
, /* [5] authenticate user_id */
2078 check_user_authorization
, /* [6] authorize user_id */
2079 check_access
, /* [4] check access (based on src & http headers) */
2080 NULL
, /* [7] check/set MIME type */
2081 NULL
, /* [8] fixups */
2082 NULL
, /* [10] logger */
2083 NULL
, /* [3] header-parser */
2084 fcgi_child_init
, /* process initialization */
2085 fcgi_child_exit
, /* process exit/cleanup */
2086 NULL
/* [1] post read-request handling */