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.22 2001/06/19 16:18:14 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)
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)
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++ = c);
273 if(stream->isClosed || stream->isReader)
275 stream->emptyBuffProc(stream, FALSE);
276 if(stream->wrNext != stream->stop)
277 return (*stream->wrNext++ = 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, buffLen, specifierLength;
402 int fastPath, n, auxBuffLen, 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;
420 LONG_DOUBLE lDoubleArg;
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] = sizeModifier;
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 frexp(lDoubleArg, &exp);
605 if(precision == -1) precision = 6;
606 buffReqd = precision + 3 + ((exp > 0) ? exp/3 : 0);
612 if(precision == -1) precision = 6;
613 buffReqd = precision + 8;
621 buffReqd = max(buffReqd + 10, minWidth);
623 * Allocate the buffer
625 if(buffReqd <= PRINTF_BUFFLEN) {
627 buffLen = PRINTF_BUFFLEN;
629 if(auxBuffPtr == NULL || buffReqd > auxBuffLen) {
630 if(auxBuffPtr != NULL) free(auxBuffPtr);
631 auxBuffPtr = (char *)Malloc(buffReqd);
632 auxBuffLen = buffReqd;
633 if(auxBuffPtr == NULL)
636 buffPtr = auxBuffPtr;
637 buffLen = auxBuffLen;
641 * This giant switch statement requires the following variables
642 * to be set up: op, sizeModifier, arg, buffPtr, fmtBuff.
643 * When fastPath == FALSE and op == 's' or 'f', the argument
644 * has been read into charPtrArg, doubleArg, or lDoubleArg.
645 * The statement produces the boolean performedOp, TRUE iff
646 * the op/sizeModifier were executed and argument consumed;
647 * if performedOp, the characters written into buffPtr[]
648 * and the character count buffCount (== EOF meaning error).
650 * The switch cases are arranged in the same order as in the
651 * description of fprintf in section 15.11 of Harbison and Steele.
657 switch(sizeModifier) {
659 intArg = va_arg(arg, int);
660 sprintf(buffPtr, fmtBuff, intArg);
661 buffCount = strlen(buffPtr);
664 longArg = va_arg(arg, long);
665 sprintf(buffPtr, fmtBuff, longArg);
666 buffCount = strlen(buffPtr);
669 shortArg = (short) va_arg(arg, int);
670 sprintf(buffPtr, fmtBuff, shortArg);
671 buffCount = strlen(buffPtr);
681 switch(sizeModifier) {
683 unsignedArg = va_arg(arg, unsigned);
684 sprintf(buffPtr, fmtBuff, unsignedArg);
685 buffCount = strlen(buffPtr);
688 uLongArg = va_arg(arg, unsigned long);
689 sprintf(buffPtr, fmtBuff, uLongArg);
690 buffCount = strlen(buffPtr);
693 uShortArg = (unsigned short) va_arg(arg, int);
694 sprintf(buffPtr, fmtBuff, uShortArg);
695 buffCount = strlen(buffPtr);
702 switch(sizeModifier) {
704 intArg = va_arg(arg, int);
705 sprintf(buffPtr, fmtBuff, intArg);
706 buffCount = strlen(buffPtr);
710 * XXX: Allowed by ISO C Amendment 1, but
711 * many platforms don't yet support wint_t
719 switch(sizeModifier) {
722 buffPtr = va_arg(arg, char *);
723 buffCount = strlen(buffPtr);
724 buffLen = buffCount + 1;
726 sprintf(buffPtr, fmtBuff, charPtrArg);
727 buffCount = strlen(buffPtr);
732 * XXX: Don't know how to convert a sequence
733 * of wide characters into a byte stream, or
734 * even how to predict the buffering required.
742 if(sizeModifier != ' ')
744 voidPtrArg = va_arg(arg, void *);
745 sprintf(buffPtr, fmtBuff, voidPtrArg);
746 buffCount = strlen(buffPtr);
749 switch(sizeModifier) {
751 intPtrArg = va_arg(arg, int *);
752 *intPtrArg = streamCount;
755 longPtrArg = va_arg(arg, long *);
756 *longPtrArg = streamCount;
759 shortPtrArg = va_arg(arg, short *);
760 *shortPtrArg = streamCount;
772 switch(sizeModifier) {
774 sprintf(buffPtr, fmtBuff, doubleArg);
775 buffCount = strlen(buffPtr);
778 sprintf(buffPtr, fmtBuff, lDoubleArg);
779 buffCount = strlen(buffPtr);
789 switch(sizeModifier) {
791 doubleArg = va_arg(arg, double);
792 sprintf(buffPtr, fmtBuff, doubleArg);
793 buffCount = strlen(buffPtr);
796 lDoubleArg = va_arg(arg, LONG_DOUBLE);
797 sprintf(buffPtr, fmtBuff, lDoubleArg);
798 buffCount = strlen(buffPtr);
805 if(sizeModifier != ' ')
816 if(performedOp) break;
821 ASSERT(buffCount < buffLen);
823 if(FCGX_PutStr(buffPtr, buffCount, stream) < 0)
825 streamCount += buffCount;
826 } else if(buffCount < 0) {
829 f += specifierLength;
830 } /* while(f != fStop) */
835 if(auxBuffPtr != NULL) free(auxBuffPtr);
840 * Copy n characters from *srcPtr to *destPtr, then increment
841 * both *srcPtr and *destPtr by n.
843 static void CopyAndAdvance(char **destPtr, char **srcPtr, int n)
845 char *dest = *destPtr;
848 for (i = 0; i < n; i++)
855 *----------------------------------------------------------------------
859 * Flushes any buffered output.
861 * Server-push is a legitimate application of FCGX_FFlush.
862 * Otherwise, FCGX_FFlush is not very useful, since FCGX_Accept
863 * does it implicitly. FCGX_FFlush may reduce performance
864 * by increasing the total number of operating system calls
865 * the application makes.
868 * EOF (-1) if an error occurred.
870 *----------------------------------------------------------------------
872 int FCGX_FFlush(FCGX_Stream *stream)
874 if(stream->isClosed || stream->isReader)
876 stream->emptyBuffProc(stream, FALSE);
877 return (stream->isClosed) ? -1 : 0;
881 *----------------------------------------------------------------------
885 * Performs FCGX_FFlush and closes the stream.
887 * This is not a very useful operation, since FCGX_Accept
888 * does it implicitly. Closing the out stream before the
889 * err stream results in an extra write if there's nothing
890 * in the err stream, and therefore reduces performance.
893 * EOF (-1) if an error occurred.
895 *----------------------------------------------------------------------
897 int FCGX_FClose(FCGX_Stream *stream)
899 if (stream == NULL) return 0;
901 if(!stream->wasFCloseCalled) {
902 if(!stream->isReader) {
903 stream->emptyBuffProc(stream, TRUE);
905 stream->wasFCloseCalled = TRUE;
906 stream->isClosed = TRUE;
907 if(stream->isReader) {
908 stream->wrNext = stream->stop = stream->rdNext;
910 stream->rdNext = stream->stop = stream->wrNext;
913 return (stream->FCGI_errno == 0) ? 0 : EOF;
917 *----------------------------------------------------------------------
921 * An error has occurred; save the error code in the stream
922 * for diagnostic purposes and set the stream state so that
923 * reads return EOF and writes have no effect.
925 *----------------------------------------------------------------------
927 static void SetError(FCGX_Stream *stream, int FCGI_errno)
930 * Preserve only the first error.
932 if(stream->FCGI_errno == 0) {
933 stream->FCGI_errno = FCGI_errno;
934 stream->isClosed = TRUE;
939 *----------------------------------------------------------------------
943 * Return the stream error code. 0 means no error, > 0
944 * is an errno(2) error, < 0 is an FCGX_errno error.
946 *----------------------------------------------------------------------
948 int FCGX_GetError(FCGX_Stream *stream) {
949 return stream->FCGI_errno;
953 *----------------------------------------------------------------------
957 * Clear the stream error code and end-of-file indication.
959 *----------------------------------------------------------------------
961 void FCGX_ClearError(FCGX_Stream *stream) {
962 stream->FCGI_errno = 0;
964 * stream->isClosed = FALSE;
965 * XXX: should clear isClosed but work is needed to make it safe
966 * to do so. For example, if an application calls FClose, gets
967 * an I/O error on the write, calls ClearError and retries
968 * the FClose, FClose (really EmptyBuffProc) will write a second
969 * EOF record. If an application calls PutChar instead of FClose
970 * after the ClearError, the application will write more data.
971 * The stream's state must discriminate between various states
972 * of the stream that are now all lumped under isClosed.
977 *======================================================================
979 *======================================================================
983 * A vector of pointers representing the parameters received
984 * by a FastCGI application server, with the vector's length
985 * and last valid element so adding new parameters is efficient.
988 typedef struct Params {
989 FCGX_ParamArray vec; /* vector of strings */
990 int length; /* number of string vec can hold */
991 char **cur; /* current item in vec; *cur == NULL */
993 typedef Params *ParamsPtr;
996 *----------------------------------------------------------------------
1000 * Creates a new Params structure.
1003 * Pointer to the new structure.
1005 *----------------------------------------------------------------------
1007 static ParamsPtr NewParams(int length)
1010 result = (Params *)Malloc(sizeof(Params));
1011 result->vec = (char **)Malloc(length * sizeof(char *));
1012 result->length = length;
1013 result->cur = result->vec;
1014 *result->cur = NULL;
1019 *----------------------------------------------------------------------
1023 * Frees a Params structure and all the parameters it contains.
1026 * env becomes invalid.
1028 *----------------------------------------------------------------------
1030 static void FreeParams(ParamsPtr *paramsPtrPtr)
1032 ParamsPtr paramsPtr = *paramsPtrPtr;
1034 if(paramsPtr == NULL) {
1037 for (p = paramsPtr->vec; p < paramsPtr->cur; p++) {
1040 free(paramsPtr->vec);
1042 *paramsPtrPtr = NULL;
1046 *----------------------------------------------------------------------
1050 * Add a name/value pair to a Params structure.
1056 * Parameters structure updated.
1058 *----------------------------------------------------------------------
1060 static void PutParam(ParamsPtr paramsPtr, char *nameValue)
1064 *paramsPtr->cur++ = nameValue;
1065 size = paramsPtr->cur - paramsPtr->vec;
1066 if(size >= paramsPtr->length) {
1067 paramsPtr->length *= 2;
1068 paramsPtr->vec = (FCGX_ParamArray)realloc(paramsPtr->vec, paramsPtr->length * sizeof(char *));
1069 paramsPtr->cur = paramsPtr->vec + size;
1071 *paramsPtr->cur = NULL;
1075 *----------------------------------------------------------------------
1077 * FCGX_GetParam -- obtain value of FCGI parameter in environment
1081 * Value bound to name, NULL if name not present in the
1082 * environment envp. Caller must not mutate the result
1083 * or retain it past the end of this request.
1085 *----------------------------------------------------------------------
1087 char *FCGX_GetParam(const char *name, FCGX_ParamArray envp)
1092 if (name == NULL || envp == NULL) return NULL;
1096 for (p = envp; *p; ++p) {
1097 if((strncmp(name, *p, len) == 0) && ((*p)[len] == '=')) {
1105 *----------------------------------------------------------------------
1107 * Start of FastCGI-specific code
1109 *----------------------------------------------------------------------
1113 *----------------------------------------------------------------------
1117 * Reads FastCGI name-value pairs from stream until EOF. Converts
1118 * each pair to name=value format and adds it to Params structure.
1120 *----------------------------------------------------------------------
1122 static int ReadParams(Params *paramsPtr, FCGX_Stream *stream)
1124 int nameLen, valueLen;
1125 unsigned char lenBuff[3];
1128 while((nameLen = FCGX_GetChar(stream)) != EOF) {
1130 * Read name length (one or four bytes) and value length
1131 * (one or four bytes) from stream.
1133 if((nameLen & 0x80) != 0) {
1134 if(FCGX_GetStr((char *) &lenBuff[0], 3, stream) != 3) {
1135 SetError(stream, FCGX_PARAMS_ERROR);
1138 nameLen = ((nameLen & 0x7f) << 24) + (lenBuff[0] << 16)
1139 + (lenBuff[1] << 8) + lenBuff[2];
1141 if((valueLen = FCGX_GetChar(stream)) == EOF) {
1142 SetError(stream, FCGX_PARAMS_ERROR);
1145 if((valueLen & 0x80) != 0) {
1146 if(FCGX_GetStr((char *) &lenBuff[0], 3, stream) != 3) {
1147 SetError(stream, FCGX_PARAMS_ERROR);
1150 valueLen = ((valueLen & 0x7f) << 24) + (lenBuff[0] << 16)
1151 + (lenBuff[1] << 8) + lenBuff[2];
1154 * nameLen and valueLen are now valid; read the name and value
1155 * from stream and construct a standard environment entry.
1157 nameValue = (char *)Malloc(nameLen + valueLen + 2);
1158 if(FCGX_GetStr(nameValue, nameLen, stream) != nameLen) {
1159 SetError(stream, FCGX_PARAMS_ERROR);
1163 *(nameValue + nameLen) = '=';
1164 if(FCGX_GetStr(nameValue + nameLen + 1, valueLen, stream)
1166 SetError(stream, FCGX_PARAMS_ERROR);
1170 *(nameValue + nameLen + valueLen + 1) = '\0';
1171 PutParam(paramsPtr, nameValue);
1177 *----------------------------------------------------------------------
1181 * Constructs an FCGI_Header struct.
1183 *----------------------------------------------------------------------
1185 static FCGI_Header MakeHeader(
1192 ASSERT(contentLength >= 0 && contentLength <= FCGI_MAX_LENGTH);
1193 ASSERT(paddingLength >= 0 && paddingLength <= 0xff);
1194 header.version = FCGI_VERSION_1;
1196 header.requestIdB1 = (requestId >> 8) & 0xff;
1197 header.requestIdB0 = (requestId ) & 0xff;
1198 header.contentLengthB1 = (contentLength >> 8) & 0xff;
1199 header.contentLengthB0 = (contentLength ) & 0xff;
1200 header.paddingLength = paddingLength;
1201 header.reserved = 0;
1206 *----------------------------------------------------------------------
1208 * MakeEndRequestBody --
1210 * Constructs an FCGI_EndRequestBody struct.
1212 *----------------------------------------------------------------------
1214 static FCGI_EndRequestBody MakeEndRequestBody(
1218 FCGI_EndRequestBody body;
1219 body.appStatusB3 = (appStatus >> 24) & 0xff;
1220 body.appStatusB2 = (appStatus >> 16) & 0xff;
1221 body.appStatusB1 = (appStatus >> 8) & 0xff;
1222 body.appStatusB0 = (appStatus ) & 0xff;
1223 body.protocolStatus = protocolStatus;
1224 memset(body.reserved, 0, sizeof(body.reserved));
1229 *----------------------------------------------------------------------
1231 * MakeUnknownTypeBody --
1233 * Constructs an FCGI_MakeUnknownTypeBody struct.
1235 *----------------------------------------------------------------------
1237 static FCGI_UnknownTypeBody MakeUnknownTypeBody(
1240 FCGI_UnknownTypeBody body;
1242 memset(body.reserved, 0, sizeof(body.reserved));
1247 *----------------------------------------------------------------------
1251 * Returns the smallest integer greater than or equal to n
1252 * that's a multiple of 8.
1254 *----------------------------------------------------------------------
1256 static int AlignInt8(unsigned n) {
1257 return (n + 7) & (UINT_MAX - 7);
1261 *----------------------------------------------------------------------
1265 * Returns the smallest pointer greater than or equal to p
1266 * that's a multiple of 8.
1268 *----------------------------------------------------------------------
1270 static unsigned char *AlignPtr8(unsigned char *p) {
1271 unsigned long u = (unsigned long) p;
1272 u = ((u + 7) & (ULONG_MAX - 7)) - u;
1278 * State associated with a stream
1280 typedef struct FCGX_Stream_Data {
1281 unsigned char *buff; /* buffer after alignment */
1282 int bufflen; /* number of bytes buff can store */
1283 unsigned char *mBuff; /* buffer as returned by Malloc */
1284 unsigned char *buffStop; /* reader: last valid byte + 1 of entire buffer.
1285 * stop generally differs from buffStop for
1286 * readers because of record structure.
1287 * writer: buff + bufflen */
1288 int type; /* reader: FCGI_PARAMS or FCGI_STDIN
1289 * writer: FCGI_STDOUT or FCGI_STDERR */
1290 int eorStop; /* reader: stop stream at end-of-record */
1291 int skip; /* reader: don't deliver content bytes */
1292 int contentLen; /* reader: bytes of unread content */
1293 int paddingLen; /* reader: bytes of unread padding */
1294 int isAnythingWritten; /* writer: data has been written to ipcFd */
1295 int rawWrite; /* writer: write data without stream headers */
1296 FCGX_Request *reqDataPtr; /* request data not specific to one stream */
1300 *----------------------------------------------------------------------
1302 * WriteCloseRecords --
1304 * Writes an EOF record for the stream content if necessary.
1305 * If this is the last writer to close, writes an FCGI_END_REQUEST
1308 *----------------------------------------------------------------------
1310 static void WriteCloseRecords(struct FCGX_Stream *stream)
1312 FCGX_Stream_Data *data = (FCGX_Stream_Data *)stream->data;
1314 * Enter rawWrite mode so final records won't be encapsulated as
1317 data->rawWrite = TRUE;
1319 * Generate EOF for stream content if needed.
1321 if(!(data->type == FCGI_STDERR
1322 && stream->wrNext == data->buff
1323 && !data->isAnythingWritten)) {
1325 header = MakeHeader(data->type, data->reqDataPtr->requestId, 0, 0);
1326 FCGX_PutStr((char *) &header, sizeof(header), stream);
1329 * Generate FCGI_END_REQUEST record if needed.
1331 if(data->reqDataPtr->nWriters == 1) {
1332 FCGI_EndRequestRecord endRequestRecord;
1333 endRequestRecord.header = MakeHeader(FCGI_END_REQUEST,
1334 data->reqDataPtr->requestId,
1335 sizeof(endRequestRecord.body), 0);
1336 endRequestRecord.body = MakeEndRequestBody(
1337 data->reqDataPtr->appStatus, FCGI_REQUEST_COMPLETE);
1338 FCGX_PutStr((char *) &endRequestRecord,
1339 sizeof(endRequestRecord), stream);
1341 data->reqDataPtr->nWriters--;
1346 static int write_it_all(int fd, char *buf, int len)
1351 wrote = OS_Write(fd, buf, len);
1361 *----------------------------------------------------------------------
1365 * Encapsulates any buffered stream content in a FastCGI
1366 * record. Writes the data, making the buffer empty.
1368 *----------------------------------------------------------------------
1370 static void EmptyBuffProc(struct FCGX_Stream *stream, int doClose)
1372 FCGX_Stream_Data *data = (FCGX_Stream_Data *)stream->data;
1375 * If the buffer contains stream data, fill in the header.
1376 * Pad the record to a multiple of 8 bytes in length. Padding
1377 * can't overflow the buffer because the buffer is a multiple
1378 * of 8 bytes in length. If the buffer contains no stream
1379 * data, reclaim the space reserved for the header.
1381 if(!data->rawWrite) {
1382 cLen = stream->wrNext - data->buff - sizeof(FCGI_Header);
1384 eLen = AlignInt8(cLen);
1386 * Giving the padding a well-defined value keeps Purify happy.
1388 memset(stream->wrNext, 0, eLen - cLen);
1389 stream->wrNext += eLen - cLen;
1390 *((FCGI_Header *) data->buff)
1391 = MakeHeader(data->type,
1392 data->reqDataPtr->requestId, cLen, eLen - cLen);
1394 stream->wrNext = data->buff;
1398 WriteCloseRecords(stream);
1400 if (stream->wrNext != data->buff) {
1401 data->isAnythingWritten = TRUE;
1402 if (write_it_all(data->reqDataPtr->ipcFd, (char *)data->buff, stream->wrNext - data->buff) < 0) {
1403 SetError(stream, OS_Errno);
1406 stream->wrNext = data->buff;
1409 * The buffer is empty.
1411 if(!data->rawWrite) {
1412 stream->wrNext += sizeof(FCGI_Header);
1417 * Return codes for Process* functions
1419 #define STREAM_RECORD 0
1421 #define BEGIN_RECORD 2
1422 #define MGMT_RECORD 3
1425 *----------------------------------------------------------------------
1427 * ProcessManagementRecord --
1429 * Reads and responds to a management record. The only type of
1430 * management record this library understands is FCGI_GET_VALUES.
1431 * The only variables that this library's FCGI_GET_VALUES
1432 * understands are FCGI_MAX_CONNS, FCGI_MAX_REQS, and FCGI_MPXS_CONNS.
1433 * Ignore other FCGI_GET_VALUES variables; respond to other
1434 * management records with a FCGI_UNKNOWN_TYPE record.
1436 *----------------------------------------------------------------------
1438 static int ProcessManagementRecord(int type, FCGX_Stream *stream)
1440 FCGX_Stream_Data *data = (FCGX_Stream_Data *)stream->data;
1441 ParamsPtr paramsPtr = NewParams(3);
1443 char response[64]; /* 64 = 8 + 3*(1+1+14+1)* + padding */
1444 char *responseP = &response[FCGI_HEADER_LEN];
1447 if(type == FCGI_GET_VALUES) {
1448 ReadParams(paramsPtr, stream);
1449 if((FCGX_GetError(stream) != 0) || (data->contentLen != 0)) {
1450 FreeParams(¶msPtr);
1451 return FCGX_PROTOCOL_ERROR;
1453 for (pPtr = paramsPtr->vec; pPtr < paramsPtr->cur; pPtr++) {
1455 *(strchr(name, '=')) = '\0';
1456 if(strcmp(name, FCGI_MAX_CONNS) == 0) {
1458 } else if(strcmp(name, FCGI_MAX_REQS) == 0) {
1460 } else if(strcmp(name, FCGI_MPXS_CONNS) == 0) {
1467 sprintf(responseP, "%c%c%s%c", len, 1, name, value);
1468 responseP += len + 3;
1471 len = responseP - &response[FCGI_HEADER_LEN];
1472 paddedLen = AlignInt8(len);
1473 *((FCGI_Header *) response)
1474 = MakeHeader(FCGI_GET_VALUES_RESULT, FCGI_NULL_REQUEST_ID,
1475 len, paddedLen - len);
1476 FreeParams(¶msPtr);
1478 paddedLen = len = sizeof(FCGI_UnknownTypeBody);
1479 ((FCGI_UnknownTypeRecord *) response)->header
1480 = MakeHeader(FCGI_UNKNOWN_TYPE, FCGI_NULL_REQUEST_ID,
1482 ((FCGI_UnknownTypeRecord *) response)->body
1483 = MakeUnknownTypeBody(type);
1485 if (write_it_all(data->reqDataPtr->ipcFd, response, FCGI_HEADER_LEN + paddedLen) < 0) {
1486 SetError(stream, OS_Errno);
1494 *----------------------------------------------------------------------
1496 * ProcessBeginRecord --
1498 * Reads an FCGI_BEGIN_REQUEST record.
1501 * BEGIN_RECORD for normal return. FCGX_PROTOCOL_ERROR for
1502 * protocol error. SKIP for attempt to multiplex
1503 * connection. -1 for error from write (errno in stream).
1506 * In case of BEGIN_RECORD return, stores requestId, role,
1507 * keepConnection values, and sets isBeginProcessed = TRUE.
1509 *----------------------------------------------------------------------
1511 static int ProcessBeginRecord(int requestId, FCGX_Stream *stream)
1513 FCGX_Stream_Data *data = (FCGX_Stream_Data *)stream->data;
1514 FCGI_BeginRequestBody body;
1515 if(requestId == 0 || data->contentLen != sizeof(body)) {
1516 return FCGX_PROTOCOL_ERROR;
1518 if(data->reqDataPtr->isBeginProcessed) {
1520 * The Web server is multiplexing the connection. This library
1521 * doesn't know how to handle multiplexing, so respond with
1522 * FCGI_END_REQUEST{protocolStatus = FCGI_CANT_MPX_CONN}
1524 FCGI_EndRequestRecord endRequestRecord;
1525 endRequestRecord.header = MakeHeader(FCGI_END_REQUEST,
1526 requestId, sizeof(endRequestRecord.body), 0);
1527 endRequestRecord.body
1528 = MakeEndRequestBody(0, FCGI_CANT_MPX_CONN);
1529 if (write_it_all(data->reqDataPtr->ipcFd, (char *)&endRequestRecord, sizeof(endRequestRecord)) < 0) {
1530 SetError(stream, OS_Errno);
1537 * Accept this new request. Read the record body.
1539 data->reqDataPtr->requestId = requestId;
1540 if(FCGX_GetStr((char *) &body, sizeof(body), stream)
1542 return FCGX_PROTOCOL_ERROR;
1544 data->reqDataPtr->keepConnection = (body.flags & FCGI_KEEP_CONN);
1545 data->reqDataPtr->role = (body.roleB1 << 8) + body.roleB0;
1546 data->reqDataPtr->isBeginProcessed = TRUE;
1547 return BEGIN_RECORD;
1551 *----------------------------------------------------------------------
1555 * Interprets FCGI_Header. Processes FCGI_BEGIN_REQUEST and
1556 * management records here; extracts information from stream
1557 * records (FCGI_PARAMS, FCGI_STDIN) into stream.
1560 * >= 0 for a normal return, < 0 for error
1563 * XXX: Many (more than there used to be).
1564 * If !stream->isRequestIdSet, ProcessHeader initializes
1565 * stream->requestId from header and sets stream->isRequestIdSet
1566 * to TRUE. ProcessHeader also sets stream->contentLen to header's
1567 * contentLength, and sets stream->paddingLen to the header's
1570 *----------------------------------------------------------------------
1572 static int ProcessHeader(FCGI_Header header, FCGX_Stream *stream)
1574 FCGX_Stream_Data *data = (FCGX_Stream_Data *)stream->data;
1576 if(header.version != FCGI_VERSION_1) {
1577 return FCGX_UNSUPPORTED_VERSION;
1579 requestId = (header.requestIdB1 << 8)
1580 + header.requestIdB0;
1581 data->contentLen = (header.contentLengthB1 << 8)
1582 + header.contentLengthB0;
1583 data->paddingLen = header.paddingLength;
1584 if(header.type == FCGI_BEGIN_REQUEST) {
1585 return ProcessBeginRecord(requestId, stream);
1587 if(requestId == FCGI_NULL_REQUEST_ID) {
1588 return ProcessManagementRecord(header.type, stream);
1590 if(requestId != data->reqDataPtr->requestId) {
1593 if(header.type != data->type) {
1594 return FCGX_PROTOCOL_ERROR;
1596 return STREAM_RECORD;
1600 *----------------------------------------------------------------------
1604 * Reads bytes from the ipcFd, supplies bytes to a stream client.
1606 *----------------------------------------------------------------------
1608 static void FillBuffProc(FCGX_Stream *stream)
1610 FCGX_Stream_Data *data = (FCGX_Stream_Data *)stream->data;
1617 * If data->buff is empty, do a read.
1619 if(stream->rdNext == data->buffStop) {
1620 count = OS_Read(data->reqDataPtr->ipcFd, (char *)data->buff,
1623 SetError(stream, (count == 0 ? FCGX_PROTOCOL_ERROR : OS_Errno));
1626 stream->rdNext = data->buff;
1627 data->buffStop = data->buff + count;
1630 * Now data->buff is not empty. If the current record contains
1631 * more content bytes, deliver all that are present in data->buff.
1633 if(data->contentLen > 0) {
1634 count = min(data->contentLen, data->buffStop - stream->rdNext);
1635 data->contentLen -= count;
1637 stream->wrNext = stream->stop = stream->rdNext + count;
1640 stream->rdNext += count;
1641 if(data->contentLen > 0) {
1649 * If the current record (whose content has been fully consumed by
1650 * the client) was padded, skip over the padding bytes.
1652 if(data->paddingLen > 0) {
1653 count = min(data->paddingLen, data->buffStop - stream->rdNext);
1654 data->paddingLen -= count;
1655 stream->rdNext += count;
1656 if(data->paddingLen > 0) {
1661 * All done with the current record, including the padding.
1662 * If we're in a recursive call from ProcessHeader, deliver EOF.
1665 stream->stop = stream->rdNext;
1666 stream->isClosed = TRUE;
1670 * Fill header with bytes from the input buffer.
1672 count = min((int)sizeof(header) - headerLen,
1673 data->buffStop - stream->rdNext);
1674 memcpy(((char *)(&header)) + headerLen, stream->rdNext, count);
1676 stream->rdNext += count;
1677 if(headerLen < sizeof(header)) {
1682 * Interpret header. eorStop prevents ProcessHeader from reading
1683 * past the end-of-record when using stream to read content.
1685 data->eorStop = TRUE;
1686 stream->stop = stream->rdNext;
1687 status = ProcessHeader(header, stream);
1688 data->eorStop = FALSE;
1689 stream->isClosed = FALSE;
1693 * If this stream record header marked the end of stream
1694 * data deliver EOF to the stream client, otherwise loop
1697 * XXX: If this is final stream and
1698 * stream->rdNext != data->buffStop, buffered
1699 * data is next request (server pipelining)?
1701 if(data->contentLen == 0) {
1702 stream->wrNext = stream->stop = stream->rdNext;
1703 stream->isClosed = TRUE;
1712 * If this header marked the beginning of a new
1713 * request, return role information to caller.
1721 SetError(stream, status);
1729 *----------------------------------------------------------------------
1733 * Creates a stream to read or write from an open ipcFd.
1734 * The stream performs reads/writes of up to bufflen bytes.
1736 *----------------------------------------------------------------------
1738 static FCGX_Stream *NewStream(
1739 FCGX_Request *reqDataPtr, int bufflen, int isReader, int streamType)
1742 * XXX: It would be a lot cleaner to have a NewStream that only
1743 * knows about the type FCGX_Stream, with all other
1744 * necessary data passed in. It appears that not just
1745 * data and the two procs are needed for initializing stream,
1746 * but also data->buff and data->buffStop. This has implications
1747 * for procs that want to swap buffers, too.
1749 FCGX_Stream *stream = (FCGX_Stream *)Malloc(sizeof(FCGX_Stream));
1750 FCGX_Stream_Data *data = (FCGX_Stream_Data *)Malloc(sizeof(FCGX_Stream_Data));
1751 data->reqDataPtr = reqDataPtr;
1752 bufflen = AlignInt8(min(max(bufflen, 32), FCGI_MAX_LENGTH + 1));
1753 data->bufflen = bufflen;
1754 data->mBuff = (unsigned char *)Malloc(bufflen);
1755 data->buff = AlignPtr8(data->mBuff);
1756 if(data->buff != data->mBuff) {
1760 data->buffStop = data->buff;
1762 data->buffStop = data->buff + data->bufflen;
1764 data->type = streamType;
1765 data->eorStop = FALSE;
1767 data->contentLen = 0;
1768 data->paddingLen = 0;
1769 data->isAnythingWritten = FALSE;
1770 data->rawWrite = FALSE;
1772 stream->data = data;
1773 stream->isReader = isReader;
1774 stream->isClosed = FALSE;
1775 stream->wasFCloseCalled = FALSE;
1776 stream->FCGI_errno = 0;
1778 stream->fillBuffProc = FillBuffProc;
1779 stream->emptyBuffProc = NULL;
1780 stream->rdNext = data->buff;
1781 stream->stop = stream->rdNext;
1782 stream->stopUnget = data->buff;
1783 stream->wrNext = stream->stop;
1785 stream->fillBuffProc = NULL;
1786 stream->emptyBuffProc = EmptyBuffProc;
1787 stream->wrNext = data->buff + sizeof(FCGI_Header);
1788 stream->stop = data->buffStop;
1789 stream->stopUnget = NULL;
1790 stream->rdNext = stream->stop;
1796 *----------------------------------------------------------------------
1800 * Frees all storage allocated when *streamPtr was created,
1801 * and nulls out *streamPtr.
1803 *----------------------------------------------------------------------
1805 void FreeStream(FCGX_Stream **streamPtr)
1807 FCGX_Stream *stream = *streamPtr;
1808 FCGX_Stream_Data *data;
1809 if(stream == NULL) {
1812 data = (FCGX_Stream_Data *)stream->data;
1813 data->reqDataPtr = NULL;
1821 *----------------------------------------------------------------------
1825 * Re-initializes the stream to read data of the specified type.
1827 *----------------------------------------------------------------------
1829 static FCGX_Stream *SetReaderType(FCGX_Stream *stream, int streamType)
1831 FCGX_Stream_Data *data = (FCGX_Stream_Data *)stream->data;
1832 ASSERT(stream->isReader);
1833 data->type = streamType;
1834 data->eorStop = FALSE;
1836 data->contentLen = 0;
1837 data->paddingLen = 0;
1838 stream->wrNext = stream->stop = stream->rdNext;
1839 stream->isClosed = FALSE;
1844 *----------------------------------------------------------------------
1848 * Creates a stream to read streamType records for the given
1849 * request. The stream performs OS reads of up to bufflen bytes.
1851 *----------------------------------------------------------------------
1853 static FCGX_Stream *NewReader(FCGX_Request *reqDataPtr, int bufflen, int streamType)
1855 return NewStream(reqDataPtr, bufflen, TRUE, streamType);
1860 *----------------------------------------------------------------------
1864 * Creates a stream to write streamType FastCGI records, using
1865 * the ipcFd and RequestId contained in *reqDataPtr.
1866 * The stream performs OS writes of up to bufflen bytes.
1868 *----------------------------------------------------------------------
1870 static FCGX_Stream *NewWriter(FCGX_Request *reqDataPtr, int bufflen, int streamType)
1872 return NewStream(reqDataPtr, bufflen, FALSE, streamType);
1877 *----------------------------------------------------------------------
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 *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)
1990 if (reqDataPtr == NULL) {
1994 /* This should probably use a 'status' member instead of 'in' */
1995 if (reqDataPtr->in) {
1996 int errStatus = FCGX_FClose(reqDataPtr->err);
1997 int outStatus = FCGX_FClose(reqDataPtr->out);
1999 if (errStatus || outStatus || FCGX_GetError(reqDataPtr->in))
2001 OS_IpcClose(reqDataPtr->ipcFd);
2002 reqDataPtr->ipcFd = -1;
2006 FCGX_Free(reqDataPtr);
2009 void FCGX_Free(FCGX_Request * request)
2011 if (request == NULL)
2014 FreeStream(&request->in);
2015 FreeStream(&request->out);
2016 FreeStream(&request->err);
2017 FreeParams(&request->paramsPtr);
2019 if (!request->keepConnection)
2021 OS_IpcClose(request->ipcFd);
2022 request->ipcFd = -1;
2026 int FCGX_OpenSocket(const char *path, int backlog)
2028 int rc = OS_CreateLocalIpcFd(path, backlog);
2029 if (rc == FCGI_LISTENSOCK_FILENO && isFastCGI == 0) {
2030 /* XXX probably need to call OS_LibInit() again for Win */
2036 int FCGX_InitRequest(FCGX_Request *request, int sock, int flags)
2038 memset(request, 0, sizeof(FCGX_Request));
2040 /* @@@ Should check that sock is open and listening */
2041 request->listen_sock = sock;
2043 /* @@@ Should validate against "known" flags */
2044 request->flags = flags;
2046 request->ipcFd = -1;
2052 *----------------------------------------------------------------------
2056 * Initilize the FCGX library. This is called by FCGX_Accept()
2057 * but must be called by the user when using FCGX_Accept_r().
2060 * 0 for successful call.
2062 *----------------------------------------------------------------------
2068 if (libInitialized) {
2072 /* If our compiler doesn't play by the ISO rules for struct layout, halt. */
2073 ASSERT(sizeof(FCGI_Header) == FCGI_HEADER_LEN);
2075 FCGX_InitRequest(&the_request, FCGI_LISTENSOCK_FILENO, 0);
2077 if (OS_LibInit(NULL) == -1) {
2078 return OS_Errno ? OS_Errno : -9997;
2081 p = getenv("FCGI_WEB_SERVER_ADDRS");
2082 webServerAddressList = p ? StringCopy(p) : NULL;
2089 *----------------------------------------------------------------------
2093 * Accepts a new request from the HTTP server.
2096 * 0 for successful call, -1 for error.
2100 * Finishes the request accepted by (and frees any
2101 * storage allocated by) the previous call to FCGX_Accept.
2102 * Creates input, output, and error streams and
2103 * assigns them to *in, *out, and *err respectively.
2104 * Creates a parameters data structure to be accessed
2105 * via getenv(3) (if assigned to environ) or by FCGX_GetParam
2106 * and assigns it to *envp.
2108 * DO NOT retain pointers to the envp array or any strings
2109 * contained in it (e.g. to the result of calling FCGX_GetParam),
2110 * since these will be freed by the next call to FCGX_Finish
2113 *----------------------------------------------------------------------
2120 FCGX_ParamArray *envp)
2124 if (!libInitialized) {
2125 if ((rc = FCGX_Init())) {
2126 return (rc < 0) ? rc : -rc;
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);
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;