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.1 1997/09/16 15:36:33 stanleyg 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--;
1338 *----------------------------------------------------------------------
1342 * Encapsulates any buffered stream content in a FastCGI
1343 * record. Writes the data, making the buffer empty.
1345 *----------------------------------------------------------------------
1347 static void EmptyBuffProc(struct FCGX_Stream *stream, int doClose)
1349 FCGX_Stream_Data *data = stream->data;
1352 * If the buffer contains stream data, fill in the header.
1353 * Pad the record to a multiple of 8 bytes in length. Padding
1354 * can't overflow the buffer because the buffer is a multiple
1355 * of 8 bytes in length. If the buffer contains no stream
1356 * data, reclaim the space reserved for the header.
1358 if(!data->rawWrite) {
1359 cLen = stream->wrNext - data->buff - sizeof(FCGI_Header);
1361 eLen = AlignInt8(cLen);
1363 * Giving the padding a well-defined value keeps Purify happy.
1365 memset(stream->wrNext, 0, eLen - cLen);
1366 stream->wrNext += eLen - cLen;
1367 *((FCGI_Header *) data->buff)
1368 = MakeHeader(data->type,
1369 data->reqDataPtr->requestId, cLen, eLen - cLen);
1371 stream->wrNext = data->buff;
1375 WriteCloseRecords(stream);
1377 if(stream->wrNext != data->buff) {
1378 data->isAnythingWritten = TRUE;
1379 if(OS_Write(data->reqDataPtr->ipcFd, (char *)data->buff,
1380 stream->wrNext - data->buff) < 0) {
1381 SetError(stream, OS_Errno);
1384 stream->wrNext = data->buff;
1387 * The buffer is empty.
1389 if(!data->rawWrite) {
1390 stream->wrNext += sizeof(FCGI_Header);
1395 * Return codes for Process* functions
1397 #define STREAM_RECORD 0
1399 #define BEGIN_RECORD 2
1400 #define MGMT_RECORD 3
1403 *----------------------------------------------------------------------
1405 * ProcessManagementRecord --
1407 * Reads and responds to a management record. The only type of
1408 * management record this library understands is FCGI_GET_VALUES.
1409 * The only variables that this library's FCGI_GET_VALUES
1410 * understands are FCGI_MAX_CONNS, FCGI_MAX_REQS, and FCGI_MPXS_CONNS.
1411 * Ignore other FCGI_GET_VALUES variables; respond to other
1412 * management records with a FCGI_UNKNOWN_TYPE record.
1414 *----------------------------------------------------------------------
1416 static int ProcessManagementRecord(int type, FCGX_Stream *stream)
1418 FCGX_Stream_Data *data = stream->data;
1419 ParamsPtr paramsPtr = NewParams(3);
1421 char response[64]; /* 64 = 8 + 3*(1+1+14+1)* + padding */
1422 char *responseP = &response[FCGI_HEADER_LEN];
1425 if(type == FCGI_GET_VALUES) {
1426 ReadParams(paramsPtr, stream);
1427 if((FCGX_GetError(stream) != 0) || (data->contentLen != 0)) {
1428 FreeParams(¶msPtr);
1429 return FCGX_PROTOCOL_ERROR;
1431 for (pPtr = paramsPtr->vec; pPtr < paramsPtr->cur; pPtr++) {
1433 *(strchr(name, '=')) = '\0';
1434 if(strcmp(name, FCGI_MAX_CONNS) == 0) {
1436 } else if(strcmp(name, FCGI_MAX_REQS) == 0) {
1438 } else if(strcmp(name, FCGI_MPXS_CONNS) == 0) {
1445 sprintf(responseP, "%c%c%s%c", len, 1, name, value);
1446 responseP += len + 3;
1449 len = responseP - &response[FCGI_HEADER_LEN];
1450 paddedLen = AlignInt8(len);
1451 *((FCGI_Header *) response)
1452 = MakeHeader(FCGI_GET_VALUES_RESULT, FCGI_NULL_REQUEST_ID,
1453 len, paddedLen - len);
1454 FreeParams(¶msPtr);
1456 paddedLen = len = sizeof(FCGI_UnknownTypeBody);
1457 ((FCGI_UnknownTypeRecord *) response)->header
1458 = MakeHeader(FCGI_UNKNOWN_TYPE, FCGI_NULL_REQUEST_ID,
1460 ((FCGI_UnknownTypeRecord *) response)->body
1461 = MakeUnknownTypeBody(type);
1463 if(OS_Write(data->reqDataPtr->ipcFd,
1464 response, FCGI_HEADER_LEN + paddedLen) < 0) {
1465 SetError(stream, OS_Errno);
1472 *----------------------------------------------------------------------
1474 * ProcessBeginRecord --
1476 * Reads an FCGI_BEGIN_REQUEST record.
1479 * BEGIN_RECORD for normal return. FCGX_PROTOCOL_ERROR for
1480 * protocol error. SKIP for attempt to multiplex
1481 * connection. -1 for error from write (errno in stream).
1484 * In case of BEGIN_RECORD return, stores requestId, role,
1485 * keepConnection values, and sets isBeginProcessed = TRUE.
1487 *----------------------------------------------------------------------
1489 static int ProcessBeginRecord(int requestId, FCGX_Stream *stream)
1491 FCGX_Stream_Data *data = stream->data;
1492 FCGI_BeginRequestBody body;
1493 if(requestId == 0 || data->contentLen != sizeof(body)) {
1494 return FCGX_PROTOCOL_ERROR;
1496 if(data->reqDataPtr->isBeginProcessed) {
1498 * The Web server is multiplexing the connection. This library
1499 * doesn't know how to handle multiplexing, so respond with
1500 * FCGI_END_REQUEST{protocolStatus = FCGI_CANT_MPX_CONN}
1502 FCGI_EndRequestRecord endRequestRecord;
1503 endRequestRecord.header = MakeHeader(FCGI_END_REQUEST,
1504 requestId, sizeof(endRequestRecord.body), 0);
1505 endRequestRecord.body
1506 = MakeEndRequestBody(0, FCGI_CANT_MPX_CONN);
1507 if(OS_Write(data->reqDataPtr->ipcFd, (char *) &endRequestRecord,
1508 sizeof(endRequestRecord)) < 0) {
1509 SetError(stream, OS_Errno);
1515 * Accept this new request. Read the record body.
1517 data->reqDataPtr->requestId = requestId;
1518 if(FCGX_GetStr((char *) &body, sizeof(body), stream)
1520 return FCGX_PROTOCOL_ERROR;
1522 data->reqDataPtr->keepConnection = (body.flags & FCGI_KEEP_CONN);
1523 data->reqDataPtr->role = (body.roleB1 << 8) + body.roleB0;
1524 data->reqDataPtr->isBeginProcessed = TRUE;
1525 return BEGIN_RECORD;
1529 *----------------------------------------------------------------------
1533 * Interprets FCGI_Header. Processes FCGI_BEGIN_REQUEST and
1534 * management records here; extracts information from stream
1535 * records (FCGI_PARAMS, FCGI_STDIN) into stream.
1538 * >= 0 for a normal return, < 0 for error
1541 * XXX: Many (more than there used to be).
1542 * If !stream->isRequestIdSet, ProcessHeader initializes
1543 * stream->requestId from header and sets stream->isRequestIdSet
1544 * to TRUE. ProcessHeader also sets stream->contentLen to header's
1545 * contentLength, and sets stream->paddingLen to the header's
1548 *----------------------------------------------------------------------
1550 static int ProcessHeader(FCGI_Header header, FCGX_Stream *stream)
1552 FCGX_Stream_Data *data = stream->data;
1554 if(header.version != FCGI_VERSION_1) {
1555 return FCGX_UNSUPPORTED_VERSION;
1557 requestId = (header.requestIdB1 << 8)
1558 + header.requestIdB0;
1559 data->contentLen = (header.contentLengthB1 << 8)
1560 + header.contentLengthB0;
1561 data->paddingLen = header.paddingLength;
1562 if(header.type == FCGI_BEGIN_REQUEST) {
1563 return ProcessBeginRecord(requestId, stream);
1565 if(requestId == FCGI_NULL_REQUEST_ID) {
1566 return ProcessManagementRecord(header.type, stream);
1568 if(requestId != data->reqDataPtr->requestId) {
1571 if(header.type != data->type) {
1572 return FCGX_PROTOCOL_ERROR;
1574 return STREAM_RECORD;
1578 *----------------------------------------------------------------------
1582 * Reads bytes from the ipcFd, supplies bytes to a stream client.
1584 *----------------------------------------------------------------------
1586 static void FillBuffProc(FCGX_Stream *stream)
1588 FCGX_Stream_Data *data = stream->data;
1595 * If data->buff is empty, do a read.
1597 if(stream->rdNext == data->buffStop) {
1598 count = OS_Read(data->reqDataPtr->ipcFd, (char *)data->buff,
1601 SetError(stream, (count == 0 ? FCGX_PROTOCOL_ERROR : OS_Errno));
1604 stream->rdNext = data->buff;
1605 data->buffStop = data->buff + count;
1608 * Now data->buff is not empty. If the current record contains
1609 * more content bytes, deliver all that are present in data->buff.
1611 if(data->contentLen > 0) {
1612 count = min(data->contentLen, data->buffStop - stream->rdNext);
1613 data->contentLen -= count;
1615 stream->wrNext = stream->stop = stream->rdNext + count;
1618 stream->rdNext += count;
1619 if(data->contentLen > 0) {
1627 * If the current record (whose content has been fully consumed by
1628 * the client) was padded, skip over the padding bytes.
1630 if(data->paddingLen > 0) {
1631 count = min(data->paddingLen, data->buffStop - stream->rdNext);
1632 data->paddingLen -= count;
1633 stream->rdNext += count;
1634 if(data->paddingLen > 0) {
1639 * All done with the current record, including the padding.
1640 * If we're in a recursive call from ProcessHeader, deliver EOF.
1643 stream->stop = stream->rdNext;
1644 stream->isClosed = TRUE;
1648 * Fill header with bytes from the input buffer.
1650 count = min((int)sizeof(header) - headerLen,
1651 data->buffStop - stream->rdNext);
1652 memcpy(((char *)(&header)) + headerLen, stream->rdNext, count);
1654 stream->rdNext += count;
1655 if(headerLen < sizeof(header)) {
1660 * Interpret header. eorStop prevents ProcessHeader from reading
1661 * past the end-of-record when using stream to read content.
1663 data->eorStop = TRUE;
1664 stream->stop = stream->rdNext;
1665 status = ProcessHeader(header, stream);
1666 data->eorStop = FALSE;
1667 stream->isClosed = FALSE;
1671 * If this stream record header marked the end of stream
1672 * data deliver EOF to the stream client, otherwise loop
1675 * XXX: If this is final stream and
1676 * stream->rdNext != data->buffStop, buffered
1677 * data is next request (server pipelining)?
1679 if(data->contentLen == 0) {
1680 stream->wrNext = stream->stop = stream->rdNext;
1681 stream->isClosed = TRUE;
1690 * If this header marked the beginning of a new
1691 * request, return role information to caller.
1699 SetError(stream, status);
1707 *----------------------------------------------------------------------
1711 * Creates a stream to read or write from an open ipcFd.
1712 * The stream performs reads/writes of up to bufflen bytes.
1714 *----------------------------------------------------------------------
1716 static FCGX_Stream *NewStream(
1717 ReqData *reqDataPtr, int bufflen, int isReader, int streamType)
1720 * XXX: It would be a lot cleaner to have a NewStream that only
1721 * knows about the type FCGX_Stream, with all other
1722 * necessary data passed in. It appears that not just
1723 * data and the two procs are needed for initializing stream,
1724 * but also data->buff and data->buffStop. This has implications
1725 * for procs that want to swap buffers, too.
1727 FCGX_Stream *stream = Malloc(sizeof(FCGX_Stream));
1728 FCGX_Stream_Data *data = Malloc(sizeof(FCGX_Stream_Data));
1729 data->reqDataPtr = reqDataPtr;
1730 bufflen = AlignInt8(min(max(bufflen, 32), FCGI_MAX_LENGTH + 1));
1731 data->bufflen = bufflen;
1732 data->mBuff = Malloc(bufflen);
1733 data->buff = AlignPtr8(data->mBuff);
1734 if(data->buff != data->mBuff) {
1738 data->buffStop = data->buff;
1740 data->buffStop = data->buff + data->bufflen;
1742 data->type = streamType;
1743 data->eorStop = FALSE;
1745 data->contentLen = 0;
1746 data->paddingLen = 0;
1747 data->isAnythingWritten = FALSE;
1748 data->rawWrite = FALSE;
1750 stream->data = data;
1751 stream->isReader = isReader;
1752 stream->isClosed = FALSE;
1753 stream->wasFCloseCalled = FALSE;
1754 stream->FCGI_errno = 0;
1756 stream->fillBuffProc = FillBuffProc;
1757 stream->emptyBuffProc = NULL;
1758 stream->rdNext = data->buff;
1759 stream->stop = stream->rdNext;
1760 stream->stopUnget = data->buff;
1761 stream->wrNext = stream->stop;
1763 stream->fillBuffProc = NULL;
1764 stream->emptyBuffProc = EmptyBuffProc;
1765 stream->wrNext = data->buff + sizeof(FCGI_Header);
1766 stream->stop = data->buffStop;
1767 stream->stopUnget = NULL;
1768 stream->rdNext = stream->stop;
1774 *----------------------------------------------------------------------
1778 * Frees all storage allocated when *streamPtr was created,
1779 * and nulls out *streamPtr.
1781 *----------------------------------------------------------------------
1783 void FreeStream(FCGX_Stream **streamPtr)
1785 FCGX_Stream *stream = *streamPtr;
1786 FCGX_Stream_Data *data;
1787 if(stream == NULL) {
1790 data = stream->data;
1791 data->reqDataPtr = NULL;
1799 *----------------------------------------------------------------------
1803 * Re-initializes the stream to read data of the specified type.
1805 *----------------------------------------------------------------------
1807 static FCGX_Stream *SetReaderType(FCGX_Stream *stream, int streamType)
1809 FCGX_Stream_Data *data = stream->data;
1810 ASSERT(stream->isReader);
1811 data->type = streamType;
1812 data->eorStop = FALSE;
1814 data->contentLen = 0;
1815 data->paddingLen = 0;
1816 stream->wrNext = stream->stop = stream->rdNext;
1817 stream->isClosed = FALSE;
1822 *----------------------------------------------------------------------
1826 * Creates a stream to read streamType records for the given
1827 * request. The stream performs OS reads of up to bufflen bytes.
1829 *----------------------------------------------------------------------
1831 static FCGX_Stream *NewReader(ReqData *reqDataPtr, int bufflen, int streamType)
1833 return NewStream(reqDataPtr, bufflen, TRUE, streamType);
1838 *----------------------------------------------------------------------
1842 * Creates a stream to write streamType FastCGI records, using
1843 * the ipcFd and RequestId contained in *reqDataPtr.
1844 * The stream performs OS writes of up to bufflen bytes.
1846 *----------------------------------------------------------------------
1848 static FCGX_Stream *NewWriter(ReqData *reqDataPtr, int bufflen, int streamType)
1850 return NewStream(reqDataPtr, bufflen, FALSE, streamType);
1855 *----------------------------------------------------------------------
1859 * Creates a stream to write streamType FastCGI records, using
1860 * the given ipcFd and request Id. This function is provided
1861 * for use by cgi-fcgi. In order to be defensive against misuse,
1862 * this function leaks a little storage; cgi-fcgi doesn't care.
1864 *----------------------------------------------------------------------
1866 FCGX_Stream *CreateWriter(
1872 ReqData *reqDataPtr = Malloc(sizeof(ReqData));
1873 reqDataPtr->ipcFd = ipcFd;
1874 reqDataPtr->requestId = requestId;
1876 * Suppress writing an FCGI_END_REQUEST record.
1878 reqDataPtr->nWriters = 2;
1879 return NewWriter(reqDataPtr, bufflen, streamType);
1883 *======================================================================
1885 *======================================================================
1888 static int isCGI = -1;
1889 static int isFastCGI = -1;
1892 *----------------------------------------------------------------------
1896 * This routine determines if the process is running as a CGI or
1897 * FastCGI process. The distinction is made by determining whether
1898 * FCGI_LISTENSOCK_FILENO is a listener ipcFd or the end of a
1899 * pipe (ie. standard in).
1902 * TRUE if the process is a CGI process, FALSE if FastCGI.
1905 * If this is a FastCGI process there's a chance that a connection
1906 * will be accepted while performing the test. If this occurs,
1907 * the connection is saved and used later by the FCGX_Accept logic.
1909 *----------------------------------------------------------------------
1911 int FCGX_IsCGI(void)
1914 * Already been here, no need to test again.
1920 if(!osLibInitialized) {
1921 if(OS_LibInit(NULL) == -1) {
1924 osLibInitialized = 1;
1927 isFastCGI = OS_IsFcgi();
1933 *----------------------------------------------------------------------
1937 * Finishes the current request from the HTTP server.
1941 * Finishes the request accepted by (and frees any
1942 * storage allocated by) the previous call to FCGX_Accept.
1944 * DO NOT retain pointers to the envp array or any strings
1945 * contained in it (e.g. to the result of calling FCGX_GetParam),
1946 * since these will be freed by the next call to FCGX_Finish
1949 *----------------------------------------------------------------------
1951 static ReqData *reqDataPtr = NULL;
1953 void FCGX_Finish(void)
1955 if(reqDataPtr != NULL && reqDataPtr->inStream != NULL) {
1957 * Complete the previous request.
1959 int errStatus = FCGX_FClose(reqDataPtr->errStream);
1960 int outStatus = FCGX_FClose(reqDataPtr->outStream);
1961 int prevRequestFailed = (errStatus != 0)
1963 || (FCGX_GetError(reqDataPtr->inStream) != 0);
1964 ASSERT(reqDataPtr->nWriters == 0);
1965 FreeStream(&reqDataPtr->inStream);
1966 FreeStream(&reqDataPtr->outStream);
1967 FreeStream(&reqDataPtr->errStream);
1968 FreeParams(&reqDataPtr->paramsPtr);
1969 if(prevRequestFailed || !reqDataPtr->keepConnection) {
1970 OS_IpcClose(reqDataPtr->ipcFd);
1971 reqDataPtr->ipcFd = -1;
1977 *----------------------------------------------------------------------
1981 * Accepts a new request from the HTTP server.
1984 * 0 for successful call, -1 for error.
1988 * Finishes the request accepted by (and frees any
1989 * storage allocated by) the previous call to FCGX_Accept.
1990 * Creates input, output, and error streams and
1991 * assigns them to *in, *out, and *err respectively.
1992 * Creates a parameters data structure to be accessed
1993 * via getenv(3) (if assigned to environ) or by FCGX_GetParam
1994 * and assigns it to *envp.
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
2001 *----------------------------------------------------------------------
2003 static ReqData reqData;
2004 static char *webServerAddressList = NULL;
2010 FCGX_ParamArray *envp)
2013 * If our compiler doesn't play by the ISO rules for struct
2016 ASSERT(sizeof(FCGI_Header) == FCGI_HEADER_LEN);
2018 if(!osLibInitialized) {
2019 if(OS_LibInit(NULL) == -1) {
2022 osLibInitialized = 1;
2026 * If our compiler doesn't play by the ISO rules for struct
2029 ASSERT(sizeof(FCGI_Header) == FCGI_HEADER_LEN);
2031 if(reqDataPtr == NULL) {
2033 * Very first call, so capture FCGI_WEB_SERVER_ADDRS from
2034 * the initial environment, and initialize reqDataPtr
2035 * and parts of reqData.
2037 char *p = getenv("FCGI_WEB_SERVER_ADDRS");
2039 webServerAddressList = StringCopy(p);
2041 reqDataPtr = &reqData;
2042 reqDataPtr->ipcFd = -1;
2043 reqDataPtr->inStream = NULL;
2044 reqDataPtr->outStream = NULL;
2045 reqDataPtr->errStream = NULL;
2048 * Not the first call. Finish the current request, if any.
2054 * If a connection isn't open, accept a new connection (blocking).
2055 * If an OS error occurs in accepting the connection,
2056 * return -1 to the caller, who should exit.
2058 if(reqDataPtr->ipcFd < 0) {
2059 reqDataPtr->ipcFd = OS_FcgiIpcAccept(webServerAddressList);
2060 if(reqDataPtr->ipcFd < 0) {
2066 * A connection is open. Read from the connection in order to
2067 * get the request's role and environment. If protocol or other
2068 * errors occur, close the connection and try again.
2070 reqDataPtr->isBeginProcessed = FALSE;
2071 reqDataPtr->inStream = NewReader(reqDataPtr, 8192, 0);
2072 FillBuffProc(reqDataPtr->inStream);
2073 if(!reqDataPtr->isBeginProcessed) {
2078 switch(reqDataPtr->role) {
2079 case FCGI_RESPONDER:
2080 roleStr = "FCGI_ROLE=RESPONDER";
2082 case FCGI_AUTHORIZER:
2083 roleStr = "FCGI_ROLE=AUTHORIZER";
2086 roleStr = "FCGI_ROLE=FILTER";
2091 reqDataPtr->paramsPtr = NewParams(30);
2092 PutParam(reqDataPtr->paramsPtr, StringCopy(roleStr));
2094 SetReaderType(reqDataPtr->inStream, FCGI_PARAMS);
2095 if(ReadParams(reqDataPtr->paramsPtr, reqDataPtr->inStream) >= 0) {
2097 * Finished reading the environment. No errors occurred, so
2098 * leave the connection-retry loop.
2103 * Close the connection and try again.
2106 FreeParams(&reqDataPtr->paramsPtr);
2107 FreeStream(&reqDataPtr->inStream);
2108 OS_Close(reqDataPtr->ipcFd);
2109 reqDataPtr->ipcFd = -1;
2112 * Build the remaining data structures representing the new
2113 * request and return successfully to the caller.
2115 SetReaderType(reqDataPtr->inStream, FCGI_STDIN);
2116 reqDataPtr->outStream = NewWriter(reqDataPtr, 8192, FCGI_STDOUT);
2117 reqDataPtr->errStream = NewWriter(reqDataPtr, 512, FCGI_STDERR);
2118 reqDataPtr->nWriters = 2;
2119 *in = reqDataPtr->inStream;
2120 *out = reqDataPtr->outStream;
2121 *err = reqDataPtr->errStream;
2122 *envp = reqDataPtr->paramsPtr->vec;
2127 *----------------------------------------------------------------------
2129 * FCGX_StartFilterData --
2131 * stream is an input stream for a FCGI_FILTER request.
2132 * stream is positioned at EOF on FCGI_STDIN.
2133 * Repositions stream to the start of FCGI_DATA.
2134 * If the preconditions are not met (e.g. FCGI_STDIN has not
2135 * been read to EOF) sets the stream error code to
2136 * FCGX_CALL_SEQ_ERROR.
2139 * 0 for a normal return, < 0 for error
2141 *----------------------------------------------------------------------
2144 int FCGX_StartFilterData(FCGX_Stream *stream)
2146 FCGX_Stream_Data *data = stream->data;
2147 if(data->reqDataPtr->role != FCGI_FILTER
2148 || !stream->isReader
2149 || !stream->isClosed
2150 || data->type != FCGI_STDIN) {
2151 SetError(stream, FCGX_CALL_SEQ_ERROR);
2154 SetReaderType(reqDataPtr->inStream, FCGI_DATA);
2159 *----------------------------------------------------------------------
2161 * FCGX_SetExitStatus --
2163 * Sets the exit status for stream's request. The exit status
2164 * is the status code the request would have exited with, had
2165 * the request been run as a CGI program. You can call
2166 * SetExitStatus several times during a request; the last call
2167 * before the request ends determines the value.
2169 *----------------------------------------------------------------------
2172 void FCGX_SetExitStatus(int status, FCGX_Stream *stream)
2174 FCGX_Stream_Data *data = stream->data;
2175 data->reqDataPtr->appStatus = status;