Add discussion of signals.
[mod_fastcgi.git] / fcgi_protocol.c
blob73bc4fd53566c75115e1495dcca9f4206e952417
1 /*
2 * $Id: fcgi_protocol.c,v 1.20 2001/11/09 21:49:15 robs Exp $
3 */
6 #include "fcgi.h"
7 #include "fcgi_protocol.h"
9 #ifdef WIN32
10 #pragma warning( disable : 4706)
11 #endif
13 /*******************************************************************************
14 * Build and queue a FastCGI message header. It is the caller's
15 * responsibility to make sure that there's enough space in the buffer, and
16 * that the data bytes (specified by 'len') are queued immediately following
17 * this header.
19 static void queue_header(fcgi_request *fr, unsigned char type, unsigned int len)
21 FCGI_Header header;
23 ap_assert(type > 0);
24 ap_assert(type <= FCGI_MAXTYPE);
25 ap_assert(len >= 0);
26 ap_assert(len <= 0xffff);
27 ap_assert(BufferFree(fr->serverOutputBuffer) >= sizeof(FCGI_Header));
29 /* Assemble and queue the packet header. */
30 header.version = FCGI_VERSION;
31 header.type = type;
32 header.requestIdB1 = (unsigned char) (fr->requestId >> 8);
33 header.requestIdB0 = (unsigned char) fr->requestId;
34 header.contentLengthB1 = (unsigned char) (len / 256); /* MSB */
35 header.contentLengthB0 = (unsigned char) (len % 256); /* LSB */
36 header.paddingLength = 0;
37 header.reserved = 0;
38 fcgi_buf_add_block(fr->serverOutputBuffer, (char *) &header, sizeof(FCGI_Header));
41 /*******************************************************************************
42 * Build a FCGI_BeginRequest message body.
44 static void build_begin_request(unsigned int role, unsigned char keepConnection,
45 FCGI_BeginRequestBody *body)
47 ap_assert((role >> 16) == 0);
48 body->roleB1 = (unsigned char) (role >> 8);
49 body->roleB0 = (unsigned char) role;
50 body->flags = (unsigned char) ((keepConnection) ? FCGI_KEEP_CONN : 0);
51 memset(body->reserved, 0, sizeof(body->reserved));
54 /*******************************************************************************
55 * Build and queue a FastCGI "Begin Request" message.
57 void fcgi_protocol_queue_begin_request(fcgi_request *fr)
59 FCGI_BeginRequestBody body;
60 int bodySize = sizeof(FCGI_BeginRequestBody);
62 /* We should be the first ones to use this buffer */
63 ap_assert(BufferLength(fr->serverOutputBuffer) == 0);
65 build_begin_request(fr->role, FALSE, &body);
66 queue_header(fr, FCGI_BEGIN_REQUEST, bodySize);
67 fcgi_buf_add_block(fr->serverOutputBuffer, (char *) &body, bodySize);
70 /*******************************************************************************
71 * Build a FastCGI name-value pair (env) header.
73 static void build_env_header(int nameLen, int valueLen,
74 unsigned char *headerBuffPtr, int *headerLenPtr)
76 unsigned char *startHeaderBuffPtr = headerBuffPtr;
78 ap_assert(nameLen >= 0);
80 if (nameLen < 0x80) {
81 *headerBuffPtr++ = (unsigned char) nameLen;
82 } else {
83 *headerBuffPtr++ = (unsigned char) ((nameLen >> 24) | 0x80);
84 *headerBuffPtr++ = (unsigned char) (nameLen >> 16);
85 *headerBuffPtr++ = (unsigned char) (nameLen >> 8);
86 *headerBuffPtr++ = (unsigned char) nameLen;
89 ap_assert(valueLen >= 0);
91 if (valueLen < 0x80) {
92 *headerBuffPtr++ = (unsigned char) valueLen;
93 } else {
94 *headerBuffPtr++ = (unsigned char) ((valueLen >> 24) | 0x80);
95 *headerBuffPtr++ = (unsigned char) (valueLen >> 16);
96 *headerBuffPtr++ = (unsigned char) (valueLen >> 8);
97 *headerBuffPtr++ = (unsigned char) valueLen;
99 *headerLenPtr = headerBuffPtr - startHeaderBuffPtr;
102 /* A static fn stolen from Apache's util_script.c...
103 * Obtain the Request-URI from the original request-line, returning
104 * a new string from the request pool containing the URI or "".
106 static char *apache_original_uri(request_rec *r)
108 char *first, *last;
110 if (r->the_request == NULL)
111 return (char *) ap_pcalloc(r->pool, 1);
113 first = r->the_request; /* use the request-line */
115 while (*first && !ap_isspace(*first))
116 ++first; /* skip over the method */
118 while (ap_isspace(*first))
119 ++first; /* and the space(s) */
121 last = first;
122 while (*last && !ap_isspace(*last))
123 ++last; /* end at next whitespace */
125 return ap_pstrndup(r->pool, first, last - first);
128 /* Based on Apache's ap_add_cgi_vars() in util_script.c.
129 * Apache's spins in sub_req_lookup_uri() trying to setup PATH_TRANSLATED,
130 * so we just don't do that part.
132 static void add_auth_cgi_vars(request_rec *r, const int compat)
134 table *e = r->subprocess_env;
136 ap_table_setn(e, "GATEWAY_INTERFACE", "CGI/1.1");
137 ap_table_setn(e, "SERVER_PROTOCOL", r->protocol);
138 ap_table_setn(e, "REQUEST_METHOD", r->method);
139 ap_table_setn(e, "QUERY_STRING", r->args ? r->args : "");
140 ap_table_setn(e, "REQUEST_URI", apache_original_uri(r));
142 /* The FastCGI spec precludes sending of CONTENT_LENGTH, PATH_INFO,
143 * PATH_TRANSLATED, and SCRIPT_NAME (for some reason?). PATH_TRANSLATED we
144 * don't have, its the variable that causes Apache to break trying to set
145 * up (and thus the reason this fn exists vs. using ap_add_cgi_vars()). */
146 if (compat) {
147 ap_table_unset(e, "CONTENT_LENGTH");
148 return;
151 /* Note that the code below special-cases scripts run from includes,
152 * because it "knows" that the sub_request has been hacked to have the
153 * args and path_info of the original request, and not any that may have
154 * come with the script URI in the include command. Ugh. */
155 if (!strcmp(r->protocol, "INCLUDED")) {
156 ap_table_setn(e, "SCRIPT_NAME", r->uri);
157 if (r->path_info && *r->path_info)
158 ap_table_setn(e, "PATH_INFO", r->path_info);
160 else if (!r->path_info || !*r->path_info)
161 ap_table_setn(e, "SCRIPT_NAME", r->uri);
162 else {
163 int path_info_start = ap_find_path_info(r->uri, r->path_info);
165 ap_table_setn(e, "SCRIPT_NAME", ap_pstrndup(r->pool, r->uri, path_info_start));
166 ap_table_setn(e, "PATH_INFO", r->path_info);
170 static void add_pass_header_vars(fcgi_request *fr)
172 const array_header *ph = fr->dynamic ? dynamic_pass_headers : fr->fs->pass_headers;
174 if (ph) {
175 const char **elt = (const char **)ph->elts;
176 int i = ph->nelts;
178 for ( ; i; --i, ++elt) {
179 const char *val = ap_table_get(fr->r->headers_in, *elt);
180 if (val) {
181 ap_table_setn(fr->r->subprocess_env, *elt, val);
187 /*******************************************************************************
188 * Build and queue the environment name-value pairs. Returns TRUE if the
189 * complete ENV was buffered, FALSE otherwise. Note: envp is updated to
190 * reflect the current position in the ENV.
192 int fcgi_protocol_queue_env(request_rec *r, fcgi_request *fr, env_status *env)
194 int charCount;
196 if (env->envp == NULL) {
197 ap_add_common_vars(r);
198 add_pass_header_vars(fr);
200 if (fr->role == FCGI_RESPONDER)
201 ap_add_cgi_vars(r);
202 else
203 add_auth_cgi_vars(r, fr->auth_compat);
205 env->envp = ap_create_environment(r->pool, r->subprocess_env);
206 env->pass = PREP;
209 while (*env->envp) {
210 switch (env->pass)
212 case PREP:
213 env->equalPtr = strchr(*env->envp, '=');
214 ap_assert(env->equalPtr != NULL);
215 env->nameLen = env->equalPtr - *env->envp;
216 env->valueLen = strlen(++env->equalPtr);
217 build_env_header(env->nameLen, env->valueLen, env->headerBuff, &env->headerLen);
218 env->totalLen = env->headerLen + env->nameLen + env->valueLen;
219 env->pass = HEADER;
220 /* drop through */
222 case HEADER:
223 if (BufferFree(fr->serverOutputBuffer) < (int)(sizeof(FCGI_Header) + env->headerLen)) {
224 return (FALSE);
226 queue_header(fr, FCGI_PARAMS, env->totalLen);
227 fcgi_buf_add_block(fr->serverOutputBuffer, (char *)env->headerBuff, env->headerLen);
228 env->pass = NAME;
229 /* drop through */
231 case NAME:
232 charCount = fcgi_buf_add_block(fr->serverOutputBuffer, *env->envp, env->nameLen);
233 if (charCount != env->nameLen) {
234 *env->envp += charCount;
235 env->nameLen -= charCount;
236 return (FALSE);
238 env->pass = VALUE;
239 /* drop through */
241 case VALUE:
242 charCount = fcgi_buf_add_block(fr->serverOutputBuffer, env->equalPtr, env->valueLen);
243 if (charCount != env->valueLen) {
244 env->equalPtr += charCount;
245 env->valueLen -= charCount;
246 return (FALSE);
248 env->pass = PREP;
250 ++env->envp;
253 if (BufferFree(fr->serverOutputBuffer) < sizeof(FCGI_Header)) {
254 return(FALSE);
256 queue_header(fr, FCGI_PARAMS, 0);
257 return(TRUE);
260 /*******************************************************************************
261 * Queue data from the client input buffer to the FastCGI server output
262 * buffer (encapsulating the data in FastCGI protocol messages).
264 void fcgi_protocol_queue_client_buffer(fcgi_request *fr)
266 int movelen;
267 int in_len, out_free;
269 if (fr->eofSent)
270 return;
273 * If there's some client data and room for at least one byte
274 * of data in the output buffer (after protocol overhead), then
275 * move some data to the output buffer.
277 in_len = BufferLength(fr->clientInputBuffer);
278 out_free = max(0, BufferFree(fr->serverOutputBuffer) - sizeof(FCGI_Header));
279 movelen = min(in_len, out_free);
280 if (movelen > 0) {
281 queue_header(fr, FCGI_STDIN, movelen);
282 fcgi_buf_get_to_buf(fr->serverOutputBuffer, fr->clientInputBuffer, movelen);
286 * If all the client data has been sent, and there's room
287 * in the output buffer, indicate EOF.
289 if (movelen == in_len && fr->expectingClientContent <= 0
290 && BufferFree(fr->serverOutputBuffer) >= sizeof(FCGI_Header))
292 queue_header(fr, FCGI_STDIN, 0);
293 fr->eofSent = TRUE;
297 /*******************************************************************************
298 * Read FastCGI protocol messages from the FastCGI server input buffer into
299 * fr->header when parsing headers, to fr->fs_stderr when reading stderr data,
300 * or to the client output buffer otherwises.
302 int fcgi_protocol_dequeue(pool *p, fcgi_request *fr)
304 FCGI_Header header;
305 int len;
307 while (BufferLength(fr->serverInputBuffer) > 0) {
309 * State #1: looking for the next complete packet header.
311 if (fr->gotHeader == FALSE) {
312 if (BufferLength(fr->serverInputBuffer) < sizeof(FCGI_Header)) {
313 return OK;
315 fcgi_buf_get_to_block(fr->serverInputBuffer, (char *) &header,
316 sizeof(FCGI_Header));
318 * XXX: Better handling of packets with other version numbers
319 * and other packet problems.
321 if (header.version != FCGI_VERSION) {
322 ap_log_rerror(FCGI_LOG_ERR_NOERRNO, fr->r,
323 "FastCGI: comm with server \"%s\" aborted: protocol error: invalid version: %d != FCGI_VERSION(%d)",
324 fr->fs_path, header.version, FCGI_VERSION);
325 return SERVER_ERROR;
327 if (header.type > FCGI_MAXTYPE) {
328 ap_log_rerror(FCGI_LOG_ERR_NOERRNO, fr->r,
329 "FastCGI: comm with server \"%s\" aborted: protocol error: invalid type: %d > FCGI_MAXTYPE(%d)",
330 fr->fs_path, header.type, FCGI_MAXTYPE);
331 return SERVER_ERROR;
334 fr->packetType = header.type;
335 fr->dataLen = (header.contentLengthB1 << 8)
336 + header.contentLengthB0;
337 fr->gotHeader = TRUE;
338 fr->paddingLen = header.paddingLength;
342 * State #2: got a header, and processing packet bytes.
344 len = min(fr->dataLen, BufferLength(fr->serverInputBuffer));
345 ap_assert(len >= 0);
346 switch (fr->packetType) {
347 case FCGI_STDOUT:
348 if (len > 0) {
349 switch(fr->parseHeader) {
350 case SCAN_CGI_READING_HEADERS:
351 fcgi_buf_get_to_array(fr->serverInputBuffer, fr->header, len);
352 break;
353 case SCAN_CGI_FINISHED:
354 len = min(BufferFree(fr->clientOutputBuffer), len);
355 if (len > 0) {
356 fcgi_buf_get_to_buf(fr->clientOutputBuffer, fr->serverInputBuffer, len);
357 } else {
358 return OK;
360 break;
361 default:
362 /* Toss data on the floor */
363 break;
365 fr->dataLen -= len;
367 break;
369 case FCGI_STDERR:
371 if (fr->fs_stderr == NULL)
373 fr->fs_stderr = ap_palloc(p, FCGI_SERVER_MAX_STDERR_LINE_LEN + 1);
376 /* We're gonna consume all thats here */
377 fr->dataLen -= len;
379 while (len > 0)
381 char *null, *end, *start = fr->fs_stderr;
383 /* Get as much as will fit in the buffer */
384 int get_len = min(len, FCGI_SERVER_MAX_STDERR_LINE_LEN - fr->fs_stderr_len);
385 fcgi_buf_get_to_block(fr->serverInputBuffer, start + fr->fs_stderr_len, get_len);
386 len -= get_len;
387 fr->fs_stderr_len += get_len;
388 *(start + fr->fs_stderr_len) = '\0';
390 /* Disallow nulls, we could be nicer but this is the motivator */
391 while ((null = memchr(start, '\0', fr->fs_stderr_len)))
393 int discard = ++null - start;
394 ap_log_rerror(FCGI_LOG_ERR_NOERRNO, fr->r,
395 "FastCGI: server \"%s\" sent a null character in the stderr stream!?, "
396 "discarding %d characters of stderr", fr->fs_path, discard);
397 start = null;
398 fr->fs_stderr_len -= discard;
401 /* Print as much as possible */
402 while ((end = strpbrk(start, "\r\n")))
404 if (start != end)
406 *end = '\0';
407 ap_log_rerror(FCGI_LOG_ERR_NOERRNO, fr->r, "FastCGI: server \"%s\" stderr: %s", fr->fs_path, start);
409 end += strspn(++end, "\r\n");
410 fr->fs_stderr_len -= (end - start);
411 start = end;
414 if (fr->fs_stderr_len)
416 if (start != fr->fs_stderr)
418 /* Move leftovers down */
419 memmove(fr->fs_stderr, start, fr->fs_stderr_len);
421 else if (fr->fs_stderr_len == FCGI_SERVER_MAX_STDERR_LINE_LEN)
423 /* Full buffer, dump it and complain */
424 ap_log_rerror(FCGI_LOG_ERR_NOERRNO, fr->r, "FastCGI: server \"%s\" stderr: %s", fr->fs_path, fr->fs_stderr);
425 ap_log_rerror(FCGI_LOG_WARN_NOERRNO, fr->r,
426 "FastCGI: too much stderr received from server \"%s\", "
427 "increase FCGI_SERVER_MAX_STDERR_LINE_LEN (%d) and rebuild "
428 "or use \"\\n\" to terminate lines",
429 fr->fs_path, FCGI_SERVER_MAX_STDERR_LINE_LEN);
430 fr->fs_stderr_len = 0;
434 break;
436 case FCGI_END_REQUEST:
437 if (!fr->readingEndRequestBody) {
438 if (fr->dataLen != sizeof(FCGI_EndRequestBody)) {
439 ap_log_rerror(FCGI_LOG_ERR_NOERRNO, fr->r,
440 "FastCGI: comm with server \"%s\" aborted: protocol error: invalid FCGI_END_REQUEST size: "
441 "%d != sizeof(FCGI_EndRequestBody)(%d)",
442 fr->fs_path, fr->dataLen, sizeof(FCGI_EndRequestBody));
443 return SERVER_ERROR;
445 fr->readingEndRequestBody = TRUE;
447 if (len>0) {
448 fcgi_buf_get_to_buf(fr->erBufPtr, fr->serverInputBuffer, len);
449 fr->dataLen -= len;
451 if (fr->dataLen == 0) {
452 FCGI_EndRequestBody *erBody = &fr->endRequestBody;
453 fcgi_buf_get_to_block(
454 fr->erBufPtr, (char *) &fr->endRequestBody,
455 sizeof(FCGI_EndRequestBody));
456 if (erBody->protocolStatus != FCGI_REQUEST_COMPLETE) {
458 * XXX: What to do with FCGI_OVERLOADED?
460 ap_log_rerror(FCGI_LOG_ERR_NOERRNO, fr->r,
461 "FastCGI: comm with server \"%s\" aborted: protocol error: invalid FCGI_END_REQUEST status: "
462 "%d != FCGI_REQUEST_COMPLETE(%d)", fr->fs_path,
463 erBody->protocolStatus, FCGI_REQUEST_COMPLETE);
464 return SERVER_ERROR;
466 fr->exitStatus = (erBody->appStatusB3 << 24)
467 + (erBody->appStatusB2 << 16)
468 + (erBody->appStatusB1 << 8)
469 + (erBody->appStatusB0 );
470 fr->exitStatusSet = TRUE;
471 fr->readingEndRequestBody = FALSE;
473 break;
474 case FCGI_GET_VALUES_RESULT:
475 /* XXX coming soon */
476 case FCGI_UNKNOWN_TYPE:
477 /* XXX coming soon */
480 * XXX Ignore unknown packet types from the FastCGI server.
482 default:
483 fcgi_buf_toss(fr->serverInputBuffer, len);
484 fr->dataLen -= len;
485 break;
486 } /* switch */
489 * Discard padding, then start looking for
490 * the next header.
492 if (fr->dataLen == 0) {
493 if (fr->paddingLen > 0) {
494 len = min(fr->paddingLen,
495 BufferLength(fr->serverInputBuffer));
496 fcgi_buf_toss(fr->serverInputBuffer, len);
497 fr->paddingLen -= len;
499 if (fr->paddingLen == 0) {
500 fr->gotHeader = FALSE;
503 } /* while */
504 return OK;