4 * Apache server module for FastCGI.
6 * $Id: mod_fastcgi.c,v 1.105 2001/02/19 06:00:10 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 fcgi_pm_job
*fcgi_dynamic_mbox
= NULL
;
109 HANDLE
*fcgi_dynamic_mbox_mutex
= NULL
;
110 HANDLE fcgi_pm_thread
= INVALID_HANDLE_VALUE
;
113 char *fcgi_empty_env
= NULL
;
115 u_int dynamicMaxProcs
= FCGI_DEFAULT_MAX_PROCS
;
116 u_int dynamicMinProcs
= FCGI_DEFAULT_MIN_PROCS
;
117 u_int dynamicMaxClassProcs
= FCGI_DEFAULT_MAX_CLASS_PROCS
;
118 u_int dynamicKillInterval
= FCGI_DEFAULT_KILL_INTERVAL
;
119 u_int dynamicUpdateInterval
= FCGI_DEFAULT_UPDATE_INTERVAL
;
120 float dynamicGain
= FCGI_DEFAULT_GAIN
;
121 u_int dynamicThreshold1
= FCGI_DEFAULT_THRESHOLD_1
;
122 u_int dynamicThresholdN
= FCGI_DEFAULT_THRESHOLD_N
;
123 u_int dynamicPleaseStartDelay
= FCGI_DEFAULT_START_PROCESS_DELAY
;
124 u_int dynamicAppConnectTimeout
= FCGI_DEFAULT_APP_CONN_TIMEOUT
;
125 char **dynamicEnvp
= &fcgi_empty_env
;
126 u_int dynamicProcessSlack
= FCGI_DEFAULT_PROCESS_SLACK
;
127 int dynamicAutoRestart
= FCGI_DEFAULT_RESTART_DYNAMIC
;
128 int dynamicAutoUpdate
= FCGI_DEFAULT_AUTOUPDATE
;
129 u_int dynamicListenQueueDepth
= FCGI_DEFAULT_LISTEN_Q
;
130 u_int dynamicInitStartDelay
= DEFAULT_INIT_START_DELAY
;
131 u_int dynamicRestartDelay
= FCGI_DEFAULT_RESTART_DELAY
;
132 array_header
*dynamic_pass_headers
= NULL
;
133 u_int dynamic_idle_timeout
= FCGI_DEFAULT_IDLE_TIMEOUT
;
135 /*******************************************************************************
136 * Construct a message and write it to the pm_pipe.
138 static void send_to_pm(pool
* const p
, const char id
, const char * const fs_path
,
139 const char *user
, const char * const group
, const unsigned long q_usec
,
140 const unsigned long req_usec
)
143 fcgi_pm_job
*job
= NULL
;
145 if (!(job
= (fcgi_pm_job
*) malloc(sizeof(fcgi_pm_job
))))
149 char buf
[FCGI_MAX_MSG_LEN
];
152 if (strlen(fs_path
) > FCGI_MAXPATH
) {
153 ap_log_error(FCGI_LOG_ERR_NOERRNO
, fcgi_apache_main_server
,
154 "FastCGI: the path \"%s\" is too long (>%d) for a dynamic server", fs_path
, FCGI_MAXPATH
);
163 job
->fs_path
= strdup(fs_path
);
164 job
->user
= strdup(user
);
165 job
->group
= strdup(group
);
167 job
->start_time
= 0L;
169 buflen
= sprintf(buf
, "%c %s %s %s*", id
, fs_path
, user
, group
);
176 job
->fs_path
= strdup(fs_path
);
177 job
->user
= strdup(user
);
178 job
->group
= strdup(group
);
180 job
->start_time
= 0L;
182 buflen
= sprintf(buf
, "%c %s %s %s*", id
, fs_path
, user
, group
);
189 job
->fs_path
= strdup(fs_path
);
191 job
->start_time
= req_usec
;
192 job
->user
= strdup(user
);
193 job
->group
= strdup(group
);
195 buflen
= sprintf(buf
, "%c %s %s %s %lu %lu*", id
, fs_path
, user
, group
, q_usec
, req_usec
);
201 if (fcgi_pm_add_job(job
) == 0)
204 SetEvent(fcgi_event_handles
[MBOX_EVENT
]);
206 ap_assert(buflen
<= FCGI_MAX_MSG_LEN
);
208 if (write(fcgi_pm_pipe
[1], (const void *)buf
, buflen
) != buflen
) {
209 ap_log_error(FCGI_LOG_WARN
, fcgi_apache_main_server
,
210 "FastCGI: write() to PM failed");
217 *----------------------------------------------------------------------
221 * An Apache module initializer, called by the Apache core
222 * after reading the server config.
224 * Start the process manager no matter what, since there may be a
225 * request for dynamic FastCGI applications without any being
226 * configured as static applications. Also, check for the existence
227 * and create if necessary a subdirectory into which all dynamic
230 *----------------------------------------------------------------------
232 static void init_module(server_rec
*s
, pool
*p
)
236 /* Register to reset to default values when the config pool is cleaned */
238 ap_register_cleanup(p
, NULL
, fcgi_config_reset_globals
, ap_null_cleanup
);
241 ap_add_version_component("mod_fastcgi/" MOD_FASTCGI_VERSION
);
243 fcgi_config_set_fcgi_uid_n_gid(1);
245 /* keep these handy */
246 fcgi_config_pool
= p
;
247 fcgi_apache_main_server
= s
;
250 /* Create Unix/Domain socket directory */
251 if ((err
= fcgi_config_make_dir(p
, fcgi_socket_dir
)))
252 ap_log_error(FCGI_LOG_ERR
, s
, "FastCGI: %s", err
);
255 /* Create Dynamic directory */
256 if ((err
= fcgi_config_make_dynamic_dir(p
, 1)))
257 ap_log_error(FCGI_LOG_ERR
, s
, "FastCGI: %s", err
);
260 /* Create the pipe for comm with the PM */
261 if (pipe(fcgi_pm_pipe
) < 0) {
262 ap_log_error(FCGI_LOG_ERR
, s
, "FastCGI: pipe() failed");
265 /* Spawn the PM only once. Under Unix, Apache calls init() routines
266 * twice, once before detach() and once after. Win32 doesn't detach.
267 * Under DSO, DSO modules are unloaded between the two init() calls.
268 * Under Unix, the -X switch causes two calls to init() but no detach
269 * (but all subprocesses are wacked so the PM is toasted anyway)! */
271 if (ap_standalone
&& getppid() != 1)
274 /* Start the Process Manager */
275 fcgi_pm_pid
= ap_spawn_child(p
, fcgi_pm_main
, NULL
, kill_only_once
, NULL
, NULL
, NULL
);
276 if (fcgi_pm_pid
<= 0) {
277 ap_log_error(FCGI_LOG_ALERT
, s
,
278 "FastCGI: can't start the process manager, spawn_child() failed");
281 close(fcgi_pm_pipe
[0]);
285 static void fcgi_child_init(server_rec
*server_conf
, pool
*p
)
288 /* Create the Event Handlers */
289 fcgi_event_handles
[0] = CreateEvent(NULL
, FALSE
, FALSE
, NULL
);
290 fcgi_event_handles
[1] = CreateEvent(NULL
, FALSE
, FALSE
, NULL
);
291 fcgi_event_handles
[2] = CreateEvent(NULL
, FALSE
, FALSE
, NULL
);
292 fcgi_dynamic_mbox_mutex
= ap_create_mutex("fcgi_dynamic_mbox_mutex");
294 /* Spawn of the process manager thread */
295 fcgi_pm_thread
= CreateThread(NULL
, 0, (LPTHREAD_START_ROUTINE
)fcgi_pm_main
, NULL
, 0, NULL
);
300 static void fcgi_child_exit(server_rec
*server_conf
, pool
*p
) {
303 /* Signaling the PM thread tp exit*/
304 SetEvent(fcgi_event_handles
[TERM_EVENT
]);
306 /* Waiting on pm thread to exit */
307 WaitForSingleObject(fcgi_pm_thread
, INFINITE
);
314 *----------------------------------------------------------------------
318 * Terminate a line: scan to the next newline, scan back to the
319 * first non-space character and store a terminating zero. Return
320 * the next character past the end of the newline.
322 * If the end of the string is reached, ASSERT!
324 * If the FIRST character(s) in the line are '\n' or "\r\n", the
325 * first character is replaced with a NULL and next character
326 * past the newline is returned. NOTE: this condition supercedes
327 * the processing of RFC-822 continuation lines.
329 * If continuation is set to 'TRUE', then it parses a (possible)
330 * sequence of RFC-822 continuation lines.
336 * Termination byte stored in string.
338 *----------------------------------------------------------------------
340 static char *get_header_line(char *start
, int continuation
)
345 if(p
[0] == '\r' && p
[1] == '\n') { /* If EOL in 1st 2 chars */
346 p
++; /* point to \n and stop */
347 } else if(*p
!= '\n') {
350 if(*p
== '\n' && p
[1] != ' ' && p
[1] != '\t')
355 while(*p
!= '\0' && *p
!= '\n') {
361 ap_assert(*p
!= '\0');
366 * Trim any trailing whitespace.
368 while(isspace((unsigned char)p
[-1]) && p
> start
) {
377 *----------------------------------------------------------------------
381 * Call with r->parseHeader == SCAN_CGI_READING_HEADERS
382 * and initial script output in fr->header.
384 * If the initial script output does not include the header
385 * terminator ("\r\n\r\n") process_headers returns with no side
386 * effects, to be called again when more script output
387 * has been appended to fr->header.
389 * If the initial script output includes the header terminator,
390 * process_headers parses the headers and determines whether or
391 * not the remaining script output will be sent to the client.
392 * If so, process_headers sends the HTTP response headers to the
393 * client and copies any non-header script output to the output
400 * May set r->parseHeader to:
401 * SCAN_CGI_FINISHED -- headers parsed, returning script response
402 * SCAN_CGI_BAD_HEADER -- malformed header from script
403 * SCAN_CGI_INT_REDIRECT -- handler should perform internal redirect
404 * SCAN_CGI_SRV_REDIRECT -- handler should return REDIRECT
406 *----------------------------------------------------------------------
409 static const char *process_headers(request_rec
*r
, fcgi_request
*fr
)
411 char *p
, *next
, *name
, *value
;
413 int hasContentType
, hasStatus
, hasLocation
;
415 ap_assert(fr
->parseHeader
== SCAN_CGI_READING_HEADERS
);
417 if (fr
->header
== NULL
)
421 * Do we have the entire header? Scan for the blank line that
422 * terminates the header.
424 p
= (char *)fr
->header
->elts
;
425 len
= fr
->header
->nelts
;
427 while(len
-- && flag
< 2) {
437 name
= "Invalid Character";
447 /* Return (to be called later when we have more data)
448 * if we don't have an entire header. */
453 * Parse all the headers.
455 fr
->parseHeader
= SCAN_CGI_FINISHED
;
456 hasContentType
= hasStatus
= hasLocation
= FALSE
;
457 next
= (char *)fr
->header
->elts
;
459 next
= get_header_line(name
= next
, TRUE
);
463 if ((p
= strchr(name
, ':')) == NULL
) {
467 while (p
!= name
&& isspace((unsigned char)*(p
- 1))) {
474 if (strpbrk(name
, " \t") != NULL
) {
478 while (isspace((unsigned char)*value
)) {
482 if (strcasecmp(name
, "Status") == 0) {
483 int statusValue
= strtol(value
, NULL
, 10);
486 goto DuplicateNotAllowed
;
488 if (statusValue
< 0) {
489 fr
->parseHeader
= SCAN_CGI_BAD_HEADER
;
490 return ap_psprintf(r
->pool
, "invalid Status '%s'", value
);
493 r
->status
= statusValue
;
494 r
->status_line
= ap_pstrdup(r
->pool
, value
);
498 if (fr
->role
== FCGI_RESPONDER
) {
499 if (strcasecmp(name
, "Content-type") == 0) {
500 if (hasContentType
) {
501 goto DuplicateNotAllowed
;
503 hasContentType
= TRUE
;
504 r
->content_type
= ap_pstrdup(r
->pool
, value
);
508 if (strcasecmp(name
, "Location") == 0) {
510 goto DuplicateNotAllowed
;
513 ap_table_set(r
->headers_out
, "Location", value
);
517 /* If the script wants them merged, it can do it */
518 ap_table_add(r
->err_headers_out
, name
, value
);
522 ap_table_add(fr
->authHeaders
, name
, value
);
526 if (fr
->role
!= FCGI_RESPONDER
)
530 * Who responds, this handler or Apache?
533 const char *location
= ap_table_get(r
->headers_out
, "Location");
535 * Based on internal redirect handling in mod_cgi.c...
537 * If a script wants to produce its own Redirect
538 * body, it now has to explicitly *say* "Status: 302"
540 if (r
->status
== 200) {
541 if(location
[0] == '/') {
543 * Location is an relative path. This handler will
544 * consume all script output, then have Apache perform an
547 fr
->parseHeader
= SCAN_CGI_INT_REDIRECT
;
551 * Location is an absolute URL. If the script didn't
552 * produce a Content-type header, this handler will
553 * consume all script output and then have Apache generate
554 * its standard redirect response. Otherwise this handler
555 * will transmit the script's response.
557 fr
->parseHeader
= SCAN_CGI_SRV_REDIRECT
;
563 * We're responding. Send headers, buffer excess script output.
565 ap_send_http_header(r
);
567 /* We need to reinstate our timeout, send_http_header() kill()s it */
568 ap_hard_timeout("FastCGI request processing", r
);
573 len
= fr
->header
->nelts
- (next
- fr
->header
->elts
);
575 ap_assert(BufferLength(fr
->clientOutputBuffer
) == 0);
576 if (BufferFree(fr
->clientOutputBuffer
) < len
) {
577 fr
->clientOutputBuffer
= fcgi_buf_new(r
->pool
, len
);
579 ap_assert(BufferFree(fr
->clientOutputBuffer
) >= len
);
581 int sent
= fcgi_buf_add_block(fr
->clientOutputBuffer
, next
, len
);
582 ap_assert(sent
== len
);
587 /* Log first line of a multi-line header */
588 if ((p
= strpbrk(name
, "\r\n")) != NULL
)
590 fr
->parseHeader
= SCAN_CGI_BAD_HEADER
;
591 return ap_psprintf(r
->pool
, "malformed header '%s'", name
);
594 fr
->parseHeader
= SCAN_CGI_BAD_HEADER
;
595 return ap_psprintf(r
->pool
, "duplicate header '%s'", name
);
599 * Read from the client filling both the FastCGI server buffer and the
600 * client buffer with the hopes of buffering the client data before
601 * making the connect() to the FastCGI server. This prevents slow
602 * clients from keeping the FastCGI server in processing longer than is
605 static int read_from_client_n_queue(fcgi_request
*fr
)
611 while (BufferFree(fr
->clientInputBuffer
) > 0 || BufferFree(fr
->serverOutputBuffer
) > 0) {
612 fcgi_protocol_queue_client_buffer(fr
);
614 if (fr
->expectingClientContent
<= 0)
617 fcgi_buf_get_free_block_info(fr
->clientInputBuffer
, &end
, &count
);
621 if ((countRead
= ap_get_client_block(fr
->r
, end
, count
)) < 0)
624 if (countRead
== 0) {
625 fr
->expectingClientContent
= 0;
628 fcgi_buf_add_update(fr
->clientInputBuffer
, countRead
);
629 ap_reset_timeout(fr
->r
);
635 static int write_to_client(fcgi_request
*fr
)
640 fcgi_buf_get_block_info(fr
->clientOutputBuffer
, &begin
, &count
);
644 /* If fewer than count bytes are written, an error occured.
645 * ap_bwrite() typically forces a flushed write to the client, this
646 * effectively results in a block (and short packets) - it should
647 * be fixed, but I didn't win much support for the idea on new-httpd.
648 * So, without patching Apache, the best way to deal with this is
649 * to size the fcgi_bufs to hold all of the script output (within
650 * reason) so the script can be released from having to wait around
651 * for the transmission to the client to complete. */
652 #ifdef RUSSIAN_APACHE
653 if (ap_rwrite(begin
, count
, fr
->r
) != count
) {
654 ap_log_rerror(FCGI_LOG_INFO
, fr
->r
,
655 "FastCGI: client stopped connection before send body completed");
659 if (ap_bwrite(fr
->r
->connection
->client
, begin
, count
) != (int) count
) {
660 ap_log_rerror(FCGI_LOG_INFO
, fr
->r
,
661 "FastCGI: client stopped connection before send body completed");
666 ap_reset_timeout(fr
->r
);
668 /* Don't bother with a wrapped buffer, limiting exposure to slow
669 * clients. The BUFF routines don't allow a writev from above,
670 * and don't always memcpy to minimize small write()s, this should
671 * be fixed, but I didn't win much support for the idea on
672 * new-httpd - I'll have to _prove_ its a problem first.. */
674 /* The default behaviour used to be to flush with every write, but this
675 * can tie up the FastCGI server longer than is necessary so its an option now */
676 if (fr
->fs
&& fr
->fs
->flush
) {
677 #ifdef RUSSIAN_APACHE
678 if (ap_rflush(fr
->r
)) {
679 ap_log_rerror(FCGI_LOG_INFO
, fr
->r
,
680 "FastCGI: client stopped connection before send body completed");
684 if (ap_bflush(fr
->r
->connection
->client
)) {
685 ap_log_rerror(FCGI_LOG_INFO
, fr
->r
,
686 "FastCGI: client stopped connection before send body completed");
690 ap_reset_timeout(fr
->r
);
693 fcgi_buf_toss(fr
->clientOutputBuffer
, count
);
697 /*******************************************************************************
698 * Determine the user and group the wrapper should be called with.
699 * Based on code in Apache's create_argv_cmd() (util_script.c).
701 static void set_uid_n_gid(request_rec
*r
, const char **user
, const char **group
)
703 if (fcgi_wrapper
== NULL
) {
709 if (strncmp("/~", r
->uri
, 2) == 0) {
710 /* its a user dir uri, just send the ~user, and leave it to the PM */
711 char *end
= strchr(r
->uri
+ 2, '/');
714 *user
= memcpy(ap_pcalloc(r
->pool
, end
- r
->uri
), r
->uri
+ 1, end
- r
->uri
- 1);
716 *user
= ap_pstrdup(r
->pool
, r
->uri
+ 1);
720 *user
= ap_psprintf(r
->pool
, "%ld", (long)r
->server
->server_uid
);
721 *group
= ap_psprintf(r
->pool
, "%ld", (long)r
->server
->server_gid
);
725 /*******************************************************************************
726 * Close the connection to the FastCGI server. This is normally called by
727 * do_work(), but may also be called as in request pool cleanup.
729 static void close_connection_to_fs(fcgi_request
*fr
)
731 pool
*rp
= fr
->r
->pool
;
734 ap_pclosesocket(rp
, fr
->fd
);
739 if (fr
->lockFd
!= NULL
) {
740 fcgi_rdwr_unlock(fr
->lockFd
, READER
);
743 if (fr
->lockFd
>= 0) {
744 ap_pclosef(rp
, fr
->lockFd
);
748 if (fr
->keepReadingFromFcgiApp
== FALSE
) {
749 /* XXX REQ_COMPLETE is only sent for requests which complete
750 * normally WRT the fcgi app. There is no data sent for
751 * connect() timeouts or requests which complete abnormally.
752 * KillDynamicProcs() and RemoveRecords() need to be looked at
753 * to be sure they can reasonably handle these cases before
754 * sending these sort of stats - theres some funk in there.
755 * XXX We should do something special when this a pool cleanup.
757 if (fcgi_util_gettimeofday(&fr
->completeTime
) < 0) {
758 /* there's no point to aborting the request, just log it */
759 ap_log_error(FCGI_LOG_ERR
, fr
->r
->server
, "FastCGI: gettimeofday() failed");
761 struct timeval qtime
, rtime
;
763 timersub(&fr
->queueTime
, &fr
->startTime
, &qtime
);
764 timersub(&fr
->completeTime
, &fr
->queueTime
, &rtime
);
766 send_to_pm(rp
, REQ_COMPLETE
, fr
->fs_path
,
768 qtime
.tv_sec
* 1000000 + qtime
.tv_usec
,
769 rtime
.tv_sec
* 1000000 + rtime
.tv_usec
);
777 static void lock_cleanup(void * data
)
779 fcgi_rdwr_unlock((FcgiRWLock
*) data
, READER
);
782 static int set_nonblocking(SOCKET fd
, int nonblocking
)
784 unsigned long ioctl_arg
= (nonblocking
) ? 1 : 0;
785 return ioctlsocket(fd
, FIONBIO
, &ioctl_arg
);
790 static int set_nonblocking(int fd
, int nonblocking
)
793 int fd_flags
= fcntl(fd
, F_GETFL
, 0);
795 if (fd_flags
< 0) return -1;
797 #if defined(O_NONBLOCK)
798 nb_flag
= O_NONBLOCK
;
799 #elif defined(O_NDELAY)
801 #elif defined(FNDELAY)
804 #error "TODO - don't read from app until all data from client is posted."
807 fd_flags
= (nonblocking
) ? (fd_flags
| nb_flag
) : (fd_flags
& ~nb_flag
);
809 return fcntl(fd
, F_SETFL
, fd_flags
);
814 /*******************************************************************************
815 * Connect to the FastCGI server.
817 static const char *open_connection_to_fs(fcgi_request
*fr
)
820 fd_set write_fds
, read_fds
;
822 request_rec
* const r
= fr
->r
;
823 pool
* const rp
= r
->pool
;
824 const char *socket_path
= NULL
;
825 struct sockaddr
*socket_addr
= NULL
;
826 int socket_addr_len
= 0;
830 const char *err
= NULL
;
833 /* Create the connection point */
835 socket_path
= fcgi_util_socket_hash_filename(rp
, fr
->fs_path
, fr
->user
, fr
->group
);
836 socket_path
= fcgi_util_socket_make_path_absolute(rp
, socket_path
, 1);
839 err
= fcgi_util_socket_make_domain_addr(rp
, (struct sockaddr_un
**)&socket_addr
,
840 &socket_addr_len
, socket_path
);
846 if (fr
->fs
->dest_addr
!= NULL
) {
847 socket_addr
= fr
->fs
->dest_addr
;
849 else if (fr
->fs
->socket_addr
) {
850 socket_addr
= fr
->fs
->socket_addr
;
853 socket_path
= fr
->fs
->socket_path
;
856 socket_addr
= fr
->fs
->socket_addr
;
858 socket_addr_len
= fr
->fs
->socket_addr_len
;
861 /* Dynamic app's lockfile handling */
864 const char *lockFileName
= fcgi_util_socket_get_lock_filename(rp
, socket_path
);
874 if (stat(lockFileName
, &lstbuf
) == 0 && S_ISREG(lstbuf
.st_mode
))
877 if (dynamicAutoUpdate
&& (stat(fr
->fs_path
, &bstbuf
) == 0)
879 && ((fr
->fs
->restartTime
> 0) && (fr
->fs
->restartTime
< bstbuf
.st_mtime
)))
881 && (lstbuf
.st_mtime
< bstbuf
.st_mtime
))
884 struct timeval tv
= {1, 0};
886 /* Its already running, but there's a newer one,
887 * ask the process manager to start it.
888 * it will notice that the binary is newer,
889 * and do a restart instead.
891 send_to_pm(rp
, PLEASE_START
, fr
->fs_path
, fr
->user
, fr
->group
, 0, 0);
893 /* Avoid sleep/alarm interactions */
894 ap_select(0, NULL
, NULL
, NULL
, &tv
);
897 fr
->lockFd
= fr
->fs
->dynamic_lock
;
900 fr
->lockFd
= ap_popenf(rp
, lockFileName
, O_APPEND
, 0);
901 result
= (fr
->lockFd
< 0) ? (0) : (1);
904 struct timeval tv
= {1, 0};
906 send_to_pm(rp
, PLEASE_START
, fr
->fs_path
, fr
->user
, fr
->group
, 0, 0);
911 /* Avoid sleep/alarm interactions */
912 ap_select(0, NULL
, NULL
, NULL
, &tv
);
916 fr
->fs
= fcgi_util_fs_get_by_id(fr
->fs_path
, 0, 0);
918 } while (result
!= 1);
920 /* Block until we get a shared (non-exclusive) read Lock */
921 if (fcgi_wait_for_shared_read_lock(fr
->lockFd
) < 0)
922 return "failed to obtain a shared read lock";
926 ap_register_cleanup(rp
, (void *) fr
->lockFd
, lock_cleanup
, ap_null_cleanup
);
930 FCGIDBG2("got_dynamic_shared_read_lock: %s", fr
->fs_path
);
940 int max_connect_time
= FCGI_NAMED_PIPE_CONNECT_TIMEOUT
;
942 fr
->using_npipe_io
= TRUE
;
946 interval
= dynamicPleaseStartDelay
* 1000;
948 if (dynamicAppConnectTimeout
) {
949 max_connect_time
= dynamicAppConnectTimeout
;
954 interval
= FCGI_NAMED_PIPE_CONNECT_TIMEOUT
* 1000;
956 if (fr
->fs
->appConnectTimeout
) {
957 max_connect_time
= fr
->fs
->appConnectTimeout
;
961 if (fcgi_util_gettimeofday(&fr
->startTime
) < 0) {
962 return "gettimeofday() failed";
967 fr
->fd
= (SOCKET
) CreateFile(socket_path
,
968 GENERIC_READ
| GENERIC_WRITE
,
969 FILE_SHARE_READ
| FILE_SHARE_WRITE
,
970 NULL
, // no security attributes
971 OPEN_EXISTING
, // opens existing pipe
972 FILE_ATTRIBUTE_NORMAL
, // default attributes
973 NULL
); // no template file
975 if (fr
->fd
!= (SOCKET
) INVALID_HANDLE_VALUE
) {
979 if (GetLastError() != ERROR_PIPE_BUSY
) {
980 return("CreateFile() failed ()");
983 // All pipe instances are busy, so wait
984 ready
= WaitNamedPipe(socket_path
, interval
);
986 if (fr
->dynamic
&& !ready
) {
987 send_to_pm(rp
, CONN_TIMEOUT
, fr
->fs_path
, fr
->user
, fr
->group
, 0, 0);
990 if (fcgi_util_gettimeofday(&fr
->queueTime
) < 0) {
991 return "gettimeofday() failed";
994 connect_time
= fr
->queueTime
.tv_sec
- fr
->startTime
.tv_sec
;
996 FCGIDBG5("interval=%d, max_connect_time=%d, connect_time=%d, ready=%d", interval
, max_connect_time
, connect_time
, ready
);
998 } while (connect_time
< max_connect_time
);
1000 if (fr
->fd
== (SOCKET
) INVALID_HANDLE_VALUE
) {
1001 return "CreateFile()/WaitNamedPipe() timed out";
1004 FCGIDBG2("got_named_pipe_connect: %s", fr
->fs_path
);
1007 ap_note_cleanups_for_h(rp
, (HANDLE
) fr
->fd
);
1008 ap_unblock_alarms();
1014 /* Create the socket */
1015 fr
->fd
= ap_psocket(rp
, socket_addr
->sa_family
, SOCK_STREAM
, 0);
1018 return "ap_psocket() failed";
1021 if (fr
->fd
>= FD_SETSIZE
) {
1022 return ap_psprintf(rp
, "socket file descriptor (%u) is larger than "
1023 "FD_SETSIZE (%u), you probably need to rebuild Apache with a "
1024 "larger FD_SETSIZE", fr
->fd
, FD_SETSIZE
);
1028 /* If appConnectTimeout is non-zero, setup do a non-blocking connect */
1029 if ((fr
->dynamic
&& dynamicAppConnectTimeout
) || (!fr
->dynamic
&& fr
->fs
->appConnectTimeout
)) {
1030 set_nonblocking(fr
->fd
, TRUE
);
1033 if (fr
->dynamic
&& fcgi_util_gettimeofday(&fr
->startTime
) < 0)
1034 return "gettimeofday() failed";
1037 if (connect(fr
->fd
, (struct sockaddr
*)socket_addr
, socket_addr_len
) == 0)
1038 goto ConnectionComplete
;
1041 errcode
= GetLastError();
1042 if (errcode
!= WSAEWOULDBLOCK
)
1043 return "connect() failed";
1045 /* ECONNREFUSED means the listen queue is full (or there isn't one).
1046 * With dynamic I can at least make sure the PM knows this is occuring */
1047 if (fr
->dynamic
&& errno
== ECONNREFUSED
) {
1048 /* @@@ This might be better as some other "kind" of message */
1049 send_to_pm(rp
, CONN_TIMEOUT
, fr
->fs_path
, fr
->user
, fr
->group
, 0, 0);
1051 errno
= ECONNREFUSED
;
1054 if (errno
!= EINPROGRESS
)
1055 return "connect() failed";
1058 /* The connect() is non-blocking */
1064 FD_ZERO(&write_fds
);
1065 FD_SET(fr
->fd
, &write_fds
);
1066 read_fds
= write_fds
;
1067 tval
.tv_sec
= dynamicPleaseStartDelay
;
1070 status
= ap_select((fr
->fd
+1), &read_fds
, &write_fds
, NULL
, &tval
);
1074 if (fcgi_util_gettimeofday(&fr
->queueTime
) < 0)
1075 return "gettimeofday() failed";
1079 /* select() timed out */
1080 send_to_pm(rp
, CONN_TIMEOUT
, fr
->fs_path
, fr
->user
, fr
->group
, 0, 0);
1081 } while ((fr
->queueTime
.tv_sec
- fr
->startTime
.tv_sec
) < (int)dynamicAppConnectTimeout
);
1083 /* XXX These can be moved down when dynamic vars live is a struct */
1085 return ap_psprintf(rp
, "connect() timed out (appConnTimeout=%dsec)",
1086 dynamicAppConnectTimeout
);
1090 tval
.tv_sec
= fr
->fs
->appConnectTimeout
;
1092 FD_ZERO(&write_fds
);
1093 FD_SET(fr
->fd
, &write_fds
);
1094 read_fds
= write_fds
;
1096 status
= ap_select((fr
->fd
+1), &read_fds
, &write_fds
, NULL
, &tval
);
1098 return ap_psprintf(rp
, "connect() timed out (appConnTimeout=%dsec)",
1099 fr
->fs
->appConnectTimeout
);
1104 return "select() failed";
1106 if (FD_ISSET(fr
->fd
, &write_fds
) || FD_ISSET(fr
->fd
, &read_fds
)) {
1108 NET_SIZE_T len
= sizeof(error
);
1110 if (getsockopt(fr
->fd
, SOL_SOCKET
, SO_ERROR
, (char *)&error
, &len
) < 0)
1111 /* Solaris pending error */
1112 return "select() failed (Solaris pending error)";
1115 /* Berkeley-derived pending error */
1117 return "select() failed (pending error)";
1120 return "select() error - THIS CAN'T HAPPEN!";
1123 /* Return to blocking mode if it was set up */
1124 if ((fr
->dynamic
&& dynamicAppConnectTimeout
) || (!fr
->dynamic
&& fr
->fs
->appConnectTimeout
)) {
1125 set_nonblocking(fr
->fd
, FALSE
);
1129 if (socket_addr
->sa_family
== AF_INET
) {
1130 /* We shouldn't be sending small packets and there's no application
1131 * level ack of the data we send, so disable Nagle */
1133 setsockopt(fr
->fd
, IPPROTO_TCP
, TCP_NODELAY
, (char *)&set
, sizeof(set
));
1140 static int server_error(fcgi_request
*fr
)
1142 #if defined(SIGPIPE) && MODULE_MAGIC_NUMBER < 19990320
1143 /* Make sure we leave with Apache's sigpipe_handler in place */
1144 if (fr
->apache_sigpipe_handler
!= NULL
)
1145 signal(SIGPIPE
, fr
->apache_sigpipe_handler
);
1147 close_connection_to_fs(fr
);
1148 ap_kill_timeout(fr
->r
);
1149 return SERVER_ERROR
;
1152 static void cleanup(void *data
)
1154 const fcgi_request
* const fr
= (fcgi_request
*)data
;
1160 set_nonblocking(fr
->fd
, FALSE
);
1163 if (fr
->fs_stderr_len
) {
1164 ap_log_rerror(FCGI_LOG_ERR_NOERRNO
, fr
->r
,
1165 "FastCGI: server \"%s\" stderr: %s", fr
->fs_path
, fr
->fs_stderr
);
1169 /*----------------------------------------------------------------------
1170 * This is the core routine for moving data between the FastCGI
1171 * application and the Web server's client.
1173 static int do_work(request_rec
*r
, fcgi_request
*fr
)
1175 struct timeval timeOut
, dynamic_last_activity_time
= {0, 0};
1176 fd_set read_set
, write_set
;
1177 int status
= 0, idle_timeout
;
1178 int numFDs
, dynamic_first_read
= fr
->dynamic
? 1 : 0;
1180 int envSent
= FALSE
; /* has the complete ENV been buffered? */
1183 const char *err
= NULL
;
1186 FD_ZERO(&write_set
);
1188 fcgi_protocol_queue_begin_request(fr
);
1190 /* Buffer as much of the environment as we can fit */
1192 envSent
= fcgi_protocol_queue_env(r
, fr
, &env
);
1194 /* Start the Apache dropdead timer. See comments at top of file. */
1195 ap_hard_timeout("buffering of FastCGI client data", r
);
1197 /* Read as much as possible from the client. */
1198 if (fr
->role
== FCGI_RESPONDER
) {
1199 status
= ap_setup_client_block(r
, REQUEST_CHUNKED_ERROR
);
1204 fr
->expectingClientContent
= (ap_should_client_block(r
) != 0);
1206 if (read_from_client_n_queue(fr
) != OK
)
1207 return server_error(fr
);
1210 /* Connect to the FastCGI Application */
1211 ap_hard_timeout("connect() to FastCGI server", r
);
1212 if ((err
= open_connection_to_fs(fr
))) {
1213 ap_log_rerror(FCGI_LOG_ERR
, r
,
1214 "FastCGI: failed to connect to server \"%s\": %s", fr
->fs_path
, err
);
1215 return server_error(fr
);
1218 numFDs
= fr
->fd
+ 1;
1219 idle_timeout
= fr
->dynamic
? dynamic_idle_timeout
: fr
->fs
->idle_timeout
;
1221 if (dynamic_first_read
) {
1222 dynamic_last_activity_time
= fr
->startTime
;
1224 if (dynamicAppConnectTimeout
) {
1225 struct timeval qwait
;
1226 timersub(&fr
->queueTime
, &fr
->startTime
, &qwait
);
1227 dynamic_first_read
= qwait
.tv_sec
/ dynamicPleaseStartDelay
+ 1;
1231 /* @@@ We never reset the timer in this loop, most folks don't mess w/
1232 * Timeout directive which means we've got the 5 min default which is way
1233 * to long to tie up a fs. We need a better/configurable solution that
1234 * uses the select */
1235 ap_hard_timeout("FastCGI request processing", r
);
1237 /* Register to get the script's stderr logged at the end of the request */
1239 ap_register_cleanup(rp
, (void *)fr
, cleanup
, ap_null_cleanup
);
1240 ap_unblock_alarms();
1242 /* Before we do any writing, set the connection non-blocking */
1244 if (fr
->using_npipe_io
) {
1245 DWORD mode
= PIPE_NOWAIT
| PIPE_READMODE_BYTE
;
1246 SetNamedPipeHandleState((HANDLE
) fr
->fd
, &mode
, NULL
, NULL
);
1251 set_nonblocking(fr
->fd
, TRUE
);
1253 /* The socket is writeable, so get the first write out of the way */
1254 if (fcgi_buf_get_to_fd(fr
->serverOutputBuffer
, fr
->fd
) < 0) {
1255 ap_log_rerror(FCGI_LOG_ERR
, r
,
1256 "FastCGI: comm with server \"%s\" aborted: write failed", fr
->fs_path
);
1257 return server_error(fr
);
1260 while (fr
->keepReadingFromFcgiApp
1261 || BufferLength(fr
->serverInputBuffer
) > 0
1262 || BufferLength(fr
->clientOutputBuffer
) > 0) {
1264 /* If we didn't buffer all of the environment yet, buffer some more */
1266 envSent
= fcgi_protocol_queue_env(r
, fr
, &env
);
1268 /* Read as much as possible from the client. */
1269 if (fr
->role
== FCGI_RESPONDER
&& !fr
->eofSent
&& envSent
) {
1271 /* ap_get_client_block() (called in read_from_client_n_queue()
1272 * can't handle a non-blocking fd, its a bummer. We might be
1273 * able to completely bypass the Apache BUFF routines in still
1274 * do it, but thats a major hassle. Apache 2.X will handle it,
1275 * and then so will we. */
1277 if (read_from_client_n_queue(fr
) != OK
)
1278 return server_error(fr
);
1281 /* To avoid deadlock, don't do a blocking select to write to
1282 * the FastCGI application without selecting to read from the
1283 * FastCGI application.
1285 doClientWrite
= FALSE
;
1286 if (fr
->keepReadingFromFcgiApp
&& BufferFree(fr
->serverInputBuffer
) > 0) {
1289 DWORD bytesavail
= 0;
1291 if (!fr
->using_npipe_io
) {
1293 FD_SET(fr
->fd
, &read_set
);
1295 /* Is data buffered for output to the FastCGI server? */
1296 if (BufferLength(fr
->serverOutputBuffer
) > 0) {
1297 FD_SET(fr
->fd
, &write_set
);
1299 FD_CLR(fr
->fd
, &write_set
);
1305 * If there's data buffered to send to the client, don't
1306 * wait indefinitely for the FastCGI app; the app might
1307 * be doing server push.
1309 if (BufferLength(fr
->clientOutputBuffer
) > 0) {
1311 timeOut
.tv_usec
= 100000; /* 0.1 sec */
1313 else if (dynamic_first_read
) {
1315 struct timeval qwait
;
1317 if (fcgi_util_gettimeofday(&fr
->queueTime
) < 0) {
1318 ap_log_rerror(FCGI_LOG_ERR
, r
, "FastCGI: gettimeofday() failed");
1319 return server_error(fr
);
1322 /* Check for idle_timeout */
1324 dynamic_last_activity_time
= fr
->queueTime
;
1327 struct timeval idle_time
;
1328 timersub(&fr
->queueTime
, &dynamic_last_activity_time
, &idle_time
);
1329 if (idle_time
.tv_sec
> idle_timeout
) {
1330 send_to_pm(rp
, CONN_TIMEOUT
, fr
->fs_path
, fr
->user
, fr
->group
, 0, 0);
1331 ap_log_rerror(FCGI_LOG_ERR_NOERRNO
, r
,
1332 "FastCGI: comm with (dynamic) server \"%s\" aborted: (first read) idle timeout (%d sec)",
1333 fr
->fs_path
, idle_timeout
);
1334 return server_error(fr
);
1338 timersub(&fr
->queueTime
, &fr
->startTime
, &qwait
);
1340 delay
= dynamic_first_read
* dynamicPleaseStartDelay
;
1341 if (qwait
.tv_sec
< delay
) {
1342 timeOut
.tv_sec
= delay
;
1343 timeOut
.tv_usec
= 100000; /* fudge for select() slop */
1344 timersub(&timeOut
, &qwait
, &timeOut
);
1347 /* Killed time somewhere.. client read? */
1348 send_to_pm(rp
, CONN_TIMEOUT
, fr
->fs_path
, fr
->user
, fr
->group
, 0, 0);
1349 dynamic_first_read
= qwait
.tv_sec
/ dynamicPleaseStartDelay
+ 1;
1350 timeOut
.tv_sec
= dynamic_first_read
* dynamicPleaseStartDelay
;
1351 timeOut
.tv_usec
= 100000; /* fudge for select() slop */
1352 timersub(&timeOut
, &qwait
, &timeOut
);
1356 timeOut
.tv_sec
= idle_timeout
;
1357 timeOut
.tv_usec
= 0;
1361 if (!fr
->using_npipe_io
) {
1363 if ((status
= ap_select(numFDs
, &read_set
, &write_set
, NULL
, &timeOut
)) < 0) {
1364 ap_log_rerror(FCGI_LOG_ERR
, r
,
1365 "FastCGI: comm with server \"%s\" aborted: select() failed", fr
->fs_path
);
1366 return server_error(fr
);
1371 int stopTime
= time(NULL
) + timeOut
.tv_sec
;
1373 if (BufferLength(fr
->serverOutputBuffer
) == 0) {
1376 while ((timeOut
.tv_sec
!= 0) && (time(NULL
) <= stopTime
)) {
1377 if (PeekNamedPipe((HANDLE
) fr
->fd
,NULL
, 0, NULL
, &bytesavail
, NULL
) &&
1393 if (BufferLength(fr
->clientOutputBuffer
) > 0) {
1394 doClientWrite
= TRUE
;
1396 else if (dynamic_first_read
) {
1397 struct timeval qwait
;
1399 if (fcgi_util_gettimeofday(&fr
->queueTime
) < 0) {
1400 ap_log_rerror(FCGI_LOG_ERR
, r
, "FastCGI: gettimeofday() failed");
1401 return server_error(fr
);
1404 timersub(&fr
->queueTime
, &fr
->startTime
, &qwait
);
1406 send_to_pm(rp
, CONN_TIMEOUT
, fr
->fs_path
, fr
->user
, fr
->group
, 0, 0);
1408 dynamic_first_read
= qwait
.tv_sec
/ dynamicPleaseStartDelay
+ 1;
1411 ap_log_rerror(FCGI_LOG_ERR_NOERRNO
, r
,
1412 "FastCGI: comm with server \"%s\" aborted: idle timeout (%d sec)",
1413 fr
->fs_path
, idle_timeout
);
1414 return server_error(fr
);
1418 #if defined(SIGPIPE) && MODULE_MAGIC_NUMBER < 19990320
1419 /* Disable Apache's SIGPIPE handler */
1420 fr
->apache_sigpipe_handler
= signal(SIGPIPE
, SIG_IGN
);
1423 /* Read from the FastCGI server */
1425 if ((fr
->using_npipe_io
1426 && (BufferFree(fr
->serverInputBuffer
) > 0)
1427 && PeekNamedPipe((HANDLE
) fr
->fd
, NULL
, 0, NULL
, &bytesavail
, NULL
)
1428 && (bytesavail
> 0))
1429 || FD_ISSET(fr
->fd
, &read_set
)) {
1431 if (FD_ISSET(fr
->fd
, &read_set
)) {
1433 if (dynamic_first_read
) {
1434 dynamic_first_read
= 0;
1435 if (fcgi_util_gettimeofday(&fr
->queueTime
) < 0) {
1436 ap_log_rerror(FCGI_LOG_ERR
, r
, "FastCGI: gettimeofday() failed");
1437 return server_error(fr
);
1441 if ((status
= fcgi_buf_add_fd(fr
->serverInputBuffer
, fr
->fd
)) < 0) {
1442 ap_log_rerror(FCGI_LOG_ERR
, r
,
1443 "FastCGI: comm with server \"%s\" aborted: read failed", fr
->fs_path
);
1444 return server_error(fr
);
1448 fr
->keepReadingFromFcgiApp
= FALSE
;
1449 close_connection_to_fs(fr
);
1453 /* Write to the FastCGI server */
1455 if ((fr
->using_npipe_io
&& (BufferLength(fr
->serverOutputBuffer
) > 0))
1456 || FD_ISSET(fr
->fd
, &write_set
)) {
1458 if (FD_ISSET(fr
->fd
, &write_set
)) {
1461 if (fcgi_buf_get_to_fd(fr
->serverOutputBuffer
, fr
->fd
) < 0) {
1462 ap_log_rerror(FCGI_LOG_ERR
, r
,
1463 "FastCGI: comm with server \"%s\" aborted: write failed", fr
->fs_path
);
1464 return server_error(fr
);
1468 #if defined(SIGPIPE) && MODULE_MAGIC_NUMBER < 19990320
1469 /* Reinstall Apache's SIGPIPE handler */
1470 signal(SIGPIPE
, fr
->apache_sigpipe_handler
);
1474 doClientWrite
= TRUE
;
1477 if (fr
->role
== FCGI_RESPONDER
&& doClientWrite
) {
1479 if (write_to_client(fr
) != OK
) {
1480 #if defined(SIGPIPE) && MODULE_MAGIC_NUMBER < 19990320
1481 /* Make sure we leave with Apache's sigpipe_handler in place */
1482 if (fr
->apache_sigpipe_handler
!= NULL
)
1483 signal(SIGPIPE
, fr
->apache_sigpipe_handler
);
1485 close_connection_to_fs(fr
);
1486 ap_kill_timeout(fr
->r
);
1491 if (fcgi_protocol_dequeue(rp
, fr
) != OK
)
1492 return server_error(fr
);
1494 if (fr
->keepReadingFromFcgiApp
&& fr
->exitStatusSet
) {
1495 /* we're done talking to the fcgi app */
1496 fr
->keepReadingFromFcgiApp
= FALSE
;
1497 close_connection_to_fs(fr
);
1500 if (fr
->parseHeader
== SCAN_CGI_READING_HEADERS
) {
1501 if ((err
= process_headers(r
, fr
))) {
1502 ap_log_rerror(FCGI_LOG_ERR
, r
,
1503 "FastCGI: comm with server \"%s\" aborted: error parsing headers: %s", fr
->fs_path
, err
);
1504 return server_error(fr
);
1510 switch (fr
->parseHeader
) {
1512 case SCAN_CGI_FINISHED
:
1513 if (fr
->role
== FCGI_RESPONDER
) {
1514 #ifdef RUSSIAN_APACHE
1517 ap_bflush(r
->connection
->client
);
1519 ap_bgetopt(r
->connection
->client
, BO_BYTECT
, &r
->bytes_sent
);
1523 case SCAN_CGI_READING_HEADERS
:
1524 ap_log_rerror(FCGI_LOG_ERR
, r
,
1525 "FastCGI: incomplete headers (%d bytes) received from server \"%s\"",
1526 fr
->header
->nelts
, fr
->fs_path
);
1527 return server_error(fr
);
1529 case SCAN_CGI_BAD_HEADER
:
1530 return server_error(fr
);
1532 case SCAN_CGI_INT_REDIRECT
:
1533 case SCAN_CGI_SRV_REDIRECT
:
1535 * XXX We really should be soaking all client input
1536 * and all script output. See mod_cgi.c.
1537 * There's other differences we need to pick up here as well!
1538 * This has to be revisited.
1551 static fcgi_request
*create_fcgi_request(request_rec
* const r
, const char *fs_path
)
1553 struct stat
*my_finfo
;
1554 pool
* const p
= r
->pool
;
1556 fcgi_request
* const fr
= (fcgi_request
*)ap_pcalloc(p
, sizeof(fcgi_request
));
1559 my_finfo
= (struct stat
*)ap_palloc(p
, sizeof(struct stat
));
1560 if (stat(fs_path
, my_finfo
) < 0) {
1561 ap_log_rerror(FCGI_LOG_ERR
, r
, "FastCGI: stat() of \"%s\" failed", fs_path
);
1566 my_finfo
= &r
->finfo
;
1567 fs_path
= r
->filename
;
1570 fs
= fcgi_util_fs_get_by_id(fs_path
, r
->server
->server_uid
, r
->server
->server_gid
);
1572 /* Its a request for a dynamic FastCGI application */
1573 const char * const err
=
1574 fcgi_util_fs_is_path_ok(p
, fs_path
, my_finfo
, r
->server
->server_uid
, r
->server
->server_gid
);
1577 ap_log_rerror(FCGI_LOG_ERR_NOERRNO
, r
, "FastCGI: invalid (dynamic) server \"%s\": %s", fs_path
, err
);
1582 fr
->serverInputBuffer
= fcgi_buf_new(p
, SERVER_BUFSIZE
);
1583 fr
->serverOutputBuffer
= fcgi_buf_new(p
, SERVER_BUFSIZE
);
1584 fr
->clientInputBuffer
= fcgi_buf_new(p
, SERVER_BUFSIZE
);
1585 fr
->clientOutputBuffer
= fcgi_buf_new(p
, SERVER_BUFSIZE
);
1586 fr
->erBufPtr
= fcgi_buf_new(p
, sizeof(FCGI_EndRequestBody
) + 1);
1587 fr
->gotHeader
= FALSE
;
1588 fr
->parseHeader
= SCAN_CGI_READING_HEADERS
;
1589 fr
->header
= ap_make_array(p
, 1, 1);
1590 fr
->fs_stderr
= NULL
;
1592 fr
->readingEndRequestBody
= FALSE
;
1594 fr
->exitStatusSet
= FALSE
;
1595 fr
->requestId
= 1; /* anything but zero is OK here */
1596 fr
->eofSent
= FALSE
;
1597 fr
->role
= FCGI_RESPONDER
;
1598 fr
->expectingClientContent
= FALSE
;
1599 fr
->keepReadingFromFcgiApp
= TRUE
;
1601 fr
->fs_path
= fs_path
;
1602 fr
->authHeaders
= ap_make_table(p
, 10);
1604 fr
->fd
= INVALID_SOCKET
;
1605 fr
->dynamic
= ((fs
== NULL
) || (fs
->directive
== APP_CLASS_DYNAMIC
)) ? TRUE
: FALSE
;
1606 fr
->using_npipe_io
= FALSE
;
1608 fr
->dynamic
= (fs
== NULL
) ? TRUE
: FALSE
;
1613 set_uid_n_gid(r
, &fr
->user
, &fr
->group
);
1619 *----------------------------------------------------------------------
1623 * This routine gets called for a request that corresponds to
1624 * a FastCGI connection. It performs the request synchronously.
1627 * Final status of request: OK or NOT_FOUND or SERVER_ERROR.
1630 * Request performed.
1632 *----------------------------------------------------------------------
1635 /* Stolen from mod_cgi.c..
1636 * KLUDGE --- for back-combatibility, we don't have to check ExecCGI
1637 * in ScriptAliased directories, which means we need to know if this
1638 * request came through ScriptAlias or not... so the Alias module
1639 * leaves a note for us.
1641 static int apache_is_scriptaliased(request_rec
*r
)
1643 const char *t
= ap_table_get(r
->notes
, "alias-forced-type");
1644 return t
&& (!strcasecmp(t
, "cgi-script"));
1647 /* If a script wants to produce its own Redirect body, it now
1648 * has to explicitly *say* "Status: 302". If it wants to use
1649 * Apache redirects say "Status: 200". See process_headers().
1651 static int post_process_for_redirects(request_rec
* const r
,
1652 const fcgi_request
* const fr
)
1654 switch(fr
->parseHeader
) {
1655 case SCAN_CGI_INT_REDIRECT
:
1657 /* @@@ There are still differences between the handling in
1658 * mod_cgi and mod_fastcgi. This needs to be revisited.
1660 /* We already read the message body (if any), so don't allow
1661 * the redirected request to think it has one. We can ignore
1662 * Transfer-Encoding, since we used REQUEST_CHUNKED_ERROR.
1665 r
->method_number
= M_GET
;
1666 ap_table_unset(r
->headers_in
, "Content-length");
1668 ap_internal_redirect_handler(ap_table_get(r
->headers_out
, "Location"), r
);
1671 case SCAN_CGI_SRV_REDIRECT
:
1679 /******************************************************************************
1680 * Process fastcgi-script requests. Based on mod_cgi::cgi_handler().
1682 static int content_handler(request_rec
*r
)
1684 fcgi_request
*fr
= NULL
;
1687 /* Setup a new FastCGI request */
1688 if ((fr
= create_fcgi_request(r
, NULL
)) == NULL
)
1689 return SERVER_ERROR
;
1691 /* If its a dynamic invocation, make sure scripts are OK here */
1692 if (fr
->dynamic
&& !(ap_allow_options(r
) & OPT_EXECCGI
) && !apache_is_scriptaliased(r
)) {
1693 ap_log_rerror(FCGI_LOG_ERR_NOERRNO
, r
,
1694 "FastCGI: \"ExecCGI Option\" is off in this directory: %s", r
->uri
);
1695 return SERVER_ERROR
;
1698 /* Process the fastcgi-script request */
1699 if ((ret
= do_work(r
, fr
)) != OK
)
1702 /* Special case redirects */
1703 return post_process_for_redirects(r
, fr
);
1707 static int post_process_auth_passed_header(table
*t
, const char *key
, const char * const val
)
1709 if (strncasecmp(key
, "Variable-", 9) == 0)
1712 ap_table_setn(t
, key
, val
);
1716 static int post_process_auth_passed_compat_header(table
*t
, const char *key
, const char * const val
)
1718 if (strncasecmp(key
, "Variable-", 9) == 0)
1719 ap_table_setn(t
, key
+ 9, val
);
1724 static int post_process_auth_failed_header(table
* const t
, const char * const key
, const char * const val
)
1726 ap_table_setn(t
, key
, val
);
1730 static void post_process_auth(fcgi_request
* const fr
, const int passed
)
1732 request_rec
* const r
= fr
->r
;
1734 /* Restore the saved subprocess_env because we muddied ours up */
1735 r
->subprocess_env
= fr
->saved_subprocess_env
;
1738 if (fr
->auth_compat
) {
1739 ap_table_do((int (*)(void *, const char *, const char *))post_process_auth_passed_compat_header
,
1740 (void *)r
->subprocess_env
, fr
->authHeaders
, NULL
);
1743 ap_table_do((int (*)(void *, const char *, const char *))post_process_auth_passed_header
,
1744 (void *)r
->subprocess_env
, fr
->authHeaders
, NULL
);
1748 ap_table_do((int (*)(void *, const char *, const char *))post_process_auth_failed_header
,
1749 (void *)r
->err_headers_out
, fr
->authHeaders
, NULL
);
1752 /* @@@ Restore these.. its a hack until I rewrite the header handling */
1753 r
->status
= HTTP_OK
;
1754 r
->status_line
= NULL
;
1757 static int check_user_authentication(request_rec
*r
)
1759 int res
, authenticated
= 0;
1760 const char *password
;
1762 const fcgi_dir_config
* const dir_config
=
1763 (const fcgi_dir_config
*)ap_get_module_config(r
->per_dir_config
, &fastcgi_module
);
1765 if (dir_config
->authenticator
== NULL
)
1768 /* Get the user password */
1769 if ((res
= ap_get_basic_auth_pw(r
, &password
)) != OK
)
1772 if ((fr
= create_fcgi_request(r
, dir_config
->authenticator
)) == NULL
)
1773 return SERVER_ERROR
;
1775 /* Save the existing subprocess_env, because we're gonna muddy it up */
1776 fr
->saved_subprocess_env
= ap_copy_table(r
->pool
, r
->subprocess_env
);
1778 ap_table_setn(r
->subprocess_env
, "REMOTE_PASSWD", password
);
1779 ap_table_setn(r
->subprocess_env
, "FCGI_APACHE_ROLE", "AUTHENTICATOR");
1781 /* The FastCGI Protocol doesn't differentiate authentication */
1782 fr
->role
= FCGI_AUTHORIZER
;
1784 /* Do we need compatibility mode? */
1785 fr
->auth_compat
= (dir_config
->authenticator_options
& FCGI_COMPAT
);
1787 if ((res
= do_work(r
, fr
)) != OK
)
1788 goto AuthenticationFailed
;
1790 authenticated
= (r
->status
== 200);
1791 post_process_auth(fr
, authenticated
);
1793 /* A redirect shouldn't be allowed during the authentication phase */
1794 if (ap_table_get(r
->headers_out
, "Location") != NULL
) {
1795 ap_log_rerror(FCGI_LOG_ERR_NOERRNO
, r
,
1796 "FastCGI: FastCgiAuthenticator \"%s\" redirected (not allowed)",
1797 dir_config
->authenticator
);
1798 goto AuthenticationFailed
;
1804 AuthenticationFailed
:
1805 if (!(dir_config
->authenticator_options
& FCGI_AUTHORITATIVE
))
1808 /* @@@ Probably should support custom_responses */
1809 ap_note_basic_auth_failure(r
);
1810 ap_log_rerror(FCGI_LOG_ERR_NOERRNO
, r
,
1811 "FastCGI: authentication failed for user \"%s\": %s", r
->connection
->user
, r
->uri
);
1812 return (res
== OK
) ? AUTH_REQUIRED
: res
;
1815 static int check_user_authorization(request_rec
*r
)
1817 int res
, authorized
= 0;
1819 const fcgi_dir_config
* const dir_config
=
1820 (const fcgi_dir_config
*)ap_get_module_config(r
->per_dir_config
, &fastcgi_module
);
1822 if (dir_config
->authorizer
== NULL
)
1825 /* @@@ We should probably honor the existing parameters to the require directive
1826 * as well as allow the definition of new ones (or use the basename of the
1827 * FastCGI server and pass the rest of the directive line), but for now keep
1830 if ((fr
= create_fcgi_request(r
, dir_config
->authorizer
)) == NULL
)
1831 return SERVER_ERROR
;
1833 /* Save the existing subprocess_env, because we're gonna muddy it up */
1834 fr
->saved_subprocess_env
= ap_copy_table(r
->pool
, r
->subprocess_env
);
1836 ap_table_setn(r
->subprocess_env
, "FCGI_APACHE_ROLE", "AUTHORIZER");
1838 fr
->role
= FCGI_AUTHORIZER
;
1840 /* Do we need compatibility mode? */
1841 fr
->auth_compat
= (dir_config
->authenticator_options
& FCGI_COMPAT
);
1843 if ((res
= do_work(r
, fr
)) != OK
)
1844 goto AuthorizationFailed
;
1846 authorized
= (r
->status
== 200);
1847 post_process_auth(fr
, authorized
);
1849 /* A redirect shouldn't be allowed during the authorization phase */
1850 if (ap_table_get(r
->headers_out
, "Location") != NULL
) {
1851 ap_log_rerror(FCGI_LOG_ERR_NOERRNO
, r
,
1852 "FastCGI: FastCgiAuthorizer \"%s\" redirected (not allowed)",
1853 dir_config
->authorizer
);
1854 goto AuthorizationFailed
;
1860 AuthorizationFailed
:
1861 if (!(dir_config
->authorizer_options
& FCGI_AUTHORITATIVE
))
1864 /* @@@ Probably should support custom_responses */
1865 ap_note_basic_auth_failure(r
);
1866 ap_log_rerror(FCGI_LOG_ERR_NOERRNO
, r
,
1867 "FastCGI: authorization failed for user \"%s\": %s", r
->connection
->user
, r
->uri
);
1868 return (res
== OK
) ? AUTH_REQUIRED
: res
;
1871 static int check_access(request_rec
*r
)
1873 int res
, access_allowed
= 0;
1875 const fcgi_dir_config
* const dir_config
=
1876 (fcgi_dir_config
*)ap_get_module_config(r
->per_dir_config
, &fastcgi_module
);
1878 if (dir_config
== NULL
|| dir_config
->access_checker
== NULL
)
1881 if ((fr
= create_fcgi_request(r
, dir_config
->access_checker
)) == NULL
)
1882 return SERVER_ERROR
;
1884 /* Save the existing subprocess_env, because we're gonna muddy it up */
1885 fr
->saved_subprocess_env
= ap_copy_table(r
->pool
, r
->subprocess_env
);
1887 ap_table_setn(r
->subprocess_env
, "FCGI_APACHE_ROLE", "ACCESS_CHECKER");
1889 /* The FastCGI Protocol doesn't differentiate access control */
1890 fr
->role
= FCGI_AUTHORIZER
;
1892 /* Do we need compatibility mode? */
1893 fr
->auth_compat
= (dir_config
->authenticator_options
& FCGI_COMPAT
);
1895 if ((res
= do_work(r
, fr
)) != OK
)
1898 access_allowed
= (r
->status
== 200);
1899 post_process_auth(fr
, access_allowed
);
1901 /* A redirect shouldn't be allowed during the access check phase */
1902 if (ap_table_get(r
->headers_out
, "Location") != NULL
) {
1903 ap_log_rerror(FCGI_LOG_ERR_NOERRNO
, r
,
1904 "FastCGI: FastCgiAccessChecker \"%s\" redirected (not allowed)",
1905 dir_config
->access_checker
);
1913 if (!(dir_config
->access_checker_options
& FCGI_AUTHORITATIVE
))
1916 /* @@@ Probably should support custom_responses */
1917 ap_log_rerror(FCGI_LOG_ERR_NOERRNO
, r
, "FastCGI: access denied: %s", r
->uri
);
1918 return (res
== OK
) ? FORBIDDEN
: res
;
1923 command_rec fastcgi_cmds
[] = {
1924 { "AppClass", fcgi_config_new_static_server
, NULL
, RSRC_CONF
, RAW_ARGS
, NULL
},
1925 { "FastCgiServer", fcgi_config_new_static_server
, NULL
, RSRC_CONF
, RAW_ARGS
, NULL
},
1927 { "ExternalAppClass", fcgi_config_new_external_server
, NULL
, RSRC_CONF
, RAW_ARGS
, NULL
},
1928 { "FastCgiExternalServer", fcgi_config_new_external_server
, NULL
, RSRC_CONF
, RAW_ARGS
, NULL
},
1930 { "FastCgiIpcDir", fcgi_config_set_socket_dir
, NULL
, RSRC_CONF
, TAKE1
, NULL
},
1932 { "FastCgiSuexec", fcgi_config_set_wrapper
, NULL
, RSRC_CONF
, TAKE1
, NULL
},
1933 { "FastCgiWrapper", fcgi_config_set_wrapper
, NULL
, RSRC_CONF
, TAKE1
, NULL
},
1935 { "FCGIConfig", fcgi_config_set_config
, NULL
, RSRC_CONF
, RAW_ARGS
, NULL
},
1936 { "FastCgiConfig", fcgi_config_set_config
, NULL
, RSRC_CONF
, RAW_ARGS
, NULL
},
1938 { "FastCgiAuthenticator", fcgi_config_new_auth_server
,
1939 (void *)FCGI_AUTH_TYPE_AUTHENTICATOR
, ACCESS_CONF
, TAKE12
,
1940 "a fastcgi-script path (absolute or relative to ServerRoot) followed by an optional -compat" },
1941 { "FastCgiAuthenticatorAuthoritative", fcgi_config_set_authoritative_slot
,
1942 (void *)XtOffsetOf(fcgi_dir_config
, authenticator_options
), ACCESS_CONF
, FLAG
,
1943 "Set to 'off' to allow authentication to be passed along to lower modules upon failure" },
1945 { "FastCgiAuthorizer", fcgi_config_new_auth_server
,
1946 (void *)FCGI_AUTH_TYPE_AUTHORIZER
, ACCESS_CONF
, TAKE12
,
1947 "a fastcgi-script path (absolute or relative to ServerRoot) followed by an optional -compat" },
1948 { "FastCgiAuthorizerAuthoritative", fcgi_config_set_authoritative_slot
,
1949 (void *)XtOffsetOf(fcgi_dir_config
, authorizer_options
), ACCESS_CONF
, FLAG
,
1950 "Set to 'off' to allow authorization to be passed along to lower modules upon failure" },
1952 { "FastCgiAccessChecker", fcgi_config_new_auth_server
,
1953 (void *)FCGI_AUTH_TYPE_ACCESS_CHECKER
, ACCESS_CONF
, TAKE12
,
1954 "a fastcgi-script path (absolute or relative to ServerRoot) followed by an optional -compat" },
1955 { "FastCgiAccessCheckerAuthoritative", fcgi_config_set_authoritative_slot
,
1956 (void *)XtOffsetOf(fcgi_dir_config
, access_checker_options
), ACCESS_CONF
, FLAG
,
1957 "Set to 'off' to allow access control to be passed along to lower modules upon failure" },
1962 handler_rec fastcgi_handlers
[] = {
1963 { FCGI_MAGIC_TYPE
, content_handler
},
1964 { "fastcgi-script", content_handler
},
1969 module MODULE_VAR_EXPORT fastcgi_module
= {
1970 STANDARD_MODULE_STUFF
,
1971 init_module
, /* initializer */
1972 fcgi_config_create_dir_config
, /* per-dir config creator */
1973 NULL
, /* per-dir config merger (default: override) */
1974 NULL
, /* per-server config creator */
1975 NULL
, /* per-server config merger (default: override) */
1976 fastcgi_cmds
, /* command table */
1977 fastcgi_handlers
, /* [9] content handlers */
1978 NULL
, /* [2] URI-to-filename translation */
1979 check_user_authentication
, /* [5] authenticate user_id */
1980 check_user_authorization
, /* [6] authorize user_id */
1981 check_access
, /* [4] check access (based on src & http headers) */
1982 NULL
, /* [7] check/set MIME type */
1983 NULL
, /* [8] fixups */
1984 NULL
, /* [10] logger */
1985 NULL
, /* [3] header-parser */
1986 fcgi_child_init
, /* process initialization */
1987 fcgi_child_exit
, /* process exit/cleanup */
1988 NULL
/* [1] post read-request handling */