4 * Apache server module for FastCGI.
6 * $Id: mod_fastcgi.c,v 1.92 2000/05/10 05:15:48 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
);
177 job
->fs_path
= strdup(fs_path
);
178 job
->user
= strdup(user
);
179 job
->group
= strdup(group
);
181 buflen
= sprintf(buf
, "%c %s %s %s*", id
, fs_path
, user
, group
);
187 job
->fs_path
= strdup(fs_path
);
188 job
->user
= strdup(user
);
189 job
->group
= strdup(group
);
191 buflen
= sprintf(buf
, "%c %s %s %s*", id
, fs_path
, user
, group
);
197 job
->fs_path
= strdup(fs_path
);
199 job
->start_time
= req_usec
;
200 job
->user
= strdup(user
);
201 job
->group
= strdup(group
);
203 buflen
= sprintf(buf
, "%c %s %s %s %lu %lu*", id
, fs_path
, user
, group
, q_usec
, req_usec
);
209 if (fcgi_pm_add_job(job
) == 0)
212 SetEvent(fcgi_event_handles
[MBOX_EVENT
]);
214 ap_assert(buflen
<= FCGI_MAX_MSG_LEN
);
216 if (write(fcgi_pm_pipe
[1], (const void *)buf
, buflen
) != buflen
) {
217 ap_log_error(FCGI_LOG_WARN
, fcgi_apache_main_server
,
218 "FastCGI: write() to PM failed");
225 *----------------------------------------------------------------------
229 * An Apache module initializer, called by the Apache core
230 * after reading the server config.
232 * Start the process manager no matter what, since there may be a
233 * request for dynamic FastCGI applications without any being
234 * configured as static applications. Also, check for the existence
235 * and create if necessary a subdirectory into which all dynamic
238 *----------------------------------------------------------------------
240 static void init_module(server_rec
*s
, pool
*p
)
244 /* Register to reset to default values when the config pool is cleaned */
246 ap_register_cleanup(p
, NULL
, fcgi_config_reset_globals
, ap_null_cleanup
);
249 ap_add_version_component("mod_fastcgi/" MOD_FASTCGI_VERSION
);
251 fcgi_config_set_fcgi_uid_n_gid(1);
253 /* keep these handy */
254 fcgi_config_pool
= p
;
255 fcgi_apache_main_server
= s
;
258 /* Create Unix/Domain socket directory */
259 if ((err
= fcgi_config_make_dir(p
, fcgi_socket_dir
)))
260 ap_log_error(FCGI_LOG_ERR
, s
, "FastCGI: %s", err
);
263 /* Create Dynamic directory */
264 if ((err
= fcgi_config_make_dynamic_dir(p
, 1)))
265 ap_log_error(FCGI_LOG_ERR
, s
, "FastCGI: %s", err
);
268 /* Create the pipe for comm with the PM */
269 if (pipe(fcgi_pm_pipe
) < 0) {
270 ap_log_error(FCGI_LOG_ERR
, s
, "FastCGI: pipe() failed");
273 /* Spawn the PM only once. Under Unix, Apache calls init() routines
274 * twice, once before detach() and once after. Win32 doesn't detach.
275 * Under DSO, DSO modules are unloaded between the two init() calls.
276 * Under Unix, the -X switch causes two calls to init() but no detach
277 * (but all subprocesses are wacked so the PM is toasted anyway)! */
279 if (ap_standalone
&& getppid() != 1)
282 /* Start the Process Manager */
283 fcgi_pm_pid
= ap_spawn_child(p
, fcgi_pm_main
, NULL
, kill_only_once
, NULL
, NULL
, NULL
);
284 if (fcgi_pm_pid
<= 0) {
285 ap_log_error(FCGI_LOG_ALERT
, s
,
286 "FastCGI: can't start the process manager, spawn_child() failed");
289 close(fcgi_pm_pipe
[0]);
293 static void fcgi_child_init(server_rec
*server_conf
, pool
*p
)
298 /* Create the Event Handlers */
299 fcgi_event_handles
[0] = CreateEvent(NULL
, FALSE
, FALSE
, NULL
);
300 fcgi_event_handles
[1] = CreateEvent(NULL
, FALSE
, FALSE
, NULL
);
301 fcgi_event_handles
[2] = CreateEvent(NULL
, FALSE
, FALSE
, NULL
);
302 fcgi_dynamic_mbox_mutex
= CreateMutex(FALSE
, FALSE
, NULL
);
304 /* Spawn of the process manager thread */
305 fcgi_pm_thread
= CreateThread(NULL
, 0, (LPTHREAD_START_ROUTINE
)fcgi_pm_main
, NULL
, 0, &tid
);
310 static void fcgi_child_exit(server_rec
*server_conf
, pool
*p
) {
313 /* Signaling the PM thread tp exit*/
314 SetEvent(fcgi_event_handles
[TERM_EVENT
]);
316 /* Waiting on pm thread to exit */
317 WaitForSingleObject(fcgi_pm_thread
, INFINITE
);
324 *----------------------------------------------------------------------
328 * Terminate a line: scan to the next newline, scan back to the
329 * first non-space character and store a terminating zero. Return
330 * the next character past the end of the newline.
332 * If the end of the string is reached, ASSERT!
334 * If the FIRST character(s) in the line are '\n' or "\r\n", the
335 * first character is replaced with a NULL and next character
336 * past the newline is returned. NOTE: this condition supercedes
337 * the processing of RFC-822 continuation lines.
339 * If continuation is set to 'TRUE', then it parses a (possible)
340 * sequence of RFC-822 continuation lines.
346 * Termination byte stored in string.
348 *----------------------------------------------------------------------
350 static char *get_header_line(char *start
, int continuation
)
355 if(p
[0] == '\r' && p
[1] == '\n') { /* If EOL in 1st 2 chars */
356 p
++; /* point to \n and stop */
357 } else if(*p
!= '\n') {
360 if(*p
== '\n' && p
[1] != ' ' && p
[1] != '\t')
365 while(*p
!= '\0' && *p
!= '\n') {
371 ap_assert(*p
!= '\0');
376 * Trim any trailing whitespace.
378 while(isspace((unsigned char)p
[-1]) && p
> start
) {
387 *----------------------------------------------------------------------
391 * Call with r->parseHeader == SCAN_CGI_READING_HEADERS
392 * and initial script output in fr->header.
394 * If the initial script output does not include the header
395 * terminator ("\r\n\r\n") process_headers returns with no side
396 * effects, to be called again when more script output
397 * has been appended to fr->header.
399 * If the initial script output includes the header terminator,
400 * process_headers parses the headers and determines whether or
401 * not the remaining script output will be sent to the client.
402 * If so, process_headers sends the HTTP response headers to the
403 * client and copies any non-header script output to the output
410 * May set r->parseHeader to:
411 * SCAN_CGI_FINISHED -- headers parsed, returning script response
412 * SCAN_CGI_BAD_HEADER -- malformed header from script
413 * SCAN_CGI_INT_REDIRECT -- handler should perform internal redirect
414 * SCAN_CGI_SRV_REDIRECT -- handler should return REDIRECT
416 *----------------------------------------------------------------------
419 static const char *process_headers(request_rec
*r
, fcgi_request
*fr
)
421 char *p
, *next
, *name
, *value
;
423 int hasContentType
, hasStatus
, hasLocation
;
425 ap_assert(fr
->parseHeader
== SCAN_CGI_READING_HEADERS
);
427 if (fr
->header
== NULL
)
431 * Do we have the entire header? Scan for the blank line that
432 * terminates the header.
434 p
= (char *)fr
->header
->elts
;
435 len
= fr
->header
->nelts
;
437 while(len
-- && flag
< 2) {
447 name
= "Invalid Character";
457 /* Return (to be called later when we have more data)
458 * if we don't have an entire header. */
463 * Parse all the headers.
465 fr
->parseHeader
= SCAN_CGI_FINISHED
;
466 hasContentType
= hasStatus
= hasLocation
= FALSE
;
467 next
= (char *)fr
->header
->elts
;
469 next
= get_header_line(name
= next
, TRUE
);
473 if ((p
= strchr(name
, ':')) == NULL
) {
477 while (p
!= name
&& isspace((unsigned char)*(p
- 1))) {
484 if (strpbrk(name
, " \t") != NULL
) {
488 while (isspace((unsigned char)*value
)) {
492 if (strcasecmp(name
, "Status") == 0) {
493 int statusValue
= strtol(value
, NULL
, 10);
496 goto DuplicateNotAllowed
;
498 if (statusValue
< 0) {
499 fr
->parseHeader
= SCAN_CGI_BAD_HEADER
;
500 return ap_psprintf(r
->pool
, "invalid Status '%s'", value
);
503 r
->status
= statusValue
;
504 r
->status_line
= ap_pstrdup(r
->pool
, value
);
508 if (fr
->role
== FCGI_RESPONDER
) {
509 if (strcasecmp(name
, "Content-type") == 0) {
510 if (hasContentType
) {
511 goto DuplicateNotAllowed
;
513 hasContentType
= TRUE
;
514 r
->content_type
= ap_pstrdup(r
->pool
, value
);
518 if (strcasecmp(name
, "Location") == 0) {
520 goto DuplicateNotAllowed
;
523 ap_table_set(r
->headers_out
, "Location", value
);
527 /* If the script wants them merged, it can do it */
528 ap_table_add(r
->err_headers_out
, name
, value
);
532 ap_table_add(fr
->authHeaders
, name
, value
);
536 if (fr
->role
!= FCGI_RESPONDER
)
540 * Who responds, this handler or Apache?
543 const char *location
= ap_table_get(r
->headers_out
, "Location");
545 * Based on internal redirect handling in mod_cgi.c...
547 * If a script wants to produce its own Redirect
548 * body, it now has to explicitly *say* "Status: 302"
550 if (r
->status
== 200) {
551 if(location
[0] == '/') {
553 * Location is an relative path. This handler will
554 * consume all script output, then have Apache perform an
557 fr
->parseHeader
= SCAN_CGI_INT_REDIRECT
;
561 * Location is an absolute URL. If the script didn't
562 * produce a Content-type header, this handler will
563 * consume all script output and then have Apache generate
564 * its standard redirect response. Otherwise this handler
565 * will transmit the script's response.
567 fr
->parseHeader
= SCAN_CGI_SRV_REDIRECT
;
573 * We're responding. Send headers, buffer excess script output.
575 ap_send_http_header(r
);
577 /* We need to reinstate our timeout, send_http_header() kill()s it */
578 ap_hard_timeout("FastCGI request processing", r
);
583 len
= fr
->header
->nelts
- (next
- fr
->header
->elts
);
585 ap_assert(BufferLength(fr
->clientOutputBuffer
) == 0);
586 if (BufferFree(fr
->clientOutputBuffer
) < len
) {
587 fr
->clientOutputBuffer
= fcgi_buf_new(r
->pool
, len
);
589 ap_assert(BufferFree(fr
->clientOutputBuffer
) >= len
);
591 int sent
= fcgi_buf_add_block(fr
->clientOutputBuffer
, next
, len
);
592 ap_assert(sent
== len
);
597 /* Log first line of a multi-line header */
598 if ((p
= strpbrk(name
, "\r\n")) != NULL
)
600 fr
->parseHeader
= SCAN_CGI_BAD_HEADER
;
601 return ap_psprintf(r
->pool
, "malformed header '%s'", name
);
604 fr
->parseHeader
= SCAN_CGI_BAD_HEADER
;
605 return ap_psprintf(r
->pool
, "duplicate header '%s'", name
);
609 * Read from the client filling both the FastCGI server buffer and the
610 * client buffer with the hopes of buffering the client data before
611 * making the connect() to the FastCGI server. This prevents slow
612 * clients from keeping the FastCGI server in processing longer than is
615 static int read_from_client_n_queue(fcgi_request
*fr
)
621 while (BufferFree(fr
->clientInputBuffer
) > 0 || BufferFree(fr
->serverOutputBuffer
) > 0) {
622 fcgi_protocol_queue_client_buffer(fr
);
624 if (fr
->expectingClientContent
<= 0)
627 fcgi_buf_get_free_block_info(fr
->clientInputBuffer
, &end
, &count
);
631 if ((countRead
= ap_get_client_block(fr
->r
, end
, count
)) < 0)
635 fr
->expectingClientContent
= 0;
637 fcgi_buf_add_update(fr
->clientInputBuffer
, countRead
);
643 static int write_to_client(fcgi_request
*fr
)
648 fcgi_buf_get_block_info(fr
->clientOutputBuffer
, &begin
, &count
);
652 /* If fewer than count bytes are written, an error occured.
653 * ap_bwrite() typically forces a flushed write to the client, this
654 * effectively results in a block (and short packets) - it should
655 * be fixed, but I didn't win much support for the idea on new-httpd.
656 * So, without patching Apache, the best way to deal with this is
657 * to size the fcgi_bufs to hold all of the script output (within
658 * reason) so the script can be released from having to wait around
659 * for the transmission to the client to complete. */
660 #ifdef RUSSIAN_APACHE
661 if (ap_rwrite(begin
, count
, fr
->r
) != count
) {
662 ap_log_rerror(FCGI_LOG_INFO
, fr
->r
,
663 "FastCGI: client stopped connection before send body completed");
667 if (ap_bwrite(fr
->r
->connection
->client
, begin
, count
) != (int) count
) {
668 ap_log_rerror(FCGI_LOG_INFO
, fr
->r
,
669 "FastCGI: client stopped connection before send body completed");
675 /* Don't bother with a wrapped buffer, limiting exposure to slow
676 * clients. The BUFF routines don't allow a writev from above,
677 * and don't always memcpy to minimize small write()s, this should
678 * be fixed, but I didn't win much support for the idea on
679 * new-httpd - I'll have to _prove_ its a problem first.. */
681 /* The default behaviour used to be to flush with every write, but this
682 * can tie up the FastCGI server longer than is necessary so its an option now */
683 if (fr
->fs
&& fr
->fs
->flush
) {
684 #ifdef RUSSIAN_APACHE
685 if (ap_rflush(fr
->r
)) {
686 ap_log_rerror(FCGI_LOG_INFO
, fr
->r
,
687 "FastCGI: client stopped connection before send body completed");
691 if (ap_bflush(fr
->r
->connection
->client
)) {
692 ap_log_rerror(FCGI_LOG_INFO
, fr
->r
,
693 "FastCGI: client stopped connection before send body completed");
699 fcgi_buf_toss(fr
->clientOutputBuffer
, count
);
703 /*******************************************************************************
704 * Determine the user and group suexec should be called with.
705 * Based on code in Apache's create_argv_cmd() (util_script.c).
707 static void set_uid_n_gid(request_rec
*r
, const char **user
, const char **group
)
709 if (fcgi_suexec
== NULL
) {
715 if (strncmp("/~", r
->uri
, 2) == 0) {
716 /* its a user dir uri, just send the ~user, and leave it to the PM */
717 char *end
= strchr(r
->uri
+ 2, '/');
720 *user
= memcpy(ap_pcalloc(r
->pool
, end
- r
->uri
), r
->uri
+ 1, end
- r
->uri
- 1);
722 *user
= ap_pstrdup(r
->pool
, r
->uri
+ 1);
726 *user
= ap_psprintf(r
->pool
, "%ld", (long)r
->server
->server_uid
);
727 *group
= ap_psprintf(r
->pool
, "%ld", (long)r
->server
->server_gid
);
731 /*******************************************************************************
732 * Close the connection to the FastCGI server. This is normally called by
733 * do_work(), but may also be called as in request pool cleanup.
735 static void close_connection_to_fs(fcgi_request
*fr
)
737 pool
*rp
= fr
->r
->pool
;
740 ap_pclosesocket(rp
, fr
->fd
);
744 fcgi_rdwr_unlock(fr
->lockFd
, READER
);
746 ap_pclosef(rp
, fr
->lockFd
);
749 if (fr
->keepReadingFromFcgiApp
== FALSE
) {
750 /* XXX REQ_COMPLETE is only sent for requests which complete
751 * normally WRT the fcgi app. There is no data sent for
752 * connect() timeouts or requests which complete abnormally.
753 * KillDynamicProcs() and RemoveRecords() need to be looked at
754 * to be sure they can reasonably handle these cases before
755 * sending these sort of stats - theres some funk in there.
756 * XXX We should do something special when this a pool cleanup.
758 if (fcgi_util_gettimeofday(&fr
->completeTime
) < 0) {
759 /* there's no point to aborting the request, just log it */
760 ap_log_error(FCGI_LOG_ERR
, fr
->r
->server
, "FastCGI: gettimeofday() failed");
762 struct timeval qtime
, rtime
;
764 timersub(&fr
->queueTime
, &fr
->startTime
, &qtime
);
765 timersub(&fr
->completeTime
, &fr
->queueTime
, &rtime
);
767 send_to_pm(rp
, REQ_COMPLETE
, fr
->fs_path
,
769 qtime
.tv_sec
* 1000000 + qtime
.tv_usec
,
770 rtime
.tv_sec
* 1000000 + rtime
.tv_usec
);
776 /*******************************************************************************
777 * Connect to the FastCGI server.
779 static const char *open_connection_to_fs(fcgi_request
*fr
)
782 fd_set write_fds
, read_fds
;
784 request_rec
* const r
= fr
->r
;
785 pool
* const rp
= r
->pool
;
786 const char *socket_path
= NULL
;
787 struct sockaddr
*socket_addr
= NULL
;
788 int socket_addr_len
= 0;
790 unsigned long ioctl_arg
;
794 const char *err
= NULL
;
797 /* Create the connection point */
799 socket_path
= fcgi_util_socket_hash_filename(rp
, fr
->fs_path
, fr
->user
, fr
->group
);
800 socket_path
= fcgi_util_socket_make_path_absolute(rp
, socket_path
, 1);
803 err
= fcgi_util_socket_make_domain_addr(rp
, (struct sockaddr_un
**)&socket_addr
,
804 &socket_addr_len
, socket_path
);
810 if (fr
->fs
->dest_addr
!= NULL
) {
811 socket_addr
= fr
->fs
->dest_addr
;
813 else if (fr
->fs
->socket_addr
) {
814 socket_addr
= fr
->fs
->socket_addr
;
817 socket_path
= fr
->fs
->socket_path
;
820 socket_addr
= fr
->fs
->socket_addr
;
822 socket_addr_len
= fr
->fs
->socket_addr_len
;
825 /* Dynamic app's lockfile handling */
828 const char *lockFileName
= fcgi_util_socket_get_lock_filename(rp
, socket_path
);
838 if (stat(lockFileName
, &lstbuf
) == 0 && S_ISREG(lstbuf
.st_mode
))
841 if (dynamicAutoUpdate
&& (stat(fr
->fs_path
, &bstbuf
) == 0)
843 && ((fr
->fs
->restartTime
> 0) && (fr
->fs
->restartTime
< bstbuf
.st_mtime
)))
845 && (lstbuf
.st_mtime
< bstbuf
.st_mtime
))
848 struct timeval tv
= {1, 0};
850 /* Its already running, but there's a newer one,
851 * ask the process manager to start it.
852 * it will notice that the binary is newer,
853 * and do a restart instead.
855 send_to_pm(rp
, PLEASE_START
, fr
->fs_path
, fr
->user
, fr
->group
, 0, 0);
857 /* Avoid sleep/alarm interactions */
858 ap_select(0, NULL
, NULL
, NULL
, &tv
);
861 fr
->lockFd
= fr
->fs
->dynamic_lock
;
864 fr
->lockFd
= ap_popenf(rp
, lockFileName
, O_APPEND
, 0);
865 result
= (fr
->lockFd
< 0) ? (0) : (1);
868 struct timeval tv
= {1, 0};
870 send_to_pm(rp
, PLEASE_START
, fr
->fs_path
, fr
->user
, fr
->group
, 0, 0);
875 /* Avoid sleep/alarm interactions */
876 ap_select(0, NULL
, NULL
, NULL
, &tv
);
880 fr
->fs
= fcgi_util_fs_get_by_id(fr
->fs_path
, 0, 0);
882 } while (result
!= 1);
884 /* Block until we get a shared (non-exclusive) read Lock */
885 if (fcgi_wait_for_shared_read_lock(fr
->lockFd
) < 0)
886 return "failed to obtain a shared read lock on server lockfile";
892 if (fr
->dynamic
&& fcgi_util_gettimeofday(&fr
->startTime
) < 0)
893 return "gettimeofday() failed";
895 if ((fr
->dynamic
&& dynamicAppConnectTimeout
) || (!fr
->dynamic
&& fr
->fs
->appConnectTimeout
)) {
896 DWORD interval
= (fr
->dynamic
? dynamicAppConnectTimeout
: fr
->fs
->appConnectTimeout
) * 1000;
898 if (!WaitNamedPipe(socket_path
, interval
))
899 return "named pipe failed to connect()";
902 if (! WaitNamedPipe(socket_path
, NMPWAIT_WAIT_FOREVER
) ) {
903 errcode
= GetLastError();
904 return "named pipe failed to connect()";
908 fr
->fd
= (int) CreateFile(socket_path
, GENERIC_READ
| GENERIC_WRITE
,
909 FILE_SHARE_READ
| FILE_SHARE_WRITE
, NULL
,
910 OPEN_EXISTING
, FILE_ATTRIBUTE_NORMAL
, NULL
);
912 if ((HANDLE
)fr
->fd
== INVALID_HANDLE_VALUE
)
913 return "CreateFile() failed";
915 ap_note_cleanups_for_h(rp
, (HANDLE
)fr
->fd
);
917 fr
->using_npipe_io
= TRUE
;
919 if (fcgi_util_gettimeofday(&fr
->queueTime
) < 0)
920 return "gettimeofday() failed";
927 /* Create the socket */
928 fr
->fd
= ap_psocket(rp
, socket_addr
->sa_family
, SOCK_STREAM
, 0);
931 return "ap_psocket() failed";
934 if (fr
->fd
>= FD_SETSIZE
) {
935 return ap_psprintf(rp
, "socket file descriptor (%u) is larger than "
936 "FD_SETSIZE (%u), you probably need to rebuild Apache with a "
937 "larger FD_SETSIZE", fr
->fd
, FD_SETSIZE
);
941 /* If appConnectTimeout is non-zero, setup do a non-blocking connect */
942 if ((fr
->dynamic
&& dynamicAppConnectTimeout
) || (!fr
->dynamic
&& fr
->fs
->appConnectTimeout
)) {
944 if ((fd_flags
= fcntl(fr
->fd
, F_GETFL
, 0)) < 0)
945 return "fcntl(F_GETFL) failed";
946 if (fcntl(fr
->fd
, F_SETFL
, fd_flags
| O_NONBLOCK
) < 0)
947 return "fcntl(F_SETFL) failed";
950 if (ioctlsocket(fr
->fd
, FIONBIO
, &ioctl_arg
) != 0)
951 return "ioctlsocket(FIONBIO) failed";
955 if (fr
->dynamic
&& fcgi_util_gettimeofday(&fr
->startTime
) < 0)
956 return "gettimeofday() failed";
959 if (connect(fr
->fd
, (struct sockaddr
*)socket_addr
, socket_addr_len
) == 0)
960 goto ConnectionComplete
;
963 errcode
= GetLastError();
964 if (errcode
!= WSAEWOULDBLOCK
)
965 return "connect() failed";
967 /* ECONNREFUSED means the listen queue is full (or there isn't one).
968 * With dynamic I can at least make sure the PM knows this is occuring */
969 if (fr
->dynamic
&& errno
== ECONNREFUSED
) {
970 /* @@@ This might be better as some other "kind" of message */
971 send_to_pm(rp
, CONN_TIMEOUT
, fr
->fs_path
, fr
->user
, fr
->group
, 0, 0);
973 errno
= ECONNREFUSED
;
976 if (errno
!= EINPROGRESS
)
977 return "connect() failed";
980 /* The connect() is non-blocking */
987 FD_SET(fr
->fd
, &write_fds
);
988 read_fds
= write_fds
;
989 tval
.tv_sec
= dynamicPleaseStartDelay
;
992 status
= ap_select((fr
->fd
+1), &read_fds
, &write_fds
, NULL
, &tval
);
996 if (fcgi_util_gettimeofday(&fr
->queueTime
) < 0)
997 return "gettimeofday() failed";
1001 /* select() timed out */
1002 send_to_pm(rp
, CONN_TIMEOUT
, fr
->fs_path
, fr
->user
, fr
->group
, 0, 0);
1003 } while ((fr
->queueTime
.tv_sec
- fr
->startTime
.tv_sec
) < (int)dynamicAppConnectTimeout
);
1005 /* XXX These can be moved down when dynamic vars live is a struct */
1007 return ap_psprintf(rp
, "connect() timed out (appConnTimeout=%dsec)",
1008 dynamicAppConnectTimeout
);
1012 tval
.tv_sec
= fr
->fs
->appConnectTimeout
;
1014 FD_ZERO(&write_fds
);
1015 FD_SET(fr
->fd
, &write_fds
);
1016 read_fds
= write_fds
;
1018 status
= ap_select((fr
->fd
+1), &read_fds
, &write_fds
, NULL
, &tval
);
1020 return ap_psprintf(rp
, "connect() timed out (appConnTimeout=%dsec)",
1021 fr
->fs
->appConnectTimeout
);
1026 return "select() failed";
1028 if (FD_ISSET(fr
->fd
, &write_fds
) || FD_ISSET(fr
->fd
, &read_fds
)) {
1030 NET_SIZE_T len
= sizeof(error
);
1032 if (getsockopt(fr
->fd
, SOL_SOCKET
, SO_ERROR
, (char *)&error
, &len
) < 0)
1033 /* Solaris pending error */
1034 return "select() failed (Solaris pending error)";
1037 /* Berkeley-derived pending error */
1039 return "select() failed (pending error)";
1042 return "select() error - THIS CAN'T HAPPEN!";
1045 /* Return to blocking mode if it was set up */
1046 if ((fr
->dynamic
&& dynamicAppConnectTimeout
) || (!fr
->dynamic
&& fr
->fs
->appConnectTimeout
)) {
1049 if (ioctlsocket(fr
->fd
, FIONBIO
, &ioctl_arg
) != 0)
1050 return "ioctlsocket(FIONBIO) failed";
1052 if ((fcntl(fr
->fd
, F_SETFL
, fd_flags
)) < 0)
1053 return "fcntl(F_SETFL) failed";
1058 if (socket_addr
->sa_family
== AF_INET
) {
1059 /* We shouldn't be sending small packets and there's no application
1060 * level ack of the data we send, so disable Nagle */
1062 setsockopt(fr
->fd
, IPPROTO_TCP
, TCP_NODELAY
, (char *)&set
, sizeof(set
));
1069 static int server_error(fcgi_request
*fr
)
1071 #if defined(SIGPIPE) && MODULE_MAGIC_NUMBER < 19990320
1072 /* Make sure we leave with Apache's sigpipe_handler in place */
1073 if (fr
->apache_sigpipe_handler
!= NULL
)
1074 signal(SIGPIPE
, fr
->apache_sigpipe_handler
);
1076 close_connection_to_fs(fr
);
1077 ap_kill_timeout(fr
->r
);
1078 return SERVER_ERROR
;
1081 static void log_fcgi_server_stderr(void *data
)
1083 const fcgi_request
* const fr
= (fcgi_request
*)data
;
1088 if (fr
->fs_stderr_len
) {
1089 ap_log_rerror(FCGI_LOG_ERR_NOERRNO
, fr
->r
,
1090 "FastCGI: server \"%s\" stderr: %s", fr
->fs_path
, fr
->fs_stderr
);
1094 /*----------------------------------------------------------------------
1095 * This is the core routine for moving data between the FastCGI
1096 * application and the Web server's client.
1098 static int do_work(request_rec
*r
, fcgi_request
*fr
)
1100 struct timeval timeOut
, dynamic_last_activity_time
= {0, 0};
1101 fd_set read_set
, write_set
;
1102 int status
= 0, idle_timeout
;
1103 int numFDs
, dynamic_first_read
= fr
->dynamic
? 1 : 0;
1105 int envSent
= FALSE
; /* has the complete ENV been buffered? */
1108 const char *err
= NULL
;
1111 FD_ZERO(&write_set
);
1113 fcgi_protocol_queue_begin_request(fr
);
1115 /* Buffer as much of the environment as we can fit */
1117 envSent
= fcgi_protocol_queue_env(r
, fr
, &env
);
1119 /* Start the Apache dropdead timer. See comments at top of file. */
1120 ap_hard_timeout("buffering of FastCGI client data", r
);
1122 /* Read as much as possible from the client. */
1123 if (fr
->role
== FCGI_RESPONDER
) {
1124 status
= ap_setup_client_block(r
, REQUEST_CHUNKED_ERROR
);
1129 fr
->expectingClientContent
= (ap_should_client_block(r
) != 0);
1131 if (read_from_client_n_queue(fr
) != OK
)
1132 return server_error(fr
);
1135 /* Connect to the FastCGI Application */
1136 ap_hard_timeout("connect() to FastCGI server", r
);
1137 if ((err
= open_connection_to_fs(fr
))) {
1138 ap_log_rerror(FCGI_LOG_ERR
, r
,
1139 "FastCGI: failed to connect to server \"%s\": %s", fr
->fs_path
, err
);
1140 return server_error(fr
);
1143 numFDs
= fr
->fd
+ 1;
1144 idle_timeout
= fr
->dynamic
? dynamic_idle_timeout
: fr
->fs
->idle_timeout
;
1146 if (dynamic_first_read
) {
1147 dynamic_last_activity_time
= fr
->startTime
;
1149 if (dynamicAppConnectTimeout
) {
1150 struct timeval qwait
;
1151 timersub(&fr
->queueTime
, &fr
->startTime
, &qwait
);
1152 dynamic_first_read
= qwait
.tv_sec
/ dynamicPleaseStartDelay
+ 1;
1156 /* @@@ We never reset the timer in this loop, most folks don't mess w/
1157 * Timeout directive which means we've got the 5 min default which is way
1158 * to long to tie up a fs. We need a better/configurable solution that
1159 * uses the select */
1160 ap_hard_timeout("FastCGI request processing", r
);
1162 /* Register to get the script's stderr logged at the end of the request */
1164 ap_register_cleanup(rp
, (void *)fr
, log_fcgi_server_stderr
, ap_null_cleanup
);
1165 ap_unblock_alarms();
1167 /* The socket is writeable, so get the first write out of the way */
1168 if (fcgi_buf_get_to_fd(fr
->serverOutputBuffer
, fr
->fd
) < 0) {
1169 ap_log_rerror(FCGI_LOG_ERR
, r
,
1170 "FastCGI: comm with server \"%s\" aborted: write failed", fr
->fs_path
);
1171 return server_error(fr
);
1174 while (fr
->keepReadingFromFcgiApp
1175 || BufferLength(fr
->serverInputBuffer
) > 0
1176 || BufferLength(fr
->clientOutputBuffer
) > 0) {
1178 /* If we didn't buffer all of the environment yet, buffer some more */
1180 envSent
= fcgi_protocol_queue_env(r
, fr
, &env
);
1182 /* Read as much as possible from the client. */
1183 if (fr
->role
== FCGI_RESPONDER
&& !fr
->eofSent
&& envSent
) {
1184 if (read_from_client_n_queue(fr
) != OK
)
1185 return server_error(fr
);
1188 /* To avoid deadlock, don't do a blocking select to write to
1189 * the FastCGI application without selecting to read from the
1190 * FastCGI application.
1192 doClientWrite
= FALSE
;
1193 if (fr
->keepReadingFromFcgiApp
&& BufferFree(fr
->serverInputBuffer
) > 0) {
1196 if (!fr
->using_npipe_io
) {
1198 FD_SET(fr
->fd
, &read_set
);
1200 /* Is data buffered for output to the FastCGI server? */
1201 if (BufferLength(fr
->serverOutputBuffer
) > 0) {
1202 FD_SET(fr
->fd
, &write_set
);
1204 FD_CLR(fr
->fd
, &write_set
);
1210 * If there's data buffered to send to the client, don't
1211 * wait indefinitely for the FastCGI app; the app might
1212 * be doing server push.
1214 if (BufferLength(fr
->clientOutputBuffer
) > 0) {
1216 timeOut
.tv_usec
= 100000; /* 0.1 sec */
1218 else if (dynamic_first_read
) {
1220 struct timeval qwait
;
1222 if (fcgi_util_gettimeofday(&fr
->queueTime
) < 0) {
1223 ap_log_rerror(FCGI_LOG_ERR
, r
, "FastCGI: gettimeofday() failed");
1224 return server_error(fr
);
1227 /* Check for idle_timeout */
1229 dynamic_last_activity_time
= fr
->queueTime
;
1232 struct timeval idle_time
;
1233 timersub(&fr
->queueTime
, &dynamic_last_activity_time
, &idle_time
);
1234 if (idle_time
.tv_sec
> idle_timeout
) {
1235 send_to_pm(rp
, CONN_TIMEOUT
, fr
->fs_path
, fr
->user
, fr
->group
, 0, 0);
1236 ap_log_rerror(FCGI_LOG_ERR
, r
,
1237 "FastCGI: comm with (dynamic) server \"%s\" aborted: (first read) idle timeout (%d sec)",
1238 fr
->fs_path
, idle_timeout
);
1239 return server_error(fr
);
1243 timersub(&fr
->queueTime
, &fr
->startTime
, &qwait
);
1245 delay
= dynamic_first_read
* dynamicPleaseStartDelay
;
1246 if (qwait
.tv_sec
< delay
) {
1247 timeOut
.tv_sec
= delay
;
1248 timeOut
.tv_usec
= 100000; /* fudge for select() slop */
1249 timersub(&timeOut
, &qwait
, &timeOut
);
1252 /* Killed time somewhere.. client read? */
1253 send_to_pm(rp
, CONN_TIMEOUT
, fr
->fs_path
, fr
->user
, fr
->group
, 0, 0);
1254 dynamic_first_read
= qwait
.tv_sec
/ dynamicPleaseStartDelay
+ 1;
1255 timeOut
.tv_sec
= dynamic_first_read
* dynamicPleaseStartDelay
;
1256 timeOut
.tv_usec
= 100000; /* fudge for select() slop */
1257 timersub(&timeOut
, &qwait
, &timeOut
);
1261 timeOut
.tv_sec
= idle_timeout
;
1262 timeOut
.tv_usec
= 0;
1266 if (!fr
->using_npipe_io
) {
1268 if ((status
= ap_select(numFDs
, &read_set
, &write_set
, NULL
, &timeOut
)) < 0) {
1269 ap_log_rerror(FCGI_LOG_ERR
, r
,
1270 "FastCGI: comm with server \"%s\" aborted: select() failed", fr
->fs_path
);
1271 return server_error(fr
);
1276 int stopTime
= time(NULL
) + timeOut
.tv_sec
;
1279 if (!(BufferLength(fr
->serverOutputBuffer
) > 0)) {
1282 while ((timeOut
.tv_sec
!= 0) && (time(NULL
) <= stopTime
)) {
1283 if (PeekNamedPipe((HANDLE
) fr
->fd
,NULL
, 0, NULL
, &bytesavail
, NULL
) &&
1299 if (BufferLength(fr
->clientOutputBuffer
) > 0) {
1300 doClientWrite
= TRUE
;
1302 else if (dynamic_first_read
) {
1303 struct timeval qwait
;
1305 if (fcgi_util_gettimeofday(&fr
->queueTime
) < 0) {
1306 ap_log_rerror(FCGI_LOG_ERR
, r
, "FastCGI: gettimeofday() failed");
1307 return server_error(fr
);
1310 timersub(&fr
->queueTime
, &fr
->startTime
, &qwait
);
1312 send_to_pm(rp
, CONN_TIMEOUT
, fr
->fs_path
, fr
->user
, fr
->group
, 0, 0);
1314 dynamic_first_read
= qwait
.tv_sec
/ dynamicPleaseStartDelay
+ 1;
1317 ap_log_rerror(FCGI_LOG_ERR
, r
,
1318 "FastCGI: comm with server \"%s\" aborted: idle timeout (%d sec)",
1319 fr
->fs_path
, idle_timeout
);
1320 return server_error(fr
);
1324 #if defined(SIGPIPE) && MODULE_MAGIC_NUMBER < 19990320
1325 /* Disable Apache's SIGPIPE handler */
1326 fr
->apache_sigpipe_handler
= signal(SIGPIPE
, SIG_IGN
);
1329 /* Read from the FastCGI server */
1331 if (((fr
->using_npipe_io
) &&
1332 (BufferFree(fr
->serverInputBuffer
) > 0)) || FD_ISSET(fr
->fd
, &read_set
)) {
1334 if (FD_ISSET(fr
->fd
, &read_set
)) {
1336 if (dynamic_first_read
) {
1337 dynamic_first_read
= 0;
1338 if (fcgi_util_gettimeofday(&fr
->queueTime
) < 0) {
1339 ap_log_rerror(FCGI_LOG_ERR
, r
, "FastCGI: gettimeofday() failed");
1340 return server_error(fr
);
1344 if ((status
= fcgi_buf_add_fd(fr
->serverInputBuffer
, fr
->fd
)) < 0) {
1345 ap_log_rerror(FCGI_LOG_ERR
, r
,
1346 "FastCGI: comm with server \"%s\" aborted: read failed", fr
->fs_path
);
1347 return server_error(fr
);
1351 fr
->keepReadingFromFcgiApp
= FALSE
;
1352 close_connection_to_fs(fr
);
1356 /* Write to the FastCGI server */
1358 if (((fr
->using_npipe_io
) &&
1359 (BufferLength(fr
->serverOutputBuffer
) > 0)) || FD_ISSET(fr
->fd
, &write_set
)) {
1361 if (FD_ISSET(fr
->fd
, &write_set
)) {
1364 if (fcgi_buf_get_to_fd(fr
->serverOutputBuffer
, fr
->fd
) < 0) {
1365 ap_log_rerror(FCGI_LOG_ERR
, r
,
1366 "FastCGI: comm with server \"%s\" aborted: write failed", fr
->fs_path
);
1367 return server_error(fr
);
1371 #if defined(SIGPIPE) && MODULE_MAGIC_NUMBER < 19990320
1372 /* Reinstall Apache's SIGPIPE handler */
1373 signal(SIGPIPE
, fr
->apache_sigpipe_handler
);
1377 doClientWrite
= TRUE
;
1380 if (fr
->role
== FCGI_RESPONDER
&& doClientWrite
) {
1381 if (write_to_client(fr
) != OK
) {
1382 #if defined(SIGPIPE) && MODULE_MAGIC_NUMBER < 19990320
1383 /* Make sure we leave with Apache's sigpipe_handler in place */
1384 if (fr
->apache_sigpipe_handler
!= NULL
)
1385 signal(SIGPIPE
, fr
->apache_sigpipe_handler
);
1387 close_connection_to_fs(fr
);
1388 ap_kill_timeout(fr
->r
);
1393 if (fcgi_protocol_dequeue(rp
, fr
) != OK
)
1394 return server_error(fr
);
1396 if (fr
->keepReadingFromFcgiApp
&& fr
->exitStatusSet
) {
1397 /* we're done talking to the fcgi app */
1398 fr
->keepReadingFromFcgiApp
= FALSE
;
1399 close_connection_to_fs(fr
);
1402 if (fr
->parseHeader
== SCAN_CGI_READING_HEADERS
) {
1403 if ((err
= process_headers(r
, fr
))) {
1404 ap_log_rerror(FCGI_LOG_ERR
, r
,
1405 "FastCGI: comm with server \"%s\" aborted: error parsing headers: %s", fr
->fs_path
, err
);
1406 return server_error(fr
);
1412 switch (fr
->parseHeader
) {
1414 case SCAN_CGI_FINISHED
:
1415 if (fr
->role
== FCGI_RESPONDER
) {
1416 #ifdef RUSSIAN_APACHE
1419 ap_bflush(r
->connection
->client
);
1421 ap_bgetopt(r
->connection
->client
, BO_BYTECT
, &r
->bytes_sent
);
1425 case SCAN_CGI_READING_HEADERS
:
1426 ap_log_rerror(FCGI_LOG_ERR
, r
,
1427 "FastCGI: incomplete headers (%d bytes) received from server \"%s\"",
1428 fr
->header
->nelts
, fr
->fs_path
);
1429 return server_error(fr
);
1431 case SCAN_CGI_BAD_HEADER
:
1432 return server_error(fr
);
1434 case SCAN_CGI_INT_REDIRECT
:
1435 case SCAN_CGI_SRV_REDIRECT
:
1437 * XXX We really should be soaking all client input
1438 * and all script output. See mod_cgi.c.
1439 * There's other differences we need to pick up here as well!
1440 * This has to be revisited.
1453 static fcgi_request
*create_fcgi_request(request_rec
* const r
, const char *fs_path
)
1455 struct stat
*my_finfo
;
1456 pool
* const p
= r
->pool
;
1458 fcgi_request
* const fr
= (fcgi_request
*)ap_pcalloc(p
, sizeof(fcgi_request
));
1461 my_finfo
= (struct stat
*)ap_palloc(p
, sizeof(struct stat
));
1462 if (stat(fs_path
, my_finfo
) < 0) {
1463 ap_log_rerror(FCGI_LOG_ERR
, r
, "FastCGI: stat() of \"%s\" failed", fs_path
);
1468 my_finfo
= &r
->finfo
;
1469 fs_path
= r
->filename
;
1472 fs
= fcgi_util_fs_get_by_id(fs_path
, r
->server
->server_uid
, r
->server
->server_gid
);
1474 /* Its a request for a dynamic FastCGI application */
1475 const char * const err
=
1476 fcgi_util_fs_is_path_ok(p
, fs_path
, my_finfo
, r
->server
->server_uid
, r
->server
->server_gid
);
1479 ap_log_rerror(FCGI_LOG_ERR_NOERRNO
, r
, "FastCGI: invalid (dynamic) server \"%s\": %s", fs_path
, err
);
1484 fr
->serverInputBuffer
= fcgi_buf_new(p
, SERVER_BUFSIZE
);
1485 fr
->serverOutputBuffer
= fcgi_buf_new(p
, SERVER_BUFSIZE
);
1486 fr
->clientInputBuffer
= fcgi_buf_new(p
, SERVER_BUFSIZE
);
1487 fr
->clientOutputBuffer
= fcgi_buf_new(p
, SERVER_BUFSIZE
);
1488 fr
->erBufPtr
= fcgi_buf_new(p
, sizeof(FCGI_EndRequestBody
) + 1);
1489 fr
->gotHeader
= FALSE
;
1490 fr
->parseHeader
= SCAN_CGI_READING_HEADERS
;
1491 fr
->header
= ap_make_array(p
, 1, 1);
1492 fr
->fs_stderr
= NULL
;
1494 fr
->readingEndRequestBody
= FALSE
;
1496 fr
->exitStatusSet
= FALSE
;
1497 fr
->requestId
= 1; /* anything but zero is OK here */
1498 fr
->eofSent
= FALSE
;
1499 fr
->role
= FCGI_RESPONDER
;
1500 fr
->expectingClientContent
= FALSE
;
1501 fr
->keepReadingFromFcgiApp
= TRUE
;
1503 fr
->fs_path
= fs_path
;
1504 fr
->authHeaders
= ap_make_table(p
, 10);
1506 fr
->fd
= INVALID_SOCKET
;
1507 fr
->dynamic
= ((fs
== NULL
) || (fs
->directive
== APP_CLASS_DYNAMIC
)) ? TRUE
: FALSE
;
1508 fr
->using_npipe_io
= FALSE
;
1510 fr
->dynamic
= (fs
== NULL
) ? TRUE
: FALSE
;
1514 set_uid_n_gid(r
, &fr
->user
, &fr
->group
);
1520 *----------------------------------------------------------------------
1524 * This routine gets called for a request that corresponds to
1525 * a FastCGI connection. It performs the request synchronously.
1528 * Final status of request: OK or NOT_FOUND or SERVER_ERROR.
1531 * Request performed.
1533 *----------------------------------------------------------------------
1536 /* Stolen from mod_cgi.c..
1537 * KLUDGE --- for back-combatibility, we don't have to check ExecCGI
1538 * in ScriptAliased directories, which means we need to know if this
1539 * request came through ScriptAlias or not... so the Alias module
1540 * leaves a note for us.
1542 static int apache_is_scriptaliased(request_rec
*r
)
1544 const char *t
= ap_table_get(r
->notes
, "alias-forced-type");
1545 return t
&& (!strcasecmp(t
, "cgi-script"));
1548 /* If a script wants to produce its own Redirect body, it now
1549 * has to explicitly *say* "Status: 302". If it wants to use
1550 * Apache redirects say "Status: 200". See process_headers().
1552 static int post_process_for_redirects(request_rec
* const r
,
1553 const fcgi_request
* const fr
)
1555 switch(fr
->parseHeader
) {
1556 case SCAN_CGI_INT_REDIRECT
:
1558 /* @@@ There are still differences between the handling in
1559 * mod_cgi and mod_fastcgi. This needs to be revisited.
1561 /* We already read the message body (if any), so don't allow
1562 * the redirected request to think it has one. We can ignore
1563 * Transfer-Encoding, since we used REQUEST_CHUNKED_ERROR.
1566 r
->method_number
= M_GET
;
1567 ap_table_unset(r
->headers_in
, "Content-length");
1569 ap_internal_redirect_handler(ap_table_get(r
->headers_out
, "Location"), r
);
1572 case SCAN_CGI_SRV_REDIRECT
:
1580 /******************************************************************************
1581 * Process fastcgi-script requests. Based on mod_cgi::cgi_handler().
1583 static int content_handler(request_rec
*r
)
1585 fcgi_request
*fr
= NULL
;
1588 /* Setup a new FastCGI request */
1589 if ((fr
= create_fcgi_request(r
, NULL
)) == NULL
)
1590 return SERVER_ERROR
;
1592 /* If its a dynamic invocation, make sure scripts are OK here */
1593 if (fr
->dynamic
&& !(ap_allow_options(r
) & OPT_EXECCGI
) && !apache_is_scriptaliased(r
)) {
1594 ap_log_rerror(FCGI_LOG_ERR_NOERRNO
, r
,
1595 "FastCGI: \"ExecCGI Option\" is off in this directory: %s", r
->uri
);
1596 return SERVER_ERROR
;
1599 /* Process the fastcgi-script request */
1600 if ((ret
= do_work(r
, fr
)) != OK
)
1603 /* Special case redirects */
1604 return post_process_for_redirects(r
, fr
);
1608 static int post_process_auth_passed_header(table
*t
, const char *key
, const char * const val
)
1610 if (strncasecmp(key
, "Variable-", 9) == 0)
1613 ap_table_setn(t
, key
, val
);
1617 static int post_process_auth_passed_compat_header(table
*t
, const char *key
, const char * const val
)
1619 if (strncasecmp(key
, "Variable-", 9) == 0)
1620 ap_table_setn(t
, key
+ 9, val
);
1625 static int post_process_auth_failed_header(table
* const t
, const char * const key
, const char * const val
)
1627 ap_table_setn(t
, key
, val
);
1631 static void post_process_auth(fcgi_request
* const fr
, const int passed
)
1633 request_rec
* const r
= fr
->r
;
1635 /* Restore the saved subprocess_env because we muddied ours up */
1636 r
->subprocess_env
= fr
->saved_subprocess_env
;
1639 if (fr
->auth_compat
) {
1640 ap_table_do((int (*)(void *, const char *, const char *))post_process_auth_passed_compat_header
,
1641 (void *)r
->subprocess_env
, fr
->authHeaders
, NULL
);
1644 ap_table_do((int (*)(void *, const char *, const char *))post_process_auth_passed_header
,
1645 (void *)r
->subprocess_env
, fr
->authHeaders
, NULL
);
1649 ap_table_do((int (*)(void *, const char *, const char *))post_process_auth_failed_header
,
1650 (void *)r
->err_headers_out
, fr
->authHeaders
, NULL
);
1653 /* @@@ Restore these.. its a hack until I rewrite the header handling */
1654 r
->status
= HTTP_OK
;
1655 r
->status_line
= NULL
;
1658 static int check_user_authentication(request_rec
*r
)
1660 int res
, authenticated
= 0;
1661 const char *password
;
1663 const fcgi_dir_config
* const dir_config
=
1664 (const fcgi_dir_config
*)ap_get_module_config(r
->per_dir_config
, &fastcgi_module
);
1666 if (dir_config
->authenticator
== NULL
)
1669 /* Get the user password */
1670 if ((res
= ap_get_basic_auth_pw(r
, &password
)) != OK
)
1673 if ((fr
= create_fcgi_request(r
, dir_config
->authenticator
)) == NULL
)
1674 return SERVER_ERROR
;
1676 /* Save the existing subprocess_env, because we're gonna muddy it up */
1677 fr
->saved_subprocess_env
= ap_copy_table(r
->pool
, r
->subprocess_env
);
1679 ap_table_setn(r
->subprocess_env
, "REMOTE_PASSWD", password
);
1680 ap_table_setn(r
->subprocess_env
, "FCGI_APACHE_ROLE", "AUTHENTICATOR");
1682 /* The FastCGI Protocol doesn't differentiate authentication */
1683 fr
->role
= FCGI_AUTHORIZER
;
1685 /* Do we need compatibility mode? */
1686 fr
->auth_compat
= (dir_config
->authenticator_options
& FCGI_COMPAT
);
1688 if ((res
= do_work(r
, fr
)) != OK
)
1689 goto AuthenticationFailed
;
1691 authenticated
= (r
->status
== 200);
1692 post_process_auth(fr
, authenticated
);
1694 /* A redirect shouldn't be allowed during the authentication phase */
1695 if (ap_table_get(r
->headers_out
, "Location") != NULL
) {
1696 ap_log_rerror(FCGI_LOG_ERR_NOERRNO
, r
,
1697 "FastCGI: FastCgiAuthenticator \"%s\" redirected (not allowed)",
1698 dir_config
->authenticator
);
1699 goto AuthenticationFailed
;
1705 AuthenticationFailed
:
1706 if (!(dir_config
->authenticator_options
& FCGI_AUTHORITATIVE
))
1709 /* @@@ Probably should support custom_responses */
1710 ap_note_basic_auth_failure(r
);
1711 ap_log_rerror(FCGI_LOG_ERR_NOERRNO
, r
,
1712 "FastCGI: authentication failed for user \"%s\": %s", r
->connection
->user
, r
->uri
);
1713 return (res
== OK
) ? AUTH_REQUIRED
: res
;
1716 static int check_user_authorization(request_rec
*r
)
1718 int res
, authorized
= 0;
1720 const fcgi_dir_config
* const dir_config
=
1721 (const fcgi_dir_config
*)ap_get_module_config(r
->per_dir_config
, &fastcgi_module
);
1723 if (dir_config
->authorizer
== NULL
)
1726 /* @@@ We should probably honor the existing parameters to the require directive
1727 * as well as allow the definition of new ones (or use the basename of the
1728 * FastCGI server and pass the rest of the directive line), but for now keep
1731 if ((fr
= create_fcgi_request(r
, dir_config
->authorizer
)) == NULL
)
1732 return SERVER_ERROR
;
1734 /* Save the existing subprocess_env, because we're gonna muddy it up */
1735 fr
->saved_subprocess_env
= ap_copy_table(r
->pool
, r
->subprocess_env
);
1737 ap_table_setn(r
->subprocess_env
, "FCGI_APACHE_ROLE", "AUTHORIZER");
1739 fr
->role
= FCGI_AUTHORIZER
;
1741 /* Do we need compatibility mode? */
1742 fr
->auth_compat
= (dir_config
->authenticator_options
& FCGI_COMPAT
);
1744 if ((res
= do_work(r
, fr
)) != OK
)
1745 goto AuthorizationFailed
;
1747 authorized
= (r
->status
== 200);
1748 post_process_auth(fr
, authorized
);
1750 /* A redirect shouldn't be allowed during the authorization phase */
1751 if (ap_table_get(r
->headers_out
, "Location") != NULL
) {
1752 ap_log_rerror(FCGI_LOG_ERR_NOERRNO
, r
,
1753 "FastCGI: FastCgiAuthorizer \"%s\" redirected (not allowed)",
1754 dir_config
->authorizer
);
1755 goto AuthorizationFailed
;
1761 AuthorizationFailed
:
1762 if (!(dir_config
->authorizer_options
& FCGI_AUTHORITATIVE
))
1765 /* @@@ Probably should support custom_responses */
1766 ap_note_basic_auth_failure(r
);
1767 ap_log_rerror(FCGI_LOG_ERR_NOERRNO
, r
,
1768 "FastCGI: authorization failed for user \"%s\": %s", r
->connection
->user
, r
->uri
);
1769 return (res
== OK
) ? AUTH_REQUIRED
: res
;
1772 static int check_access(request_rec
*r
)
1774 int res
, access_allowed
= 0;
1776 const fcgi_dir_config
* const dir_config
=
1777 (fcgi_dir_config
*)ap_get_module_config(r
->per_dir_config
, &fastcgi_module
);
1779 if (dir_config
== NULL
|| dir_config
->access_checker
== NULL
)
1782 if ((fr
= create_fcgi_request(r
, dir_config
->access_checker
)) == NULL
)
1783 return SERVER_ERROR
;
1785 /* Save the existing subprocess_env, because we're gonna muddy it up */
1786 fr
->saved_subprocess_env
= ap_copy_table(r
->pool
, r
->subprocess_env
);
1788 ap_table_setn(r
->subprocess_env
, "FCGI_APACHE_ROLE", "ACCESS_CHECKER");
1790 /* The FastCGI Protocol doesn't differentiate access control */
1791 fr
->role
= FCGI_AUTHORIZER
;
1793 /* Do we need compatibility mode? */
1794 fr
->auth_compat
= (dir_config
->authenticator_options
& FCGI_COMPAT
);
1796 if ((res
= do_work(r
, fr
)) != OK
)
1799 access_allowed
= (r
->status
== 200);
1800 post_process_auth(fr
, access_allowed
);
1802 /* A redirect shouldn't be allowed during the access check phase */
1803 if (ap_table_get(r
->headers_out
, "Location") != NULL
) {
1804 ap_log_rerror(FCGI_LOG_ERR_NOERRNO
, r
,
1805 "FastCGI: FastCgiAccessChecker \"%s\" redirected (not allowed)",
1806 dir_config
->access_checker
);
1814 if (!(dir_config
->access_checker_options
& FCGI_AUTHORITATIVE
))
1817 /* @@@ Probably should support custom_responses */
1818 ap_log_rerror(FCGI_LOG_ERR_NOERRNO
, r
, "FastCGI: access denied: %s", r
->uri
);
1819 return (res
== OK
) ? FORBIDDEN
: res
;
1824 command_rec fastcgi_cmds
[] = {
1825 { "AppClass", fcgi_config_new_static_server
, NULL
, RSRC_CONF
, RAW_ARGS
, NULL
},
1826 { "FastCgiServer", fcgi_config_new_static_server
, NULL
, RSRC_CONF
, RAW_ARGS
, NULL
},
1828 { "ExternalAppClass", fcgi_config_new_external_server
, NULL
, RSRC_CONF
, RAW_ARGS
, NULL
},
1829 { "FastCgiExternalServer", fcgi_config_new_external_server
, NULL
, RSRC_CONF
, RAW_ARGS
, NULL
},
1831 { "FastCgiIpcDir", fcgi_config_set_socket_dir
, NULL
, RSRC_CONF
, TAKE1
, NULL
},
1833 { "FastCgiSuexec", fcgi_config_set_suexec
, NULL
, RSRC_CONF
, TAKE1
, NULL
},
1835 { "FCGIConfig", fcgi_config_set_config
, NULL
, RSRC_CONF
, RAW_ARGS
, NULL
},
1836 { "FastCgiConfig", fcgi_config_set_config
, NULL
, RSRC_CONF
, RAW_ARGS
, NULL
},
1838 { "FastCgiAuthenticator", fcgi_config_new_auth_server
,
1839 (void *)FCGI_AUTH_TYPE_AUTHENTICATOR
, ACCESS_CONF
, TAKE12
,
1840 "a fastcgi-script path (absolute or relative to ServerRoot) followed by an optional -compat" },
1841 { "FastCgiAuthenticatorAuthoritative", fcgi_config_set_authoritative_slot
,
1842 (void *)XtOffsetOf(fcgi_dir_config
, authenticator_options
), ACCESS_CONF
, FLAG
,
1843 "Set to 'off' to allow authentication to be passed along to lower modules upon failure" },
1845 { "FastCgiAuthorizer", fcgi_config_new_auth_server
,
1846 (void *)FCGI_AUTH_TYPE_AUTHORIZER
, ACCESS_CONF
, TAKE12
,
1847 "a fastcgi-script path (absolute or relative to ServerRoot) followed by an optional -compat" },
1848 { "FastCgiAuthorizerAuthoritative", fcgi_config_set_authoritative_slot
,
1849 (void *)XtOffsetOf(fcgi_dir_config
, authorizer_options
), ACCESS_CONF
, FLAG
,
1850 "Set to 'off' to allow authorization to be passed along to lower modules upon failure" },
1852 { "FastCgiAccessChecker", fcgi_config_new_auth_server
,
1853 (void *)FCGI_AUTH_TYPE_ACCESS_CHECKER
, ACCESS_CONF
, TAKE12
,
1854 "a fastcgi-script path (absolute or relative to ServerRoot) followed by an optional -compat" },
1855 { "FastCgiAccessCheckerAuthoritative", fcgi_config_set_authoritative_slot
,
1856 (void *)XtOffsetOf(fcgi_dir_config
, access_checker_options
), ACCESS_CONF
, FLAG
,
1857 "Set to 'off' to allow access control to be passed along to lower modules upon failure" },
1862 handler_rec fastcgi_handlers
[] = {
1863 { FCGI_MAGIC_TYPE
, content_handler
},
1864 { "fastcgi-script", content_handler
},
1869 module MODULE_VAR_EXPORT fastcgi_module
= {
1870 STANDARD_MODULE_STUFF
,
1871 init_module
, /* initializer */
1872 fcgi_config_create_dir_config
, /* per-dir config creator */
1873 NULL
, /* per-dir config merger (default: override) */
1874 NULL
, /* per-server config creator */
1875 NULL
, /* per-server config merger (default: override) */
1876 fastcgi_cmds
, /* command table */
1877 fastcgi_handlers
, /* [9] content handlers */
1878 NULL
, /* [2] URI-to-filename translation */
1879 check_user_authentication
, /* [5] authenticate user_id */
1880 check_user_authorization
, /* [6] authorize user_id */
1881 check_access
, /* [4] check access (based on src & http headers) */
1882 NULL
, /* [7] check/set MIME type */
1883 NULL
, /* [8] fixups */
1884 NULL
, /* [10] logger */
1885 NULL
, /* [3] header-parser */
1886 fcgi_child_init
, /* process initialization */
1887 fcgi_child_exit
, /* process exit/cleanup */
1888 NULL
/* [1] post read-request handling */