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.35 2003/06/22 00:16:43 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)
56 * This is a workaround for one version of the HP C compiler
57 * (c89 on HP-UX 9.04, also Stratus FTX), which will dump core
58 * if given 'long double' for varargs.
60 #ifdef HAVE_VA_ARG_LONG_DOUBLE_BUG
61 #define LONG_DOUBLE double
63 #define LONG_DOUBLE long double
69 static int libInitialized = 0;
70 static int isFastCGI = -1;
71 static char *webServerAddressList = NULL;
72 static FCGX_Request the_request;
74 void FCGX_ShutdownPending(void)
79 static void *Malloc(size_t size)
81 void *result = malloc(size);
82 ASSERT(size == 0 || result != NULL);
86 static char *StringCopy(char *str)
88 int strLen = strlen(str);
89 char *newString = (char *)Malloc(strLen + 1);
90 memcpy(newString, str, strLen);
91 newString[strLen] = '\000';
97 *----------------------------------------------------------------------
101 * Reads a byte from the input stream and returns it.
104 * The byte, or EOF (-1) if the end of input has been reached.
106 *----------------------------------------------------------------------
108 int FCGX_GetChar(FCGX_Stream *stream)
110 if (stream->isClosed || ! stream->isReader)
113 if (stream->rdNext != stream->stop)
114 return *stream->rdNext++;
116 stream->fillBuffProc(stream);
117 if (stream->isClosed)
120 stream->stopUnget = stream->rdNext;
121 if (stream->rdNext != stream->stop)
122 return *stream->rdNext++;
124 ASSERT(stream->isClosed); /* bug in fillBufProc if not */
129 *----------------------------------------------------------------------
133 * Reads up to n consecutive bytes from the input stream
134 * into the character array str. Performs no interpretation
135 * of the input bytes.
138 * Number of bytes read. If result is smaller than n,
139 * the end of input has been reached.
141 *----------------------------------------------------------------------
143 int FCGX_GetStr(char *str, int n, FCGX_Stream *stream)
147 if (stream->isClosed || ! stream->isReader || n <= 0) {
151 * Fast path: n bytes are already available
153 if(n <= (stream->stop - stream->rdNext)) {
154 memcpy(str, stream->rdNext, n);
159 * General case: stream is closed or buffer fill procedure
164 if(stream->rdNext != stream->stop) {
165 m = min(n - bytesMoved, stream->stop - stream->rdNext);
166 memcpy(str, stream->rdNext, m);
173 if(stream->isClosed || !stream->isReader)
175 stream->fillBuffProc(stream);
176 if (stream->isClosed)
179 stream->stopUnget = stream->rdNext;
184 *----------------------------------------------------------------------
188 * Reads up to n-1 consecutive bytes from the input stream
189 * into the character array str. Stops before n-1 bytes
190 * have been read if '\n' or EOF is read. The terminating '\n'
191 * is copied to str. After copying the last byte into str,
192 * stores a '\0' terminator.
195 * NULL if EOF is the first thing read from the input stream,
198 *----------------------------------------------------------------------
200 char *FCGX_GetLine(char *str, int n, FCGX_Stream *stream)
207 c = FCGX_GetChar(stream);
224 *----------------------------------------------------------------------
228 * Pushes back the character c onto the input stream. One
229 * character of pushback is guaranteed once a character
230 * has been read. No pushback is possible for EOF.
233 * Returns c if the pushback succeeded, EOF if not.
235 *----------------------------------------------------------------------
237 int FCGX_UnGetChar(int c, FCGX_Stream *stream) {
241 || stream->rdNext == stream->stopUnget)
244 *stream->rdNext = (unsigned char) c;
249 *----------------------------------------------------------------------
253 * Returns EOF if end-of-file has been detected while reading
254 * from stream; otherwise returns 0.
256 * Note that FCGX_HasSeenEOF(s) may return 0, yet an immediately
257 * following FCGX_GetChar(s) may return EOF. This function, like
258 * the standard C stdio function feof, does not provide the
259 * ability to peek ahead.
262 * EOF if end-of-file has been detected, 0 if not.
264 *----------------------------------------------------------------------
266 int FCGX_HasSeenEOF(FCGX_Stream *stream) {
267 return (stream->isClosed) ? EOF : 0;
271 *----------------------------------------------------------------------
275 * Writes a byte to the output stream.
278 * The byte, or EOF (-1) if an error occurred.
280 *----------------------------------------------------------------------
282 int FCGX_PutChar(int c, FCGX_Stream *stream)
284 if(stream->wrNext != stream->stop)
285 return (*stream->wrNext++ = (unsigned char) c);
286 if(stream->isClosed || stream->isReader)
288 stream->emptyBuffProc(stream, FALSE);
289 if(stream->wrNext != stream->stop)
290 return (*stream->wrNext++ = (unsigned char) c);
291 ASSERT(stream->isClosed); /* bug in emptyBuffProc if not */
296 *----------------------------------------------------------------------
300 * Writes n consecutive bytes from the character array str
301 * into the output stream. Performs no interpretation
302 * of the output bytes.
305 * Number of bytes written (n) for normal return,
306 * EOF (-1) if an error occurred.
308 *----------------------------------------------------------------------
310 int FCGX_PutStr(const char *str, int n, FCGX_Stream *stream)
315 * Fast path: room for n bytes in the buffer
317 if(n <= (stream->stop - stream->wrNext)) {
318 memcpy(stream->wrNext, str, n);
323 * General case: stream is closed or buffer empty procedure
328 if(stream->wrNext != stream->stop) {
329 m = min(n - bytesMoved, stream->stop - stream->wrNext);
330 memcpy(stream->wrNext, str, m);
337 if(stream->isClosed || stream->isReader)
339 stream->emptyBuffProc(stream, FALSE);
344 *----------------------------------------------------------------------
348 * Writes a character string to the output stream.
351 * number of bytes written for normal return,
352 * EOF (-1) if an error occurred.
354 *----------------------------------------------------------------------
356 int FCGX_PutS(const char *str, FCGX_Stream *stream)
358 return FCGX_PutStr(str, strlen(str), stream);
362 *----------------------------------------------------------------------
366 * Performs output formatting and writes the results
367 * to the output stream.
370 * number of bytes written for normal return,
371 * EOF (-1) if an error occurred.
373 *----------------------------------------------------------------------
375 int FCGX_FPrintF(FCGX_Stream *stream, const char *format, ...)
379 va_start(ap, format);
380 result = FCGX_VFPrintF(stream, format, ap);
386 *----------------------------------------------------------------------
390 * Performs output formatting and writes the results
391 * to the output stream.
394 * number of bytes written for normal return,
395 * EOF (-1) if an error occurred.
397 *----------------------------------------------------------------------
400 #define PRINTF_BUFFLEN 100
402 * More than sufficient space for all unmodified conversions
405 #define FMT_BUFFLEN 25
407 * Max size of a format specifier is 1 + 5 + 7 + 7 + 2 + 1 + slop
409 static void CopyAndAdvance(char **destPtr, char **srcPtr, int n);
411 int FCGX_VFPrintF(FCGX_Stream *stream, const char *format, va_list arg)
413 char *f, *fStop, *percentPtr, *p, *fmtBuffPtr, *buffPtr;
414 int op, performedOp, sizeModifier, buffCount = 0, buffLen, specifierLength;
415 int fastPath, n, auxBuffLen = 0, buffReqd, minWidth, precision, exp;
416 char *auxBuffPtr = NULL;
418 char fmtBuff[FMT_BUFFLEN];
419 char buff[PRINTF_BUFFLEN];
424 unsigned unsignedArg;
425 unsigned long uLongArg;
426 unsigned short uShortArg;
427 char *charPtrArg = NULL;
432 double doubleArg = 0.0;
433 LONG_DOUBLE lDoubleArg = 0.0L;
437 fStop = f + strlen(f);
439 percentPtr = (char *)memchr(f, '%', fStop - f);
440 if(percentPtr == NULL) percentPtr = fStop;
441 if(percentPtr != f) {
442 if(FCGX_PutStr(f, percentPtr - f, stream) < 0)
444 streamCount += percentPtr - f;
446 if(f == fStop) break;
450 * The following loop always executes either once or twice.
455 * Fast path: Scan optimistically, hoping that no flags,
456 * minimum field width, or precision are specified.
457 * Use the preallocated buffer, which is large enough
458 * for all fast path cases. If the conversion specifier
459 * is really more complex, run the loop a second time
460 * using the slow path.
461 * Note that fast path execution of %s bypasses the buffer
462 * and %f is not attempted on the fast path due to
463 * its large buffering requirements.
465 op = *(percentPtr + 1);
471 op = *(percentPtr + 2);
472 fmtBuff[1] = (char) sizeModifier;
473 fmtBuff[2] = (char) op;
479 fmtBuff[1] = (char) op;
485 buffLen = PRINTF_BUFFLEN;
488 * Slow path: Scan the conversion specifier and construct
489 * a new format string, compute an upper bound on the
490 * amount of buffering that sprintf will require,
491 * and allocate a larger buffer if necessary.
494 fmtBuffPtr = &fmtBuff[1];
498 n = strspn(p, "-0+ #");
501 CopyAndAdvance(&fmtBuffPtr, &p, n);
503 * Scan minimum field width
505 n = strspn(p, "0123456789");
508 minWidth = va_arg(arg, int);
509 if(abs(minWidth) > 999999)
512 * The following use of strlen rather than the
513 * value returned from sprintf is because SUNOS4
514 * returns a char * instead of an int count.
516 sprintf(fmtBuffPtr, "%d", minWidth);
517 fmtBuffPtr += strlen(fmtBuffPtr);
523 minWidth = strtol(p, NULL, 10);
524 CopyAndAdvance(&fmtBuffPtr, &p, n);
532 CopyAndAdvance(&fmtBuffPtr, &p, 1);
533 n = strspn(p, "0123456789");
536 precision = va_arg(arg, int);
537 if(precision < 0) precision = 0;
538 if(precision > 999999)
541 * The following use of strlen rather than the
542 * value returned from sprintf is because SUNOS4
543 * returns a char * instead of an int count.
545 sprintf(fmtBuffPtr, "%d", precision);
546 fmtBuffPtr += strlen(fmtBuffPtr);
552 precision = strtol(p, NULL, 10);
553 CopyAndAdvance(&fmtBuffPtr, &p, n);
561 * Scan size modifier and conversion operation
568 CopyAndAdvance(&fmtBuffPtr, &p, 1);
575 CopyAndAdvance(&fmtBuffPtr, &p, 1);
576 ASSERT(fmtBuffPtr - fmtBuff < FMT_BUFFLEN);
578 specifierLength = p - percentPtr;
580 * Bound the required buffer size. For s and f
581 * conversions this requires examining the argument.
592 buffReqd = max(precision, 46);
595 charPtrArg = va_arg(arg, char *);
596 if (!charPtrArg) charPtrArg = "(null)";
597 if(precision == -1) {
598 buffReqd = strlen(charPtrArg);
600 p = (char *)memchr(charPtrArg, '\0', precision);
602 (p == NULL) ? precision : p - charPtrArg;
606 switch(sizeModifier) {
608 doubleArg = va_arg(arg, double);
609 frexp(doubleArg, &exp);
612 lDoubleArg = va_arg(arg, LONG_DOUBLE);
613 /* XXX Need to check for the presence of
614 * frexpl() and use it if available */
615 frexp((double) lDoubleArg, &exp);
620 if(precision == -1) precision = 6;
621 buffReqd = precision + 3 + ((exp > 0) ? exp/3 : 0);
627 if(precision == -1) precision = 6;
628 buffReqd = precision + 8;
636 buffReqd = max(buffReqd + 10, minWidth);
638 * Allocate the buffer
640 if(buffReqd <= PRINTF_BUFFLEN) {
642 buffLen = PRINTF_BUFFLEN;
644 if(auxBuffPtr == NULL || buffReqd > auxBuffLen) {
645 if(auxBuffPtr != NULL) free(auxBuffPtr);
646 auxBuffPtr = (char *)Malloc(buffReqd);
647 auxBuffLen = buffReqd;
648 if(auxBuffPtr == NULL)
651 buffPtr = auxBuffPtr;
652 buffLen = auxBuffLen;
656 * This giant switch statement requires the following variables
657 * to be set up: op, sizeModifier, arg, buffPtr, fmtBuff.
658 * When fastPath == FALSE and op == 's' or 'f', the argument
659 * has been read into charPtrArg, doubleArg, or lDoubleArg.
660 * The statement produces the boolean performedOp, TRUE iff
661 * the op/sizeModifier were executed and argument consumed;
662 * if performedOp, the characters written into buffPtr[]
663 * and the character count buffCount (== EOF meaning error).
665 * The switch cases are arranged in the same order as in the
666 * description of fprintf in section 15.11 of Harbison and Steele.
672 switch(sizeModifier) {
674 intArg = va_arg(arg, int);
675 sprintf(buffPtr, fmtBuff, intArg);
676 buffCount = strlen(buffPtr);
679 longArg = va_arg(arg, long);
680 sprintf(buffPtr, fmtBuff, longArg);
681 buffCount = strlen(buffPtr);
684 shortArg = (short) va_arg(arg, int);
685 sprintf(buffPtr, fmtBuff, shortArg);
686 buffCount = strlen(buffPtr);
696 switch(sizeModifier) {
698 unsignedArg = va_arg(arg, unsigned);
699 sprintf(buffPtr, fmtBuff, unsignedArg);
700 buffCount = strlen(buffPtr);
703 uLongArg = va_arg(arg, unsigned long);
704 sprintf(buffPtr, fmtBuff, uLongArg);
705 buffCount = strlen(buffPtr);
708 uShortArg = (unsigned short) va_arg(arg, int);
709 sprintf(buffPtr, fmtBuff, uShortArg);
710 buffCount = strlen(buffPtr);
717 switch(sizeModifier) {
719 intArg = va_arg(arg, int);
720 sprintf(buffPtr, fmtBuff, intArg);
721 buffCount = strlen(buffPtr);
725 * XXX: Allowed by ISO C Amendment 1, but
726 * many platforms don't yet support wint_t
734 switch(sizeModifier) {
737 buffPtr = va_arg(arg, char *);
738 buffCount = strlen(buffPtr);
739 buffLen = buffCount + 1;
741 sprintf(buffPtr, fmtBuff, charPtrArg);
742 buffCount = strlen(buffPtr);
747 * XXX: Don't know how to convert a sequence
748 * of wide characters into a byte stream, or
749 * even how to predict the buffering required.
757 if(sizeModifier != ' ')
759 voidPtrArg = va_arg(arg, void *);
760 sprintf(buffPtr, fmtBuff, voidPtrArg);
761 buffCount = strlen(buffPtr);
764 switch(sizeModifier) {
766 intPtrArg = va_arg(arg, int *);
767 *intPtrArg = streamCount;
770 longPtrArg = va_arg(arg, long *);
771 *longPtrArg = streamCount;
774 shortPtrArg = (short *) va_arg(arg, short *);
775 *shortPtrArg = (short) streamCount;
787 switch(sizeModifier) {
789 sprintf(buffPtr, fmtBuff, doubleArg);
790 buffCount = strlen(buffPtr);
793 sprintf(buffPtr, fmtBuff, lDoubleArg);
794 buffCount = strlen(buffPtr);
804 switch(sizeModifier) {
806 doubleArg = va_arg(arg, double);
807 sprintf(buffPtr, fmtBuff, doubleArg);
808 buffCount = strlen(buffPtr);
811 lDoubleArg = va_arg(arg, LONG_DOUBLE);
812 sprintf(buffPtr, fmtBuff, lDoubleArg);
813 buffCount = strlen(buffPtr);
820 if(sizeModifier != ' ')
831 if(performedOp) break;
836 ASSERT(buffCount < buffLen);
838 if(FCGX_PutStr(buffPtr, buffCount, stream) < 0)
840 streamCount += buffCount;
841 } else if(buffCount < 0) {
844 f += specifierLength;
845 } /* while(f != fStop) */
850 if(auxBuffPtr != NULL) free(auxBuffPtr);
855 * Copy n characters from *srcPtr to *destPtr, then increment
856 * both *srcPtr and *destPtr by n.
858 static void CopyAndAdvance(char **destPtr, char **srcPtr, int n)
860 char *dest = *destPtr;
863 for (i = 0; i < n; i++)
870 *----------------------------------------------------------------------
874 * Flushes any buffered output.
876 * Server-push is a legitimate application of FCGX_FFlush.
877 * Otherwise, FCGX_FFlush is not very useful, since FCGX_Accept
878 * does it implicitly. FCGX_FFlush may reduce performance
879 * by increasing the total number of operating system calls
880 * the application makes.
883 * EOF (-1) if an error occurred.
885 *----------------------------------------------------------------------
887 int FCGX_FFlush(FCGX_Stream *stream)
889 if(stream->isClosed || stream->isReader)
891 stream->emptyBuffProc(stream, FALSE);
892 return (stream->isClosed) ? -1 : 0;
896 *----------------------------------------------------------------------
900 * Performs FCGX_FFlush and closes the stream.
902 * This is not a very useful operation, since FCGX_Accept
903 * does it implicitly. Closing the out stream before the
904 * err stream results in an extra write if there's nothing
905 * in the err stream, and therefore reduces performance.
908 * EOF (-1) if an error occurred.
910 *----------------------------------------------------------------------
912 int FCGX_FClose(FCGX_Stream *stream)
914 if (stream == NULL) return 0;
916 if(!stream->wasFCloseCalled) {
917 if(!stream->isReader) {
918 stream->emptyBuffProc(stream, TRUE);
920 stream->wasFCloseCalled = TRUE;
921 stream->isClosed = TRUE;
922 if(stream->isReader) {
923 stream->wrNext = stream->stop = stream->rdNext;
925 stream->rdNext = stream->stop = stream->wrNext;
928 return (stream->FCGI_errno == 0) ? 0 : EOF;
932 *----------------------------------------------------------------------
936 * An error has occurred; save the error code in the stream
937 * for diagnostic purposes and set the stream state so that
938 * reads return EOF and writes have no effect.
940 *----------------------------------------------------------------------
942 static void SetError(FCGX_Stream *stream, int FCGI_errno)
945 * Preserve only the first error.
947 if(stream->FCGI_errno == 0) {
948 stream->FCGI_errno = FCGI_errno;
951 stream->isClosed = TRUE;
955 *----------------------------------------------------------------------
959 * Return the stream error code. 0 means no error, > 0
960 * is an errno(2) error, < 0 is an FCGX_errno error.
962 *----------------------------------------------------------------------
964 int FCGX_GetError(FCGX_Stream *stream) {
965 return stream->FCGI_errno;
969 *----------------------------------------------------------------------
973 * Clear the stream error code and end-of-file indication.
975 *----------------------------------------------------------------------
977 void FCGX_ClearError(FCGX_Stream *stream) {
978 stream->FCGI_errno = 0;
980 * stream->isClosed = FALSE;
981 * XXX: should clear isClosed but work is needed to make it safe
982 * to do so. For example, if an application calls FClose, gets
983 * an I/O error on the write, calls ClearError and retries
984 * the FClose, FClose (really EmptyBuffProc) will write a second
985 * EOF record. If an application calls PutChar instead of FClose
986 * after the ClearError, the application will write more data.
987 * The stream's state must discriminate between various states
988 * of the stream that are now all lumped under isClosed.
993 *======================================================================
995 *======================================================================
999 * A vector of pointers representing the parameters received
1000 * by a FastCGI application server, with the vector's length
1001 * and last valid element so adding new parameters is efficient.
1004 typedef struct Params {
1005 FCGX_ParamArray vec; /* vector of strings */
1006 int length; /* number of string vec can hold */
1007 char **cur; /* current item in vec; *cur == NULL */
1009 typedef Params *ParamsPtr;
1012 *----------------------------------------------------------------------
1016 * Creates a new Params structure.
1019 * Pointer to the new structure.
1021 *----------------------------------------------------------------------
1023 static ParamsPtr NewParams(int length)
1026 result = (Params *)Malloc(sizeof(Params));
1027 result->vec = (char **)Malloc(length * sizeof(char *));
1028 result->length = length;
1029 result->cur = result->vec;
1030 *result->cur = NULL;
1035 *----------------------------------------------------------------------
1039 * Frees a Params structure and all the parameters it contains.
1042 * env becomes invalid.
1044 *----------------------------------------------------------------------
1046 static void FreeParams(ParamsPtr *paramsPtrPtr)
1048 ParamsPtr paramsPtr = *paramsPtrPtr;
1050 if(paramsPtr == NULL) {
1053 for (p = paramsPtr->vec; p < paramsPtr->cur; p++) {
1056 free(paramsPtr->vec);
1058 *paramsPtrPtr = NULL;
1062 *----------------------------------------------------------------------
1066 * Add a name/value pair to a Params structure.
1072 * Parameters structure updated.
1074 *----------------------------------------------------------------------
1076 static void PutParam(ParamsPtr paramsPtr, char *nameValue)
1080 *paramsPtr->cur++ = nameValue;
1081 size = paramsPtr->cur - paramsPtr->vec;
1082 if(size >= paramsPtr->length) {
1083 paramsPtr->length *= 2;
1084 paramsPtr->vec = (FCGX_ParamArray)realloc(paramsPtr->vec, paramsPtr->length * sizeof(char *));
1085 paramsPtr->cur = paramsPtr->vec + size;
1087 *paramsPtr->cur = NULL;
1091 *----------------------------------------------------------------------
1093 * FCGX_GetParam -- obtain value of FCGI parameter in environment
1097 * Value bound to name, NULL if name not present in the
1098 * environment envp. Caller must not mutate the result
1099 * or retain it past the end of this request.
1101 *----------------------------------------------------------------------
1103 char *FCGX_GetParam(const char *name, FCGX_ParamArray envp)
1108 if (name == NULL || envp == NULL) return NULL;
1112 for (p = envp; *p; ++p) {
1113 if((strncmp(name, *p, len) == 0) && ((*p)[len] == '=')) {
1121 *----------------------------------------------------------------------
1123 * Start of FastCGI-specific code
1125 *----------------------------------------------------------------------
1129 *----------------------------------------------------------------------
1133 * Reads FastCGI name-value pairs from stream until EOF. Converts
1134 * each pair to name=value format and adds it to Params structure.
1136 *----------------------------------------------------------------------
1138 static int ReadParams(Params *paramsPtr, FCGX_Stream *stream)
1140 int nameLen, valueLen;
1141 unsigned char lenBuff[3];
1144 while((nameLen = FCGX_GetChar(stream)) != EOF) {
1146 * Read name length (one or four bytes) and value length
1147 * (one or four bytes) from stream.
1149 if((nameLen & 0x80) != 0) {
1150 if(FCGX_GetStr((char *) &lenBuff[0], 3, stream) != 3) {
1151 SetError(stream, FCGX_PARAMS_ERROR);
1154 nameLen = ((nameLen & 0x7f) << 24) + (lenBuff[0] << 16)
1155 + (lenBuff[1] << 8) + lenBuff[2];
1157 if((valueLen = FCGX_GetChar(stream)) == EOF) {
1158 SetError(stream, FCGX_PARAMS_ERROR);
1161 if((valueLen & 0x80) != 0) {
1162 if(FCGX_GetStr((char *) &lenBuff[0], 3, stream) != 3) {
1163 SetError(stream, FCGX_PARAMS_ERROR);
1166 valueLen = ((valueLen & 0x7f) << 24) + (lenBuff[0] << 16)
1167 + (lenBuff[1] << 8) + lenBuff[2];
1170 * nameLen and valueLen are now valid; read the name and value
1171 * from stream and construct a standard environment entry.
1173 nameValue = (char *)Malloc(nameLen + valueLen + 2);
1174 if(FCGX_GetStr(nameValue, nameLen, stream) != nameLen) {
1175 SetError(stream, FCGX_PARAMS_ERROR);
1179 *(nameValue + nameLen) = '=';
1180 if(FCGX_GetStr(nameValue + nameLen + 1, valueLen, stream)
1182 SetError(stream, FCGX_PARAMS_ERROR);
1186 *(nameValue + nameLen + valueLen + 1) = '\0';
1187 PutParam(paramsPtr, nameValue);
1193 *----------------------------------------------------------------------
1197 * Constructs an FCGI_Header struct.
1199 *----------------------------------------------------------------------
1201 static FCGI_Header MakeHeader(
1208 ASSERT(contentLength >= 0 && contentLength <= FCGI_MAX_LENGTH);
1209 ASSERT(paddingLength >= 0 && paddingLength <= 0xff);
1210 header.version = FCGI_VERSION_1;
1211 header.type = (unsigned char) type;
1212 header.requestIdB1 = (unsigned char) ((requestId >> 8) & 0xff);
1213 header.requestIdB0 = (unsigned char) ((requestId ) & 0xff);
1214 header.contentLengthB1 = (unsigned char) ((contentLength >> 8) & 0xff);
1215 header.contentLengthB0 = (unsigned char) ((contentLength ) & 0xff);
1216 header.paddingLength = (unsigned char) paddingLength;
1217 header.reserved = 0;
1222 *----------------------------------------------------------------------
1224 * MakeEndRequestBody --
1226 * Constructs an FCGI_EndRequestBody struct.
1228 *----------------------------------------------------------------------
1230 static FCGI_EndRequestBody MakeEndRequestBody(
1234 FCGI_EndRequestBody body;
1235 body.appStatusB3 = (unsigned char) ((appStatus >> 24) & 0xff);
1236 body.appStatusB2 = (unsigned char) ((appStatus >> 16) & 0xff);
1237 body.appStatusB1 = (unsigned char) ((appStatus >> 8) & 0xff);
1238 body.appStatusB0 = (unsigned char) ((appStatus ) & 0xff);
1239 body.protocolStatus = (unsigned char) protocolStatus;
1240 memset(body.reserved, 0, sizeof(body.reserved));
1245 *----------------------------------------------------------------------
1247 * MakeUnknownTypeBody --
1249 * Constructs an FCGI_MakeUnknownTypeBody struct.
1251 *----------------------------------------------------------------------
1253 static FCGI_UnknownTypeBody MakeUnknownTypeBody(
1256 FCGI_UnknownTypeBody body;
1257 body.type = (unsigned char) type;
1258 memset(body.reserved, 0, sizeof(body.reserved));
1263 *----------------------------------------------------------------------
1267 * Returns the smallest integer greater than or equal to n
1268 * that's a multiple of 8.
1270 *----------------------------------------------------------------------
1272 static int AlignInt8(unsigned n) {
1273 return (n + 7) & (UINT_MAX - 7);
1277 *----------------------------------------------------------------------
1281 * Returns the smallest pointer greater than or equal to p
1282 * that's a multiple of 8.
1284 *----------------------------------------------------------------------
1286 static unsigned char *AlignPtr8(unsigned char *p) {
1287 unsigned long u = (unsigned long) p;
1288 u = ((u + 7) & (ULONG_MAX - 7)) - u;
1294 * State associated with a stream
1296 typedef struct FCGX_Stream_Data {
1297 unsigned char *buff; /* buffer after alignment */
1298 int bufflen; /* number of bytes buff can store */
1299 unsigned char *mBuff; /* buffer as returned by Malloc */
1300 unsigned char *buffStop; /* reader: last valid byte + 1 of entire buffer.
1301 * stop generally differs from buffStop for
1302 * readers because of record structure.
1303 * writer: buff + bufflen */
1304 int type; /* reader: FCGI_PARAMS or FCGI_STDIN
1305 * writer: FCGI_STDOUT or FCGI_STDERR */
1306 int eorStop; /* reader: stop stream at end-of-record */
1307 int skip; /* reader: don't deliver content bytes */
1308 int contentLen; /* reader: bytes of unread content */
1309 int paddingLen; /* reader: bytes of unread padding */
1310 int isAnythingWritten; /* writer: data has been written to ipcFd */
1311 int rawWrite; /* writer: write data without stream headers */
1312 FCGX_Request *reqDataPtr; /* request data not specific to one stream */
1316 *----------------------------------------------------------------------
1318 * WriteCloseRecords --
1320 * Writes an EOF record for the stream content if necessary.
1321 * If this is the last writer to close, writes an FCGI_END_REQUEST
1324 *----------------------------------------------------------------------
1326 static void WriteCloseRecords(struct FCGX_Stream *stream)
1328 FCGX_Stream_Data *data = (FCGX_Stream_Data *)stream->data;
1330 * Enter rawWrite mode so final records won't be encapsulated as
1333 data->rawWrite = TRUE;
1335 * Generate EOF for stream content if needed.
1337 if(!(data->type == FCGI_STDERR
1338 && stream->wrNext == data->buff
1339 && !data->isAnythingWritten)) {
1341 header = MakeHeader(data->type, data->reqDataPtr->requestId, 0, 0);
1342 FCGX_PutStr((char *) &header, sizeof(header), stream);
1345 * Generate FCGI_END_REQUEST record if needed.
1347 if(data->reqDataPtr->nWriters == 1) {
1348 FCGI_EndRequestRecord endRequestRecord;
1349 endRequestRecord.header = MakeHeader(FCGI_END_REQUEST,
1350 data->reqDataPtr->requestId,
1351 sizeof(endRequestRecord.body), 0);
1352 endRequestRecord.body = MakeEndRequestBody(
1353 data->reqDataPtr->appStatus, FCGI_REQUEST_COMPLETE);
1354 FCGX_PutStr((char *) &endRequestRecord,
1355 sizeof(endRequestRecord), stream);
1357 data->reqDataPtr->nWriters--;
1362 static int write_it_all(int fd, char *buf, int len)
1367 wrote = OS_Write(fd, buf, len);
1377 *----------------------------------------------------------------------
1381 * Encapsulates any buffered stream content in a FastCGI
1382 * record. Writes the data, making the buffer empty.
1384 *----------------------------------------------------------------------
1386 static void EmptyBuffProc(struct FCGX_Stream *stream, int doClose)
1388 FCGX_Stream_Data *data = (FCGX_Stream_Data *)stream->data;
1391 * If the buffer contains stream data, fill in the header.
1392 * Pad the record to a multiple of 8 bytes in length. Padding
1393 * can't overflow the buffer because the buffer is a multiple
1394 * of 8 bytes in length. If the buffer contains no stream
1395 * data, reclaim the space reserved for the header.
1397 if(!data->rawWrite) {
1398 cLen = stream->wrNext - data->buff - sizeof(FCGI_Header);
1400 eLen = AlignInt8(cLen);
1402 * Giving the padding a well-defined value keeps Purify happy.
1404 memset(stream->wrNext, 0, eLen - cLen);
1405 stream->wrNext += eLen - cLen;
1406 *((FCGI_Header *) data->buff)
1407 = MakeHeader(data->type,
1408 data->reqDataPtr->requestId, cLen, eLen - cLen);
1410 stream->wrNext = data->buff;
1414 WriteCloseRecords(stream);
1416 if (stream->wrNext != data->buff) {
1417 data->isAnythingWritten = TRUE;
1418 if (write_it_all(data->reqDataPtr->ipcFd, (char *)data->buff, stream->wrNext - data->buff) < 0) {
1419 SetError(stream, OS_Errno);
1422 stream->wrNext = data->buff;
1425 * The buffer is empty.
1427 if(!data->rawWrite) {
1428 stream->wrNext += sizeof(FCGI_Header);
1433 * Return codes for Process* functions
1435 #define STREAM_RECORD 0
1437 #define BEGIN_RECORD 2
1438 #define MGMT_RECORD 3
1441 *----------------------------------------------------------------------
1443 * ProcessManagementRecord --
1445 * Reads and responds to a management record. The only type of
1446 * management record this library understands is FCGI_GET_VALUES.
1447 * The only variables that this library's FCGI_GET_VALUES
1448 * understands are FCGI_MAX_CONNS, FCGI_MAX_REQS, and FCGI_MPXS_CONNS.
1449 * Ignore other FCGI_GET_VALUES variables; respond to other
1450 * management records with a FCGI_UNKNOWN_TYPE record.
1452 *----------------------------------------------------------------------
1454 static int ProcessManagementRecord(int type, FCGX_Stream *stream)
1456 FCGX_Stream_Data *data = (FCGX_Stream_Data *)stream->data;
1457 ParamsPtr paramsPtr = NewParams(3);
1459 char response[64]; /* 64 = 8 + 3*(1+1+14+1)* + padding */
1460 char *responseP = &response[FCGI_HEADER_LEN];
1461 char *name, value = '\0';
1463 if(type == FCGI_GET_VALUES) {
1464 ReadParams(paramsPtr, stream);
1465 if((FCGX_GetError(stream) != 0) || (data->contentLen != 0)) {
1466 FreeParams(¶msPtr);
1467 return FCGX_PROTOCOL_ERROR;
1469 for (pPtr = paramsPtr->vec; pPtr < paramsPtr->cur; pPtr++) {
1471 *(strchr(name, '=')) = '\0';
1472 if(strcmp(name, FCGI_MAX_CONNS) == 0) {
1474 } else if(strcmp(name, FCGI_MAX_REQS) == 0) {
1476 } else if(strcmp(name, FCGI_MPXS_CONNS) == 0) {
1483 sprintf(responseP, "%c%c%s%c", len, 1, name, value);
1484 responseP += len + 3;
1487 len = responseP - &response[FCGI_HEADER_LEN];
1488 paddedLen = AlignInt8(len);
1489 *((FCGI_Header *) response)
1490 = MakeHeader(FCGI_GET_VALUES_RESULT, FCGI_NULL_REQUEST_ID,
1491 len, paddedLen - len);
1492 FreeParams(¶msPtr);
1494 paddedLen = len = sizeof(FCGI_UnknownTypeBody);
1495 ((FCGI_UnknownTypeRecord *) response)->header
1496 = MakeHeader(FCGI_UNKNOWN_TYPE, FCGI_NULL_REQUEST_ID,
1498 ((FCGI_UnknownTypeRecord *) response)->body
1499 = MakeUnknownTypeBody(type);
1501 if (write_it_all(data->reqDataPtr->ipcFd, response, FCGI_HEADER_LEN + paddedLen) < 0) {
1502 SetError(stream, OS_Errno);
1510 *----------------------------------------------------------------------
1512 * ProcessBeginRecord --
1514 * Reads an FCGI_BEGIN_REQUEST record.
1517 * BEGIN_RECORD for normal return. FCGX_PROTOCOL_ERROR for
1518 * protocol error. SKIP for attempt to multiplex
1519 * connection. -1 for error from write (errno in stream).
1522 * In case of BEGIN_RECORD return, stores requestId, role,
1523 * keepConnection values, and sets isBeginProcessed = TRUE.
1525 *----------------------------------------------------------------------
1527 static int ProcessBeginRecord(int requestId, FCGX_Stream *stream)
1529 FCGX_Stream_Data *data = (FCGX_Stream_Data *)stream->data;
1530 FCGI_BeginRequestBody body;
1531 if(requestId == 0 || data->contentLen != sizeof(body)) {
1532 return FCGX_PROTOCOL_ERROR;
1534 if(data->reqDataPtr->isBeginProcessed) {
1536 * The Web server is multiplexing the connection. This library
1537 * doesn't know how to handle multiplexing, so respond with
1538 * FCGI_END_REQUEST{protocolStatus = FCGI_CANT_MPX_CONN}
1540 FCGI_EndRequestRecord endRequestRecord;
1541 endRequestRecord.header = MakeHeader(FCGI_END_REQUEST,
1542 requestId, sizeof(endRequestRecord.body), 0);
1543 endRequestRecord.body
1544 = MakeEndRequestBody(0, FCGI_CANT_MPX_CONN);
1545 if (write_it_all(data->reqDataPtr->ipcFd, (char *)&endRequestRecord, sizeof(endRequestRecord)) < 0) {
1546 SetError(stream, OS_Errno);
1553 * Accept this new request. Read the record body.
1555 data->reqDataPtr->requestId = requestId;
1556 if(FCGX_GetStr((char *) &body, sizeof(body), stream)
1558 return FCGX_PROTOCOL_ERROR;
1560 data->reqDataPtr->keepConnection = (body.flags & FCGI_KEEP_CONN);
1561 data->reqDataPtr->role = (body.roleB1 << 8) + body.roleB0;
1562 data->reqDataPtr->isBeginProcessed = TRUE;
1563 return BEGIN_RECORD;
1567 *----------------------------------------------------------------------
1571 * Interprets FCGI_Header. Processes FCGI_BEGIN_REQUEST and
1572 * management records here; extracts information from stream
1573 * records (FCGI_PARAMS, FCGI_STDIN) into stream.
1576 * >= 0 for a normal return, < 0 for error
1579 * XXX: Many (more than there used to be).
1580 * If !stream->isRequestIdSet, ProcessHeader initializes
1581 * stream->requestId from header and sets stream->isRequestIdSet
1582 * to TRUE. ProcessHeader also sets stream->contentLen to header's
1583 * contentLength, and sets stream->paddingLen to the header's
1586 *----------------------------------------------------------------------
1588 static int ProcessHeader(FCGI_Header header, FCGX_Stream *stream)
1590 FCGX_Stream_Data *data = (FCGX_Stream_Data *)stream->data;
1592 if(header.version != FCGI_VERSION_1) {
1593 return FCGX_UNSUPPORTED_VERSION;
1595 requestId = (header.requestIdB1 << 8)
1596 + header.requestIdB0;
1597 data->contentLen = (header.contentLengthB1 << 8)
1598 + header.contentLengthB0;
1599 data->paddingLen = header.paddingLength;
1600 if(header.type == FCGI_BEGIN_REQUEST) {
1601 return ProcessBeginRecord(requestId, stream);
1603 if(requestId == FCGI_NULL_REQUEST_ID) {
1604 return ProcessManagementRecord(header.type, stream);
1606 if(requestId != data->reqDataPtr->requestId) {
1609 if(header.type != data->type) {
1610 return FCGX_PROTOCOL_ERROR;
1612 return STREAM_RECORD;
1616 *----------------------------------------------------------------------
1620 * Reads bytes from the ipcFd, supplies bytes to a stream client.
1622 *----------------------------------------------------------------------
1624 static void FillBuffProc(FCGX_Stream *stream)
1626 FCGX_Stream_Data *data = (FCGX_Stream_Data *)stream->data;
1633 * If data->buff is empty, do a read.
1635 if(stream->rdNext == data->buffStop) {
1636 count = OS_Read(data->reqDataPtr->ipcFd, (char *)data->buff,
1639 SetError(stream, (count == 0 ? FCGX_PROTOCOL_ERROR : OS_Errno));
1642 stream->rdNext = data->buff;
1643 data->buffStop = data->buff + count;
1646 * Now data->buff is not empty. If the current record contains
1647 * more content bytes, deliver all that are present in data->buff.
1649 if(data->contentLen > 0) {
1650 count = min(data->contentLen, data->buffStop - stream->rdNext);
1651 data->contentLen -= count;
1653 stream->wrNext = stream->stop = stream->rdNext + count;
1656 stream->rdNext += count;
1657 if(data->contentLen > 0) {
1665 * If the current record (whose content has been fully consumed by
1666 * the client) was padded, skip over the padding bytes.
1668 if(data->paddingLen > 0) {
1669 count = min(data->paddingLen, data->buffStop - stream->rdNext);
1670 data->paddingLen -= count;
1671 stream->rdNext += count;
1672 if(data->paddingLen > 0) {
1677 * All done with the current record, including the padding.
1678 * If we're in a recursive call from ProcessHeader, deliver EOF.
1681 stream->stop = stream->rdNext;
1682 stream->isClosed = TRUE;
1686 * Fill header with bytes from the input buffer.
1688 count = min((int)sizeof(header) - headerLen,
1689 data->buffStop - stream->rdNext);
1690 memcpy(((char *)(&header)) + headerLen, stream->rdNext, count);
1692 stream->rdNext += count;
1693 if(headerLen < sizeof(header)) {
1698 * Interpret header. eorStop prevents ProcessHeader from reading
1699 * past the end-of-record when using stream to read content.
1701 data->eorStop = TRUE;
1702 stream->stop = stream->rdNext;
1703 status = ProcessHeader(header, stream);
1704 data->eorStop = FALSE;
1705 stream->isClosed = FALSE;
1709 * If this stream record header marked the end of stream
1710 * data deliver EOF to the stream client, otherwise loop
1713 * XXX: If this is final stream and
1714 * stream->rdNext != data->buffStop, buffered
1715 * data is next request (server pipelining)?
1717 if(data->contentLen == 0) {
1718 stream->wrNext = stream->stop = stream->rdNext;
1719 stream->isClosed = TRUE;
1728 * If this header marked the beginning of a new
1729 * request, return role information to caller.
1737 SetError(stream, status);
1745 *----------------------------------------------------------------------
1749 * Creates a stream to read or write from an open ipcFd.
1750 * The stream performs reads/writes of up to bufflen bytes.
1752 *----------------------------------------------------------------------
1754 static FCGX_Stream *NewStream(
1755 FCGX_Request *reqDataPtr, int bufflen, int isReader, int streamType)
1758 * XXX: It would be a lot cleaner to have a NewStream that only
1759 * knows about the type FCGX_Stream, with all other
1760 * necessary data passed in. It appears that not just
1761 * data and the two procs are needed for initializing stream,
1762 * but also data->buff and data->buffStop. This has implications
1763 * for procs that want to swap buffers, too.
1765 FCGX_Stream *stream = (FCGX_Stream *)Malloc(sizeof(FCGX_Stream));
1766 FCGX_Stream_Data *data = (FCGX_Stream_Data *)Malloc(sizeof(FCGX_Stream_Data));
1767 data->reqDataPtr = reqDataPtr;
1768 bufflen = AlignInt8(min(max(bufflen, 32), FCGI_MAX_LENGTH + 1));
1769 data->bufflen = bufflen;
1770 data->mBuff = (unsigned char *)Malloc(bufflen);
1771 data->buff = AlignPtr8(data->mBuff);
1772 if(data->buff != data->mBuff) {
1776 data->buffStop = data->buff;
1778 data->buffStop = data->buff + data->bufflen;
1780 data->type = streamType;
1781 data->eorStop = FALSE;
1783 data->contentLen = 0;
1784 data->paddingLen = 0;
1785 data->isAnythingWritten = FALSE;
1786 data->rawWrite = FALSE;
1788 stream->data = data;
1789 stream->isReader = isReader;
1790 stream->isClosed = FALSE;
1791 stream->wasFCloseCalled = FALSE;
1792 stream->FCGI_errno = 0;
1794 stream->fillBuffProc = FillBuffProc;
1795 stream->emptyBuffProc = NULL;
1796 stream->rdNext = data->buff;
1797 stream->stop = stream->rdNext;
1798 stream->stopUnget = data->buff;
1799 stream->wrNext = stream->stop;
1801 stream->fillBuffProc = NULL;
1802 stream->emptyBuffProc = EmptyBuffProc;
1803 stream->wrNext = data->buff + sizeof(FCGI_Header);
1804 stream->stop = data->buffStop;
1805 stream->stopUnget = NULL;
1806 stream->rdNext = stream->stop;
1812 *----------------------------------------------------------------------
1814 * FCGX_FreeStream --
1816 * Frees all storage allocated when *streamPtr was created,
1817 * and nulls out *streamPtr.
1819 *----------------------------------------------------------------------
1821 void FCGX_FreeStream(FCGX_Stream **streamPtr)
1823 FCGX_Stream *stream = *streamPtr;
1824 FCGX_Stream_Data *data;
1825 if(stream == NULL) {
1828 data = (FCGX_Stream_Data *)stream->data;
1829 data->reqDataPtr = NULL;
1837 *----------------------------------------------------------------------
1841 * Re-initializes the stream to read data of the specified type.
1843 *----------------------------------------------------------------------
1845 static FCGX_Stream *SetReaderType(FCGX_Stream *stream, int streamType)
1847 FCGX_Stream_Data *data = (FCGX_Stream_Data *)stream->data;
1848 ASSERT(stream->isReader);
1849 data->type = streamType;
1850 data->eorStop = FALSE;
1852 data->contentLen = 0;
1853 data->paddingLen = 0;
1854 stream->wrNext = stream->stop = stream->rdNext;
1855 stream->isClosed = FALSE;
1860 *----------------------------------------------------------------------
1864 * Creates a stream to read streamType records for the given
1865 * request. The stream performs OS reads of up to bufflen bytes.
1867 *----------------------------------------------------------------------
1869 static FCGX_Stream *NewReader(FCGX_Request *reqDataPtr, int bufflen, int streamType)
1871 return NewStream(reqDataPtr, bufflen, TRUE, streamType);
1875 *----------------------------------------------------------------------
1879 * Creates a stream to write streamType FastCGI records, using
1880 * the ipcFd and RequestId contained in *reqDataPtr.
1881 * The stream performs OS writes of up to bufflen bytes.
1883 *----------------------------------------------------------------------
1885 static FCGX_Stream *NewWriter(FCGX_Request *reqDataPtr, int bufflen, int streamType)
1887 return NewStream(reqDataPtr, bufflen, FALSE, streamType);
1891 *----------------------------------------------------------------------
1893 * FCGX_CreateWriter --
1895 * Creates a stream to write streamType FastCGI records, using
1896 * the given ipcFd and request Id. This function is provided
1897 * for use by cgi-fcgi. In order to be defensive against misuse,
1898 * this function leaks a little storage; cgi-fcgi doesn't care.
1900 *----------------------------------------------------------------------
1902 FCGX_Stream *FCGX_CreateWriter(
1908 FCGX_Request *reqDataPtr = (FCGX_Request *)Malloc(sizeof(FCGX_Request));
1909 reqDataPtr->ipcFd = ipcFd;
1910 reqDataPtr->requestId = requestId;
1912 * Suppress writing an FCGI_END_REQUEST record.
1914 reqDataPtr->nWriters = 2;
1915 return NewWriter(reqDataPtr, bufflen, streamType);
1919 *======================================================================
1921 *======================================================================
1925 *----------------------------------------------------------------------
1929 * This routine determines if the process is running as a CGI or
1930 * FastCGI process. The distinction is made by determining whether
1931 * FCGI_LISTENSOCK_FILENO is a listener ipcFd or the end of a
1932 * pipe (ie. standard in).
1935 * TRUE if the process is a CGI process, FALSE if FastCGI.
1937 *----------------------------------------------------------------------
1939 int FCGX_IsCGI(void)
1941 if (isFastCGI != -1) {
1945 if (!libInitialized) {
1946 int rc = FCGX_Init();
1948 /* exit() isn't great, but hey */
1949 exit((rc < 0) ? rc : -rc);
1953 isFastCGI = OS_IsFcgi(FCGI_LISTENSOCK_FILENO);
1959 *----------------------------------------------------------------------
1963 * Finishes the current request from the HTTP server.
1967 * Finishes the request accepted by (and frees any
1968 * storage allocated by) the previous call to FCGX_Accept.
1970 * DO NOT retain pointers to the envp array or any strings
1971 * contained in it (e.g. to the result of calling FCGX_GetParam),
1972 * since these will be freed by the next call to FCGX_Finish
1975 *----------------------------------------------------------------------
1978 void FCGX_Finish(void)
1980 FCGX_Finish_r(&the_request);
1984 *----------------------------------------------------------------------
1988 * Finishes the current request from the HTTP server.
1992 * Finishes the request accepted by (and frees any
1993 * storage allocated by) the previous call to FCGX_Accept.
1995 * DO NOT retain pointers to the envp array or any strings
1996 * contained in it (e.g. to the result of calling FCGX_GetParam),
1997 * since these will be freed by the next call to FCGX_Finish
2000 *----------------------------------------------------------------------
2002 void FCGX_Finish_r(FCGX_Request *reqDataPtr)
2006 if (reqDataPtr == NULL) {
2010 close = !reqDataPtr->keepConnection;
2012 /* This should probably use a 'status' member instead of 'in' */
2013 if (reqDataPtr->in) {
2014 close |= FCGX_FClose(reqDataPtr->err);
2015 close |= FCGX_FClose(reqDataPtr->out);
2016 close |= FCGX_GetError(reqDataPtr->in);
2018 /* discard any remaining data in input stream on persistent connections */
2019 if (!close && !reqDataPtr->in->isClosed && reqDataPtr->keepConnection) {
2020 FCGX_Stream *stream = reqDataPtr->in;
2023 stream->rdNext = stream->stop;
2024 stream->fillBuffProc(stream);
2025 } while (!stream->isClosed);
2027 close |= FCGX_GetError(stream);
2031 FCGX_Free(reqDataPtr, close);
2034 void FCGX_Free(FCGX_Request * request, int close)
2036 if (request == NULL)
2039 FCGX_FreeStream(&request->in);
2040 FCGX_FreeStream(&request->out);
2041 FCGX_FreeStream(&request->err);
2042 FreeParams(&request->paramsPtr);
2045 OS_IpcClose(request->ipcFd, ! request->detached);
2046 request->ipcFd = -1;
2047 request->detached = 0;
2051 int FCGX_OpenSocket(const char *path, int backlog)
2053 int rc = OS_CreateLocalIpcFd(path, backlog);
2054 if (rc == FCGI_LISTENSOCK_FILENO && isFastCGI == 0) {
2055 /* XXX probably need to call OS_LibInit() again for Win */
2061 int FCGX_InitRequest(FCGX_Request *request, int sock, int flags)
2063 memset(request, 0, sizeof(FCGX_Request));
2065 /* @@@ Should check that sock is open and listening */
2066 request->listen_sock = sock;
2068 /* @@@ Should validate against "known" flags */
2069 request->flags = flags;
2071 request->ipcFd = -1;
2077 *----------------------------------------------------------------------
2081 * Initilize the FCGX library. This is called by FCGX_Accept()
2082 * but must be called by the user when using FCGX_Accept_r().
2085 * 0 for successful call.
2087 *----------------------------------------------------------------------
2093 if (libInitialized) {
2097 FCGX_InitRequest(&the_request, FCGI_LISTENSOCK_FILENO, 0);
2099 if (OS_LibInit(NULL) == -1) {
2100 return OS_Errno ? OS_Errno : -9997;
2103 p = getenv("FCGI_WEB_SERVER_ADDRS");
2104 webServerAddressList = p ? StringCopy(p) : NULL;
2111 *----------------------------------------------------------------------
2115 * Accepts a new request from the HTTP server.
2118 * 0 for successful call, -1 for error.
2122 * Finishes the request accepted by (and frees any
2123 * storage allocated by) the previous call to FCGX_Accept.
2124 * Creates input, output, and error streams and
2125 * assigns them to *in, *out, and *err respectively.
2126 * Creates a parameters data structure to be accessed
2127 * via getenv(3) (if assigned to environ) or by FCGX_GetParam
2128 * and assigns it to *envp.
2130 * DO NOT retain pointers to the envp array or any strings
2131 * contained in it (e.g. to the result of calling FCGX_GetParam),
2132 * since these will be freed by the next call to FCGX_Finish
2135 *----------------------------------------------------------------------
2142 FCGX_ParamArray *envp)
2146 if (! libInitialized) {
2153 rc = FCGX_Accept_r(&the_request);
2155 *in = the_request.in;
2156 *out = the_request.out;
2157 *err = the_request.err;
2158 *envp = the_request.envp;
2164 *----------------------------------------------------------------------
2168 * Accepts a new request from the HTTP server.
2171 * 0 for successful call, -1 for error.
2175 * Finishes the request accepted by (and frees any
2176 * storage allocated by) the previous call to FCGX_Accept.
2177 * Creates input, output, and error streams and
2178 * assigns them to *in, *out, and *err respectively.
2179 * Creates a parameters data structure to be accessed
2180 * via getenv(3) (if assigned to environ) or by FCGX_GetParam
2181 * and assigns it to *envp.
2183 * DO NOT retain pointers to the envp array or any strings
2184 * contained in it (e.g. to the result of calling FCGX_GetParam),
2185 * since these will be freed by the next call to FCGX_Finish
2188 *----------------------------------------------------------------------
2190 int FCGX_Accept_r(FCGX_Request *reqDataPtr)
2192 if (!libInitialized) {
2196 /* Finish the current request, if any. */
2197 FCGX_Finish_r(reqDataPtr);
2201 * If a connection isn't open, accept a new connection (blocking).
2202 * If an OS error occurs in accepting the connection,
2203 * return -1 to the caller, who should exit.
2205 if (reqDataPtr->ipcFd < 0) {
2206 int fail_on_intr = reqDataPtr->flags & FCGI_FAIL_ACCEPT_ON_INTR;
2208 reqDataPtr->ipcFd = OS_Accept(reqDataPtr->listen_sock, fail_on_intr, webServerAddressList);
2209 if (reqDataPtr->ipcFd < 0) {
2210 return (errno > 0) ? (0 - errno) : -9999;
2214 * A connection is open. Read from the connection in order to
2215 * get the request's role and environment. If protocol or other
2216 * errors occur, close the connection and try again.
2218 reqDataPtr->isBeginProcessed = FALSE;
2219 reqDataPtr->in = NewReader(reqDataPtr, 8192, 0);
2220 FillBuffProc(reqDataPtr->in);
2221 if(!reqDataPtr->isBeginProcessed) {
2226 switch(reqDataPtr->role) {
2227 case FCGI_RESPONDER:
2228 roleStr = "FCGI_ROLE=RESPONDER";
2230 case FCGI_AUTHORIZER:
2231 roleStr = "FCGI_ROLE=AUTHORIZER";
2234 roleStr = "FCGI_ROLE=FILTER";
2239 reqDataPtr->paramsPtr = NewParams(30);
2240 PutParam(reqDataPtr->paramsPtr, StringCopy(roleStr));
2242 SetReaderType(reqDataPtr->in, FCGI_PARAMS);
2243 if(ReadParams(reqDataPtr->paramsPtr, reqDataPtr->in) >= 0) {
2245 * Finished reading the environment. No errors occurred, so
2246 * leave the connection-retry loop.
2252 * Close the connection and try again.
2255 FCGX_Free(reqDataPtr, 1);
2259 * Build the remaining data structures representing the new
2260 * request and return successfully to the caller.
2262 SetReaderType(reqDataPtr->in, FCGI_STDIN);
2263 reqDataPtr->out = NewWriter(reqDataPtr, 8192, FCGI_STDOUT);
2264 reqDataPtr->err = NewWriter(reqDataPtr, 512, FCGI_STDERR);
2265 reqDataPtr->nWriters = 2;
2266 reqDataPtr->envp = reqDataPtr->paramsPtr->vec;
2271 *----------------------------------------------------------------------
2273 * FCGX_StartFilterData --
2275 * stream is an input stream for a FCGI_FILTER request.
2276 * stream is positioned at EOF on FCGI_STDIN.
2277 * Repositions stream to the start of FCGI_DATA.
2278 * If the preconditions are not met (e.g. FCGI_STDIN has not
2279 * been read to EOF) sets the stream error code to
2280 * FCGX_CALL_SEQ_ERROR.
2283 * 0 for a normal return, < 0 for error
2285 *----------------------------------------------------------------------
2288 int FCGX_StartFilterData(FCGX_Stream *stream)
2290 FCGX_Stream_Data *data = (FCGX_Stream_Data *)stream->data;
2291 if(data->reqDataPtr->role != FCGI_FILTER
2292 || !stream->isReader
2293 || !stream->isClosed
2294 || data->type != FCGI_STDIN) {
2295 SetError(stream, FCGX_CALL_SEQ_ERROR);
2298 SetReaderType(stream, FCGI_DATA);
2303 *----------------------------------------------------------------------
2305 * FCGX_SetExitStatus --
2307 * Sets the exit status for stream's request. The exit status
2308 * is the status code the request would have exited with, had
2309 * the request been run as a CGI program. You can call
2310 * SetExitStatus several times during a request; the last call
2311 * before the request ends determines the value.
2313 *----------------------------------------------------------------------
2316 void FCGX_SetExitStatus(int status, FCGX_Stream *stream)
2318 FCGX_Stream_Data *data = (FCGX_Stream_Data *)stream->data;
2319 data->reqDataPtr->appStatus = status;
2324 FCGX_Attach(FCGX_Request * r)
2326 r->detached = FALSE;
2332 FCGX_Detach(FCGX_Request * r)