4 * Apache server module for FastCGI.
6 * $Id: mod_fastcgi.c,v 1.121 2002/02/12 03:20:53 robs Exp $
8 * Copyright (c) 1995-1996 Open Market, Inc.
10 * See the file "LICENSE.TERMS" for information on usage and redistribution
11 * of this file, and for a DISCLAIMER OF ALL WARRANTIES.
14 * Patches for Apache-1.1 provided by
18 * Patches for Linux provided by
20 * <langles@vote-smart.org>
22 * Patches for suexec handling by
23 * Brian Grossman <brian@SoftHome.net> and
24 * Rob Saccoccio <robs@ipass.net>
28 * Module design notes.
32 * mod_fastcgi spawns several processes: one process manager process
33 * and several application processes. None of these processes
34 * handle SIGHUP, so they just go away when the Web server performs
35 * a restart (as Apache does every time it starts.)
37 * In order to allow the process manager to properly cleanup the
38 * running fastcgi processes (without being disturbed by Apache),
39 * an intermediate process was introduced. The diagram is as follows;
41 * ApacheWS --> MiddleProc --> ProcMgr --> FCGI processes
43 * On a restart, ApacheWS sends a SIGKILL to MiddleProc and then
44 * collects it via waitpid(). The ProcMgr periodically checks for
45 * its parent (via getppid()) and if it does not have one, as in
46 * case when MiddleProc has terminated, ProcMgr issues a SIGTERM
47 * to all FCGI processes, waitpid()s on them and then exits, so it
48 * can be collected by init(1). Doing it any other way (short of
49 * changing Apache API), results either in inconsistent results or
50 * in generation of zombie processes.
52 * XXX: How does Apache 1.2 implement "gentle" restart
53 * that does not disrupt current connections? How does
54 * gentle restart interact with restart cleanup?
56 * 2. Request timeouts.
58 * Earlier versions of this module used ap_soft_timeout() rather than
59 * ap_hard_timeout() and ate FastCGI server output until it completed.
60 * This precluded the FastCGI server from having to implement a
61 * SIGPIPE handler, but meant hanging the application longer than
62 * necessary. SIGPIPE handler now must be installed in ALL FastCGI
63 * applications. The handler should abort further processing and go
64 * back into the accept() loop.
66 * Although using ap_soft_timeout() is better than ap_hard_timeout()
67 * we have to be more careful about SIGINT handling and subsequent
68 * processing, so, for now, make it hard.
75 #define timersub(a, b, result) \
77 (result)->tv_sec = (a)->tv_sec - (b)->tv_sec; \
78 (result)->tv_usec = (a)->tv_usec - (b)->tv_usec; \
79 if ((result)->tv_usec < 0) { \
81 (result)->tv_usec += 1000000; \
90 pool
*fcgi_config_pool
; /* the config pool */
91 server_rec
*fcgi_apache_main_server
;
93 const char *fcgi_wrapper
= NULL
; /* wrapper path */
94 uid_t fcgi_user_id
; /* the run uid of Apache & PM */
95 gid_t fcgi_group_id
; /* the run gid of Apache & PM */
97 fcgi_server
*fcgi_servers
= NULL
; /* AppClasses */
99 char *fcgi_socket_dir
= DEFAULT_SOCK_DIR
; /* default FastCgiIpcDir */
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 int dynamicFlush
= FCGI_FLUSH
;
135 u_int dynamicListenQueueDepth
= FCGI_DEFAULT_LISTEN_Q
;
136 u_int dynamicInitStartDelay
= DEFAULT_INIT_START_DELAY
;
137 u_int dynamicRestartDelay
= FCGI_DEFAULT_RESTART_DELAY
;
138 array_header
*dynamic_pass_headers
= NULL
;
139 u_int dynamic_idle_timeout
= FCGI_DEFAULT_IDLE_TIMEOUT
;
141 /*******************************************************************************
142 * Construct a message and write it to the pm_pipe.
144 static void send_to_pm(const char id
, const char * const fs_path
,
145 const char *user
, const char * const group
, const unsigned long q_usec
,
146 const unsigned long req_usec
)
149 fcgi_pm_job
*job
= NULL
;
151 if (!(job
= (fcgi_pm_job
*) malloc(sizeof(fcgi_pm_job
))))
154 static int failed_count
= 0;
156 char buf
[FCGI_MAX_MSG_LEN
];
159 if (strlen(fs_path
) > FCGI_MAXPATH
) {
160 ap_log_error(FCGI_LOG_ERR_NOERRNO
, fcgi_apache_main_server
,
161 "FastCGI: the path \"%s\" is too long (>%d) for a dynamic server", fs_path
, FCGI_MAXPATH
);
167 case FCGI_SERVER_START_JOB
:
170 job
->fs_path
= strdup(fs_path
);
171 job
->user
= strdup(user
);
172 job
->group
= strdup(group
);
174 job
->start_time
= 0L;
176 buflen
= sprintf(buf
, "%c %s %s %s*", id
, fs_path
, user
, group
);
180 case FCGI_REQUEST_TIMEOUT_JOB
:
183 job
->fs_path
= strdup(fs_path
);
184 job
->user
= strdup(user
);
185 job
->group
= strdup(group
);
187 job
->start_time
= 0L;
189 buflen
= sprintf(buf
, "%c %s %s %s*", id
, fs_path
, user
, group
);
193 case FCGI_REQUEST_COMPLETE_JOB
:
196 job
->fs_path
= strdup(fs_path
);
198 job
->start_time
= req_usec
;
199 job
->user
= strdup(user
);
200 job
->group
= strdup(group
);
202 buflen
= sprintf(buf
, "%c %s %s %s %lu %lu*", id
, fs_path
, user
, group
, q_usec
, req_usec
);
208 if (fcgi_pm_add_job(job
)) return;
210 SetEvent(fcgi_event_handles
[MBOX_EVENT
]);
212 ap_assert(buflen
<= FCGI_MAX_MSG_LEN
);
214 /* There is no apache flag or function that can be used to id
215 * restart/shutdown pending so ignore the first few failures as
216 * once it breaks it will stay broke */
217 if (write(fcgi_pm_pipe
[1], (const void *)buf
, buflen
) != buflen
218 && failed_count
++ > 10)
220 ap_log_error(FCGI_LOG_WARN
, fcgi_apache_main_server
,
221 "FastCGI: write() to PM failed (ignore if a restart or shutdown is pending)");
227 *----------------------------------------------------------------------
231 * An Apache module initializer, called by the Apache core
232 * after reading the server config.
234 * Start the process manager no matter what, since there may be a
235 * request for dynamic FastCGI applications without any being
236 * configured as static applications. Also, check for the existence
237 * and create if necessary a subdirectory into which all dynamic
240 *----------------------------------------------------------------------
242 static void init_module(server_rec
*s
, pool
*p
)
246 /* Register to reset to default values when the config pool is cleaned */
248 ap_register_cleanup(p
, NULL
, fcgi_config_reset_globals
, ap_null_cleanup
);
251 ap_add_version_component("mod_fastcgi/" MOD_FASTCGI_VERSION
);
253 fcgi_config_set_fcgi_uid_n_gid(1);
255 /* keep these handy */
256 fcgi_config_pool
= p
;
257 fcgi_apache_main_server
= s
;
260 /* Create Unix/Domain socket directory */
261 if ((err
= fcgi_config_make_dir(p
, fcgi_socket_dir
)))
262 ap_log_error(FCGI_LOG_ERR
, s
, "FastCGI: %s", err
);
265 /* Create Dynamic directory */
266 if ((err
= fcgi_config_make_dynamic_dir(p
, 1)))
267 ap_log_error(FCGI_LOG_ERR
, s
, "FastCGI: %s", err
);
270 /* Spawn the PM only once. Under Unix, Apache calls init() routines
271 * twice, once before detach() and once after. Win32 doesn't detach.
272 * Under DSO, DSO modules are unloaded between the two init() calls.
273 * Under Unix, the -X switch causes two calls to init() but no detach
274 * (but all subprocesses are wacked so the PM is toasted anyway)! */
276 if (ap_standalone
&& ap_restart_time
== 0)
279 /* Create the pipe for comm with the PM */
280 if (pipe(fcgi_pm_pipe
) < 0) {
281 ap_log_error(FCGI_LOG_ERR
, s
, "FastCGI: pipe() failed");
284 /* Start the Process Manager */
285 fcgi_pm_pid
= ap_spawn_child(p
, fcgi_pm_main
, NULL
, kill_only_once
, NULL
, NULL
, NULL
);
286 if (fcgi_pm_pid
<= 0) {
287 ap_log_error(FCGI_LOG_ALERT
, s
,
288 "FastCGI: can't start the process manager, spawn_child() failed");
291 close(fcgi_pm_pipe
[0]);
295 static void fcgi_child_init(server_rec
*dc0
, pool
*dc1
)
298 /* Create the MBOX, TERM, and WAKE event handlers */
299 fcgi_event_handles
[0] = CreateEvent(NULL
, FALSE
, FALSE
, NULL
);
300 if (fcgi_event_handles
[0] == NULL
) {
301 ap_log_error(FCGI_LOG_ALERT
, fcgi_apache_main_server
,
302 "FastCGI: CreateEvent() failed");
304 fcgi_event_handles
[1] = CreateEvent(NULL
, FALSE
, FALSE
, NULL
);
305 if (fcgi_event_handles
[1] == NULL
) {
306 ap_log_error(FCGI_LOG_ALERT
, fcgi_apache_main_server
,
307 "FastCGI: CreateEvent() failed");
309 fcgi_event_handles
[2] = CreateEvent(NULL
, FALSE
, FALSE
, NULL
);
310 if (fcgi_event_handles
[2] == NULL
) {
311 ap_log_error(FCGI_LOG_ALERT
, fcgi_apache_main_server
,
312 "FastCGI: CreateEvent() failed");
315 /* Create the mbox mutex (PM - request threads) */
316 fcgi_dynamic_mbox_mutex
= CreateMutex(NULL
, FALSE
, NULL
);
317 if (fcgi_dynamic_mbox_mutex
== NULL
) {
318 ap_log_error(FCGI_LOG_ALERT
, fcgi_apache_main_server
,
319 "FastCGI: CreateMutex() failed");
322 /* Spawn of the process manager thread */
323 fcgi_pm_thread
= CreateThread(NULL
, 0, (LPTHREAD_START_ROUTINE
)fcgi_pm_main
, NULL
, 0, NULL
);
324 if (fcgi_pm_thread
== NULL
) {
325 ap_log_error(FCGI_LOG_ALERT
, fcgi_apache_main_server
,
326 "CreateThread() failed to spawn the process manager");
333 static void fcgi_child_exit(server_rec
*dc0
, pool
*dc1
)
336 /* Signal the PM thread to exit*/
337 SetEvent(fcgi_event_handles
[TERM_EVENT
]);
339 /* Waiting on pm thread to exit */
340 WaitForSingleObject(fcgi_pm_thread
, INFINITE
);
347 *----------------------------------------------------------------------
351 * Terminate a line: scan to the next newline, scan back to the
352 * first non-space character and store a terminating zero. Return
353 * the next character past the end of the newline.
355 * If the end of the string is reached, ASSERT!
357 * If the FIRST character(s) in the line are '\n' or "\r\n", the
358 * first character is replaced with a NULL and next character
359 * past the newline is returned. NOTE: this condition supercedes
360 * the processing of RFC-822 continuation lines.
362 * If continuation is set to 'TRUE', then it parses a (possible)
363 * sequence of RFC-822 continuation lines.
369 * Termination byte stored in string.
371 *----------------------------------------------------------------------
373 static char *get_header_line(char *start
, int continuation
)
378 if(p
[0] == '\r' && p
[1] == '\n') { /* If EOL in 1st 2 chars */
379 p
++; /* point to \n and stop */
380 } else if(*p
!= '\n') {
383 if(*p
== '\n' && p
[1] != ' ' && p
[1] != '\t')
388 while(*p
!= '\0' && *p
!= '\n') {
394 ap_assert(*p
!= '\0');
399 * Trim any trailing whitespace.
401 while(isspace((unsigned char)p
[-1]) && p
> start
) {
410 *----------------------------------------------------------------------
414 * Call with r->parseHeader == SCAN_CGI_READING_HEADERS
415 * and initial script output in fr->header.
417 * If the initial script output does not include the header
418 * terminator ("\r\n\r\n") process_headers returns with no side
419 * effects, to be called again when more script output
420 * has been appended to fr->header.
422 * If the initial script output includes the header terminator,
423 * process_headers parses the headers and determines whether or
424 * not the remaining script output will be sent to the client.
425 * If so, process_headers sends the HTTP response headers to the
426 * client and copies any non-header script output to the output
433 * May set r->parseHeader to:
434 * SCAN_CGI_FINISHED -- headers parsed, returning script response
435 * SCAN_CGI_BAD_HEADER -- malformed header from script
436 * SCAN_CGI_INT_REDIRECT -- handler should perform internal redirect
437 * SCAN_CGI_SRV_REDIRECT -- handler should return REDIRECT
439 *----------------------------------------------------------------------
442 static const char *process_headers(request_rec
*r
, fcgi_request
*fr
)
444 char *p
, *next
, *name
, *value
;
446 int hasContentType
, hasStatus
, hasLocation
;
448 ap_assert(fr
->parseHeader
== SCAN_CGI_READING_HEADERS
);
450 if (fr
->header
== NULL
)
454 * Do we have the entire header? Scan for the blank line that
455 * terminates the header.
457 p
= (char *)fr
->header
->elts
;
458 len
= fr
->header
->nelts
;
460 while(len
-- && flag
< 2) {
470 name
= "Invalid Character";
480 /* Return (to be called later when we have more data)
481 * if we don't have an entire header. */
486 * Parse all the headers.
488 fr
->parseHeader
= SCAN_CGI_FINISHED
;
489 hasContentType
= hasStatus
= hasLocation
= FALSE
;
490 next
= (char *)fr
->header
->elts
;
492 next
= get_header_line(name
= next
, TRUE
);
496 if ((p
= strchr(name
, ':')) == NULL
) {
500 while (p
!= name
&& isspace((unsigned char)*(p
- 1))) {
507 if (strpbrk(name
, " \t") != NULL
) {
511 while (isspace((unsigned char)*value
)) {
515 if (strcasecmp(name
, "Status") == 0) {
516 int statusValue
= strtol(value
, NULL
, 10);
519 goto DuplicateNotAllowed
;
521 if (statusValue
< 0) {
522 fr
->parseHeader
= SCAN_CGI_BAD_HEADER
;
523 return ap_psprintf(r
->pool
, "invalid Status '%s'", value
);
526 r
->status
= statusValue
;
527 r
->status_line
= ap_pstrdup(r
->pool
, value
);
531 if (fr
->role
== FCGI_RESPONDER
) {
532 if (strcasecmp(name
, "Content-type") == 0) {
533 if (hasContentType
) {
534 goto DuplicateNotAllowed
;
536 hasContentType
= TRUE
;
537 r
->content_type
= ap_pstrdup(r
->pool
, value
);
541 if (strcasecmp(name
, "Location") == 0) {
543 goto DuplicateNotAllowed
;
546 ap_table_set(r
->headers_out
, "Location", value
);
550 /* If the script wants them merged, it can do it */
551 ap_table_add(r
->err_headers_out
, name
, value
);
555 ap_table_add(fr
->authHeaders
, name
, value
);
559 if (fr
->role
!= FCGI_RESPONDER
)
563 * Who responds, this handler or Apache?
566 const char *location
= ap_table_get(r
->headers_out
, "Location");
568 * Based on internal redirect handling in mod_cgi.c...
570 * If a script wants to produce its own Redirect
571 * body, it now has to explicitly *say* "Status: 302"
573 if (r
->status
== 200) {
574 if(location
[0] == '/') {
576 * Location is an relative path. This handler will
577 * consume all script output, then have Apache perform an
580 fr
->parseHeader
= SCAN_CGI_INT_REDIRECT
;
584 * Location is an absolute URL. If the script didn't
585 * produce a Content-type header, this handler will
586 * consume all script output and then have Apache generate
587 * its standard redirect response. Otherwise this handler
588 * will transmit the script's response.
590 fr
->parseHeader
= SCAN_CGI_SRV_REDIRECT
;
596 * We're responding. Send headers, buffer excess script output.
598 ap_send_http_header(r
);
600 /* We need to reinstate our timeout, send_http_header() kill()s it */
601 ap_hard_timeout("FastCGI request processing", r
);
606 len
= fr
->header
->nelts
- (next
- fr
->header
->elts
);
608 ap_assert(BufferLength(fr
->clientOutputBuffer
) == 0);
609 if (BufferFree(fr
->clientOutputBuffer
) < len
) {
610 fr
->clientOutputBuffer
= fcgi_buf_new(r
->pool
, len
);
612 ap_assert(BufferFree(fr
->clientOutputBuffer
) >= len
);
614 int sent
= fcgi_buf_add_block(fr
->clientOutputBuffer
, next
, len
);
615 ap_assert(sent
== len
);
620 /* Log first line of a multi-line header */
621 if ((p
= strpbrk(name
, "\r\n")) != NULL
)
623 fr
->parseHeader
= SCAN_CGI_BAD_HEADER
;
624 return ap_psprintf(r
->pool
, "malformed header '%s'", name
);
627 fr
->parseHeader
= SCAN_CGI_BAD_HEADER
;
628 return ap_psprintf(r
->pool
, "duplicate header '%s'", name
);
632 * Read from the client filling both the FastCGI server buffer and the
633 * client buffer with the hopes of buffering the client data before
634 * making the connect() to the FastCGI server. This prevents slow
635 * clients from keeping the FastCGI server in processing longer than is
638 static int read_from_client_n_queue(fcgi_request
*fr
)
644 while (BufferFree(fr
->clientInputBuffer
) > 0 || BufferFree(fr
->serverOutputBuffer
) > 0) {
645 fcgi_protocol_queue_client_buffer(fr
);
647 if (fr
->expectingClientContent
<= 0)
650 fcgi_buf_get_free_block_info(fr
->clientInputBuffer
, &end
, &count
);
654 if ((countRead
= ap_get_client_block(fr
->r
, end
, count
)) < 0)
657 if (countRead
== 0) {
658 fr
->expectingClientContent
= 0;
661 fcgi_buf_add_update(fr
->clientInputBuffer
, countRead
);
662 ap_reset_timeout(fr
->r
);
668 static int write_to_client(fcgi_request
*fr
)
673 fcgi_buf_get_block_info(fr
->clientOutputBuffer
, &begin
, &count
);
677 /* If fewer than count bytes are written, an error occured.
678 * ap_bwrite() typically forces a flushed write to the client, this
679 * effectively results in a block (and short packets) - it should
680 * be fixed, but I didn't win much support for the idea on new-httpd.
681 * So, without patching Apache, the best way to deal with this is
682 * to size the fcgi_bufs to hold all of the script output (within
683 * reason) so the script can be released from having to wait around
684 * for the transmission to the client to complete. */
685 #ifdef RUSSIAN_APACHE
686 if (ap_rwrite(begin
, count
, fr
->r
) != count
) {
687 ap_log_rerror(FCGI_LOG_INFO_NOERRNO
, fr
->r
,
688 "FastCGI: client stopped connection before send body completed");
692 if (ap_bwrite(fr
->r
->connection
->client
, begin
, count
) != count
) {
693 ap_log_rerror(FCGI_LOG_INFO_NOERRNO
, fr
->r
,
694 "FastCGI: client stopped connection before send body completed");
699 ap_reset_timeout(fr
->r
);
701 /* Don't bother with a wrapped buffer, limiting exposure to slow
702 * clients. The BUFF routines don't allow a writev from above,
703 * and don't always memcpy to minimize small write()s, this should
704 * be fixed, but I didn't win much support for the idea on
705 * new-httpd - I'll have to _prove_ its a problem first.. */
707 /* The default behaviour used to be to flush with every write, but this
708 * can tie up the FastCGI server longer than is necessary so its an option now */
709 if (fr
->fs
? fr
->fs
->flush
: dynamicFlush
) {
710 #ifdef RUSSIAN_APACHE
711 if (ap_rflush(fr
->r
)) {
712 ap_log_rerror(FCGI_LOG_INFO_NOERRNO
, fr
->r
,
713 "FastCGI: client stopped connection before send body completed");
717 if (ap_bflush(fr
->r
->connection
->client
)) {
718 ap_log_rerror(FCGI_LOG_INFO_NOERRNO
, fr
->r
,
719 "FastCGI: client stopped connection before send body completed");
723 ap_reset_timeout(fr
->r
);
726 fcgi_buf_toss(fr
->clientOutputBuffer
, count
);
730 /*******************************************************************************
731 * Determine the user and group the wrapper should be called with.
732 * Based on code in Apache's create_argv_cmd() (util_script.c).
734 static void set_uid_n_gid(request_rec
*r
, const char **user
, const char **group
)
736 if (fcgi_wrapper
== NULL
) {
742 if (strncmp("/~", r
->uri
, 2) == 0) {
743 /* its a user dir uri, just send the ~user, and leave it to the PM */
744 char *end
= strchr(r
->uri
+ 2, '/');
747 *user
= memcpy(ap_pcalloc(r
->pool
, end
- r
->uri
), r
->uri
+ 1, end
- r
->uri
- 1);
749 *user
= ap_pstrdup(r
->pool
, r
->uri
+ 1);
753 *user
= ap_psprintf(r
->pool
, "%ld", (long)r
->server
->server_uid
);
754 *group
= ap_psprintf(r
->pool
, "%ld", (long)r
->server
->server_gid
);
758 static void send_request_complete(fcgi_request
*fr
)
760 if (fr
->completeTime
.tv_sec
)
762 struct timeval qtime
, rtime
;
764 timersub(&fr
->queueTime
, &fr
->startTime
, &qtime
);
765 timersub(&fr
->completeTime
, &fr
->queueTime
, &rtime
);
767 send_to_pm(FCGI_REQUEST_COMPLETE_JOB
, fr
->fs_path
,
769 qtime
.tv_sec
* 1000000 + qtime
.tv_usec
,
770 rtime
.tv_sec
* 1000000 + rtime
.tv_usec
);
776 static int set_nonblocking(const fcgi_request
* fr
, int nonblocking
)
778 if (fr
->using_npipe_io
)
782 DWORD mode
= PIPE_NOWAIT
| PIPE_READMODE_BYTE
;
783 if (SetNamedPipeHandleState((HANDLE
) fr
->fd
, &mode
, NULL
, NULL
) == 0)
785 ap_log_rerror(FCGI_LOG_ERR
, fr
->r
,
786 "FastCGI: SetNamedPipeHandleState() failed");
793 unsigned long ioctl_arg
= (nonblocking
) ? 1 : 0;
794 if (ioctlsocket(fr
->fd
, FIONBIO
, &ioctl_arg
) != 0)
796 errno
= WSAGetLastError();
797 ap_log_rerror(FCGI_LOG_ERR_ERRNO
, fr
->r
,
798 "FastCGI: ioctlsocket() failed");
808 static int set_nonblocking(const fcgi_request
* fr
, int nonblocking
)
811 int fd_flags
= fcntl(fr
->fd
, F_GETFL
, 0);
813 if (fd_flags
< 0) return -1;
815 #if defined(O_NONBLOCK)
816 nb_flag
= O_NONBLOCK
;
817 #elif defined(O_NDELAY)
819 #elif defined(FNDELAY)
822 #error "TODO - don't read from app until all data from client is posted."
825 fd_flags
= (nonblocking
) ? (fd_flags
| nb_flag
) : (fd_flags
& ~nb_flag
);
827 return fcntl(fr
->fd
, F_SETFL
, fd_flags
);
832 /*******************************************************************************
833 * Close the connection to the FastCGI server. This is normally called by
834 * do_work(), but may also be called as in request pool cleanup.
836 static void close_connection_to_fs(fcgi_request
*fr
)
840 if (fr
->fd
!= INVALID_SOCKET
)
842 set_nonblocking(fr
, FALSE
);
844 if (fr
->using_npipe_io
)
846 CloseHandle((HANDLE
) fr
->fd
);
853 fr
->fd
= INVALID_SOCKET
;
860 set_nonblocking(fr
, FALSE
);
867 if (fr
->dynamic
&& fr
->keepReadingFromFcgiApp
== FALSE
)
869 /* XXX FCGI_REQUEST_COMPLETE_JOB is only sent for requests which complete
870 * normally WRT the fcgi app. There is no data sent for
871 * connect() timeouts or requests which complete abnormally.
872 * KillDynamicProcs() and RemoveRecords() need to be looked at
873 * to be sure they can reasonably handle these cases before
874 * sending these sort of stats - theres some funk in there.
876 if (fcgi_util_ticks(&fr
->completeTime
) < 0)
878 /* there's no point to aborting the request, just log it */
879 ap_log_error(FCGI_LOG_ERR
, fr
->r
->server
, "FastCGI: can't get time of day");
884 /*******************************************************************************
885 * Connect to the FastCGI server.
887 static int open_connection_to_fs(fcgi_request
*fr
)
890 fd_set write_fds
, read_fds
;
892 request_rec
* const r
= fr
->r
;
893 pool
* const rp
= r
->pool
;
894 const char *socket_path
= NULL
;
895 struct sockaddr
*socket_addr
= NULL
;
896 int socket_addr_len
= 0;
898 const char *err
= NULL
;
901 /* Create the connection point */
904 socket_path
= fcgi_util_socket_hash_filename(rp
, fr
->fs_path
, fr
->user
, fr
->group
);
905 socket_path
= fcgi_util_socket_make_path_absolute(rp
, socket_path
, 1);
908 err
= fcgi_util_socket_make_domain_addr(rp
, (struct sockaddr_un
**)&socket_addr
,
909 &socket_addr_len
, socket_path
);
911 ap_log_rerror(FCGI_LOG_ERR
, r
,
912 "FastCGI: failed to connect to server \"%s\": "
913 "%s", fr
->fs_path
, err
);
921 if (fr
->fs
->dest_addr
!= NULL
) {
922 socket_addr
= fr
->fs
->dest_addr
;
924 else if (fr
->fs
->socket_addr
) {
925 socket_addr
= fr
->fs
->socket_addr
;
928 socket_path
= fr
->fs
->socket_path
;
931 socket_addr
= fr
->fs
->socket_addr
;
933 socket_addr_len
= fr
->fs
->socket_addr_len
;
939 if (fr
->fs
&& fr
->fs
->restartTime
)
941 struct stat sock_stat
;
943 if (stat(socket_path
, &sock_stat
) == 0)
947 if (dynamicAutoUpdate
)
949 struct stat app_stat
;
951 /* TODO: follow sym links */
953 if (stat(fr
->fs_path
, &app_stat
) == 0)
956 if (fr
->fs
->restartTime
< app_stat
.st_mtime
)
958 if (sock_stat
.st_mtime
< app_stat
.st_mtime
)
962 struct timeval tv
= {1, 0};
965 * There's a newer one, request a restart.
967 send_to_pm(FCGI_SERVER_RESTART_JOB
, fr
->fs_path
, fr
->user
, fr
->group
, 0, 0);
972 /* Avoid sleep/alarm interactions */
973 ap_select(0, NULL
, NULL
, NULL
, &tv
);
981 send_to_pm(FCGI_SERVER_START_JOB
, fr
->fs_path
, fr
->user
, fr
->group
, 0, 0);
983 /* Wait until it looks like its running */
990 fr
->fs
= fcgi_util_fs_get_by_id(fr
->fs_path
, 0, 0);
992 if (fr
->fs
&& fr
->fs
->restartTime
)
994 struct timeval tv
= {1, 0};
996 /* Avoid sleep/alarm interactions */
997 ap_select(0, NULL
, NULL
, NULL
, &tv
);
999 if (stat(socket_path
, &sock_stat
) == 0)
1015 int max_connect_time
= FCGI_NAMED_PIPE_CONNECT_TIMEOUT
;
1017 fr
->using_npipe_io
= TRUE
;
1021 interval
= dynamicPleaseStartDelay
* 1000;
1023 if (dynamicAppConnectTimeout
) {
1024 max_connect_time
= dynamicAppConnectTimeout
;
1029 interval
= FCGI_NAMED_PIPE_CONNECT_TIMEOUT
* 1000;
1031 if (fr
->fs
->appConnectTimeout
) {
1032 max_connect_time
= fr
->fs
->appConnectTimeout
;
1036 if (fcgi_util_ticks(&fr
->startTime
) < 0) {
1037 ap_log_rerror(FCGI_LOG_ERR
, r
,
1038 "FastCGI: failed to connect to server \"%s\": "
1039 "can't get time of day", fr
->fs_path
);
1045 fr
->fd
= (SOCKET
) CreateFile(socket_path
,
1046 GENERIC_READ
| GENERIC_WRITE
,
1047 FILE_SHARE_READ
| FILE_SHARE_WRITE
,
1048 NULL
, // no security attributes
1049 OPEN_EXISTING
, // opens existing pipe
1050 FILE_ATTRIBUTE_NORMAL
, // default attributes
1051 NULL
); // no template file
1053 if (fr
->fd
!= (SOCKET
) INVALID_HANDLE_VALUE
) {
1057 if (GetLastError() != ERROR_PIPE_BUSY
1058 && GetLastError() != ERROR_FILE_NOT_FOUND
)
1060 ap_log_rerror(FCGI_LOG_ERR
, r
,
1061 "FastCGI: failed to connect to server \"%s\": "
1062 "CreateFile() failed", fr
->fs_path
);
1066 // All pipe instances are busy, so wait
1067 ready
= WaitNamedPipe(socket_path
, interval
);
1069 if (fr
->dynamic
&& !ready
) {
1070 send_to_pm(FCGI_REQUEST_TIMEOUT_JOB
, fr
->fs_path
, fr
->user
, fr
->group
, 0, 0);
1073 if (fcgi_util_ticks(&fr
->queueTime
) < 0) {
1074 ap_log_rerror(FCGI_LOG_ERR
, r
,
1075 "FastCGI: failed to connect to server \"%s\": "
1076 "can't get time of day", fr
->fs_path
);
1080 connect_time
= fr
->queueTime
.tv_sec
- fr
->startTime
.tv_sec
;
1082 FCGIDBG5("interval=%d, max_connect_time=%d, connect_time=%d, ready=%d", interval
, max_connect_time
, connect_time
, ready
);
1084 } while (connect_time
< max_connect_time
);
1086 if (fr
->fd
== (SOCKET
) INVALID_HANDLE_VALUE
) {
1087 ap_log_rerror(FCGI_LOG_ERR
, r
,
1088 "FastCGI: failed to connect to server \"%s\": "
1089 "CreateFile()/WaitNamedPipe() timed out", fr
->fs_path
);
1090 fr
->fd
= INVALID_SOCKET
;
1094 FCGIDBG2("got_named_pipe_connect: %s", fr
->fs_path
);
1100 /* Create the socket */
1101 fr
->fd
= socket(socket_addr
->sa_family
, SOCK_STREAM
, 0);
1104 if (fr
->fd
== INVALID_SOCKET
) {
1105 errno
= WSAGetLastError(); // Not sure this is going to work as expected
1109 ap_log_rerror(FCGI_LOG_ERR_ERRNO
, r
,
1110 "FastCGI: failed to connect to server \"%s\": "
1111 "socket() failed", fr
->fs_path
);
1116 if (fr
->fd
>= FD_SETSIZE
) {
1117 ap_log_rerror(FCGI_LOG_ERR
, r
,
1118 "FastCGI: failed to connect to server \"%s\": "
1119 "socket file descriptor (%u) is larger than "
1120 "FD_SETSIZE (%u), you probably need to rebuild Apache with a "
1121 "larger FD_SETSIZE", fr
->fs_path
, fr
->fd
, FD_SETSIZE
);
1126 /* If appConnectTimeout is non-zero, setup do a non-blocking connect */
1127 if ((fr
->dynamic
&& dynamicAppConnectTimeout
) || (!fr
->dynamic
&& fr
->fs
->appConnectTimeout
)) {
1128 set_nonblocking(fr
, TRUE
);
1131 if (fr
->dynamic
&& fcgi_util_ticks(&fr
->startTime
) < 0) {
1132 ap_log_rerror(FCGI_LOG_ERR
, r
,
1133 "FastCGI: failed to connect to server \"%s\": "
1134 "can't get time of day", fr
->fs_path
);
1139 if (connect(fr
->fd
, (struct sockaddr
*)socket_addr
, socket_addr_len
) == 0)
1140 goto ConnectionComplete
;
1144 errno
= WSAGetLastError();
1145 if (errno
!= WSAEWOULDBLOCK
) {
1146 ap_log_rerror(FCGI_LOG_ERR_ERRNO
, r
,
1147 "FastCGI: failed to connect to server \"%s\": "
1148 "connect() failed", fr
->fs_path
);
1154 /* ECONNREFUSED means the listen queue is full (or there isn't one).
1155 * With dynamic I can at least make sure the PM knows this is occuring */
1156 if (fr
->dynamic
&& errno
== ECONNREFUSED
) {
1157 /* @@@ This might be better as some other "kind" of message */
1158 send_to_pm(FCGI_REQUEST_TIMEOUT_JOB
, fr
->fs_path
, fr
->user
, fr
->group
, 0, 0);
1160 errno
= ECONNREFUSED
;
1163 if (errno
!= EINPROGRESS
) {
1164 ap_log_rerror(FCGI_LOG_ERR
, r
,
1165 "FastCGI: failed to connect to server \"%s\": "
1166 "connect() failed", fr
->fs_path
);
1172 /* The connect() is non-blocking */
1178 FD_ZERO(&write_fds
);
1179 FD_SET(fr
->fd
, &write_fds
);
1180 read_fds
= write_fds
;
1181 tval
.tv_sec
= dynamicPleaseStartDelay
;
1184 status
= ap_select((fr
->fd
+1), &read_fds
, &write_fds
, NULL
, &tval
);
1188 if (fcgi_util_ticks(&fr
->queueTime
) < 0) {
1189 ap_log_rerror(FCGI_LOG_ERR
, r
,
1190 "FastCGI: failed to connect to server \"%s\": "
1191 "can't get time of day", fr
->fs_path
);
1198 /* select() timed out */
1199 send_to_pm(FCGI_REQUEST_TIMEOUT_JOB
, fr
->fs_path
, fr
->user
, fr
->group
, 0, 0);
1200 } while ((fr
->queueTime
.tv_sec
- fr
->startTime
.tv_sec
) < (int)dynamicAppConnectTimeout
);
1202 /* XXX These can be moved down when dynamic vars live is a struct */
1204 ap_log_rerror(FCGI_LOG_ERR_NOERRNO
, r
,
1205 "FastCGI: failed to connect to server \"%s\": "
1206 "connect() timed out (appConnTimeout=%dsec)",
1207 fr
->fs_path
, dynamicAppConnectTimeout
);
1212 tval
.tv_sec
= fr
->fs
->appConnectTimeout
;
1214 FD_ZERO(&write_fds
);
1215 FD_SET(fr
->fd
, &write_fds
);
1216 read_fds
= write_fds
;
1218 status
= ap_select((fr
->fd
+1), &read_fds
, &write_fds
, NULL
, &tval
);
1221 ap_log_rerror(FCGI_LOG_ERR_NOERRNO
, r
,
1222 "FastCGI: failed to connect to server \"%s\": "
1223 "connect() timed out (appConnTimeout=%dsec)",
1224 fr
->fs_path
, dynamicAppConnectTimeout
);
1231 errno
= WSAGetLastError();
1233 ap_log_rerror(FCGI_LOG_ERR_ERRNO
, r
,
1234 "FastCGI: failed to connect to server \"%s\": "
1235 "select() failed", fr
->fs_path
);
1239 if (FD_ISSET(fr
->fd
, &write_fds
) || FD_ISSET(fr
->fd
, &read_fds
)) {
1241 NET_SIZE_T len
= sizeof(error
);
1243 if (getsockopt(fr
->fd
, SOL_SOCKET
, SO_ERROR
, (char *)&error
, &len
) < 0) {
1244 /* Solaris pending error */
1246 errno
= WSAGetLastError();
1248 ap_log_rerror(FCGI_LOG_ERR_ERRNO
, r
,
1249 "FastCGI: failed to connect to server \"%s\": "
1250 "select() failed (Solaris pending error)", fr
->fs_path
);
1255 /* Berkeley-derived pending error */
1257 ap_log_rerror(FCGI_LOG_ERR_ERRNO
, r
,
1258 "FastCGI: failed to connect to server \"%s\": "
1259 "select() failed (pending error)", fr
->fs_path
);
1265 errno
= WSAGetLastError();
1267 ap_log_rerror(FCGI_LOG_ERR_ERRNO
, r
,
1268 "FastCGI: failed to connect to server \"%s\": "
1269 "select() error - THIS CAN'T HAPPEN!", fr
->fs_path
);
1274 /* Return to blocking mode if it was set up */
1275 if ((fr
->dynamic
&& dynamicAppConnectTimeout
) || (!fr
->dynamic
&& fr
->fs
->appConnectTimeout
)) {
1276 set_nonblocking(fr
, FALSE
);
1280 if (socket_addr
->sa_family
== AF_INET
) {
1281 /* We shouldn't be sending small packets and there's no application
1282 * level ack of the data we send, so disable Nagle */
1284 setsockopt(fr
->fd
, IPPROTO_TCP
, TCP_NODELAY
, (char *)&set
, sizeof(set
));
1291 static int server_error(fcgi_request
*fr
)
1293 #if defined(SIGPIPE) && MODULE_MAGIC_NUMBER < 19990320
1294 /* Make sure we leave with Apache's sigpipe_handler in place */
1295 if (fr
->apache_sigpipe_handler
!= NULL
)
1296 signal(SIGPIPE
, fr
->apache_sigpipe_handler
);
1298 close_connection_to_fs(fr
);
1299 ap_kill_timeout(fr
->r
);
1300 return SERVER_ERROR
;
1303 static void cleanup(void *data
)
1305 fcgi_request
* const fr
= (fcgi_request
*) data
;
1307 if (fr
== NULL
) return;
1309 /* its more than likely already run, but... */
1310 close_connection_to_fs(fr
);
1312 send_request_complete(fr
);
1314 if (fr
->fs_stderr_len
) {
1315 ap_log_rerror(FCGI_LOG_ERR_NOERRNO
, fr
->r
,
1316 "FastCGI: server \"%s\" stderr: %s", fr
->fs_path
, fr
->fs_stderr
);
1320 /*----------------------------------------------------------------------
1321 * This is the core routine for moving data between the FastCGI
1322 * application and the Web server's client.
1324 static int do_work(request_rec
*r
, fcgi_request
*fr
)
1326 struct timeval timeOut
, dynamic_last_activity_time
= {0, 0};
1327 fd_set read_set
, write_set
;
1328 int status
= 0, idle_timeout
;
1329 int numFDs
, dynamic_first_read
= fr
->dynamic
? 1 : 0;
1331 int envSent
= FALSE
; /* has the complete ENV been buffered? */
1334 const char *err
= NULL
;
1337 FD_ZERO(&write_set
);
1339 fcgi_protocol_queue_begin_request(fr
);
1341 /* Buffer as much of the environment as we can fit */
1343 envSent
= fcgi_protocol_queue_env(r
, fr
, &env
);
1345 /* Start the Apache dropdead timer. See comments at top of file. */
1346 ap_hard_timeout("buffering of FastCGI client data", r
);
1348 /* Read as much as possible from the client. */
1349 if (fr
->role
== FCGI_RESPONDER
) {
1350 status
= ap_setup_client_block(r
, REQUEST_CHUNKED_ERROR
);
1355 fr
->expectingClientContent
= (ap_should_client_block(r
) != 0);
1357 if (read_from_client_n_queue(fr
) != OK
)
1358 return server_error(fr
);
1362 ap_register_cleanup(rp
, (void *)fr
, cleanup
, ap_null_cleanup
);
1363 ap_unblock_alarms();
1365 /* Connect to the FastCGI Application */
1366 ap_hard_timeout("connect() to FastCGI server", r
);
1367 if (open_connection_to_fs(fr
) != FCGI_OK
) {
1368 return server_error(fr
);
1371 numFDs
= fr
->fd
+ 1;
1372 idle_timeout
= fr
->dynamic
? dynamic_idle_timeout
: fr
->fs
->idle_timeout
;
1374 if (dynamic_first_read
) {
1375 dynamic_last_activity_time
= fr
->startTime
;
1377 if (dynamicAppConnectTimeout
) {
1378 struct timeval qwait
;
1379 timersub(&fr
->queueTime
, &fr
->startTime
, &qwait
);
1380 dynamic_first_read
= qwait
.tv_sec
/ dynamicPleaseStartDelay
+ 1;
1384 /* @@@ We never reset the timer in this loop, most folks don't mess w/
1385 * Timeout directive which means we've got the 5 min default which is way
1386 * to long to tie up a fs. We need a better/configurable solution that
1387 * uses the select */
1388 ap_hard_timeout("FastCGI request processing", r
);
1390 /* Before we do any writing, set the connection non-blocking */
1391 set_nonblocking(fr
, TRUE
);
1393 /* The socket is writeable, so get the first write out of the way */
1394 if (fcgi_buf_get_to_fd(fr
->serverOutputBuffer
, fr
->fd
) < 0) {
1396 if (! fr
->using_npipe_io
)
1397 ap_log_rerror(FCGI_LOG_ERR_ERRNO
, r
,
1398 "FastCGI: comm with server \"%s\" aborted: write failed", fr
->fs_path
);
1401 ap_log_rerror(FCGI_LOG_ERR
, r
,
1402 "FastCGI: comm with server \"%s\" aborted: write failed", fr
->fs_path
);
1403 return server_error(fr
);
1406 while (fr
->keepReadingFromFcgiApp
1407 || BufferLength(fr
->serverInputBuffer
) > 0
1408 || BufferLength(fr
->clientOutputBuffer
) > 0) {
1410 /* If we didn't buffer all of the environment yet, buffer some more */
1412 envSent
= fcgi_protocol_queue_env(r
, fr
, &env
);
1414 /* Read as much as possible from the client. */
1415 if (fr
->role
== FCGI_RESPONDER
&& !fr
->eofSent
&& envSent
) {
1417 /* ap_get_client_block() (called in read_from_client_n_queue()
1418 * can't handle a non-blocking fd, its a bummer. We might be
1419 * able to completely bypass the Apache BUFF routines in still
1420 * do it, but thats a major hassle. Apache 2.X will handle it,
1421 * and then so will we. */
1423 if (read_from_client_n_queue(fr
) != OK
)
1424 return server_error(fr
);
1427 /* To avoid deadlock, don't do a blocking select to write to
1428 * the FastCGI application without selecting to read from the
1429 * FastCGI application.
1431 doClientWrite
= FALSE
;
1432 if (fr
->keepReadingFromFcgiApp
&& BufferFree(fr
->serverInputBuffer
) > 0) {
1435 DWORD bytesavail
= 0;
1437 if (!fr
->using_npipe_io
) {
1439 FD_SET(fr
->fd
, &read_set
);
1441 /* Is data buffered for output to the FastCGI server? */
1442 if (BufferLength(fr
->serverOutputBuffer
) > 0) {
1443 FD_SET(fr
->fd
, &write_set
);
1445 FD_CLR(fr
->fd
, &write_set
);
1451 * If there's data buffered to send to the client, don't
1452 * wait indefinitely for the FastCGI app; the app might
1453 * be doing server push.
1455 if (BufferLength(fr
->clientOutputBuffer
) > 0) {
1457 timeOut
.tv_usec
= 100000; /* 0.1 sec */
1459 else if (dynamic_first_read
) {
1461 struct timeval qwait
;
1463 if (fcgi_util_ticks(&fr
->queueTime
) < 0) {
1464 ap_log_rerror(FCGI_LOG_ERR
, r
, "FastCGI: can't get time of day");
1465 return server_error(fr
);
1468 /* Check for idle_timeout */
1470 dynamic_last_activity_time
= fr
->queueTime
;
1473 struct timeval idle_time
;
1474 timersub(&fr
->queueTime
, &dynamic_last_activity_time
, &idle_time
);
1475 if (idle_time
.tv_sec
> idle_timeout
) {
1476 send_to_pm(FCGI_REQUEST_TIMEOUT_JOB
, fr
->fs_path
, fr
->user
, fr
->group
, 0, 0);
1477 ap_log_rerror(FCGI_LOG_ERR_NOERRNO
, r
,
1478 "FastCGI: comm with (dynamic) server \"%s\" aborted: (first read) idle timeout (%d sec)",
1479 fr
->fs_path
, idle_timeout
);
1480 return server_error(fr
);
1484 timersub(&fr
->queueTime
, &fr
->startTime
, &qwait
);
1486 delay
= dynamic_first_read
* dynamicPleaseStartDelay
;
1487 if (qwait
.tv_sec
< delay
) {
1488 timeOut
.tv_sec
= delay
;
1489 timeOut
.tv_usec
= 100000; /* fudge for select() slop */
1490 timersub(&timeOut
, &qwait
, &timeOut
);
1493 /* Killed time somewhere.. client read? */
1494 send_to_pm(FCGI_REQUEST_TIMEOUT_JOB
, fr
->fs_path
, fr
->user
, fr
->group
, 0, 0);
1495 dynamic_first_read
= qwait
.tv_sec
/ dynamicPleaseStartDelay
+ 1;
1496 timeOut
.tv_sec
= dynamic_first_read
* dynamicPleaseStartDelay
;
1497 timeOut
.tv_usec
= 100000; /* fudge for select() slop */
1498 timersub(&timeOut
, &qwait
, &timeOut
);
1502 timeOut
.tv_sec
= idle_timeout
;
1503 timeOut
.tv_usec
= 0;
1507 if (!fr
->using_npipe_io
) {
1509 if ((status
= ap_select(numFDs
, &read_set
, &write_set
, NULL
, &timeOut
)) < 0) {
1511 errno
= WSAGetLastError();
1513 ap_log_rerror(FCGI_LOG_ERR_ERRNO
, r
,
1514 "FastCGI: comm with server \"%s\" aborted: select() failed", fr
->fs_path
);
1515 return server_error(fr
);
1520 int stopTime
= time(NULL
) + timeOut
.tv_sec
;
1522 if (BufferLength(fr
->serverOutputBuffer
) == 0)
1526 while ((timeOut
.tv_sec
!= 0) && (time(NULL
) <= stopTime
))
1528 BOOL ok
= PeekNamedPipe((HANDLE
) fr
->fd
,NULL
, 0, NULL
, &bytesavail
, NULL
);
1531 ap_log_rerror(FCGI_LOG_ERR
, r
,
1532 "FastCGI: comm with sever \"%s\" aborted: PeekNamedPipe() failed",
1534 return server_error(fr
);
1551 if (BufferLength(fr
->clientOutputBuffer
) > 0) {
1552 doClientWrite
= TRUE
;
1554 else if (dynamic_first_read
) {
1555 struct timeval qwait
;
1557 if (fcgi_util_ticks(&fr
->queueTime
) < 0) {
1558 ap_log_rerror(FCGI_LOG_ERR
, r
, "FastCGI: can't get time of day");
1559 return server_error(fr
);
1562 timersub(&fr
->queueTime
, &fr
->startTime
, &qwait
);
1564 send_to_pm(FCGI_REQUEST_TIMEOUT_JOB
, fr
->fs_path
, fr
->user
, fr
->group
, 0, 0);
1566 dynamic_first_read
= qwait
.tv_sec
/ dynamicPleaseStartDelay
+ 1;
1569 ap_log_rerror(FCGI_LOG_ERR_NOERRNO
, r
,
1570 "FastCGI: comm with server \"%s\" aborted: idle timeout (%d sec)",
1571 fr
->fs_path
, idle_timeout
);
1572 return server_error(fr
);
1576 #if defined(SIGPIPE) && MODULE_MAGIC_NUMBER < 19990320
1577 /* Disable Apache's SIGPIPE handler */
1578 fr
->apache_sigpipe_handler
= signal(SIGPIPE
, SIG_IGN
);
1581 /* Read from the FastCGI server */
1583 if ((fr
->using_npipe_io
1584 && (BufferFree(fr
->serverInputBuffer
) > 0)
1585 && PeekNamedPipe((HANDLE
) fr
->fd
, NULL
, 0, NULL
, &bytesavail
, NULL
)
1586 && (bytesavail
> 0))
1587 || FD_ISSET(fr
->fd
, &read_set
)) {
1589 if (FD_ISSET(fr
->fd
, &read_set
)) {
1591 if (dynamic_first_read
) {
1592 dynamic_first_read
= 0;
1593 if (fcgi_util_ticks(&fr
->queueTime
) < 0) {
1594 ap_log_rerror(FCGI_LOG_ERR
, r
, "FastCGI: can't get time of day");
1595 return server_error(fr
);
1599 if ((status
= fcgi_buf_add_fd(fr
->serverInputBuffer
, fr
->fd
)) < 0) {
1601 if (! fr
->using_npipe_io
)
1602 ap_log_rerror(FCGI_LOG_ERR_ERRNO
, r
,
1603 "FastCGI: comm with server \"%s\" aborted: read failed", fr
->fs_path
);
1606 ap_log_rerror(FCGI_LOG_ERR
, r
,
1607 "FastCGI: comm with server \"%s\" aborted: read failed", fr
->fs_path
);
1608 return server_error(fr
);
1612 fr
->keepReadingFromFcgiApp
= FALSE
;
1613 close_connection_to_fs(fr
);
1617 /* Write to the FastCGI server */
1618 if (BufferLength(fr
->serverOutputBuffer
) > 0)
1621 /* XXX this is broke because it will cause a spin if the app doesn't read */
1622 if (fr
->using_npipe_io
|| FD_ISSET(fr
->fd
, &write_set
))
1624 if (FD_ISSET(fr
->fd
, &write_set
))
1627 if (fcgi_buf_get_to_fd(fr
->serverOutputBuffer
, fr
->fd
) < 0)
1629 /* XXX this could fail even if the app finished sending a response */
1631 if (! fr
->using_npipe_io
)
1632 ap_log_rerror(FCGI_LOG_ERR_ERRNO
, r
,
1633 "FastCGI: comm with server \"%s\" aborted: write failed", fr
->fs_path
);
1636 ap_log_rerror(FCGI_LOG_ERR
, r
,
1637 "FastCGI: comm with server \"%s\" aborted: write failed", fr
->fs_path
);
1639 return server_error(fr
);
1644 #if defined(SIGPIPE) && MODULE_MAGIC_NUMBER < 19990320
1645 /* Reinstall Apache's SIGPIPE handler */
1646 signal(SIGPIPE
, fr
->apache_sigpipe_handler
);
1650 doClientWrite
= TRUE
;
1653 if (fr
->role
== FCGI_RESPONDER
&& doClientWrite
) {
1655 if (write_to_client(fr
) != OK
) {
1656 #if defined(SIGPIPE) && MODULE_MAGIC_NUMBER < 19990320
1657 /* Make sure we leave with Apache's sigpipe_handler in place */
1658 if (fr
->apache_sigpipe_handler
!= NULL
)
1659 signal(SIGPIPE
, fr
->apache_sigpipe_handler
);
1661 close_connection_to_fs(fr
);
1662 ap_kill_timeout(fr
->r
);
1667 if (fcgi_protocol_dequeue(rp
, fr
) != OK
)
1668 return server_error(fr
);
1670 if (fr
->keepReadingFromFcgiApp
&& fr
->exitStatusSet
) {
1671 /* we're done talking to the fcgi app */
1672 fr
->keepReadingFromFcgiApp
= FALSE
;
1673 close_connection_to_fs(fr
);
1676 if (fr
->parseHeader
== SCAN_CGI_READING_HEADERS
) {
1677 if ((err
= process_headers(r
, fr
))) {
1678 ap_log_rerror(FCGI_LOG_ERR_NOERRNO
, r
,
1679 "FastCGI: comm with server \"%s\" aborted: error parsing headers: %s", fr
->fs_path
, err
);
1680 return server_error(fr
);
1686 switch (fr
->parseHeader
) {
1688 case SCAN_CGI_FINISHED
:
1689 if (fr
->role
== FCGI_RESPONDER
) {
1690 #ifdef RUSSIAN_APACHE
1693 ap_bflush(r
->connection
->client
);
1695 ap_bgetopt(r
->connection
->client
, BO_BYTECT
, &r
->bytes_sent
);
1699 case SCAN_CGI_READING_HEADERS
:
1700 ap_log_rerror(FCGI_LOG_ERR_NOERRNO
, r
,
1701 "FastCGI: incomplete headers (%d bytes) received from server \"%s\"",
1702 fr
->header
->nelts
, fr
->fs_path
);
1703 return server_error(fr
);
1705 case SCAN_CGI_BAD_HEADER
:
1706 return server_error(fr
);
1708 case SCAN_CGI_INT_REDIRECT
:
1709 case SCAN_CGI_SRV_REDIRECT
:
1711 * XXX We really should be soaking all client input
1712 * and all script output. See mod_cgi.c.
1713 * There's other differences we need to pick up here as well!
1714 * This has to be revisited.
1726 static fcgi_request
*create_fcgi_request(request_rec
* const r
, const char *fs_path
)
1728 struct stat
*my_finfo
;
1729 pool
* const p
= r
->pool
;
1731 fcgi_request
* const fr
= (fcgi_request
*)ap_pcalloc(p
, sizeof(fcgi_request
));
1734 my_finfo
= (struct stat
*)ap_palloc(p
, sizeof(struct stat
));
1735 if (stat(fs_path
, my_finfo
) < 0) {
1736 ap_log_rerror(FCGI_LOG_ERR_ERRNO
, r
,
1737 "FastCGI: stat() of \"%s\" failed", fs_path
);
1742 my_finfo
= &r
->finfo
;
1743 fs_path
= r
->filename
;
1746 fs
= fcgi_util_fs_get_by_id(fs_path
, r
->server
->server_uid
, r
->server
->server_gid
);
1748 /* Its a request for a dynamic FastCGI application */
1749 const char * const err
=
1750 fcgi_util_fs_is_path_ok(p
, fs_path
, my_finfo
);
1753 ap_log_rerror(FCGI_LOG_ERR_NOERRNO
, r
, "FastCGI: invalid (dynamic) server \"%s\": %s", fs_path
, err
);
1758 fr
->serverInputBuffer
= fcgi_buf_new(p
, SERVER_BUFSIZE
);
1759 fr
->serverOutputBuffer
= fcgi_buf_new(p
, SERVER_BUFSIZE
);
1760 fr
->clientInputBuffer
= fcgi_buf_new(p
, SERVER_BUFSIZE
);
1761 fr
->clientOutputBuffer
= fcgi_buf_new(p
, SERVER_BUFSIZE
);
1762 fr
->erBufPtr
= fcgi_buf_new(p
, sizeof(FCGI_EndRequestBody
) + 1);
1763 fr
->gotHeader
= FALSE
;
1764 fr
->parseHeader
= SCAN_CGI_READING_HEADERS
;
1765 fr
->header
= ap_make_array(p
, 1, 1);
1766 fr
->fs_stderr
= NULL
;
1768 fr
->readingEndRequestBody
= FALSE
;
1770 fr
->exitStatusSet
= FALSE
;
1771 fr
->requestId
= 1; /* anything but zero is OK here */
1772 fr
->eofSent
= FALSE
;
1773 fr
->role
= FCGI_RESPONDER
;
1774 fr
->expectingClientContent
= FALSE
;
1775 fr
->keepReadingFromFcgiApp
= TRUE
;
1777 fr
->fs_path
= fs_path
;
1778 fr
->authHeaders
= ap_make_table(p
, 10);
1780 fr
->fd
= INVALID_SOCKET
;
1781 fr
->dynamic
= ((fs
== NULL
) || (fs
->directive
== APP_CLASS_DYNAMIC
)) ? TRUE
: FALSE
;
1782 fr
->using_npipe_io
= FALSE
;
1784 fr
->dynamic
= (fs
== NULL
) ? TRUE
: FALSE
;
1788 set_uid_n_gid(r
, &fr
->user
, &fr
->group
);
1794 *----------------------------------------------------------------------
1798 * This routine gets called for a request that corresponds to
1799 * a FastCGI connection. It performs the request synchronously.
1802 * Final status of request: OK or NOT_FOUND or SERVER_ERROR.
1805 * Request performed.
1807 *----------------------------------------------------------------------
1810 /* Stolen from mod_cgi.c..
1811 * KLUDGE --- for back-combatibility, we don't have to check ExecCGI
1812 * in ScriptAliased directories, which means we need to know if this
1813 * request came through ScriptAlias or not... so the Alias module
1814 * leaves a note for us.
1816 static int apache_is_scriptaliased(request_rec
*r
)
1818 const char *t
= ap_table_get(r
->notes
, "alias-forced-type");
1819 return t
&& (!strcasecmp(t
, "cgi-script"));
1822 /* If a script wants to produce its own Redirect body, it now
1823 * has to explicitly *say* "Status: 302". If it wants to use
1824 * Apache redirects say "Status: 200". See process_headers().
1826 static int post_process_for_redirects(request_rec
* const r
,
1827 const fcgi_request
* const fr
)
1829 switch(fr
->parseHeader
) {
1830 case SCAN_CGI_INT_REDIRECT
:
1832 /* @@@ There are still differences between the handling in
1833 * mod_cgi and mod_fastcgi. This needs to be revisited.
1835 /* We already read the message body (if any), so don't allow
1836 * the redirected request to think it has one. We can ignore
1837 * Transfer-Encoding, since we used REQUEST_CHUNKED_ERROR.
1840 r
->method_number
= M_GET
;
1841 ap_table_unset(r
->headers_in
, "Content-length");
1843 ap_internal_redirect_handler(ap_table_get(r
->headers_out
, "Location"), r
);
1846 case SCAN_CGI_SRV_REDIRECT
:
1854 /******************************************************************************
1855 * Process fastcgi-script requests. Based on mod_cgi::cgi_handler().
1857 static int content_handler(request_rec
*r
)
1859 fcgi_request
*fr
= NULL
;
1862 FCGIDBG1("->content_handler()");
1864 /* Setup a new FastCGI request */
1865 if ((fr
= create_fcgi_request(r
, NULL
)) == NULL
)
1866 return SERVER_ERROR
;
1868 /* If its a dynamic invocation, make sure scripts are OK here */
1869 if (fr
->dynamic
&& !(ap_allow_options(r
) & OPT_EXECCGI
) && !apache_is_scriptaliased(r
)) {
1870 ap_log_rerror(FCGI_LOG_ERR_NOERRNO
, r
,
1871 "FastCGI: \"ExecCGI Option\" is off in this directory: %s", r
->uri
);
1872 return SERVER_ERROR
;
1875 /* Process the fastcgi-script request */
1876 if ((ret
= do_work(r
, fr
)) != OK
)
1879 /* Special case redirects */
1880 ret
= post_process_for_redirects(r
, fr
);
1882 FCGIDBG1("<-content_handler()");
1888 static int post_process_auth_passed_header(table
*t
, const char *key
, const char * const val
)
1890 if (strncasecmp(key
, "Variable-", 9) == 0)
1893 ap_table_setn(t
, key
, val
);
1897 static int post_process_auth_passed_compat_header(table
*t
, const char *key
, const char * const val
)
1899 if (strncasecmp(key
, "Variable-", 9) == 0)
1900 ap_table_setn(t
, key
+ 9, val
);
1905 static int post_process_auth_failed_header(table
* const t
, const char * const key
, const char * const val
)
1907 ap_table_setn(t
, key
, val
);
1911 static void post_process_auth(fcgi_request
* const fr
, const int passed
)
1913 request_rec
* const r
= fr
->r
;
1915 /* Restore the saved subprocess_env because we muddied ours up */
1916 r
->subprocess_env
= fr
->saved_subprocess_env
;
1919 if (fr
->auth_compat
) {
1920 ap_table_do((int (*)(void *, const char *, const char *))post_process_auth_passed_compat_header
,
1921 (void *)r
->subprocess_env
, fr
->authHeaders
, NULL
);
1924 ap_table_do((int (*)(void *, const char *, const char *))post_process_auth_passed_header
,
1925 (void *)r
->subprocess_env
, fr
->authHeaders
, NULL
);
1929 ap_table_do((int (*)(void *, const char *, const char *))post_process_auth_failed_header
,
1930 (void *)r
->err_headers_out
, fr
->authHeaders
, NULL
);
1933 /* @@@ Restore these.. its a hack until I rewrite the header handling */
1934 r
->status
= HTTP_OK
;
1935 r
->status_line
= NULL
;
1938 static int check_user_authentication(request_rec
*r
)
1940 int res
, authenticated
= 0;
1941 const char *password
;
1943 const fcgi_dir_config
* const dir_config
=
1944 (const fcgi_dir_config
*)ap_get_module_config(r
->per_dir_config
, &fastcgi_module
);
1946 if (dir_config
->authenticator
== NULL
)
1949 /* Get the user password */
1950 if ((res
= ap_get_basic_auth_pw(r
, &password
)) != OK
)
1953 if ((fr
= create_fcgi_request(r
, dir_config
->authenticator
)) == NULL
)
1954 return SERVER_ERROR
;
1956 /* Save the existing subprocess_env, because we're gonna muddy it up */
1957 fr
->saved_subprocess_env
= ap_copy_table(r
->pool
, r
->subprocess_env
);
1959 ap_table_setn(r
->subprocess_env
, "REMOTE_PASSWD", password
);
1960 ap_table_setn(r
->subprocess_env
, "FCGI_APACHE_ROLE", "AUTHENTICATOR");
1962 /* The FastCGI Protocol doesn't differentiate authentication */
1963 fr
->role
= FCGI_AUTHORIZER
;
1965 /* Do we need compatibility mode? */
1966 fr
->auth_compat
= (dir_config
->authenticator_options
& FCGI_COMPAT
);
1968 if ((res
= do_work(r
, fr
)) != OK
)
1969 goto AuthenticationFailed
;
1971 authenticated
= (r
->status
== 200);
1972 post_process_auth(fr
, authenticated
);
1974 /* A redirect shouldn't be allowed during the authentication phase */
1975 if (ap_table_get(r
->headers_out
, "Location") != NULL
) {
1976 ap_log_rerror(FCGI_LOG_ERR_NOERRNO
, r
,
1977 "FastCGI: FastCgiAuthenticator \"%s\" redirected (not allowed)",
1978 dir_config
->authenticator
);
1979 goto AuthenticationFailed
;
1985 AuthenticationFailed
:
1986 if (!(dir_config
->authenticator_options
& FCGI_AUTHORITATIVE
))
1989 /* @@@ Probably should support custom_responses */
1990 ap_note_basic_auth_failure(r
);
1991 ap_log_rerror(FCGI_LOG_ERR_NOERRNO
, r
,
1992 "FastCGI: authentication failed for user \"%s\": %s", r
->connection
->user
, r
->uri
);
1993 return (res
== OK
) ? AUTH_REQUIRED
: res
;
1996 static int check_user_authorization(request_rec
*r
)
1998 int res
, authorized
= 0;
2000 const fcgi_dir_config
* const dir_config
=
2001 (const fcgi_dir_config
*)ap_get_module_config(r
->per_dir_config
, &fastcgi_module
);
2003 if (dir_config
->authorizer
== NULL
)
2006 /* @@@ We should probably honor the existing parameters to the require directive
2007 * as well as allow the definition of new ones (or use the basename of the
2008 * FastCGI server and pass the rest of the directive line), but for now keep
2011 if ((fr
= create_fcgi_request(r
, dir_config
->authorizer
)) == NULL
)
2012 return SERVER_ERROR
;
2014 /* Save the existing subprocess_env, because we're gonna muddy it up */
2015 fr
->saved_subprocess_env
= ap_copy_table(r
->pool
, r
->subprocess_env
);
2017 ap_table_setn(r
->subprocess_env
, "FCGI_APACHE_ROLE", "AUTHORIZER");
2019 fr
->role
= FCGI_AUTHORIZER
;
2021 /* Do we need compatibility mode? */
2022 fr
->auth_compat
= (dir_config
->authenticator_options
& FCGI_COMPAT
);
2024 if ((res
= do_work(r
, fr
)) != OK
)
2025 goto AuthorizationFailed
;
2027 authorized
= (r
->status
== 200);
2028 post_process_auth(fr
, authorized
);
2030 /* A redirect shouldn't be allowed during the authorization phase */
2031 if (ap_table_get(r
->headers_out
, "Location") != NULL
) {
2032 ap_log_rerror(FCGI_LOG_ERR_NOERRNO
, r
,
2033 "FastCGI: FastCgiAuthorizer \"%s\" redirected (not allowed)",
2034 dir_config
->authorizer
);
2035 goto AuthorizationFailed
;
2041 AuthorizationFailed
:
2042 if (!(dir_config
->authorizer_options
& FCGI_AUTHORITATIVE
))
2045 /* @@@ Probably should support custom_responses */
2046 ap_note_basic_auth_failure(r
);
2047 ap_log_rerror(FCGI_LOG_ERR_NOERRNO
, r
,
2048 "FastCGI: authorization failed for user \"%s\": %s", r
->connection
->user
, r
->uri
);
2049 return (res
== OK
) ? AUTH_REQUIRED
: res
;
2052 static int check_access(request_rec
*r
)
2054 int res
, access_allowed
= 0;
2056 const fcgi_dir_config
* const dir_config
=
2057 (fcgi_dir_config
*)ap_get_module_config(r
->per_dir_config
, &fastcgi_module
);
2059 if (dir_config
== NULL
|| dir_config
->access_checker
== NULL
)
2062 if ((fr
= create_fcgi_request(r
, dir_config
->access_checker
)) == NULL
)
2063 return SERVER_ERROR
;
2065 /* Save the existing subprocess_env, because we're gonna muddy it up */
2066 fr
->saved_subprocess_env
= ap_copy_table(r
->pool
, r
->subprocess_env
);
2068 ap_table_setn(r
->subprocess_env
, "FCGI_APACHE_ROLE", "ACCESS_CHECKER");
2070 /* The FastCGI Protocol doesn't differentiate access control */
2071 fr
->role
= FCGI_AUTHORIZER
;
2073 /* Do we need compatibility mode? */
2074 fr
->auth_compat
= (dir_config
->authenticator_options
& FCGI_COMPAT
);
2076 if ((res
= do_work(r
, fr
)) != OK
)
2079 access_allowed
= (r
->status
== 200);
2080 post_process_auth(fr
, access_allowed
);
2082 /* A redirect shouldn't be allowed during the access check phase */
2083 if (ap_table_get(r
->headers_out
, "Location") != NULL
) {
2084 ap_log_rerror(FCGI_LOG_ERR_NOERRNO
, r
,
2085 "FastCGI: FastCgiAccessChecker \"%s\" redirected (not allowed)",
2086 dir_config
->access_checker
);
2094 if (!(dir_config
->access_checker_options
& FCGI_AUTHORITATIVE
))
2097 /* @@@ Probably should support custom_responses */
2098 ap_log_rerror(FCGI_LOG_ERR_NOERRNO
, r
, "FastCGI: access denied: %s", r
->uri
);
2099 return (res
== OK
) ? FORBIDDEN
: res
;
2102 command_rec fastcgi_cmds
[] = {
2103 { "AppClass", fcgi_config_new_static_server
, NULL
, RSRC_CONF
, RAW_ARGS
, NULL
},
2104 { "FastCgiServer", fcgi_config_new_static_server
, NULL
, RSRC_CONF
, RAW_ARGS
, NULL
},
2106 { "ExternalAppClass", fcgi_config_new_external_server
, NULL
, RSRC_CONF
, RAW_ARGS
, NULL
},
2107 { "FastCgiExternalServer", fcgi_config_new_external_server
, NULL
, RSRC_CONF
, RAW_ARGS
, NULL
},
2109 { "FastCgiIpcDir", fcgi_config_set_socket_dir
, NULL
, RSRC_CONF
, TAKE1
, NULL
},
2111 { "FastCgiSuexec", fcgi_config_set_wrapper
, NULL
, RSRC_CONF
, TAKE1
, NULL
},
2112 { "FastCgiWrapper", fcgi_config_set_wrapper
, NULL
, RSRC_CONF
, TAKE1
, NULL
},
2114 { "FCGIConfig", fcgi_config_set_config
, NULL
, RSRC_CONF
, RAW_ARGS
, NULL
},
2115 { "FastCgiConfig", fcgi_config_set_config
, NULL
, RSRC_CONF
, RAW_ARGS
, NULL
},
2117 { "FastCgiAuthenticator", fcgi_config_new_auth_server
,
2118 (void *)FCGI_AUTH_TYPE_AUTHENTICATOR
, ACCESS_CONF
, TAKE12
,
2119 "a fastcgi-script path (absolute or relative to ServerRoot) followed by an optional -compat" },
2120 { "FastCgiAuthenticatorAuthoritative", fcgi_config_set_authoritative_slot
,
2121 (void *)XtOffsetOf(fcgi_dir_config
, authenticator_options
), ACCESS_CONF
, FLAG
,
2122 "Set to 'off' to allow authentication to be passed along to lower modules upon failure" },
2124 { "FastCgiAuthorizer", fcgi_config_new_auth_server
,
2125 (void *)FCGI_AUTH_TYPE_AUTHORIZER
, ACCESS_CONF
, TAKE12
,
2126 "a fastcgi-script path (absolute or relative to ServerRoot) followed by an optional -compat" },
2127 { "FastCgiAuthorizerAuthoritative", fcgi_config_set_authoritative_slot
,
2128 (void *)XtOffsetOf(fcgi_dir_config
, authorizer_options
), ACCESS_CONF
, FLAG
,
2129 "Set to 'off' to allow authorization to be passed along to lower modules upon failure" },
2131 { "FastCgiAccessChecker", fcgi_config_new_auth_server
,
2132 (void *)FCGI_AUTH_TYPE_ACCESS_CHECKER
, ACCESS_CONF
, TAKE12
,
2133 "a fastcgi-script path (absolute or relative to ServerRoot) followed by an optional -compat" },
2134 { "FastCgiAccessCheckerAuthoritative", fcgi_config_set_authoritative_slot
,
2135 (void *)XtOffsetOf(fcgi_dir_config
, access_checker_options
), ACCESS_CONF
, FLAG
,
2136 "Set to 'off' to allow access control to be passed along to lower modules upon failure" },
2141 handler_rec fastcgi_handlers
[] = {
2142 { FCGI_MAGIC_TYPE
, content_handler
},
2143 { "fastcgi-script", content_handler
},
2148 module MODULE_VAR_EXPORT fastcgi_module
= {
2149 STANDARD_MODULE_STUFF
,
2150 init_module
, /* initializer */
2151 fcgi_config_create_dir_config
, /* per-dir config creator */
2152 NULL
, /* per-dir config merger (default: override) */
2153 NULL
, /* per-server config creator */
2154 NULL
, /* per-server config merger (default: override) */
2155 fastcgi_cmds
, /* command table */
2156 fastcgi_handlers
, /* [9] content handlers */
2157 NULL
, /* [2] URI-to-filename translation */
2158 check_user_authentication
, /* [5] authenticate user_id */
2159 check_user_authorization
, /* [6] authorize user_id */
2160 check_access
, /* [4] check access (based on src & http headers) */
2161 NULL
, /* [7] check/set MIME type */
2162 NULL
, /* [8] fixups */
2163 NULL
, /* [10] logger */
2164 NULL
, /* [3] header-parser */
2165 fcgi_child_init
, /* process initialization */
2166 fcgi_child_exit
, /* process exit/cleanup */
2167 NULL
/* [1] post read-request handling */