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.
14 static const char rcsid[] = "$Id: fcgiapp.c,v 1.23 2001/06/20 16:50:02 robs Exp $";
19 #include <fcntl.h> /* for fcntl */
21 #include <memory.h> /* for memchr() */
26 #include <sys/types.h>
28 #include "fcgi_config.h"
30 #ifdef HAVE_SYS_SOCKET_H
31 #include <sys/socket.h> /* for getpeername */
34 #ifdef HAVE_SYS_TIME_H
47 #define DLLAPI __declspec(dllexport)
51 #include "fcgiappmisc.h"
58 * This is a workaround for one version of the HP C compiler
59 * (c89 on HP-UX 9.04, also Stratus FTX), which will dump core
60 * if given 'long double' for varargs.
62 #ifdef HAVE_VA_ARG_LONG_DOUBLE_BUG
63 #define LONG_DOUBLE double
65 #define LONG_DOUBLE long double
71 static int libInitialized = 0;
72 static int isFastCGI = -1;
73 static char *webServerAddressList = NULL;
74 static FCGX_Request the_request;
76 static void *Malloc(size_t size)
78 void *result = malloc(size);
79 ASSERT(size == 0 || result != NULL);
83 static char *StringCopy(char *str)
85 int strLen = strlen(str);
86 char *newString = (char *)Malloc(strLen + 1);
87 memcpy(newString, str, strLen);
88 newString[strLen] = '\000';
94 *----------------------------------------------------------------------
98 * Reads a byte from the input stream and returns it.
101 * The byte, or EOF (-1) if the end of input has been reached.
103 *----------------------------------------------------------------------
105 int FCGX_GetChar(FCGX_Stream *stream)
107 if(stream->rdNext != stream->stop)
108 return *stream->rdNext++;
109 if(stream->isClosed || !stream->isReader)
111 stream->fillBuffProc(stream);
112 stream->stopUnget = stream->rdNext;
113 if(stream->rdNext != stream->stop)
114 return *stream->rdNext++;
115 ASSERT(stream->isClosed); /* bug in fillBufProc if not */
120 *----------------------------------------------------------------------
124 * Reads up to n consecutive bytes from the input stream
125 * into the character array str. Performs no interpretation
126 * of the input bytes.
129 * Number of bytes read. If result is smaller than n,
130 * the end of input has been reached.
132 *----------------------------------------------------------------------
134 int FCGX_GetStr(char *str, int n, FCGX_Stream *stream)
142 * Fast path: n bytes are already available
144 if(n <= (stream->stop - stream->rdNext)) {
145 memcpy(str, stream->rdNext, n);
150 * General case: stream is closed or buffer fill procedure
155 if(stream->rdNext != stream->stop) {
156 m = min(n - bytesMoved, stream->stop - stream->rdNext);
157 memcpy(str, stream->rdNext, m);
164 if(stream->isClosed || !stream->isReader)
166 stream->fillBuffProc(stream);
167 stream->stopUnget = stream->rdNext;
172 *----------------------------------------------------------------------
176 * Reads up to n-1 consecutive bytes from the input stream
177 * into the character array str. Stops before n-1 bytes
178 * have been read if '\n' or EOF is read. The terminating '\n'
179 * is copied to str. After copying the last byte into str,
180 * stores a '\0' terminator.
183 * NULL if EOF is the first thing read from the input stream,
186 *----------------------------------------------------------------------
188 char *FCGX_GetLine(char *str, int n, FCGX_Stream *stream)
195 c = FCGX_GetChar(stream);
212 *----------------------------------------------------------------------
216 * Pushes back the character c onto the input stream. One
217 * character of pushback is guaranteed once a character
218 * has been read. No pushback is possible for EOF.
221 * Returns c if the pushback succeeded, EOF if not.
223 *----------------------------------------------------------------------
225 int FCGX_UnGetChar(int c, FCGX_Stream *stream) {
229 || stream->rdNext == stream->stopUnget)
232 *stream->rdNext = (unsigned char) c;
237 *----------------------------------------------------------------------
241 * Returns EOF if end-of-file has been detected while reading
242 * from stream; otherwise returns 0.
244 * Note that FCGX_HasSeenEOF(s) may return 0, yet an immediately
245 * following FCGX_GetChar(s) may return EOF. This function, like
246 * the standard C stdio function feof, does not provide the
247 * ability to peek ahead.
250 * EOF if end-of-file has been detected, 0 if not.
252 *----------------------------------------------------------------------
254 int FCGX_HasSeenEOF(FCGX_Stream *stream) {
255 return (stream->isClosed) ? EOF : 0;
259 *----------------------------------------------------------------------
263 * Writes a byte to the output stream.
266 * The byte, or EOF (-1) if an error occurred.
268 *----------------------------------------------------------------------
270 int FCGX_PutChar(int c, FCGX_Stream *stream)
272 if(stream->wrNext != stream->stop)
273 return (*stream->wrNext++ = (unsigned char) c);
274 if(stream->isClosed || stream->isReader)
276 stream->emptyBuffProc(stream, FALSE);
277 if(stream->wrNext != stream->stop)
278 return (*stream->wrNext++ = (unsigned char) c);
279 ASSERT(stream->isClosed); /* bug in emptyBuffProc if not */
284 *----------------------------------------------------------------------
288 * Writes n consecutive bytes from the character array str
289 * into the output stream. Performs no interpretation
290 * of the output bytes.
293 * Number of bytes written (n) for normal return,
294 * EOF (-1) if an error occurred.
296 *----------------------------------------------------------------------
298 int FCGX_PutStr(const char *str, int n, FCGX_Stream *stream)
303 * Fast path: room for n bytes in the buffer
305 if(n <= (stream->stop - stream->wrNext)) {
306 memcpy(stream->wrNext, str, n);
311 * General case: stream is closed or buffer empty procedure
316 if(stream->wrNext != stream->stop) {
317 m = min(n - bytesMoved, stream->stop - stream->wrNext);
318 memcpy(stream->wrNext, str, m);
325 if(stream->isClosed || stream->isReader)
327 stream->emptyBuffProc(stream, FALSE);
332 *----------------------------------------------------------------------
336 * Writes a character string to the output stream.
339 * number of bytes written for normal return,
340 * EOF (-1) if an error occurred.
342 *----------------------------------------------------------------------
344 int FCGX_PutS(const char *str, FCGX_Stream *stream)
346 return FCGX_PutStr(str, strlen(str), stream);
350 *----------------------------------------------------------------------
354 * Performs output formatting and writes the results
355 * to the output stream.
358 * number of bytes written for normal return,
359 * EOF (-1) if an error occurred.
361 *----------------------------------------------------------------------
363 int FCGX_FPrintF(FCGX_Stream *stream, const char *format, ...)
367 va_start(ap, format);
368 result = FCGX_VFPrintF(stream, format, ap);
374 *----------------------------------------------------------------------
378 * Performs output formatting and writes the results
379 * to the output stream.
382 * number of bytes written for normal return,
383 * EOF (-1) if an error occurred.
385 *----------------------------------------------------------------------
388 #define PRINTF_BUFFLEN 100
390 * More than sufficient space for all unmodified conversions
393 #define FMT_BUFFLEN 25
395 * Max size of a format specifier is 1 + 5 + 7 + 7 + 2 + 1 + slop
397 static void CopyAndAdvance(char **destPtr, char **srcPtr, int n);
399 int FCGX_VFPrintF(FCGX_Stream *stream, const char *format, va_list arg)
401 char *f, *fStop, *percentPtr, *p, *fmtBuffPtr, *buffPtr;
402 int op, performedOp, sizeModifier, buffCount = 0, buffLen, specifierLength;
403 int fastPath, n, auxBuffLen = 0, buffReqd, minWidth, precision, exp;
404 char *auxBuffPtr = NULL;
406 char fmtBuff[FMT_BUFFLEN];
407 char buff[PRINTF_BUFFLEN];
412 unsigned unsignedArg;
413 unsigned long uLongArg;
414 unsigned short uShortArg;
415 char *charPtrArg = NULL;
420 double doubleArg = 0.0;
421 LONG_DOUBLE lDoubleArg = 0.0L;
425 fStop = f + strlen(f);
427 percentPtr = (char *)memchr(f, '%', fStop - f);
428 if(percentPtr == NULL) percentPtr = fStop;
429 if(percentPtr != f) {
430 if(FCGX_PutStr(f, percentPtr - f, stream) < 0)
432 streamCount += percentPtr - f;
434 if(f == fStop) break;
438 * The following loop always executes either once or twice.
443 * Fast path: Scan optimistically, hoping that no flags,
444 * minimum field width, or precision are specified.
445 * Use the preallocated buffer, which is large enough
446 * for all fast path cases. If the conversion specifier
447 * is really more complex, run the loop a second time
448 * using the slow path.
449 * Note that fast path execution of %s bypasses the buffer
450 * and %f is not attempted on the fast path due to
451 * its large buffering requirements.
453 op = *(percentPtr + 1);
459 op = *(percentPtr + 2);
460 fmtBuff[1] = (char) sizeModifier;
461 fmtBuff[2] = (char) op;
467 fmtBuff[1] = (char) op;
473 buffLen = PRINTF_BUFFLEN;
476 * Slow path: Scan the conversion specifier and construct
477 * a new format string, compute an upper bound on the
478 * amount of buffering that sprintf will require,
479 * and allocate a larger buffer if necessary.
482 fmtBuffPtr = &fmtBuff[1];
486 n = strspn(p, "-0+ #");
489 CopyAndAdvance(&fmtBuffPtr, &p, n);
491 * Scan minimum field width
493 n = strspn(p, "0123456789");
496 minWidth = va_arg(arg, int);
497 if(abs(minWidth) > 999999)
500 * The following use of strlen rather than the
501 * value returned from sprintf is because SUNOS4
502 * returns a char * instead of an int count.
504 sprintf(fmtBuffPtr, "%d", minWidth);
505 fmtBuffPtr += strlen(fmtBuffPtr);
511 minWidth = strtol(p, NULL, 10);
512 CopyAndAdvance(&fmtBuffPtr, &p, n);
520 CopyAndAdvance(&fmtBuffPtr, &p, 1);
521 n = strspn(p, "0123456789");
524 precision = va_arg(arg, int);
525 if(precision < 0) precision = 0;
526 if(precision > 999999)
529 * The following use of strlen rather than the
530 * value returned from sprintf is because SUNOS4
531 * returns a char * instead of an int count.
533 sprintf(fmtBuffPtr, "%d", precision);
534 fmtBuffPtr += strlen(fmtBuffPtr);
540 precision = strtol(p, NULL, 10);
541 CopyAndAdvance(&fmtBuffPtr, &p, n);
549 * Scan size modifier and conversion operation
556 CopyAndAdvance(&fmtBuffPtr, &p, 1);
563 CopyAndAdvance(&fmtBuffPtr, &p, 1);
564 ASSERT(fmtBuffPtr - fmtBuff < FMT_BUFFLEN);
566 specifierLength = p - percentPtr;
568 * Bound the required buffer size. For s and f
569 * conversions this requires examining the argument.
580 buffReqd = max(precision, 46);
583 charPtrArg = va_arg(arg, char *);
584 if (!charPtrArg) charPtrArg = "(null)";
585 if(precision == -1) {
586 buffReqd = strlen(charPtrArg);
588 p = (char *)memchr(charPtrArg, '\0', precision);
590 (p == NULL) ? precision : p - charPtrArg;
594 switch(sizeModifier) {
596 doubleArg = va_arg(arg, double);
597 frexp(doubleArg, &exp);
600 lDoubleArg = va_arg(arg, LONG_DOUBLE);
601 /* XXX Need to check for the presence of
602 * frexpl() and use it if available */
603 frexp((double) lDoubleArg, &exp);
608 if(precision == -1) precision = 6;
609 buffReqd = precision + 3 + ((exp > 0) ? exp/3 : 0);
615 if(precision == -1) precision = 6;
616 buffReqd = precision + 8;
624 buffReqd = max(buffReqd + 10, minWidth);
626 * Allocate the buffer
628 if(buffReqd <= PRINTF_BUFFLEN) {
630 buffLen = PRINTF_BUFFLEN;
632 if(auxBuffPtr == NULL || buffReqd > auxBuffLen) {
633 if(auxBuffPtr != NULL) free(auxBuffPtr);
634 auxBuffPtr = (char *)Malloc(buffReqd);
635 auxBuffLen = buffReqd;
636 if(auxBuffPtr == NULL)
639 buffPtr = auxBuffPtr;
640 buffLen = auxBuffLen;
644 * This giant switch statement requires the following variables
645 * to be set up: op, sizeModifier, arg, buffPtr, fmtBuff.
646 * When fastPath == FALSE and op == 's' or 'f', the argument
647 * has been read into charPtrArg, doubleArg, or lDoubleArg.
648 * The statement produces the boolean performedOp, TRUE iff
649 * the op/sizeModifier were executed and argument consumed;
650 * if performedOp, the characters written into buffPtr[]
651 * and the character count buffCount (== EOF meaning error).
653 * The switch cases are arranged in the same order as in the
654 * description of fprintf in section 15.11 of Harbison and Steele.
660 switch(sizeModifier) {
662 intArg = va_arg(arg, int);
663 sprintf(buffPtr, fmtBuff, intArg);
664 buffCount = strlen(buffPtr);
667 longArg = va_arg(arg, long);
668 sprintf(buffPtr, fmtBuff, longArg);
669 buffCount = strlen(buffPtr);
672 shortArg = (short) va_arg(arg, int);
673 sprintf(buffPtr, fmtBuff, shortArg);
674 buffCount = strlen(buffPtr);
684 switch(sizeModifier) {
686 unsignedArg = va_arg(arg, unsigned);
687 sprintf(buffPtr, fmtBuff, unsignedArg);
688 buffCount = strlen(buffPtr);
691 uLongArg = va_arg(arg, unsigned long);
692 sprintf(buffPtr, fmtBuff, uLongArg);
693 buffCount = strlen(buffPtr);
696 uShortArg = (unsigned short) va_arg(arg, int);
697 sprintf(buffPtr, fmtBuff, uShortArg);
698 buffCount = strlen(buffPtr);
705 switch(sizeModifier) {
707 intArg = va_arg(arg, int);
708 sprintf(buffPtr, fmtBuff, intArg);
709 buffCount = strlen(buffPtr);
713 * XXX: Allowed by ISO C Amendment 1, but
714 * many platforms don't yet support wint_t
722 switch(sizeModifier) {
725 buffPtr = va_arg(arg, char *);
726 buffCount = strlen(buffPtr);
727 buffLen = buffCount + 1;
729 sprintf(buffPtr, fmtBuff, charPtrArg);
730 buffCount = strlen(buffPtr);
735 * XXX: Don't know how to convert a sequence
736 * of wide characters into a byte stream, or
737 * even how to predict the buffering required.
745 if(sizeModifier != ' ')
747 voidPtrArg = va_arg(arg, void *);
748 sprintf(buffPtr, fmtBuff, voidPtrArg);
749 buffCount = strlen(buffPtr);
752 switch(sizeModifier) {
754 intPtrArg = va_arg(arg, int *);
755 *intPtrArg = streamCount;
758 longPtrArg = va_arg(arg, long *);
759 *longPtrArg = streamCount;
762 shortPtrArg = (short *) va_arg(arg, short *);
763 *shortPtrArg = (short) streamCount;
775 switch(sizeModifier) {
777 sprintf(buffPtr, fmtBuff, doubleArg);
778 buffCount = strlen(buffPtr);
781 sprintf(buffPtr, fmtBuff, lDoubleArg);
782 buffCount = strlen(buffPtr);
792 switch(sizeModifier) {
794 doubleArg = va_arg(arg, double);
795 sprintf(buffPtr, fmtBuff, doubleArg);
796 buffCount = strlen(buffPtr);
799 lDoubleArg = va_arg(arg, LONG_DOUBLE);
800 sprintf(buffPtr, fmtBuff, lDoubleArg);
801 buffCount = strlen(buffPtr);
808 if(sizeModifier != ' ')
819 if(performedOp) break;
824 ASSERT(buffCount < buffLen);
826 if(FCGX_PutStr(buffPtr, buffCount, stream) < 0)
828 streamCount += buffCount;
829 } else if(buffCount < 0) {
832 f += specifierLength;
833 } /* while(f != fStop) */
838 if(auxBuffPtr != NULL) free(auxBuffPtr);
843 * Copy n characters from *srcPtr to *destPtr, then increment
844 * both *srcPtr and *destPtr by n.
846 static void CopyAndAdvance(char **destPtr, char **srcPtr, int n)
848 char *dest = *destPtr;
851 for (i = 0; i < n; i++)
858 *----------------------------------------------------------------------
862 * Flushes any buffered output.
864 * Server-push is a legitimate application of FCGX_FFlush.
865 * Otherwise, FCGX_FFlush is not very useful, since FCGX_Accept
866 * does it implicitly. FCGX_FFlush may reduce performance
867 * by increasing the total number of operating system calls
868 * the application makes.
871 * EOF (-1) if an error occurred.
873 *----------------------------------------------------------------------
875 int FCGX_FFlush(FCGX_Stream *stream)
877 if(stream->isClosed || stream->isReader)
879 stream->emptyBuffProc(stream, FALSE);
880 return (stream->isClosed) ? -1 : 0;
884 *----------------------------------------------------------------------
888 * Performs FCGX_FFlush and closes the stream.
890 * This is not a very useful operation, since FCGX_Accept
891 * does it implicitly. Closing the out stream before the
892 * err stream results in an extra write if there's nothing
893 * in the err stream, and therefore reduces performance.
896 * EOF (-1) if an error occurred.
898 *----------------------------------------------------------------------
900 int FCGX_FClose(FCGX_Stream *stream)
902 if (stream == NULL) return 0;
904 if(!stream->wasFCloseCalled) {
905 if(!stream->isReader) {
906 stream->emptyBuffProc(stream, TRUE);
908 stream->wasFCloseCalled = TRUE;
909 stream->isClosed = TRUE;
910 if(stream->isReader) {
911 stream->wrNext = stream->stop = stream->rdNext;
913 stream->rdNext = stream->stop = stream->wrNext;
916 return (stream->FCGI_errno == 0) ? 0 : EOF;
920 *----------------------------------------------------------------------
924 * An error has occurred; save the error code in the stream
925 * for diagnostic purposes and set the stream state so that
926 * reads return EOF and writes have no effect.
928 *----------------------------------------------------------------------
930 static void SetError(FCGX_Stream *stream, int FCGI_errno)
933 * Preserve only the first error.
935 if(stream->FCGI_errno == 0) {
936 stream->FCGI_errno = FCGI_errno;
937 stream->isClosed = TRUE;
942 *----------------------------------------------------------------------
946 * Return the stream error code. 0 means no error, > 0
947 * is an errno(2) error, < 0 is an FCGX_errno error.
949 *----------------------------------------------------------------------
951 int FCGX_GetError(FCGX_Stream *stream) {
952 return stream->FCGI_errno;
956 *----------------------------------------------------------------------
960 * Clear the stream error code and end-of-file indication.
962 *----------------------------------------------------------------------
964 void FCGX_ClearError(FCGX_Stream *stream) {
965 stream->FCGI_errno = 0;
967 * stream->isClosed = FALSE;
968 * XXX: should clear isClosed but work is needed to make it safe
969 * to do so. For example, if an application calls FClose, gets
970 * an I/O error on the write, calls ClearError and retries
971 * the FClose, FClose (really EmptyBuffProc) will write a second
972 * EOF record. If an application calls PutChar instead of FClose
973 * after the ClearError, the application will write more data.
974 * The stream's state must discriminate between various states
975 * of the stream that are now all lumped under isClosed.
980 *======================================================================
982 *======================================================================
986 * A vector of pointers representing the parameters received
987 * by a FastCGI application server, with the vector's length
988 * and last valid element so adding new parameters is efficient.
991 typedef struct Params {
992 FCGX_ParamArray vec; /* vector of strings */
993 int length; /* number of string vec can hold */
994 char **cur; /* current item in vec; *cur == NULL */
996 typedef Params *ParamsPtr;
999 *----------------------------------------------------------------------
1003 * Creates a new Params structure.
1006 * Pointer to the new structure.
1008 *----------------------------------------------------------------------
1010 static ParamsPtr NewParams(int length)
1013 result = (Params *)Malloc(sizeof(Params));
1014 result->vec = (char **)Malloc(length * sizeof(char *));
1015 result->length = length;
1016 result->cur = result->vec;
1017 *result->cur = NULL;
1022 *----------------------------------------------------------------------
1026 * Frees a Params structure and all the parameters it contains.
1029 * env becomes invalid.
1031 *----------------------------------------------------------------------
1033 static void FreeParams(ParamsPtr *paramsPtrPtr)
1035 ParamsPtr paramsPtr = *paramsPtrPtr;
1037 if(paramsPtr == NULL) {
1040 for (p = paramsPtr->vec; p < paramsPtr->cur; p++) {
1043 free(paramsPtr->vec);
1045 *paramsPtrPtr = NULL;
1049 *----------------------------------------------------------------------
1053 * Add a name/value pair to a Params structure.
1059 * Parameters structure updated.
1061 *----------------------------------------------------------------------
1063 static void PutParam(ParamsPtr paramsPtr, char *nameValue)
1067 *paramsPtr->cur++ = nameValue;
1068 size = paramsPtr->cur - paramsPtr->vec;
1069 if(size >= paramsPtr->length) {
1070 paramsPtr->length *= 2;
1071 paramsPtr->vec = (FCGX_ParamArray)realloc(paramsPtr->vec, paramsPtr->length * sizeof(char *));
1072 paramsPtr->cur = paramsPtr->vec + size;
1074 *paramsPtr->cur = NULL;
1078 *----------------------------------------------------------------------
1080 * FCGX_GetParam -- obtain value of FCGI parameter in environment
1084 * Value bound to name, NULL if name not present in the
1085 * environment envp. Caller must not mutate the result
1086 * or retain it past the end of this request.
1088 *----------------------------------------------------------------------
1090 char *FCGX_GetParam(const char *name, FCGX_ParamArray envp)
1095 if (name == NULL || envp == NULL) return NULL;
1099 for (p = envp; *p; ++p) {
1100 if((strncmp(name, *p, len) == 0) && ((*p)[len] == '=')) {
1108 *----------------------------------------------------------------------
1110 * Start of FastCGI-specific code
1112 *----------------------------------------------------------------------
1116 *----------------------------------------------------------------------
1120 * Reads FastCGI name-value pairs from stream until EOF. Converts
1121 * each pair to name=value format and adds it to Params structure.
1123 *----------------------------------------------------------------------
1125 static int ReadParams(Params *paramsPtr, FCGX_Stream *stream)
1127 int nameLen, valueLen;
1128 unsigned char lenBuff[3];
1131 while((nameLen = FCGX_GetChar(stream)) != EOF) {
1133 * Read name length (one or four bytes) and value length
1134 * (one or four bytes) from stream.
1136 if((nameLen & 0x80) != 0) {
1137 if(FCGX_GetStr((char *) &lenBuff[0], 3, stream) != 3) {
1138 SetError(stream, FCGX_PARAMS_ERROR);
1141 nameLen = ((nameLen & 0x7f) << 24) + (lenBuff[0] << 16)
1142 + (lenBuff[1] << 8) + lenBuff[2];
1144 if((valueLen = FCGX_GetChar(stream)) == EOF) {
1145 SetError(stream, FCGX_PARAMS_ERROR);
1148 if((valueLen & 0x80) != 0) {
1149 if(FCGX_GetStr((char *) &lenBuff[0], 3, stream) != 3) {
1150 SetError(stream, FCGX_PARAMS_ERROR);
1153 valueLen = ((valueLen & 0x7f) << 24) + (lenBuff[0] << 16)
1154 + (lenBuff[1] << 8) + lenBuff[2];
1157 * nameLen and valueLen are now valid; read the name and value
1158 * from stream and construct a standard environment entry.
1160 nameValue = (char *)Malloc(nameLen + valueLen + 2);
1161 if(FCGX_GetStr(nameValue, nameLen, stream) != nameLen) {
1162 SetError(stream, FCGX_PARAMS_ERROR);
1166 *(nameValue + nameLen) = '=';
1167 if(FCGX_GetStr(nameValue + nameLen + 1, valueLen, stream)
1169 SetError(stream, FCGX_PARAMS_ERROR);
1173 *(nameValue + nameLen + valueLen + 1) = '\0';
1174 PutParam(paramsPtr, nameValue);
1180 *----------------------------------------------------------------------
1184 * Constructs an FCGI_Header struct.
1186 *----------------------------------------------------------------------
1188 static FCGI_Header MakeHeader(
1195 ASSERT(contentLength >= 0 && contentLength <= FCGI_MAX_LENGTH);
1196 ASSERT(paddingLength >= 0 && paddingLength <= 0xff);
1197 header.version = FCGI_VERSION_1;
1198 header.type = (unsigned char) type;
1199 header.requestIdB1 = (unsigned char) ((requestId >> 8) & 0xff);
1200 header.requestIdB0 = (unsigned char) ((requestId ) & 0xff);
1201 header.contentLengthB1 = (unsigned char) ((contentLength >> 8) & 0xff);
1202 header.contentLengthB0 = (unsigned char) ((contentLength ) & 0xff);
1203 header.paddingLength = (unsigned char) paddingLength;
1204 header.reserved = 0;
1209 *----------------------------------------------------------------------
1211 * MakeEndRequestBody --
1213 * Constructs an FCGI_EndRequestBody struct.
1215 *----------------------------------------------------------------------
1217 static FCGI_EndRequestBody MakeEndRequestBody(
1221 FCGI_EndRequestBody body;
1222 body.appStatusB3 = (unsigned char) ((appStatus >> 24) & 0xff);
1223 body.appStatusB2 = (unsigned char) ((appStatus >> 16) & 0xff);
1224 body.appStatusB1 = (unsigned char) ((appStatus >> 8) & 0xff);
1225 body.appStatusB0 = (unsigned char) ((appStatus ) & 0xff);
1226 body.protocolStatus = (unsigned char) protocolStatus;
1227 memset(body.reserved, 0, sizeof(body.reserved));
1232 *----------------------------------------------------------------------
1234 * MakeUnknownTypeBody --
1236 * Constructs an FCGI_MakeUnknownTypeBody struct.
1238 *----------------------------------------------------------------------
1240 static FCGI_UnknownTypeBody MakeUnknownTypeBody(
1243 FCGI_UnknownTypeBody body;
1244 body.type = (unsigned char) type;
1245 memset(body.reserved, 0, sizeof(body.reserved));
1250 *----------------------------------------------------------------------
1254 * Returns the smallest integer greater than or equal to n
1255 * that's a multiple of 8.
1257 *----------------------------------------------------------------------
1259 static int AlignInt8(unsigned n) {
1260 return (n + 7) & (UINT_MAX - 7);
1264 *----------------------------------------------------------------------
1268 * Returns the smallest pointer greater than or equal to p
1269 * that's a multiple of 8.
1271 *----------------------------------------------------------------------
1273 static unsigned char *AlignPtr8(unsigned char *p) {
1274 unsigned long u = (unsigned long) p;
1275 u = ((u + 7) & (ULONG_MAX - 7)) - u;
1281 * State associated with a stream
1283 typedef struct FCGX_Stream_Data {
1284 unsigned char *buff; /* buffer after alignment */
1285 int bufflen; /* number of bytes buff can store */
1286 unsigned char *mBuff; /* buffer as returned by Malloc */
1287 unsigned char *buffStop; /* reader: last valid byte + 1 of entire buffer.
1288 * stop generally differs from buffStop for
1289 * readers because of record structure.
1290 * writer: buff + bufflen */
1291 int type; /* reader: FCGI_PARAMS or FCGI_STDIN
1292 * writer: FCGI_STDOUT or FCGI_STDERR */
1293 int eorStop; /* reader: stop stream at end-of-record */
1294 int skip; /* reader: don't deliver content bytes */
1295 int contentLen; /* reader: bytes of unread content */
1296 int paddingLen; /* reader: bytes of unread padding */
1297 int isAnythingWritten; /* writer: data has been written to ipcFd */
1298 int rawWrite; /* writer: write data without stream headers */
1299 FCGX_Request *reqDataPtr; /* request data not specific to one stream */
1303 *----------------------------------------------------------------------
1305 * WriteCloseRecords --
1307 * Writes an EOF record for the stream content if necessary.
1308 * If this is the last writer to close, writes an FCGI_END_REQUEST
1311 *----------------------------------------------------------------------
1313 static void WriteCloseRecords(struct FCGX_Stream *stream)
1315 FCGX_Stream_Data *data = (FCGX_Stream_Data *)stream->data;
1317 * Enter rawWrite mode so final records won't be encapsulated as
1320 data->rawWrite = TRUE;
1322 * Generate EOF for stream content if needed.
1324 if(!(data->type == FCGI_STDERR
1325 && stream->wrNext == data->buff
1326 && !data->isAnythingWritten)) {
1328 header = MakeHeader(data->type, data->reqDataPtr->requestId, 0, 0);
1329 FCGX_PutStr((char *) &header, sizeof(header), stream);
1332 * Generate FCGI_END_REQUEST record if needed.
1334 if(data->reqDataPtr->nWriters == 1) {
1335 FCGI_EndRequestRecord endRequestRecord;
1336 endRequestRecord.header = MakeHeader(FCGI_END_REQUEST,
1337 data->reqDataPtr->requestId,
1338 sizeof(endRequestRecord.body), 0);
1339 endRequestRecord.body = MakeEndRequestBody(
1340 data->reqDataPtr->appStatus, FCGI_REQUEST_COMPLETE);
1341 FCGX_PutStr((char *) &endRequestRecord,
1342 sizeof(endRequestRecord), stream);
1344 data->reqDataPtr->nWriters--;
1349 static int write_it_all(int fd, char *buf, int len)
1354 wrote = OS_Write(fd, buf, len);
1364 *----------------------------------------------------------------------
1368 * Encapsulates any buffered stream content in a FastCGI
1369 * record. Writes the data, making the buffer empty.
1371 *----------------------------------------------------------------------
1373 static void EmptyBuffProc(struct FCGX_Stream *stream, int doClose)
1375 FCGX_Stream_Data *data = (FCGX_Stream_Data *)stream->data;
1378 * If the buffer contains stream data, fill in the header.
1379 * Pad the record to a multiple of 8 bytes in length. Padding
1380 * can't overflow the buffer because the buffer is a multiple
1381 * of 8 bytes in length. If the buffer contains no stream
1382 * data, reclaim the space reserved for the header.
1384 if(!data->rawWrite) {
1385 cLen = stream->wrNext - data->buff - sizeof(FCGI_Header);
1387 eLen = AlignInt8(cLen);
1389 * Giving the padding a well-defined value keeps Purify happy.
1391 memset(stream->wrNext, 0, eLen - cLen);
1392 stream->wrNext += eLen - cLen;
1393 *((FCGI_Header *) data->buff)
1394 = MakeHeader(data->type,
1395 data->reqDataPtr->requestId, cLen, eLen - cLen);
1397 stream->wrNext = data->buff;
1401 WriteCloseRecords(stream);
1403 if (stream->wrNext != data->buff) {
1404 data->isAnythingWritten = TRUE;
1405 if (write_it_all(data->reqDataPtr->ipcFd, (char *)data->buff, stream->wrNext - data->buff) < 0) {
1406 SetError(stream, OS_Errno);
1409 stream->wrNext = data->buff;
1412 * The buffer is empty.
1414 if(!data->rawWrite) {
1415 stream->wrNext += sizeof(FCGI_Header);
1420 * Return codes for Process* functions
1422 #define STREAM_RECORD 0
1424 #define BEGIN_RECORD 2
1425 #define MGMT_RECORD 3
1428 *----------------------------------------------------------------------
1430 * ProcessManagementRecord --
1432 * Reads and responds to a management record. The only type of
1433 * management record this library understands is FCGI_GET_VALUES.
1434 * The only variables that this library's FCGI_GET_VALUES
1435 * understands are FCGI_MAX_CONNS, FCGI_MAX_REQS, and FCGI_MPXS_CONNS.
1436 * Ignore other FCGI_GET_VALUES variables; respond to other
1437 * management records with a FCGI_UNKNOWN_TYPE record.
1439 *----------------------------------------------------------------------
1441 static int ProcessManagementRecord(int type, FCGX_Stream *stream)
1443 FCGX_Stream_Data *data = (FCGX_Stream_Data *)stream->data;
1444 ParamsPtr paramsPtr = NewParams(3);
1446 char response[64]; /* 64 = 8 + 3*(1+1+14+1)* + padding */
1447 char *responseP = &response[FCGI_HEADER_LEN];
1448 char *name, value = '\0';
1450 if(type == FCGI_GET_VALUES) {
1451 ReadParams(paramsPtr, stream);
1452 if((FCGX_GetError(stream) != 0) || (data->contentLen != 0)) {
1453 FreeParams(¶msPtr);
1454 return FCGX_PROTOCOL_ERROR;
1456 for (pPtr = paramsPtr->vec; pPtr < paramsPtr->cur; pPtr++) {
1458 *(strchr(name, '=')) = '\0';
1459 if(strcmp(name, FCGI_MAX_CONNS) == 0) {
1461 } else if(strcmp(name, FCGI_MAX_REQS) == 0) {
1463 } else if(strcmp(name, FCGI_MPXS_CONNS) == 0) {
1470 sprintf(responseP, "%c%c%s%c", len, 1, name, value);
1471 responseP += len + 3;
1474 len = responseP - &response[FCGI_HEADER_LEN];
1475 paddedLen = AlignInt8(len);
1476 *((FCGI_Header *) response)
1477 = MakeHeader(FCGI_GET_VALUES_RESULT, FCGI_NULL_REQUEST_ID,
1478 len, paddedLen - len);
1479 FreeParams(¶msPtr);
1481 paddedLen = len = sizeof(FCGI_UnknownTypeBody);
1482 ((FCGI_UnknownTypeRecord *) response)->header
1483 = MakeHeader(FCGI_UNKNOWN_TYPE, FCGI_NULL_REQUEST_ID,
1485 ((FCGI_UnknownTypeRecord *) response)->body
1486 = MakeUnknownTypeBody(type);
1488 if (write_it_all(data->reqDataPtr->ipcFd, response, FCGI_HEADER_LEN + paddedLen) < 0) {
1489 SetError(stream, OS_Errno);
1497 *----------------------------------------------------------------------
1499 * ProcessBeginRecord --
1501 * Reads an FCGI_BEGIN_REQUEST record.
1504 * BEGIN_RECORD for normal return. FCGX_PROTOCOL_ERROR for
1505 * protocol error. SKIP for attempt to multiplex
1506 * connection. -1 for error from write (errno in stream).
1509 * In case of BEGIN_RECORD return, stores requestId, role,
1510 * keepConnection values, and sets isBeginProcessed = TRUE.
1512 *----------------------------------------------------------------------
1514 static int ProcessBeginRecord(int requestId, FCGX_Stream *stream)
1516 FCGX_Stream_Data *data = (FCGX_Stream_Data *)stream->data;
1517 FCGI_BeginRequestBody body;
1518 if(requestId == 0 || data->contentLen != sizeof(body)) {
1519 return FCGX_PROTOCOL_ERROR;
1521 if(data->reqDataPtr->isBeginProcessed) {
1523 * The Web server is multiplexing the connection. This library
1524 * doesn't know how to handle multiplexing, so respond with
1525 * FCGI_END_REQUEST{protocolStatus = FCGI_CANT_MPX_CONN}
1527 FCGI_EndRequestRecord endRequestRecord;
1528 endRequestRecord.header = MakeHeader(FCGI_END_REQUEST,
1529 requestId, sizeof(endRequestRecord.body), 0);
1530 endRequestRecord.body
1531 = MakeEndRequestBody(0, FCGI_CANT_MPX_CONN);
1532 if (write_it_all(data->reqDataPtr->ipcFd, (char *)&endRequestRecord, sizeof(endRequestRecord)) < 0) {
1533 SetError(stream, OS_Errno);
1540 * Accept this new request. Read the record body.
1542 data->reqDataPtr->requestId = requestId;
1543 if(FCGX_GetStr((char *) &body, sizeof(body), stream)
1545 return FCGX_PROTOCOL_ERROR;
1547 data->reqDataPtr->keepConnection = (body.flags & FCGI_KEEP_CONN);
1548 data->reqDataPtr->role = (body.roleB1 << 8) + body.roleB0;
1549 data->reqDataPtr->isBeginProcessed = TRUE;
1550 return BEGIN_RECORD;
1554 *----------------------------------------------------------------------
1558 * Interprets FCGI_Header. Processes FCGI_BEGIN_REQUEST and
1559 * management records here; extracts information from stream
1560 * records (FCGI_PARAMS, FCGI_STDIN) into stream.
1563 * >= 0 for a normal return, < 0 for error
1566 * XXX: Many (more than there used to be).
1567 * If !stream->isRequestIdSet, ProcessHeader initializes
1568 * stream->requestId from header and sets stream->isRequestIdSet
1569 * to TRUE. ProcessHeader also sets stream->contentLen to header's
1570 * contentLength, and sets stream->paddingLen to the header's
1573 *----------------------------------------------------------------------
1575 static int ProcessHeader(FCGI_Header header, FCGX_Stream *stream)
1577 FCGX_Stream_Data *data = (FCGX_Stream_Data *)stream->data;
1579 if(header.version != FCGI_VERSION_1) {
1580 return FCGX_UNSUPPORTED_VERSION;
1582 requestId = (header.requestIdB1 << 8)
1583 + header.requestIdB0;
1584 data->contentLen = (header.contentLengthB1 << 8)
1585 + header.contentLengthB0;
1586 data->paddingLen = header.paddingLength;
1587 if(header.type == FCGI_BEGIN_REQUEST) {
1588 return ProcessBeginRecord(requestId, stream);
1590 if(requestId == FCGI_NULL_REQUEST_ID) {
1591 return ProcessManagementRecord(header.type, stream);
1593 if(requestId != data->reqDataPtr->requestId) {
1596 if(header.type != data->type) {
1597 return FCGX_PROTOCOL_ERROR;
1599 return STREAM_RECORD;
1603 *----------------------------------------------------------------------
1607 * Reads bytes from the ipcFd, supplies bytes to a stream client.
1609 *----------------------------------------------------------------------
1611 static void FillBuffProc(FCGX_Stream *stream)
1613 FCGX_Stream_Data *data = (FCGX_Stream_Data *)stream->data;
1620 * If data->buff is empty, do a read.
1622 if(stream->rdNext == data->buffStop) {
1623 count = OS_Read(data->reqDataPtr->ipcFd, (char *)data->buff,
1626 SetError(stream, (count == 0 ? FCGX_PROTOCOL_ERROR : OS_Errno));
1629 stream->rdNext = data->buff;
1630 data->buffStop = data->buff + count;
1633 * Now data->buff is not empty. If the current record contains
1634 * more content bytes, deliver all that are present in data->buff.
1636 if(data->contentLen > 0) {
1637 count = min(data->contentLen, data->buffStop - stream->rdNext);
1638 data->contentLen -= count;
1640 stream->wrNext = stream->stop = stream->rdNext + count;
1643 stream->rdNext += count;
1644 if(data->contentLen > 0) {
1652 * If the current record (whose content has been fully consumed by
1653 * the client) was padded, skip over the padding bytes.
1655 if(data->paddingLen > 0) {
1656 count = min(data->paddingLen, data->buffStop - stream->rdNext);
1657 data->paddingLen -= count;
1658 stream->rdNext += count;
1659 if(data->paddingLen > 0) {
1664 * All done with the current record, including the padding.
1665 * If we're in a recursive call from ProcessHeader, deliver EOF.
1668 stream->stop = stream->rdNext;
1669 stream->isClosed = TRUE;
1673 * Fill header with bytes from the input buffer.
1675 count = min((int)sizeof(header) - headerLen,
1676 data->buffStop - stream->rdNext);
1677 memcpy(((char *)(&header)) + headerLen, stream->rdNext, count);
1679 stream->rdNext += count;
1680 if(headerLen < sizeof(header)) {
1685 * Interpret header. eorStop prevents ProcessHeader from reading
1686 * past the end-of-record when using stream to read content.
1688 data->eorStop = TRUE;
1689 stream->stop = stream->rdNext;
1690 status = ProcessHeader(header, stream);
1691 data->eorStop = FALSE;
1692 stream->isClosed = FALSE;
1696 * If this stream record header marked the end of stream
1697 * data deliver EOF to the stream client, otherwise loop
1700 * XXX: If this is final stream and
1701 * stream->rdNext != data->buffStop, buffered
1702 * data is next request (server pipelining)?
1704 if(data->contentLen == 0) {
1705 stream->wrNext = stream->stop = stream->rdNext;
1706 stream->isClosed = TRUE;
1715 * If this header marked the beginning of a new
1716 * request, return role information to caller.
1724 SetError(stream, status);
1732 *----------------------------------------------------------------------
1736 * Creates a stream to read or write from an open ipcFd.
1737 * The stream performs reads/writes of up to bufflen bytes.
1739 *----------------------------------------------------------------------
1741 static FCGX_Stream *NewStream(
1742 FCGX_Request *reqDataPtr, int bufflen, int isReader, int streamType)
1745 * XXX: It would be a lot cleaner to have a NewStream that only
1746 * knows about the type FCGX_Stream, with all other
1747 * necessary data passed in. It appears that not just
1748 * data and the two procs are needed for initializing stream,
1749 * but also data->buff and data->buffStop. This has implications
1750 * for procs that want to swap buffers, too.
1752 FCGX_Stream *stream = (FCGX_Stream *)Malloc(sizeof(FCGX_Stream));
1753 FCGX_Stream_Data *data = (FCGX_Stream_Data *)Malloc(sizeof(FCGX_Stream_Data));
1754 data->reqDataPtr = reqDataPtr;
1755 bufflen = AlignInt8(min(max(bufflen, 32), FCGI_MAX_LENGTH + 1));
1756 data->bufflen = bufflen;
1757 data->mBuff = (unsigned char *)Malloc(bufflen);
1758 data->buff = AlignPtr8(data->mBuff);
1759 if(data->buff != data->mBuff) {
1763 data->buffStop = data->buff;
1765 data->buffStop = data->buff + data->bufflen;
1767 data->type = streamType;
1768 data->eorStop = FALSE;
1770 data->contentLen = 0;
1771 data->paddingLen = 0;
1772 data->isAnythingWritten = FALSE;
1773 data->rawWrite = FALSE;
1775 stream->data = data;
1776 stream->isReader = isReader;
1777 stream->isClosed = FALSE;
1778 stream->wasFCloseCalled = FALSE;
1779 stream->FCGI_errno = 0;
1781 stream->fillBuffProc = FillBuffProc;
1782 stream->emptyBuffProc = NULL;
1783 stream->rdNext = data->buff;
1784 stream->stop = stream->rdNext;
1785 stream->stopUnget = data->buff;
1786 stream->wrNext = stream->stop;
1788 stream->fillBuffProc = NULL;
1789 stream->emptyBuffProc = EmptyBuffProc;
1790 stream->wrNext = data->buff + sizeof(FCGI_Header);
1791 stream->stop = data->buffStop;
1792 stream->stopUnget = NULL;
1793 stream->rdNext = stream->stop;
1799 *----------------------------------------------------------------------
1803 * Frees all storage allocated when *streamPtr was created,
1804 * and nulls out *streamPtr.
1806 *----------------------------------------------------------------------
1808 void FreeStream(FCGX_Stream **streamPtr)
1810 FCGX_Stream *stream = *streamPtr;
1811 FCGX_Stream_Data *data;
1812 if(stream == NULL) {
1815 data = (FCGX_Stream_Data *)stream->data;
1816 data->reqDataPtr = NULL;
1824 *----------------------------------------------------------------------
1828 * Re-initializes the stream to read data of the specified type.
1830 *----------------------------------------------------------------------
1832 static FCGX_Stream *SetReaderType(FCGX_Stream *stream, int streamType)
1834 FCGX_Stream_Data *data = (FCGX_Stream_Data *)stream->data;
1835 ASSERT(stream->isReader);
1836 data->type = streamType;
1837 data->eorStop = FALSE;
1839 data->contentLen = 0;
1840 data->paddingLen = 0;
1841 stream->wrNext = stream->stop = stream->rdNext;
1842 stream->isClosed = FALSE;
1847 *----------------------------------------------------------------------
1851 * Creates a stream to read streamType records for the given
1852 * request. The stream performs OS reads of up to bufflen bytes.
1854 *----------------------------------------------------------------------
1856 static FCGX_Stream *NewReader(FCGX_Request *reqDataPtr, int bufflen, int streamType)
1858 return NewStream(reqDataPtr, bufflen, TRUE, streamType);
1863 *----------------------------------------------------------------------
1867 * Creates a stream to write streamType FastCGI records, using
1868 * the ipcFd and RequestId contained in *reqDataPtr.
1869 * The stream performs OS writes of up to bufflen bytes.
1871 *----------------------------------------------------------------------
1873 static FCGX_Stream *NewWriter(FCGX_Request *reqDataPtr, int bufflen, int streamType)
1875 return NewStream(reqDataPtr, bufflen, FALSE, streamType);
1880 *----------------------------------------------------------------------
1884 * Creates a stream to write streamType FastCGI records, using
1885 * the given ipcFd and request Id. This function is provided
1886 * for use by cgi-fcgi. In order to be defensive against misuse,
1887 * this function leaks a little storage; cgi-fcgi doesn't care.
1889 *----------------------------------------------------------------------
1891 FCGX_Stream *CreateWriter(
1897 FCGX_Request *reqDataPtr = (FCGX_Request *)Malloc(sizeof(FCGX_Request));
1898 reqDataPtr->ipcFd = ipcFd;
1899 reqDataPtr->requestId = requestId;
1901 * Suppress writing an FCGI_END_REQUEST record.
1903 reqDataPtr->nWriters = 2;
1904 return NewWriter(reqDataPtr, bufflen, streamType);
1908 *======================================================================
1910 *======================================================================
1914 *----------------------------------------------------------------------
1918 * This routine determines if the process is running as a CGI or
1919 * FastCGI process. The distinction is made by determining whether
1920 * FCGI_LISTENSOCK_FILENO is a listener ipcFd or the end of a
1921 * pipe (ie. standard in).
1924 * TRUE if the process is a CGI process, FALSE if FastCGI.
1926 *----------------------------------------------------------------------
1928 int FCGX_IsCGI(void)
1930 if (isFastCGI != -1) {
1934 if (!libInitialized) {
1935 int rc = FCGX_Init();
1937 /* exit() isn't great, but hey */
1938 exit((rc < 0) ? rc : -rc);
1942 isFastCGI = OS_IsFcgi(FCGI_LISTENSOCK_FILENO);
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 *----------------------------------------------------------------------
1967 void FCGX_Finish(void)
1969 FCGX_Finish_r(&the_request);
1973 *----------------------------------------------------------------------
1977 * Finishes the current request from the HTTP server.
1981 * Finishes the request accepted by (and frees any
1982 * storage allocated by) the previous call to FCGX_Accept.
1984 * DO NOT retain pointers to the envp array or any strings
1985 * contained in it (e.g. to the result of calling FCGX_GetParam),
1986 * since these will be freed by the next call to FCGX_Finish
1989 *----------------------------------------------------------------------
1991 void FCGX_Finish_r(FCGX_Request *reqDataPtr)
1993 if (reqDataPtr == NULL) {
1997 /* This should probably use a 'status' member instead of 'in' */
1998 if (reqDataPtr->in) {
1999 int errStatus = FCGX_FClose(reqDataPtr->err);
2000 int outStatus = FCGX_FClose(reqDataPtr->out);
2002 if (errStatus || outStatus || FCGX_GetError(reqDataPtr->in))
2004 OS_IpcClose(reqDataPtr->ipcFd);
2005 reqDataPtr->ipcFd = -1;
2009 FCGX_Free(reqDataPtr);
2012 void FCGX_Free(FCGX_Request * request)
2014 if (request == NULL)
2017 FreeStream(&request->in);
2018 FreeStream(&request->out);
2019 FreeStream(&request->err);
2020 FreeParams(&request->paramsPtr);
2022 if (!request->keepConnection)
2024 OS_IpcClose(request->ipcFd);
2025 request->ipcFd = -1;
2029 int FCGX_OpenSocket(const char *path, int backlog)
2031 int rc = OS_CreateLocalIpcFd(path, backlog);
2032 if (rc == FCGI_LISTENSOCK_FILENO && isFastCGI == 0) {
2033 /* XXX probably need to call OS_LibInit() again for Win */
2039 int FCGX_InitRequest(FCGX_Request *request, int sock, int flags)
2041 memset(request, 0, sizeof(FCGX_Request));
2043 /* @@@ Should check that sock is open and listening */
2044 request->listen_sock = sock;
2046 /* @@@ Should validate against "known" flags */
2047 request->flags = flags;
2049 request->ipcFd = -1;
2055 *----------------------------------------------------------------------
2059 * Initilize the FCGX library. This is called by FCGX_Accept()
2060 * but must be called by the user when using FCGX_Accept_r().
2063 * 0 for successful call.
2065 *----------------------------------------------------------------------
2071 if (libInitialized) {
2075 /* If our compiler doesn't play by the ISO rules for struct layout, halt. */
2076 ASSERT(sizeof(FCGI_Header) == FCGI_HEADER_LEN);
2078 FCGX_InitRequest(&the_request, FCGI_LISTENSOCK_FILENO, 0);
2080 if (OS_LibInit(NULL) == -1) {
2081 return OS_Errno ? OS_Errno : -9997;
2084 p = getenv("FCGI_WEB_SERVER_ADDRS");
2085 webServerAddressList = p ? StringCopy(p) : NULL;
2092 *----------------------------------------------------------------------
2096 * Accepts a new request from the HTTP server.
2099 * 0 for successful call, -1 for error.
2103 * Finishes the request accepted by (and frees any
2104 * storage allocated by) the previous call to FCGX_Accept.
2105 * Creates input, output, and error streams and
2106 * assigns them to *in, *out, and *err respectively.
2107 * Creates a parameters data structure to be accessed
2108 * via getenv(3) (if assigned to environ) or by FCGX_GetParam
2109 * and assigns it to *envp.
2111 * DO NOT retain pointers to the envp array or any strings
2112 * contained in it (e.g. to the result of calling FCGX_GetParam),
2113 * since these will be freed by the next call to FCGX_Finish
2116 *----------------------------------------------------------------------
2123 FCGX_ParamArray *envp)
2127 if (! libInitialized) {
2134 rc = FCGX_Accept_r(&the_request);
2136 *in = the_request.in;
2137 *out = the_request.out;
2138 *err = the_request.err;
2139 *envp = the_request.envp;
2145 *----------------------------------------------------------------------
2149 * Accepts a new request from the HTTP server.
2152 * 0 for successful call, -1 for error.
2156 * Finishes the request accepted by (and frees any
2157 * storage allocated by) the previous call to FCGX_Accept.
2158 * Creates input, output, and error streams and
2159 * assigns them to *in, *out, and *err respectively.
2160 * Creates a parameters data structure to be accessed
2161 * via getenv(3) (if assigned to environ) or by FCGX_GetParam
2162 * and assigns it to *envp.
2164 * DO NOT retain pointers to the envp array or any strings
2165 * contained in it (e.g. to the result of calling FCGX_GetParam),
2166 * since these will be freed by the next call to FCGX_Finish
2169 *----------------------------------------------------------------------
2171 int FCGX_Accept_r(FCGX_Request *reqDataPtr)
2173 if (!libInitialized) {
2177 /* Finish the current request, if any. */
2178 FCGX_Finish_r(reqDataPtr);
2182 * If a connection isn't open, accept a new connection (blocking).
2183 * If an OS error occurs in accepting the connection,
2184 * return -1 to the caller, who should exit.
2186 if (reqDataPtr->ipcFd < 0) {
2187 int fail_on_intr = reqDataPtr->flags & FCGI_FAIL_ACCEPT_ON_INTR;
2189 reqDataPtr->ipcFd = OS_Accept(reqDataPtr->listen_sock, fail_on_intr, webServerAddressList);
2190 if (reqDataPtr->ipcFd < 0) {
2191 return (errno > 0) ? (0 - errno) : -9999;
2195 * A connection is open. Read from the connection in order to
2196 * get the request's role and environment. If protocol or other
2197 * errors occur, close the connection and try again.
2199 reqDataPtr->isBeginProcessed = FALSE;
2200 reqDataPtr->in = NewReader(reqDataPtr, 8192, 0);
2201 FillBuffProc(reqDataPtr->in);
2202 if(!reqDataPtr->isBeginProcessed) {
2207 switch(reqDataPtr->role) {
2208 case FCGI_RESPONDER:
2209 roleStr = "FCGI_ROLE=RESPONDER";
2211 case FCGI_AUTHORIZER:
2212 roleStr = "FCGI_ROLE=AUTHORIZER";
2215 roleStr = "FCGI_ROLE=FILTER";
2220 reqDataPtr->paramsPtr = NewParams(30);
2221 PutParam(reqDataPtr->paramsPtr, StringCopy(roleStr));
2223 SetReaderType(reqDataPtr->in, FCGI_PARAMS);
2224 if(ReadParams(reqDataPtr->paramsPtr, reqDataPtr->in) >= 0) {
2226 * Finished reading the environment. No errors occurred, so
2227 * leave the connection-retry loop.
2233 * Close the connection and try again.
2236 FCGX_Free(reqDataPtr);
2240 * Build the remaining data structures representing the new
2241 * request and return successfully to the caller.
2243 SetReaderType(reqDataPtr->in, FCGI_STDIN);
2244 reqDataPtr->out = NewWriter(reqDataPtr, 8192, FCGI_STDOUT);
2245 reqDataPtr->err = NewWriter(reqDataPtr, 512, FCGI_STDERR);
2246 reqDataPtr->nWriters = 2;
2247 reqDataPtr->envp = reqDataPtr->paramsPtr->vec;
2252 *----------------------------------------------------------------------
2254 * FCGX_StartFilterData --
2256 * stream is an input stream for a FCGI_FILTER request.
2257 * stream is positioned at EOF on FCGI_STDIN.
2258 * Repositions stream to the start of FCGI_DATA.
2259 * If the preconditions are not met (e.g. FCGI_STDIN has not
2260 * been read to EOF) sets the stream error code to
2261 * FCGX_CALL_SEQ_ERROR.
2264 * 0 for a normal return, < 0 for error
2266 *----------------------------------------------------------------------
2269 int FCGX_StartFilterData(FCGX_Stream *stream)
2271 FCGX_Stream_Data *data = (FCGX_Stream_Data *)stream->data;
2272 if(data->reqDataPtr->role != FCGI_FILTER
2273 || !stream->isReader
2274 || !stream->isClosed
2275 || data->type != FCGI_STDIN) {
2276 SetError(stream, FCGX_CALL_SEQ_ERROR);
2279 SetReaderType(stream, FCGI_DATA);
2284 *----------------------------------------------------------------------
2286 * FCGX_SetExitStatus --
2288 * Sets the exit status for stream's request. The exit status
2289 * is the status code the request would have exited with, had
2290 * the request been run as a CGI program. You can call
2291 * SetExitStatus several times during a request; the last call
2292 * before the request ends determines the value.
2294 *----------------------------------------------------------------------
2297 void FCGX_SetExitStatus(int status, FCGX_Stream *stream)
2299 FCGX_Stream_Data *data = (FCGX_Stream_Data *)stream->data;
2300 data->reqDataPtr->appStatus = status;