4 * Apache server module for FastCGI.
6 * $Id: mod_fastcgi.c,v 1.98 2000/09/19 14:51:35 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 * The Apache Timeout directive allows per-server configuration of
59 * the timeout associated with a request. This is typically used to
60 * detect dead clients. The timer is reset for every successful
61 * read/write. The default value is 5min. Thats way too long to tie
62 * up a FastCGI server. For now this dropdead timer is used a little
63 * differently in FastCGI. All of the FastCGI server I/O AND the
64 * client I/O must complete within Timeout seconds. This isn't
65 * exactly what we want.. it should be revisited. See http_main.h.
67 * We need a way to configurably control the timeout associated with
68 * FastCGI server exchanges AND one for client exchanges. This could
69 * be done with the select() in doWork() (which should be rewritten
70 * anyway). This will allow us to free up the FastCGI as soon as
73 * Earlier versions of this module used ap_soft_timeout() rather than
74 * ap_hard_timeout() and ate FastCGI server output until it completed.
75 * This precluded the FastCGI server from having to implement a
76 * SIGPIPE handler, but meant hanging the application longer than
77 * necessary. SIGPIPE handler now must be installed in ALL FastCGI
78 * applications. The handler should abort further processing and go
79 * back into the accept() loop.
81 * Although using ap_soft_timeout() is better than ap_hard_timeout()
82 * we have to be more careful about SIGINT handling and subsequent
83 * processing, so, for now, make it hard.
90 #define timersub(a, b, result) \
92 (result)->tv_sec = (a)->tv_sec - (b)->tv_sec; \
93 (result)->tv_usec = (a)->tv_usec - (b)->tv_usec; \
94 if ((result)->tv_usec < 0) { \
96 (result)->tv_usec += 1000000; \
105 pool
*fcgi_config_pool
; /* the config pool */
106 server_rec
*fcgi_apache_main_server
;
108 const char *fcgi_suexec
= NULL
; /* suexec_bin path */
109 uid_t fcgi_user_id
; /* the run uid of Apache & PM */
110 gid_t fcgi_group_id
; /* the run gid of Apache & PM */
112 fcgi_server
*fcgi_servers
= NULL
; /* AppClasses */
114 char *fcgi_socket_dir
= DEFAULT_SOCK_DIR
; /* default FastCgiIpcDir */
117 pid_t fcgi_pm_pid
= -1;
119 char *fcgi_dynamic_dir
= NULL
; /* directory for the dynamic
120 * fastcgi apps' sockets */
123 fcgi_pm_job
*fcgi_dynamic_mbox
= NULL
;
124 HANDLE
*fcgi_dynamic_mbox_mutex
= NULL
;
125 HANDLE fcgi_pm_thread
= INVALID_HANDLE_VALUE
;
128 char *fcgi_empty_env
= NULL
;
130 u_int dynamicMaxProcs
= FCGI_DEFAULT_MAX_PROCS
;
131 u_int dynamicMinProcs
= FCGI_DEFAULT_MIN_PROCS
;
132 u_int dynamicMaxClassProcs
= FCGI_DEFAULT_MAX_CLASS_PROCS
;
133 u_int dynamicKillInterval
= FCGI_DEFAULT_KILL_INTERVAL
;
134 u_int dynamicUpdateInterval
= FCGI_DEFAULT_UPDATE_INTERVAL
;
135 float dynamicGain
= FCGI_DEFAULT_GAIN
;
136 u_int dynamicThreshhold1
= FCGI_DEFAULT_THRESHHOLD_1
;
137 u_int dynamicThreshholdN
= FCGI_DEFAULT_THRESHHOLD_N
;
138 u_int dynamicPleaseStartDelay
= FCGI_DEFAULT_START_PROCESS_DELAY
;
139 u_int dynamicAppConnectTimeout
= FCGI_DEFAULT_APP_CONN_TIMEOUT
;
140 char **dynamicEnvp
= &fcgi_empty_env
;
141 u_int dynamicProcessSlack
= FCGI_DEFAULT_PROCESS_SLACK
;
142 int dynamicAutoRestart
= FCGI_DEFAULT_RESTART_DYNAMIC
;
143 int dynamicAutoUpdate
= FCGI_DEFAULT_AUTOUPDATE
;
144 u_int dynamicListenQueueDepth
= FCGI_DEFAULT_LISTEN_Q
;
145 u_int dynamicInitStartDelay
= DEFAULT_INIT_START_DELAY
;
146 u_int dynamicRestartDelay
= FCGI_DEFAULT_RESTART_DELAY
;
147 array_header
*dynamic_pass_headers
= NULL
;
148 u_int dynamic_idle_timeout
= FCGI_DEFAULT_IDLE_TIMEOUT
;
150 /*******************************************************************************
151 * Construct a message and write it to the pm_pipe.
153 static void send_to_pm(pool
* const p
, const char id
, const char * const fs_path
,
154 const char *user
, const char * const group
, const unsigned long q_usec
,
155 const unsigned long req_usec
)
158 fcgi_pm_job
*job
= NULL
;
160 if (!(job
= (fcgi_pm_job
*) malloc(sizeof(fcgi_pm_job
))))
164 char buf
[FCGI_MAX_MSG_LEN
];
167 if (strlen(fs_path
) > FCGI_MAXPATH
) {
168 ap_log_error(FCGI_LOG_ERR_NOERRNO
, fcgi_apache_main_server
,
169 "FastCGI: the path \"%s\" is too long (>%d) for a dynamic server", fs_path
, FCGI_MAXPATH
);
178 job
->fs_path
= strdup(fs_path
);
179 job
->user
= strdup(user
);
180 job
->group
= strdup(group
);
182 job
->start_time
= 0L;
184 buflen
= sprintf(buf
, "%c %s %s %s*", id
, fs_path
, user
, group
);
191 job
->fs_path
= strdup(fs_path
);
192 job
->user
= strdup(user
);
193 job
->group
= strdup(group
);
195 job
->start_time
= 0L;
197 buflen
= sprintf(buf
, "%c %s %s %s*", id
, fs_path
, user
, group
);
204 job
->fs_path
= strdup(fs_path
);
206 job
->start_time
= req_usec
;
207 job
->user
= strdup(user
);
208 job
->group
= strdup(group
);
210 buflen
= sprintf(buf
, "%c %s %s %s %lu %lu*", id
, fs_path
, user
, group
, q_usec
, req_usec
);
216 if (fcgi_pm_add_job(job
) == 0)
219 SetEvent(fcgi_event_handles
[MBOX_EVENT
]);
221 ap_assert(buflen
<= FCGI_MAX_MSG_LEN
);
223 if (write(fcgi_pm_pipe
[1], (const void *)buf
, buflen
) != buflen
) {
224 ap_log_error(FCGI_LOG_WARN
, fcgi_apache_main_server
,
225 "FastCGI: write() to PM failed");
232 *----------------------------------------------------------------------
236 * An Apache module initializer, called by the Apache core
237 * after reading the server config.
239 * Start the process manager no matter what, since there may be a
240 * request for dynamic FastCGI applications without any being
241 * configured as static applications. Also, check for the existence
242 * and create if necessary a subdirectory into which all dynamic
245 *----------------------------------------------------------------------
247 static void init_module(server_rec
*s
, pool
*p
)
251 /* Register to reset to default values when the config pool is cleaned */
253 ap_register_cleanup(p
, NULL
, fcgi_config_reset_globals
, ap_null_cleanup
);
256 ap_add_version_component("mod_fastcgi/" MOD_FASTCGI_VERSION
);
258 fcgi_config_set_fcgi_uid_n_gid(1);
260 /* keep these handy */
261 fcgi_config_pool
= p
;
262 fcgi_apache_main_server
= s
;
265 /* Create Unix/Domain socket directory */
266 if ((err
= fcgi_config_make_dir(p
, fcgi_socket_dir
)))
267 ap_log_error(FCGI_LOG_ERR
, s
, "FastCGI: %s", err
);
270 /* Create Dynamic directory */
271 if ((err
= fcgi_config_make_dynamic_dir(p
, 1)))
272 ap_log_error(FCGI_LOG_ERR
, s
, "FastCGI: %s", err
);
275 /* Create the pipe for comm with the PM */
276 if (pipe(fcgi_pm_pipe
) < 0) {
277 ap_log_error(FCGI_LOG_ERR
, s
, "FastCGI: pipe() failed");
280 /* Spawn the PM only once. Under Unix, Apache calls init() routines
281 * twice, once before detach() and once after. Win32 doesn't detach.
282 * Under DSO, DSO modules are unloaded between the two init() calls.
283 * Under Unix, the -X switch causes two calls to init() but no detach
284 * (but all subprocesses are wacked so the PM is toasted anyway)! */
286 if (ap_standalone
&& getppid() != 1)
289 /* Start the Process Manager */
290 fcgi_pm_pid
= ap_spawn_child(p
, fcgi_pm_main
, NULL
, kill_only_once
, NULL
, NULL
, NULL
);
291 if (fcgi_pm_pid
<= 0) {
292 ap_log_error(FCGI_LOG_ALERT
, s
,
293 "FastCGI: can't start the process manager, spawn_child() failed");
296 close(fcgi_pm_pipe
[0]);
300 static void fcgi_child_init(server_rec
*server_conf
, pool
*p
)
303 /* Create the Event Handlers */
304 fcgi_event_handles
[0] = CreateEvent(NULL
, FALSE
, FALSE
, NULL
);
305 fcgi_event_handles
[1] = CreateEvent(NULL
, FALSE
, FALSE
, NULL
);
306 fcgi_event_handles
[2] = CreateEvent(NULL
, FALSE
, FALSE
, NULL
);
307 fcgi_dynamic_mbox_mutex
= ap_create_mutex("fcgi_dynamic_mbox_mutex");
309 /* Spawn of the process manager thread */
310 fcgi_pm_thread
= CreateThread(NULL
, 0, (LPTHREAD_START_ROUTINE
)fcgi_pm_main
, NULL
, 0, NULL
);
315 static void fcgi_child_exit(server_rec
*server_conf
, pool
*p
) {
318 /* Signaling the PM thread tp exit*/
319 SetEvent(fcgi_event_handles
[TERM_EVENT
]);
321 /* Waiting on pm thread to exit */
322 WaitForSingleObject(fcgi_pm_thread
, INFINITE
);
329 *----------------------------------------------------------------------
333 * Terminate a line: scan to the next newline, scan back to the
334 * first non-space character and store a terminating zero. Return
335 * the next character past the end of the newline.
337 * If the end of the string is reached, ASSERT!
339 * If the FIRST character(s) in the line are '\n' or "\r\n", the
340 * first character is replaced with a NULL and next character
341 * past the newline is returned. NOTE: this condition supercedes
342 * the processing of RFC-822 continuation lines.
344 * If continuation is set to 'TRUE', then it parses a (possible)
345 * sequence of RFC-822 continuation lines.
351 * Termination byte stored in string.
353 *----------------------------------------------------------------------
355 static char *get_header_line(char *start
, int continuation
)
360 if(p
[0] == '\r' && p
[1] == '\n') { /* If EOL in 1st 2 chars */
361 p
++; /* point to \n and stop */
362 } else if(*p
!= '\n') {
365 if(*p
== '\n' && p
[1] != ' ' && p
[1] != '\t')
370 while(*p
!= '\0' && *p
!= '\n') {
376 ap_assert(*p
!= '\0');
381 * Trim any trailing whitespace.
383 while(isspace((unsigned char)p
[-1]) && p
> start
) {
392 *----------------------------------------------------------------------
396 * Call with r->parseHeader == SCAN_CGI_READING_HEADERS
397 * and initial script output in fr->header.
399 * If the initial script output does not include the header
400 * terminator ("\r\n\r\n") process_headers returns with no side
401 * effects, to be called again when more script output
402 * has been appended to fr->header.
404 * If the initial script output includes the header terminator,
405 * process_headers parses the headers and determines whether or
406 * not the remaining script output will be sent to the client.
407 * If so, process_headers sends the HTTP response headers to the
408 * client and copies any non-header script output to the output
415 * May set r->parseHeader to:
416 * SCAN_CGI_FINISHED -- headers parsed, returning script response
417 * SCAN_CGI_BAD_HEADER -- malformed header from script
418 * SCAN_CGI_INT_REDIRECT -- handler should perform internal redirect
419 * SCAN_CGI_SRV_REDIRECT -- handler should return REDIRECT
421 *----------------------------------------------------------------------
424 static const char *process_headers(request_rec
*r
, fcgi_request
*fr
)
426 char *p
, *next
, *name
, *value
;
428 int hasContentType
, hasStatus
, hasLocation
;
430 ap_assert(fr
->parseHeader
== SCAN_CGI_READING_HEADERS
);
432 if (fr
->header
== NULL
)
436 * Do we have the entire header? Scan for the blank line that
437 * terminates the header.
439 p
= (char *)fr
->header
->elts
;
440 len
= fr
->header
->nelts
;
442 while(len
-- && flag
< 2) {
452 name
= "Invalid Character";
462 /* Return (to be called later when we have more data)
463 * if we don't have an entire header. */
468 * Parse all the headers.
470 fr
->parseHeader
= SCAN_CGI_FINISHED
;
471 hasContentType
= hasStatus
= hasLocation
= FALSE
;
472 next
= (char *)fr
->header
->elts
;
474 next
= get_header_line(name
= next
, TRUE
);
478 if ((p
= strchr(name
, ':')) == NULL
) {
482 while (p
!= name
&& isspace((unsigned char)*(p
- 1))) {
489 if (strpbrk(name
, " \t") != NULL
) {
493 while (isspace((unsigned char)*value
)) {
497 if (strcasecmp(name
, "Status") == 0) {
498 int statusValue
= strtol(value
, NULL
, 10);
501 goto DuplicateNotAllowed
;
503 if (statusValue
< 0) {
504 fr
->parseHeader
= SCAN_CGI_BAD_HEADER
;
505 return ap_psprintf(r
->pool
, "invalid Status '%s'", value
);
508 r
->status
= statusValue
;
509 r
->status_line
= ap_pstrdup(r
->pool
, value
);
513 if (fr
->role
== FCGI_RESPONDER
) {
514 if (strcasecmp(name
, "Content-type") == 0) {
515 if (hasContentType
) {
516 goto DuplicateNotAllowed
;
518 hasContentType
= TRUE
;
519 r
->content_type
= ap_pstrdup(r
->pool
, value
);
523 if (strcasecmp(name
, "Location") == 0) {
525 goto DuplicateNotAllowed
;
528 ap_table_set(r
->headers_out
, "Location", value
);
532 /* If the script wants them merged, it can do it */
533 ap_table_add(r
->err_headers_out
, name
, value
);
537 ap_table_add(fr
->authHeaders
, name
, value
);
541 if (fr
->role
!= FCGI_RESPONDER
)
545 * Who responds, this handler or Apache?
548 const char *location
= ap_table_get(r
->headers_out
, "Location");
550 * Based on internal redirect handling in mod_cgi.c...
552 * If a script wants to produce its own Redirect
553 * body, it now has to explicitly *say* "Status: 302"
555 if (r
->status
== 200) {
556 if(location
[0] == '/') {
558 * Location is an relative path. This handler will
559 * consume all script output, then have Apache perform an
562 fr
->parseHeader
= SCAN_CGI_INT_REDIRECT
;
566 * Location is an absolute URL. If the script didn't
567 * produce a Content-type header, this handler will
568 * consume all script output and then have Apache generate
569 * its standard redirect response. Otherwise this handler
570 * will transmit the script's response.
572 fr
->parseHeader
= SCAN_CGI_SRV_REDIRECT
;
578 * We're responding. Send headers, buffer excess script output.
580 ap_send_http_header(r
);
582 /* We need to reinstate our timeout, send_http_header() kill()s it */
583 ap_hard_timeout("FastCGI request processing", r
);
588 len
= fr
->header
->nelts
- (next
- fr
->header
->elts
);
590 ap_assert(BufferLength(fr
->clientOutputBuffer
) == 0);
591 if (BufferFree(fr
->clientOutputBuffer
) < len
) {
592 fr
->clientOutputBuffer
= fcgi_buf_new(r
->pool
, len
);
594 ap_assert(BufferFree(fr
->clientOutputBuffer
) >= len
);
596 int sent
= fcgi_buf_add_block(fr
->clientOutputBuffer
, next
, len
);
597 ap_assert(sent
== len
);
602 /* Log first line of a multi-line header */
603 if ((p
= strpbrk(name
, "\r\n")) != NULL
)
605 fr
->parseHeader
= SCAN_CGI_BAD_HEADER
;
606 return ap_psprintf(r
->pool
, "malformed header '%s'", name
);
609 fr
->parseHeader
= SCAN_CGI_BAD_HEADER
;
610 return ap_psprintf(r
->pool
, "duplicate header '%s'", name
);
614 * Read from the client filling both the FastCGI server buffer and the
615 * client buffer with the hopes of buffering the client data before
616 * making the connect() to the FastCGI server. This prevents slow
617 * clients from keeping the FastCGI server in processing longer than is
620 static int read_from_client_n_queue(fcgi_request
*fr
)
626 while (BufferFree(fr
->clientInputBuffer
) > 0 || BufferFree(fr
->serverOutputBuffer
) > 0) {
627 fcgi_protocol_queue_client_buffer(fr
);
629 if (fr
->expectingClientContent
<= 0)
632 fcgi_buf_get_free_block_info(fr
->clientInputBuffer
, &end
, &count
);
636 if ((countRead
= ap_get_client_block(fr
->r
, end
, count
)) < 0)
640 fr
->expectingClientContent
= 0;
642 fcgi_buf_add_update(fr
->clientInputBuffer
, countRead
);
648 static int write_to_client(fcgi_request
*fr
)
653 fcgi_buf_get_block_info(fr
->clientOutputBuffer
, &begin
, &count
);
657 /* If fewer than count bytes are written, an error occured.
658 * ap_bwrite() typically forces a flushed write to the client, this
659 * effectively results in a block (and short packets) - it should
660 * be fixed, but I didn't win much support for the idea on new-httpd.
661 * So, without patching Apache, the best way to deal with this is
662 * to size the fcgi_bufs to hold all of the script output (within
663 * reason) so the script can be released from having to wait around
664 * for the transmission to the client to complete. */
665 #ifdef RUSSIAN_APACHE
666 if (ap_rwrite(begin
, count
, fr
->r
) != count
) {
667 ap_log_rerror(FCGI_LOG_INFO
, fr
->r
,
668 "FastCGI: client stopped connection before send body completed");
672 if (ap_bwrite(fr
->r
->connection
->client
, begin
, count
) != (int) count
) {
673 ap_log_rerror(FCGI_LOG_INFO
, fr
->r
,
674 "FastCGI: client stopped connection before send body completed");
680 /* Don't bother with a wrapped buffer, limiting exposure to slow
681 * clients. The BUFF routines don't allow a writev from above,
682 * and don't always memcpy to minimize small write()s, this should
683 * be fixed, but I didn't win much support for the idea on
684 * new-httpd - I'll have to _prove_ its a problem first.. */
686 /* The default behaviour used to be to flush with every write, but this
687 * can tie up the FastCGI server longer than is necessary so its an option now */
688 if (fr
->fs
&& fr
->fs
->flush
) {
689 #ifdef RUSSIAN_APACHE
690 if (ap_rflush(fr
->r
)) {
691 ap_log_rerror(FCGI_LOG_INFO
, fr
->r
,
692 "FastCGI: client stopped connection before send body completed");
696 if (ap_bflush(fr
->r
->connection
->client
)) {
697 ap_log_rerror(FCGI_LOG_INFO
, fr
->r
,
698 "FastCGI: client stopped connection before send body completed");
704 fcgi_buf_toss(fr
->clientOutputBuffer
, count
);
708 /*******************************************************************************
709 * Determine the user and group suexec should be called with.
710 * Based on code in Apache's create_argv_cmd() (util_script.c).
712 static void set_uid_n_gid(request_rec
*r
, const char **user
, const char **group
)
714 if (fcgi_suexec
== NULL
) {
720 if (strncmp("/~", r
->uri
, 2) == 0) {
721 /* its a user dir uri, just send the ~user, and leave it to the PM */
722 char *end
= strchr(r
->uri
+ 2, '/');
725 *user
= memcpy(ap_pcalloc(r
->pool
, end
- r
->uri
), r
->uri
+ 1, end
- r
->uri
- 1);
727 *user
= ap_pstrdup(r
->pool
, r
->uri
+ 1);
731 *user
= ap_psprintf(r
->pool
, "%ld", (long)r
->server
->server_uid
);
732 *group
= ap_psprintf(r
->pool
, "%ld", (long)r
->server
->server_gid
);
736 /*******************************************************************************
737 * Close the connection to the FastCGI server. This is normally called by
738 * do_work(), but may also be called as in request pool cleanup.
740 static void close_connection_to_fs(fcgi_request
*fr
)
742 pool
*rp
= fr
->r
->pool
;
745 ap_pclosesocket(rp
, fr
->fd
);
750 if (fr
->lockFd
!= NULL
) {
751 fcgi_rdwr_unlock(fr
->lockFd
, READER
);
754 if (fr
->lockFd
>= 0) {
755 ap_pclosef(rp
, fr
->lockFd
);
759 if (fr
->keepReadingFromFcgiApp
== FALSE
) {
760 /* XXX REQ_COMPLETE is only sent for requests which complete
761 * normally WRT the fcgi app. There is no data sent for
762 * connect() timeouts or requests which complete abnormally.
763 * KillDynamicProcs() and RemoveRecords() need to be looked at
764 * to be sure they can reasonably handle these cases before
765 * sending these sort of stats - theres some funk in there.
766 * XXX We should do something special when this a pool cleanup.
768 if (fcgi_util_gettimeofday(&fr
->completeTime
) < 0) {
769 /* there's no point to aborting the request, just log it */
770 ap_log_error(FCGI_LOG_ERR
, fr
->r
->server
, "FastCGI: gettimeofday() failed");
772 struct timeval qtime
, rtime
;
774 timersub(&fr
->queueTime
, &fr
->startTime
, &qtime
);
775 timersub(&fr
->completeTime
, &fr
->queueTime
, &rtime
);
777 send_to_pm(rp
, REQ_COMPLETE
, fr
->fs_path
,
779 qtime
.tv_sec
* 1000000 + qtime
.tv_usec
,
780 rtime
.tv_sec
* 1000000 + rtime
.tv_usec
);
787 static void lock_cleanup(void * data
)
789 fcgi_rdwr_unlock((FcgiRWLock
*) data
, READER
);
793 /*******************************************************************************
794 * Connect to the FastCGI server.
796 static const char *open_connection_to_fs(fcgi_request
*fr
)
799 fd_set write_fds
, read_fds
;
801 request_rec
* const r
= fr
->r
;
802 pool
* const rp
= r
->pool
;
803 const char *socket_path
= NULL
;
804 struct sockaddr
*socket_addr
= NULL
;
805 int socket_addr_len
= 0;
807 unsigned long ioctl_arg
;
811 const char *err
= NULL
;
814 /* Create the connection point */
816 socket_path
= fcgi_util_socket_hash_filename(rp
, fr
->fs_path
, fr
->user
, fr
->group
);
817 socket_path
= fcgi_util_socket_make_path_absolute(rp
, socket_path
, 1);
820 err
= fcgi_util_socket_make_domain_addr(rp
, (struct sockaddr_un
**)&socket_addr
,
821 &socket_addr_len
, socket_path
);
827 if (fr
->fs
->dest_addr
!= NULL
) {
828 socket_addr
= fr
->fs
->dest_addr
;
830 else if (fr
->fs
->socket_addr
) {
831 socket_addr
= fr
->fs
->socket_addr
;
834 socket_path
= fr
->fs
->socket_path
;
837 socket_addr
= fr
->fs
->socket_addr
;
839 socket_addr_len
= fr
->fs
->socket_addr_len
;
842 /* Dynamic app's lockfile handling */
845 const char *lockFileName
= fcgi_util_socket_get_lock_filename(rp
, socket_path
);
855 if (stat(lockFileName
, &lstbuf
) == 0 && S_ISREG(lstbuf
.st_mode
))
858 if (dynamicAutoUpdate
&& (stat(fr
->fs_path
, &bstbuf
) == 0)
860 && ((fr
->fs
->restartTime
> 0) && (fr
->fs
->restartTime
< bstbuf
.st_mtime
)))
862 && (lstbuf
.st_mtime
< bstbuf
.st_mtime
))
865 struct timeval tv
= {1, 0};
867 /* Its already running, but there's a newer one,
868 * ask the process manager to start it.
869 * it will notice that the binary is newer,
870 * and do a restart instead.
872 send_to_pm(rp
, PLEASE_START
, fr
->fs_path
, fr
->user
, fr
->group
, 0, 0);
874 /* Avoid sleep/alarm interactions */
875 ap_select(0, NULL
, NULL
, NULL
, &tv
);
878 fr
->lockFd
= fr
->fs
->dynamic_lock
;
881 fr
->lockFd
= ap_popenf(rp
, lockFileName
, O_APPEND
, 0);
882 result
= (fr
->lockFd
< 0) ? (0) : (1);
885 struct timeval tv
= {1, 0};
887 send_to_pm(rp
, PLEASE_START
, fr
->fs_path
, fr
->user
, fr
->group
, 0, 0);
892 /* Avoid sleep/alarm interactions */
893 ap_select(0, NULL
, NULL
, NULL
, &tv
);
897 fr
->fs
= fcgi_util_fs_get_by_id(fr
->fs_path
, 0, 0);
899 } while (result
!= 1);
901 /* Block until we get a shared (non-exclusive) read Lock */
902 if (fcgi_wait_for_shared_read_lock(fr
->lockFd
) < 0)
903 return "failed to obtain a shared read lock";
907 ap_register_cleanup(rp
, (void *) fr
->lockFd
, lock_cleanup
, ap_null_cleanup
);
911 FCGIDBG2("got_dynamic_shared_read_lock: %s", fr
->fs_path
);
921 int max_connect_time
= FCGI_NAMED_PIPE_CONNECT_TIMEOUT
;
923 fr
->using_npipe_io
= TRUE
;
927 interval
= dynamicPleaseStartDelay
* 1000;
929 if (dynamicAppConnectTimeout
) {
930 max_connect_time
= dynamicAppConnectTimeout
;
935 interval
= FCGI_NAMED_PIPE_CONNECT_TIMEOUT
* 1000;
937 if (fr
->fs
->appConnectTimeout
) {
938 max_connect_time
= fr
->fs
->appConnectTimeout
;
942 if (fcgi_util_gettimeofday(&fr
->startTime
) < 0) {
943 return "gettimeofday() failed";
948 fr
->fd
= (SOCKET
) CreateFile(socket_path
,
949 GENERIC_READ
| GENERIC_WRITE
,
950 FILE_SHARE_READ
| FILE_SHARE_WRITE
,
951 NULL
, // no security attributes
952 OPEN_EXISTING
, // opens existing pipe
953 FILE_ATTRIBUTE_NORMAL
, // default attributes
954 NULL
); // no template file
956 if (fr
->fd
!= (SOCKET
) INVALID_HANDLE_VALUE
) {
960 if (GetLastError() != ERROR_PIPE_BUSY
) {
961 return("CreateFile() failed ()");
964 // All pipe instances are busy, so wait
965 ready
= WaitNamedPipe(socket_path
, interval
);
967 if (fr
->dynamic
&& !ready
) {
968 send_to_pm(rp
, CONN_TIMEOUT
, fr
->fs_path
, fr
->user
, fr
->group
, 0, 0);
971 if (fcgi_util_gettimeofday(&fr
->queueTime
) < 0) {
972 return "gettimeofday() failed";
975 connect_time
= fr
->queueTime
.tv_sec
- fr
->startTime
.tv_sec
;
977 FCGIDBG5("interval=%d, max_connect_time=%d, connect_time=%d, ready=%d", interval
, max_connect_time
, connect_time
, ready
);
979 } while (connect_time
< max_connect_time
);
981 if (fr
->fd
== (SOCKET
) INVALID_HANDLE_VALUE
) {
982 return "CreateFile()/WaitNamedPipe() timed out";
985 FCGIDBG2("got_named_pipe_connect: %s", fr
->fs_path
);
988 ap_note_cleanups_for_h(rp
, (HANDLE
) fr
->fd
);
995 /* Create the socket */
996 fr
->fd
= ap_psocket(rp
, socket_addr
->sa_family
, SOCK_STREAM
, 0);
999 return "ap_psocket() failed";
1002 if (fr
->fd
>= FD_SETSIZE
) {
1003 return ap_psprintf(rp
, "socket file descriptor (%u) is larger than "
1004 "FD_SETSIZE (%u), you probably need to rebuild Apache with a "
1005 "larger FD_SETSIZE", fr
->fd
, FD_SETSIZE
);
1009 /* If appConnectTimeout is non-zero, setup do a non-blocking connect */
1010 if ((fr
->dynamic
&& dynamicAppConnectTimeout
) || (!fr
->dynamic
&& fr
->fs
->appConnectTimeout
)) {
1012 if ((fd_flags
= fcntl(fr
->fd
, F_GETFL
, 0)) < 0)
1013 return "fcntl(F_GETFL) failed";
1014 if (fcntl(fr
->fd
, F_SETFL
, fd_flags
| O_NONBLOCK
) < 0)
1015 return "fcntl(F_SETFL) failed";
1018 if (ioctlsocket(fr
->fd
, FIONBIO
, &ioctl_arg
) != 0)
1019 return "ioctlsocket(FIONBIO) failed";
1023 if (fr
->dynamic
&& fcgi_util_gettimeofday(&fr
->startTime
) < 0)
1024 return "gettimeofday() failed";
1027 if (connect(fr
->fd
, (struct sockaddr
*)socket_addr
, socket_addr_len
) == 0)
1028 goto ConnectionComplete
;
1031 errcode
= GetLastError();
1032 if (errcode
!= WSAEWOULDBLOCK
)
1033 return "connect() failed";
1035 /* ECONNREFUSED means the listen queue is full (or there isn't one).
1036 * With dynamic I can at least make sure the PM knows this is occuring */
1037 if (fr
->dynamic
&& errno
== ECONNREFUSED
) {
1038 /* @@@ This might be better as some other "kind" of message */
1039 send_to_pm(rp
, CONN_TIMEOUT
, fr
->fs_path
, fr
->user
, fr
->group
, 0, 0);
1041 errno
= ECONNREFUSED
;
1044 if (errno
!= EINPROGRESS
)
1045 return "connect() failed";
1048 /* The connect() is non-blocking */
1054 FD_ZERO(&write_fds
);
1055 FD_SET(fr
->fd
, &write_fds
);
1056 read_fds
= write_fds
;
1057 tval
.tv_sec
= dynamicPleaseStartDelay
;
1060 status
= ap_select((fr
->fd
+1), &read_fds
, &write_fds
, NULL
, &tval
);
1064 if (fcgi_util_gettimeofday(&fr
->queueTime
) < 0)
1065 return "gettimeofday() failed";
1069 /* select() timed out */
1070 send_to_pm(rp
, CONN_TIMEOUT
, fr
->fs_path
, fr
->user
, fr
->group
, 0, 0);
1071 } while ((fr
->queueTime
.tv_sec
- fr
->startTime
.tv_sec
) < (int)dynamicAppConnectTimeout
);
1073 /* XXX These can be moved down when dynamic vars live is a struct */
1075 return ap_psprintf(rp
, "connect() timed out (appConnTimeout=%dsec)",
1076 dynamicAppConnectTimeout
);
1080 tval
.tv_sec
= fr
->fs
->appConnectTimeout
;
1082 FD_ZERO(&write_fds
);
1083 FD_SET(fr
->fd
, &write_fds
);
1084 read_fds
= write_fds
;
1086 status
= ap_select((fr
->fd
+1), &read_fds
, &write_fds
, NULL
, &tval
);
1088 return ap_psprintf(rp
, "connect() timed out (appConnTimeout=%dsec)",
1089 fr
->fs
->appConnectTimeout
);
1094 return "select() failed";
1096 if (FD_ISSET(fr
->fd
, &write_fds
) || FD_ISSET(fr
->fd
, &read_fds
)) {
1098 NET_SIZE_T len
= sizeof(error
);
1100 if (getsockopt(fr
->fd
, SOL_SOCKET
, SO_ERROR
, (char *)&error
, &len
) < 0)
1101 /* Solaris pending error */
1102 return "select() failed (Solaris pending error)";
1105 /* Berkeley-derived pending error */
1107 return "select() failed (pending error)";
1110 return "select() error - THIS CAN'T HAPPEN!";
1113 /* Return to blocking mode if it was set up */
1114 if ((fr
->dynamic
&& dynamicAppConnectTimeout
) || (!fr
->dynamic
&& fr
->fs
->appConnectTimeout
)) {
1117 if (ioctlsocket(fr
->fd
, FIONBIO
, &ioctl_arg
) != 0)
1118 return "ioctlsocket(FIONBIO) failed";
1120 if ((fcntl(fr
->fd
, F_SETFL
, fd_flags
)) < 0)
1121 return "fcntl(F_SETFL) failed";
1126 if (socket_addr
->sa_family
== AF_INET
) {
1127 /* We shouldn't be sending small packets and there's no application
1128 * level ack of the data we send, so disable Nagle */
1130 setsockopt(fr
->fd
, IPPROTO_TCP
, TCP_NODELAY
, (char *)&set
, sizeof(set
));
1137 static int server_error(fcgi_request
*fr
)
1139 #if defined(SIGPIPE) && MODULE_MAGIC_NUMBER < 19990320
1140 /* Make sure we leave with Apache's sigpipe_handler in place */
1141 if (fr
->apache_sigpipe_handler
!= NULL
)
1142 signal(SIGPIPE
, fr
->apache_sigpipe_handler
);
1144 close_connection_to_fs(fr
);
1145 ap_kill_timeout(fr
->r
);
1146 return SERVER_ERROR
;
1149 static void log_fcgi_server_stderr(void *data
)
1151 const fcgi_request
* const fr
= (fcgi_request
*)data
;
1156 if (fr
->fs_stderr_len
) {
1157 ap_log_rerror(FCGI_LOG_ERR_NOERRNO
, fr
->r
,
1158 "FastCGI: server \"%s\" stderr: %s", fr
->fs_path
, fr
->fs_stderr
);
1162 /*----------------------------------------------------------------------
1163 * This is the core routine for moving data between the FastCGI
1164 * application and the Web server's client.
1166 static int do_work(request_rec
*r
, fcgi_request
*fr
)
1168 struct timeval timeOut
, dynamic_last_activity_time
= {0, 0};
1169 fd_set read_set
, write_set
;
1170 int status
= 0, idle_timeout
;
1171 int numFDs
, dynamic_first_read
= fr
->dynamic
? 1 : 0;
1173 int envSent
= FALSE
; /* has the complete ENV been buffered? */
1176 const char *err
= NULL
;
1179 FD_ZERO(&write_set
);
1181 fcgi_protocol_queue_begin_request(fr
);
1183 /* Buffer as much of the environment as we can fit */
1185 envSent
= fcgi_protocol_queue_env(r
, fr
, &env
);
1187 /* Start the Apache dropdead timer. See comments at top of file. */
1188 ap_hard_timeout("buffering of FastCGI client data", r
);
1190 /* Read as much as possible from the client. */
1191 if (fr
->role
== FCGI_RESPONDER
) {
1192 status
= ap_setup_client_block(r
, REQUEST_CHUNKED_ERROR
);
1197 fr
->expectingClientContent
= (ap_should_client_block(r
) != 0);
1199 if (read_from_client_n_queue(fr
) != OK
)
1200 return server_error(fr
);
1203 /* Connect to the FastCGI Application */
1204 ap_hard_timeout("connect() to FastCGI server", r
);
1205 if ((err
= open_connection_to_fs(fr
))) {
1206 ap_log_rerror(FCGI_LOG_ERR
, r
,
1207 "FastCGI: failed to connect to server \"%s\": %s", fr
->fs_path
, err
);
1208 return server_error(fr
);
1211 numFDs
= fr
->fd
+ 1;
1212 idle_timeout
= fr
->dynamic
? dynamic_idle_timeout
: fr
->fs
->idle_timeout
;
1214 if (dynamic_first_read
) {
1215 dynamic_last_activity_time
= fr
->startTime
;
1217 if (dynamicAppConnectTimeout
) {
1218 struct timeval qwait
;
1219 timersub(&fr
->queueTime
, &fr
->startTime
, &qwait
);
1220 dynamic_first_read
= qwait
.tv_sec
/ dynamicPleaseStartDelay
+ 1;
1224 /* @@@ We never reset the timer in this loop, most folks don't mess w/
1225 * Timeout directive which means we've got the 5 min default which is way
1226 * to long to tie up a fs. We need a better/configurable solution that
1227 * uses the select */
1228 ap_hard_timeout("FastCGI request processing", r
);
1230 /* Register to get the script's stderr logged at the end of the request */
1232 ap_register_cleanup(rp
, (void *)fr
, log_fcgi_server_stderr
, ap_null_cleanup
);
1233 ap_unblock_alarms();
1235 /* The socket is writeable, so get the first write out of the way */
1236 if (fcgi_buf_get_to_fd(fr
->serverOutputBuffer
, fr
->fd
) < 0) {
1237 ap_log_rerror(FCGI_LOG_ERR
, r
,
1238 "FastCGI: comm with server \"%s\" aborted: write failed", fr
->fs_path
);
1239 return server_error(fr
);
1242 while (fr
->keepReadingFromFcgiApp
1243 || BufferLength(fr
->serverInputBuffer
) > 0
1244 || BufferLength(fr
->clientOutputBuffer
) > 0) {
1246 /* If we didn't buffer all of the environment yet, buffer some more */
1248 envSent
= fcgi_protocol_queue_env(r
, fr
, &env
);
1250 /* Read as much as possible from the client. */
1251 if (fr
->role
== FCGI_RESPONDER
&& !fr
->eofSent
&& envSent
) {
1252 if (read_from_client_n_queue(fr
) != OK
)
1253 return server_error(fr
);
1256 /* To avoid deadlock, don't do a blocking select to write to
1257 * the FastCGI application without selecting to read from the
1258 * FastCGI application.
1260 doClientWrite
= FALSE
;
1261 if (fr
->keepReadingFromFcgiApp
&& BufferFree(fr
->serverInputBuffer
) > 0) {
1264 if (!fr
->using_npipe_io
) {
1266 FD_SET(fr
->fd
, &read_set
);
1268 /* Is data buffered for output to the FastCGI server? */
1269 if (BufferLength(fr
->serverOutputBuffer
) > 0) {
1270 FD_SET(fr
->fd
, &write_set
);
1272 FD_CLR(fr
->fd
, &write_set
);
1278 * If there's data buffered to send to the client, don't
1279 * wait indefinitely for the FastCGI app; the app might
1280 * be doing server push.
1282 if (BufferLength(fr
->clientOutputBuffer
) > 0) {
1284 timeOut
.tv_usec
= 100000; /* 0.1 sec */
1286 else if (dynamic_first_read
) {
1288 struct timeval qwait
;
1290 if (fcgi_util_gettimeofday(&fr
->queueTime
) < 0) {
1291 ap_log_rerror(FCGI_LOG_ERR
, r
, "FastCGI: gettimeofday() failed");
1292 return server_error(fr
);
1295 /* Check for idle_timeout */
1297 dynamic_last_activity_time
= fr
->queueTime
;
1300 struct timeval idle_time
;
1301 timersub(&fr
->queueTime
, &dynamic_last_activity_time
, &idle_time
);
1302 if (idle_time
.tv_sec
> idle_timeout
) {
1303 send_to_pm(rp
, CONN_TIMEOUT
, fr
->fs_path
, fr
->user
, fr
->group
, 0, 0);
1304 ap_log_rerror(FCGI_LOG_ERR_NOERRNO
, r
,
1305 "FastCGI: comm with (dynamic) server \"%s\" aborted: (first read) idle timeout (%d sec)",
1306 fr
->fs_path
, idle_timeout
);
1307 return server_error(fr
);
1311 timersub(&fr
->queueTime
, &fr
->startTime
, &qwait
);
1313 delay
= dynamic_first_read
* dynamicPleaseStartDelay
;
1314 if (qwait
.tv_sec
< delay
) {
1315 timeOut
.tv_sec
= delay
;
1316 timeOut
.tv_usec
= 100000; /* fudge for select() slop */
1317 timersub(&timeOut
, &qwait
, &timeOut
);
1320 /* Killed time somewhere.. client read? */
1321 send_to_pm(rp
, CONN_TIMEOUT
, fr
->fs_path
, fr
->user
, fr
->group
, 0, 0);
1322 dynamic_first_read
= qwait
.tv_sec
/ dynamicPleaseStartDelay
+ 1;
1323 timeOut
.tv_sec
= dynamic_first_read
* dynamicPleaseStartDelay
;
1324 timeOut
.tv_usec
= 100000; /* fudge for select() slop */
1325 timersub(&timeOut
, &qwait
, &timeOut
);
1329 timeOut
.tv_sec
= idle_timeout
;
1330 timeOut
.tv_usec
= 0;
1334 if (!fr
->using_npipe_io
) {
1336 if ((status
= ap_select(numFDs
, &read_set
, &write_set
, NULL
, &timeOut
)) < 0) {
1337 ap_log_rerror(FCGI_LOG_ERR
, r
,
1338 "FastCGI: comm with server \"%s\" aborted: select() failed", fr
->fs_path
);
1339 return server_error(fr
);
1344 int stopTime
= time(NULL
) + timeOut
.tv_sec
;
1347 if (!(BufferLength(fr
->serverOutputBuffer
) > 0)) {
1350 while ((timeOut
.tv_sec
!= 0) && (time(NULL
) <= stopTime
)) {
1351 if (PeekNamedPipe((HANDLE
) fr
->fd
,NULL
, 0, NULL
, &bytesavail
, NULL
) &&
1367 if (BufferLength(fr
->clientOutputBuffer
) > 0) {
1368 doClientWrite
= TRUE
;
1370 else if (dynamic_first_read
) {
1371 struct timeval qwait
;
1373 if (fcgi_util_gettimeofday(&fr
->queueTime
) < 0) {
1374 ap_log_rerror(FCGI_LOG_ERR
, r
, "FastCGI: gettimeofday() failed");
1375 return server_error(fr
);
1378 timersub(&fr
->queueTime
, &fr
->startTime
, &qwait
);
1380 send_to_pm(rp
, CONN_TIMEOUT
, fr
->fs_path
, fr
->user
, fr
->group
, 0, 0);
1382 dynamic_first_read
= qwait
.tv_sec
/ dynamicPleaseStartDelay
+ 1;
1385 ap_log_rerror(FCGI_LOG_ERR_NOERRNO
, r
,
1386 "FastCGI: comm with server \"%s\" aborted: idle timeout (%d sec)",
1387 fr
->fs_path
, idle_timeout
);
1388 return server_error(fr
);
1392 #if defined(SIGPIPE) && MODULE_MAGIC_NUMBER < 19990320
1393 /* Disable Apache's SIGPIPE handler */
1394 fr
->apache_sigpipe_handler
= signal(SIGPIPE
, SIG_IGN
);
1397 /* Read from the FastCGI server */
1399 if (((fr
->using_npipe_io
) &&
1400 (BufferFree(fr
->serverInputBuffer
) > 0)) || FD_ISSET(fr
->fd
, &read_set
)) {
1402 if (FD_ISSET(fr
->fd
, &read_set
)) {
1404 if (dynamic_first_read
) {
1405 dynamic_first_read
= 0;
1406 if (fcgi_util_gettimeofday(&fr
->queueTime
) < 0) {
1407 ap_log_rerror(FCGI_LOG_ERR
, r
, "FastCGI: gettimeofday() failed");
1408 return server_error(fr
);
1412 if ((status
= fcgi_buf_add_fd(fr
->serverInputBuffer
, fr
->fd
)) < 0) {
1413 ap_log_rerror(FCGI_LOG_ERR
, r
,
1414 "FastCGI: comm with server \"%s\" aborted: read failed", fr
->fs_path
);
1415 return server_error(fr
);
1419 fr
->keepReadingFromFcgiApp
= FALSE
;
1420 close_connection_to_fs(fr
);
1424 /* Write to the FastCGI server */
1426 if (((fr
->using_npipe_io
) &&
1427 (BufferLength(fr
->serverOutputBuffer
) > 0)) || FD_ISSET(fr
->fd
, &write_set
)) {
1429 if (FD_ISSET(fr
->fd
, &write_set
)) {
1432 if (fcgi_buf_get_to_fd(fr
->serverOutputBuffer
, fr
->fd
) < 0) {
1433 ap_log_rerror(FCGI_LOG_ERR
, r
,
1434 "FastCGI: comm with server \"%s\" aborted: write failed", fr
->fs_path
);
1435 return server_error(fr
);
1439 #if defined(SIGPIPE) && MODULE_MAGIC_NUMBER < 19990320
1440 /* Reinstall Apache's SIGPIPE handler */
1441 signal(SIGPIPE
, fr
->apache_sigpipe_handler
);
1445 doClientWrite
= TRUE
;
1448 if (fr
->role
== FCGI_RESPONDER
&& doClientWrite
) {
1449 if (write_to_client(fr
) != OK
) {
1450 #if defined(SIGPIPE) && MODULE_MAGIC_NUMBER < 19990320
1451 /* Make sure we leave with Apache's sigpipe_handler in place */
1452 if (fr
->apache_sigpipe_handler
!= NULL
)
1453 signal(SIGPIPE
, fr
->apache_sigpipe_handler
);
1455 close_connection_to_fs(fr
);
1456 ap_kill_timeout(fr
->r
);
1461 if (fcgi_protocol_dequeue(rp
, fr
) != OK
)
1462 return server_error(fr
);
1464 if (fr
->keepReadingFromFcgiApp
&& fr
->exitStatusSet
) {
1465 /* we're done talking to the fcgi app */
1466 fr
->keepReadingFromFcgiApp
= FALSE
;
1467 close_connection_to_fs(fr
);
1470 if (fr
->parseHeader
== SCAN_CGI_READING_HEADERS
) {
1471 if ((err
= process_headers(r
, fr
))) {
1472 ap_log_rerror(FCGI_LOG_ERR
, r
,
1473 "FastCGI: comm with server \"%s\" aborted: error parsing headers: %s", fr
->fs_path
, err
);
1474 return server_error(fr
);
1480 switch (fr
->parseHeader
) {
1482 case SCAN_CGI_FINISHED
:
1483 if (fr
->role
== FCGI_RESPONDER
) {
1484 #ifdef RUSSIAN_APACHE
1487 ap_bflush(r
->connection
->client
);
1489 ap_bgetopt(r
->connection
->client
, BO_BYTECT
, &r
->bytes_sent
);
1493 case SCAN_CGI_READING_HEADERS
:
1494 ap_log_rerror(FCGI_LOG_ERR
, r
,
1495 "FastCGI: incomplete headers (%d bytes) received from server \"%s\"",
1496 fr
->header
->nelts
, fr
->fs_path
);
1497 return server_error(fr
);
1499 case SCAN_CGI_BAD_HEADER
:
1500 return server_error(fr
);
1502 case SCAN_CGI_INT_REDIRECT
:
1503 case SCAN_CGI_SRV_REDIRECT
:
1505 * XXX We really should be soaking all client input
1506 * and all script output. See mod_cgi.c.
1507 * There's other differences we need to pick up here as well!
1508 * This has to be revisited.
1521 static fcgi_request
*create_fcgi_request(request_rec
* const r
, const char *fs_path
)
1523 struct stat
*my_finfo
;
1524 pool
* const p
= r
->pool
;
1526 fcgi_request
* const fr
= (fcgi_request
*)ap_pcalloc(p
, sizeof(fcgi_request
));
1529 my_finfo
= (struct stat
*)ap_palloc(p
, sizeof(struct stat
));
1530 if (stat(fs_path
, my_finfo
) < 0) {
1531 ap_log_rerror(FCGI_LOG_ERR
, r
, "FastCGI: stat() of \"%s\" failed", fs_path
);
1536 my_finfo
= &r
->finfo
;
1537 fs_path
= r
->filename
;
1540 fs
= fcgi_util_fs_get_by_id(fs_path
, r
->server
->server_uid
, r
->server
->server_gid
);
1542 /* Its a request for a dynamic FastCGI application */
1543 const char * const err
=
1544 fcgi_util_fs_is_path_ok(p
, fs_path
, my_finfo
, r
->server
->server_uid
, r
->server
->server_gid
);
1547 ap_log_rerror(FCGI_LOG_ERR_NOERRNO
, r
, "FastCGI: invalid (dynamic) server \"%s\": %s", fs_path
, err
);
1552 fr
->serverInputBuffer
= fcgi_buf_new(p
, SERVER_BUFSIZE
);
1553 fr
->serverOutputBuffer
= fcgi_buf_new(p
, SERVER_BUFSIZE
);
1554 fr
->clientInputBuffer
= fcgi_buf_new(p
, SERVER_BUFSIZE
);
1555 fr
->clientOutputBuffer
= fcgi_buf_new(p
, SERVER_BUFSIZE
);
1556 fr
->erBufPtr
= fcgi_buf_new(p
, sizeof(FCGI_EndRequestBody
) + 1);
1557 fr
->gotHeader
= FALSE
;
1558 fr
->parseHeader
= SCAN_CGI_READING_HEADERS
;
1559 fr
->header
= ap_make_array(p
, 1, 1);
1560 fr
->fs_stderr
= NULL
;
1562 fr
->readingEndRequestBody
= FALSE
;
1564 fr
->exitStatusSet
= FALSE
;
1565 fr
->requestId
= 1; /* anything but zero is OK here */
1566 fr
->eofSent
= FALSE
;
1567 fr
->role
= FCGI_RESPONDER
;
1568 fr
->expectingClientContent
= FALSE
;
1569 fr
->keepReadingFromFcgiApp
= TRUE
;
1571 fr
->fs_path
= fs_path
;
1572 fr
->authHeaders
= ap_make_table(p
, 10);
1574 fr
->fd
= INVALID_SOCKET
;
1575 fr
->dynamic
= ((fs
== NULL
) || (fs
->directive
== APP_CLASS_DYNAMIC
)) ? TRUE
: FALSE
;
1576 fr
->using_npipe_io
= FALSE
;
1578 fr
->dynamic
= (fs
== NULL
) ? TRUE
: FALSE
;
1583 set_uid_n_gid(r
, &fr
->user
, &fr
->group
);
1589 *----------------------------------------------------------------------
1593 * This routine gets called for a request that corresponds to
1594 * a FastCGI connection. It performs the request synchronously.
1597 * Final status of request: OK or NOT_FOUND or SERVER_ERROR.
1600 * Request performed.
1602 *----------------------------------------------------------------------
1605 /* Stolen from mod_cgi.c..
1606 * KLUDGE --- for back-combatibility, we don't have to check ExecCGI
1607 * in ScriptAliased directories, which means we need to know if this
1608 * request came through ScriptAlias or not... so the Alias module
1609 * leaves a note for us.
1611 static int apache_is_scriptaliased(request_rec
*r
)
1613 const char *t
= ap_table_get(r
->notes
, "alias-forced-type");
1614 return t
&& (!strcasecmp(t
, "cgi-script"));
1617 /* If a script wants to produce its own Redirect body, it now
1618 * has to explicitly *say* "Status: 302". If it wants to use
1619 * Apache redirects say "Status: 200". See process_headers().
1621 static int post_process_for_redirects(request_rec
* const r
,
1622 const fcgi_request
* const fr
)
1624 switch(fr
->parseHeader
) {
1625 case SCAN_CGI_INT_REDIRECT
:
1627 /* @@@ There are still differences between the handling in
1628 * mod_cgi and mod_fastcgi. This needs to be revisited.
1630 /* We already read the message body (if any), so don't allow
1631 * the redirected request to think it has one. We can ignore
1632 * Transfer-Encoding, since we used REQUEST_CHUNKED_ERROR.
1635 r
->method_number
= M_GET
;
1636 ap_table_unset(r
->headers_in
, "Content-length");
1638 ap_internal_redirect_handler(ap_table_get(r
->headers_out
, "Location"), r
);
1641 case SCAN_CGI_SRV_REDIRECT
:
1649 /******************************************************************************
1650 * Process fastcgi-script requests. Based on mod_cgi::cgi_handler().
1652 static int content_handler(request_rec
*r
)
1654 fcgi_request
*fr
= NULL
;
1657 /* Setup a new FastCGI request */
1658 if ((fr
= create_fcgi_request(r
, NULL
)) == NULL
)
1659 return SERVER_ERROR
;
1661 /* If its a dynamic invocation, make sure scripts are OK here */
1662 if (fr
->dynamic
&& !(ap_allow_options(r
) & OPT_EXECCGI
) && !apache_is_scriptaliased(r
)) {
1663 ap_log_rerror(FCGI_LOG_ERR_NOERRNO
, r
,
1664 "FastCGI: \"ExecCGI Option\" is off in this directory: %s", r
->uri
);
1665 return SERVER_ERROR
;
1668 /* Process the fastcgi-script request */
1669 if ((ret
= do_work(r
, fr
)) != OK
)
1672 /* Special case redirects */
1673 return post_process_for_redirects(r
, fr
);
1677 static int post_process_auth_passed_header(table
*t
, const char *key
, const char * const val
)
1679 if (strncasecmp(key
, "Variable-", 9) == 0)
1682 ap_table_setn(t
, key
, val
);
1686 static int post_process_auth_passed_compat_header(table
*t
, const char *key
, const char * const val
)
1688 if (strncasecmp(key
, "Variable-", 9) == 0)
1689 ap_table_setn(t
, key
+ 9, val
);
1694 static int post_process_auth_failed_header(table
* const t
, const char * const key
, const char * const val
)
1696 ap_table_setn(t
, key
, val
);
1700 static void post_process_auth(fcgi_request
* const fr
, const int passed
)
1702 request_rec
* const r
= fr
->r
;
1704 /* Restore the saved subprocess_env because we muddied ours up */
1705 r
->subprocess_env
= fr
->saved_subprocess_env
;
1708 if (fr
->auth_compat
) {
1709 ap_table_do((int (*)(void *, const char *, const char *))post_process_auth_passed_compat_header
,
1710 (void *)r
->subprocess_env
, fr
->authHeaders
, NULL
);
1713 ap_table_do((int (*)(void *, const char *, const char *))post_process_auth_passed_header
,
1714 (void *)r
->subprocess_env
, fr
->authHeaders
, NULL
);
1718 ap_table_do((int (*)(void *, const char *, const char *))post_process_auth_failed_header
,
1719 (void *)r
->err_headers_out
, fr
->authHeaders
, NULL
);
1722 /* @@@ Restore these.. its a hack until I rewrite the header handling */
1723 r
->status
= HTTP_OK
;
1724 r
->status_line
= NULL
;
1727 static int check_user_authentication(request_rec
*r
)
1729 int res
, authenticated
= 0;
1730 const char *password
;
1732 const fcgi_dir_config
* const dir_config
=
1733 (const fcgi_dir_config
*)ap_get_module_config(r
->per_dir_config
, &fastcgi_module
);
1735 if (dir_config
->authenticator
== NULL
)
1738 /* Get the user password */
1739 if ((res
= ap_get_basic_auth_pw(r
, &password
)) != OK
)
1742 if ((fr
= create_fcgi_request(r
, dir_config
->authenticator
)) == NULL
)
1743 return SERVER_ERROR
;
1745 /* Save the existing subprocess_env, because we're gonna muddy it up */
1746 fr
->saved_subprocess_env
= ap_copy_table(r
->pool
, r
->subprocess_env
);
1748 ap_table_setn(r
->subprocess_env
, "REMOTE_PASSWD", password
);
1749 ap_table_setn(r
->subprocess_env
, "FCGI_APACHE_ROLE", "AUTHENTICATOR");
1751 /* The FastCGI Protocol doesn't differentiate authentication */
1752 fr
->role
= FCGI_AUTHORIZER
;
1754 /* Do we need compatibility mode? */
1755 fr
->auth_compat
= (dir_config
->authenticator_options
& FCGI_COMPAT
);
1757 if ((res
= do_work(r
, fr
)) != OK
)
1758 goto AuthenticationFailed
;
1760 authenticated
= (r
->status
== 200);
1761 post_process_auth(fr
, authenticated
);
1763 /* A redirect shouldn't be allowed during the authentication phase */
1764 if (ap_table_get(r
->headers_out
, "Location") != NULL
) {
1765 ap_log_rerror(FCGI_LOG_ERR_NOERRNO
, r
,
1766 "FastCGI: FastCgiAuthenticator \"%s\" redirected (not allowed)",
1767 dir_config
->authenticator
);
1768 goto AuthenticationFailed
;
1774 AuthenticationFailed
:
1775 if (!(dir_config
->authenticator_options
& FCGI_AUTHORITATIVE
))
1778 /* @@@ Probably should support custom_responses */
1779 ap_note_basic_auth_failure(r
);
1780 ap_log_rerror(FCGI_LOG_ERR_NOERRNO
, r
,
1781 "FastCGI: authentication failed for user \"%s\": %s", r
->connection
->user
, r
->uri
);
1782 return (res
== OK
) ? AUTH_REQUIRED
: res
;
1785 static int check_user_authorization(request_rec
*r
)
1787 int res
, authorized
= 0;
1789 const fcgi_dir_config
* const dir_config
=
1790 (const fcgi_dir_config
*)ap_get_module_config(r
->per_dir_config
, &fastcgi_module
);
1792 if (dir_config
->authorizer
== NULL
)
1795 /* @@@ We should probably honor the existing parameters to the require directive
1796 * as well as allow the definition of new ones (or use the basename of the
1797 * FastCGI server and pass the rest of the directive line), but for now keep
1800 if ((fr
= create_fcgi_request(r
, dir_config
->authorizer
)) == NULL
)
1801 return SERVER_ERROR
;
1803 /* Save the existing subprocess_env, because we're gonna muddy it up */
1804 fr
->saved_subprocess_env
= ap_copy_table(r
->pool
, r
->subprocess_env
);
1806 ap_table_setn(r
->subprocess_env
, "FCGI_APACHE_ROLE", "AUTHORIZER");
1808 fr
->role
= FCGI_AUTHORIZER
;
1810 /* Do we need compatibility mode? */
1811 fr
->auth_compat
= (dir_config
->authenticator_options
& FCGI_COMPAT
);
1813 if ((res
= do_work(r
, fr
)) != OK
)
1814 goto AuthorizationFailed
;
1816 authorized
= (r
->status
== 200);
1817 post_process_auth(fr
, authorized
);
1819 /* A redirect shouldn't be allowed during the authorization phase */
1820 if (ap_table_get(r
->headers_out
, "Location") != NULL
) {
1821 ap_log_rerror(FCGI_LOG_ERR_NOERRNO
, r
,
1822 "FastCGI: FastCgiAuthorizer \"%s\" redirected (not allowed)",
1823 dir_config
->authorizer
);
1824 goto AuthorizationFailed
;
1830 AuthorizationFailed
:
1831 if (!(dir_config
->authorizer_options
& FCGI_AUTHORITATIVE
))
1834 /* @@@ Probably should support custom_responses */
1835 ap_note_basic_auth_failure(r
);
1836 ap_log_rerror(FCGI_LOG_ERR_NOERRNO
, r
,
1837 "FastCGI: authorization failed for user \"%s\": %s", r
->connection
->user
, r
->uri
);
1838 return (res
== OK
) ? AUTH_REQUIRED
: res
;
1841 static int check_access(request_rec
*r
)
1843 int res
, access_allowed
= 0;
1845 const fcgi_dir_config
* const dir_config
=
1846 (fcgi_dir_config
*)ap_get_module_config(r
->per_dir_config
, &fastcgi_module
);
1848 if (dir_config
== NULL
|| dir_config
->access_checker
== NULL
)
1851 if ((fr
= create_fcgi_request(r
, dir_config
->access_checker
)) == NULL
)
1852 return SERVER_ERROR
;
1854 /* Save the existing subprocess_env, because we're gonna muddy it up */
1855 fr
->saved_subprocess_env
= ap_copy_table(r
->pool
, r
->subprocess_env
);
1857 ap_table_setn(r
->subprocess_env
, "FCGI_APACHE_ROLE", "ACCESS_CHECKER");
1859 /* The FastCGI Protocol doesn't differentiate access control */
1860 fr
->role
= FCGI_AUTHORIZER
;
1862 /* Do we need compatibility mode? */
1863 fr
->auth_compat
= (dir_config
->authenticator_options
& FCGI_COMPAT
);
1865 if ((res
= do_work(r
, fr
)) != OK
)
1868 access_allowed
= (r
->status
== 200);
1869 post_process_auth(fr
, access_allowed
);
1871 /* A redirect shouldn't be allowed during the access check phase */
1872 if (ap_table_get(r
->headers_out
, "Location") != NULL
) {
1873 ap_log_rerror(FCGI_LOG_ERR_NOERRNO
, r
,
1874 "FastCGI: FastCgiAccessChecker \"%s\" redirected (not allowed)",
1875 dir_config
->access_checker
);
1883 if (!(dir_config
->access_checker_options
& FCGI_AUTHORITATIVE
))
1886 /* @@@ Probably should support custom_responses */
1887 ap_log_rerror(FCGI_LOG_ERR_NOERRNO
, r
, "FastCGI: access denied: %s", r
->uri
);
1888 return (res
== OK
) ? FORBIDDEN
: res
;
1893 command_rec fastcgi_cmds
[] = {
1894 { "AppClass", fcgi_config_new_static_server
, NULL
, RSRC_CONF
, RAW_ARGS
, NULL
},
1895 { "FastCgiServer", fcgi_config_new_static_server
, NULL
, RSRC_CONF
, RAW_ARGS
, NULL
},
1897 { "ExternalAppClass", fcgi_config_new_external_server
, NULL
, RSRC_CONF
, RAW_ARGS
, NULL
},
1898 { "FastCgiExternalServer", fcgi_config_new_external_server
, NULL
, RSRC_CONF
, RAW_ARGS
, NULL
},
1900 { "FastCgiIpcDir", fcgi_config_set_socket_dir
, NULL
, RSRC_CONF
, TAKE1
, NULL
},
1902 { "FastCgiSuexec", fcgi_config_set_suexec
, NULL
, RSRC_CONF
, TAKE1
, NULL
},
1904 { "FCGIConfig", fcgi_config_set_config
, NULL
, RSRC_CONF
, RAW_ARGS
, NULL
},
1905 { "FastCgiConfig", fcgi_config_set_config
, NULL
, RSRC_CONF
, RAW_ARGS
, NULL
},
1907 { "FastCgiAuthenticator", fcgi_config_new_auth_server
,
1908 (void *)FCGI_AUTH_TYPE_AUTHENTICATOR
, ACCESS_CONF
, TAKE12
,
1909 "a fastcgi-script path (absolute or relative to ServerRoot) followed by an optional -compat" },
1910 { "FastCgiAuthenticatorAuthoritative", fcgi_config_set_authoritative_slot
,
1911 (void *)XtOffsetOf(fcgi_dir_config
, authenticator_options
), ACCESS_CONF
, FLAG
,
1912 "Set to 'off' to allow authentication to be passed along to lower modules upon failure" },
1914 { "FastCgiAuthorizer", fcgi_config_new_auth_server
,
1915 (void *)FCGI_AUTH_TYPE_AUTHORIZER
, ACCESS_CONF
, TAKE12
,
1916 "a fastcgi-script path (absolute or relative to ServerRoot) followed by an optional -compat" },
1917 { "FastCgiAuthorizerAuthoritative", fcgi_config_set_authoritative_slot
,
1918 (void *)XtOffsetOf(fcgi_dir_config
, authorizer_options
), ACCESS_CONF
, FLAG
,
1919 "Set to 'off' to allow authorization to be passed along to lower modules upon failure" },
1921 { "FastCgiAccessChecker", fcgi_config_new_auth_server
,
1922 (void *)FCGI_AUTH_TYPE_ACCESS_CHECKER
, ACCESS_CONF
, TAKE12
,
1923 "a fastcgi-script path (absolute or relative to ServerRoot) followed by an optional -compat" },
1924 { "FastCgiAccessCheckerAuthoritative", fcgi_config_set_authoritative_slot
,
1925 (void *)XtOffsetOf(fcgi_dir_config
, access_checker_options
), ACCESS_CONF
, FLAG
,
1926 "Set to 'off' to allow access control to be passed along to lower modules upon failure" },
1931 handler_rec fastcgi_handlers
[] = {
1932 { FCGI_MAGIC_TYPE
, content_handler
},
1933 { "fastcgi-script", content_handler
},
1938 module MODULE_VAR_EXPORT fastcgi_module
= {
1939 STANDARD_MODULE_STUFF
,
1940 init_module
, /* initializer */
1941 fcgi_config_create_dir_config
, /* per-dir config creator */
1942 NULL
, /* per-dir config merger (default: override) */
1943 NULL
, /* per-server config creator */
1944 NULL
, /* per-server config merger (default: override) */
1945 fastcgi_cmds
, /* command table */
1946 fastcgi_handlers
, /* [9] content handlers */
1947 NULL
, /* [2] URI-to-filename translation */
1948 check_user_authentication
, /* [5] authenticate user_id */
1949 check_user_authorization
, /* [6] authorize user_id */
1950 check_access
, /* [4] check access (based on src & http headers) */
1951 NULL
, /* [7] check/set MIME type */
1952 NULL
, /* [8] fixups */
1953 NULL
, /* [10] logger */
1954 NULL
, /* [3] header-parser */
1955 fcgi_child_init
, /* process initialization */
1956 fcgi_child_exit
, /* process exit/cleanup */
1957 NULL
/* [1] post read-request handling */