bump version to 0.82 and prepare for release
[catagits/fcgi2.git] / libfcgi / fcgiapp.c
CommitLineData
ae0319bf 1/*
0198fd3c 2 * fcgiapp.c --
3 *
4 * FastCGI application library: request-at-a-time
5 *
6 *
7 * Copyright (c) 1996 Open Market, Inc.
8 *
af1b4cad 9 * See the file "LICENSE" for information on usage and redistribution
0198fd3c 10 * of this file, and for a DISCLAIMER OF ALL WARRANTIES.
11 *
12 */
0198fd3c 13#ifndef lint
2a7273a1 14static const char rcsid[] = "$Id: fcgiapp.c,v 1.35 2003/06/22 00:16:43 robs Exp $";
0198fd3c 15#endif /* not lint */
16
6ad90ad2 17#include <assert.h>
18#include <errno.h>
19#include <fcntl.h> /* for fcntl */
20#include <math.h>
21#include <memory.h> /* for memchr() */
22#include <stdarg.h>
0198fd3c 23#include <stdio.h>
6ad90ad2 24#include <stdlib.h>
25#include <string.h>
0198fd3c 26#include <sys/types.h>
6ad90ad2 27
fc0ac9b7 28#include "fcgi_config.h"
29
6ad90ad2 30#ifdef HAVE_SYS_SOCKET_H
31#include <sys/socket.h> /* for getpeername */
32#endif
33
0198fd3c 34#ifdef HAVE_SYS_TIME_H
35#include <sys/time.h>
36#endif
37
0198fd3c 38#ifdef HAVE_UNISTD_H
39#include <unistd.h>
40#endif
41
75ccbd96 42#ifdef HAVE_LIMITS_H
43#include <limits.h>
44#endif
45
fc0ac9b7 46#ifdef _WIN32
47#define DLLAPI __declspec(dllexport)
48#endif
49
0198fd3c 50#include "fcgimisc.h"
0198fd3c 51#include "fastcgi.h"
52#include "fcgios.h"
569591e9 53#include "fcgiapp.h"
0198fd3c 54
55/*
ae0319bf 56 * This is a workaround for one version of the HP C compiler
0198fd3c 57 * (c89 on HP-UX 9.04, also Stratus FTX), which will dump core
58 * if given 'long double' for varargs.
59 */
60#ifdef HAVE_VA_ARG_LONG_DOUBLE_BUG
61#define LONG_DOUBLE double
62#else
63#define LONG_DOUBLE long double
64#endif
65
5a7cc494 66/*
ae0319bf 67 * Globals
5a7cc494 68 */
69static int libInitialized = 0;
165bb74e 70static int isFastCGI = -1;
5a7cc494 71static char *webServerAddressList = NULL;
faca4b3a 72static FCGX_Request the_request;
5a7cc494 73
6c50b8b4 74void FCGX_ShutdownPending(void)
75{
76 OS_ShutdownPending();
77}
78
0198fd3c 79static void *Malloc(size_t size)
80{
81 void *result = malloc(size);
82 ASSERT(size == 0 || result != NULL);
83 return result;
84}
85
86static char *StringCopy(char *str)
87{
88 int strLen = strlen(str);
aadcc3c8 89 char *newString = (char *)Malloc(strLen + 1);
0198fd3c 90 memcpy(newString, str, strLen);
91 newString[strLen] = '\000';
92 return newString;
93}
94
569591e9 95
0198fd3c 96/*
97 *----------------------------------------------------------------------
98 *
99 * FCGX_GetChar --
100 *
101 * Reads a byte from the input stream and returns it.
102 *
103 * Results:
104 * The byte, or EOF (-1) if the end of input has been reached.
105 *
106 *----------------------------------------------------------------------
107 */
108int FCGX_GetChar(FCGX_Stream *stream)
109{
396788f8 110 if (stream->isClosed || ! stream->isReader)
99b44eaa 111 return EOF;
396788f8 112
113 if (stream->rdNext != stream->stop)
114 return *stream->rdNext++;
115
99b44eaa 116 stream->fillBuffProc(stream);
33977e3b 117 if (stream->isClosed)
118 return EOF;
396788f8 119
99b44eaa 120 stream->stopUnget = stream->rdNext;
396788f8 121 if (stream->rdNext != stream->stop)
99b44eaa 122 return *stream->rdNext++;
396788f8 123
99b44eaa 124 ASSERT(stream->isClosed); /* bug in fillBufProc if not */
125 return EOF;
0198fd3c 126}
569591e9 127
0198fd3c 128/*
129 *----------------------------------------------------------------------
130 *
131 * FCGX_GetStr --
132 *
133 * Reads up to n consecutive bytes from the input stream
134 * into the character array str. Performs no interpretation
135 * of the input bytes.
136 *
137 * Results:
138 * Number of bytes read. If result is smaller than n,
139 * the end of input has been reached.
140 *
141 *----------------------------------------------------------------------
142 */
143int FCGX_GetStr(char *str, int n, FCGX_Stream *stream)
144{
145 int m, bytesMoved;
146
396788f8 147 if (stream->isClosed || ! stream->isReader || n <= 0) {
0198fd3c 148 return 0;
149 }
150 /*
151 * Fast path: n bytes are already available
152 */
153 if(n <= (stream->stop - stream->rdNext)) {
154 memcpy(str, stream->rdNext, n);
155 stream->rdNext += n;
156 return n;
157 }
158 /*
159 * General case: stream is closed or buffer fill procedure
160 * needs to be called
161 */
162 bytesMoved = 0;
163 for (;;) {
164 if(stream->rdNext != stream->stop) {
165 m = min(n - bytesMoved, stream->stop - stream->rdNext);
166 memcpy(str, stream->rdNext, m);
167 bytesMoved += m;
168 stream->rdNext += m;
169 if(bytesMoved == n)
170 return bytesMoved;
171 str += m;
33977e3b 172 }
0198fd3c 173 if(stream->isClosed || !stream->isReader)
174 return bytesMoved;
175 stream->fillBuffProc(stream);
33977e3b 176 if (stream->isClosed)
177 return bytesMoved;
178
0198fd3c 179 stream->stopUnget = stream->rdNext;
180 }
181}
569591e9 182
0198fd3c 183/*
184 *----------------------------------------------------------------------
185 *
186 * FCGX_GetLine --
187 *
188 * Reads up to n-1 consecutive bytes from the input stream
189 * into the character array str. Stops before n-1 bytes
190 * have been read if '\n' or EOF is read. The terminating '\n'
191 * is copied to str. After copying the last byte into str,
192 * stores a '\0' terminator.
193 *
194 * Results:
195 * NULL if EOF is the first thing read from the input stream,
196 * str otherwise.
197 *
198 *----------------------------------------------------------------------
199 */
200char *FCGX_GetLine(char *str, int n, FCGX_Stream *stream)
201{
202 int c;
203 char *p = str;
611bc63f 204
0198fd3c 205 n--;
206 while (n > 0) {
207 c = FCGX_GetChar(stream);
208 if(c == EOF) {
209 if(p == str)
210 return NULL;
ae0319bf 211 else
0198fd3c 212 break;
ae0319bf 213 }
611bc63f 214 *p++ = (char) c;
0198fd3c 215 n--;
216 if(c == '\n')
217 break;
218 }
219 *p = '\0';
220 return str;
221}
569591e9 222
0198fd3c 223/*
224 *----------------------------------------------------------------------
225 *
226 * FCGX_UnGetChar --
227 *
228 * Pushes back the character c onto the input stream. One
229 * character of pushback is guaranteed once a character
230 * has been read. No pushback is possible for EOF.
231 *
232 * Results:
233 * Returns c if the pushback succeeded, EOF if not.
234 *
235 *----------------------------------------------------------------------
236 */
237int FCGX_UnGetChar(int c, FCGX_Stream *stream) {
238 if(c == EOF
239 || stream->isClosed
240 || !stream->isReader
241 || stream->rdNext == stream->stopUnget)
242 return EOF;
243 --(stream->rdNext);
611bc63f 244 *stream->rdNext = (unsigned char) c;
0198fd3c 245 return c;
246}
247
248/*
249 *----------------------------------------------------------------------
250 *
251 * FCGX_HasSeenEOF --
252 *
253 * Returns EOF if end-of-file has been detected while reading
254 * from stream; otherwise returns 0.
255 *
256 * Note that FCGX_HasSeenEOF(s) may return 0, yet an immediately
257 * following FCGX_GetChar(s) may return EOF. This function, like
258 * the standard C stdio function feof, does not provide the
259 * ability to peek ahead.
260 *
261 * Results:
262 * EOF if end-of-file has been detected, 0 if not.
263 *
264 *----------------------------------------------------------------------
265 */
266int FCGX_HasSeenEOF(FCGX_Stream *stream) {
267 return (stream->isClosed) ? EOF : 0;
268}
569591e9 269
0198fd3c 270/*
271 *----------------------------------------------------------------------
272 *
273 * FCGX_PutChar --
274 *
275 * Writes a byte to the output stream.
276 *
277 * Results:
278 * The byte, or EOF (-1) if an error occurred.
ae0319bf 279 *
0198fd3c 280 *----------------------------------------------------------------------
281 */
282int FCGX_PutChar(int c, FCGX_Stream *stream)
283{
284 if(stream->wrNext != stream->stop)
611bc63f 285 return (*stream->wrNext++ = (unsigned char) c);
0198fd3c 286 if(stream->isClosed || stream->isReader)
287 return EOF;
288 stream->emptyBuffProc(stream, FALSE);
289 if(stream->wrNext != stream->stop)
611bc63f 290 return (*stream->wrNext++ = (unsigned char) c);
0198fd3c 291 ASSERT(stream->isClosed); /* bug in emptyBuffProc if not */
292 return EOF;
293}
569591e9 294
0198fd3c 295/*
296 *----------------------------------------------------------------------
297 *
298 * FCGX_PutStr --
299 *
300 * Writes n consecutive bytes from the character array str
301 * into the output stream. Performs no interpretation
302 * of the output bytes.
303 *
304 * Results:
305 * Number of bytes written (n) for normal return,
306 * EOF (-1) if an error occurred.
ae0319bf 307 *
0198fd3c 308 *----------------------------------------------------------------------
309 */
310int FCGX_PutStr(const char *str, int n, FCGX_Stream *stream)
311{
312 int m, bytesMoved;
313
314 /*
315 * Fast path: room for n bytes in the buffer
316 */
317 if(n <= (stream->stop - stream->wrNext)) {
318 memcpy(stream->wrNext, str, n);
319 stream->wrNext += n;
320 return n;
321 }
322 /*
323 * General case: stream is closed or buffer empty procedure
324 * needs to be called
325 */
326 bytesMoved = 0;
327 for (;;) {
328 if(stream->wrNext != stream->stop) {
329 m = min(n - bytesMoved, stream->stop - stream->wrNext);
330 memcpy(stream->wrNext, str, m);
331 bytesMoved += m;
332 stream->wrNext += m;
333 if(bytesMoved == n)
334 return bytesMoved;
335 str += m;
336 }
337 if(stream->isClosed || stream->isReader)
338 return -1;
339 stream->emptyBuffProc(stream, FALSE);
340 }
341}
569591e9 342
0198fd3c 343/*
344 *----------------------------------------------------------------------
345 *
346 * FCGX_PutS --
347 *
348 * Writes a character string to the output stream.
349 *
350 * Results:
351 * number of bytes written for normal return,
352 * EOF (-1) if an error occurred.
ae0319bf 353 *
0198fd3c 354 *----------------------------------------------------------------------
355 */
356int FCGX_PutS(const char *str, FCGX_Stream *stream)
357{
358 return FCGX_PutStr(str, strlen(str), stream);
359}
569591e9 360
0198fd3c 361/*
362 *----------------------------------------------------------------------
363 *
364 * FCGX_FPrintF --
365 *
366 * Performs output formatting and writes the results
367 * to the output stream.
368 *
369 * Results:
370 * number of bytes written for normal return,
371 * EOF (-1) if an error occurred.
ae0319bf 372 *
0198fd3c 373 *----------------------------------------------------------------------
374 */
375int FCGX_FPrintF(FCGX_Stream *stream, const char *format, ...)
376{
377 int result;
378 va_list ap;
379 va_start(ap, format);
380 result = FCGX_VFPrintF(stream, format, ap);
381 va_end(ap);
382 return result;
383}
384
385/*
386 *----------------------------------------------------------------------
387 *
388 * FCGX_VFPrintF --
389 *
390 * Performs output formatting and writes the results
391 * to the output stream.
392 *
393 * Results:
394 * number of bytes written for normal return,
395 * EOF (-1) if an error occurred.
ae0319bf 396 *
0198fd3c 397 *----------------------------------------------------------------------
398 */
399
400#define PRINTF_BUFFLEN 100
401 /*
402 * More than sufficient space for all unmodified conversions
403 * except %s and %f.
404 */
405#define FMT_BUFFLEN 25
406 /*
407 * Max size of a format specifier is 1 + 5 + 7 + 7 + 2 + 1 + slop
408 */
409static void CopyAndAdvance(char **destPtr, char **srcPtr, int n);
410
411int FCGX_VFPrintF(FCGX_Stream *stream, const char *format, va_list arg)
412{
413 char *f, *fStop, *percentPtr, *p, *fmtBuffPtr, *buffPtr;
611bc63f 414 int op, performedOp, sizeModifier, buffCount = 0, buffLen, specifierLength;
415 int fastPath, n, auxBuffLen = 0, buffReqd, minWidth, precision, exp;
0198fd3c 416 char *auxBuffPtr = NULL;
417 int streamCount = 0;
418 char fmtBuff[FMT_BUFFLEN];
419 char buff[PRINTF_BUFFLEN];
420
421 int intArg;
422 short shortArg;
423 long longArg;
424 unsigned unsignedArg;
425 unsigned long uLongArg;
426 unsigned short uShortArg;
611bc63f 427 char *charPtrArg = NULL;
0198fd3c 428 void *voidPtrArg;
429 int *intPtrArg;
430 long *longPtrArg;
431 short *shortPtrArg;
611bc63f 432 double doubleArg = 0.0;
433 LONG_DOUBLE lDoubleArg = 0.0L;
0198fd3c 434
435 fmtBuff[0] = '%';
436 f = (char *) format;
437 fStop = f + strlen(f);
438 while (f != fStop) {
aadcc3c8 439 percentPtr = (char *)memchr(f, '%', fStop - f);
0198fd3c 440 if(percentPtr == NULL) percentPtr = fStop;
441 if(percentPtr != f) {
59bfcb87 442 if(FCGX_PutStr(f, percentPtr - f, stream) < 0)
443 goto ErrorReturn;
0198fd3c 444 streamCount += percentPtr - f;
445 f = percentPtr;
446 if(f == fStop) break;
447 }
448 fastPath = TRUE;
449 /*
450 * The following loop always executes either once or twice.
451 */
452 for (;;) {
453 if(fastPath) {
454 /*
455 * Fast path: Scan optimistically, hoping that no flags,
456 * minimum field width, or precision are specified.
457 * Use the preallocated buffer, which is large enough
458 * for all fast path cases. If the conversion specifier
459 * is really more complex, run the loop a second time
460 * using the slow path.
461 * Note that fast path execution of %s bypasses the buffer
462 * and %f is not attempted on the fast path due to
463 * its large buffering requirements.
464 */
465 op = *(percentPtr + 1);
466 switch(op) {
467 case 'l':
468 case 'L':
469 case 'h':
470 sizeModifier = op;
471 op = *(percentPtr + 2);
611bc63f 472 fmtBuff[1] = (char) sizeModifier;
473 fmtBuff[2] = (char) op;
0198fd3c 474 fmtBuff[3] = '\0';
475 specifierLength = 3;
476 break;
477 default:
478 sizeModifier = ' ';
611bc63f 479 fmtBuff[1] = (char) op;
0198fd3c 480 fmtBuff[2] = '\0';
481 specifierLength = 2;
482 break;
483 }
484 buffPtr = buff;
485 buffLen = PRINTF_BUFFLEN;
486 } else {
487 /*
488 * Slow path: Scan the conversion specifier and construct
489 * a new format string, compute an upper bound on the
490 * amount of buffering that sprintf will require,
491 * and allocate a larger buffer if necessary.
492 */
493 p = percentPtr + 1;
494 fmtBuffPtr = &fmtBuff[1];
495 /*
496 * Scan flags
497 */
498 n = strspn(p, "-0+ #");
59bfcb87 499 if(n > 5)
500 goto ErrorReturn;
0198fd3c 501 CopyAndAdvance(&fmtBuffPtr, &p, n);
502 /*
503 * Scan minimum field width
504 */
505 n = strspn(p, "0123456789");
506 if(n == 0) {
507 if(*p == '*') {
508 minWidth = va_arg(arg, int);
59bfcb87 509 if(abs(minWidth) > 999999)
510 goto ErrorReturn;
0198fd3c 511 /*
512 * The following use of strlen rather than the
513 * value returned from sprintf is because SUNOS4
514 * returns a char * instead of an int count.
515 */
516 sprintf(fmtBuffPtr, "%d", minWidth);
517 fmtBuffPtr += strlen(fmtBuffPtr);
518 p++;
519 } else {
520 minWidth = 0;
521 }
522 } else if(n <= 6) {
523 minWidth = strtol(p, NULL, 10);
524 CopyAndAdvance(&fmtBuffPtr, &p, n);
525 } else {
526 goto ErrorReturn;
527 }
528 /*
529 * Scan precision
530 */
531 if(*p == '.') {
532 CopyAndAdvance(&fmtBuffPtr, &p, 1);
533 n = strspn(p, "0123456789");
534 if(n == 0) {
535 if(*p == '*') {
536 precision = va_arg(arg, int);
537 if(precision < 0) precision = 0;
59bfcb87 538 if(precision > 999999)
539 goto ErrorReturn;
0198fd3c 540 /*
541 * The following use of strlen rather than the
542 * value returned from sprintf is because SUNOS4
543 * returns a char * instead of an int count.
544 */
545 sprintf(fmtBuffPtr, "%d", precision);
546 fmtBuffPtr += strlen(fmtBuffPtr);
547 p++;
548 } else {
549 precision = 0;
550 }
551 } else if(n <= 6) {
552 precision = strtol(p, NULL, 10);
553 CopyAndAdvance(&fmtBuffPtr, &p, n);
554 } else {
555 goto ErrorReturn;
556 }
557 } else {
558 precision = -1;
559 }
560 /*
561 * Scan size modifier and conversion operation
562 */
563 switch(*p) {
564 case 'l':
565 case 'L':
566 case 'h':
567 sizeModifier = *p;
568 CopyAndAdvance(&fmtBuffPtr, &p, 1);
569 break;
570 default:
571 sizeModifier = ' ';
572 break;
573 }
574 op = *p;
575 CopyAndAdvance(&fmtBuffPtr, &p, 1);
576 ASSERT(fmtBuffPtr - fmtBuff < FMT_BUFFLEN);
577 *fmtBuffPtr = '\0';
578 specifierLength = p - percentPtr;
579 /*
580 * Bound the required buffer size. For s and f
581 * conversions this requires examining the argument.
582 */
583 switch(op) {
584 case 'd':
585 case 'i':
586 case 'u':
587 case 'o':
588 case 'x':
589 case 'X':
590 case 'c':
591 case 'p':
592 buffReqd = max(precision, 46);
593 break;
594 case 's':
595 charPtrArg = va_arg(arg, char *);
a25dc891 596 if (!charPtrArg) charPtrArg = "(null)";
0198fd3c 597 if(precision == -1) {
598 buffReqd = strlen(charPtrArg);
599 } else {
aadcc3c8 600 p = (char *)memchr(charPtrArg, '\0', precision);
0198fd3c 601 buffReqd =
602 (p == NULL) ? precision : p - charPtrArg;
603 }
604 break;
605 case 'f':
606 switch(sizeModifier) {
607 case ' ':
608 doubleArg = va_arg(arg, double);
611bc63f 609 frexp(doubleArg, &exp);
0198fd3c 610 break;
611 case 'L':
612 lDoubleArg = va_arg(arg, LONG_DOUBLE);
611bc63f 613 /* XXX Need to check for the presence of
614 * frexpl() and use it if available */
615 frexp((double) lDoubleArg, &exp);
0198fd3c 616 break;
617 default:
618 goto ErrorReturn;
619 }
620 if(precision == -1) precision = 6;
621 buffReqd = precision + 3 + ((exp > 0) ? exp/3 : 0);
622 break;
623 case 'e':
624 case 'E':
625 case 'g':
626 case 'G':
627 if(precision == -1) precision = 6;
628 buffReqd = precision + 8;
629 break;
630 case 'n':
631 case '%':
632 default:
633 goto ErrorReturn;
634 break;
635 }
636 buffReqd = max(buffReqd + 10, minWidth);
637 /*
638 * Allocate the buffer
639 */
640 if(buffReqd <= PRINTF_BUFFLEN) {
641 buffPtr = buff;
642 buffLen = PRINTF_BUFFLEN;
643 } else {
644 if(auxBuffPtr == NULL || buffReqd > auxBuffLen) {
645 if(auxBuffPtr != NULL) free(auxBuffPtr);
aadcc3c8 646 auxBuffPtr = (char *)Malloc(buffReqd);
0198fd3c 647 auxBuffLen = buffReqd;
59bfcb87 648 if(auxBuffPtr == NULL)
649 goto ErrorReturn;
0198fd3c 650 }
651 buffPtr = auxBuffPtr;
652 buffLen = auxBuffLen;
653 }
654 }
655 /*
656 * This giant switch statement requires the following variables
657 * to be set up: op, sizeModifier, arg, buffPtr, fmtBuff.
658 * When fastPath == FALSE and op == 's' or 'f', the argument
659 * has been read into charPtrArg, doubleArg, or lDoubleArg.
660 * The statement produces the boolean performedOp, TRUE iff
661 * the op/sizeModifier were executed and argument consumed;
662 * if performedOp, the characters written into buffPtr[]
663 * and the character count buffCount (== EOF meaning error).
664 *
665 * The switch cases are arranged in the same order as in the
666 * description of fprintf in section 15.11 of Harbison and Steele.
667 */
668 performedOp = TRUE;
669 switch(op) {
670 case 'd':
671 case 'i':
672 switch(sizeModifier) {
673 case ' ':
674 intArg = va_arg(arg, int);
675 sprintf(buffPtr, fmtBuff, intArg);
676 buffCount = strlen(buffPtr);
677 break;
678 case 'l':
679 longArg = va_arg(arg, long);
680 sprintf(buffPtr, fmtBuff, longArg);
681 buffCount = strlen(buffPtr);
682 break;
683 case 'h':
ab4f3d6f 684 shortArg = (short) va_arg(arg, int);
685 sprintf(buffPtr, fmtBuff, shortArg);
0198fd3c 686 buffCount = strlen(buffPtr);
687 break;
688 default:
689 goto ErrorReturn;
690 }
691 break;
692 case 'u':
693 case 'o':
694 case 'x':
695 case 'X':
696 switch(sizeModifier) {
697 case ' ':
698 unsignedArg = va_arg(arg, unsigned);
699 sprintf(buffPtr, fmtBuff, unsignedArg);
700 buffCount = strlen(buffPtr);
701 break;
702 case 'l':
703 uLongArg = va_arg(arg, unsigned long);
704 sprintf(buffPtr, fmtBuff, uLongArg);
705 buffCount = strlen(buffPtr);
706 break;
707 case 'h':
ab4f3d6f 708 uShortArg = (unsigned short) va_arg(arg, int);
709 sprintf(buffPtr, fmtBuff, uShortArg);
0198fd3c 710 buffCount = strlen(buffPtr);
711 break;
712 default:
713 goto ErrorReturn;
714 }
715 break;
716 case 'c':
717 switch(sizeModifier) {
718 case ' ':
719 intArg = va_arg(arg, int);
720 sprintf(buffPtr, fmtBuff, intArg);
721 buffCount = strlen(buffPtr);
722 break;
723 case 'l':
724 /*
725 * XXX: Allowed by ISO C Amendment 1, but
726 * many platforms don't yet support wint_t
727 */
728 goto ErrorReturn;
729 default:
730 goto ErrorReturn;
731 }
732 break;
733 case 's':
734 switch(sizeModifier) {
735 case ' ':
736 if(fastPath) {
737 buffPtr = va_arg(arg, char *);
738 buffCount = strlen(buffPtr);
739 buffLen = buffCount + 1;
740 } else {
741 sprintf(buffPtr, fmtBuff, charPtrArg);
742 buffCount = strlen(buffPtr);
743 }
744 break;
745 case 'l':
746 /*
747 * XXX: Don't know how to convert a sequence
748 * of wide characters into a byte stream, or
749 * even how to predict the buffering required.
750 */
751 goto ErrorReturn;
752 default:
753 goto ErrorReturn;
754 }
755 break;
756 case 'p':
59bfcb87 757 if(sizeModifier != ' ')
758 goto ErrorReturn;
0198fd3c 759 voidPtrArg = va_arg(arg, void *);
760 sprintf(buffPtr, fmtBuff, voidPtrArg);
761 buffCount = strlen(buffPtr);
762 break;
763 case 'n':
764 switch(sizeModifier) {
765 case ' ':
766 intPtrArg = va_arg(arg, int *);
767 *intPtrArg = streamCount;
768 break;
769 case 'l':
770 longPtrArg = va_arg(arg, long *);
771 *longPtrArg = streamCount;
772 break;
773 case 'h':
611bc63f 774 shortPtrArg = (short *) va_arg(arg, short *);
775 *shortPtrArg = (short) streamCount;
0198fd3c 776 break;
777 default:
778 goto ErrorReturn;
779 }
780 buffCount = 0;
781 break;
782 case 'f':
783 if(fastPath) {
784 performedOp = FALSE;
785 break;
786 }
787 switch(sizeModifier) {
788 case ' ':
789 sprintf(buffPtr, fmtBuff, doubleArg);
790 buffCount = strlen(buffPtr);
791 break;
792 case 'L':
793 sprintf(buffPtr, fmtBuff, lDoubleArg);
794 buffCount = strlen(buffPtr);
795 break;
796 default:
797 goto ErrorReturn;
798 }
799 break;
800 case 'e':
801 case 'E':
802 case 'g':
803 case 'G':
804 switch(sizeModifier) {
805 case ' ':
806 doubleArg = va_arg(arg, double);
807 sprintf(buffPtr, fmtBuff, doubleArg);
808 buffCount = strlen(buffPtr);
809 break;
810 case 'L':
811 lDoubleArg = va_arg(arg, LONG_DOUBLE);
812 sprintf(buffPtr, fmtBuff, lDoubleArg);
813 buffCount = strlen(buffPtr);
814 break;
815 default:
816 goto ErrorReturn;
817 }
818 break;
819 case '%':
820 if(sizeModifier != ' ')
821 goto ErrorReturn;
822 buff[0] = '%';
823 buffCount = 1;
824 break;
825 case '\0':
826 goto ErrorReturn;
827 default:
828 performedOp = FALSE;
829 break;
830 } /* switch(op) */
831 if(performedOp) break;
59bfcb87 832 if(!fastPath)
833 goto ErrorReturn;
0198fd3c 834 fastPath = FALSE;
835 } /* for (;;) */
836 ASSERT(buffCount < buffLen);
837 if(buffCount > 0) {
838 if(FCGX_PutStr(buffPtr, buffCount, stream) < 0)
839 goto ErrorReturn;
840 streamCount += buffCount;
841 } else if(buffCount < 0) {
842 goto ErrorReturn;
843 }
844 f += specifierLength;
845 } /* while(f != fStop) */
846 goto NormalReturn;
847 ErrorReturn:
848 streamCount = -1;
849 NormalReturn:
850 if(auxBuffPtr != NULL) free(auxBuffPtr);
851 return streamCount;
852}
853
854/*
855 * Copy n characters from *srcPtr to *destPtr, then increment
856 * both *srcPtr and *destPtr by n.
857 */
858static void CopyAndAdvance(char **destPtr, char **srcPtr, int n)
859{
860 char *dest = *destPtr;
861 char *src = *srcPtr;
862 int i;
863 for (i = 0; i < n; i++)
864 *dest++ = *src++;
865 *destPtr = dest;
866 *srcPtr = src;
867}
569591e9 868
0198fd3c 869/*
870 *----------------------------------------------------------------------
871 *
872 * FCGX_FFlush --
873 *
874 * Flushes any buffered output.
875 *
876 * Server-push is a legitimate application of FCGX_FFlush.
877 * Otherwise, FCGX_FFlush is not very useful, since FCGX_Accept
878 * does it implicitly. FCGX_FFlush may reduce performance
879 * by increasing the total number of operating system calls
880 * the application makes.
881 *
882 * Results:
883 * EOF (-1) if an error occurred.
ae0319bf 884 *
0198fd3c 885 *----------------------------------------------------------------------
886 */
887int FCGX_FFlush(FCGX_Stream *stream)
888{
889 if(stream->isClosed || stream->isReader)
890 return 0;
891 stream->emptyBuffProc(stream, FALSE);
892 return (stream->isClosed) ? -1 : 0;
893}
569591e9 894
0198fd3c 895/*
896 *----------------------------------------------------------------------
897 *
898 * FCGX_FClose --
899 *
900 * Performs FCGX_FFlush and closes the stream.
901 *
902 * This is not a very useful operation, since FCGX_Accept
903 * does it implicitly. Closing the out stream before the
904 * err stream results in an extra write if there's nothing
905 * in the err stream, and therefore reduces performance.
906 *
907 * Results:
908 * EOF (-1) if an error occurred.
ae0319bf 909 *
0198fd3c 910 *----------------------------------------------------------------------
911 */
912int FCGX_FClose(FCGX_Stream *stream)
913{
59bfcb87 914 if (stream == NULL) return 0;
915
0198fd3c 916 if(!stream->wasFCloseCalled) {
917 if(!stream->isReader) {
918 stream->emptyBuffProc(stream, TRUE);
919 }
920 stream->wasFCloseCalled = TRUE;
921 stream->isClosed = TRUE;
922 if(stream->isReader) {
923 stream->wrNext = stream->stop = stream->rdNext;
924 } else {
925 stream->rdNext = stream->stop = stream->wrNext;
926 }
927 }
928 return (stream->FCGI_errno == 0) ? 0 : EOF;
929}
569591e9 930
0198fd3c 931/*
932 *----------------------------------------------------------------------
933 *
934 * SetError --
935 *
936 * An error has occurred; save the error code in the stream
937 * for diagnostic purposes and set the stream state so that
938 * reads return EOF and writes have no effect.
939 *
940 *----------------------------------------------------------------------
941 */
942static void SetError(FCGX_Stream *stream, int FCGI_errno)
943{
944 /*
945 * Preserve only the first error.
946 */
947 if(stream->FCGI_errno == 0) {
948 stream->FCGI_errno = FCGI_errno;
0198fd3c 949 }
396788f8 950
951 stream->isClosed = TRUE;
0198fd3c 952}
953
954/*
955 *----------------------------------------------------------------------
956 *
957 * FCGX_GetError --
958 *
959 * Return the stream error code. 0 means no error, > 0
960 * is an errno(2) error, < 0 is an FCGX_errno error.
961 *
962 *----------------------------------------------------------------------
963 */
964int FCGX_GetError(FCGX_Stream *stream) {
965 return stream->FCGI_errno;
966}
967
968/*
969 *----------------------------------------------------------------------
970 *
971 * FCGX_ClearError --
972 *
973 * Clear the stream error code and end-of-file indication.
974 *
975 *----------------------------------------------------------------------
976 */
977void FCGX_ClearError(FCGX_Stream *stream) {
978 stream->FCGI_errno = 0;
979 /*
980 * stream->isClosed = FALSE;
981 * XXX: should clear isClosed but work is needed to make it safe
982 * to do so. For example, if an application calls FClose, gets
983 * an I/O error on the write, calls ClearError and retries
984 * the FClose, FClose (really EmptyBuffProc) will write a second
985 * EOF record. If an application calls PutChar instead of FClose
986 * after the ClearError, the application will write more data.
987 * The stream's state must discriminate between various states
988 * of the stream that are now all lumped under isClosed.
989 */
990}
569591e9 991
0198fd3c 992/*
993 *======================================================================
994 * Parameters
995 *======================================================================
996 */
997
998/*
999 * A vector of pointers representing the parameters received
1000 * by a FastCGI application server, with the vector's length
1001 * and last valid element so adding new parameters is efficient.
1002 */
1003
1004typedef struct Params {
1005 FCGX_ParamArray vec; /* vector of strings */
1006 int length; /* number of string vec can hold */
1007 char **cur; /* current item in vec; *cur == NULL */
1008} Params;
1009typedef Params *ParamsPtr;
569591e9 1010
0198fd3c 1011/*
1012 *----------------------------------------------------------------------
1013 *
1014 * NewParams --
1015 *
1016 * Creates a new Params structure.
1017 *
1018 * Results:
1019 * Pointer to the new structure.
1020 *
1021 *----------------------------------------------------------------------
1022 */
1023static ParamsPtr NewParams(int length)
1024{
1025 ParamsPtr result;
aadcc3c8 1026 result = (Params *)Malloc(sizeof(Params));
1027 result->vec = (char **)Malloc(length * sizeof(char *));
0198fd3c 1028 result->length = length;
1029 result->cur = result->vec;
1030 *result->cur = NULL;
1031 return result;
1032}
569591e9 1033
0198fd3c 1034/*
1035 *----------------------------------------------------------------------
1036 *
1037 * FreeParams --
1038 *
1039 * Frees a Params structure and all the parameters it contains.
1040 *
1041 * Side effects:
0b7c9662 1042 * env becomes invalid.
0198fd3c 1043 *
1044 *----------------------------------------------------------------------
1045 */
1046static void FreeParams(ParamsPtr *paramsPtrPtr)
1047{
1048 ParamsPtr paramsPtr = *paramsPtrPtr;
1049 char **p;
1050 if(paramsPtr == NULL) {
1051 return;
1052 }
1053 for (p = paramsPtr->vec; p < paramsPtr->cur; p++) {
1054 free(*p);
1055 }
1056 free(paramsPtr->vec);
1057 free(paramsPtr);
1058 *paramsPtrPtr = NULL;
1059}
569591e9 1060
0198fd3c 1061/*
1062 *----------------------------------------------------------------------
1063 *
1064 * PutParam --
1065 *
1066 * Add a name/value pair to a Params structure.
1067 *
1068 * Results:
1069 * None.
1070 *
ae0319bf 1071 * Side effects:
0198fd3c 1072 * Parameters structure updated.
1073 *
1074 *----------------------------------------------------------------------
ae0319bf 1075 */
0198fd3c 1076static void PutParam(ParamsPtr paramsPtr, char *nameValue)
1077{
1078 int size;
1079
1080 *paramsPtr->cur++ = nameValue;
1081 size = paramsPtr->cur - paramsPtr->vec;
1082 if(size >= paramsPtr->length) {
1083 paramsPtr->length *= 2;
aadcc3c8 1084 paramsPtr->vec = (FCGX_ParamArray)realloc(paramsPtr->vec, paramsPtr->length * sizeof(char *));
0198fd3c 1085 paramsPtr->cur = paramsPtr->vec + size;
1086 }
1087 *paramsPtr->cur = NULL;
1088}
569591e9 1089
0198fd3c 1090/*
1091 *----------------------------------------------------------------------
1092 *
1093 * FCGX_GetParam -- obtain value of FCGI parameter in environment
1094 *
1095 *
1096 * Results:
1097 * Value bound to name, NULL if name not present in the
1098 * environment envp. Caller must not mutate the result
1099 * or retain it past the end of this request.
1100 *
1101 *----------------------------------------------------------------------
1102 */
1103char *FCGX_GetParam(const char *name, FCGX_ParamArray envp)
1104{
1105 int len;
1106 char **p;
2fe790fc 1107
1108 if (name == NULL || envp == NULL) return NULL;
1109
0198fd3c 1110 len = strlen(name);
2fe790fc 1111
1112 for (p = envp; *p; ++p) {
0198fd3c 1113 if((strncmp(name, *p, len) == 0) && ((*p)[len] == '=')) {
1114 return *p+len+1;
1115 }
1116 }
1117 return NULL;
1118}
569591e9 1119
0198fd3c 1120/*
1121 *----------------------------------------------------------------------
1122 *
1123 * Start of FastCGI-specific code
1124 *
1125 *----------------------------------------------------------------------
1126 */
569591e9 1127
0198fd3c 1128/*
1129 *----------------------------------------------------------------------
1130 *
1131 * ReadParams --
1132 *
1133 * Reads FastCGI name-value pairs from stream until EOF. Converts
1134 * each pair to name=value format and adds it to Params structure.
1135 *
1136 *----------------------------------------------------------------------
1137 */
1138static int ReadParams(Params *paramsPtr, FCGX_Stream *stream)
1139{
1140 int nameLen, valueLen;
1141 unsigned char lenBuff[3];
1142 char *nameValue;
1143
1144 while((nameLen = FCGX_GetChar(stream)) != EOF) {
1145 /*
1146 * Read name length (one or four bytes) and value length
1147 * (one or four bytes) from stream.
1148 */
1149 if((nameLen & 0x80) != 0) {
1150 if(FCGX_GetStr((char *) &lenBuff[0], 3, stream) != 3) {
1151 SetError(stream, FCGX_PARAMS_ERROR);
1152 return -1;
1153 }
1154 nameLen = ((nameLen & 0x7f) << 24) + (lenBuff[0] << 16)
1155 + (lenBuff[1] << 8) + lenBuff[2];
1156 }
1157 if((valueLen = FCGX_GetChar(stream)) == EOF) {
1158 SetError(stream, FCGX_PARAMS_ERROR);
1159 return -1;
1160 }
1161 if((valueLen & 0x80) != 0) {
1162 if(FCGX_GetStr((char *) &lenBuff[0], 3, stream) != 3) {
1163 SetError(stream, FCGX_PARAMS_ERROR);
1164 return -1;
1165 }
1166 valueLen = ((valueLen & 0x7f) << 24) + (lenBuff[0] << 16)
1167 + (lenBuff[1] << 8) + lenBuff[2];
1168 }
1169 /*
1170 * nameLen and valueLen are now valid; read the name and value
1171 * from stream and construct a standard environment entry.
1172 */
aadcc3c8 1173 nameValue = (char *)Malloc(nameLen + valueLen + 2);
0198fd3c 1174 if(FCGX_GetStr(nameValue, nameLen, stream) != nameLen) {
1175 SetError(stream, FCGX_PARAMS_ERROR);
1176 free(nameValue);
1177 return -1;
1178 }
1179 *(nameValue + nameLen) = '=';
1180 if(FCGX_GetStr(nameValue + nameLen + 1, valueLen, stream)
1181 != valueLen) {
1182 SetError(stream, FCGX_PARAMS_ERROR);
1183 free(nameValue);
1184 return -1;
1185 }
1186 *(nameValue + nameLen + valueLen + 1) = '\0';
1187 PutParam(paramsPtr, nameValue);
1188 }
1189 return 0;
1190}
569591e9 1191
0198fd3c 1192/*
1193 *----------------------------------------------------------------------
1194 *
1195 * MakeHeader --
1196 *
1197 * Constructs an FCGI_Header struct.
1198 *
1199 *----------------------------------------------------------------------
1200 */
1201static FCGI_Header MakeHeader(
1202 int type,
1203 int requestId,
1204 int contentLength,
1205 int paddingLength)
1206{
1207 FCGI_Header header;
1208 ASSERT(contentLength >= 0 && contentLength <= FCGI_MAX_LENGTH);
1209 ASSERT(paddingLength >= 0 && paddingLength <= 0xff);
1210 header.version = FCGI_VERSION_1;
611bc63f 1211 header.type = (unsigned char) type;
1212 header.requestIdB1 = (unsigned char) ((requestId >> 8) & 0xff);
1213 header.requestIdB0 = (unsigned char) ((requestId ) & 0xff);
1214 header.contentLengthB1 = (unsigned char) ((contentLength >> 8) & 0xff);
1215 header.contentLengthB0 = (unsigned char) ((contentLength ) & 0xff);
1216 header.paddingLength = (unsigned char) paddingLength;
0198fd3c 1217 header.reserved = 0;
1218 return header;
1219}
569591e9 1220
0198fd3c 1221/*
1222 *----------------------------------------------------------------------
1223 *
1224 * MakeEndRequestBody --
1225 *
1226 * Constructs an FCGI_EndRequestBody struct.
1227 *
1228 *----------------------------------------------------------------------
1229 */
1230static FCGI_EndRequestBody MakeEndRequestBody(
1231 int appStatus,
1232 int protocolStatus)
1233{
1234 FCGI_EndRequestBody body;
611bc63f 1235 body.appStatusB3 = (unsigned char) ((appStatus >> 24) & 0xff);
1236 body.appStatusB2 = (unsigned char) ((appStatus >> 16) & 0xff);
1237 body.appStatusB1 = (unsigned char) ((appStatus >> 8) & 0xff);
1238 body.appStatusB0 = (unsigned char) ((appStatus ) & 0xff);
1239 body.protocolStatus = (unsigned char) protocolStatus;
0198fd3c 1240 memset(body.reserved, 0, sizeof(body.reserved));
1241 return body;
1242}
569591e9 1243
0198fd3c 1244/*
1245 *----------------------------------------------------------------------
1246 *
1247 * MakeUnknownTypeBody --
1248 *
1249 * Constructs an FCGI_MakeUnknownTypeBody struct.
1250 *
1251 *----------------------------------------------------------------------
1252 */
1253static FCGI_UnknownTypeBody MakeUnknownTypeBody(
1254 int type)
1255{
1256 FCGI_UnknownTypeBody body;
611bc63f 1257 body.type = (unsigned char) type;
0198fd3c 1258 memset(body.reserved, 0, sizeof(body.reserved));
1259 return body;
1260}
569591e9 1261
0198fd3c 1262/*
1263 *----------------------------------------------------------------------
1264 *
1265 * AlignInt8 --
1266 *
1267 * Returns the smallest integer greater than or equal to n
1268 * that's a multiple of 8.
1269 *
1270 *----------------------------------------------------------------------
1271 */
1272static int AlignInt8(unsigned n) {
1273 return (n + 7) & (UINT_MAX - 7);
1274}
1275
1276/*
1277 *----------------------------------------------------------------------
1278 *
1279 * AlignPtr8 --
1280 *
1281 * Returns the smallest pointer greater than or equal to p
1282 * that's a multiple of 8.
1283 *
1284 *----------------------------------------------------------------------
1285 */
1286static unsigned char *AlignPtr8(unsigned char *p) {
1287 unsigned long u = (unsigned long) p;
1288 u = ((u + 7) & (ULONG_MAX - 7)) - u;
1289 return p + u;
1290}
569591e9 1291
0198fd3c 1292
1293/*
1294 * State associated with a stream
1295 */
1296typedef struct FCGX_Stream_Data {
1297 unsigned char *buff; /* buffer after alignment */
1298 int bufflen; /* number of bytes buff can store */
1299 unsigned char *mBuff; /* buffer as returned by Malloc */
1300 unsigned char *buffStop; /* reader: last valid byte + 1 of entire buffer.
1301 * stop generally differs from buffStop for
1302 * readers because of record structure.
1303 * writer: buff + bufflen */
1304 int type; /* reader: FCGI_PARAMS or FCGI_STDIN
1305 * writer: FCGI_STDOUT or FCGI_STDERR */
1306 int eorStop; /* reader: stop stream at end-of-record */
1307 int skip; /* reader: don't deliver content bytes */
1308 int contentLen; /* reader: bytes of unread content */
1309 int paddingLen; /* reader: bytes of unread padding */
1310 int isAnythingWritten; /* writer: data has been written to ipcFd */
1311 int rawWrite; /* writer: write data without stream headers */
5a7cc494 1312 FCGX_Request *reqDataPtr; /* request data not specific to one stream */
0198fd3c 1313} FCGX_Stream_Data;
569591e9 1314
0198fd3c 1315/*
1316 *----------------------------------------------------------------------
1317 *
1318 * WriteCloseRecords --
1319 *
1320 * Writes an EOF record for the stream content if necessary.
1321 * If this is the last writer to close, writes an FCGI_END_REQUEST
1322 * record.
1323 *
1324 *----------------------------------------------------------------------
1325 */
1326static void WriteCloseRecords(struct FCGX_Stream *stream)
1327{
aadcc3c8 1328 FCGX_Stream_Data *data = (FCGX_Stream_Data *)stream->data;
0198fd3c 1329 /*
1330 * Enter rawWrite mode so final records won't be encapsulated as
1331 * stream data.
1332 */
1333 data->rawWrite = TRUE;
1334 /*
1335 * Generate EOF for stream content if needed.
1336 */
1337 if(!(data->type == FCGI_STDERR
1338 && stream->wrNext == data->buff
1339 && !data->isAnythingWritten)) {
1340 FCGI_Header header;
1341 header = MakeHeader(data->type, data->reqDataPtr->requestId, 0, 0);
1342 FCGX_PutStr((char *) &header, sizeof(header), stream);
1343 };
1344 /*
1345 * Generate FCGI_END_REQUEST record if needed.
1346 */
1347 if(data->reqDataPtr->nWriters == 1) {
1348 FCGI_EndRequestRecord endRequestRecord;
1349 endRequestRecord.header = MakeHeader(FCGI_END_REQUEST,
1350 data->reqDataPtr->requestId,
1351 sizeof(endRequestRecord.body), 0);
1352 endRequestRecord.body = MakeEndRequestBody(
1353 data->reqDataPtr->appStatus, FCGI_REQUEST_COMPLETE);
1354 FCGX_PutStr((char *) &endRequestRecord,
1355 sizeof(endRequestRecord), stream);
1356 }
1357 data->reqDataPtr->nWriters--;
1358}
569591e9 1359
19d98b91 1360
1361
1362static int write_it_all(int fd, char *buf, int len)
1363{
1364 int wrote;
ae0319bf 1365
19d98b91 1366 while (len) {
1367 wrote = OS_Write(fd, buf, len);
1368 if (wrote < 0)
1369 return wrote;
1370 len -= wrote;
1371 buf += wrote;
1372 }
1373 return len;
1374}
1375
0198fd3c 1376/*
1377 *----------------------------------------------------------------------
1378 *
1379 * EmptyBuffProc --
1380 *
1381 * Encapsulates any buffered stream content in a FastCGI
1382 * record. Writes the data, making the buffer empty.
1383 *
1384 *----------------------------------------------------------------------
1385 */
1386static void EmptyBuffProc(struct FCGX_Stream *stream, int doClose)
1387{
aadcc3c8 1388 FCGX_Stream_Data *data = (FCGX_Stream_Data *)stream->data;
0198fd3c 1389 int cLen, eLen;
1390 /*
1391 * If the buffer contains stream data, fill in the header.
1392 * Pad the record to a multiple of 8 bytes in length. Padding
1393 * can't overflow the buffer because the buffer is a multiple
1394 * of 8 bytes in length. If the buffer contains no stream
1395 * data, reclaim the space reserved for the header.
1396 */
1397 if(!data->rawWrite) {
1398 cLen = stream->wrNext - data->buff - sizeof(FCGI_Header);
1399 if(cLen > 0) {
1400 eLen = AlignInt8(cLen);
1401 /*
1402 * Giving the padding a well-defined value keeps Purify happy.
1403 */
1404 memset(stream->wrNext, 0, eLen - cLen);
1405 stream->wrNext += eLen - cLen;
1406 *((FCGI_Header *) data->buff)
1407 = MakeHeader(data->type,
1408 data->reqDataPtr->requestId, cLen, eLen - cLen);
1409 } else {
1410 stream->wrNext = data->buff;
1411 }
1412 }
1413 if(doClose) {
1414 WriteCloseRecords(stream);
1415 };
19d98b91 1416 if (stream->wrNext != data->buff) {
0198fd3c 1417 data->isAnythingWritten = TRUE;
19d98b91 1418 if (write_it_all(data->reqDataPtr->ipcFd, (char *)data->buff, stream->wrNext - data->buff) < 0) {
0198fd3c 1419 SetError(stream, OS_Errno);
1420 return;
1421 }
1422 stream->wrNext = data->buff;
1423 }
1424 /*
1425 * The buffer is empty.
1426 */
1427 if(!data->rawWrite) {
1428 stream->wrNext += sizeof(FCGI_Header);
1429 }
1430}
569591e9 1431
0198fd3c 1432/*
1433 * Return codes for Process* functions
1434 */
1435#define STREAM_RECORD 0
1436#define SKIP 1
1437#define BEGIN_RECORD 2
1438#define MGMT_RECORD 3
1439
1440/*
1441 *----------------------------------------------------------------------
1442 *
1443 * ProcessManagementRecord --
1444 *
1445 * Reads and responds to a management record. The only type of
1446 * management record this library understands is FCGI_GET_VALUES.
1447 * The only variables that this library's FCGI_GET_VALUES
1448 * understands are FCGI_MAX_CONNS, FCGI_MAX_REQS, and FCGI_MPXS_CONNS.
1449 * Ignore other FCGI_GET_VALUES variables; respond to other
1450 * management records with a FCGI_UNKNOWN_TYPE record.
1451 *
1452 *----------------------------------------------------------------------
1453 */
1454static int ProcessManagementRecord(int type, FCGX_Stream *stream)
1455{
aadcc3c8 1456 FCGX_Stream_Data *data = (FCGX_Stream_Data *)stream->data;
16fe131b 1457 ParamsPtr paramsPtr;
0198fd3c 1458 char **pPtr;
1459 char response[64]; /* 64 = 8 + 3*(1+1+14+1)* + padding */
1460 char *responseP = &response[FCGI_HEADER_LEN];
611bc63f 1461 char *name, value = '\0';
0198fd3c 1462 int len, paddedLen;
1463 if(type == FCGI_GET_VALUES) {
16fe131b 1464 paramsPtr = NewParams(3);
0198fd3c 1465 ReadParams(paramsPtr, stream);
1466 if((FCGX_GetError(stream) != 0) || (data->contentLen != 0)) {
1467 FreeParams(&paramsPtr);
1468 return FCGX_PROTOCOL_ERROR;
1469 }
1470 for (pPtr = paramsPtr->vec; pPtr < paramsPtr->cur; pPtr++) {
1471 name = *pPtr;
1472 *(strchr(name, '=')) = '\0';
1473 if(strcmp(name, FCGI_MAX_CONNS) == 0) {
1474 value = '1';
1475 } else if(strcmp(name, FCGI_MAX_REQS) == 0) {
1476 value = '1';
1477 } else if(strcmp(name, FCGI_MPXS_CONNS) == 0) {
1478 value = '0';
1479 } else {
1480 name = NULL;
1481 }
1482 if(name != NULL) {
1483 len = strlen(name);
1484 sprintf(responseP, "%c%c%s%c", len, 1, name, value);
1485 responseP += len + 3;
1486 }
1487 }
1488 len = responseP - &response[FCGI_HEADER_LEN];
1489 paddedLen = AlignInt8(len);
1490 *((FCGI_Header *) response)
1491 = MakeHeader(FCGI_GET_VALUES_RESULT, FCGI_NULL_REQUEST_ID,
1492 len, paddedLen - len);
1493 FreeParams(&paramsPtr);
1494 } else {
1495 paddedLen = len = sizeof(FCGI_UnknownTypeBody);
1496 ((FCGI_UnknownTypeRecord *) response)->header
1497 = MakeHeader(FCGI_UNKNOWN_TYPE, FCGI_NULL_REQUEST_ID,
1498 len, 0);
1499 ((FCGI_UnknownTypeRecord *) response)->body
1500 = MakeUnknownTypeBody(type);
1501 }
19d98b91 1502 if (write_it_all(data->reqDataPtr->ipcFd, response, FCGI_HEADER_LEN + paddedLen) < 0) {
0198fd3c 1503 SetError(stream, OS_Errno);
1504 return -1;
1505 }
19d98b91 1506
0198fd3c 1507 return MGMT_RECORD;
1508}
569591e9 1509
0198fd3c 1510/*
1511 *----------------------------------------------------------------------
1512 *
1513 * ProcessBeginRecord --
1514 *
1515 * Reads an FCGI_BEGIN_REQUEST record.
1516 *
1517 * Results:
1518 * BEGIN_RECORD for normal return. FCGX_PROTOCOL_ERROR for
1519 * protocol error. SKIP for attempt to multiplex
1520 * connection. -1 for error from write (errno in stream).
1521 *
1522 * Side effects:
1523 * In case of BEGIN_RECORD return, stores requestId, role,
1524 * keepConnection values, and sets isBeginProcessed = TRUE.
1525 *
1526 *----------------------------------------------------------------------
1527 */
1528static int ProcessBeginRecord(int requestId, FCGX_Stream *stream)
1529{
aadcc3c8 1530 FCGX_Stream_Data *data = (FCGX_Stream_Data *)stream->data;
0198fd3c 1531 FCGI_BeginRequestBody body;
1532 if(requestId == 0 || data->contentLen != sizeof(body)) {
1533 return FCGX_PROTOCOL_ERROR;
1534 }
1535 if(data->reqDataPtr->isBeginProcessed) {
1536 /*
1537 * The Web server is multiplexing the connection. This library
1538 * doesn't know how to handle multiplexing, so respond with
1539 * FCGI_END_REQUEST{protocolStatus = FCGI_CANT_MPX_CONN}
1540 */
1541 FCGI_EndRequestRecord endRequestRecord;
1542 endRequestRecord.header = MakeHeader(FCGI_END_REQUEST,
1543 requestId, sizeof(endRequestRecord.body), 0);
1544 endRequestRecord.body
1545 = MakeEndRequestBody(0, FCGI_CANT_MPX_CONN);
19d98b91 1546 if (write_it_all(data->reqDataPtr->ipcFd, (char *)&endRequestRecord, sizeof(endRequestRecord)) < 0) {
0198fd3c 1547 SetError(stream, OS_Errno);
1548 return -1;
1549 }
19d98b91 1550
0198fd3c 1551 return SKIP;
1552 }
1553 /*
1554 * Accept this new request. Read the record body.
1555 */
1556 data->reqDataPtr->requestId = requestId;
1557 if(FCGX_GetStr((char *) &body, sizeof(body), stream)
1558 != sizeof(body)) {
1559 return FCGX_PROTOCOL_ERROR;
1560 }
1561 data->reqDataPtr->keepConnection = (body.flags & FCGI_KEEP_CONN);
1562 data->reqDataPtr->role = (body.roleB1 << 8) + body.roleB0;
1563 data->reqDataPtr->isBeginProcessed = TRUE;
1564 return BEGIN_RECORD;
1565}
569591e9 1566
0198fd3c 1567/*
1568 *----------------------------------------------------------------------
1569 *
1570 * ProcessHeader --
1571 *
1572 * Interprets FCGI_Header. Processes FCGI_BEGIN_REQUEST and
1573 * management records here; extracts information from stream
1574 * records (FCGI_PARAMS, FCGI_STDIN) into stream.
1575 *
1576 * Results:
1577 * >= 0 for a normal return, < 0 for error
1578 *
1579 * Side effects:
1580 * XXX: Many (more than there used to be).
1581 * If !stream->isRequestIdSet, ProcessHeader initializes
1582 * stream->requestId from header and sets stream->isRequestIdSet
1583 * to TRUE. ProcessHeader also sets stream->contentLen to header's
1584 * contentLength, and sets stream->paddingLen to the header's
1585 * paddingLength.
1586 *
1587 *----------------------------------------------------------------------
1588 */
1589static int ProcessHeader(FCGI_Header header, FCGX_Stream *stream)
1590{
aadcc3c8 1591 FCGX_Stream_Data *data = (FCGX_Stream_Data *)stream->data;
0198fd3c 1592 int requestId;
1593 if(header.version != FCGI_VERSION_1) {
1594 return FCGX_UNSUPPORTED_VERSION;
1595 }
1596 requestId = (header.requestIdB1 << 8)
1597 + header.requestIdB0;
1598 data->contentLen = (header.contentLengthB1 << 8)
1599 + header.contentLengthB0;
1600 data->paddingLen = header.paddingLength;
1601 if(header.type == FCGI_BEGIN_REQUEST) {
1602 return ProcessBeginRecord(requestId, stream);
1603 }
1604 if(requestId == FCGI_NULL_REQUEST_ID) {
1605 return ProcessManagementRecord(header.type, stream);
1606 }
1607 if(requestId != data->reqDataPtr->requestId) {
1608 return SKIP;
1609 }
1610 if(header.type != data->type) {
1611 return FCGX_PROTOCOL_ERROR;
1612 }
1613 return STREAM_RECORD;
1614}
569591e9 1615
0198fd3c 1616/*
1617 *----------------------------------------------------------------------
1618 *
1619 * FillBuffProc --
1620 *
1621 * Reads bytes from the ipcFd, supplies bytes to a stream client.
1622 *
1623 *----------------------------------------------------------------------
1624 */
1625static void FillBuffProc(FCGX_Stream *stream)
1626{
aadcc3c8 1627 FCGX_Stream_Data *data = (FCGX_Stream_Data *)stream->data;
0198fd3c 1628 FCGI_Header header;
1629 int headerLen = 0;
1630 int status, count;
1631
1632 for (;;) {
1633 /*
1634 * If data->buff is empty, do a read.
1635 */
1636 if(stream->rdNext == data->buffStop) {
1637 count = OS_Read(data->reqDataPtr->ipcFd, (char *)data->buff,
1638 data->bufflen);
1639 if(count <= 0) {
1640 SetError(stream, (count == 0 ? FCGX_PROTOCOL_ERROR : OS_Errno));
1641 return;
1642 }
1643 stream->rdNext = data->buff;
1644 data->buffStop = data->buff + count;
1645 }
1646 /*
1647 * Now data->buff is not empty. If the current record contains
1648 * more content bytes, deliver all that are present in data->buff.
1649 */
1650 if(data->contentLen > 0) {
1651 count = min(data->contentLen, data->buffStop - stream->rdNext);
1652 data->contentLen -= count;
1653 if(!data->skip) {
1654 stream->wrNext = stream->stop = stream->rdNext + count;
1655 return;
1656 } else {
1657 stream->rdNext += count;
1658 if(data->contentLen > 0) {
1659 continue;
1660 } else {
1661 data->skip = FALSE;
1662 }
1663 }
1664 }
1665 /*
1666 * If the current record (whose content has been fully consumed by
1667 * the client) was padded, skip over the padding bytes.
1668 */
1669 if(data->paddingLen > 0) {
1670 count = min(data->paddingLen, data->buffStop - stream->rdNext);
1671 data->paddingLen -= count;
1672 stream->rdNext += count;
1673 if(data->paddingLen > 0) {
1674 continue;
1675 }
1676 }
1677 /*
1678 * All done with the current record, including the padding.
1679 * If we're in a recursive call from ProcessHeader, deliver EOF.
1680 */
1681 if(data->eorStop) {
1682 stream->stop = stream->rdNext;
1683 stream->isClosed = TRUE;
1684 return;
1685 }
1686 /*
1687 * Fill header with bytes from the input buffer.
1688 */
1689 count = min((int)sizeof(header) - headerLen,
1690 data->buffStop - stream->rdNext);
1691 memcpy(((char *)(&header)) + headerLen, stream->rdNext, count);
1692 headerLen += count;
1693 stream->rdNext += count;
1694 if(headerLen < sizeof(header)) {
1695 continue;
1696 };
1697 headerLen = 0;
1698 /*
1699 * Interpret header. eorStop prevents ProcessHeader from reading
1700 * past the end-of-record when using stream to read content.
1701 */
1702 data->eorStop = TRUE;
1703 stream->stop = stream->rdNext;
1704 status = ProcessHeader(header, stream);
1705 data->eorStop = FALSE;
1706 stream->isClosed = FALSE;
1707 switch(status) {
1708 case STREAM_RECORD:
1709 /*
1710 * If this stream record header marked the end of stream
1711 * data deliver EOF to the stream client, otherwise loop
1712 * and deliver data.
1713 *
1714 * XXX: If this is final stream and
1715 * stream->rdNext != data->buffStop, buffered
1716 * data is next request (server pipelining)?
1717 */
1718 if(data->contentLen == 0) {
1719 stream->wrNext = stream->stop = stream->rdNext;
1720 stream->isClosed = TRUE;
1721 return;
1722 }
1723 break;
1724 case SKIP:
1725 data->skip = TRUE;
1726 break;
1727 case BEGIN_RECORD:
1728 /*
1729 * If this header marked the beginning of a new
1730 * request, return role information to caller.
1731 */
1732 return;
1733 break;
1734 case MGMT_RECORD:
1735 break;
1736 default:
1737 ASSERT(status < 0);
1738 SetError(stream, status);
1739 return;
1740 break;
1741 }
1742 }
1743}
569591e9 1744
0198fd3c 1745/*
1746 *----------------------------------------------------------------------
1747 *
1748 * NewStream --
1749 *
1750 * Creates a stream to read or write from an open ipcFd.
1751 * The stream performs reads/writes of up to bufflen bytes.
1752 *
1753 *----------------------------------------------------------------------
1754 */
1755static FCGX_Stream *NewStream(
5a7cc494 1756 FCGX_Request *reqDataPtr, int bufflen, int isReader, int streamType)
0198fd3c 1757{
1758 /*
1759 * XXX: It would be a lot cleaner to have a NewStream that only
1760 * knows about the type FCGX_Stream, with all other
1761 * necessary data passed in. It appears that not just
1762 * data and the two procs are needed for initializing stream,
1763 * but also data->buff and data->buffStop. This has implications
1764 * for procs that want to swap buffers, too.
1765 */
aadcc3c8 1766 FCGX_Stream *stream = (FCGX_Stream *)Malloc(sizeof(FCGX_Stream));
1767 FCGX_Stream_Data *data = (FCGX_Stream_Data *)Malloc(sizeof(FCGX_Stream_Data));
0198fd3c 1768 data->reqDataPtr = reqDataPtr;
1769 bufflen = AlignInt8(min(max(bufflen, 32), FCGI_MAX_LENGTH + 1));
1770 data->bufflen = bufflen;
aadcc3c8 1771 data->mBuff = (unsigned char *)Malloc(bufflen);
0198fd3c 1772 data->buff = AlignPtr8(data->mBuff);
1773 if(data->buff != data->mBuff) {
1774 data->bufflen -= 8;
1775 }
1776 if(isReader) {
1777 data->buffStop = data->buff;
1778 } else {
1779 data->buffStop = data->buff + data->bufflen;
1780 }
1781 data->type = streamType;
1782 data->eorStop = FALSE;
1783 data->skip = FALSE;
1784 data->contentLen = 0;
1785 data->paddingLen = 0;
1786 data->isAnythingWritten = FALSE;
1787 data->rawWrite = FALSE;
1788
1789 stream->data = data;
1790 stream->isReader = isReader;
1791 stream->isClosed = FALSE;
1792 stream->wasFCloseCalled = FALSE;
1793 stream->FCGI_errno = 0;
1794 if(isReader) {
1795 stream->fillBuffProc = FillBuffProc;
1796 stream->emptyBuffProc = NULL;
1797 stream->rdNext = data->buff;
1798 stream->stop = stream->rdNext;
1799 stream->stopUnget = data->buff;
1800 stream->wrNext = stream->stop;
1801 } else {
1802 stream->fillBuffProc = NULL;
1803 stream->emptyBuffProc = EmptyBuffProc;
1804 stream->wrNext = data->buff + sizeof(FCGI_Header);
1805 stream->stop = data->buffStop;
1806 stream->stopUnget = NULL;
1807 stream->rdNext = stream->stop;
1808 }
1809 return stream;
1810}
569591e9 1811
0198fd3c 1812/*
1813 *----------------------------------------------------------------------
1814 *
569591e9 1815 * FCGX_FreeStream --
0198fd3c 1816 *
1817 * Frees all storage allocated when *streamPtr was created,
1818 * and nulls out *streamPtr.
1819 *
1820 *----------------------------------------------------------------------
1821 */
569591e9 1822void FCGX_FreeStream(FCGX_Stream **streamPtr)
0198fd3c 1823{
1824 FCGX_Stream *stream = *streamPtr;
1825 FCGX_Stream_Data *data;
1826 if(stream == NULL) {
1827 return;
1828 }
aadcc3c8 1829 data = (FCGX_Stream_Data *)stream->data;
0198fd3c 1830 data->reqDataPtr = NULL;
1831 free(data->mBuff);
1832 free(data);
1833 free(stream);
1834 *streamPtr = NULL;
1835}
569591e9 1836
0198fd3c 1837/*
1838 *----------------------------------------------------------------------
1839 *
1840 * SetReaderType --
1841 *
1842 * Re-initializes the stream to read data of the specified type.
1843 *
1844 *----------------------------------------------------------------------
1845 */
1846static FCGX_Stream *SetReaderType(FCGX_Stream *stream, int streamType)
1847{
aadcc3c8 1848 FCGX_Stream_Data *data = (FCGX_Stream_Data *)stream->data;
0198fd3c 1849 ASSERT(stream->isReader);
1850 data->type = streamType;
1851 data->eorStop = FALSE;
1852 data->skip = FALSE;
1853 data->contentLen = 0;
1854 data->paddingLen = 0;
1855 stream->wrNext = stream->stop = stream->rdNext;
1856 stream->isClosed = FALSE;
1857 return stream;
1858}
569591e9 1859
0198fd3c 1860/*
1861 *----------------------------------------------------------------------
1862 *
1863 * NewReader --
1864 *
1865 * Creates a stream to read streamType records for the given
1866 * request. The stream performs OS reads of up to bufflen bytes.
1867 *
1868 *----------------------------------------------------------------------
1869 */
5a7cc494 1870static FCGX_Stream *NewReader(FCGX_Request *reqDataPtr, int bufflen, int streamType)
0198fd3c 1871{
1872 return NewStream(reqDataPtr, bufflen, TRUE, streamType);
1873}
1874
0198fd3c 1875/*
1876 *----------------------------------------------------------------------
1877 *
1878 * NewWriter --
1879 *
1880 * Creates a stream to write streamType FastCGI records, using
1881 * the ipcFd and RequestId contained in *reqDataPtr.
1882 * The stream performs OS writes of up to bufflen bytes.
1883 *
1884 *----------------------------------------------------------------------
1885 */
5a7cc494 1886static FCGX_Stream *NewWriter(FCGX_Request *reqDataPtr, int bufflen, int streamType)
0198fd3c 1887{
1888 return NewStream(reqDataPtr, bufflen, FALSE, streamType);
1889}
1890
0198fd3c 1891/*
1892 *----------------------------------------------------------------------
1893 *
569591e9 1894 * FCGX_CreateWriter --
0198fd3c 1895 *
1896 * Creates a stream to write streamType FastCGI records, using
1897 * the given ipcFd and request Id. This function is provided
1898 * for use by cgi-fcgi. In order to be defensive against misuse,
1899 * this function leaks a little storage; cgi-fcgi doesn't care.
1900 *
1901 *----------------------------------------------------------------------
1902 */
569591e9 1903FCGX_Stream *FCGX_CreateWriter(
0198fd3c 1904 int ipcFd,
1905 int requestId,
1906 int bufflen,
1907 int streamType)
1908{
aadcc3c8 1909 FCGX_Request *reqDataPtr = (FCGX_Request *)Malloc(sizeof(FCGX_Request));
0198fd3c 1910 reqDataPtr->ipcFd = ipcFd;
1911 reqDataPtr->requestId = requestId;
1912 /*
1913 * Suppress writing an FCGI_END_REQUEST record.
1914 */
1915 reqDataPtr->nWriters = 2;
1916 return NewWriter(reqDataPtr, bufflen, streamType);
1917}
569591e9 1918
0198fd3c 1919/*
1920 *======================================================================
1921 * Control
1922 *======================================================================
1923 */
1924
0198fd3c 1925/*
1926 *----------------------------------------------------------------------
1927 *
1928 * FCGX_IsCGI --
1929 *
1930 * This routine determines if the process is running as a CGI or
1931 * FastCGI process. The distinction is made by determining whether
1932 * FCGI_LISTENSOCK_FILENO is a listener ipcFd or the end of a
1933 * pipe (ie. standard in).
1934 *
1935 * Results:
1936 * TRUE if the process is a CGI process, FALSE if FastCGI.
1937 *
0198fd3c 1938 *----------------------------------------------------------------------
1939 */
1940int FCGX_IsCGI(void)
1941{
5a7cc494 1942 if (isFastCGI != -1) {
1943 return !isFastCGI;
0198fd3c 1944 }
ae0319bf 1945
5a7cc494 1946 if (!libInitialized) {
1947 int rc = FCGX_Init();
1948 if (rc) {
1949 /* exit() isn't great, but hey */
1950 exit((rc < 0) ? rc : -rc);
1951 }
ae0319bf 1952 }
0198fd3c 1953
0b7c9662 1954 isFastCGI = OS_IsFcgi(FCGI_LISTENSOCK_FILENO);
5a7cc494 1955
1956 return !isFastCGI;
0198fd3c 1957}
569591e9 1958
0198fd3c 1959/*
1960 *----------------------------------------------------------------------
1961 *
1962 * FCGX_Finish --
1963 *
1964 * Finishes the current request from the HTTP server.
1965 *
1966 * Side effects:
1967 *
1968 * Finishes the request accepted by (and frees any
1969 * storage allocated by) the previous call to FCGX_Accept.
1970 *
1971 * DO NOT retain pointers to the envp array or any strings
1972 * contained in it (e.g. to the result of calling FCGX_GetParam),
1973 * since these will be freed by the next call to FCGX_Finish
1974 * or FCGX_Accept.
1975 *
1976 *----------------------------------------------------------------------
1977 */
0198fd3c 1978
1979void FCGX_Finish(void)
1980{
faca4b3a 1981 FCGX_Finish_r(&the_request);
5a7cc494 1982}
1983
1984/*
1985 *----------------------------------------------------------------------
1986 *
1987 * FCGX_Finish_r --
1988 *
1989 * Finishes the current request from the HTTP server.
1990 *
1991 * Side effects:
1992 *
1993 * Finishes the request accepted by (and frees any
1994 * storage allocated by) the previous call to FCGX_Accept.
1995 *
1996 * DO NOT retain pointers to the envp array or any strings
1997 * contained in it (e.g. to the result of calling FCGX_GetParam),
1998 * since these will be freed by the next call to FCGX_Finish
1999 * or FCGX_Accept.
2000 *
2001 *----------------------------------------------------------------------
2002 */
2003void FCGX_Finish_r(FCGX_Request *reqDataPtr)
2004{
bef7e0fc 2005 int close;
2006
5a7cc494 2007 if (reqDataPtr == NULL) {
2008 return;
2009 }
2010
bef7e0fc 2011 close = !reqDataPtr->keepConnection;
2012
59bfcb87 2013 /* This should probably use a 'status' member instead of 'in' */
0b7c9662 2014 if (reqDataPtr->in) {
bef7e0fc 2015 close |= FCGX_FClose(reqDataPtr->err);
2016 close |= FCGX_FClose(reqDataPtr->out);
c4d74207 2017 close |= FCGX_GetError(reqDataPtr->in);
5a7cc494 2018
21472f7d 2019 /* discard any remaining data in input stream on persistent connections */
2020 if (!close && !reqDataPtr->in->isClosed && reqDataPtr->keepConnection) {
c4d74207 2021 FCGX_Stream *stream = reqDataPtr->in;
2022
2023 do {
2024 stream->rdNext = stream->stop;
2025 stream->fillBuffProc(stream);
2026 } while (!stream->isClosed);
2027
2028 close |= FCGX_GetError(stream);
2029 }
8462b1ec 2030 }
5a7cc494 2031
bef7e0fc 2032 FCGX_Free(reqDataPtr, close);
8462b1ec 2033}
59bfcb87 2034
bef7e0fc 2035void FCGX_Free(FCGX_Request * request, int close)
8462b1ec 2036{
2037 if (request == NULL)
2038 return;
5a7cc494 2039
569591e9 2040 FCGX_FreeStream(&request->in);
2041 FCGX_FreeStream(&request->out);
2042 FCGX_FreeStream(&request->err);
8462b1ec 2043 FreeParams(&request->paramsPtr);
5a7cc494 2044
bef7e0fc 2045 if (close) {
2a7273a1 2046 OS_IpcClose(request->ipcFd, ! request->detached);
8462b1ec 2047 request->ipcFd = -1;
2a7273a1 2048 request->detached = 0;
0198fd3c 2049 }
2050}
5a7cc494 2051
0b7c9662 2052int FCGX_OpenSocket(const char *path, int backlog)
2053{
165bb74e 2054 int rc = OS_CreateLocalIpcFd(path, backlog);
2055 if (rc == FCGI_LISTENSOCK_FILENO && isFastCGI == 0) {
2056 /* XXX probably need to call OS_LibInit() again for Win */
2057 isFastCGI = 1;
2058 }
3da6011f 2059 return rc;
0b7c9662 2060}
2061
2062int FCGX_InitRequest(FCGX_Request *request, int sock, int flags)
5a7cc494 2063{
2064 memset(request, 0, sizeof(FCGX_Request));
0b7c9662 2065
2066 /* @@@ Should check that sock is open and listening */
2067 request->listen_sock = sock;
2068
2069 /* @@@ Should validate against "known" flags */
2070 request->flags = flags;
2071
8c74d6f3 2072 request->ipcFd = -1;
2073
0b7c9662 2074 return 0;
5a7cc494 2075}
2076
2077/*
2078 *----------------------------------------------------------------------
2079 *
2080 * FCGX_Init --
2081 *
2082 * Initilize the FCGX library. This is called by FCGX_Accept()
2083 * but must be called by the user when using FCGX_Accept_r().
2084 *
2085 * Results:
2086 * 0 for successful call.
2087 *
2088 *----------------------------------------------------------------------
2089 */
2090int FCGX_Init(void)
2091{
2092 char *p;
ae0319bf 2093
5a7cc494 2094 if (libInitialized) {
2095 return 0;
2096 }
2097
faca4b3a 2098 FCGX_InitRequest(&the_request, FCGI_LISTENSOCK_FILENO, 0);
5a7cc494 2099
2100 if (OS_LibInit(NULL) == -1) {
2101 return OS_Errno ? OS_Errno : -9997;
2102 }
2103
2104 p = getenv("FCGI_WEB_SERVER_ADDRS");
faca4b3a 2105 webServerAddressList = p ? StringCopy(p) : NULL;
ae0319bf 2106
5a7cc494 2107 libInitialized = 1;
2108 return 0;
2109}
2110
0198fd3c 2111/*
2112 *----------------------------------------------------------------------
2113 *
2114 * FCGX_Accept --
2115 *
2116 * Accepts a new request from the HTTP server.
2117 *
2118 * Results:
2119 * 0 for successful call, -1 for error.
2120 *
2121 * Side effects:
2122 *
2123 * Finishes the request accepted by (and frees any
2124 * storage allocated by) the previous call to FCGX_Accept.
2125 * Creates input, output, and error streams and
2126 * assigns them to *in, *out, and *err respectively.
2127 * Creates a parameters data structure to be accessed
2128 * via getenv(3) (if assigned to environ) or by FCGX_GetParam
2129 * and assigns it to *envp.
2130 *
2131 * DO NOT retain pointers to the envp array or any strings
2132 * contained in it (e.g. to the result of calling FCGX_GetParam),
2133 * since these will be freed by the next call to FCGX_Finish
2134 * or FCGX_Accept.
2135 *
2136 *----------------------------------------------------------------------
2137 */
0198fd3c 2138
2139int FCGX_Accept(
2140 FCGX_Stream **in,
2141 FCGX_Stream **out,
2142 FCGX_Stream **err,
2143 FCGX_ParamArray *envp)
2144{
165bb74e 2145 int rc;
2146
611bc63f 2147 if (! libInitialized) {
2148 rc = FCGX_Init();
2149 if (rc) {
2150 return rc;
5a7cc494 2151 }
ae0319bf 2152 }
0198fd3c 2153
faca4b3a 2154 rc = FCGX_Accept_r(&the_request);
165bb74e 2155
faca4b3a 2156 *in = the_request.in;
2157 *out = the_request.out;
2158 *err = the_request.err;
2159 *envp = the_request.envp;
165bb74e 2160
2161 return rc;
5a7cc494 2162}
0198fd3c 2163
5a7cc494 2164/*
2165 *----------------------------------------------------------------------
2166 *
2167 * FCGX_Accept_r --
2168 *
2169 * Accepts a new request from the HTTP server.
2170 *
2171 * Results:
2172 * 0 for successful call, -1 for error.
2173 *
2174 * Side effects:
2175 *
2176 * Finishes the request accepted by (and frees any
2177 * storage allocated by) the previous call to FCGX_Accept.
2178 * Creates input, output, and error streams and
2179 * assigns them to *in, *out, and *err respectively.
2180 * Creates a parameters data structure to be accessed
2181 * via getenv(3) (if assigned to environ) or by FCGX_GetParam
2182 * and assigns it to *envp.
2183 *
2184 * DO NOT retain pointers to the envp array or any strings
2185 * contained in it (e.g. to the result of calling FCGX_GetParam),
2186 * since these will be freed by the next call to FCGX_Finish
2187 * or FCGX_Accept.
2188 *
2189 *----------------------------------------------------------------------
2190 */
0b7c9662 2191int FCGX_Accept_r(FCGX_Request *reqDataPtr)
5a7cc494 2192{
2193 if (!libInitialized) {
2194 return -9998;
0198fd3c 2195 }
5a7cc494 2196
2197 /* Finish the current request, if any. */
2198 FCGX_Finish_r(reqDataPtr);
2199
2200 for (;;) {
0198fd3c 2201 /*
2202 * If a connection isn't open, accept a new connection (blocking).
2203 * If an OS error occurs in accepting the connection,
2204 * return -1 to the caller, who should exit.
2205 */
5a7cc494 2206 if (reqDataPtr->ipcFd < 0) {
0b7c9662 2207 int fail_on_intr = reqDataPtr->flags & FCGI_FAIL_ACCEPT_ON_INTR;
2208
2209 reqDataPtr->ipcFd = OS_Accept(reqDataPtr->listen_sock, fail_on_intr, webServerAddressList);
5a7cc494 2210 if (reqDataPtr->ipcFd < 0) {
2211 return (errno > 0) ? (0 - errno) : -9999;
2212 }
2213 }
0198fd3c 2214 /*
2215 * A connection is open. Read from the connection in order to
2216 * get the request's role and environment. If protocol or other
2217 * errors occur, close the connection and try again.
2218 */
2219 reqDataPtr->isBeginProcessed = FALSE;
0b7c9662 2220 reqDataPtr->in = NewReader(reqDataPtr, 8192, 0);
2221 FillBuffProc(reqDataPtr->in);
0198fd3c 2222 if(!reqDataPtr->isBeginProcessed) {
2223 goto TryAgain;
2224 }
2225 {
2226 char *roleStr;
2227 switch(reqDataPtr->role) {
2228 case FCGI_RESPONDER:
2229 roleStr = "FCGI_ROLE=RESPONDER";
2230 break;
2231 case FCGI_AUTHORIZER:
2232 roleStr = "FCGI_ROLE=AUTHORIZER";
2233 break;
2234 case FCGI_FILTER:
2235 roleStr = "FCGI_ROLE=FILTER";
2236 break;
2237 default:
2238 goto TryAgain;
2239 }
2240 reqDataPtr->paramsPtr = NewParams(30);
2241 PutParam(reqDataPtr->paramsPtr, StringCopy(roleStr));
2242 }
0b7c9662 2243 SetReaderType(reqDataPtr->in, FCGI_PARAMS);
2244 if(ReadParams(reqDataPtr->paramsPtr, reqDataPtr->in) >= 0) {
0198fd3c 2245 /*
2246 * Finished reading the environment. No errors occurred, so
2247 * leave the connection-retry loop.
2248 */
2249 break;
2250 }
eff1a9bb 2251
0198fd3c 2252 /*
2253 * Close the connection and try again.
2254 */
eff1a9bb 2255TryAgain:
bef7e0fc 2256 FCGX_Free(reqDataPtr, 1);
eff1a9bb 2257
0198fd3c 2258 } /* for (;;) */
2259 /*
2260 * Build the remaining data structures representing the new
2261 * request and return successfully to the caller.
2262 */
0b7c9662 2263 SetReaderType(reqDataPtr->in, FCGI_STDIN);
2264 reqDataPtr->out = NewWriter(reqDataPtr, 8192, FCGI_STDOUT);
2265 reqDataPtr->err = NewWriter(reqDataPtr, 512, FCGI_STDERR);
0198fd3c 2266 reqDataPtr->nWriters = 2;
165bb74e 2267 reqDataPtr->envp = reqDataPtr->paramsPtr->vec;
0198fd3c 2268 return 0;
2269}
569591e9 2270
0198fd3c 2271/*
2272 *----------------------------------------------------------------------
2273 *
2274 * FCGX_StartFilterData --
2275 *
2276 * stream is an input stream for a FCGI_FILTER request.
2277 * stream is positioned at EOF on FCGI_STDIN.
2278 * Repositions stream to the start of FCGI_DATA.
2279 * If the preconditions are not met (e.g. FCGI_STDIN has not
2280 * been read to EOF) sets the stream error code to
2281 * FCGX_CALL_SEQ_ERROR.
2282 *
2283 * Results:
ae0319bf 2284 * 0 for a normal return, < 0 for error
0198fd3c 2285 *
2286 *----------------------------------------------------------------------
2287 */
2288
2289int FCGX_StartFilterData(FCGX_Stream *stream)
2290{
aadcc3c8 2291 FCGX_Stream_Data *data = (FCGX_Stream_Data *)stream->data;
0198fd3c 2292 if(data->reqDataPtr->role != FCGI_FILTER
2293 || !stream->isReader
2294 || !stream->isClosed
2295 || data->type != FCGI_STDIN) {
2296 SetError(stream, FCGX_CALL_SEQ_ERROR);
2297 return -1;
2298 }
faca4b3a 2299 SetReaderType(stream, FCGI_DATA);
0198fd3c 2300 return 0;
2301}
569591e9 2302
0198fd3c 2303/*
2304 *----------------------------------------------------------------------
2305 *
2306 * FCGX_SetExitStatus --
2307 *
2308 * Sets the exit status for stream's request. The exit status
2309 * is the status code the request would have exited with, had
2310 * the request been run as a CGI program. You can call
2311 * SetExitStatus several times during a request; the last call
2312 * before the request ends determines the value.
2313 *
2314 *----------------------------------------------------------------------
2315 */
2316
2317void FCGX_SetExitStatus(int status, FCGX_Stream *stream)
2318{
aadcc3c8 2319 FCGX_Stream_Data *data = (FCGX_Stream_Data *)stream->data;
0198fd3c 2320 data->reqDataPtr->appStatus = status;
2321}
5a7cc494 2322
2a7273a1 2323
2324int
2325FCGX_Attach(FCGX_Request * r)
2326{
2327 r->detached = FALSE;
2328 return 0;
2329}
2330
2331
2332int
2333FCGX_Detach(FCGX_Request * r)
2334{
2335 if (r->ipcFd <= 0)
2336 {
2337 return -1;
2338 }
2339
2340 r->detached = TRUE;
2341 return 0;
2342}