2 * $Id: fcgi_protocol.c,v 1.17 2000/04/27 19:53:54 robs Exp $
7 #include "fcgi_protocol.h"
9 /*******************************************************************************
10 * Build and queue a FastCGI message header. It is the caller's
11 * responsibility to make sure that there's enough space in the buffer, and
12 * that the data bytes (specified by 'len') are queued immediately following
15 static void queue_header(fcgi_request
*fr
, unsigned char type
, unsigned int len
)
19 ap_assert(type
> 0 && type
<= FCGI_MAXTYPE
);
20 ap_assert(len
>= 0 && len
<= 0xffff);
21 ap_assert(BufferFree(fr
->serverOutputBuffer
) > sizeof(FCGI_Header
));
23 /* Assemble and queue the packet header. */
24 header
.version
= FCGI_VERSION
;
26 header
.requestIdB1
= (unsigned char) (fr
->requestId
>> 8);
27 header
.requestIdB0
= (unsigned char) fr
->requestId
;
28 header
.contentLengthB1
= (unsigned char) (len
/ 256); /* MSB */
29 header
.contentLengthB0
= (unsigned char) (len
% 256); /* LSB */
30 header
.paddingLength
= 0;
32 fcgi_buf_add_block(fr
->serverOutputBuffer
, (char *) &header
, sizeof(FCGI_Header
));
35 /*******************************************************************************
36 * Build a FCGI_BeginRequest message body.
38 static void build_begin_request(unsigned int role
, unsigned char keepConnection
,
39 FCGI_BeginRequestBody
*body
)
41 ap_assert((role
>> 16) == 0);
42 body
->roleB1
= (unsigned char) (role
>> 8);
43 body
->roleB0
= (unsigned char) role
;
44 body
->flags
= (unsigned char) ((keepConnection
) ? FCGI_KEEP_CONN
: 0);
45 memset(body
->reserved
, 0, sizeof(body
->reserved
));
48 /*******************************************************************************
49 * Build and queue a FastCGI "Begin Request" message.
51 void fcgi_protocol_queue_begin_request(fcgi_request
*fr
)
53 FCGI_BeginRequestBody body
;
54 int bodySize
= sizeof(FCGI_BeginRequestBody
);
56 /* We should be the first ones to use this buffer */
57 ap_assert(BufferLength(fr
->serverOutputBuffer
) == 0);
59 build_begin_request(fr
->role
, FALSE
, &body
);
60 queue_header(fr
, FCGI_BEGIN_REQUEST
, bodySize
);
61 fcgi_buf_add_block(fr
->serverOutputBuffer
, (char *) &body
, bodySize
);
64 /*******************************************************************************
65 * Build a FastCGI name-value pair (env) header.
67 static void build_env_header(int nameLen
, int valueLen
,
68 unsigned char *headerBuffPtr
, int *headerLenPtr
)
70 unsigned char *startHeaderBuffPtr
= headerBuffPtr
;
72 ap_assert(nameLen
>= 0);
75 *headerBuffPtr
++ = (unsigned char) nameLen
;
77 *headerBuffPtr
++ = (unsigned char) ((nameLen
>> 24) | 0x80);
78 *headerBuffPtr
++ = (unsigned char) (nameLen
>> 16);
79 *headerBuffPtr
++ = (unsigned char) (nameLen
>> 8);
80 *headerBuffPtr
++ = (unsigned char) nameLen
;
83 ap_assert(valueLen
>= 0);
85 if (valueLen
< 0x80) {
86 *headerBuffPtr
++ = (unsigned char) valueLen
;
88 *headerBuffPtr
++ = (unsigned char) ((valueLen
>> 24) | 0x80);
89 *headerBuffPtr
++ = (unsigned char) (valueLen
>> 16);
90 *headerBuffPtr
++ = (unsigned char) (valueLen
>> 8);
91 *headerBuffPtr
++ = (unsigned char) valueLen
;
93 *headerLenPtr
= headerBuffPtr
- startHeaderBuffPtr
;
96 /* A static fn stolen from Apache's util_script.c...
97 * Obtain the Request-URI from the original request-line, returning
98 * a new string from the request pool containing the URI or "".
100 static char *apache_original_uri(request_rec
*r
)
104 if (r
->the_request
== NULL
)
105 return (char *) ap_pcalloc(r
->pool
, 1);
107 first
= r
->the_request
; /* use the request-line */
109 while (*first
&& !ap_isspace(*first
))
110 ++first
; /* skip over the method */
112 while (ap_isspace(*first
))
113 ++first
; /* and the space(s) */
116 while (*last
&& !ap_isspace(*last
))
117 ++last
; /* end at next whitespace */
119 return ap_pstrndup(r
->pool
, first
, last
- first
);
122 /* Based on Apache's ap_add_cgi_vars() in util_script.c.
123 * Apache's spins in sub_req_lookup_uri() trying to setup PATH_TRANSLATED,
124 * so we just don't do that part.
126 static void add_auth_cgi_vars(request_rec
*r
, const int compat
)
128 table
*e
= r
->subprocess_env
;
130 ap_table_setn(e
, "GATEWAY_INTERFACE", "CGI/1.1");
131 ap_table_setn(e
, "SERVER_PROTOCOL", r
->protocol
);
132 ap_table_setn(e
, "REQUEST_METHOD", r
->method
);
133 ap_table_setn(e
, "QUERY_STRING", r
->args
? r
->args
: "");
134 ap_table_setn(e
, "REQUEST_URI", apache_original_uri(r
));
136 /* The FastCGI spec precludes sending of CONTENT_LENGTH, PATH_INFO,
137 * PATH_TRANSLATED, and SCRIPT_NAME (for some reason?). PATH_TRANSLATED we
138 * don't have, its the variable that causes Apache to break trying to set
139 * up (and thus the reason this fn exists vs. using ap_add_cgi_vars()). */
141 ap_table_unset(e
, "CONTENT_LENGTH");
145 /* Note that the code below special-cases scripts run from includes,
146 * because it "knows" that the sub_request has been hacked to have the
147 * args and path_info of the original request, and not any that may have
148 * come with the script URI in the include command. Ugh. */
149 if (!strcmp(r
->protocol
, "INCLUDED")) {
150 ap_table_setn(e
, "SCRIPT_NAME", r
->uri
);
151 if (r
->path_info
&& *r
->path_info
)
152 ap_table_setn(e
, "PATH_INFO", r
->path_info
);
154 else if (!r
->path_info
|| !*r
->path_info
)
155 ap_table_setn(e
, "SCRIPT_NAME", r
->uri
);
157 int path_info_start
= ap_find_path_info(r
->uri
, r
->path_info
);
159 ap_table_setn(e
, "SCRIPT_NAME", ap_pstrndup(r
->pool
, r
->uri
, path_info_start
));
160 ap_table_setn(e
, "PATH_INFO", r
->path_info
);
164 static void add_pass_header_vars(fcgi_request
*fr
)
166 const array_header
*ph
= fr
->dynamic
? dynamic_pass_headers
: fr
->fs
->pass_headers
;
169 const char **elt
= (const char **)ph
->elts
;
172 for ( ; i
; --i
, ++elt
) {
173 const char *val
= ap_table_get(fr
->r
->headers_in
, *elt
);
175 ap_table_setn(fr
->r
->subprocess_env
, *elt
, val
);
181 /*******************************************************************************
182 * Build and queue the environment name-value pairs. Returns TRUE if the
183 * complete ENV was buffered, FALSE otherwise. Note: envp is updated to
184 * reflect the current position in the ENV.
186 int fcgi_protocol_queue_env(request_rec
*r
, fcgi_request
*fr
, env_status
*env
)
190 if (env
->envp
== NULL
) {
191 ap_add_common_vars(r
);
192 add_pass_header_vars(fr
);
194 if (fr
->role
== FCGI_RESPONDER
)
197 add_auth_cgi_vars(r
, fr
->auth_compat
);
199 env
->envp
= ap_create_environment(r
->pool
, r
->subprocess_env
);
207 env
->equalPtr
= strchr(*env
->envp
, '=');
208 ap_assert(env
->equalPtr
!= NULL
);
209 env
->nameLen
= env
->equalPtr
- *env
->envp
;
210 env
->valueLen
= strlen(++env
->equalPtr
);
211 build_env_header(env
->nameLen
, env
->valueLen
, env
->headerBuff
, &env
->headerLen
);
212 env
->totalLen
= env
->headerLen
+ env
->nameLen
+ env
->valueLen
;
217 if (BufferFree(fr
->serverOutputBuffer
) < (int)(sizeof(FCGI_Header
) + env
->headerLen
)) {
220 queue_header(fr
, FCGI_PARAMS
, env
->totalLen
);
221 fcgi_buf_add_block(fr
->serverOutputBuffer
, (char *)env
->headerBuff
, env
->headerLen
);
226 charCount
= fcgi_buf_add_block(fr
->serverOutputBuffer
, *env
->envp
, env
->nameLen
);
227 if (charCount
!= env
->nameLen
) {
228 *env
->envp
+= charCount
;
229 env
->nameLen
-= charCount
;
236 charCount
= fcgi_buf_add_block(fr
->serverOutputBuffer
, env
->equalPtr
, env
->valueLen
);
237 if (charCount
!= env
->valueLen
) {
238 env
->equalPtr
+= charCount
;
239 env
->valueLen
-= charCount
;
247 if (BufferFree(fr
->serverOutputBuffer
) < sizeof(FCGI_Header
)) {
250 queue_header(fr
, FCGI_PARAMS
, 0);
254 /*******************************************************************************
255 * Queue data from the client input buffer to the FastCGI server output
256 * buffer (encapsulating the data in FastCGI protocol messages).
258 void fcgi_protocol_queue_client_buffer(fcgi_request
*fr
)
261 int in_len
, out_free
;
267 * If there's some client data and room for at least one byte
268 * of data in the output buffer (after protocol overhead), then
269 * move some data to the output buffer.
271 in_len
= BufferLength(fr
->clientInputBuffer
);
272 out_free
= max(0, BufferFree(fr
->serverOutputBuffer
) - sizeof(FCGI_Header
));
273 movelen
= min(in_len
, out_free
);
275 queue_header(fr
, FCGI_STDIN
, movelen
);
276 fcgi_buf_get_to_buf(fr
->serverOutputBuffer
, fr
->clientInputBuffer
, movelen
);
280 * If all the client data has been sent, and there's room
281 * in the output buffer, indicate EOF.
283 if (movelen
== in_len
&& fr
->expectingClientContent
<= 0
284 && BufferFree(fr
->serverOutputBuffer
) >= sizeof(FCGI_Header
))
286 queue_header(fr
, FCGI_STDIN
, 0);
291 /*******************************************************************************
292 * Read FastCGI protocol messages from the FastCGI server input buffer into
293 * fr->header when parsing headers, to fr->fs_stderr when reading stderr data,
294 * or to the client output buffer otherwises.
296 int fcgi_protocol_dequeue(pool
*p
, fcgi_request
*fr
)
301 while (BufferLength(fr
->serverInputBuffer
) > 0) {
303 * State #1: looking for the next complete packet header.
305 if (fr
->gotHeader
== FALSE
) {
306 if (BufferLength(fr
->serverInputBuffer
) < sizeof(FCGI_Header
)) {
309 fcgi_buf_get_to_block(fr
->serverInputBuffer
, (char *) &header
,
310 sizeof(FCGI_Header
));
312 * XXX: Better handling of packets with other version numbers
313 * and other packet problems.
315 if (header
.version
!= FCGI_VERSION
) {
316 ap_log_rerror(FCGI_LOG_ERR_NOERRNO
, fr
->r
,
317 "FastCGI: comm with server \"%s\" aborted: protocol error: invalid version: %d != FCGI_VERSION(%d)",
318 fr
->fs_path
, header
.version
, FCGI_VERSION
);
321 if (header
.type
> FCGI_MAXTYPE
) {
322 ap_log_rerror(FCGI_LOG_ERR_NOERRNO
, fr
->r
,
323 "FastCGI: comm with server \"%s\" aborted: protocol error: invalid type: %d > FCGI_MAXTYPE(%d)",
324 fr
->fs_path
, header
.type
, FCGI_MAXTYPE
);
328 fr
->packetType
= header
.type
;
329 fr
->dataLen
= (header
.contentLengthB1
<< 8)
330 + header
.contentLengthB0
;
331 fr
->gotHeader
= TRUE
;
332 fr
->paddingLen
= header
.paddingLength
;
336 * State #2: got a header, and processing packet bytes.
338 len
= min(fr
->dataLen
, BufferLength(fr
->serverInputBuffer
));
340 switch (fr
->packetType
) {
343 switch(fr
->parseHeader
) {
344 case SCAN_CGI_READING_HEADERS
:
345 fcgi_buf_get_to_array(fr
->serverInputBuffer
, fr
->header
, len
);
347 case SCAN_CGI_FINISHED
:
348 len
= min(BufferFree(fr
->clientOutputBuffer
), len
);
350 fcgi_buf_get_to_buf(fr
->clientOutputBuffer
, fr
->serverInputBuffer
, len
);
356 /* Toss data on the floor */
365 if (fr
->fs_stderr
== NULL
)
367 fr
->fs_stderr
= ap_palloc(p
, FCGI_SERVER_MAX_STDERR_LINE_LEN
+ 1);
370 /* We're gonna consume all thats here */
375 char *null
, *end
, *start
= fr
->fs_stderr
;
377 /* Get as much as will fit in the buffer */
378 int get_len
= min(len
, FCGI_SERVER_MAX_STDERR_LINE_LEN
- fr
->fs_stderr_len
);
379 fcgi_buf_get_to_block(fr
->serverInputBuffer
, start
+ fr
->fs_stderr_len
, get_len
);
381 fr
->fs_stderr_len
+= get_len
;
382 *(start
+ fr
->fs_stderr_len
) = '\0';
384 /* Disallow nulls, we could be nicer but this is the motivator */
385 while ((null
= memchr(start
, '\0', fr
->fs_stderr_len
)))
387 int discard
= ++null
- start
;
388 ap_log_rerror(FCGI_LOG_ERR_NOERRNO
, fr
->r
,
389 "FastCGI: server \"%s\" sent a null character in the stderr stream!?, "
390 "discarding %d characters of stderr", fr
->fs_path
, discard
);
392 fr
->fs_stderr_len
-= discard
;
395 /* Print as much as possible */
396 while ((end
= strpbrk(start
, "\r\n")))
401 ap_log_rerror(FCGI_LOG_ERR_NOERRNO
, fr
->r
, "FastCGI: server \"%s\" stderr: %s", fr
->fs_path
, start
);
403 end
+= strspn(++end
, "\r\n");
404 fr
->fs_stderr_len
-= (end
- start
);
408 if (fr
->fs_stderr_len
)
410 if (start
!= fr
->fs_stderr
)
412 /* Move leftovers down */
413 memmove(fr
->fs_stderr
, start
, fr
->fs_stderr_len
);
415 else if (fr
->fs_stderr_len
== FCGI_SERVER_MAX_STDERR_LINE_LEN
)
417 /* Full buffer, dump it and complain */
418 ap_log_rerror(FCGI_LOG_ERR_NOERRNO
, fr
->r
, "FastCGI: server \"%s\" stderr: %s", fr
->fs_path
, fr
->fs_stderr
);
419 ap_log_rerror(FCGI_LOG_WARN_NOERRNO
, fr
->r
,
420 "FastCGI: too much stderr received from server \"%s\", "
421 "increase FCGI_SERVER_MAX_STDERR_LINE_LEN (%d) and rebuild "
422 "or use \"\\n\" to terminate lines",
423 fr
->fs_path
, FCGI_SERVER_MAX_STDERR_LINE_LEN
);
424 fr
->fs_stderr_len
= 0;
430 case FCGI_END_REQUEST
:
431 if (!fr
->readingEndRequestBody
) {
432 if (fr
->dataLen
!= sizeof(FCGI_EndRequestBody
)) {
433 ap_log_rerror(FCGI_LOG_ERR_NOERRNO
, fr
->r
,
434 "FastCGI: comm with server \"%s\" aborted: protocol error: invalid FCGI_END_REQUEST size: "
435 "%d != sizeof(FCGI_EndRequestBody)(%d)",
436 fr
->fs_path
, fr
->dataLen
, sizeof(FCGI_EndRequestBody
));
439 fr
->readingEndRequestBody
= TRUE
;
442 fcgi_buf_get_to_buf(fr
->erBufPtr
, fr
->serverInputBuffer
, len
);
445 if (fr
->dataLen
== 0) {
446 FCGI_EndRequestBody
*erBody
= &fr
->endRequestBody
;
447 fcgi_buf_get_to_block(
448 fr
->erBufPtr
, (char *) &fr
->endRequestBody
,
449 sizeof(FCGI_EndRequestBody
));
450 if (erBody
->protocolStatus
!= FCGI_REQUEST_COMPLETE
) {
452 * XXX: What to do with FCGI_OVERLOADED?
454 ap_log_rerror(FCGI_LOG_ERR_NOERRNO
, fr
->r
,
455 "FastCGI: comm with server \"%s\" aborted: protocol error: invalid FCGI_END_REQUEST status: "
456 "%d != FCGI_REQUEST_COMPLETE(%d)", fr
->fs_path
,
457 erBody
->protocolStatus
, FCGI_REQUEST_COMPLETE
);
460 fr
->exitStatus
= (erBody
->appStatusB3
<< 24)
461 + (erBody
->appStatusB2
<< 16)
462 + (erBody
->appStatusB1
<< 8)
463 + (erBody
->appStatusB0
);
464 fr
->exitStatusSet
= TRUE
;
465 fr
->readingEndRequestBody
= FALSE
;
468 case FCGI_GET_VALUES_RESULT
:
469 /* XXX coming soon */
470 case FCGI_UNKNOWN_TYPE
:
471 /* XXX coming soon */
474 * XXX Ignore unknown packet types from the FastCGI server.
477 fcgi_buf_toss(fr
->serverInputBuffer
, len
);
483 * Discard padding, then start looking for
486 if (fr
->dataLen
== 0) {
487 if (fr
->paddingLen
> 0) {
488 len
= min(fr
->paddingLen
,
489 BufferLength(fr
->serverInputBuffer
));
490 fcgi_buf_toss(fr
->serverInputBuffer
, len
);
491 fr
->paddingLen
-= len
;
493 if (fr
->paddingLen
== 0) {
494 fr
->gotHeader
= FALSE
;