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.21 2001/06/18 14:25:09 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)
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)
193 c = FCGX_GetChar(stream);
210 *----------------------------------------------------------------------
214 * Pushes back the character c onto the input stream. One
215 * character of pushback is guaranteed once a character
216 * has been read. No pushback is possible for EOF.
219 * Returns c if the pushback succeeded, EOF if not.
221 *----------------------------------------------------------------------
223 int FCGX_UnGetChar(int c, FCGX_Stream *stream) {
227 || stream->rdNext == stream->stopUnget)
235 *----------------------------------------------------------------------
239 * Returns EOF if end-of-file has been detected while reading
240 * from stream; otherwise returns 0.
242 * Note that FCGX_HasSeenEOF(s) may return 0, yet an immediately
243 * following FCGX_GetChar(s) may return EOF. This function, like
244 * the standard C stdio function feof, does not provide the
245 * ability to peek ahead.
248 * EOF if end-of-file has been detected, 0 if not.
250 *----------------------------------------------------------------------
252 int FCGX_HasSeenEOF(FCGX_Stream *stream) {
253 return (stream->isClosed) ? EOF : 0;
257 *----------------------------------------------------------------------
261 * Writes a byte to the output stream.
264 * The byte, or EOF (-1) if an error occurred.
266 *----------------------------------------------------------------------
268 int FCGX_PutChar(int c, FCGX_Stream *stream)
270 if(stream->wrNext != stream->stop)
271 return (*stream->wrNext++ = c);
272 if(stream->isClosed || stream->isReader)
274 stream->emptyBuffProc(stream, FALSE);
275 if(stream->wrNext != stream->stop)
276 return (*stream->wrNext++ = c);
277 ASSERT(stream->isClosed); /* bug in emptyBuffProc if not */
282 *----------------------------------------------------------------------
286 * Writes n consecutive bytes from the character array str
287 * into the output stream. Performs no interpretation
288 * of the output bytes.
291 * Number of bytes written (n) for normal return,
292 * EOF (-1) if an error occurred.
294 *----------------------------------------------------------------------
296 int FCGX_PutStr(const char *str, int n, FCGX_Stream *stream)
301 * Fast path: room for n bytes in the buffer
303 if(n <= (stream->stop - stream->wrNext)) {
304 memcpy(stream->wrNext, str, n);
309 * General case: stream is closed or buffer empty procedure
314 if(stream->wrNext != stream->stop) {
315 m = min(n - bytesMoved, stream->stop - stream->wrNext);
316 memcpy(stream->wrNext, str, m);
323 if(stream->isClosed || stream->isReader)
325 stream->emptyBuffProc(stream, FALSE);
330 *----------------------------------------------------------------------
334 * Writes a character string to the output stream.
337 * number of bytes written for normal return,
338 * EOF (-1) if an error occurred.
340 *----------------------------------------------------------------------
342 int FCGX_PutS(const char *str, FCGX_Stream *stream)
344 return FCGX_PutStr(str, strlen(str), stream);
348 *----------------------------------------------------------------------
352 * Performs output formatting and writes the results
353 * to the output stream.
356 * number of bytes written for normal return,
357 * EOF (-1) if an error occurred.
359 *----------------------------------------------------------------------
361 int FCGX_FPrintF(FCGX_Stream *stream, const char *format, ...)
365 va_start(ap, format);
366 result = FCGX_VFPrintF(stream, format, ap);
372 *----------------------------------------------------------------------
376 * Performs output formatting and writes the results
377 * to the output stream.
380 * number of bytes written for normal return,
381 * EOF (-1) if an error occurred.
383 *----------------------------------------------------------------------
386 #define PRINTF_BUFFLEN 100
388 * More than sufficient space for all unmodified conversions
391 #define FMT_BUFFLEN 25
393 * Max size of a format specifier is 1 + 5 + 7 + 7 + 2 + 1 + slop
395 static void CopyAndAdvance(char **destPtr, char **srcPtr, int n);
397 int FCGX_VFPrintF(FCGX_Stream *stream, const char *format, va_list arg)
399 char *f, *fStop, *percentPtr, *p, *fmtBuffPtr, *buffPtr;
400 int op, performedOp, sizeModifier, buffCount, buffLen, specifierLength;
401 int fastPath, n, auxBuffLen, buffReqd, minWidth, precision, exp;
402 char *auxBuffPtr = NULL;
404 char fmtBuff[FMT_BUFFLEN];
405 char buff[PRINTF_BUFFLEN];
410 unsigned unsignedArg;
411 unsigned long uLongArg;
412 unsigned short uShortArg;
419 LONG_DOUBLE lDoubleArg;
423 fStop = f + strlen(f);
425 percentPtr = (char *)memchr(f, '%', fStop - f);
426 if(percentPtr == NULL) percentPtr = fStop;
427 if(percentPtr != f) {
428 if(FCGX_PutStr(f, percentPtr - f, stream) < 0)
430 streamCount += percentPtr - f;
432 if(f == fStop) break;
436 * The following loop always executes either once or twice.
441 * Fast path: Scan optimistically, hoping that no flags,
442 * minimum field width, or precision are specified.
443 * Use the preallocated buffer, which is large enough
444 * for all fast path cases. If the conversion specifier
445 * is really more complex, run the loop a second time
446 * using the slow path.
447 * Note that fast path execution of %s bypasses the buffer
448 * and %f is not attempted on the fast path due to
449 * its large buffering requirements.
451 op = *(percentPtr + 1);
457 op = *(percentPtr + 2);
458 fmtBuff[1] = sizeModifier;
471 buffLen = PRINTF_BUFFLEN;
474 * Slow path: Scan the conversion specifier and construct
475 * a new format string, compute an upper bound on the
476 * amount of buffering that sprintf will require,
477 * and allocate a larger buffer if necessary.
480 fmtBuffPtr = &fmtBuff[1];
484 n = strspn(p, "-0+ #");
487 CopyAndAdvance(&fmtBuffPtr, &p, n);
489 * Scan minimum field width
491 n = strspn(p, "0123456789");
494 minWidth = va_arg(arg, int);
495 if(abs(minWidth) > 999999)
498 * The following use of strlen rather than the
499 * value returned from sprintf is because SUNOS4
500 * returns a char * instead of an int count.
502 sprintf(fmtBuffPtr, "%d", minWidth);
503 fmtBuffPtr += strlen(fmtBuffPtr);
509 minWidth = strtol(p, NULL, 10);
510 CopyAndAdvance(&fmtBuffPtr, &p, n);
518 CopyAndAdvance(&fmtBuffPtr, &p, 1);
519 n = strspn(p, "0123456789");
522 precision = va_arg(arg, int);
523 if(precision < 0) precision = 0;
524 if(precision > 999999)
527 * The following use of strlen rather than the
528 * value returned from sprintf is because SUNOS4
529 * returns a char * instead of an int count.
531 sprintf(fmtBuffPtr, "%d", precision);
532 fmtBuffPtr += strlen(fmtBuffPtr);
538 precision = strtol(p, NULL, 10);
539 CopyAndAdvance(&fmtBuffPtr, &p, n);
547 * Scan size modifier and conversion operation
554 CopyAndAdvance(&fmtBuffPtr, &p, 1);
561 CopyAndAdvance(&fmtBuffPtr, &p, 1);
562 ASSERT(fmtBuffPtr - fmtBuff < FMT_BUFFLEN);
564 specifierLength = p - percentPtr;
566 * Bound the required buffer size. For s and f
567 * conversions this requires examining the argument.
578 buffReqd = max(precision, 46);
581 charPtrArg = va_arg(arg, char *);
582 if (!charPtrArg) charPtrArg = "(null)";
583 if(precision == -1) {
584 buffReqd = strlen(charPtrArg);
586 p = (char *)memchr(charPtrArg, '\0', precision);
588 (p == NULL) ? precision : p - charPtrArg;
592 switch(sizeModifier) {
594 doubleArg = va_arg(arg, double);
595 frexp(doubleArg, &exp);
598 lDoubleArg = va_arg(arg, LONG_DOUBLE);
599 frexp(lDoubleArg, &exp);
604 if(precision == -1) precision = 6;
605 buffReqd = precision + 3 + ((exp > 0) ? exp/3 : 0);
611 if(precision == -1) precision = 6;
612 buffReqd = precision + 8;
620 buffReqd = max(buffReqd + 10, minWidth);
622 * Allocate the buffer
624 if(buffReqd <= PRINTF_BUFFLEN) {
626 buffLen = PRINTF_BUFFLEN;
628 if(auxBuffPtr == NULL || buffReqd > auxBuffLen) {
629 if(auxBuffPtr != NULL) free(auxBuffPtr);
630 auxBuffPtr = (char *)Malloc(buffReqd);
631 auxBuffLen = buffReqd;
632 if(auxBuffPtr == NULL)
635 buffPtr = auxBuffPtr;
636 buffLen = auxBuffLen;
640 * This giant switch statement requires the following variables
641 * to be set up: op, sizeModifier, arg, buffPtr, fmtBuff.
642 * When fastPath == FALSE and op == 's' or 'f', the argument
643 * has been read into charPtrArg, doubleArg, or lDoubleArg.
644 * The statement produces the boolean performedOp, TRUE iff
645 * the op/sizeModifier were executed and argument consumed;
646 * if performedOp, the characters written into buffPtr[]
647 * and the character count buffCount (== EOF meaning error).
649 * The switch cases are arranged in the same order as in the
650 * description of fprintf in section 15.11 of Harbison and Steele.
656 switch(sizeModifier) {
658 intArg = va_arg(arg, int);
659 sprintf(buffPtr, fmtBuff, intArg);
660 buffCount = strlen(buffPtr);
663 longArg = va_arg(arg, long);
664 sprintf(buffPtr, fmtBuff, longArg);
665 buffCount = strlen(buffPtr);
668 shortArg = (short) va_arg(arg, int);
669 sprintf(buffPtr, fmtBuff, shortArg);
670 buffCount = strlen(buffPtr);
680 switch(sizeModifier) {
682 unsignedArg = va_arg(arg, unsigned);
683 sprintf(buffPtr, fmtBuff, unsignedArg);
684 buffCount = strlen(buffPtr);
687 uLongArg = va_arg(arg, unsigned long);
688 sprintf(buffPtr, fmtBuff, uLongArg);
689 buffCount = strlen(buffPtr);
692 uShortArg = (unsigned short) va_arg(arg, int);
693 sprintf(buffPtr, fmtBuff, uShortArg);
694 buffCount = strlen(buffPtr);
701 switch(sizeModifier) {
703 intArg = va_arg(arg, int);
704 sprintf(buffPtr, fmtBuff, intArg);
705 buffCount = strlen(buffPtr);
709 * XXX: Allowed by ISO C Amendment 1, but
710 * many platforms don't yet support wint_t
718 switch(sizeModifier) {
721 buffPtr = va_arg(arg, char *);
722 buffCount = strlen(buffPtr);
723 buffLen = buffCount + 1;
725 sprintf(buffPtr, fmtBuff, charPtrArg);
726 buffCount = strlen(buffPtr);
731 * XXX: Don't know how to convert a sequence
732 * of wide characters into a byte stream, or
733 * even how to predict the buffering required.
741 if(sizeModifier != ' ')
743 voidPtrArg = va_arg(arg, void *);
744 sprintf(buffPtr, fmtBuff, voidPtrArg);
745 buffCount = strlen(buffPtr);
748 switch(sizeModifier) {
750 intPtrArg = va_arg(arg, int *);
751 *intPtrArg = streamCount;
754 longPtrArg = va_arg(arg, long *);
755 *longPtrArg = streamCount;
758 shortPtrArg = va_arg(arg, short *);
759 *shortPtrArg = streamCount;
771 switch(sizeModifier) {
773 sprintf(buffPtr, fmtBuff, doubleArg);
774 buffCount = strlen(buffPtr);
777 sprintf(buffPtr, fmtBuff, lDoubleArg);
778 buffCount = strlen(buffPtr);
788 switch(sizeModifier) {
790 doubleArg = va_arg(arg, double);
791 sprintf(buffPtr, fmtBuff, doubleArg);
792 buffCount = strlen(buffPtr);
795 lDoubleArg = va_arg(arg, LONG_DOUBLE);
796 sprintf(buffPtr, fmtBuff, lDoubleArg);
797 buffCount = strlen(buffPtr);
804 if(sizeModifier != ' ')
815 if(performedOp) break;
820 ASSERT(buffCount < buffLen);
822 if(FCGX_PutStr(buffPtr, buffCount, stream) < 0)
824 streamCount += buffCount;
825 } else if(buffCount < 0) {
828 f += specifierLength;
829 } /* while(f != fStop) */
834 if(auxBuffPtr != NULL) free(auxBuffPtr);
839 * Copy n characters from *srcPtr to *destPtr, then increment
840 * both *srcPtr and *destPtr by n.
842 static void CopyAndAdvance(char **destPtr, char **srcPtr, int n)
844 char *dest = *destPtr;
847 for (i = 0; i < n; i++)
854 *----------------------------------------------------------------------
858 * Flushes any buffered output.
860 * Server-push is a legitimate application of FCGX_FFlush.
861 * Otherwise, FCGX_FFlush is not very useful, since FCGX_Accept
862 * does it implicitly. FCGX_FFlush may reduce performance
863 * by increasing the total number of operating system calls
864 * the application makes.
867 * EOF (-1) if an error occurred.
869 *----------------------------------------------------------------------
871 int FCGX_FFlush(FCGX_Stream *stream)
873 if(stream->isClosed || stream->isReader)
875 stream->emptyBuffProc(stream, FALSE);
876 return (stream->isClosed) ? -1 : 0;
880 *----------------------------------------------------------------------
884 * Performs FCGX_FFlush and closes the stream.
886 * This is not a very useful operation, since FCGX_Accept
887 * does it implicitly. Closing the out stream before the
888 * err stream results in an extra write if there's nothing
889 * in the err stream, and therefore reduces performance.
892 * EOF (-1) if an error occurred.
894 *----------------------------------------------------------------------
896 int FCGX_FClose(FCGX_Stream *stream)
898 if (stream == NULL) return 0;
900 if(!stream->wasFCloseCalled) {
901 if(!stream->isReader) {
902 stream->emptyBuffProc(stream, TRUE);
904 stream->wasFCloseCalled = TRUE;
905 stream->isClosed = TRUE;
906 if(stream->isReader) {
907 stream->wrNext = stream->stop = stream->rdNext;
909 stream->rdNext = stream->stop = stream->wrNext;
912 return (stream->FCGI_errno == 0) ? 0 : EOF;
916 *----------------------------------------------------------------------
920 * An error has occurred; save the error code in the stream
921 * for diagnostic purposes and set the stream state so that
922 * reads return EOF and writes have no effect.
924 *----------------------------------------------------------------------
926 static void SetError(FCGX_Stream *stream, int FCGI_errno)
929 * Preserve only the first error.
931 if(stream->FCGI_errno == 0) {
932 stream->FCGI_errno = FCGI_errno;
933 stream->isClosed = TRUE;
938 *----------------------------------------------------------------------
942 * Return the stream error code. 0 means no error, > 0
943 * is an errno(2) error, < 0 is an FCGX_errno error.
945 *----------------------------------------------------------------------
947 int FCGX_GetError(FCGX_Stream *stream) {
948 return stream->FCGI_errno;
952 *----------------------------------------------------------------------
956 * Clear the stream error code and end-of-file indication.
958 *----------------------------------------------------------------------
960 void FCGX_ClearError(FCGX_Stream *stream) {
961 stream->FCGI_errno = 0;
963 * stream->isClosed = FALSE;
964 * XXX: should clear isClosed but work is needed to make it safe
965 * to do so. For example, if an application calls FClose, gets
966 * an I/O error on the write, calls ClearError and retries
967 * the FClose, FClose (really EmptyBuffProc) will write a second
968 * EOF record. If an application calls PutChar instead of FClose
969 * after the ClearError, the application will write more data.
970 * The stream's state must discriminate between various states
971 * of the stream that are now all lumped under isClosed.
976 *======================================================================
978 *======================================================================
982 * A vector of pointers representing the parameters received
983 * by a FastCGI application server, with the vector's length
984 * and last valid element so adding new parameters is efficient.
987 typedef struct Params {
988 FCGX_ParamArray vec; /* vector of strings */
989 int length; /* number of string vec can hold */
990 char **cur; /* current item in vec; *cur == NULL */
992 typedef Params *ParamsPtr;
995 *----------------------------------------------------------------------
999 * Creates a new Params structure.
1002 * Pointer to the new structure.
1004 *----------------------------------------------------------------------
1006 static ParamsPtr NewParams(int length)
1009 result = (Params *)Malloc(sizeof(Params));
1010 result->vec = (char **)Malloc(length * sizeof(char *));
1011 result->length = length;
1012 result->cur = result->vec;
1013 *result->cur = NULL;
1018 *----------------------------------------------------------------------
1022 * Frees a Params structure and all the parameters it contains.
1025 * env becomes invalid.
1027 *----------------------------------------------------------------------
1029 static void FreeParams(ParamsPtr *paramsPtrPtr)
1031 ParamsPtr paramsPtr = *paramsPtrPtr;
1033 if(paramsPtr == NULL) {
1036 for (p = paramsPtr->vec; p < paramsPtr->cur; p++) {
1039 free(paramsPtr->vec);
1041 *paramsPtrPtr = NULL;
1045 *----------------------------------------------------------------------
1049 * Add a name/value pair to a Params structure.
1055 * Parameters structure updated.
1057 *----------------------------------------------------------------------
1059 static void PutParam(ParamsPtr paramsPtr, char *nameValue)
1063 *paramsPtr->cur++ = nameValue;
1064 size = paramsPtr->cur - paramsPtr->vec;
1065 if(size >= paramsPtr->length) {
1066 paramsPtr->length *= 2;
1067 paramsPtr->vec = (FCGX_ParamArray)realloc(paramsPtr->vec, paramsPtr->length * sizeof(char *));
1068 paramsPtr->cur = paramsPtr->vec + size;
1070 *paramsPtr->cur = NULL;
1074 *----------------------------------------------------------------------
1076 * FCGX_GetParam -- obtain value of FCGI parameter in environment
1080 * Value bound to name, NULL if name not present in the
1081 * environment envp. Caller must not mutate the result
1082 * or retain it past the end of this request.
1084 *----------------------------------------------------------------------
1086 char *FCGX_GetParam(const char *name, FCGX_ParamArray envp)
1091 if (name == NULL || envp == NULL) return NULL;
1095 for (p = envp; *p; ++p) {
1096 if((strncmp(name, *p, len) == 0) && ((*p)[len] == '=')) {
1104 *----------------------------------------------------------------------
1106 * Start of FastCGI-specific code
1108 *----------------------------------------------------------------------
1112 *----------------------------------------------------------------------
1116 * Reads FastCGI name-value pairs from stream until EOF. Converts
1117 * each pair to name=value format and adds it to Params structure.
1119 *----------------------------------------------------------------------
1121 static int ReadParams(Params *paramsPtr, FCGX_Stream *stream)
1123 int nameLen, valueLen;
1124 unsigned char lenBuff[3];
1127 while((nameLen = FCGX_GetChar(stream)) != EOF) {
1129 * Read name length (one or four bytes) and value length
1130 * (one or four bytes) from stream.
1132 if((nameLen & 0x80) != 0) {
1133 if(FCGX_GetStr((char *) &lenBuff[0], 3, stream) != 3) {
1134 SetError(stream, FCGX_PARAMS_ERROR);
1137 nameLen = ((nameLen & 0x7f) << 24) + (lenBuff[0] << 16)
1138 + (lenBuff[1] << 8) + lenBuff[2];
1140 if((valueLen = FCGX_GetChar(stream)) == EOF) {
1141 SetError(stream, FCGX_PARAMS_ERROR);
1144 if((valueLen & 0x80) != 0) {
1145 if(FCGX_GetStr((char *) &lenBuff[0], 3, stream) != 3) {
1146 SetError(stream, FCGX_PARAMS_ERROR);
1149 valueLen = ((valueLen & 0x7f) << 24) + (lenBuff[0] << 16)
1150 + (lenBuff[1] << 8) + lenBuff[2];
1153 * nameLen and valueLen are now valid; read the name and value
1154 * from stream and construct a standard environment entry.
1156 nameValue = (char *)Malloc(nameLen + valueLen + 2);
1157 if(FCGX_GetStr(nameValue, nameLen, stream) != nameLen) {
1158 SetError(stream, FCGX_PARAMS_ERROR);
1162 *(nameValue + nameLen) = '=';
1163 if(FCGX_GetStr(nameValue + nameLen + 1, valueLen, stream)
1165 SetError(stream, FCGX_PARAMS_ERROR);
1169 *(nameValue + nameLen + valueLen + 1) = '\0';
1170 PutParam(paramsPtr, nameValue);
1176 *----------------------------------------------------------------------
1180 * Constructs an FCGI_Header struct.
1182 *----------------------------------------------------------------------
1184 static FCGI_Header MakeHeader(
1191 ASSERT(contentLength >= 0 && contentLength <= FCGI_MAX_LENGTH);
1192 ASSERT(paddingLength >= 0 && paddingLength <= 0xff);
1193 header.version = FCGI_VERSION_1;
1195 header.requestIdB1 = (requestId >> 8) & 0xff;
1196 header.requestIdB0 = (requestId ) & 0xff;
1197 header.contentLengthB1 = (contentLength >> 8) & 0xff;
1198 header.contentLengthB0 = (contentLength ) & 0xff;
1199 header.paddingLength = paddingLength;
1200 header.reserved = 0;
1205 *----------------------------------------------------------------------
1207 * MakeEndRequestBody --
1209 * Constructs an FCGI_EndRequestBody struct.
1211 *----------------------------------------------------------------------
1213 static FCGI_EndRequestBody MakeEndRequestBody(
1217 FCGI_EndRequestBody body;
1218 body.appStatusB3 = (appStatus >> 24) & 0xff;
1219 body.appStatusB2 = (appStatus >> 16) & 0xff;
1220 body.appStatusB1 = (appStatus >> 8) & 0xff;
1221 body.appStatusB0 = (appStatus ) & 0xff;
1222 body.protocolStatus = protocolStatus;
1223 memset(body.reserved, 0, sizeof(body.reserved));
1228 *----------------------------------------------------------------------
1230 * MakeUnknownTypeBody --
1232 * Constructs an FCGI_MakeUnknownTypeBody struct.
1234 *----------------------------------------------------------------------
1236 static FCGI_UnknownTypeBody MakeUnknownTypeBody(
1239 FCGI_UnknownTypeBody body;
1241 memset(body.reserved, 0, sizeof(body.reserved));
1246 *----------------------------------------------------------------------
1250 * Returns the smallest integer greater than or equal to n
1251 * that's a multiple of 8.
1253 *----------------------------------------------------------------------
1255 static int AlignInt8(unsigned n) {
1256 return (n + 7) & (UINT_MAX - 7);
1260 *----------------------------------------------------------------------
1264 * Returns the smallest pointer greater than or equal to p
1265 * that's a multiple of 8.
1267 *----------------------------------------------------------------------
1269 static unsigned char *AlignPtr8(unsigned char *p) {
1270 unsigned long u = (unsigned long) p;
1271 u = ((u + 7) & (ULONG_MAX - 7)) - u;
1277 * State associated with a stream
1279 typedef struct FCGX_Stream_Data {
1280 unsigned char *buff; /* buffer after alignment */
1281 int bufflen; /* number of bytes buff can store */
1282 unsigned char *mBuff; /* buffer as returned by Malloc */
1283 unsigned char *buffStop; /* reader: last valid byte + 1 of entire buffer.
1284 * stop generally differs from buffStop for
1285 * readers because of record structure.
1286 * writer: buff + bufflen */
1287 int type; /* reader: FCGI_PARAMS or FCGI_STDIN
1288 * writer: FCGI_STDOUT or FCGI_STDERR */
1289 int eorStop; /* reader: stop stream at end-of-record */
1290 int skip; /* reader: don't deliver content bytes */
1291 int contentLen; /* reader: bytes of unread content */
1292 int paddingLen; /* reader: bytes of unread padding */
1293 int isAnythingWritten; /* writer: data has been written to ipcFd */
1294 int rawWrite; /* writer: write data without stream headers */
1295 FCGX_Request *reqDataPtr; /* request data not specific to one stream */
1299 *----------------------------------------------------------------------
1301 * WriteCloseRecords --
1303 * Writes an EOF record for the stream content if necessary.
1304 * If this is the last writer to close, writes an FCGI_END_REQUEST
1307 *----------------------------------------------------------------------
1309 static void WriteCloseRecords(struct FCGX_Stream *stream)
1311 FCGX_Stream_Data *data = (FCGX_Stream_Data *)stream->data;
1313 * Enter rawWrite mode so final records won't be encapsulated as
1316 data->rawWrite = TRUE;
1318 * Generate EOF for stream content if needed.
1320 if(!(data->type == FCGI_STDERR
1321 && stream->wrNext == data->buff
1322 && !data->isAnythingWritten)) {
1324 header = MakeHeader(data->type, data->reqDataPtr->requestId, 0, 0);
1325 FCGX_PutStr((char *) &header, sizeof(header), stream);
1328 * Generate FCGI_END_REQUEST record if needed.
1330 if(data->reqDataPtr->nWriters == 1) {
1331 FCGI_EndRequestRecord endRequestRecord;
1332 endRequestRecord.header = MakeHeader(FCGI_END_REQUEST,
1333 data->reqDataPtr->requestId,
1334 sizeof(endRequestRecord.body), 0);
1335 endRequestRecord.body = MakeEndRequestBody(
1336 data->reqDataPtr->appStatus, FCGI_REQUEST_COMPLETE);
1337 FCGX_PutStr((char *) &endRequestRecord,
1338 sizeof(endRequestRecord), stream);
1340 data->reqDataPtr->nWriters--;
1345 static int write_it_all(int fd, char *buf, int len)
1350 wrote = OS_Write(fd, buf, len);
1360 *----------------------------------------------------------------------
1364 * Encapsulates any buffered stream content in a FastCGI
1365 * record. Writes the data, making the buffer empty.
1367 *----------------------------------------------------------------------
1369 static void EmptyBuffProc(struct FCGX_Stream *stream, int doClose)
1371 FCGX_Stream_Data *data = (FCGX_Stream_Data *)stream->data;
1374 * If the buffer contains stream data, fill in the header.
1375 * Pad the record to a multiple of 8 bytes in length. Padding
1376 * can't overflow the buffer because the buffer is a multiple
1377 * of 8 bytes in length. If the buffer contains no stream
1378 * data, reclaim the space reserved for the header.
1380 if(!data->rawWrite) {
1381 cLen = stream->wrNext - data->buff - sizeof(FCGI_Header);
1383 eLen = AlignInt8(cLen);
1385 * Giving the padding a well-defined value keeps Purify happy.
1387 memset(stream->wrNext, 0, eLen - cLen);
1388 stream->wrNext += eLen - cLen;
1389 *((FCGI_Header *) data->buff)
1390 = MakeHeader(data->type,
1391 data->reqDataPtr->requestId, cLen, eLen - cLen);
1393 stream->wrNext = data->buff;
1397 WriteCloseRecords(stream);
1399 if (stream->wrNext != data->buff) {
1400 data->isAnythingWritten = TRUE;
1401 if (write_it_all(data->reqDataPtr->ipcFd, (char *)data->buff, stream->wrNext - data->buff) < 0) {
1402 SetError(stream, OS_Errno);
1405 stream->wrNext = data->buff;
1408 * The buffer is empty.
1410 if(!data->rawWrite) {
1411 stream->wrNext += sizeof(FCGI_Header);
1416 * Return codes for Process* functions
1418 #define STREAM_RECORD 0
1420 #define BEGIN_RECORD 2
1421 #define MGMT_RECORD 3
1424 *----------------------------------------------------------------------
1426 * ProcessManagementRecord --
1428 * Reads and responds to a management record. The only type of
1429 * management record this library understands is FCGI_GET_VALUES.
1430 * The only variables that this library's FCGI_GET_VALUES
1431 * understands are FCGI_MAX_CONNS, FCGI_MAX_REQS, and FCGI_MPXS_CONNS.
1432 * Ignore other FCGI_GET_VALUES variables; respond to other
1433 * management records with a FCGI_UNKNOWN_TYPE record.
1435 *----------------------------------------------------------------------
1437 static int ProcessManagementRecord(int type, FCGX_Stream *stream)
1439 FCGX_Stream_Data *data = (FCGX_Stream_Data *)stream->data;
1440 ParamsPtr paramsPtr = NewParams(3);
1442 char response[64]; /* 64 = 8 + 3*(1+1+14+1)* + padding */
1443 char *responseP = &response[FCGI_HEADER_LEN];
1446 if(type == FCGI_GET_VALUES) {
1447 ReadParams(paramsPtr, stream);
1448 if((FCGX_GetError(stream) != 0) || (data->contentLen != 0)) {
1449 FreeParams(¶msPtr);
1450 return FCGX_PROTOCOL_ERROR;
1452 for (pPtr = paramsPtr->vec; pPtr < paramsPtr->cur; pPtr++) {
1454 *(strchr(name, '=')) = '\0';
1455 if(strcmp(name, FCGI_MAX_CONNS) == 0) {
1457 } else if(strcmp(name, FCGI_MAX_REQS) == 0) {
1459 } else if(strcmp(name, FCGI_MPXS_CONNS) == 0) {
1466 sprintf(responseP, "%c%c%s%c", len, 1, name, value);
1467 responseP += len + 3;
1470 len = responseP - &response[FCGI_HEADER_LEN];
1471 paddedLen = AlignInt8(len);
1472 *((FCGI_Header *) response)
1473 = MakeHeader(FCGI_GET_VALUES_RESULT, FCGI_NULL_REQUEST_ID,
1474 len, paddedLen - len);
1475 FreeParams(¶msPtr);
1477 paddedLen = len = sizeof(FCGI_UnknownTypeBody);
1478 ((FCGI_UnknownTypeRecord *) response)->header
1479 = MakeHeader(FCGI_UNKNOWN_TYPE, FCGI_NULL_REQUEST_ID,
1481 ((FCGI_UnknownTypeRecord *) response)->body
1482 = MakeUnknownTypeBody(type);
1484 if (write_it_all(data->reqDataPtr->ipcFd, response, FCGI_HEADER_LEN + paddedLen) < 0) {
1485 SetError(stream, OS_Errno);
1493 *----------------------------------------------------------------------
1495 * ProcessBeginRecord --
1497 * Reads an FCGI_BEGIN_REQUEST record.
1500 * BEGIN_RECORD for normal return. FCGX_PROTOCOL_ERROR for
1501 * protocol error. SKIP for attempt to multiplex
1502 * connection. -1 for error from write (errno in stream).
1505 * In case of BEGIN_RECORD return, stores requestId, role,
1506 * keepConnection values, and sets isBeginProcessed = TRUE.
1508 *----------------------------------------------------------------------
1510 static int ProcessBeginRecord(int requestId, FCGX_Stream *stream)
1512 FCGX_Stream_Data *data = (FCGX_Stream_Data *)stream->data;
1513 FCGI_BeginRequestBody body;
1514 if(requestId == 0 || data->contentLen != sizeof(body)) {
1515 return FCGX_PROTOCOL_ERROR;
1517 if(data->reqDataPtr->isBeginProcessed) {
1519 * The Web server is multiplexing the connection. This library
1520 * doesn't know how to handle multiplexing, so respond with
1521 * FCGI_END_REQUEST{protocolStatus = FCGI_CANT_MPX_CONN}
1523 FCGI_EndRequestRecord endRequestRecord;
1524 endRequestRecord.header = MakeHeader(FCGI_END_REQUEST,
1525 requestId, sizeof(endRequestRecord.body), 0);
1526 endRequestRecord.body
1527 = MakeEndRequestBody(0, FCGI_CANT_MPX_CONN);
1528 if (write_it_all(data->reqDataPtr->ipcFd, (char *)&endRequestRecord, sizeof(endRequestRecord)) < 0) {
1529 SetError(stream, OS_Errno);
1536 * Accept this new request. Read the record body.
1538 data->reqDataPtr->requestId = requestId;
1539 if(FCGX_GetStr((char *) &body, sizeof(body), stream)
1541 return FCGX_PROTOCOL_ERROR;
1543 data->reqDataPtr->keepConnection = (body.flags & FCGI_KEEP_CONN);
1544 data->reqDataPtr->role = (body.roleB1 << 8) + body.roleB0;
1545 data->reqDataPtr->isBeginProcessed = TRUE;
1546 return BEGIN_RECORD;
1550 *----------------------------------------------------------------------
1554 * Interprets FCGI_Header. Processes FCGI_BEGIN_REQUEST and
1555 * management records here; extracts information from stream
1556 * records (FCGI_PARAMS, FCGI_STDIN) into stream.
1559 * >= 0 for a normal return, < 0 for error
1562 * XXX: Many (more than there used to be).
1563 * If !stream->isRequestIdSet, ProcessHeader initializes
1564 * stream->requestId from header and sets stream->isRequestIdSet
1565 * to TRUE. ProcessHeader also sets stream->contentLen to header's
1566 * contentLength, and sets stream->paddingLen to the header's
1569 *----------------------------------------------------------------------
1571 static int ProcessHeader(FCGI_Header header, FCGX_Stream *stream)
1573 FCGX_Stream_Data *data = (FCGX_Stream_Data *)stream->data;
1575 if(header.version != FCGI_VERSION_1) {
1576 return FCGX_UNSUPPORTED_VERSION;
1578 requestId = (header.requestIdB1 << 8)
1579 + header.requestIdB0;
1580 data->contentLen = (header.contentLengthB1 << 8)
1581 + header.contentLengthB0;
1582 data->paddingLen = header.paddingLength;
1583 if(header.type == FCGI_BEGIN_REQUEST) {
1584 return ProcessBeginRecord(requestId, stream);
1586 if(requestId == FCGI_NULL_REQUEST_ID) {
1587 return ProcessManagementRecord(header.type, stream);
1589 if(requestId != data->reqDataPtr->requestId) {
1592 if(header.type != data->type) {
1593 return FCGX_PROTOCOL_ERROR;
1595 return STREAM_RECORD;
1599 *----------------------------------------------------------------------
1603 * Reads bytes from the ipcFd, supplies bytes to a stream client.
1605 *----------------------------------------------------------------------
1607 static void FillBuffProc(FCGX_Stream *stream)
1609 FCGX_Stream_Data *data = (FCGX_Stream_Data *)stream->data;
1616 * If data->buff is empty, do a read.
1618 if(stream->rdNext == data->buffStop) {
1619 count = OS_Read(data->reqDataPtr->ipcFd, (char *)data->buff,
1622 SetError(stream, (count == 0 ? FCGX_PROTOCOL_ERROR : OS_Errno));
1625 stream->rdNext = data->buff;
1626 data->buffStop = data->buff + count;
1629 * Now data->buff is not empty. If the current record contains
1630 * more content bytes, deliver all that are present in data->buff.
1632 if(data->contentLen > 0) {
1633 count = min(data->contentLen, data->buffStop - stream->rdNext);
1634 data->contentLen -= count;
1636 stream->wrNext = stream->stop = stream->rdNext + count;
1639 stream->rdNext += count;
1640 if(data->contentLen > 0) {
1648 * If the current record (whose content has been fully consumed by
1649 * the client) was padded, skip over the padding bytes.
1651 if(data->paddingLen > 0) {
1652 count = min(data->paddingLen, data->buffStop - stream->rdNext);
1653 data->paddingLen -= count;
1654 stream->rdNext += count;
1655 if(data->paddingLen > 0) {
1660 * All done with the current record, including the padding.
1661 * If we're in a recursive call from ProcessHeader, deliver EOF.
1664 stream->stop = stream->rdNext;
1665 stream->isClosed = TRUE;
1669 * Fill header with bytes from the input buffer.
1671 count = min((int)sizeof(header) - headerLen,
1672 data->buffStop - stream->rdNext);
1673 memcpy(((char *)(&header)) + headerLen, stream->rdNext, count);
1675 stream->rdNext += count;
1676 if(headerLen < sizeof(header)) {
1681 * Interpret header. eorStop prevents ProcessHeader from reading
1682 * past the end-of-record when using stream to read content.
1684 data->eorStop = TRUE;
1685 stream->stop = stream->rdNext;
1686 status = ProcessHeader(header, stream);
1687 data->eorStop = FALSE;
1688 stream->isClosed = FALSE;
1692 * If this stream record header marked the end of stream
1693 * data deliver EOF to the stream client, otherwise loop
1696 * XXX: If this is final stream and
1697 * stream->rdNext != data->buffStop, buffered
1698 * data is next request (server pipelining)?
1700 if(data->contentLen == 0) {
1701 stream->wrNext = stream->stop = stream->rdNext;
1702 stream->isClosed = TRUE;
1711 * If this header marked the beginning of a new
1712 * request, return role information to caller.
1720 SetError(stream, status);
1728 *----------------------------------------------------------------------
1732 * Creates a stream to read or write from an open ipcFd.
1733 * The stream performs reads/writes of up to bufflen bytes.
1735 *----------------------------------------------------------------------
1737 static FCGX_Stream *NewStream(
1738 FCGX_Request *reqDataPtr, int bufflen, int isReader, int streamType)
1741 * XXX: It would be a lot cleaner to have a NewStream that only
1742 * knows about the type FCGX_Stream, with all other
1743 * necessary data passed in. It appears that not just
1744 * data and the two procs are needed for initializing stream,
1745 * but also data->buff and data->buffStop. This has implications
1746 * for procs that want to swap buffers, too.
1748 FCGX_Stream *stream = (FCGX_Stream *)Malloc(sizeof(FCGX_Stream));
1749 FCGX_Stream_Data *data = (FCGX_Stream_Data *)Malloc(sizeof(FCGX_Stream_Data));
1750 data->reqDataPtr = reqDataPtr;
1751 bufflen = AlignInt8(min(max(bufflen, 32), FCGI_MAX_LENGTH + 1));
1752 data->bufflen = bufflen;
1753 data->mBuff = (unsigned char *)Malloc(bufflen);
1754 data->buff = AlignPtr8(data->mBuff);
1755 if(data->buff != data->mBuff) {
1759 data->buffStop = data->buff;
1761 data->buffStop = data->buff + data->bufflen;
1763 data->type = streamType;
1764 data->eorStop = FALSE;
1766 data->contentLen = 0;
1767 data->paddingLen = 0;
1768 data->isAnythingWritten = FALSE;
1769 data->rawWrite = FALSE;
1771 stream->data = data;
1772 stream->isReader = isReader;
1773 stream->isClosed = FALSE;
1774 stream->wasFCloseCalled = FALSE;
1775 stream->FCGI_errno = 0;
1777 stream->fillBuffProc = FillBuffProc;
1778 stream->emptyBuffProc = NULL;
1779 stream->rdNext = data->buff;
1780 stream->stop = stream->rdNext;
1781 stream->stopUnget = data->buff;
1782 stream->wrNext = stream->stop;
1784 stream->fillBuffProc = NULL;
1785 stream->emptyBuffProc = EmptyBuffProc;
1786 stream->wrNext = data->buff + sizeof(FCGI_Header);
1787 stream->stop = data->buffStop;
1788 stream->stopUnget = NULL;
1789 stream->rdNext = stream->stop;
1795 *----------------------------------------------------------------------
1799 * Frees all storage allocated when *streamPtr was created,
1800 * and nulls out *streamPtr.
1802 *----------------------------------------------------------------------
1804 void FreeStream(FCGX_Stream **streamPtr)
1806 FCGX_Stream *stream = *streamPtr;
1807 FCGX_Stream_Data *data;
1808 if(stream == NULL) {
1811 data = (FCGX_Stream_Data *)stream->data;
1812 data->reqDataPtr = NULL;
1820 *----------------------------------------------------------------------
1824 * Re-initializes the stream to read data of the specified type.
1826 *----------------------------------------------------------------------
1828 static FCGX_Stream *SetReaderType(FCGX_Stream *stream, int streamType)
1830 FCGX_Stream_Data *data = (FCGX_Stream_Data *)stream->data;
1831 ASSERT(stream->isReader);
1832 data->type = streamType;
1833 data->eorStop = FALSE;
1835 data->contentLen = 0;
1836 data->paddingLen = 0;
1837 stream->wrNext = stream->stop = stream->rdNext;
1838 stream->isClosed = FALSE;
1843 *----------------------------------------------------------------------
1847 * Creates a stream to read streamType records for the given
1848 * request. The stream performs OS reads of up to bufflen bytes.
1850 *----------------------------------------------------------------------
1852 static FCGX_Stream *NewReader(FCGX_Request *reqDataPtr, int bufflen, int streamType)
1854 return NewStream(reqDataPtr, bufflen, TRUE, streamType);
1859 *----------------------------------------------------------------------
1863 * Creates a stream to write streamType FastCGI records, using
1864 * the ipcFd and RequestId contained in *reqDataPtr.
1865 * The stream performs OS writes of up to bufflen bytes.
1867 *----------------------------------------------------------------------
1869 static FCGX_Stream *NewWriter(FCGX_Request *reqDataPtr, int bufflen, int streamType)
1871 return NewStream(reqDataPtr, bufflen, FALSE, streamType);
1876 *----------------------------------------------------------------------
1880 * Creates a stream to write streamType FastCGI records, using
1881 * the given ipcFd and request Id. This function is provided
1882 * for use by cgi-fcgi. In order to be defensive against misuse,
1883 * this function leaks a little storage; cgi-fcgi doesn't care.
1885 *----------------------------------------------------------------------
1887 FCGX_Stream *CreateWriter(
1893 FCGX_Request *reqDataPtr = (FCGX_Request *)Malloc(sizeof(FCGX_Request));
1894 reqDataPtr->ipcFd = ipcFd;
1895 reqDataPtr->requestId = requestId;
1897 * Suppress writing an FCGI_END_REQUEST record.
1899 reqDataPtr->nWriters = 2;
1900 return NewWriter(reqDataPtr, bufflen, streamType);
1904 *======================================================================
1906 *======================================================================
1910 *----------------------------------------------------------------------
1914 * This routine determines if the process is running as a CGI or
1915 * FastCGI process. The distinction is made by determining whether
1916 * FCGI_LISTENSOCK_FILENO is a listener ipcFd or the end of a
1917 * pipe (ie. standard in).
1920 * TRUE if the process is a CGI process, FALSE if FastCGI.
1922 *----------------------------------------------------------------------
1924 int FCGX_IsCGI(void)
1926 if (isFastCGI != -1) {
1930 if (!libInitialized) {
1931 int rc = FCGX_Init();
1933 /* exit() isn't great, but hey */
1934 exit((rc < 0) ? rc : -rc);
1938 isFastCGI = OS_IsFcgi(FCGI_LISTENSOCK_FILENO);
1944 *----------------------------------------------------------------------
1948 * Finishes the current request from the HTTP server.
1952 * Finishes the request accepted by (and frees any
1953 * storage allocated by) the previous call to FCGX_Accept.
1955 * DO NOT retain pointers to the envp array or any strings
1956 * contained in it (e.g. to the result of calling FCGX_GetParam),
1957 * since these will be freed by the next call to FCGX_Finish
1960 *----------------------------------------------------------------------
1963 void FCGX_Finish(void)
1965 FCGX_Finish_r(&the_request);
1969 *----------------------------------------------------------------------
1973 * Finishes the current request from the HTTP server.
1977 * Finishes the request accepted by (and frees any
1978 * storage allocated by) the previous call to FCGX_Accept.
1980 * DO NOT retain pointers to the envp array or any strings
1981 * contained in it (e.g. to the result of calling FCGX_GetParam),
1982 * since these will be freed by the next call to FCGX_Finish
1985 *----------------------------------------------------------------------
1987 void FCGX_Finish_r(FCGX_Request *reqDataPtr)
1989 if (reqDataPtr == NULL) {
1993 /* This should probably use a 'status' member instead of 'in' */
1994 if (reqDataPtr->in) {
1995 int errStatus = FCGX_FClose(reqDataPtr->err);
1996 int outStatus = FCGX_FClose(reqDataPtr->out);
1998 if (errStatus || outStatus || FCGX_GetError(reqDataPtr->in))
2000 OS_IpcClose(reqDataPtr->ipcFd);
2001 reqDataPtr->ipcFd = -1;
2005 FCGX_Free(reqDataPtr);
2008 void FCGX_Free(FCGX_Request * request)
2010 if (request == NULL)
2013 FreeStream(&request->in);
2014 FreeStream(&request->out);
2015 FreeStream(&request->err);
2016 FreeParams(&request->paramsPtr);
2018 if (!request->keepConnection)
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) {
2124 if ((rc = FCGX_Init())) {
2125 return (rc < 0) ? rc : -rc;
2129 rc = FCGX_Accept_r(&the_request);
2131 *in = the_request.in;
2132 *out = the_request.out;
2133 *err = the_request.err;
2134 *envp = the_request.envp;
2140 *----------------------------------------------------------------------
2144 * Accepts a new request from the HTTP server.
2147 * 0 for successful call, -1 for error.
2151 * Finishes the request accepted by (and frees any
2152 * storage allocated by) the previous call to FCGX_Accept.
2153 * Creates input, output, and error streams and
2154 * assigns them to *in, *out, and *err respectively.
2155 * Creates a parameters data structure to be accessed
2156 * via getenv(3) (if assigned to environ) or by FCGX_GetParam
2157 * and assigns it to *envp.
2159 * DO NOT retain pointers to the envp array or any strings
2160 * contained in it (e.g. to the result of calling FCGX_GetParam),
2161 * since these will be freed by the next call to FCGX_Finish
2164 *----------------------------------------------------------------------
2166 int FCGX_Accept_r(FCGX_Request *reqDataPtr)
2168 if (!libInitialized) {
2172 /* Finish the current request, if any. */
2173 FCGX_Finish_r(reqDataPtr);
2177 * If a connection isn't open, accept a new connection (blocking).
2178 * If an OS error occurs in accepting the connection,
2179 * return -1 to the caller, who should exit.
2181 if (reqDataPtr->ipcFd < 0) {
2182 int fail_on_intr = reqDataPtr->flags & FCGI_FAIL_ACCEPT_ON_INTR;
2184 reqDataPtr->ipcFd = OS_Accept(reqDataPtr->listen_sock, fail_on_intr, webServerAddressList);
2185 if (reqDataPtr->ipcFd < 0) {
2186 return (errno > 0) ? (0 - errno) : -9999;
2190 * A connection is open. Read from the connection in order to
2191 * get the request's role and environment. If protocol or other
2192 * errors occur, close the connection and try again.
2194 reqDataPtr->isBeginProcessed = FALSE;
2195 reqDataPtr->in = NewReader(reqDataPtr, 8192, 0);
2196 FillBuffProc(reqDataPtr->in);
2197 if(!reqDataPtr->isBeginProcessed) {
2202 switch(reqDataPtr->role) {
2203 case FCGI_RESPONDER:
2204 roleStr = "FCGI_ROLE=RESPONDER";
2206 case FCGI_AUTHORIZER:
2207 roleStr = "FCGI_ROLE=AUTHORIZER";
2210 roleStr = "FCGI_ROLE=FILTER";
2215 reqDataPtr->paramsPtr = NewParams(30);
2216 PutParam(reqDataPtr->paramsPtr, StringCopy(roleStr));
2218 SetReaderType(reqDataPtr->in, FCGI_PARAMS);
2219 if(ReadParams(reqDataPtr->paramsPtr, reqDataPtr->in) >= 0) {
2221 * Finished reading the environment. No errors occurred, so
2222 * leave the connection-retry loop.
2228 * Close the connection and try again.
2231 FCGX_Free(reqDataPtr);
2235 * Build the remaining data structures representing the new
2236 * request and return successfully to the caller.
2238 SetReaderType(reqDataPtr->in, FCGI_STDIN);
2239 reqDataPtr->out = NewWriter(reqDataPtr, 8192, FCGI_STDOUT);
2240 reqDataPtr->err = NewWriter(reqDataPtr, 512, FCGI_STDERR);
2241 reqDataPtr->nWriters = 2;
2242 reqDataPtr->envp = reqDataPtr->paramsPtr->vec;
2247 *----------------------------------------------------------------------
2249 * FCGX_StartFilterData --
2251 * stream is an input stream for a FCGI_FILTER request.
2252 * stream is positioned at EOF on FCGI_STDIN.
2253 * Repositions stream to the start of FCGI_DATA.
2254 * If the preconditions are not met (e.g. FCGI_STDIN has not
2255 * been read to EOF) sets the stream error code to
2256 * FCGX_CALL_SEQ_ERROR.
2259 * 0 for a normal return, < 0 for error
2261 *----------------------------------------------------------------------
2264 int FCGX_StartFilterData(FCGX_Stream *stream)
2266 FCGX_Stream_Data *data = (FCGX_Stream_Data *)stream->data;
2267 if(data->reqDataPtr->role != FCGI_FILTER
2268 || !stream->isReader
2269 || !stream->isClosed
2270 || data->type != FCGI_STDIN) {
2271 SetError(stream, FCGX_CALL_SEQ_ERROR);
2274 SetReaderType(stream, FCGI_DATA);
2279 *----------------------------------------------------------------------
2281 * FCGX_SetExitStatus --
2283 * Sets the exit status for stream's request. The exit status
2284 * is the status code the request would have exited with, had
2285 * the request been run as a CGI program. You can call
2286 * SetExitStatus several times during a request; the last call
2287 * before the request ends determines the value.
2289 *----------------------------------------------------------------------
2292 void FCGX_SetExitStatus(int status, FCGX_Stream *stream)
2294 FCGX_Stream_Data *data = (FCGX_Stream_Data *)stream->data;
2295 data->reqDataPtr->appStatus = status;