4 * FastCGI application library: request-at-a-time
7 * Copyright (c) 1996 Open Market, Inc.
9 * See the file "LICENSE.TERMS" for information on usage and redistribution
10 * of this file, and for a DISCLAIMER OF ALL WARRANTIES.
15 static const char rcsid[] = "$Id: fcgiapp.c,v 1.3 1999/02/12 00:46:41 roberts Exp $";
19 #define DLLAPI __declspec(dllexport)
23 #include <sys/types.h>
24 #ifdef HAVE_SYS_TIME_H
28 #include "fcgi_config.h"
36 #include <memory.h> /* for memchr() */
40 #ifdef HAVE_SYS_SOCKET_H
41 #include <sys/socket.h> /* for getpeername */
43 #include <fcntl.h> /* for fcntl */
47 #include "fcgiappmisc.h"
52 * This is a workaround for one version of the HP C compiler
53 * (c89 on HP-UX 9.04, also Stratus FTX), which will dump core
54 * if given 'long double' for varargs.
56 #ifdef HAVE_VA_ARG_LONG_DOUBLE_BUG
57 #define LONG_DOUBLE double
59 #define LONG_DOUBLE long double
62 static int osLibInitialized = 0;
64 static void *Malloc(size_t size)
66 void *result = malloc(size);
67 ASSERT(size == 0 || result != NULL);
71 static char *StringCopy(char *str)
73 int strLen = strlen(str);
74 char *newString = Malloc(strLen + 1);
75 memcpy(newString, str, strLen);
76 newString[strLen] = '\000';
82 *----------------------------------------------------------------------
86 * Reads a byte from the input stream and returns it.
89 * The byte, or EOF (-1) if the end of input has been reached.
91 *----------------------------------------------------------------------
93 int FCGX_GetChar(FCGX_Stream *stream)
95 if(stream->rdNext != stream->stop)
96 return *stream->rdNext++;
97 if(stream->isClosed || !stream->isReader)
99 stream->fillBuffProc(stream);
100 stream->stopUnget = stream->rdNext;
101 if(stream->rdNext != stream->stop)
102 return *stream->rdNext++;
103 ASSERT(stream->isClosed); /* bug in fillBufProc if not */
108 *----------------------------------------------------------------------
112 * Reads up to n consecutive bytes from the input stream
113 * into the character array str. Performs no interpretation
114 * of the input bytes.
117 * Number of bytes read. If result is smaller than n,
118 * the end of input has been reached.
120 *----------------------------------------------------------------------
122 int FCGX_GetStr(char *str, int n, FCGX_Stream *stream)
130 * Fast path: n bytes are already available
132 if(n <= (stream->stop - stream->rdNext)) {
133 memcpy(str, stream->rdNext, n);
138 * General case: stream is closed or buffer fill procedure
143 if(stream->rdNext != stream->stop) {
144 m = min(n - bytesMoved, stream->stop - stream->rdNext);
145 memcpy(str, stream->rdNext, m);
152 if(stream->isClosed || !stream->isReader)
154 stream->fillBuffProc(stream);
155 stream->stopUnget = stream->rdNext;
160 *----------------------------------------------------------------------
164 * Reads up to n-1 consecutive bytes from the input stream
165 * into the character array str. Stops before n-1 bytes
166 * have been read if '\n' or EOF is read. The terminating '\n'
167 * is copied to str. After copying the last byte into str,
168 * stores a '\0' terminator.
171 * NULL if EOF is the first thing read from the input stream,
174 *----------------------------------------------------------------------
176 char *FCGX_GetLine(char *str, int n, FCGX_Stream *stream)
182 c = FCGX_GetChar(stream);
199 *----------------------------------------------------------------------
203 * Pushes back the character c onto the input stream. One
204 * character of pushback is guaranteed once a character
205 * has been read. No pushback is possible for EOF.
208 * Returns c if the pushback succeeded, EOF if not.
210 *----------------------------------------------------------------------
212 int FCGX_UnGetChar(int c, FCGX_Stream *stream) {
216 || stream->rdNext == stream->stopUnget)
224 *----------------------------------------------------------------------
228 * Returns EOF if end-of-file has been detected while reading
229 * from stream; otherwise returns 0.
231 * Note that FCGX_HasSeenEOF(s) may return 0, yet an immediately
232 * following FCGX_GetChar(s) may return EOF. This function, like
233 * the standard C stdio function feof, does not provide the
234 * ability to peek ahead.
237 * EOF if end-of-file has been detected, 0 if not.
239 *----------------------------------------------------------------------
241 int FCGX_HasSeenEOF(FCGX_Stream *stream) {
242 return (stream->isClosed) ? EOF : 0;
246 *----------------------------------------------------------------------
250 * Writes a byte to the output stream.
253 * The byte, or EOF (-1) if an error occurred.
255 *----------------------------------------------------------------------
257 int FCGX_PutChar(int c, FCGX_Stream *stream)
259 if(stream->wrNext != stream->stop)
260 return (*stream->wrNext++ = c);
261 if(stream->isClosed || stream->isReader)
263 stream->emptyBuffProc(stream, FALSE);
264 if(stream->wrNext != stream->stop)
265 return (*stream->wrNext++ = c);
266 ASSERT(stream->isClosed); /* bug in emptyBuffProc if not */
271 *----------------------------------------------------------------------
275 * Writes n consecutive bytes from the character array str
276 * into the output stream. Performs no interpretation
277 * of the output bytes.
280 * Number of bytes written (n) for normal return,
281 * EOF (-1) if an error occurred.
283 *----------------------------------------------------------------------
285 int FCGX_PutStr(const char *str, int n, FCGX_Stream *stream)
290 * Fast path: room for n bytes in the buffer
292 if(n <= (stream->stop - stream->wrNext)) {
293 memcpy(stream->wrNext, str, n);
298 * General case: stream is closed or buffer empty procedure
303 if(stream->wrNext != stream->stop) {
304 m = min(n - bytesMoved, stream->stop - stream->wrNext);
305 memcpy(stream->wrNext, str, m);
312 if(stream->isClosed || stream->isReader)
314 stream->emptyBuffProc(stream, FALSE);
319 *----------------------------------------------------------------------
323 * Writes a character string to the output stream.
326 * number of bytes written for normal return,
327 * EOF (-1) if an error occurred.
329 *----------------------------------------------------------------------
331 int FCGX_PutS(const char *str, FCGX_Stream *stream)
333 return FCGX_PutStr(str, strlen(str), stream);
337 *----------------------------------------------------------------------
341 * Performs output formatting and writes the results
342 * to the output stream.
345 * number of bytes written for normal return,
346 * EOF (-1) if an error occurred.
348 *----------------------------------------------------------------------
350 int FCGX_FPrintF(FCGX_Stream *stream, const char *format, ...)
354 va_start(ap, format);
355 result = FCGX_VFPrintF(stream, format, ap);
361 *----------------------------------------------------------------------
365 * Performs output formatting and writes the results
366 * to the output stream.
369 * number of bytes written for normal return,
370 * EOF (-1) if an error occurred.
372 *----------------------------------------------------------------------
375 #define PRINTF_BUFFLEN 100
377 * More than sufficient space for all unmodified conversions
380 #define FMT_BUFFLEN 25
382 * Max size of a format specifier is 1 + 5 + 7 + 7 + 2 + 1 + slop
384 static void CopyAndAdvance(char **destPtr, char **srcPtr, int n);
386 int FCGX_VFPrintF(FCGX_Stream *stream, const char *format, va_list arg)
388 char *f, *fStop, *percentPtr, *p, *fmtBuffPtr, *buffPtr;
389 int op, performedOp, sizeModifier, buffCount, buffLen, specifierLength;
390 int fastPath, n, auxBuffLen, buffReqd, minWidth, precision, exp;
391 char *auxBuffPtr = NULL;
393 char fmtBuff[FMT_BUFFLEN];
394 char buff[PRINTF_BUFFLEN];
399 unsigned unsignedArg;
400 unsigned long uLongArg;
401 unsigned short uShortArg;
408 LONG_DOUBLE lDoubleArg;
412 fStop = f + strlen(f);
414 percentPtr = memchr(f, '%', fStop - f);
415 if(percentPtr == NULL) percentPtr = fStop;
416 if(percentPtr != f) {
417 if(FCGX_PutStr(f, percentPtr - f, stream) < 0) goto ErrorReturn;
418 streamCount += percentPtr - f;
420 if(f == fStop) break;
424 * The following loop always executes either once or twice.
429 * Fast path: Scan optimistically, hoping that no flags,
430 * minimum field width, or precision are specified.
431 * Use the preallocated buffer, which is large enough
432 * for all fast path cases. If the conversion specifier
433 * is really more complex, run the loop a second time
434 * using the slow path.
435 * Note that fast path execution of %s bypasses the buffer
436 * and %f is not attempted on the fast path due to
437 * its large buffering requirements.
439 op = *(percentPtr + 1);
445 op = *(percentPtr + 2);
446 fmtBuff[1] = sizeModifier;
459 buffLen = PRINTF_BUFFLEN;
462 * Slow path: Scan the conversion specifier and construct
463 * a new format string, compute an upper bound on the
464 * amount of buffering that sprintf will require,
465 * and allocate a larger buffer if necessary.
468 fmtBuffPtr = &fmtBuff[1];
472 n = strspn(p, "-0+ #");
473 if(n > 5) goto ErrorReturn;
474 CopyAndAdvance(&fmtBuffPtr, &p, n);
476 * Scan minimum field width
478 n = strspn(p, "0123456789");
481 minWidth = va_arg(arg, int);
482 if(abs(minWidth) > 999999) goto ErrorReturn;
484 * The following use of strlen rather than the
485 * value returned from sprintf is because SUNOS4
486 * returns a char * instead of an int count.
488 sprintf(fmtBuffPtr, "%d", minWidth);
489 fmtBuffPtr += strlen(fmtBuffPtr);
495 minWidth = strtol(p, NULL, 10);
496 CopyAndAdvance(&fmtBuffPtr, &p, n);
504 CopyAndAdvance(&fmtBuffPtr, &p, 1);
505 n = strspn(p, "0123456789");
508 precision = va_arg(arg, int);
509 if(precision < 0) precision = 0;
510 if(precision > 999999) goto ErrorReturn;
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.
516 sprintf(fmtBuffPtr, "%d", precision);
517 fmtBuffPtr += strlen(fmtBuffPtr);
523 precision = strtol(p, NULL, 10);
524 CopyAndAdvance(&fmtBuffPtr, &p, n);
532 * Scan size modifier and conversion operation
539 CopyAndAdvance(&fmtBuffPtr, &p, 1);
546 CopyAndAdvance(&fmtBuffPtr, &p, 1);
547 ASSERT(fmtBuffPtr - fmtBuff < FMT_BUFFLEN);
549 specifierLength = p - percentPtr;
551 * Bound the required buffer size. For s and f
552 * conversions this requires examining the argument.
563 buffReqd = max(precision, 46);
566 charPtrArg = va_arg(arg, char *);
567 if(precision == -1) {
568 buffReqd = strlen(charPtrArg);
570 p = memchr(charPtrArg, '\0', precision);
572 (p == NULL) ? precision : p - charPtrArg;
576 switch(sizeModifier) {
578 doubleArg = va_arg(arg, double);
579 frexp(doubleArg, &exp);
582 lDoubleArg = va_arg(arg, LONG_DOUBLE);
583 frexp(lDoubleArg, &exp);
588 if(precision == -1) precision = 6;
589 buffReqd = precision + 3 + ((exp > 0) ? exp/3 : 0);
595 if(precision == -1) precision = 6;
596 buffReqd = precision + 8;
604 buffReqd = max(buffReqd + 10, minWidth);
606 * Allocate the buffer
608 if(buffReqd <= PRINTF_BUFFLEN) {
610 buffLen = PRINTF_BUFFLEN;
612 if(auxBuffPtr == NULL || buffReqd > auxBuffLen) {
613 if(auxBuffPtr != NULL) free(auxBuffPtr);
614 auxBuffPtr = Malloc(buffReqd);
615 auxBuffLen = buffReqd;
616 if(auxBuffPtr == NULL) goto ErrorReturn;
618 buffPtr = auxBuffPtr;
619 buffLen = auxBuffLen;
623 * This giant switch statement requires the following variables
624 * to be set up: op, sizeModifier, arg, buffPtr, fmtBuff.
625 * When fastPath == FALSE and op == 's' or 'f', the argument
626 * has been read into charPtrArg, doubleArg, or lDoubleArg.
627 * The statement produces the boolean performedOp, TRUE iff
628 * the op/sizeModifier were executed and argument consumed;
629 * if performedOp, the characters written into buffPtr[]
630 * and the character count buffCount (== EOF meaning error).
632 * The switch cases are arranged in the same order as in the
633 * description of fprintf in section 15.11 of Harbison and Steele.
639 switch(sizeModifier) {
641 intArg = va_arg(arg, int);
642 sprintf(buffPtr, fmtBuff, intArg);
643 buffCount = strlen(buffPtr);
646 longArg = va_arg(arg, long);
647 sprintf(buffPtr, fmtBuff, longArg);
648 buffCount = strlen(buffPtr);
651 shortArg = va_arg(arg, short);
652 sprintf(buffPtr, fmtBuff, shortArg);
653 buffCount = strlen(buffPtr);
663 switch(sizeModifier) {
665 unsignedArg = va_arg(arg, unsigned);
666 sprintf(buffPtr, fmtBuff, unsignedArg);
667 buffCount = strlen(buffPtr);
670 uLongArg = va_arg(arg, unsigned long);
671 sprintf(buffPtr, fmtBuff, uLongArg);
672 buffCount = strlen(buffPtr);
675 uShortArg = va_arg(arg, unsigned short);
676 sprintf(buffPtr, fmtBuff, uShortArg);
677 buffCount = strlen(buffPtr);
684 switch(sizeModifier) {
686 intArg = va_arg(arg, int);
687 sprintf(buffPtr, fmtBuff, intArg);
688 buffCount = strlen(buffPtr);
692 * XXX: Allowed by ISO C Amendment 1, but
693 * many platforms don't yet support wint_t
701 switch(sizeModifier) {
704 buffPtr = va_arg(arg, char *);
705 buffCount = strlen(buffPtr);
706 buffLen = buffCount + 1;
708 sprintf(buffPtr, fmtBuff, charPtrArg);
709 buffCount = strlen(buffPtr);
714 * XXX: Don't know how to convert a sequence
715 * of wide characters into a byte stream, or
716 * even how to predict the buffering required.
724 if(sizeModifier != ' ') goto ErrorReturn;
725 voidPtrArg = va_arg(arg, void *);
726 sprintf(buffPtr, fmtBuff, voidPtrArg);
727 buffCount = strlen(buffPtr);
730 switch(sizeModifier) {
732 intPtrArg = va_arg(arg, int *);
733 *intPtrArg = streamCount;
736 longPtrArg = va_arg(arg, long *);
737 *longPtrArg = streamCount;
740 shortPtrArg = va_arg(arg, short *);
741 *shortPtrArg = streamCount;
753 switch(sizeModifier) {
755 sprintf(buffPtr, fmtBuff, doubleArg);
756 buffCount = strlen(buffPtr);
759 sprintf(buffPtr, fmtBuff, lDoubleArg);
760 buffCount = strlen(buffPtr);
770 switch(sizeModifier) {
772 doubleArg = va_arg(arg, double);
773 sprintf(buffPtr, fmtBuff, doubleArg);
774 buffCount = strlen(buffPtr);
777 lDoubleArg = va_arg(arg, LONG_DOUBLE);
778 sprintf(buffPtr, fmtBuff, lDoubleArg);
779 buffCount = strlen(buffPtr);
786 if(sizeModifier != ' ')
797 if(performedOp) break;
798 if(!fastPath) goto ErrorReturn;
801 ASSERT(buffCount < buffLen);
803 if(FCGX_PutStr(buffPtr, buffCount, stream) < 0)
805 streamCount += buffCount;
806 } else if(buffCount < 0) {
809 f += specifierLength;
810 } /* while(f != fStop) */
815 if(auxBuffPtr != NULL) free(auxBuffPtr);
820 * Copy n characters from *srcPtr to *destPtr, then increment
821 * both *srcPtr and *destPtr by n.
823 static void CopyAndAdvance(char **destPtr, char **srcPtr, int n)
825 char *dest = *destPtr;
828 for (i = 0; i < n; i++)
835 *----------------------------------------------------------------------
839 * Flushes any buffered output.
841 * Server-push is a legitimate application of FCGX_FFlush.
842 * Otherwise, FCGX_FFlush is not very useful, since FCGX_Accept
843 * does it implicitly. FCGX_FFlush may reduce performance
844 * by increasing the total number of operating system calls
845 * the application makes.
848 * EOF (-1) if an error occurred.
850 *----------------------------------------------------------------------
852 int FCGX_FFlush(FCGX_Stream *stream)
854 if(stream->isClosed || stream->isReader)
856 stream->emptyBuffProc(stream, FALSE);
857 return (stream->isClosed) ? -1 : 0;
861 *----------------------------------------------------------------------
865 * Performs FCGX_FFlush and closes the stream.
867 * This is not a very useful operation, since FCGX_Accept
868 * does it implicitly. Closing the out stream before the
869 * err stream results in an extra write if there's nothing
870 * in the err stream, and therefore reduces performance.
873 * EOF (-1) if an error occurred.
875 *----------------------------------------------------------------------
877 int FCGX_FClose(FCGX_Stream *stream)
879 if(!stream->wasFCloseCalled) {
880 if(!stream->isReader) {
881 stream->emptyBuffProc(stream, TRUE);
883 stream->wasFCloseCalled = TRUE;
884 stream->isClosed = TRUE;
885 if(stream->isReader) {
886 stream->wrNext = stream->stop = stream->rdNext;
888 stream->rdNext = stream->stop = stream->wrNext;
891 return (stream->FCGI_errno == 0) ? 0 : EOF;
895 *----------------------------------------------------------------------
899 * An error has occurred; save the error code in the stream
900 * for diagnostic purposes and set the stream state so that
901 * reads return EOF and writes have no effect.
903 *----------------------------------------------------------------------
905 static void SetError(FCGX_Stream *stream, int FCGI_errno)
908 * Preserve only the first error.
910 if(stream->FCGI_errno == 0) {
911 stream->FCGI_errno = FCGI_errno;
912 stream->isClosed = TRUE;
917 *----------------------------------------------------------------------
921 * Return the stream error code. 0 means no error, > 0
922 * is an errno(2) error, < 0 is an FCGX_errno error.
924 *----------------------------------------------------------------------
926 int FCGX_GetError(FCGX_Stream *stream) {
927 return stream->FCGI_errno;
931 *----------------------------------------------------------------------
935 * Clear the stream error code and end-of-file indication.
937 *----------------------------------------------------------------------
939 void FCGX_ClearError(FCGX_Stream *stream) {
940 stream->FCGI_errno = 0;
942 * stream->isClosed = FALSE;
943 * XXX: should clear isClosed but work is needed to make it safe
944 * to do so. For example, if an application calls FClose, gets
945 * an I/O error on the write, calls ClearError and retries
946 * the FClose, FClose (really EmptyBuffProc) will write a second
947 * EOF record. If an application calls PutChar instead of FClose
948 * after the ClearError, the application will write more data.
949 * The stream's state must discriminate between various states
950 * of the stream that are now all lumped under isClosed.
955 *======================================================================
957 *======================================================================
961 * A vector of pointers representing the parameters received
962 * by a FastCGI application server, with the vector's length
963 * and last valid element so adding new parameters is efficient.
966 typedef struct Params {
967 FCGX_ParamArray vec; /* vector of strings */
968 int length; /* number of string vec can hold */
969 char **cur; /* current item in vec; *cur == NULL */
971 typedef Params *ParamsPtr;
974 *----------------------------------------------------------------------
978 * Creates a new Params structure.
981 * Pointer to the new structure.
983 *----------------------------------------------------------------------
985 static ParamsPtr NewParams(int length)
988 result = Malloc(sizeof(Params));
989 result->vec = (char **) Malloc(length * sizeof(char *));
990 result->length = length;
991 result->cur = result->vec;
997 *----------------------------------------------------------------------
1001 * Frees a Params structure and all the parameters it contains.
1004 * paramsPtr becomes invalid.
1006 *----------------------------------------------------------------------
1008 static void FreeParams(ParamsPtr *paramsPtrPtr)
1010 ParamsPtr paramsPtr = *paramsPtrPtr;
1012 if(paramsPtr == NULL) {
1015 for (p = paramsPtr->vec; p < paramsPtr->cur; p++) {
1018 free(paramsPtr->vec);
1020 *paramsPtrPtr = NULL;
1024 *----------------------------------------------------------------------
1028 * Add a name/value pair to a Params structure.
1034 * Parameters structure updated.
1036 *----------------------------------------------------------------------
1038 static void PutParam(ParamsPtr paramsPtr, char *nameValue)
1042 *paramsPtr->cur++ = nameValue;
1043 size = paramsPtr->cur - paramsPtr->vec;
1044 if(size >= paramsPtr->length) {
1045 paramsPtr->length *= 2;
1047 realloc(paramsPtr->vec, paramsPtr->length * sizeof(char *));
1048 paramsPtr->cur = paramsPtr->vec + size;
1050 *paramsPtr->cur = NULL;
1054 *----------------------------------------------------------------------
1056 * FCGX_GetParam -- obtain value of FCGI parameter in environment
1060 * Value bound to name, NULL if name not present in the
1061 * environment envp. Caller must not mutate the result
1062 * or retain it past the end of this request.
1064 *----------------------------------------------------------------------
1066 char *FCGX_GetParam(const char *name, FCGX_ParamArray envp)
1071 if(len == 0) return NULL;
1072 for (p = envp; *p != NULL; p++) {
1073 if((strncmp(name, *p, len) == 0) && ((*p)[len] == '=')) {
1081 *----------------------------------------------------------------------
1083 * Start of FastCGI-specific code
1085 *----------------------------------------------------------------------
1089 *----------------------------------------------------------------------
1093 * Reads FastCGI name-value pairs from stream until EOF. Converts
1094 * each pair to name=value format and adds it to Params structure.
1096 *----------------------------------------------------------------------
1098 static int ReadParams(Params *paramsPtr, FCGX_Stream *stream)
1100 int nameLen, valueLen;
1101 unsigned char lenBuff[3];
1104 while((nameLen = FCGX_GetChar(stream)) != EOF) {
1106 * Read name length (one or four bytes) and value length
1107 * (one or four bytes) from stream.
1109 if((nameLen & 0x80) != 0) {
1110 if(FCGX_GetStr((char *) &lenBuff[0], 3, stream) != 3) {
1111 SetError(stream, FCGX_PARAMS_ERROR);
1114 nameLen = ((nameLen & 0x7f) << 24) + (lenBuff[0] << 16)
1115 + (lenBuff[1] << 8) + lenBuff[2];
1117 if((valueLen = FCGX_GetChar(stream)) == EOF) {
1118 SetError(stream, FCGX_PARAMS_ERROR);
1121 if((valueLen & 0x80) != 0) {
1122 if(FCGX_GetStr((char *) &lenBuff[0], 3, stream) != 3) {
1123 SetError(stream, FCGX_PARAMS_ERROR);
1126 valueLen = ((valueLen & 0x7f) << 24) + (lenBuff[0] << 16)
1127 + (lenBuff[1] << 8) + lenBuff[2];
1130 * nameLen and valueLen are now valid; read the name and value
1131 * from stream and construct a standard environment entry.
1133 nameValue = Malloc(nameLen + valueLen + 2);
1134 if(FCGX_GetStr(nameValue, nameLen, stream) != nameLen) {
1135 SetError(stream, FCGX_PARAMS_ERROR);
1139 *(nameValue + nameLen) = '=';
1140 if(FCGX_GetStr(nameValue + nameLen + 1, valueLen, stream)
1142 SetError(stream, FCGX_PARAMS_ERROR);
1146 *(nameValue + nameLen + valueLen + 1) = '\0';
1147 PutParam(paramsPtr, nameValue);
1153 *----------------------------------------------------------------------
1157 * Constructs an FCGI_Header struct.
1159 *----------------------------------------------------------------------
1161 static FCGI_Header MakeHeader(
1168 ASSERT(contentLength >= 0 && contentLength <= FCGI_MAX_LENGTH);
1169 ASSERT(paddingLength >= 0 && paddingLength <= 0xff);
1170 header.version = FCGI_VERSION_1;
1172 header.requestIdB1 = (requestId >> 8) & 0xff;
1173 header.requestIdB0 = (requestId ) & 0xff;
1174 header.contentLengthB1 = (contentLength >> 8) & 0xff;
1175 header.contentLengthB0 = (contentLength ) & 0xff;
1176 header.paddingLength = paddingLength;
1177 header.reserved = 0;
1182 *----------------------------------------------------------------------
1184 * MakeEndRequestBody --
1186 * Constructs an FCGI_EndRequestBody struct.
1188 *----------------------------------------------------------------------
1190 static FCGI_EndRequestBody MakeEndRequestBody(
1194 FCGI_EndRequestBody body;
1195 body.appStatusB3 = (appStatus >> 24) & 0xff;
1196 body.appStatusB2 = (appStatus >> 16) & 0xff;
1197 body.appStatusB1 = (appStatus >> 8) & 0xff;
1198 body.appStatusB0 = (appStatus ) & 0xff;
1199 body.protocolStatus = protocolStatus;
1200 memset(body.reserved, 0, sizeof(body.reserved));
1205 *----------------------------------------------------------------------
1207 * MakeUnknownTypeBody --
1209 * Constructs an FCGI_MakeUnknownTypeBody struct.
1211 *----------------------------------------------------------------------
1213 static FCGI_UnknownTypeBody MakeUnknownTypeBody(
1216 FCGI_UnknownTypeBody body;
1218 memset(body.reserved, 0, sizeof(body.reserved));
1223 *----------------------------------------------------------------------
1227 * Returns the smallest integer greater than or equal to n
1228 * that's a multiple of 8.
1230 *----------------------------------------------------------------------
1232 static int AlignInt8(unsigned n) {
1233 return (n + 7) & (UINT_MAX - 7);
1237 *----------------------------------------------------------------------
1241 * Returns the smallest pointer greater than or equal to p
1242 * that's a multiple of 8.
1244 *----------------------------------------------------------------------
1246 static unsigned char *AlignPtr8(unsigned char *p) {
1247 unsigned long u = (unsigned long) p;
1248 u = ((u + 7) & (ULONG_MAX - 7)) - u;
1253 * State associated with a request
1255 typedef struct ReqData {
1256 int ipcFd; /* < 0 means no connection */
1257 int isBeginProcessed; /* FCGI_BEGIN_REQUEST seen */
1258 int requestId; /* valid if isBeginProcessed */
1259 int keepConnection; /* don't close ipcFd at end of request */
1262 int nWriters; /* number of open writers (0..2) */
1263 FCGX_Stream *inStream;
1264 FCGX_Stream *outStream;
1265 FCGX_Stream *errStream;
1266 ParamsPtr paramsPtr;
1271 * State associated with a stream
1273 typedef struct FCGX_Stream_Data {
1274 unsigned char *buff; /* buffer after alignment */
1275 int bufflen; /* number of bytes buff can store */
1276 unsigned char *mBuff; /* buffer as returned by Malloc */
1277 unsigned char *buffStop; /* reader: last valid byte + 1 of entire buffer.
1278 * stop generally differs from buffStop for
1279 * readers because of record structure.
1280 * writer: buff + bufflen */
1281 int type; /* reader: FCGI_PARAMS or FCGI_STDIN
1282 * writer: FCGI_STDOUT or FCGI_STDERR */
1283 int eorStop; /* reader: stop stream at end-of-record */
1284 int skip; /* reader: don't deliver content bytes */
1285 int contentLen; /* reader: bytes of unread content */
1286 int paddingLen; /* reader: bytes of unread padding */
1287 int isAnythingWritten; /* writer: data has been written to ipcFd */
1288 int rawWrite; /* writer: write data without stream headers */
1289 ReqData *reqDataPtr; /* request data not specific to one stream */
1293 *----------------------------------------------------------------------
1295 * WriteCloseRecords --
1297 * Writes an EOF record for the stream content if necessary.
1298 * If this is the last writer to close, writes an FCGI_END_REQUEST
1301 *----------------------------------------------------------------------
1303 static void WriteCloseRecords(struct FCGX_Stream *stream)
1305 FCGX_Stream_Data *data = stream->data;
1307 * Enter rawWrite mode so final records won't be encapsulated as
1310 data->rawWrite = TRUE;
1312 * Generate EOF for stream content if needed.
1314 if(!(data->type == FCGI_STDERR
1315 && stream->wrNext == data->buff
1316 && !data->isAnythingWritten)) {
1318 header = MakeHeader(data->type, data->reqDataPtr->requestId, 0, 0);
1319 FCGX_PutStr((char *) &header, sizeof(header), stream);
1322 * Generate FCGI_END_REQUEST record if needed.
1324 if(data->reqDataPtr->nWriters == 1) {
1325 FCGI_EndRequestRecord endRequestRecord;
1326 endRequestRecord.header = MakeHeader(FCGI_END_REQUEST,
1327 data->reqDataPtr->requestId,
1328 sizeof(endRequestRecord.body), 0);
1329 endRequestRecord.body = MakeEndRequestBody(
1330 data->reqDataPtr->appStatus, FCGI_REQUEST_COMPLETE);
1331 FCGX_PutStr((char *) &endRequestRecord,
1332 sizeof(endRequestRecord), stream);
1334 data->reqDataPtr->nWriters--;
1339 static int write_it_all(int fd, char *buf, int len)
1344 wrote = OS_Write(fd, buf, len);
1354 *----------------------------------------------------------------------
1358 * Encapsulates any buffered stream content in a FastCGI
1359 * record. Writes the data, making the buffer empty.
1361 *----------------------------------------------------------------------
1363 static void EmptyBuffProc(struct FCGX_Stream *stream, int doClose)
1365 FCGX_Stream_Data *data = stream->data;
1368 * If the buffer contains stream data, fill in the header.
1369 * Pad the record to a multiple of 8 bytes in length. Padding
1370 * can't overflow the buffer because the buffer is a multiple
1371 * of 8 bytes in length. If the buffer contains no stream
1372 * data, reclaim the space reserved for the header.
1374 if(!data->rawWrite) {
1375 cLen = stream->wrNext - data->buff - sizeof(FCGI_Header);
1377 eLen = AlignInt8(cLen);
1379 * Giving the padding a well-defined value keeps Purify happy.
1381 memset(stream->wrNext, 0, eLen - cLen);
1382 stream->wrNext += eLen - cLen;
1383 *((FCGI_Header *) data->buff)
1384 = MakeHeader(data->type,
1385 data->reqDataPtr->requestId, cLen, eLen - cLen);
1387 stream->wrNext = data->buff;
1391 WriteCloseRecords(stream);
1393 if (stream->wrNext != data->buff) {
1394 data->isAnythingWritten = TRUE;
1395 if (write_it_all(data->reqDataPtr->ipcFd, (char *)data->buff, stream->wrNext - data->buff) < 0) {
1396 SetError(stream, OS_Errno);
1399 stream->wrNext = data->buff;
1402 * The buffer is empty.
1404 if(!data->rawWrite) {
1405 stream->wrNext += sizeof(FCGI_Header);
1410 * Return codes for Process* functions
1412 #define STREAM_RECORD 0
1414 #define BEGIN_RECORD 2
1415 #define MGMT_RECORD 3
1418 *----------------------------------------------------------------------
1420 * ProcessManagementRecord --
1422 * Reads and responds to a management record. The only type of
1423 * management record this library understands is FCGI_GET_VALUES.
1424 * The only variables that this library's FCGI_GET_VALUES
1425 * understands are FCGI_MAX_CONNS, FCGI_MAX_REQS, and FCGI_MPXS_CONNS.
1426 * Ignore other FCGI_GET_VALUES variables; respond to other
1427 * management records with a FCGI_UNKNOWN_TYPE record.
1429 *----------------------------------------------------------------------
1431 static int ProcessManagementRecord(int type, FCGX_Stream *stream)
1433 FCGX_Stream_Data *data = stream->data;
1434 ParamsPtr paramsPtr = NewParams(3);
1436 char response[64]; /* 64 = 8 + 3*(1+1+14+1)* + padding */
1437 char *responseP = &response[FCGI_HEADER_LEN];
1440 if(type == FCGI_GET_VALUES) {
1441 ReadParams(paramsPtr, stream);
1442 if((FCGX_GetError(stream) != 0) || (data->contentLen != 0)) {
1443 FreeParams(¶msPtr);
1444 return FCGX_PROTOCOL_ERROR;
1446 for (pPtr = paramsPtr->vec; pPtr < paramsPtr->cur; pPtr++) {
1448 *(strchr(name, '=')) = '\0';
1449 if(strcmp(name, FCGI_MAX_CONNS) == 0) {
1451 } else if(strcmp(name, FCGI_MAX_REQS) == 0) {
1453 } else if(strcmp(name, FCGI_MPXS_CONNS) == 0) {
1460 sprintf(responseP, "%c%c%s%c", len, 1, name, value);
1461 responseP += len + 3;
1464 len = responseP - &response[FCGI_HEADER_LEN];
1465 paddedLen = AlignInt8(len);
1466 *((FCGI_Header *) response)
1467 = MakeHeader(FCGI_GET_VALUES_RESULT, FCGI_NULL_REQUEST_ID,
1468 len, paddedLen - len);
1469 FreeParams(¶msPtr);
1471 paddedLen = len = sizeof(FCGI_UnknownTypeBody);
1472 ((FCGI_UnknownTypeRecord *) response)->header
1473 = MakeHeader(FCGI_UNKNOWN_TYPE, FCGI_NULL_REQUEST_ID,
1475 ((FCGI_UnknownTypeRecord *) response)->body
1476 = MakeUnknownTypeBody(type);
1478 if (write_it_all(data->reqDataPtr->ipcFd, response, FCGI_HEADER_LEN + paddedLen) < 0) {
1479 SetError(stream, OS_Errno);
1487 *----------------------------------------------------------------------
1489 * ProcessBeginRecord --
1491 * Reads an FCGI_BEGIN_REQUEST record.
1494 * BEGIN_RECORD for normal return. FCGX_PROTOCOL_ERROR for
1495 * protocol error. SKIP for attempt to multiplex
1496 * connection. -1 for error from write (errno in stream).
1499 * In case of BEGIN_RECORD return, stores requestId, role,
1500 * keepConnection values, and sets isBeginProcessed = TRUE.
1502 *----------------------------------------------------------------------
1504 static int ProcessBeginRecord(int requestId, FCGX_Stream *stream)
1506 FCGX_Stream_Data *data = stream->data;
1507 FCGI_BeginRequestBody body;
1508 if(requestId == 0 || data->contentLen != sizeof(body)) {
1509 return FCGX_PROTOCOL_ERROR;
1511 if(data->reqDataPtr->isBeginProcessed) {
1513 * The Web server is multiplexing the connection. This library
1514 * doesn't know how to handle multiplexing, so respond with
1515 * FCGI_END_REQUEST{protocolStatus = FCGI_CANT_MPX_CONN}
1517 FCGI_EndRequestRecord endRequestRecord;
1518 endRequestRecord.header = MakeHeader(FCGI_END_REQUEST,
1519 requestId, sizeof(endRequestRecord.body), 0);
1520 endRequestRecord.body
1521 = MakeEndRequestBody(0, FCGI_CANT_MPX_CONN);
1522 if (write_it_all(data->reqDataPtr->ipcFd, (char *)&endRequestRecord, sizeof(endRequestRecord)) < 0) {
1523 SetError(stream, OS_Errno);
1530 * Accept this new request. Read the record body.
1532 data->reqDataPtr->requestId = requestId;
1533 if(FCGX_GetStr((char *) &body, sizeof(body), stream)
1535 return FCGX_PROTOCOL_ERROR;
1537 data->reqDataPtr->keepConnection = (body.flags & FCGI_KEEP_CONN);
1538 data->reqDataPtr->role = (body.roleB1 << 8) + body.roleB0;
1539 data->reqDataPtr->isBeginProcessed = TRUE;
1540 return BEGIN_RECORD;
1544 *----------------------------------------------------------------------
1548 * Interprets FCGI_Header. Processes FCGI_BEGIN_REQUEST and
1549 * management records here; extracts information from stream
1550 * records (FCGI_PARAMS, FCGI_STDIN) into stream.
1553 * >= 0 for a normal return, < 0 for error
1556 * XXX: Many (more than there used to be).
1557 * If !stream->isRequestIdSet, ProcessHeader initializes
1558 * stream->requestId from header and sets stream->isRequestIdSet
1559 * to TRUE. ProcessHeader also sets stream->contentLen to header's
1560 * contentLength, and sets stream->paddingLen to the header's
1563 *----------------------------------------------------------------------
1565 static int ProcessHeader(FCGI_Header header, FCGX_Stream *stream)
1567 FCGX_Stream_Data *data = stream->data;
1569 if(header.version != FCGI_VERSION_1) {
1570 return FCGX_UNSUPPORTED_VERSION;
1572 requestId = (header.requestIdB1 << 8)
1573 + header.requestIdB0;
1574 data->contentLen = (header.contentLengthB1 << 8)
1575 + header.contentLengthB0;
1576 data->paddingLen = header.paddingLength;
1577 if(header.type == FCGI_BEGIN_REQUEST) {
1578 return ProcessBeginRecord(requestId, stream);
1580 if(requestId == FCGI_NULL_REQUEST_ID) {
1581 return ProcessManagementRecord(header.type, stream);
1583 if(requestId != data->reqDataPtr->requestId) {
1586 if(header.type != data->type) {
1587 return FCGX_PROTOCOL_ERROR;
1589 return STREAM_RECORD;
1593 *----------------------------------------------------------------------
1597 * Reads bytes from the ipcFd, supplies bytes to a stream client.
1599 *----------------------------------------------------------------------
1601 static void FillBuffProc(FCGX_Stream *stream)
1603 FCGX_Stream_Data *data = stream->data;
1610 * If data->buff is empty, do a read.
1612 if(stream->rdNext == data->buffStop) {
1613 count = OS_Read(data->reqDataPtr->ipcFd, (char *)data->buff,
1616 SetError(stream, (count == 0 ? FCGX_PROTOCOL_ERROR : OS_Errno));
1619 stream->rdNext = data->buff;
1620 data->buffStop = data->buff + count;
1623 * Now data->buff is not empty. If the current record contains
1624 * more content bytes, deliver all that are present in data->buff.
1626 if(data->contentLen > 0) {
1627 count = min(data->contentLen, data->buffStop - stream->rdNext);
1628 data->contentLen -= count;
1630 stream->wrNext = stream->stop = stream->rdNext + count;
1633 stream->rdNext += count;
1634 if(data->contentLen > 0) {
1642 * If the current record (whose content has been fully consumed by
1643 * the client) was padded, skip over the padding bytes.
1645 if(data->paddingLen > 0) {
1646 count = min(data->paddingLen, data->buffStop - stream->rdNext);
1647 data->paddingLen -= count;
1648 stream->rdNext += count;
1649 if(data->paddingLen > 0) {
1654 * All done with the current record, including the padding.
1655 * If we're in a recursive call from ProcessHeader, deliver EOF.
1658 stream->stop = stream->rdNext;
1659 stream->isClosed = TRUE;
1663 * Fill header with bytes from the input buffer.
1665 count = min((int)sizeof(header) - headerLen,
1666 data->buffStop - stream->rdNext);
1667 memcpy(((char *)(&header)) + headerLen, stream->rdNext, count);
1669 stream->rdNext += count;
1670 if(headerLen < sizeof(header)) {
1675 * Interpret header. eorStop prevents ProcessHeader from reading
1676 * past the end-of-record when using stream to read content.
1678 data->eorStop = TRUE;
1679 stream->stop = stream->rdNext;
1680 status = ProcessHeader(header, stream);
1681 data->eorStop = FALSE;
1682 stream->isClosed = FALSE;
1686 * If this stream record header marked the end of stream
1687 * data deliver EOF to the stream client, otherwise loop
1690 * XXX: If this is final stream and
1691 * stream->rdNext != data->buffStop, buffered
1692 * data is next request (server pipelining)?
1694 if(data->contentLen == 0) {
1695 stream->wrNext = stream->stop = stream->rdNext;
1696 stream->isClosed = TRUE;
1705 * If this header marked the beginning of a new
1706 * request, return role information to caller.
1714 SetError(stream, status);
1722 *----------------------------------------------------------------------
1726 * Creates a stream to read or write from an open ipcFd.
1727 * The stream performs reads/writes of up to bufflen bytes.
1729 *----------------------------------------------------------------------
1731 static FCGX_Stream *NewStream(
1732 ReqData *reqDataPtr, int bufflen, int isReader, int streamType)
1735 * XXX: It would be a lot cleaner to have a NewStream that only
1736 * knows about the type FCGX_Stream, with all other
1737 * necessary data passed in. It appears that not just
1738 * data and the two procs are needed for initializing stream,
1739 * but also data->buff and data->buffStop. This has implications
1740 * for procs that want to swap buffers, too.
1742 FCGX_Stream *stream = Malloc(sizeof(FCGX_Stream));
1743 FCGX_Stream_Data *data = Malloc(sizeof(FCGX_Stream_Data));
1744 data->reqDataPtr = reqDataPtr;
1745 bufflen = AlignInt8(min(max(bufflen, 32), FCGI_MAX_LENGTH + 1));
1746 data->bufflen = bufflen;
1747 data->mBuff = Malloc(bufflen);
1748 data->buff = AlignPtr8(data->mBuff);
1749 if(data->buff != data->mBuff) {
1753 data->buffStop = data->buff;
1755 data->buffStop = data->buff + data->bufflen;
1757 data->type = streamType;
1758 data->eorStop = FALSE;
1760 data->contentLen = 0;
1761 data->paddingLen = 0;
1762 data->isAnythingWritten = FALSE;
1763 data->rawWrite = FALSE;
1765 stream->data = data;
1766 stream->isReader = isReader;
1767 stream->isClosed = FALSE;
1768 stream->wasFCloseCalled = FALSE;
1769 stream->FCGI_errno = 0;
1771 stream->fillBuffProc = FillBuffProc;
1772 stream->emptyBuffProc = NULL;
1773 stream->rdNext = data->buff;
1774 stream->stop = stream->rdNext;
1775 stream->stopUnget = data->buff;
1776 stream->wrNext = stream->stop;
1778 stream->fillBuffProc = NULL;
1779 stream->emptyBuffProc = EmptyBuffProc;
1780 stream->wrNext = data->buff + sizeof(FCGI_Header);
1781 stream->stop = data->buffStop;
1782 stream->stopUnget = NULL;
1783 stream->rdNext = stream->stop;
1789 *----------------------------------------------------------------------
1793 * Frees all storage allocated when *streamPtr was created,
1794 * and nulls out *streamPtr.
1796 *----------------------------------------------------------------------
1798 void FreeStream(FCGX_Stream **streamPtr)
1800 FCGX_Stream *stream = *streamPtr;
1801 FCGX_Stream_Data *data;
1802 if(stream == NULL) {
1805 data = stream->data;
1806 data->reqDataPtr = NULL;
1814 *----------------------------------------------------------------------
1818 * Re-initializes the stream to read data of the specified type.
1820 *----------------------------------------------------------------------
1822 static FCGX_Stream *SetReaderType(FCGX_Stream *stream, int streamType)
1824 FCGX_Stream_Data *data = stream->data;
1825 ASSERT(stream->isReader);
1826 data->type = streamType;
1827 data->eorStop = FALSE;
1829 data->contentLen = 0;
1830 data->paddingLen = 0;
1831 stream->wrNext = stream->stop = stream->rdNext;
1832 stream->isClosed = FALSE;
1837 *----------------------------------------------------------------------
1841 * Creates a stream to read streamType records for the given
1842 * request. The stream performs OS reads of up to bufflen bytes.
1844 *----------------------------------------------------------------------
1846 static FCGX_Stream *NewReader(ReqData *reqDataPtr, int bufflen, int streamType)
1848 return NewStream(reqDataPtr, bufflen, TRUE, streamType);
1853 *----------------------------------------------------------------------
1857 * Creates a stream to write streamType FastCGI records, using
1858 * the ipcFd and RequestId contained in *reqDataPtr.
1859 * The stream performs OS writes of up to bufflen bytes.
1861 *----------------------------------------------------------------------
1863 static FCGX_Stream *NewWriter(ReqData *reqDataPtr, int bufflen, int streamType)
1865 return NewStream(reqDataPtr, bufflen, FALSE, streamType);
1870 *----------------------------------------------------------------------
1874 * Creates a stream to write streamType FastCGI records, using
1875 * the given ipcFd and request Id. This function is provided
1876 * for use by cgi-fcgi. In order to be defensive against misuse,
1877 * this function leaks a little storage; cgi-fcgi doesn't care.
1879 *----------------------------------------------------------------------
1881 FCGX_Stream *CreateWriter(
1887 ReqData *reqDataPtr = Malloc(sizeof(ReqData));
1888 reqDataPtr->ipcFd = ipcFd;
1889 reqDataPtr->requestId = requestId;
1891 * Suppress writing an FCGI_END_REQUEST record.
1893 reqDataPtr->nWriters = 2;
1894 return NewWriter(reqDataPtr, bufflen, streamType);
1898 *======================================================================
1900 *======================================================================
1903 static int isCGI = -1;
1904 static int isFastCGI = -1;
1907 *----------------------------------------------------------------------
1911 * This routine determines if the process is running as a CGI or
1912 * FastCGI process. The distinction is made by determining whether
1913 * FCGI_LISTENSOCK_FILENO is a listener ipcFd or the end of a
1914 * pipe (ie. standard in).
1917 * TRUE if the process is a CGI process, FALSE if FastCGI.
1920 * If this is a FastCGI process there's a chance that a connection
1921 * will be accepted while performing the test. If this occurs,
1922 * the connection is saved and used later by the FCGX_Accept logic.
1924 *----------------------------------------------------------------------
1926 int FCGX_IsCGI(void)
1929 * Already been here, no need to test again.
1935 if(!osLibInitialized) {
1936 if(OS_LibInit(NULL) == -1) {
1939 osLibInitialized = 1;
1942 isFastCGI = OS_IsFcgi();
1948 *----------------------------------------------------------------------
1952 * Finishes the current request from the HTTP server.
1956 * Finishes the request accepted by (and frees any
1957 * storage allocated by) the previous call to FCGX_Accept.
1959 * DO NOT retain pointers to the envp array or any strings
1960 * contained in it (e.g. to the result of calling FCGX_GetParam),
1961 * since these will be freed by the next call to FCGX_Finish
1964 *----------------------------------------------------------------------
1966 static ReqData *reqDataPtr = NULL;
1968 void FCGX_Finish(void)
1970 if(reqDataPtr != NULL && reqDataPtr->inStream != NULL) {
1972 * Complete the previous request.
1974 int errStatus = FCGX_FClose(reqDataPtr->errStream);
1975 int outStatus = FCGX_FClose(reqDataPtr->outStream);
1976 int prevRequestFailed = (errStatus != 0)
1978 || (FCGX_GetError(reqDataPtr->inStream) != 0);
1979 ASSERT(reqDataPtr->nWriters == 0);
1980 FreeStream(&reqDataPtr->inStream);
1981 FreeStream(&reqDataPtr->outStream);
1982 FreeStream(&reqDataPtr->errStream);
1983 FreeParams(&reqDataPtr->paramsPtr);
1984 if(prevRequestFailed || !reqDataPtr->keepConnection) {
1985 OS_IpcClose(reqDataPtr->ipcFd);
1986 reqDataPtr->ipcFd = -1;
1992 *----------------------------------------------------------------------
1996 * Accepts a new request from the HTTP server.
1999 * 0 for successful call, -1 for error.
2003 * Finishes the request accepted by (and frees any
2004 * storage allocated by) the previous call to FCGX_Accept.
2005 * Creates input, output, and error streams and
2006 * assigns them to *in, *out, and *err respectively.
2007 * Creates a parameters data structure to be accessed
2008 * via getenv(3) (if assigned to environ) or by FCGX_GetParam
2009 * and assigns it to *envp.
2011 * DO NOT retain pointers to the envp array or any strings
2012 * contained in it (e.g. to the result of calling FCGX_GetParam),
2013 * since these will be freed by the next call to FCGX_Finish
2016 *----------------------------------------------------------------------
2018 static ReqData reqData;
2019 static char *webServerAddressList = NULL;
2025 FCGX_ParamArray *envp)
2028 * If our compiler doesn't play by the ISO rules for struct
2031 ASSERT(sizeof(FCGI_Header) == FCGI_HEADER_LEN);
2033 if(!osLibInitialized) {
2034 if(OS_LibInit(NULL) == -1) {
2037 osLibInitialized = 1;
2041 * If our compiler doesn't play by the ISO rules for struct
2044 ASSERT(sizeof(FCGI_Header) == FCGI_HEADER_LEN);
2046 if(reqDataPtr == NULL) {
2048 * Very first call, so capture FCGI_WEB_SERVER_ADDRS from
2049 * the initial environment, and initialize reqDataPtr
2050 * and parts of reqData.
2052 char *p = getenv("FCGI_WEB_SERVER_ADDRS");
2054 webServerAddressList = StringCopy(p);
2056 reqDataPtr = &reqData;
2057 reqDataPtr->ipcFd = -1;
2058 reqDataPtr->inStream = NULL;
2059 reqDataPtr->outStream = NULL;
2060 reqDataPtr->errStream = NULL;
2063 * Not the first call. Finish the current request, if any.
2069 * If a connection isn't open, accept a new connection (blocking).
2070 * If an OS error occurs in accepting the connection,
2071 * return -1 to the caller, who should exit.
2073 if(reqDataPtr->ipcFd < 0) {
2074 reqDataPtr->ipcFd = OS_FcgiIpcAccept(webServerAddressList);
2075 if(reqDataPtr->ipcFd < 0) {
2077 return (errno > 0) ? (0 - errno) : -9999;
2081 * A connection is open. Read from the connection in order to
2082 * get the request's role and environment. If protocol or other
2083 * errors occur, close the connection and try again.
2085 reqDataPtr->isBeginProcessed = FALSE;
2086 reqDataPtr->inStream = NewReader(reqDataPtr, 8192, 0);
2087 FillBuffProc(reqDataPtr->inStream);
2088 if(!reqDataPtr->isBeginProcessed) {
2093 switch(reqDataPtr->role) {
2094 case FCGI_RESPONDER:
2095 roleStr = "FCGI_ROLE=RESPONDER";
2097 case FCGI_AUTHORIZER:
2098 roleStr = "FCGI_ROLE=AUTHORIZER";
2101 roleStr = "FCGI_ROLE=FILTER";
2106 reqDataPtr->paramsPtr = NewParams(30);
2107 PutParam(reqDataPtr->paramsPtr, StringCopy(roleStr));
2109 SetReaderType(reqDataPtr->inStream, FCGI_PARAMS);
2110 if(ReadParams(reqDataPtr->paramsPtr, reqDataPtr->inStream) >= 0) {
2112 * Finished reading the environment. No errors occurred, so
2113 * leave the connection-retry loop.
2118 * Close the connection and try again.
2121 FreeParams(&reqDataPtr->paramsPtr);
2122 FreeStream(&reqDataPtr->inStream);
2123 OS_Close(reqDataPtr->ipcFd);
2124 reqDataPtr->ipcFd = -1;
2127 * Build the remaining data structures representing the new
2128 * request and return successfully to the caller.
2130 SetReaderType(reqDataPtr->inStream, FCGI_STDIN);
2131 reqDataPtr->outStream = NewWriter(reqDataPtr, 8192, FCGI_STDOUT);
2132 reqDataPtr->errStream = NewWriter(reqDataPtr, 512, FCGI_STDERR);
2133 reqDataPtr->nWriters = 2;
2134 *in = reqDataPtr->inStream;
2135 *out = reqDataPtr->outStream;
2136 *err = reqDataPtr->errStream;
2137 *envp = reqDataPtr->paramsPtr->vec;
2142 *----------------------------------------------------------------------
2144 * FCGX_StartFilterData --
2146 * stream is an input stream for a FCGI_FILTER request.
2147 * stream is positioned at EOF on FCGI_STDIN.
2148 * Repositions stream to the start of FCGI_DATA.
2149 * If the preconditions are not met (e.g. FCGI_STDIN has not
2150 * been read to EOF) sets the stream error code to
2151 * FCGX_CALL_SEQ_ERROR.
2154 * 0 for a normal return, < 0 for error
2156 *----------------------------------------------------------------------
2159 int FCGX_StartFilterData(FCGX_Stream *stream)
2161 FCGX_Stream_Data *data = stream->data;
2162 if(data->reqDataPtr->role != FCGI_FILTER
2163 || !stream->isReader
2164 || !stream->isClosed
2165 || data->type != FCGI_STDIN) {
2166 SetError(stream, FCGX_CALL_SEQ_ERROR);
2169 SetReaderType(reqDataPtr->inStream, FCGI_DATA);
2174 *----------------------------------------------------------------------
2176 * FCGX_SetExitStatus --
2178 * Sets the exit status for stream's request. The exit status
2179 * is the status code the request would have exited with, had
2180 * the request been run as a CGI program. You can call
2181 * SetExitStatus several times during a request; the last call
2182 * before the request ends determines the value.
2184 *----------------------------------------------------------------------
2187 void FCGX_SetExitStatus(int status, FCGX_Stream *stream)
2189 FCGX_Stream_Data *data = stream->data;
2190 data->reqDataPtr->appStatus = status;