4 * Apache server module for FastCGI.
6 * $Id: mod_fastcgi.c,v 1.87 2000/04/06 05:29:25 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 */
122 char *fcgi_empty_env
= NULL
;
124 u_int dynamicMaxProcs
= FCGI_DEFAULT_MAX_PROCS
;
125 u_int dynamicMinProcs
= FCGI_DEFAULT_MIN_PROCS
;
126 u_int dynamicMaxClassProcs
= FCGI_DEFAULT_MAX_CLASS_PROCS
;
127 u_int dynamicKillInterval
= FCGI_DEFAULT_KILL_INTERVAL
;
128 u_int dynamicUpdateInterval
= FCGI_DEFAULT_UPDATE_INTERVAL
;
129 float dynamicGain
= FCGI_DEFAULT_GAIN
;
130 u_int dynamicThreshhold1
= FCGI_DEFAULT_THRESHHOLD_1
;
131 u_int dynamicThreshholdN
= FCGI_DEFAULT_THRESHHOLD_N
;
132 u_int dynamicPleaseStartDelay
= FCGI_DEFAULT_START_PROCESS_DELAY
;
133 u_int dynamicAppConnectTimeout
= FCGI_DEFAULT_APP_CONN_TIMEOUT
;
134 char **dynamicEnvp
= &fcgi_empty_env
;
135 u_int dynamicProcessSlack
= FCGI_DEFAULT_PROCESS_SLACK
;
136 int dynamicAutoRestart
= FCGI_DEFAULT_RESTART_DYNAMIC
;
137 int dynamicAutoUpdate
= FCGI_DEFAULT_AUTOUPDATE
;
138 u_int dynamicListenQueueDepth
= FCGI_DEFAULT_LISTEN_Q
;
139 u_int dynamicInitStartDelay
= DEFAULT_INIT_START_DELAY
;
140 u_int dynamicRestartDelay
= FCGI_DEFAULT_RESTART_DELAY
;
141 array_header
*dynamic_pass_headers
= NULL
;
142 u_int dynamic_idle_timeout
= FCGI_DEFAULT_IDLE_TIMEOUT
;
144 /*******************************************************************************
145 * Construct a message and write it to the pm_pipe.
147 static void send_to_pm(pool
* const p
, const char id
, const char * const fs_path
,
148 const char *user
, const char * const group
, const unsigned long q_usec
,
149 const unsigned long req_usec
)
152 char buf
[FCGI_MAX_MSG_LEN
];
154 if (strlen(fs_path
) > FCGI_MAXPATH
) {
155 ap_log_error(FCGI_LOG_ERR_NOERRNO
, fcgi_apache_main_server
,
156 "FastCGI: the path \"%s\" is too long (>%d) for a dynamic server", fs_path
, FCGI_MAXPATH
);
162 buflen
= sprintf(buf
, "%c %s %s %s*", id
, fs_path
, user
, group
);
165 buflen
= sprintf(buf
, "%c %s %s %s*", id
, fs_path
, user
, group
);
168 buflen
= sprintf(buf
, "%c %s %s %s %lu %lu*", id
, fs_path
, user
, group
, q_usec
, req_usec
);
172 ap_assert(buflen
<= FCGI_MAX_MSG_LEN
);
174 if (write(fcgi_pm_pipe
[1], (const void *)buf
, buflen
) != buflen
) {
175 ap_log_error(FCGI_LOG_WARN
, fcgi_apache_main_server
,
176 "FastCGI: write() to PM failed");
182 *----------------------------------------------------------------------
186 * An Apache module initializer, called by the Apache core
187 * after reading the server config.
189 * Start the process manager no matter what, since there may be a
190 * request for dynamic FastCGI applications without any being
191 * configured as static applications. Also, check for the existence
192 * and create if necessary a subdirectory into which all dynamic
195 *----------------------------------------------------------------------
197 static void init_module(server_rec
*s
, pool
*p
)
201 /* Register to reset to default values when the config pool is cleaned */
203 ap_register_cleanup(p
, NULL
, fcgi_config_reset_globals
, ap_null_cleanup
);
206 ap_add_version_component("mod_fastcgi/" MOD_FASTCGI_VERSION
);
208 fcgi_config_set_fcgi_uid_n_gid(1);
210 /* keep these handy */
211 fcgi_config_pool
= p
;
212 fcgi_apache_main_server
= s
;
214 /* Create Unix/Domain socket directory */
215 if ((err
= fcgi_config_make_dir(p
, fcgi_socket_dir
)))
216 ap_log_error(FCGI_LOG_ERR
, s
, "FastCGI: %s", err
);
218 /* Create Dynamic directory */
219 if ((err
= fcgi_config_make_dynamic_dir(p
, 1)))
220 ap_log_error(FCGI_LOG_ERR
, s
, "FastCGI: %s", err
);
222 /* Create the pipe for comm with the PM */
223 if (pipe(fcgi_pm_pipe
) < 0) {
224 ap_log_error(FCGI_LOG_ERR
, s
, "FastCGI: pipe() failed");
227 /* Spawn the PM only once. Under Unix, Apache calls init() routines
228 * twice, once before detach() and once after. Win32 doesn't detach.
229 * Under DSO, DSO modules are unloaded between the two init() calls.
230 * Under Unix, the -X switch causes two calls to init() but no detach
231 * (but all subprocesses are wacked so the PM is toasted anyway)! */
233 if (ap_standalone
&& getppid() != 1)
237 /* Start the Process Manager */
238 fcgi_pm_pid
= ap_spawn_child(p
, fcgi_pm_main
, NULL
, kill_only_once
, NULL
, NULL
, NULL
);
239 if (fcgi_pm_pid
<= 0) {
240 ap_log_error(FCGI_LOG_ALERT
, s
,
241 "FastCGI: can't start the process manager, spawn_child() failed");
244 close(fcgi_pm_pipe
[0]);
248 *----------------------------------------------------------------------
252 * Terminate a line: scan to the next newline, scan back to the
253 * first non-space character and store a terminating zero. Return
254 * the next character past the end of the newline.
256 * If the end of the string is reached, ASSERT!
258 * If the FIRST character(s) in the line are '\n' or "\r\n", the
259 * first character is replaced with a NULL and next character
260 * past the newline is returned. NOTE: this condition supercedes
261 * the processing of RFC-822 continuation lines.
263 * If continuation is set to 'TRUE', then it parses a (possible)
264 * sequence of RFC-822 continuation lines.
270 * Termination byte stored in string.
272 *----------------------------------------------------------------------
274 static char *get_header_line(char *start
, int continuation
)
279 if(p
[0] == '\r' && p
[1] == '\n') { /* If EOL in 1st 2 chars */
280 p
++; /* point to \n and stop */
281 } else if(*p
!= '\n') {
284 if(*p
== '\n' && p
[1] != ' ' && p
[1] != '\t')
289 while(*p
!= '\0' && *p
!= '\n') {
295 ap_assert(*p
!= '\0');
300 * Trim any trailing whitespace.
302 while(isspace((unsigned char)p
[-1]) && p
> start
) {
311 *----------------------------------------------------------------------
315 * Call with r->parseHeader == SCAN_CGI_READING_HEADERS
316 * and initial script output in fr->header.
318 * If the initial script output does not include the header
319 * terminator ("\r\n\r\n") process_headers returns with no side
320 * effects, to be called again when more script output
321 * has been appended to fr->header.
323 * If the initial script output includes the header terminator,
324 * process_headers parses the headers and determines whether or
325 * not the remaining script output will be sent to the client.
326 * If so, process_headers sends the HTTP response headers to the
327 * client and copies any non-header script output to the output
334 * May set r->parseHeader to:
335 * SCAN_CGI_FINISHED -- headers parsed, returning script response
336 * SCAN_CGI_BAD_HEADER -- malformed header from script
337 * SCAN_CGI_INT_REDIRECT -- handler should perform internal redirect
338 * SCAN_CGI_SRV_REDIRECT -- handler should return REDIRECT
340 *----------------------------------------------------------------------
343 static const char *process_headers(request_rec
*r
, fcgi_request
*fr
)
345 char *p
, *next
, *name
, *value
;
347 int hasContentType
, hasStatus
, hasLocation
;
349 ap_assert(fr
->parseHeader
== SCAN_CGI_READING_HEADERS
);
351 if (fr
->header
== NULL
)
355 * Do we have the entire header? Scan for the blank line that
356 * terminates the header.
358 p
= (char *)fr
->header
->elts
;
359 len
= fr
->header
->nelts
;
361 while(len
-- && flag
< 2) {
371 name
= "Invalid Character";
381 /* Return (to be called later when we have more data)
382 * if we don't have an entire header. */
387 * Parse all the headers.
389 fr
->parseHeader
= SCAN_CGI_FINISHED
;
390 hasContentType
= hasStatus
= hasLocation
= FALSE
;
391 next
= (char *)fr
->header
->elts
;
393 next
= get_header_line(name
= next
, TRUE
);
397 if ((p
= strchr(name
, ':')) == NULL
) {
401 while (p
!= name
&& isspace((unsigned char)*(p
- 1))) {
408 if (strpbrk(name
, " \t") != NULL
) {
412 while (isspace((unsigned char)*value
)) {
416 if (strcasecmp(name
, "Status") == 0) {
417 int statusValue
= strtol(value
, NULL
, 10);
420 goto DuplicateNotAllowed
;
422 if (statusValue
< 0) {
423 fr
->parseHeader
= SCAN_CGI_BAD_HEADER
;
424 return ap_psprintf(r
->pool
, "invalid Status '%s'", value
);
427 r
->status
= statusValue
;
428 r
->status_line
= ap_pstrdup(r
->pool
, value
);
432 if (fr
->role
== FCGI_RESPONDER
) {
433 if (strcasecmp(name
, "Content-type") == 0) {
434 if (hasContentType
) {
435 goto DuplicateNotAllowed
;
437 hasContentType
= TRUE
;
438 r
->content_type
= ap_pstrdup(r
->pool
, value
);
442 if (strcasecmp(name
, "Location") == 0) {
444 goto DuplicateNotAllowed
;
447 ap_table_set(r
->headers_out
, "Location", value
);
451 /* If the script wants them merged, it can do it */
452 ap_table_add(r
->err_headers_out
, name
, value
);
456 ap_table_add(fr
->authHeaders
, name
, value
);
460 if (fr
->role
!= FCGI_RESPONDER
)
464 * Who responds, this handler or Apache?
467 const char *location
= ap_table_get(r
->headers_out
, "Location");
469 * Based on internal redirect handling in mod_cgi.c...
471 * If a script wants to produce its own Redirect
472 * body, it now has to explicitly *say* "Status: 302"
474 if (r
->status
== 200) {
475 if(location
[0] == '/') {
477 * Location is an relative path. This handler will
478 * consume all script output, then have Apache perform an
481 fr
->parseHeader
= SCAN_CGI_INT_REDIRECT
;
485 * Location is an absolute URL. If the script didn't
486 * produce a Content-type header, this handler will
487 * consume all script output and then have Apache generate
488 * its standard redirect response. Otherwise this handler
489 * will transmit the script's response.
491 fr
->parseHeader
= SCAN_CGI_SRV_REDIRECT
;
497 * We're responding. Send headers, buffer excess script output.
499 ap_send_http_header(r
);
501 /* We need to reinstate our timeout, send_http_header() kill()s it */
502 ap_hard_timeout("FastCGI request processing", r
);
507 len
= fr
->header
->nelts
- (next
- fr
->header
->elts
);
509 ap_assert(BufferLength(fr
->clientOutputBuffer
) == 0);
510 if (BufferFree(fr
->clientOutputBuffer
) < len
) {
511 fr
->clientOutputBuffer
= fcgi_buf_new(r
->pool
, len
);
513 ap_assert(BufferFree(fr
->clientOutputBuffer
) >= len
);
515 int sent
= fcgi_buf_add_block(fr
->clientOutputBuffer
, next
, len
);
516 ap_assert(sent
== len
);
521 /* Log first line of a multi-line header */
522 if ((p
= strpbrk(name
, "\r\n")) != NULL
)
524 fr
->parseHeader
= SCAN_CGI_BAD_HEADER
;
525 return ap_psprintf(r
->pool
, "malformed header '%s'", name
);
528 fr
->parseHeader
= SCAN_CGI_BAD_HEADER
;
529 return ap_psprintf(r
->pool
, "duplicate header '%s'", name
);
533 * Read from the client filling both the FastCGI server buffer and the
534 * client buffer with the hopes of buffering the client data before
535 * making the connect() to the FastCGI server. This prevents slow
536 * clients from keeping the FastCGI server in processing longer than is
539 static int read_from_client_n_queue(fcgi_request
*fr
)
545 while (BufferFree(fr
->clientInputBuffer
) > 0 || BufferFree(fr
->serverOutputBuffer
) > 0) {
546 fcgi_protocol_queue_client_buffer(fr
);
548 if (fr
->expectingClientContent
<= 0)
551 fcgi_buf_get_free_block_info(fr
->clientInputBuffer
, &end
, &count
);
555 if ((countRead
= ap_get_client_block(fr
->r
, end
, count
)) < 0)
559 fr
->expectingClientContent
= 0;
561 fcgi_buf_add_update(fr
->clientInputBuffer
, countRead
);
567 static int write_to_client(fcgi_request
*fr
)
572 fcgi_buf_get_block_info(fr
->clientOutputBuffer
, &begin
, &count
);
576 /* If fewer than count bytes are written, an error occured.
577 * ap_bwrite() typically forces a flushed write to the client, this
578 * effectively results in a block (and short packets) - it should
579 * be fixed, but I didn't win much support for the idea on new-httpd.
580 * So, without patching Apache, the best way to deal with this is
581 * to size the fcgi_bufs to hold all of the script output (within
582 * reason) so the script can be released from having to wait around
583 * for the transmission to the client to complete. */
584 #ifdef RUSSIAN_APACHE
585 if (ap_rwrite(begin
, count
, fr
->r
) != count
) {
586 ap_log_rerror(FCGI_LOG_INFO
, fr
->r
,
587 "FastCGI: client stopped connection before send body completed");
591 if (ap_bwrite(fr
->r
->connection
->client
, begin
, count
) != count
) {
592 ap_log_rerror(FCGI_LOG_INFO
, fr
->r
,
593 "FastCGI: client stopped connection before send body completed");
599 /* Don't bother with a wrapped buffer, limiting exposure to slow
600 * clients. The BUFF routines don't allow a writev from above,
601 * and don't always memcpy to minimize small write()s, this should
602 * be fixed, but I didn't win much support for the idea on
603 * new-httpd - I'll have to _prove_ its a problem first.. */
605 /* The default behaviour used to be to flush with every write, but this
606 * can tie up the FastCGI server longer than is necessary so its an option now */
607 if (fr
->fs
&& fr
->fs
->flush
) {
608 #ifdef RUSSIAN_APACHE
609 if (ap_rflush(fr
->r
)) {
610 ap_log_rerror(FCGI_LOG_INFO
, fr
->r
,
611 "FastCGI: client stopped connection before send body completed");
615 if (ap_bflush(fr
->r
->connection
->client
)) {
616 ap_log_rerror(FCGI_LOG_INFO
, fr
->r
,
617 "FastCGI: client stopped connection before send body completed");
623 fcgi_buf_toss(fr
->clientOutputBuffer
, count
);
627 /*******************************************************************************
628 * Determine the user and group suexec should be called with.
629 * Based on code in Apache's create_argv_cmd() (util_script.c).
631 static void set_uid_n_gid(request_rec
*r
, const char **user
, const char **group
)
633 if (fcgi_suexec
== NULL
) {
639 if (strncmp("/~", r
->uri
, 2) == 0) {
640 /* its a user dir uri, just send the ~user, and leave it to the PM */
641 char *end
= strchr(r
->uri
+ 2, '/');
644 *user
= memcpy(ap_pcalloc(r
->pool
, end
- r
->uri
), r
->uri
+ 1, end
- r
->uri
- 1);
646 *user
= ap_pstrdup(r
->pool
, r
->uri
+ 1);
650 *user
= ap_psprintf(r
->pool
, "%ld", (long)r
->server
->server_uid
);
651 *group
= ap_psprintf(r
->pool
, "%ld", (long)r
->server
->server_gid
);
655 /*******************************************************************************
656 * Close the connection to the FastCGI server. This is normally called by
657 * do_work(), but may also be called as in request pool cleanup.
659 static void close_connection_to_fs(fcgi_request
*fr
)
661 pool
*rp
= fr
->r
->pool
;
664 ap_pclosesocket(rp
, fr
->fd
);
667 ap_pclosef(rp
, fr
->lockFd
);
669 if (fr
->keepReadingFromFcgiApp
== FALSE
) {
670 /* XXX REQ_COMPLETE is only sent for requests which complete
671 * normally WRT the fcgi app. There is no data sent for
672 * connect() timeouts or requests which complete abnormally.
673 * KillDynamicProcs() and RemoveRecords() need to be looked at
674 * to be sure they can reasonably handle these cases before
675 * sending these sort of stats - theres some funk in there.
676 * XXX We should do something special when this a pool cleanup.
678 if (gettimeofday(&fr
->completeTime
, NULL
) < 0) {
679 /* there's no point to aborting the request, just log it */
680 ap_log_error(FCGI_LOG_ERR
, fr
->r
->server
, "FastCGI: gettimeofday() failed");
682 struct timeval qtime
, rtime
;
684 timersub(&fr
->queueTime
, &fr
->startTime
, &qtime
);
685 timersub(&fr
->completeTime
, &fr
->queueTime
, &rtime
);
687 send_to_pm(rp
, REQ_COMPLETE
, fr
->fs_path
,
689 qtime
.tv_sec
* 1000000 + qtime
.tv_usec
,
690 rtime
.tv_sec
* 1000000 + rtime
.tv_usec
);
696 /*******************************************************************************
697 * Connect to the FastCGI server.
699 static const char *open_connection_to_fs(fcgi_request
*fr
)
703 fd_set write_fds
, read_fds
;
705 request_rec
* const r
= fr
->r
;
706 pool
* const rp
= r
->pool
;
707 const char *socket_path
= NULL
;
708 struct sockaddr
*socket_addr
= NULL
;
710 const char *err
= NULL
;
712 /* Create the connection point */
714 socket_path
= fcgi_util_socket_hash_filename(rp
, fr
->fs_path
, fr
->user
, fr
->group
);
715 socket_path
= fcgi_util_socket_make_path_absolute(rp
, socket_path
, 1);
716 err
= fcgi_util_socket_make_domain_addr(rp
, (struct sockaddr_un
**)&socket_addr
,
717 &socket_addr_len
, socket_path
);
721 socket_addr
= fr
->fs
->socket_addr
;
722 socket_addr_len
= fr
->fs
->socket_addr_len
;
725 /* Dynamic app's lockfile handling */
727 const char *lockFileName
= fcgi_util_socket_get_lock_filename(rp
, socket_path
);
733 if (stat(lockFileName
, &lstbuf
) == 0 && S_ISREG(lstbuf
.st_mode
)) {
734 if (dynamicAutoUpdate
&&
735 (stat(fr
->fs_path
, &bstbuf
) == 0) &&
736 (lstbuf
.st_mtime
< bstbuf
.st_mtime
))
738 struct timeval tv
= {1, 0};
740 /* Its already running, but there's a newer one,
741 * ask the process manager to start it.
742 * it will notice that the binary is newer,
743 * and do a restart instead.
745 send_to_pm(rp
, PLEASE_START
, fr
->fs_path
, fr
->user
, fr
->group
, 0, 0);
747 /* Avoid sleep/alarm interactions */
748 ap_select(0, NULL
, NULL
, NULL
, &tv
);
750 fr
->lockFd
= ap_popenf(rp
, lockFileName
, O_APPEND
, 0);
751 result
= (fr
->lockFd
< 0) ? (0) : (1);
753 struct timeval tv
= {1, 0};
755 send_to_pm(rp
, PLEASE_START
, fr
->fs_path
, fr
->user
, fr
->group
, 0, 0);
757 /* Avoid sleep/alarm interactions */
758 ap_select(0, NULL
, NULL
, NULL
, &tv
);
760 } while (result
!= 1);
762 /* Block until we get a shared (non-exclusive) read Lock */
763 if (fcgi_wait_for_shared_read_lock(fr
->lockFd
) < 0)
764 return "failed to obtain a shared read lock on server lockfile";
767 /* Create the socket */
768 fr
->fd
= ap_psocket(rp
, socket_addr
->sa_family
, SOCK_STREAM
, 0);
770 return "ap_psocket() failed";
772 if (fr
->fd
>= FD_SETSIZE
) {
773 return ap_psprintf(rp
, "socket file descriptor (%u) is larger than "
774 "FD_SETSIZE (%u), you probably need to rebuild Apache with a "
775 "larger FD_SETSIZE", fr
->fd
, FD_SETSIZE
);
778 /* If appConnectTimeout is non-zero, setup do a non-blocking connect */
779 if ((fr
->dynamic
&& dynamicAppConnectTimeout
) || (!fr
->dynamic
&& fr
->fs
->appConnectTimeout
)) {
780 if ((fd_flags
= fcntl(fr
->fd
, F_GETFL
, 0)) < 0)
781 return "fcntl(F_GETFL) failed";
782 if (fcntl(fr
->fd
, F_SETFL
, fd_flags
| O_NONBLOCK
) < 0)
783 return "fcntl(F_SETFL) failed";
786 if (fr
->dynamic
&& gettimeofday(&fr
->startTime
, NULL
) < 0)
787 return "gettimeofday() failed";
790 if (connect(fr
->fd
, (struct sockaddr
*)socket_addr
, socket_addr_len
) == 0)
791 goto ConnectionComplete
;
793 /* ECONNREFUSED means the listen queue is full (or there isn't one).
794 * With dynamic I can at least make sure the PM knows this is occuring */
795 if (fr
->dynamic
&& errno
== ECONNREFUSED
) {
796 /* @@@ This might be better as some other "kind" of message */
797 send_to_pm(rp
, CONN_TIMEOUT
, fr
->fs_path
, fr
->user
, fr
->group
, 0, 0);
799 errno
= ECONNREFUSED
;
802 if (errno
!= EINPROGRESS
)
803 return "connect() failed";
805 /* The connect() is non-blocking */
812 FD_SET(fr
->fd
, &write_fds
);
813 read_fds
= write_fds
;
814 tval
.tv_sec
= dynamicPleaseStartDelay
;
817 status
= ap_select((fr
->fd
+1), &read_fds
, &write_fds
, NULL
, &tval
);
821 if (gettimeofday(&fr
->queueTime
, NULL
) < 0)
822 return "gettimeofday() failed";
826 /* select() timed out */
827 send_to_pm(rp
, CONN_TIMEOUT
, fr
->fs_path
, fr
->user
, fr
->group
, 0, 0);
828 } while ((fr
->queueTime
.tv_sec
- fr
->startTime
.tv_sec
) < dynamicAppConnectTimeout
);
830 /* XXX These can be moved down when dynamic vars live is a struct */
832 return ap_psprintf(rp
, "connect() timed out (appConnTimeout=%dsec)",
833 dynamicAppConnectTimeout
);
837 tval
.tv_sec
= fr
->fs
->appConnectTimeout
;
840 FD_SET(fr
->fd
, &write_fds
);
841 read_fds
= write_fds
;
843 status
= ap_select((fr
->fd
+1), &read_fds
, &write_fds
, NULL
, &tval
);
845 return ap_psprintf(rp
, "connect() timed out (appConnTimeout=%dsec)",
846 fr
->fs
->appConnectTimeout
);
851 return "select() failed";
853 if (FD_ISSET(fr
->fd
, &write_fds
) || FD_ISSET(fr
->fd
, &read_fds
)) {
855 NET_SIZE_T len
= sizeof(error
);
857 if (getsockopt(fr
->fd
, SOL_SOCKET
, SO_ERROR
, (char *)&error
, &len
) < 0)
858 /* Solaris pending error */
859 return "select() failed (Solaris pending error)";
862 /* Berkeley-derived pending error */
864 return "select() failed (pending error)";
867 return "select() error - THIS CAN'T HAPPEN!";
870 /* Return to blocking mode if it was set up */
871 if ((fr
->dynamic
&& dynamicAppConnectTimeout
) || (!fr
->dynamic
&& fr
->fs
->appConnectTimeout
)) {
872 if ((fcntl(fr
->fd
, F_SETFL
, fd_flags
)) < 0)
873 return "fcntl(F_SETFL) failed";
877 if (socket_addr
->sa_family
== AF_INET
) {
878 /* We shouldn't be sending small packets and there's no application
879 * level ack of the data we send, so disable Nagle */
881 setsockopt(fr
->fd
, IPPROTO_TCP
, TCP_NODELAY
, (char *)&set
, sizeof(set
));
888 static int server_error(fcgi_request
*fr
)
890 #if defined(SIGPIPE) && MODULE_MAGIC_NUMBER < 19990320
891 /* Make sure we leave with Apache's sigpipe_handler in place */
892 if (fr
->apache_sigpipe_handler
!= NULL
)
893 signal(SIGPIPE
, fr
->apache_sigpipe_handler
);
895 close_connection_to_fs(fr
);
896 ap_kill_timeout(fr
->r
);
900 static void log_fcgi_server_stderr(void *data
)
902 const fcgi_request
* const fr
= (fcgi_request
*)data
;
907 if (fr
->fs_stderr_len
) {
908 ap_log_rerror(FCGI_LOG_ERR_NOERRNO
, fr
->r
,
909 "FastCGI: server \"%s\" stderr: %s", fr
->fs_path
, fr
->fs_stderr
);
913 /*----------------------------------------------------------------------
914 * This is the core routine for moving data between the FastCGI
915 * application and the Web server's client.
917 static int do_work(request_rec
*r
, fcgi_request
*fr
)
919 struct timeval timeOut
, dynamic_last_activity_time
;
920 fd_set read_set
, write_set
;
921 int status
= 0, idle_timeout
;
922 int numFDs
, dynamic_first_read
= fr
->dynamic
? 1 : 0;
924 int envSent
= FALSE
; /* has the complete ENV been buffered? */
925 char **envp
= NULL
; /* pointer used by fcgi_protocol_queue_env() */
927 const char *err
= NULL
;
932 fcgi_protocol_queue_begin_request(fr
);
934 /* Buffer as much of the environment as we can fit */
935 envSent
= fcgi_protocol_queue_env(r
, fr
, &envp
);
937 /* Start the Apache dropdead timer. See comments at top of file. */
938 ap_hard_timeout("buffering of FastCGI client data", r
);
940 /* Read as much as possible from the client. */
941 if (fr
->role
== FCGI_RESPONDER
) {
942 status
= ap_setup_client_block(r
, REQUEST_CHUNKED_ERROR
);
947 fr
->expectingClientContent
= (ap_should_client_block(r
) != 0);
949 if (read_from_client_n_queue(fr
) != OK
)
950 return server_error(fr
);
953 /* Connect to the FastCGI Application */
954 ap_hard_timeout("connect() to FastCGI server", r
);
955 if ((err
= open_connection_to_fs(fr
))) {
956 ap_log_rerror(FCGI_LOG_ERR
, r
,
957 "FastCGI: failed to connect to server \"%s\": %s", fr
->fs_path
, err
);
958 return server_error(fr
);
962 idle_timeout
= fr
->dynamic
? dynamic_idle_timeout
: fr
->fs
->idle_timeout
;
964 if (dynamic_first_read
) {
965 dynamic_last_activity_time
= fr
->startTime
;
967 if (dynamicAppConnectTimeout
) {
968 struct timeval qwait
;
969 timersub(&fr
->queueTime
, &fr
->startTime
, &qwait
);
970 dynamic_first_read
= qwait
.tv_sec
/ dynamicPleaseStartDelay
+ 1;
974 /* @@@ We never reset the timer in this loop, most folks don't mess w/
975 * Timeout directive which means we've got the 5 min default which is way
976 * to long to tie up a fs. We need a better/configurable solution that
978 ap_hard_timeout("FastCGI request processing", r
);
980 /* Register to get the script's stderr logged at the end of the request */
982 ap_register_cleanup(rp
, (void *)fr
, log_fcgi_server_stderr
, ap_null_cleanup
);
985 /* The socket is writeable, so get the first write out of the way */
986 if (fcgi_buf_get_to_fd(fr
->serverOutputBuffer
, fr
->fd
) < 0) {
987 ap_log_rerror(FCGI_LOG_ERR
, r
,
988 "FastCGI: comm with server \"%s\" aborted: write failed", fr
->fs_path
);
989 return server_error(fr
);
992 while (fr
->keepReadingFromFcgiApp
993 || BufferLength(fr
->serverInputBuffer
) > 0
994 || BufferLength(fr
->clientOutputBuffer
) > 0) {
996 /* If we didn't buffer all of the environment yet, buffer some more */
998 envSent
= fcgi_protocol_queue_env(r
, fr
, &envp
);
1000 /* Read as much as possible from the client. */
1001 if (fr
->role
== FCGI_RESPONDER
&& !fr
->eofSent
&& envSent
) {
1002 if (read_from_client_n_queue(fr
) != OK
)
1003 return server_error(fr
);
1006 /* To avoid deadlock, don't do a blocking select to write to
1007 * the FastCGI application without selecting to read from the
1008 * FastCGI application.
1010 doClientWrite
= FALSE
;
1011 if (fr
->keepReadingFromFcgiApp
&& BufferFree(fr
->serverInputBuffer
) > 0) {
1013 FD_SET(fr
->fd
, &read_set
);
1015 /* Is data buffered for output to the FastCGI server? */
1016 if (BufferLength(fr
->serverOutputBuffer
) > 0) {
1017 FD_SET(fr
->fd
, &write_set
);
1019 FD_CLR(fr
->fd
, &write_set
);
1022 * If there's data buffered to send to the client, don't
1023 * wait indefinitely for the FastCGI app; the app might
1024 * be doing server push.
1026 if (BufferLength(fr
->clientOutputBuffer
) > 0) {
1028 timeOut
.tv_usec
= 100000; /* 0.1 sec */
1030 else if (dynamic_first_read
) {
1032 struct timeval qwait
;
1034 if (gettimeofday(&fr
->queueTime
, NULL
) < 0) {
1035 ap_log_rerror(FCGI_LOG_ERR
, r
, "FastCGI: gettimeofday() failed");
1036 return server_error(fr
);
1039 /* Check for idle_timeout */
1041 dynamic_last_activity_time
= fr
->queueTime
;
1044 struct timeval idle_time
;
1045 timersub(&fr
->queueTime
, &dynamic_last_activity_time
, &idle_time
);
1046 if (idle_time
.tv_sec
> idle_timeout
) {
1047 send_to_pm(rp
, CONN_TIMEOUT
, fr
->fs_path
, fr
->user
, fr
->group
, 0, 0);
1048 ap_log_rerror(FCGI_LOG_ERR
, r
,
1049 "FastCGI: comm with (dynamic) server \"%s\" aborted: (first read) idle timeout (%d sec)",
1050 fr
->fs_path
, idle_timeout
);
1051 return server_error(fr
);
1055 timersub(&fr
->queueTime
, &fr
->startTime
, &qwait
);
1057 delay
= dynamic_first_read
* dynamicPleaseStartDelay
;
1058 if (qwait
.tv_sec
< delay
) {
1059 timeOut
.tv_sec
= delay
;
1060 timeOut
.tv_usec
= 100000; /* fudge for select() slop */
1061 timersub(&timeOut
, &qwait
, &timeOut
);
1064 /* Killed time somewhere.. client read? */
1065 send_to_pm(rp
, CONN_TIMEOUT
, fr
->fs_path
, fr
->user
, fr
->group
, 0, 0);
1066 dynamic_first_read
= qwait
.tv_sec
/ dynamicPleaseStartDelay
+ 1;
1067 timeOut
.tv_sec
= dynamic_first_read
* dynamicPleaseStartDelay
;
1068 timeOut
.tv_usec
= 100000; /* fudge for select() slop */
1069 timersub(&timeOut
, &qwait
, &timeOut
);
1073 timeOut
.tv_sec
= idle_timeout
;
1074 timeOut
.tv_usec
= 0;
1077 if ((status
= ap_select(numFDs
, &read_set
, &write_set
, NULL
, &timeOut
)) < 0) {
1078 ap_log_rerror(FCGI_LOG_ERR
, r
,
1079 "FastCGI: comm with server \"%s\" aborted: select() failed", fr
->fs_path
);
1080 return server_error(fr
);
1084 if (BufferLength(fr
->clientOutputBuffer
) > 0) {
1085 doClientWrite
= TRUE
;
1087 else if (dynamic_first_read
) {
1088 struct timeval qwait
;
1090 if (gettimeofday(&fr
->queueTime
, NULL
) < 0) {
1091 ap_log_rerror(FCGI_LOG_ERR
, r
, "FastCGI: gettimeofday() failed");
1092 return server_error(fr
);
1095 timersub(&fr
->queueTime
, &fr
->startTime
, &qwait
);
1097 send_to_pm(rp
, CONN_TIMEOUT
, fr
->fs_path
, fr
->user
, fr
->group
, 0, 0);
1099 dynamic_first_read
= qwait
.tv_sec
/ dynamicPleaseStartDelay
+ 1;
1102 ap_log_rerror(FCGI_LOG_ERR
, r
,
1103 "FastCGI: comm with server \"%s\" aborted: idle timeout (%d sec)",
1104 fr
->fs_path
, idle_timeout
);
1105 return server_error(fr
);
1109 #if defined(SIGPIPE) && MODULE_MAGIC_NUMBER < 19990320
1110 /* Disable Apache's SIGPIPE handler */
1111 fr
->apache_sigpipe_handler
= signal(SIGPIPE
, SIG_IGN
);
1114 /* Read from the FastCGI server */
1115 if (FD_ISSET(fr
->fd
, &read_set
)) {
1117 if (dynamic_first_read
) {
1118 dynamic_first_read
= 0;
1119 if (gettimeofday(&fr
->queueTime
, NULL
) < 0) {
1120 ap_log_rerror(FCGI_LOG_ERR
, r
, "FastCGI: gettimeofday() failed");
1121 return server_error(fr
);
1125 if ((status
= fcgi_buf_add_fd(fr
->serverInputBuffer
, fr
->fd
)) < 0) {
1126 ap_log_rerror(FCGI_LOG_ERR
, r
,
1127 "FastCGI: comm with server \"%s\" aborted: read failed", fr
->fs_path
);
1128 return server_error(fr
);
1132 fr
->keepReadingFromFcgiApp
= FALSE
;
1133 close_connection_to_fs(fr
);
1137 /* Write to the FastCGI server */
1138 if (FD_ISSET(fr
->fd
, &write_set
)) {
1139 if (fcgi_buf_get_to_fd(fr
->serverOutputBuffer
, fr
->fd
) < 0) {
1140 ap_log_rerror(FCGI_LOG_ERR
, r
,
1141 "FastCGI: comm with server \"%s\" aborted: write failed", fr
->fs_path
);
1142 return server_error(fr
);
1146 #if defined(SIGPIPE) && MODULE_MAGIC_NUMBER < 19990320
1147 /* Reinstall Apache's SIGPIPE handler */
1148 signal(SIGPIPE
, fr
->apache_sigpipe_handler
);
1152 doClientWrite
= TRUE
;
1155 if (fr
->role
== FCGI_RESPONDER
&& doClientWrite
) {
1156 if (write_to_client(fr
) != OK
) {
1157 #if defined(SIGPIPE) && MODULE_MAGIC_NUMBER < 19990320
1158 /* Make sure we leave with Apache's sigpipe_handler in place */
1159 if (fr
->apache_sigpipe_handler
!= NULL
)
1160 signal(SIGPIPE
, fr
->apache_sigpipe_handler
);
1162 close_connection_to_fs(fr
);
1163 ap_kill_timeout(fr
->r
);
1168 if (fcgi_protocol_dequeue(rp
, fr
) != OK
)
1169 return server_error(fr
);
1171 if (fr
->keepReadingFromFcgiApp
&& fr
->exitStatusSet
) {
1172 /* we're done talking to the fcgi app */
1173 fr
->keepReadingFromFcgiApp
= FALSE
;
1174 close_connection_to_fs(fr
);
1177 if (fr
->parseHeader
== SCAN_CGI_READING_HEADERS
) {
1178 if ((err
= process_headers(r
, fr
))) {
1179 ap_log_rerror(FCGI_LOG_ERR
, r
,
1180 "FastCGI: comm with server \"%s\" aborted: error parsing headers: %s", fr
->fs_path
, err
);
1181 return server_error(fr
);
1187 switch (fr
->parseHeader
) {
1189 case SCAN_CGI_FINISHED
:
1190 if (fr
->role
== FCGI_RESPONDER
) {
1191 #ifdef RUSSIAN_APACHE
1194 ap_bflush(r
->connection
->client
);
1196 ap_bgetopt(r
->connection
->client
, BO_BYTECT
, &r
->bytes_sent
);
1200 case SCAN_CGI_READING_HEADERS
:
1201 ap_log_rerror(FCGI_LOG_ERR
, r
,
1202 "FastCGI: incomplete headers (%d bytes) received from server \"%s\"",
1203 fr
->header
->nelts
, fr
->fs_path
);
1204 return server_error(fr
);
1206 case SCAN_CGI_BAD_HEADER
:
1207 return server_error(fr
);
1209 case SCAN_CGI_INT_REDIRECT
:
1210 case SCAN_CGI_SRV_REDIRECT
:
1212 * XXX We really should be soaking all client input
1213 * and all script output. See mod_cgi.c.
1214 * There's other differences we need to pick up here as well!
1215 * This has to be revisited.
1228 static fcgi_request
*create_fcgi_request(request_rec
* const r
, const char *fs_path
)
1230 struct stat
*my_finfo
;
1231 pool
* const p
= r
->pool
;
1233 fcgi_request
* const fr
= (fcgi_request
*)ap_pcalloc(p
, sizeof(fcgi_request
));
1236 my_finfo
= (struct stat
*)ap_palloc(p
, sizeof(struct stat
));
1237 if (stat(fs_path
, my_finfo
) < 0) {
1238 ap_log_rerror(FCGI_LOG_ERR
, r
, "FastCGI: stat() of \"%s\" failed", fs_path
);
1243 my_finfo
= &r
->finfo
;
1244 fs_path
= r
->filename
;
1247 fs
= fcgi_util_fs_get_by_id(fs_path
, r
->server
->server_uid
, r
->server
->server_gid
);
1249 /* Its a request for a dynamic FastCGI application */
1250 const char * const err
=
1251 fcgi_util_fs_is_path_ok(p
, fs_path
, my_finfo
, r
->server
->server_uid
, r
->server
->server_gid
);
1254 ap_log_rerror(FCGI_LOG_ERR_NOERRNO
, r
, "FastCGI: invalid (dynamic) server \"%s\": %s", fs_path
, err
);
1259 fr
->serverInputBuffer
= fcgi_buf_new(p
, SERVER_BUFSIZE
);
1260 fr
->serverOutputBuffer
= fcgi_buf_new(p
, SERVER_BUFSIZE
);
1261 fr
->clientInputBuffer
= fcgi_buf_new(p
, SERVER_BUFSIZE
);
1262 fr
->clientOutputBuffer
= fcgi_buf_new(p
, SERVER_BUFSIZE
);
1263 fr
->erBufPtr
= fcgi_buf_new(p
, sizeof(FCGI_EndRequestBody
) + 1);
1264 fr
->gotHeader
= FALSE
;
1265 fr
->parseHeader
= SCAN_CGI_READING_HEADERS
;
1266 fr
->header
= ap_make_array(p
, 1, 1);
1267 fr
->fs_stderr
= NULL
;
1269 fr
->readingEndRequestBody
= FALSE
;
1271 fr
->exitStatusSet
= FALSE
;
1272 fr
->requestId
= 1; /* anything but zero is OK here */
1273 fr
->eofSent
= FALSE
;
1275 fr
->role
= FCGI_RESPONDER
;
1276 fr
->expectingClientContent
= FALSE
;
1277 fr
->keepReadingFromFcgiApp
= TRUE
;
1279 fr
->fs_path
= fs_path
;
1280 fr
->authHeaders
= ap_make_table(p
, 10);
1281 fr
->dynamic
= (fs
== NULL
) ? TRUE
: FALSE
;
1283 set_uid_n_gid(r
, &fr
->user
, &fr
->group
);
1289 *----------------------------------------------------------------------
1293 * This routine gets called for a request that corresponds to
1294 * a FastCGI connection. It performs the request synchronously.
1297 * Final status of request: OK or NOT_FOUND or SERVER_ERROR.
1300 * Request performed.
1302 *----------------------------------------------------------------------
1305 /* Stolen from mod_cgi.c..
1306 * KLUDGE --- for back-combatibility, we don't have to check ExecCGI
1307 * in ScriptAliased directories, which means we need to know if this
1308 * request came through ScriptAlias or not... so the Alias module
1309 * leaves a note for us.
1311 static int apache_is_scriptaliased(request_rec
*r
)
1313 const char *t
= ap_table_get(r
->notes
, "alias-forced-type");
1314 return t
&& (!strcasecmp(t
, "cgi-script"));
1317 /* If a script wants to produce its own Redirect body, it now
1318 * has to explicitly *say* "Status: 302". If it wants to use
1319 * Apache redirects say "Status: 200". See process_headers().
1321 static int post_process_for_redirects(request_rec
* const r
,
1322 const fcgi_request
* const fr
)
1324 switch(fr
->parseHeader
) {
1325 case SCAN_CGI_INT_REDIRECT
:
1327 /* @@@ There are still differences between the handling in
1328 * mod_cgi and mod_fastcgi. This needs to be revisited.
1330 /* We already read the message body (if any), so don't allow
1331 * the redirected request to think it has one. We can ignore
1332 * Transfer-Encoding, since we used REQUEST_CHUNKED_ERROR.
1335 r
->method_number
= M_GET
;
1336 ap_table_unset(r
->headers_in
, "Content-length");
1338 ap_internal_redirect_handler(ap_table_get(r
->headers_out
, "Location"), r
);
1341 case SCAN_CGI_SRV_REDIRECT
:
1349 /******************************************************************************
1350 * Process fastcgi-script requests. Based on mod_cgi::cgi_handler().
1352 static int content_handler(request_rec
*r
)
1354 fcgi_request
*fr
= NULL
;
1357 /* Setup a new FastCGI request */
1358 if ((fr
= create_fcgi_request(r
, NULL
)) == NULL
)
1359 return SERVER_ERROR
;
1361 /* If its a dynamic invocation, make sure scripts are OK here */
1362 if (fr
->dynamic
&& !(ap_allow_options(r
) & OPT_EXECCGI
) && !apache_is_scriptaliased(r
)) {
1363 ap_log_rerror(FCGI_LOG_ERR_NOERRNO
, r
,
1364 "FastCGI: \"ExecCGI Option\" is off in this directory: %s", r
->uri
);
1365 return SERVER_ERROR
;
1368 /* Process the fastcgi-script request */
1369 if ((ret
= do_work(r
, fr
)) != OK
)
1372 /* Special case redirects */
1373 return post_process_for_redirects(r
, fr
);
1377 static int post_process_auth_passed_header(table
*t
, const char *key
, const char * const val
)
1379 if (strncasecmp(key
, "Variable-", 9) == 0)
1382 ap_table_setn(t
, key
, val
);
1386 static int post_process_auth_passed_compat_header(table
*t
, const char *key
, const char * const val
)
1388 if (strncasecmp(key
, "Variable-", 9) == 0)
1389 ap_table_setn(t
, key
+ 9, val
);
1394 static int post_process_auth_failed_header(table
* const t
, const char * const key
, const char * const val
)
1396 ap_table_setn(t
, key
, val
);
1400 static void post_process_auth(fcgi_request
* const fr
, const int passed
)
1402 request_rec
* const r
= fr
->r
;
1404 /* Restore the saved subprocess_env because we muddied ours up */
1405 r
->subprocess_env
= fr
->saved_subprocess_env
;
1408 if (fr
->auth_compat
) {
1409 ap_table_do((int (*)(void *, const char *, const char *))post_process_auth_passed_compat_header
,
1410 (void *)r
->subprocess_env
, fr
->authHeaders
, NULL
);
1413 ap_table_do((int (*)(void *, const char *, const char *))post_process_auth_passed_header
,
1414 (void *)r
->subprocess_env
, fr
->authHeaders
, NULL
);
1418 ap_table_do((int (*)(void *, const char *, const char *))post_process_auth_failed_header
,
1419 (void *)r
->err_headers_out
, fr
->authHeaders
, NULL
);
1422 /* @@@ Restore these.. its a hack until I rewrite the header handling */
1423 r
->status
= HTTP_OK
;
1424 r
->status_line
= NULL
;
1427 static int check_user_authentication(request_rec
*r
)
1429 int res
, authenticated
= 0;
1430 const char *password
;
1432 const fcgi_dir_config
* const dir_config
=
1433 (const fcgi_dir_config
*)ap_get_module_config(r
->per_dir_config
, &fastcgi_module
);
1435 if (dir_config
->authenticator
== NULL
)
1438 /* Get the user password */
1439 if ((res
= ap_get_basic_auth_pw(r
, &password
)) != OK
)
1442 if ((fr
= create_fcgi_request(r
, dir_config
->authenticator
)) == NULL
)
1443 return SERVER_ERROR
;
1445 /* Save the existing subprocess_env, because we're gonna muddy it up */
1446 fr
->saved_subprocess_env
= ap_copy_table(r
->pool
, r
->subprocess_env
);
1448 ap_table_setn(r
->subprocess_env
, "REMOTE_PASSWD", password
);
1449 ap_table_setn(r
->subprocess_env
, "FCGI_APACHE_ROLE", "AUTHENTICATOR");
1451 /* The FastCGI Protocol doesn't differentiate authentication */
1452 fr
->role
= FCGI_AUTHORIZER
;
1454 /* Do we need compatibility mode? */
1455 fr
->auth_compat
= (dir_config
->authenticator_options
& FCGI_COMPAT
);
1457 if ((res
= do_work(r
, fr
)) != OK
)
1458 goto AuthenticationFailed
;
1460 authenticated
= (r
->status
== 200);
1461 post_process_auth(fr
, authenticated
);
1463 /* A redirect shouldn't be allowed during the authentication phase */
1464 if (ap_table_get(r
->headers_out
, "Location") != NULL
) {
1465 ap_log_rerror(FCGI_LOG_ERR_NOERRNO
, r
,
1466 "FastCGI: FastCgiAuthenticator \"%s\" redirected (not allowed)",
1467 dir_config
->authenticator
);
1468 goto AuthenticationFailed
;
1474 AuthenticationFailed
:
1475 if (!(dir_config
->authenticator_options
& FCGI_AUTHORITATIVE
))
1478 /* @@@ Probably should support custom_responses */
1479 ap_note_basic_auth_failure(r
);
1480 ap_log_rerror(FCGI_LOG_ERR_NOERRNO
, r
,
1481 "FastCGI: authentication failed for user \"%s\": %s", r
->connection
->user
, r
->uri
);
1482 return (res
== OK
) ? AUTH_REQUIRED
: res
;
1485 static int check_user_authorization(request_rec
*r
)
1487 int res
, authorized
= 0;
1489 const fcgi_dir_config
* const dir_config
=
1490 (const fcgi_dir_config
*)ap_get_module_config(r
->per_dir_config
, &fastcgi_module
);
1492 if (dir_config
->authorizer
== NULL
)
1495 /* @@@ We should probably honor the existing parameters to the require directive
1496 * as well as allow the definition of new ones (or use the basename of the
1497 * FastCGI server and pass the rest of the directive line), but for now keep
1500 if ((fr
= create_fcgi_request(r
, dir_config
->authorizer
)) == NULL
)
1501 return SERVER_ERROR
;
1503 /* Save the existing subprocess_env, because we're gonna muddy it up */
1504 fr
->saved_subprocess_env
= ap_copy_table(r
->pool
, r
->subprocess_env
);
1506 ap_table_setn(r
->subprocess_env
, "FCGI_APACHE_ROLE", "AUTHORIZER");
1508 fr
->role
= FCGI_AUTHORIZER
;
1510 /* Do we need compatibility mode? */
1511 fr
->auth_compat
= (dir_config
->authenticator_options
& FCGI_COMPAT
);
1513 if ((res
= do_work(r
, fr
)) != OK
)
1514 goto AuthorizationFailed
;
1516 authorized
= (r
->status
== 200);
1517 post_process_auth(fr
, authorized
);
1519 /* A redirect shouldn't be allowed during the authorization phase */
1520 if (ap_table_get(r
->headers_out
, "Location") != NULL
) {
1521 ap_log_rerror(FCGI_LOG_ERR_NOERRNO
, r
,
1522 "FastCGI: FastCgiAuthorizer \"%s\" redirected (not allowed)",
1523 dir_config
->authorizer
);
1524 goto AuthorizationFailed
;
1530 AuthorizationFailed
:
1531 if (!(dir_config
->authorizer_options
& FCGI_AUTHORITATIVE
))
1534 /* @@@ Probably should support custom_responses */
1535 ap_note_basic_auth_failure(r
);
1536 ap_log_rerror(FCGI_LOG_ERR_NOERRNO
, r
,
1537 "FastCGI: authorization failed for user \"%s\": %s", r
->connection
->user
, r
->uri
);
1538 return (res
== OK
) ? AUTH_REQUIRED
: res
;
1541 static int check_access(request_rec
*r
)
1543 int res
, access_allowed
= 0;
1545 const fcgi_dir_config
* const dir_config
=
1546 (fcgi_dir_config
*)ap_get_module_config(r
->per_dir_config
, &fastcgi_module
);
1548 if (dir_config
== NULL
|| dir_config
->access_checker
== NULL
)
1551 if ((fr
= create_fcgi_request(r
, dir_config
->access_checker
)) == NULL
)
1552 return SERVER_ERROR
;
1554 /* Save the existing subprocess_env, because we're gonna muddy it up */
1555 fr
->saved_subprocess_env
= ap_copy_table(r
->pool
, r
->subprocess_env
);
1557 ap_table_setn(r
->subprocess_env
, "FCGI_APACHE_ROLE", "ACCESS_CHECKER");
1559 /* The FastCGI Protocol doesn't differentiate access control */
1560 fr
->role
= FCGI_AUTHORIZER
;
1562 /* Do we need compatibility mode? */
1563 fr
->auth_compat
= (dir_config
->authenticator_options
& FCGI_COMPAT
);
1565 if ((res
= do_work(r
, fr
)) != OK
)
1568 access_allowed
= (r
->status
== 200);
1569 post_process_auth(fr
, access_allowed
);
1571 /* A redirect shouldn't be allowed during the access check phase */
1572 if (ap_table_get(r
->headers_out
, "Location") != NULL
) {
1573 ap_log_rerror(FCGI_LOG_ERR_NOERRNO
, r
,
1574 "FastCGI: FastCgiAccessChecker \"%s\" redirected (not allowed)",
1575 dir_config
->access_checker
);
1583 if (!(dir_config
->access_checker_options
& FCGI_AUTHORITATIVE
))
1586 /* @@@ Probably should support custom_responses */
1587 ap_log_rerror(FCGI_LOG_ERR_NOERRNO
, r
, "FastCGI: access denied: %s", r
->uri
);
1588 return (res
== OK
) ? FORBIDDEN
: res
;
1593 command_rec fastcgi_cmds
[] = {
1594 { "AppClass", fcgi_config_new_static_server
, NULL
, RSRC_CONF
, RAW_ARGS
, NULL
},
1595 { "FastCgiServer", fcgi_config_new_static_server
, NULL
, RSRC_CONF
, RAW_ARGS
, NULL
},
1597 { "ExternalAppClass", fcgi_config_new_external_server
, NULL
, RSRC_CONF
, RAW_ARGS
, NULL
},
1598 { "FastCgiExternalServer", fcgi_config_new_external_server
, NULL
, RSRC_CONF
, RAW_ARGS
, NULL
},
1600 { "FastCgiIpcDir", fcgi_config_set_socket_dir
, NULL
, RSRC_CONF
, TAKE1
, NULL
},
1602 { "FastCgiSuexec", fcgi_config_set_suexec
, NULL
, RSRC_CONF
, TAKE1
, NULL
},
1604 { "FCGIConfig", fcgi_config_set_config
, NULL
, RSRC_CONF
, RAW_ARGS
, NULL
},
1605 { "FastCgiConfig", fcgi_config_set_config
, NULL
, RSRC_CONF
, RAW_ARGS
, NULL
},
1607 { "FastCgiAuthenticator", fcgi_config_new_auth_server
,
1608 (void *)FCGI_AUTH_TYPE_AUTHENTICATOR
, ACCESS_CONF
, TAKE12
,
1609 "a fastcgi-script path (absolute or relative to ServerRoot) followed by an optional -compat" },
1610 { "FastCgiAuthenticatorAuthoritative", fcgi_config_set_authoritative_slot
,
1611 (void *)XtOffsetOf(fcgi_dir_config
, authenticator_options
), ACCESS_CONF
, FLAG
,
1612 "Set to 'off' to allow authentication to be passed along to lower modules upon failure" },
1614 { "FastCgiAuthorizer", fcgi_config_new_auth_server
,
1615 (void *)FCGI_AUTH_TYPE_AUTHORIZER
, ACCESS_CONF
, TAKE12
,
1616 "a fastcgi-script path (absolute or relative to ServerRoot) followed by an optional -compat" },
1617 { "FastCgiAuthorizerAuthoritative", fcgi_config_set_authoritative_slot
,
1618 (void *)XtOffsetOf(fcgi_dir_config
, authorizer_options
), ACCESS_CONF
, FLAG
,
1619 "Set to 'off' to allow authorization to be passed along to lower modules upon failure" },
1621 { "FastCgiAccessChecker", fcgi_config_new_auth_server
,
1622 (void *)FCGI_AUTH_TYPE_ACCESS_CHECKER
, ACCESS_CONF
, TAKE12
,
1623 "a fastcgi-script path (absolute or relative to ServerRoot) followed by an optional -compat" },
1624 { "FastCgiAccessCheckerAuthoritative", fcgi_config_set_authoritative_slot
,
1625 (void *)XtOffsetOf(fcgi_dir_config
, access_checker_options
), ACCESS_CONF
, FLAG
,
1626 "Set to 'off' to allow access control to be passed along to lower modules upon failure" },
1631 handler_rec fastcgi_handlers
[] = {
1632 { FCGI_MAGIC_TYPE
, content_handler
},
1633 { "fastcgi-script", content_handler
},
1638 module MODULE_VAR_EXPORT fastcgi_module
= {
1639 STANDARD_MODULE_STUFF
,
1640 init_module
, /* initializer */
1641 fcgi_config_create_dir_config
, /* per-dir config creator */
1642 NULL
, /* per-dir config merger (default: override) */
1643 NULL
, /* per-server config creator */
1644 NULL
, /* per-server config merger (default: override) */
1645 fastcgi_cmds
, /* command table */
1646 fastcgi_handlers
, /* [9] content handlers */
1647 NULL
, /* [2] URI-to-filename translation */
1648 check_user_authentication
, /* [5] authenticate user_id */
1649 check_user_authorization
, /* [6] authorize user_id */
1650 check_access
, /* [4] check access (based on src & http headers) */
1651 NULL
, /* [7] check/set MIME type */
1652 NULL
, /* [8] fixups */
1653 NULL
, /* [10] logger */
1654 NULL
, /* [3] header-parser */
1655 NULL
, /* process initialization */
1656 NULL
, /* process exit/cleanup */
1657 NULL
/* [1] post read-request handling */