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.26 2001/06/22 14:21:03 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
48 #define DLLAPI __declspec(dllexport)
57 * This is a workaround for one version of the HP C compiler
58 * (c89 on HP-UX 9.04, also Stratus FTX), which will dump core
59 * if given 'long double' for varargs.
61 #ifdef HAVE_VA_ARG_LONG_DOUBLE_BUG
62 #define LONG_DOUBLE double
64 #define LONG_DOUBLE long double
70 static int libInitialized = 0;
71 static int isFastCGI = -1;
72 static char *webServerAddressList = NULL;
73 static FCGX_Request the_request;
75 static void *Malloc(size_t size)
77 void *result = malloc(size);
78 ASSERT(size == 0 || result != NULL);
82 static char *StringCopy(char *str)
84 int strLen = strlen(str);
85 char *newString = (char *)Malloc(strLen + 1);
86 memcpy(newString, str, strLen);
87 newString[strLen] = '\000';
93 *----------------------------------------------------------------------
97 * Reads a byte from the input stream and returns it.
100 * The byte, or EOF (-1) if the end of input has been reached.
102 *----------------------------------------------------------------------
104 int FCGX_GetChar(FCGX_Stream *stream)
106 if(stream->rdNext != stream->stop)
107 return *stream->rdNext++;
108 if(stream->isClosed || !stream->isReader)
110 stream->fillBuffProc(stream);
111 stream->stopUnget = stream->rdNext;
112 if(stream->rdNext != stream->stop)
113 return *stream->rdNext++;
114 ASSERT(stream->isClosed); /* bug in fillBufProc if not */
119 *----------------------------------------------------------------------
123 * Reads up to n consecutive bytes from the input stream
124 * into the character array str. Performs no interpretation
125 * of the input bytes.
128 * Number of bytes read. If result is smaller than n,
129 * the end of input has been reached.
131 *----------------------------------------------------------------------
133 int FCGX_GetStr(char *str, int n, FCGX_Stream *stream)
141 * Fast path: n bytes are already available
143 if(n <= (stream->stop - stream->rdNext)) {
144 memcpy(str, stream->rdNext, n);
149 * General case: stream is closed or buffer fill procedure
154 if(stream->rdNext != stream->stop) {
155 m = min(n - bytesMoved, stream->stop - stream->rdNext);
156 memcpy(str, stream->rdNext, m);
163 if(stream->isClosed || !stream->isReader)
165 stream->fillBuffProc(stream);
166 stream->stopUnget = stream->rdNext;
171 *----------------------------------------------------------------------
175 * Reads up to n-1 consecutive bytes from the input stream
176 * into the character array str. Stops before n-1 bytes
177 * have been read if '\n' or EOF is read. The terminating '\n'
178 * is copied to str. After copying the last byte into str,
179 * stores a '\0' terminator.
182 * NULL if EOF is the first thing read from the input stream,
185 *----------------------------------------------------------------------
187 char *FCGX_GetLine(char *str, int n, FCGX_Stream *stream)
194 c = FCGX_GetChar(stream);
211 *----------------------------------------------------------------------
215 * Pushes back the character c onto the input stream. One
216 * character of pushback is guaranteed once a character
217 * has been read. No pushback is possible for EOF.
220 * Returns c if the pushback succeeded, EOF if not.
222 *----------------------------------------------------------------------
224 int FCGX_UnGetChar(int c, FCGX_Stream *stream) {
228 || stream->rdNext == stream->stopUnget)
231 *stream->rdNext = (unsigned char) c;
236 *----------------------------------------------------------------------
240 * Returns EOF if end-of-file has been detected while reading
241 * from stream; otherwise returns 0.
243 * Note that FCGX_HasSeenEOF(s) may return 0, yet an immediately
244 * following FCGX_GetChar(s) may return EOF. This function, like
245 * the standard C stdio function feof, does not provide the
246 * ability to peek ahead.
249 * EOF if end-of-file has been detected, 0 if not.
251 *----------------------------------------------------------------------
253 int FCGX_HasSeenEOF(FCGX_Stream *stream) {
254 return (stream->isClosed) ? EOF : 0;
258 *----------------------------------------------------------------------
262 * Writes a byte to the output stream.
265 * The byte, or EOF (-1) if an error occurred.
267 *----------------------------------------------------------------------
269 int FCGX_PutChar(int c, FCGX_Stream *stream)
271 if(stream->wrNext != stream->stop)
272 return (*stream->wrNext++ = (unsigned char) c);
273 if(stream->isClosed || stream->isReader)
275 stream->emptyBuffProc(stream, FALSE);
276 if(stream->wrNext != stream->stop)
277 return (*stream->wrNext++ = (unsigned char) c);
278 ASSERT(stream->isClosed); /* bug in emptyBuffProc if not */
283 *----------------------------------------------------------------------
287 * Writes n consecutive bytes from the character array str
288 * into the output stream. Performs no interpretation
289 * of the output bytes.
292 * Number of bytes written (n) for normal return,
293 * EOF (-1) if an error occurred.
295 *----------------------------------------------------------------------
297 int FCGX_PutStr(const char *str, int n, FCGX_Stream *stream)
302 * Fast path: room for n bytes in the buffer
304 if(n <= (stream->stop - stream->wrNext)) {
305 memcpy(stream->wrNext, str, n);
310 * General case: stream is closed or buffer empty procedure
315 if(stream->wrNext != stream->stop) {
316 m = min(n - bytesMoved, stream->stop - stream->wrNext);
317 memcpy(stream->wrNext, str, m);
324 if(stream->isClosed || stream->isReader)
326 stream->emptyBuffProc(stream, FALSE);
331 *----------------------------------------------------------------------
335 * Writes a character string to the output stream.
338 * number of bytes written for normal return,
339 * EOF (-1) if an error occurred.
341 *----------------------------------------------------------------------
343 int FCGX_PutS(const char *str, FCGX_Stream *stream)
345 return FCGX_PutStr(str, strlen(str), stream);
349 *----------------------------------------------------------------------
353 * Performs output formatting and writes the results
354 * to the output stream.
357 * number of bytes written for normal return,
358 * EOF (-1) if an error occurred.
360 *----------------------------------------------------------------------
362 int FCGX_FPrintF(FCGX_Stream *stream, const char *format, ...)
366 va_start(ap, format);
367 result = FCGX_VFPrintF(stream, format, ap);
373 *----------------------------------------------------------------------
377 * Performs output formatting and writes the results
378 * to the output stream.
381 * number of bytes written for normal return,
382 * EOF (-1) if an error occurred.
384 *----------------------------------------------------------------------
387 #define PRINTF_BUFFLEN 100
389 * More than sufficient space for all unmodified conversions
392 #define FMT_BUFFLEN 25
394 * Max size of a format specifier is 1 + 5 + 7 + 7 + 2 + 1 + slop
396 static void CopyAndAdvance(char **destPtr, char **srcPtr, int n);
398 int FCGX_VFPrintF(FCGX_Stream *stream, const char *format, va_list arg)
400 char *f, *fStop, *percentPtr, *p, *fmtBuffPtr, *buffPtr;
401 int op, performedOp, sizeModifier, buffCount = 0, buffLen, specifierLength;
402 int fastPath, n, auxBuffLen = 0, buffReqd, minWidth, precision, exp;
403 char *auxBuffPtr = NULL;
405 char fmtBuff[FMT_BUFFLEN];
406 char buff[PRINTF_BUFFLEN];
411 unsigned unsignedArg;
412 unsigned long uLongArg;
413 unsigned short uShortArg;
414 char *charPtrArg = NULL;
419 double doubleArg = 0.0;
420 LONG_DOUBLE lDoubleArg = 0.0L;
424 fStop = f + strlen(f);
426 percentPtr = (char *)memchr(f, '%', fStop - f);
427 if(percentPtr == NULL) percentPtr = fStop;
428 if(percentPtr != f) {
429 if(FCGX_PutStr(f, percentPtr - f, stream) < 0)
431 streamCount += percentPtr - f;
433 if(f == fStop) break;
437 * The following loop always executes either once or twice.
442 * Fast path: Scan optimistically, hoping that no flags,
443 * minimum field width, or precision are specified.
444 * Use the preallocated buffer, which is large enough
445 * for all fast path cases. If the conversion specifier
446 * is really more complex, run the loop a second time
447 * using the slow path.
448 * Note that fast path execution of %s bypasses the buffer
449 * and %f is not attempted on the fast path due to
450 * its large buffering requirements.
452 op = *(percentPtr + 1);
458 op = *(percentPtr + 2);
459 fmtBuff[1] = (char) sizeModifier;
460 fmtBuff[2] = (char) op;
466 fmtBuff[1] = (char) op;
472 buffLen = PRINTF_BUFFLEN;
475 * Slow path: Scan the conversion specifier and construct
476 * a new format string, compute an upper bound on the
477 * amount of buffering that sprintf will require,
478 * and allocate a larger buffer if necessary.
481 fmtBuffPtr = &fmtBuff[1];
485 n = strspn(p, "-0+ #");
488 CopyAndAdvance(&fmtBuffPtr, &p, n);
490 * Scan minimum field width
492 n = strspn(p, "0123456789");
495 minWidth = va_arg(arg, int);
496 if(abs(minWidth) > 999999)
499 * The following use of strlen rather than the
500 * value returned from sprintf is because SUNOS4
501 * returns a char * instead of an int count.
503 sprintf(fmtBuffPtr, "%d", minWidth);
504 fmtBuffPtr += strlen(fmtBuffPtr);
510 minWidth = strtol(p, NULL, 10);
511 CopyAndAdvance(&fmtBuffPtr, &p, n);
519 CopyAndAdvance(&fmtBuffPtr, &p, 1);
520 n = strspn(p, "0123456789");
523 precision = va_arg(arg, int);
524 if(precision < 0) precision = 0;
525 if(precision > 999999)
528 * The following use of strlen rather than the
529 * value returned from sprintf is because SUNOS4
530 * returns a char * instead of an int count.
532 sprintf(fmtBuffPtr, "%d", precision);
533 fmtBuffPtr += strlen(fmtBuffPtr);
539 precision = strtol(p, NULL, 10);
540 CopyAndAdvance(&fmtBuffPtr, &p, n);
548 * Scan size modifier and conversion operation
555 CopyAndAdvance(&fmtBuffPtr, &p, 1);
562 CopyAndAdvance(&fmtBuffPtr, &p, 1);
563 ASSERT(fmtBuffPtr - fmtBuff < FMT_BUFFLEN);
565 specifierLength = p - percentPtr;
567 * Bound the required buffer size. For s and f
568 * conversions this requires examining the argument.
579 buffReqd = max(precision, 46);
582 charPtrArg = va_arg(arg, char *);
583 if (!charPtrArg) charPtrArg = "(null)";
584 if(precision == -1) {
585 buffReqd = strlen(charPtrArg);
587 p = (char *)memchr(charPtrArg, '\0', precision);
589 (p == NULL) ? precision : p - charPtrArg;
593 switch(sizeModifier) {
595 doubleArg = va_arg(arg, double);
596 frexp(doubleArg, &exp);
599 lDoubleArg = va_arg(arg, LONG_DOUBLE);
600 /* XXX Need to check for the presence of
601 * frexpl() and use it if available */
602 frexp((double) lDoubleArg, &exp);
607 if(precision == -1) precision = 6;
608 buffReqd = precision + 3 + ((exp > 0) ? exp/3 : 0);
614 if(precision == -1) precision = 6;
615 buffReqd = precision + 8;
623 buffReqd = max(buffReqd + 10, minWidth);
625 * Allocate the buffer
627 if(buffReqd <= PRINTF_BUFFLEN) {
629 buffLen = PRINTF_BUFFLEN;
631 if(auxBuffPtr == NULL || buffReqd > auxBuffLen) {
632 if(auxBuffPtr != NULL) free(auxBuffPtr);
633 auxBuffPtr = (char *)Malloc(buffReqd);
634 auxBuffLen = buffReqd;
635 if(auxBuffPtr == NULL)
638 buffPtr = auxBuffPtr;
639 buffLen = auxBuffLen;
643 * This giant switch statement requires the following variables
644 * to be set up: op, sizeModifier, arg, buffPtr, fmtBuff.
645 * When fastPath == FALSE and op == 's' or 'f', the argument
646 * has been read into charPtrArg, doubleArg, or lDoubleArg.
647 * The statement produces the boolean performedOp, TRUE iff
648 * the op/sizeModifier were executed and argument consumed;
649 * if performedOp, the characters written into buffPtr[]
650 * and the character count buffCount (== EOF meaning error).
652 * The switch cases are arranged in the same order as in the
653 * description of fprintf in section 15.11 of Harbison and Steele.
659 switch(sizeModifier) {
661 intArg = va_arg(arg, int);
662 sprintf(buffPtr, fmtBuff, intArg);
663 buffCount = strlen(buffPtr);
666 longArg = va_arg(arg, long);
667 sprintf(buffPtr, fmtBuff, longArg);
668 buffCount = strlen(buffPtr);
671 shortArg = (short) va_arg(arg, int);
672 sprintf(buffPtr, fmtBuff, shortArg);
673 buffCount = strlen(buffPtr);
683 switch(sizeModifier) {
685 unsignedArg = va_arg(arg, unsigned);
686 sprintf(buffPtr, fmtBuff, unsignedArg);
687 buffCount = strlen(buffPtr);
690 uLongArg = va_arg(arg, unsigned long);
691 sprintf(buffPtr, fmtBuff, uLongArg);
692 buffCount = strlen(buffPtr);
695 uShortArg = (unsigned short) va_arg(arg, int);
696 sprintf(buffPtr, fmtBuff, uShortArg);
697 buffCount = strlen(buffPtr);
704 switch(sizeModifier) {
706 intArg = va_arg(arg, int);
707 sprintf(buffPtr, fmtBuff, intArg);
708 buffCount = strlen(buffPtr);
712 * XXX: Allowed by ISO C Amendment 1, but
713 * many platforms don't yet support wint_t
721 switch(sizeModifier) {
724 buffPtr = va_arg(arg, char *);
725 buffCount = strlen(buffPtr);
726 buffLen = buffCount + 1;
728 sprintf(buffPtr, fmtBuff, charPtrArg);
729 buffCount = strlen(buffPtr);
734 * XXX: Don't know how to convert a sequence
735 * of wide characters into a byte stream, or
736 * even how to predict the buffering required.
744 if(sizeModifier != ' ')
746 voidPtrArg = va_arg(arg, void *);
747 sprintf(buffPtr, fmtBuff, voidPtrArg);
748 buffCount = strlen(buffPtr);
751 switch(sizeModifier) {
753 intPtrArg = va_arg(arg, int *);
754 *intPtrArg = streamCount;
757 longPtrArg = va_arg(arg, long *);
758 *longPtrArg = streamCount;
761 shortPtrArg = (short *) va_arg(arg, short *);
762 *shortPtrArg = (short) streamCount;
774 switch(sizeModifier) {
776 sprintf(buffPtr, fmtBuff, doubleArg);
777 buffCount = strlen(buffPtr);
780 sprintf(buffPtr, fmtBuff, lDoubleArg);
781 buffCount = strlen(buffPtr);
791 switch(sizeModifier) {
793 doubleArg = va_arg(arg, double);
794 sprintf(buffPtr, fmtBuff, doubleArg);
795 buffCount = strlen(buffPtr);
798 lDoubleArg = va_arg(arg, LONG_DOUBLE);
799 sprintf(buffPtr, fmtBuff, lDoubleArg);
800 buffCount = strlen(buffPtr);
807 if(sizeModifier != ' ')
818 if(performedOp) break;
823 ASSERT(buffCount < buffLen);
825 if(FCGX_PutStr(buffPtr, buffCount, stream) < 0)
827 streamCount += buffCount;
828 } else if(buffCount < 0) {
831 f += specifierLength;
832 } /* while(f != fStop) */
837 if(auxBuffPtr != NULL) free(auxBuffPtr);
842 * Copy n characters from *srcPtr to *destPtr, then increment
843 * both *srcPtr and *destPtr by n.
845 static void CopyAndAdvance(char **destPtr, char **srcPtr, int n)
847 char *dest = *destPtr;
850 for (i = 0; i < n; i++)
857 *----------------------------------------------------------------------
861 * Flushes any buffered output.
863 * Server-push is a legitimate application of FCGX_FFlush.
864 * Otherwise, FCGX_FFlush is not very useful, since FCGX_Accept
865 * does it implicitly. FCGX_FFlush may reduce performance
866 * by increasing the total number of operating system calls
867 * the application makes.
870 * EOF (-1) if an error occurred.
872 *----------------------------------------------------------------------
874 int FCGX_FFlush(FCGX_Stream *stream)
876 if(stream->isClosed || stream->isReader)
878 stream->emptyBuffProc(stream, FALSE);
879 return (stream->isClosed) ? -1 : 0;
883 *----------------------------------------------------------------------
887 * Performs FCGX_FFlush and closes the stream.
889 * This is not a very useful operation, since FCGX_Accept
890 * does it implicitly. Closing the out stream before the
891 * err stream results in an extra write if there's nothing
892 * in the err stream, and therefore reduces performance.
895 * EOF (-1) if an error occurred.
897 *----------------------------------------------------------------------
899 int FCGX_FClose(FCGX_Stream *stream)
901 if (stream == NULL) return 0;
903 if(!stream->wasFCloseCalled) {
904 if(!stream->isReader) {
905 stream->emptyBuffProc(stream, TRUE);
907 stream->wasFCloseCalled = TRUE;
908 stream->isClosed = TRUE;
909 if(stream->isReader) {
910 stream->wrNext = stream->stop = stream->rdNext;
912 stream->rdNext = stream->stop = stream->wrNext;
915 return (stream->FCGI_errno == 0) ? 0 : EOF;
919 *----------------------------------------------------------------------
923 * An error has occurred; save the error code in the stream
924 * for diagnostic purposes and set the stream state so that
925 * reads return EOF and writes have no effect.
927 *----------------------------------------------------------------------
929 static void SetError(FCGX_Stream *stream, int FCGI_errno)
932 * Preserve only the first error.
934 if(stream->FCGI_errno == 0) {
935 stream->FCGI_errno = FCGI_errno;
936 stream->isClosed = TRUE;
941 *----------------------------------------------------------------------
945 * Return the stream error code. 0 means no error, > 0
946 * is an errno(2) error, < 0 is an FCGX_errno error.
948 *----------------------------------------------------------------------
950 int FCGX_GetError(FCGX_Stream *stream) {
951 return stream->FCGI_errno;
955 *----------------------------------------------------------------------
959 * Clear the stream error code and end-of-file indication.
961 *----------------------------------------------------------------------
963 void FCGX_ClearError(FCGX_Stream *stream) {
964 stream->FCGI_errno = 0;
966 * stream->isClosed = FALSE;
967 * XXX: should clear isClosed but work is needed to make it safe
968 * to do so. For example, if an application calls FClose, gets
969 * an I/O error on the write, calls ClearError and retries
970 * the FClose, FClose (really EmptyBuffProc) will write a second
971 * EOF record. If an application calls PutChar instead of FClose
972 * after the ClearError, the application will write more data.
973 * The stream's state must discriminate between various states
974 * of the stream that are now all lumped under isClosed.
979 *======================================================================
981 *======================================================================
985 * A vector of pointers representing the parameters received
986 * by a FastCGI application server, with the vector's length
987 * and last valid element so adding new parameters is efficient.
990 typedef struct Params {
991 FCGX_ParamArray vec; /* vector of strings */
992 int length; /* number of string vec can hold */
993 char **cur; /* current item in vec; *cur == NULL */
995 typedef Params *ParamsPtr;
998 *----------------------------------------------------------------------
1002 * Creates a new Params structure.
1005 * Pointer to the new structure.
1007 *----------------------------------------------------------------------
1009 static ParamsPtr NewParams(int length)
1012 result = (Params *)Malloc(sizeof(Params));
1013 result->vec = (char **)Malloc(length * sizeof(char *));
1014 result->length = length;
1015 result->cur = result->vec;
1016 *result->cur = NULL;
1021 *----------------------------------------------------------------------
1025 * Frees a Params structure and all the parameters it contains.
1028 * env becomes invalid.
1030 *----------------------------------------------------------------------
1032 static void FreeParams(ParamsPtr *paramsPtrPtr)
1034 ParamsPtr paramsPtr = *paramsPtrPtr;
1036 if(paramsPtr == NULL) {
1039 for (p = paramsPtr->vec; p < paramsPtr->cur; p++) {
1042 free(paramsPtr->vec);
1044 *paramsPtrPtr = NULL;
1048 *----------------------------------------------------------------------
1052 * Add a name/value pair to a Params structure.
1058 * Parameters structure updated.
1060 *----------------------------------------------------------------------
1062 static void PutParam(ParamsPtr paramsPtr, char *nameValue)
1066 *paramsPtr->cur++ = nameValue;
1067 size = paramsPtr->cur - paramsPtr->vec;
1068 if(size >= paramsPtr->length) {
1069 paramsPtr->length *= 2;
1070 paramsPtr->vec = (FCGX_ParamArray)realloc(paramsPtr->vec, paramsPtr->length * sizeof(char *));
1071 paramsPtr->cur = paramsPtr->vec + size;
1073 *paramsPtr->cur = NULL;
1077 *----------------------------------------------------------------------
1079 * FCGX_GetParam -- obtain value of FCGI parameter in environment
1083 * Value bound to name, NULL if name not present in the
1084 * environment envp. Caller must not mutate the result
1085 * or retain it past the end of this request.
1087 *----------------------------------------------------------------------
1089 char *FCGX_GetParam(const char *name, FCGX_ParamArray envp)
1094 if (name == NULL || envp == NULL) return NULL;
1098 for (p = envp; *p; ++p) {
1099 if((strncmp(name, *p, len) == 0) && ((*p)[len] == '=')) {
1107 *----------------------------------------------------------------------
1109 * Start of FastCGI-specific code
1111 *----------------------------------------------------------------------
1115 *----------------------------------------------------------------------
1119 * Reads FastCGI name-value pairs from stream until EOF. Converts
1120 * each pair to name=value format and adds it to Params structure.
1122 *----------------------------------------------------------------------
1124 static int ReadParams(Params *paramsPtr, FCGX_Stream *stream)
1126 int nameLen, valueLen;
1127 unsigned char lenBuff[3];
1130 while((nameLen = FCGX_GetChar(stream)) != EOF) {
1132 * Read name length (one or four bytes) and value length
1133 * (one or four bytes) from stream.
1135 if((nameLen & 0x80) != 0) {
1136 if(FCGX_GetStr((char *) &lenBuff[0], 3, stream) != 3) {
1137 SetError(stream, FCGX_PARAMS_ERROR);
1140 nameLen = ((nameLen & 0x7f) << 24) + (lenBuff[0] << 16)
1141 + (lenBuff[1] << 8) + lenBuff[2];
1143 if((valueLen = FCGX_GetChar(stream)) == EOF) {
1144 SetError(stream, FCGX_PARAMS_ERROR);
1147 if((valueLen & 0x80) != 0) {
1148 if(FCGX_GetStr((char *) &lenBuff[0], 3, stream) != 3) {
1149 SetError(stream, FCGX_PARAMS_ERROR);
1152 valueLen = ((valueLen & 0x7f) << 24) + (lenBuff[0] << 16)
1153 + (lenBuff[1] << 8) + lenBuff[2];
1156 * nameLen and valueLen are now valid; read the name and value
1157 * from stream and construct a standard environment entry.
1159 nameValue = (char *)Malloc(nameLen + valueLen + 2);
1160 if(FCGX_GetStr(nameValue, nameLen, stream) != nameLen) {
1161 SetError(stream, FCGX_PARAMS_ERROR);
1165 *(nameValue + nameLen) = '=';
1166 if(FCGX_GetStr(nameValue + nameLen + 1, valueLen, stream)
1168 SetError(stream, FCGX_PARAMS_ERROR);
1172 *(nameValue + nameLen + valueLen + 1) = '\0';
1173 PutParam(paramsPtr, nameValue);
1179 *----------------------------------------------------------------------
1183 * Constructs an FCGI_Header struct.
1185 *----------------------------------------------------------------------
1187 static FCGI_Header MakeHeader(
1194 ASSERT(contentLength >= 0 && contentLength <= FCGI_MAX_LENGTH);
1195 ASSERT(paddingLength >= 0 && paddingLength <= 0xff);
1196 header.version = FCGI_VERSION_1;
1197 header.type = (unsigned char) type;
1198 header.requestIdB1 = (unsigned char) ((requestId >> 8) & 0xff);
1199 header.requestIdB0 = (unsigned char) ((requestId ) & 0xff);
1200 header.contentLengthB1 = (unsigned char) ((contentLength >> 8) & 0xff);
1201 header.contentLengthB0 = (unsigned char) ((contentLength ) & 0xff);
1202 header.paddingLength = (unsigned char) paddingLength;
1203 header.reserved = 0;
1208 *----------------------------------------------------------------------
1210 * MakeEndRequestBody --
1212 * Constructs an FCGI_EndRequestBody struct.
1214 *----------------------------------------------------------------------
1216 static FCGI_EndRequestBody MakeEndRequestBody(
1220 FCGI_EndRequestBody body;
1221 body.appStatusB3 = (unsigned char) ((appStatus >> 24) & 0xff);
1222 body.appStatusB2 = (unsigned char) ((appStatus >> 16) & 0xff);
1223 body.appStatusB1 = (unsigned char) ((appStatus >> 8) & 0xff);
1224 body.appStatusB0 = (unsigned char) ((appStatus ) & 0xff);
1225 body.protocolStatus = (unsigned char) protocolStatus;
1226 memset(body.reserved, 0, sizeof(body.reserved));
1231 *----------------------------------------------------------------------
1233 * MakeUnknownTypeBody --
1235 * Constructs an FCGI_MakeUnknownTypeBody struct.
1237 *----------------------------------------------------------------------
1239 static FCGI_UnknownTypeBody MakeUnknownTypeBody(
1242 FCGI_UnknownTypeBody body;
1243 body.type = (unsigned char) type;
1244 memset(body.reserved, 0, sizeof(body.reserved));
1249 *----------------------------------------------------------------------
1253 * Returns the smallest integer greater than or equal to n
1254 * that's a multiple of 8.
1256 *----------------------------------------------------------------------
1258 static int AlignInt8(unsigned n) {
1259 return (n + 7) & (UINT_MAX - 7);
1263 *----------------------------------------------------------------------
1267 * Returns the smallest pointer greater than or equal to p
1268 * that's a multiple of 8.
1270 *----------------------------------------------------------------------
1272 static unsigned char *AlignPtr8(unsigned char *p) {
1273 unsigned long u = (unsigned long) p;
1274 u = ((u + 7) & (ULONG_MAX - 7)) - u;
1280 * State associated with a stream
1282 typedef struct FCGX_Stream_Data {
1283 unsigned char *buff; /* buffer after alignment */
1284 int bufflen; /* number of bytes buff can store */
1285 unsigned char *mBuff; /* buffer as returned by Malloc */
1286 unsigned char *buffStop; /* reader: last valid byte + 1 of entire buffer.
1287 * stop generally differs from buffStop for
1288 * readers because of record structure.
1289 * writer: buff + bufflen */
1290 int type; /* reader: FCGI_PARAMS or FCGI_STDIN
1291 * writer: FCGI_STDOUT or FCGI_STDERR */
1292 int eorStop; /* reader: stop stream at end-of-record */
1293 int skip; /* reader: don't deliver content bytes */
1294 int contentLen; /* reader: bytes of unread content */
1295 int paddingLen; /* reader: bytes of unread padding */
1296 int isAnythingWritten; /* writer: data has been written to ipcFd */
1297 int rawWrite; /* writer: write data without stream headers */
1298 FCGX_Request *reqDataPtr; /* request data not specific to one stream */
1302 *----------------------------------------------------------------------
1304 * WriteCloseRecords --
1306 * Writes an EOF record for the stream content if necessary.
1307 * If this is the last writer to close, writes an FCGI_END_REQUEST
1310 *----------------------------------------------------------------------
1312 static void WriteCloseRecords(struct FCGX_Stream *stream)
1314 FCGX_Stream_Data *data = (FCGX_Stream_Data *)stream->data;
1316 * Enter rawWrite mode so final records won't be encapsulated as
1319 data->rawWrite = TRUE;
1321 * Generate EOF for stream content if needed.
1323 if(!(data->type == FCGI_STDERR
1324 && stream->wrNext == data->buff
1325 && !data->isAnythingWritten)) {
1327 header = MakeHeader(data->type, data->reqDataPtr->requestId, 0, 0);
1328 FCGX_PutStr((char *) &header, sizeof(header), stream);
1331 * Generate FCGI_END_REQUEST record if needed.
1333 if(data->reqDataPtr->nWriters == 1) {
1334 FCGI_EndRequestRecord endRequestRecord;
1335 endRequestRecord.header = MakeHeader(FCGI_END_REQUEST,
1336 data->reqDataPtr->requestId,
1337 sizeof(endRequestRecord.body), 0);
1338 endRequestRecord.body = MakeEndRequestBody(
1339 data->reqDataPtr->appStatus, FCGI_REQUEST_COMPLETE);
1340 FCGX_PutStr((char *) &endRequestRecord,
1341 sizeof(endRequestRecord), stream);
1343 data->reqDataPtr->nWriters--;
1348 static int write_it_all(int fd, char *buf, int len)
1353 wrote = OS_Write(fd, buf, len);
1363 *----------------------------------------------------------------------
1367 * Encapsulates any buffered stream content in a FastCGI
1368 * record. Writes the data, making the buffer empty.
1370 *----------------------------------------------------------------------
1372 static void EmptyBuffProc(struct FCGX_Stream *stream, int doClose)
1374 FCGX_Stream_Data *data = (FCGX_Stream_Data *)stream->data;
1377 * If the buffer contains stream data, fill in the header.
1378 * Pad the record to a multiple of 8 bytes in length. Padding
1379 * can't overflow the buffer because the buffer is a multiple
1380 * of 8 bytes in length. If the buffer contains no stream
1381 * data, reclaim the space reserved for the header.
1383 if(!data->rawWrite) {
1384 cLen = stream->wrNext - data->buff - sizeof(FCGI_Header);
1386 eLen = AlignInt8(cLen);
1388 * Giving the padding a well-defined value keeps Purify happy.
1390 memset(stream->wrNext, 0, eLen - cLen);
1391 stream->wrNext += eLen - cLen;
1392 *((FCGI_Header *) data->buff)
1393 = MakeHeader(data->type,
1394 data->reqDataPtr->requestId, cLen, eLen - cLen);
1396 stream->wrNext = data->buff;
1400 WriteCloseRecords(stream);
1402 if (stream->wrNext != data->buff) {
1403 data->isAnythingWritten = TRUE;
1404 if (write_it_all(data->reqDataPtr->ipcFd, (char *)data->buff, stream->wrNext - data->buff) < 0) {
1405 SetError(stream, OS_Errno);
1408 stream->wrNext = data->buff;
1411 * The buffer is empty.
1413 if(!data->rawWrite) {
1414 stream->wrNext += sizeof(FCGI_Header);
1419 * Return codes for Process* functions
1421 #define STREAM_RECORD 0
1423 #define BEGIN_RECORD 2
1424 #define MGMT_RECORD 3
1427 *----------------------------------------------------------------------
1429 * ProcessManagementRecord --
1431 * Reads and responds to a management record. The only type of
1432 * management record this library understands is FCGI_GET_VALUES.
1433 * The only variables that this library's FCGI_GET_VALUES
1434 * understands are FCGI_MAX_CONNS, FCGI_MAX_REQS, and FCGI_MPXS_CONNS.
1435 * Ignore other FCGI_GET_VALUES variables; respond to other
1436 * management records with a FCGI_UNKNOWN_TYPE record.
1438 *----------------------------------------------------------------------
1440 static int ProcessManagementRecord(int type, FCGX_Stream *stream)
1442 FCGX_Stream_Data *data = (FCGX_Stream_Data *)stream->data;
1443 ParamsPtr paramsPtr = NewParams(3);
1445 char response[64]; /* 64 = 8 + 3*(1+1+14+1)* + padding */
1446 char *responseP = &response[FCGI_HEADER_LEN];
1447 char *name, value = '\0';
1449 if(type == FCGI_GET_VALUES) {
1450 ReadParams(paramsPtr, stream);
1451 if((FCGX_GetError(stream) != 0) || (data->contentLen != 0)) {
1452 FreeParams(¶msPtr);
1453 return FCGX_PROTOCOL_ERROR;
1455 for (pPtr = paramsPtr->vec; pPtr < paramsPtr->cur; pPtr++) {
1457 *(strchr(name, '=')) = '\0';
1458 if(strcmp(name, FCGI_MAX_CONNS) == 0) {
1460 } else if(strcmp(name, FCGI_MAX_REQS) == 0) {
1462 } else if(strcmp(name, FCGI_MPXS_CONNS) == 0) {
1469 sprintf(responseP, "%c%c%s%c", len, 1, name, value);
1470 responseP += len + 3;
1473 len = responseP - &response[FCGI_HEADER_LEN];
1474 paddedLen = AlignInt8(len);
1475 *((FCGI_Header *) response)
1476 = MakeHeader(FCGI_GET_VALUES_RESULT, FCGI_NULL_REQUEST_ID,
1477 len, paddedLen - len);
1478 FreeParams(¶msPtr);
1480 paddedLen = len = sizeof(FCGI_UnknownTypeBody);
1481 ((FCGI_UnknownTypeRecord *) response)->header
1482 = MakeHeader(FCGI_UNKNOWN_TYPE, FCGI_NULL_REQUEST_ID,
1484 ((FCGI_UnknownTypeRecord *) response)->body
1485 = MakeUnknownTypeBody(type);
1487 if (write_it_all(data->reqDataPtr->ipcFd, response, FCGI_HEADER_LEN + paddedLen) < 0) {
1488 SetError(stream, OS_Errno);
1496 *----------------------------------------------------------------------
1498 * ProcessBeginRecord --
1500 * Reads an FCGI_BEGIN_REQUEST record.
1503 * BEGIN_RECORD for normal return. FCGX_PROTOCOL_ERROR for
1504 * protocol error. SKIP for attempt to multiplex
1505 * connection. -1 for error from write (errno in stream).
1508 * In case of BEGIN_RECORD return, stores requestId, role,
1509 * keepConnection values, and sets isBeginProcessed = TRUE.
1511 *----------------------------------------------------------------------
1513 static int ProcessBeginRecord(int requestId, FCGX_Stream *stream)
1515 FCGX_Stream_Data *data = (FCGX_Stream_Data *)stream->data;
1516 FCGI_BeginRequestBody body;
1517 if(requestId == 0 || data->contentLen != sizeof(body)) {
1518 return FCGX_PROTOCOL_ERROR;
1520 if(data->reqDataPtr->isBeginProcessed) {
1522 * The Web server is multiplexing the connection. This library
1523 * doesn't know how to handle multiplexing, so respond with
1524 * FCGI_END_REQUEST{protocolStatus = FCGI_CANT_MPX_CONN}
1526 FCGI_EndRequestRecord endRequestRecord;
1527 endRequestRecord.header = MakeHeader(FCGI_END_REQUEST,
1528 requestId, sizeof(endRequestRecord.body), 0);
1529 endRequestRecord.body
1530 = MakeEndRequestBody(0, FCGI_CANT_MPX_CONN);
1531 if (write_it_all(data->reqDataPtr->ipcFd, (char *)&endRequestRecord, sizeof(endRequestRecord)) < 0) {
1532 SetError(stream, OS_Errno);
1539 * Accept this new request. Read the record body.
1541 data->reqDataPtr->requestId = requestId;
1542 if(FCGX_GetStr((char *) &body, sizeof(body), stream)
1544 return FCGX_PROTOCOL_ERROR;
1546 data->reqDataPtr->keepConnection = (body.flags & FCGI_KEEP_CONN);
1547 data->reqDataPtr->role = (body.roleB1 << 8) + body.roleB0;
1548 data->reqDataPtr->isBeginProcessed = TRUE;
1549 return BEGIN_RECORD;
1553 *----------------------------------------------------------------------
1557 * Interprets FCGI_Header. Processes FCGI_BEGIN_REQUEST and
1558 * management records here; extracts information from stream
1559 * records (FCGI_PARAMS, FCGI_STDIN) into stream.
1562 * >= 0 for a normal return, < 0 for error
1565 * XXX: Many (more than there used to be).
1566 * If !stream->isRequestIdSet, ProcessHeader initializes
1567 * stream->requestId from header and sets stream->isRequestIdSet
1568 * to TRUE. ProcessHeader also sets stream->contentLen to header's
1569 * contentLength, and sets stream->paddingLen to the header's
1572 *----------------------------------------------------------------------
1574 static int ProcessHeader(FCGI_Header header, FCGX_Stream *stream)
1576 FCGX_Stream_Data *data = (FCGX_Stream_Data *)stream->data;
1578 if(header.version != FCGI_VERSION_1) {
1579 return FCGX_UNSUPPORTED_VERSION;
1581 requestId = (header.requestIdB1 << 8)
1582 + header.requestIdB0;
1583 data->contentLen = (header.contentLengthB1 << 8)
1584 + header.contentLengthB0;
1585 data->paddingLen = header.paddingLength;
1586 if(header.type == FCGI_BEGIN_REQUEST) {
1587 return ProcessBeginRecord(requestId, stream);
1589 if(requestId == FCGI_NULL_REQUEST_ID) {
1590 return ProcessManagementRecord(header.type, stream);
1592 if(requestId != data->reqDataPtr->requestId) {
1595 if(header.type != data->type) {
1596 return FCGX_PROTOCOL_ERROR;
1598 return STREAM_RECORD;
1602 *----------------------------------------------------------------------
1606 * Reads bytes from the ipcFd, supplies bytes to a stream client.
1608 *----------------------------------------------------------------------
1610 static void FillBuffProc(FCGX_Stream *stream)
1612 FCGX_Stream_Data *data = (FCGX_Stream_Data *)stream->data;
1619 * If data->buff is empty, do a read.
1621 if(stream->rdNext == data->buffStop) {
1622 count = OS_Read(data->reqDataPtr->ipcFd, (char *)data->buff,
1625 SetError(stream, (count == 0 ? FCGX_PROTOCOL_ERROR : OS_Errno));
1628 stream->rdNext = data->buff;
1629 data->buffStop = data->buff + count;
1632 * Now data->buff is not empty. If the current record contains
1633 * more content bytes, deliver all that are present in data->buff.
1635 if(data->contentLen > 0) {
1636 count = min(data->contentLen, data->buffStop - stream->rdNext);
1637 data->contentLen -= count;
1639 stream->wrNext = stream->stop = stream->rdNext + count;
1642 stream->rdNext += count;
1643 if(data->contentLen > 0) {
1651 * If the current record (whose content has been fully consumed by
1652 * the client) was padded, skip over the padding bytes.
1654 if(data->paddingLen > 0) {
1655 count = min(data->paddingLen, data->buffStop - stream->rdNext);
1656 data->paddingLen -= count;
1657 stream->rdNext += count;
1658 if(data->paddingLen > 0) {
1663 * All done with the current record, including the padding.
1664 * If we're in a recursive call from ProcessHeader, deliver EOF.
1667 stream->stop = stream->rdNext;
1668 stream->isClosed = TRUE;
1672 * Fill header with bytes from the input buffer.
1674 count = min((int)sizeof(header) - headerLen,
1675 data->buffStop - stream->rdNext);
1676 memcpy(((char *)(&header)) + headerLen, stream->rdNext, count);
1678 stream->rdNext += count;
1679 if(headerLen < sizeof(header)) {
1684 * Interpret header. eorStop prevents ProcessHeader from reading
1685 * past the end-of-record when using stream to read content.
1687 data->eorStop = TRUE;
1688 stream->stop = stream->rdNext;
1689 status = ProcessHeader(header, stream);
1690 data->eorStop = FALSE;
1691 stream->isClosed = FALSE;
1695 * If this stream record header marked the end of stream
1696 * data deliver EOF to the stream client, otherwise loop
1699 * XXX: If this is final stream and
1700 * stream->rdNext != data->buffStop, buffered
1701 * data is next request (server pipelining)?
1703 if(data->contentLen == 0) {
1704 stream->wrNext = stream->stop = stream->rdNext;
1705 stream->isClosed = TRUE;
1714 * If this header marked the beginning of a new
1715 * request, return role information to caller.
1723 SetError(stream, status);
1731 *----------------------------------------------------------------------
1735 * Creates a stream to read or write from an open ipcFd.
1736 * The stream performs reads/writes of up to bufflen bytes.
1738 *----------------------------------------------------------------------
1740 static FCGX_Stream *NewStream(
1741 FCGX_Request *reqDataPtr, int bufflen, int isReader, int streamType)
1744 * XXX: It would be a lot cleaner to have a NewStream that only
1745 * knows about the type FCGX_Stream, with all other
1746 * necessary data passed in. It appears that not just
1747 * data and the two procs are needed for initializing stream,
1748 * but also data->buff and data->buffStop. This has implications
1749 * for procs that want to swap buffers, too.
1751 FCGX_Stream *stream = (FCGX_Stream *)Malloc(sizeof(FCGX_Stream));
1752 FCGX_Stream_Data *data = (FCGX_Stream_Data *)Malloc(sizeof(FCGX_Stream_Data));
1753 data->reqDataPtr = reqDataPtr;
1754 bufflen = AlignInt8(min(max(bufflen, 32), FCGI_MAX_LENGTH + 1));
1755 data->bufflen = bufflen;
1756 data->mBuff = (unsigned char *)Malloc(bufflen);
1757 data->buff = AlignPtr8(data->mBuff);
1758 if(data->buff != data->mBuff) {
1762 data->buffStop = data->buff;
1764 data->buffStop = data->buff + data->bufflen;
1766 data->type = streamType;
1767 data->eorStop = FALSE;
1769 data->contentLen = 0;
1770 data->paddingLen = 0;
1771 data->isAnythingWritten = FALSE;
1772 data->rawWrite = FALSE;
1774 stream->data = data;
1775 stream->isReader = isReader;
1776 stream->isClosed = FALSE;
1777 stream->wasFCloseCalled = FALSE;
1778 stream->FCGI_errno = 0;
1780 stream->fillBuffProc = FillBuffProc;
1781 stream->emptyBuffProc = NULL;
1782 stream->rdNext = data->buff;
1783 stream->stop = stream->rdNext;
1784 stream->stopUnget = data->buff;
1785 stream->wrNext = stream->stop;
1787 stream->fillBuffProc = NULL;
1788 stream->emptyBuffProc = EmptyBuffProc;
1789 stream->wrNext = data->buff + sizeof(FCGI_Header);
1790 stream->stop = data->buffStop;
1791 stream->stopUnget = NULL;
1792 stream->rdNext = stream->stop;
1798 *----------------------------------------------------------------------
1800 * FCGX_FreeStream --
1802 * Frees all storage allocated when *streamPtr was created,
1803 * and nulls out *streamPtr.
1805 *----------------------------------------------------------------------
1807 void FCGX_FreeStream(FCGX_Stream **streamPtr)
1809 FCGX_Stream *stream = *streamPtr;
1810 FCGX_Stream_Data *data;
1811 if(stream == NULL) {
1814 data = (FCGX_Stream_Data *)stream->data;
1815 data->reqDataPtr = NULL;
1823 *----------------------------------------------------------------------
1827 * Re-initializes the stream to read data of the specified type.
1829 *----------------------------------------------------------------------
1831 static FCGX_Stream *SetReaderType(FCGX_Stream *stream, int streamType)
1833 FCGX_Stream_Data *data = (FCGX_Stream_Data *)stream->data;
1834 ASSERT(stream->isReader);
1835 data->type = streamType;
1836 data->eorStop = FALSE;
1838 data->contentLen = 0;
1839 data->paddingLen = 0;
1840 stream->wrNext = stream->stop = stream->rdNext;
1841 stream->isClosed = FALSE;
1846 *----------------------------------------------------------------------
1850 * Creates a stream to read streamType records for the given
1851 * request. The stream performs OS reads of up to bufflen bytes.
1853 *----------------------------------------------------------------------
1855 static FCGX_Stream *NewReader(FCGX_Request *reqDataPtr, int bufflen, int streamType)
1857 return NewStream(reqDataPtr, bufflen, TRUE, streamType);
1861 *----------------------------------------------------------------------
1865 * Creates a stream to write streamType FastCGI records, using
1866 * the ipcFd and RequestId contained in *reqDataPtr.
1867 * The stream performs OS writes of up to bufflen bytes.
1869 *----------------------------------------------------------------------
1871 static FCGX_Stream *NewWriter(FCGX_Request *reqDataPtr, int bufflen, int streamType)
1873 return NewStream(reqDataPtr, bufflen, FALSE, streamType);
1877 *----------------------------------------------------------------------
1879 * FCGX_CreateWriter --
1881 * Creates a stream to write streamType FastCGI records, using
1882 * the given ipcFd and request Id. This function is provided
1883 * for use by cgi-fcgi. In order to be defensive against misuse,
1884 * this function leaks a little storage; cgi-fcgi doesn't care.
1886 *----------------------------------------------------------------------
1888 FCGX_Stream *FCGX_CreateWriter(
1894 FCGX_Request *reqDataPtr = (FCGX_Request *)Malloc(sizeof(FCGX_Request));
1895 reqDataPtr->ipcFd = ipcFd;
1896 reqDataPtr->requestId = requestId;
1898 * Suppress writing an FCGI_END_REQUEST record.
1900 reqDataPtr->nWriters = 2;
1901 return NewWriter(reqDataPtr, bufflen, streamType);
1905 *======================================================================
1907 *======================================================================
1911 *----------------------------------------------------------------------
1915 * This routine determines if the process is running as a CGI or
1916 * FastCGI process. The distinction is made by determining whether
1917 * FCGI_LISTENSOCK_FILENO is a listener ipcFd or the end of a
1918 * pipe (ie. standard in).
1921 * TRUE if the process is a CGI process, FALSE if FastCGI.
1923 *----------------------------------------------------------------------
1925 int FCGX_IsCGI(void)
1927 if (isFastCGI != -1) {
1931 if (!libInitialized) {
1932 int rc = FCGX_Init();
1934 /* exit() isn't great, but hey */
1935 exit((rc < 0) ? rc : -rc);
1939 isFastCGI = OS_IsFcgi(FCGI_LISTENSOCK_FILENO);
1945 *----------------------------------------------------------------------
1949 * Finishes the current request from the HTTP server.
1953 * Finishes the request accepted by (and frees any
1954 * storage allocated by) the previous call to FCGX_Accept.
1956 * DO NOT retain pointers to the envp array or any strings
1957 * contained in it (e.g. to the result of calling FCGX_GetParam),
1958 * since these will be freed by the next call to FCGX_Finish
1961 *----------------------------------------------------------------------
1964 void FCGX_Finish(void)
1966 FCGX_Finish_r(&the_request);
1970 *----------------------------------------------------------------------
1974 * Finishes the current request from the HTTP server.
1978 * Finishes the request accepted by (and frees any
1979 * storage allocated by) the previous call to FCGX_Accept.
1981 * DO NOT retain pointers to the envp array or any strings
1982 * contained in it (e.g. to the result of calling FCGX_GetParam),
1983 * since these will be freed by the next call to FCGX_Finish
1986 *----------------------------------------------------------------------
1988 void FCGX_Finish_r(FCGX_Request *reqDataPtr)
1992 if (reqDataPtr == NULL) {
1996 close = !reqDataPtr->keepConnection;
1998 /* This should probably use a 'status' member instead of 'in' */
1999 if (reqDataPtr->in) {
2000 close |= FCGX_FClose(reqDataPtr->err);
2001 close |= FCGX_FClose(reqDataPtr->out);
2003 close |= FCGX_GetError(reqDataPtr->in);
2006 FCGX_Free(reqDataPtr, close);
2009 void FCGX_Free(FCGX_Request * request, int close)
2011 if (request == NULL)
2014 FCGX_FreeStream(&request->in);
2015 FCGX_FreeStream(&request->out);
2016 FCGX_FreeStream(&request->err);
2017 FreeParams(&request->paramsPtr);
2020 OS_IpcClose(request->ipcFd);
2021 request->ipcFd = -1;
2025 int FCGX_OpenSocket(const char *path, int backlog)
2027 int rc = OS_CreateLocalIpcFd(path, backlog);
2028 if (rc == FCGI_LISTENSOCK_FILENO && isFastCGI == 0) {
2029 /* XXX probably need to call OS_LibInit() again for Win */
2035 int FCGX_InitRequest(FCGX_Request *request, int sock, int flags)
2037 memset(request, 0, sizeof(FCGX_Request));
2039 /* @@@ Should check that sock is open and listening */
2040 request->listen_sock = sock;
2042 /* @@@ Should validate against "known" flags */
2043 request->flags = flags;
2045 request->ipcFd = -1;
2051 *----------------------------------------------------------------------
2055 * Initilize the FCGX library. This is called by FCGX_Accept()
2056 * but must be called by the user when using FCGX_Accept_r().
2059 * 0 for successful call.
2061 *----------------------------------------------------------------------
2067 if (libInitialized) {
2071 /* If our compiler doesn't play by the ISO rules for struct layout, halt. */
2072 ASSERT(sizeof(FCGI_Header) == FCGI_HEADER_LEN);
2074 FCGX_InitRequest(&the_request, FCGI_LISTENSOCK_FILENO, 0);
2076 if (OS_LibInit(NULL) == -1) {
2077 return OS_Errno ? OS_Errno : -9997;
2080 p = getenv("FCGI_WEB_SERVER_ADDRS");
2081 webServerAddressList = p ? StringCopy(p) : NULL;
2088 *----------------------------------------------------------------------
2092 * Accepts a new request from the HTTP server.
2095 * 0 for successful call, -1 for error.
2099 * Finishes the request accepted by (and frees any
2100 * storage allocated by) the previous call to FCGX_Accept.
2101 * Creates input, output, and error streams and
2102 * assigns them to *in, *out, and *err respectively.
2103 * Creates a parameters data structure to be accessed
2104 * via getenv(3) (if assigned to environ) or by FCGX_GetParam
2105 * and assigns it to *envp.
2107 * DO NOT retain pointers to the envp array or any strings
2108 * contained in it (e.g. to the result of calling FCGX_GetParam),
2109 * since these will be freed by the next call to FCGX_Finish
2112 *----------------------------------------------------------------------
2119 FCGX_ParamArray *envp)
2123 if (! libInitialized) {
2130 rc = FCGX_Accept_r(&the_request);
2132 *in = the_request.in;
2133 *out = the_request.out;
2134 *err = the_request.err;
2135 *envp = the_request.envp;
2141 *----------------------------------------------------------------------
2145 * Accepts a new request from the HTTP server.
2148 * 0 for successful call, -1 for error.
2152 * Finishes the request accepted by (and frees any
2153 * storage allocated by) the previous call to FCGX_Accept.
2154 * Creates input, output, and error streams and
2155 * assigns them to *in, *out, and *err respectively.
2156 * Creates a parameters data structure to be accessed
2157 * via getenv(3) (if assigned to environ) or by FCGX_GetParam
2158 * and assigns it to *envp.
2160 * DO NOT retain pointers to the envp array or any strings
2161 * contained in it (e.g. to the result of calling FCGX_GetParam),
2162 * since these will be freed by the next call to FCGX_Finish
2165 *----------------------------------------------------------------------
2167 int FCGX_Accept_r(FCGX_Request *reqDataPtr)
2169 if (!libInitialized) {
2173 /* Finish the current request, if any. */
2174 FCGX_Finish_r(reqDataPtr);
2178 * If a connection isn't open, accept a new connection (blocking).
2179 * If an OS error occurs in accepting the connection,
2180 * return -1 to the caller, who should exit.
2182 if (reqDataPtr->ipcFd < 0) {
2183 int fail_on_intr = reqDataPtr->flags & FCGI_FAIL_ACCEPT_ON_INTR;
2185 reqDataPtr->ipcFd = OS_Accept(reqDataPtr->listen_sock, fail_on_intr, webServerAddressList);
2186 if (reqDataPtr->ipcFd < 0) {
2187 return (errno > 0) ? (0 - errno) : -9999;
2191 * A connection is open. Read from the connection in order to
2192 * get the request's role and environment. If protocol or other
2193 * errors occur, close the connection and try again.
2195 reqDataPtr->isBeginProcessed = FALSE;
2196 reqDataPtr->in = NewReader(reqDataPtr, 8192, 0);
2197 FillBuffProc(reqDataPtr->in);
2198 if(!reqDataPtr->isBeginProcessed) {
2203 switch(reqDataPtr->role) {
2204 case FCGI_RESPONDER:
2205 roleStr = "FCGI_ROLE=RESPONDER";
2207 case FCGI_AUTHORIZER:
2208 roleStr = "FCGI_ROLE=AUTHORIZER";
2211 roleStr = "FCGI_ROLE=FILTER";
2216 reqDataPtr->paramsPtr = NewParams(30);
2217 PutParam(reqDataPtr->paramsPtr, StringCopy(roleStr));
2219 SetReaderType(reqDataPtr->in, FCGI_PARAMS);
2220 if(ReadParams(reqDataPtr->paramsPtr, reqDataPtr->in) >= 0) {
2222 * Finished reading the environment. No errors occurred, so
2223 * leave the connection-retry loop.
2229 * Close the connection and try again.
2232 FCGX_Free(reqDataPtr, 1);
2236 * Build the remaining data structures representing the new
2237 * request and return successfully to the caller.
2239 SetReaderType(reqDataPtr->in, FCGI_STDIN);
2240 reqDataPtr->out = NewWriter(reqDataPtr, 8192, FCGI_STDOUT);
2241 reqDataPtr->err = NewWriter(reqDataPtr, 512, FCGI_STDERR);
2242 reqDataPtr->nWriters = 2;
2243 reqDataPtr->envp = reqDataPtr->paramsPtr->vec;
2248 *----------------------------------------------------------------------
2250 * FCGX_StartFilterData --
2252 * stream is an input stream for a FCGI_FILTER request.
2253 * stream is positioned at EOF on FCGI_STDIN.
2254 * Repositions stream to the start of FCGI_DATA.
2255 * If the preconditions are not met (e.g. FCGI_STDIN has not
2256 * been read to EOF) sets the stream error code to
2257 * FCGX_CALL_SEQ_ERROR.
2260 * 0 for a normal return, < 0 for error
2262 *----------------------------------------------------------------------
2265 int FCGX_StartFilterData(FCGX_Stream *stream)
2267 FCGX_Stream_Data *data = (FCGX_Stream_Data *)stream->data;
2268 if(data->reqDataPtr->role != FCGI_FILTER
2269 || !stream->isReader
2270 || !stream->isClosed
2271 || data->type != FCGI_STDIN) {
2272 SetError(stream, FCGX_CALL_SEQ_ERROR);
2275 SetReaderType(stream, FCGI_DATA);
2280 *----------------------------------------------------------------------
2282 * FCGX_SetExitStatus --
2284 * Sets the exit status for stream's request. The exit status
2285 * is the status code the request would have exited with, had
2286 * the request been run as a CGI program. You can call
2287 * SetExitStatus several times during a request; the last call
2288 * before the request ends determines the value.
2290 *----------------------------------------------------------------------
2293 void FCGX_SetExitStatus(int status, FCGX_Stream *stream)
2295 FCGX_Stream_Data *data = (FCGX_Stream_Data *)stream->data;
2296 data->reqDataPtr->appStatus = status;