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.32 2001/11/21 21:03:35 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->rdNext != stream->stop)
111 return *stream->rdNext++;
112 if(stream->isClosed || !stream->isReader)
114 stream->fillBuffProc(stream);
115 stream->stopUnget = stream->rdNext;
116 if(stream->rdNext != stream->stop)
117 return *stream->rdNext++;
118 ASSERT(stream->isClosed); /* bug in fillBufProc if not */
123 *----------------------------------------------------------------------
127 * Reads up to n consecutive bytes from the input stream
128 * into the character array str. Performs no interpretation
129 * of the input bytes.
132 * Number of bytes read. If result is smaller than n,
133 * the end of input has been reached.
135 *----------------------------------------------------------------------
137 int FCGX_GetStr(char *str, int n, FCGX_Stream *stream)
145 * Fast path: n bytes are already available
147 if(n <= (stream->stop - stream->rdNext)) {
148 memcpy(str, stream->rdNext, n);
153 * General case: stream is closed or buffer fill procedure
158 if(stream->rdNext != stream->stop) {
159 m = min(n - bytesMoved, stream->stop - stream->rdNext);
160 memcpy(str, stream->rdNext, m);
167 if(stream->isClosed || !stream->isReader)
169 stream->fillBuffProc(stream);
170 stream->stopUnget = stream->rdNext;
175 *----------------------------------------------------------------------
179 * Reads up to n-1 consecutive bytes from the input stream
180 * into the character array str. Stops before n-1 bytes
181 * have been read if '\n' or EOF is read. The terminating '\n'
182 * is copied to str. After copying the last byte into str,
183 * stores a '\0' terminator.
186 * NULL if EOF is the first thing read from the input stream,
189 *----------------------------------------------------------------------
191 char *FCGX_GetLine(char *str, int n, FCGX_Stream *stream)
198 c = FCGX_GetChar(stream);
215 *----------------------------------------------------------------------
219 * Pushes back the character c onto the input stream. One
220 * character of pushback is guaranteed once a character
221 * has been read. No pushback is possible for EOF.
224 * Returns c if the pushback succeeded, EOF if not.
226 *----------------------------------------------------------------------
228 int FCGX_UnGetChar(int c, FCGX_Stream *stream) {
232 || stream->rdNext == stream->stopUnget)
235 *stream->rdNext = (unsigned char) c;
240 *----------------------------------------------------------------------
244 * Returns EOF if end-of-file has been detected while reading
245 * from stream; otherwise returns 0.
247 * Note that FCGX_HasSeenEOF(s) may return 0, yet an immediately
248 * following FCGX_GetChar(s) may return EOF. This function, like
249 * the standard C stdio function feof, does not provide the
250 * ability to peek ahead.
253 * EOF if end-of-file has been detected, 0 if not.
255 *----------------------------------------------------------------------
257 int FCGX_HasSeenEOF(FCGX_Stream *stream) {
258 return (stream->isClosed) ? EOF : 0;
262 *----------------------------------------------------------------------
266 * Writes a byte to the output stream.
269 * The byte, or EOF (-1) if an error occurred.
271 *----------------------------------------------------------------------
273 int FCGX_PutChar(int c, FCGX_Stream *stream)
275 if(stream->wrNext != stream->stop)
276 return (*stream->wrNext++ = (unsigned char) c);
277 if(stream->isClosed || stream->isReader)
279 stream->emptyBuffProc(stream, FALSE);
280 if(stream->wrNext != stream->stop)
281 return (*stream->wrNext++ = (unsigned char) c);
282 ASSERT(stream->isClosed); /* bug in emptyBuffProc if not */
287 *----------------------------------------------------------------------
291 * Writes n consecutive bytes from the character array str
292 * into the output stream. Performs no interpretation
293 * of the output bytes.
296 * Number of bytes written (n) for normal return,
297 * EOF (-1) if an error occurred.
299 *----------------------------------------------------------------------
301 int FCGX_PutStr(const char *str, int n, FCGX_Stream *stream)
306 * Fast path: room for n bytes in the buffer
308 if(n <= (stream->stop - stream->wrNext)) {
309 memcpy(stream->wrNext, str, n);
314 * General case: stream is closed or buffer empty procedure
319 if(stream->wrNext != stream->stop) {
320 m = min(n - bytesMoved, stream->stop - stream->wrNext);
321 memcpy(stream->wrNext, str, m);
328 if(stream->isClosed || stream->isReader)
330 stream->emptyBuffProc(stream, FALSE);
335 *----------------------------------------------------------------------
339 * Writes a character string to the output stream.
342 * number of bytes written for normal return,
343 * EOF (-1) if an error occurred.
345 *----------------------------------------------------------------------
347 int FCGX_PutS(const char *str, FCGX_Stream *stream)
349 return FCGX_PutStr(str, strlen(str), stream);
353 *----------------------------------------------------------------------
357 * Performs output formatting and writes the results
358 * to the output stream.
361 * number of bytes written for normal return,
362 * EOF (-1) if an error occurred.
364 *----------------------------------------------------------------------
366 int FCGX_FPrintF(FCGX_Stream *stream, const char *format, ...)
370 va_start(ap, format);
371 result = FCGX_VFPrintF(stream, format, ap);
377 *----------------------------------------------------------------------
381 * Performs output formatting and writes the results
382 * to the output stream.
385 * number of bytes written for normal return,
386 * EOF (-1) if an error occurred.
388 *----------------------------------------------------------------------
391 #define PRINTF_BUFFLEN 100
393 * More than sufficient space for all unmodified conversions
396 #define FMT_BUFFLEN 25
398 * Max size of a format specifier is 1 + 5 + 7 + 7 + 2 + 1 + slop
400 static void CopyAndAdvance(char **destPtr, char **srcPtr, int n);
402 int FCGX_VFPrintF(FCGX_Stream *stream, const char *format, va_list arg)
404 char *f, *fStop, *percentPtr, *p, *fmtBuffPtr, *buffPtr;
405 int op, performedOp, sizeModifier, buffCount = 0, buffLen, specifierLength;
406 int fastPath, n, auxBuffLen = 0, buffReqd, minWidth, precision, exp;
407 char *auxBuffPtr = NULL;
409 char fmtBuff[FMT_BUFFLEN];
410 char buff[PRINTF_BUFFLEN];
415 unsigned unsignedArg;
416 unsigned long uLongArg;
417 unsigned short uShortArg;
418 char *charPtrArg = NULL;
423 double doubleArg = 0.0;
424 LONG_DOUBLE lDoubleArg = 0.0L;
428 fStop = f + strlen(f);
430 percentPtr = (char *)memchr(f, '%', fStop - f);
431 if(percentPtr == NULL) percentPtr = fStop;
432 if(percentPtr != f) {
433 if(FCGX_PutStr(f, percentPtr - f, stream) < 0)
435 streamCount += percentPtr - f;
437 if(f == fStop) break;
441 * The following loop always executes either once or twice.
446 * Fast path: Scan optimistically, hoping that no flags,
447 * minimum field width, or precision are specified.
448 * Use the preallocated buffer, which is large enough
449 * for all fast path cases. If the conversion specifier
450 * is really more complex, run the loop a second time
451 * using the slow path.
452 * Note that fast path execution of %s bypasses the buffer
453 * and %f is not attempted on the fast path due to
454 * its large buffering requirements.
456 op = *(percentPtr + 1);
462 op = *(percentPtr + 2);
463 fmtBuff[1] = (char) sizeModifier;
464 fmtBuff[2] = (char) op;
470 fmtBuff[1] = (char) op;
476 buffLen = PRINTF_BUFFLEN;
479 * Slow path: Scan the conversion specifier and construct
480 * a new format string, compute an upper bound on the
481 * amount of buffering that sprintf will require,
482 * and allocate a larger buffer if necessary.
485 fmtBuffPtr = &fmtBuff[1];
489 n = strspn(p, "-0+ #");
492 CopyAndAdvance(&fmtBuffPtr, &p, n);
494 * Scan minimum field width
496 n = strspn(p, "0123456789");
499 minWidth = va_arg(arg, int);
500 if(abs(minWidth) > 999999)
503 * The following use of strlen rather than the
504 * value returned from sprintf is because SUNOS4
505 * returns a char * instead of an int count.
507 sprintf(fmtBuffPtr, "%d", minWidth);
508 fmtBuffPtr += strlen(fmtBuffPtr);
514 minWidth = strtol(p, NULL, 10);
515 CopyAndAdvance(&fmtBuffPtr, &p, n);
523 CopyAndAdvance(&fmtBuffPtr, &p, 1);
524 n = strspn(p, "0123456789");
527 precision = va_arg(arg, int);
528 if(precision < 0) precision = 0;
529 if(precision > 999999)
532 * The following use of strlen rather than the
533 * value returned from sprintf is because SUNOS4
534 * returns a char * instead of an int count.
536 sprintf(fmtBuffPtr, "%d", precision);
537 fmtBuffPtr += strlen(fmtBuffPtr);
543 precision = strtol(p, NULL, 10);
544 CopyAndAdvance(&fmtBuffPtr, &p, n);
552 * Scan size modifier and conversion operation
559 CopyAndAdvance(&fmtBuffPtr, &p, 1);
566 CopyAndAdvance(&fmtBuffPtr, &p, 1);
567 ASSERT(fmtBuffPtr - fmtBuff < FMT_BUFFLEN);
569 specifierLength = p - percentPtr;
571 * Bound the required buffer size. For s and f
572 * conversions this requires examining the argument.
583 buffReqd = max(precision, 46);
586 charPtrArg = va_arg(arg, char *);
587 if (!charPtrArg) charPtrArg = "(null)";
588 if(precision == -1) {
589 buffReqd = strlen(charPtrArg);
591 p = (char *)memchr(charPtrArg, '\0', precision);
593 (p == NULL) ? precision : p - charPtrArg;
597 switch(sizeModifier) {
599 doubleArg = va_arg(arg, double);
600 frexp(doubleArg, &exp);
603 lDoubleArg = va_arg(arg, LONG_DOUBLE);
604 /* XXX Need to check for the presence of
605 * frexpl() and use it if available */
606 frexp((double) lDoubleArg, &exp);
611 if(precision == -1) precision = 6;
612 buffReqd = precision + 3 + ((exp > 0) ? exp/3 : 0);
618 if(precision == -1) precision = 6;
619 buffReqd = precision + 8;
627 buffReqd = max(buffReqd + 10, minWidth);
629 * Allocate the buffer
631 if(buffReqd <= PRINTF_BUFFLEN) {
633 buffLen = PRINTF_BUFFLEN;
635 if(auxBuffPtr == NULL || buffReqd > auxBuffLen) {
636 if(auxBuffPtr != NULL) free(auxBuffPtr);
637 auxBuffPtr = (char *)Malloc(buffReqd);
638 auxBuffLen = buffReqd;
639 if(auxBuffPtr == NULL)
642 buffPtr = auxBuffPtr;
643 buffLen = auxBuffLen;
647 * This giant switch statement requires the following variables
648 * to be set up: op, sizeModifier, arg, buffPtr, fmtBuff.
649 * When fastPath == FALSE and op == 's' or 'f', the argument
650 * has been read into charPtrArg, doubleArg, or lDoubleArg.
651 * The statement produces the boolean performedOp, TRUE iff
652 * the op/sizeModifier were executed and argument consumed;
653 * if performedOp, the characters written into buffPtr[]
654 * and the character count buffCount (== EOF meaning error).
656 * The switch cases are arranged in the same order as in the
657 * description of fprintf in section 15.11 of Harbison and Steele.
663 switch(sizeModifier) {
665 intArg = va_arg(arg, int);
666 sprintf(buffPtr, fmtBuff, intArg);
667 buffCount = strlen(buffPtr);
670 longArg = va_arg(arg, long);
671 sprintf(buffPtr, fmtBuff, longArg);
672 buffCount = strlen(buffPtr);
675 shortArg = (short) va_arg(arg, int);
676 sprintf(buffPtr, fmtBuff, shortArg);
677 buffCount = strlen(buffPtr);
687 switch(sizeModifier) {
689 unsignedArg = va_arg(arg, unsigned);
690 sprintf(buffPtr, fmtBuff, unsignedArg);
691 buffCount = strlen(buffPtr);
694 uLongArg = va_arg(arg, unsigned long);
695 sprintf(buffPtr, fmtBuff, uLongArg);
696 buffCount = strlen(buffPtr);
699 uShortArg = (unsigned short) va_arg(arg, int);
700 sprintf(buffPtr, fmtBuff, uShortArg);
701 buffCount = strlen(buffPtr);
708 switch(sizeModifier) {
710 intArg = va_arg(arg, int);
711 sprintf(buffPtr, fmtBuff, intArg);
712 buffCount = strlen(buffPtr);
716 * XXX: Allowed by ISO C Amendment 1, but
717 * many platforms don't yet support wint_t
725 switch(sizeModifier) {
728 buffPtr = va_arg(arg, char *);
729 buffCount = strlen(buffPtr);
730 buffLen = buffCount + 1;
732 sprintf(buffPtr, fmtBuff, charPtrArg);
733 buffCount = strlen(buffPtr);
738 * XXX: Don't know how to convert a sequence
739 * of wide characters into a byte stream, or
740 * even how to predict the buffering required.
748 if(sizeModifier != ' ')
750 voidPtrArg = va_arg(arg, void *);
751 sprintf(buffPtr, fmtBuff, voidPtrArg);
752 buffCount = strlen(buffPtr);
755 switch(sizeModifier) {
757 intPtrArg = va_arg(arg, int *);
758 *intPtrArg = streamCount;
761 longPtrArg = va_arg(arg, long *);
762 *longPtrArg = streamCount;
765 shortPtrArg = (short *) va_arg(arg, short *);
766 *shortPtrArg = (short) streamCount;
778 switch(sizeModifier) {
780 sprintf(buffPtr, fmtBuff, doubleArg);
781 buffCount = strlen(buffPtr);
784 sprintf(buffPtr, fmtBuff, lDoubleArg);
785 buffCount = strlen(buffPtr);
795 switch(sizeModifier) {
797 doubleArg = va_arg(arg, double);
798 sprintf(buffPtr, fmtBuff, doubleArg);
799 buffCount = strlen(buffPtr);
802 lDoubleArg = va_arg(arg, LONG_DOUBLE);
803 sprintf(buffPtr, fmtBuff, lDoubleArg);
804 buffCount = strlen(buffPtr);
811 if(sizeModifier != ' ')
822 if(performedOp) break;
827 ASSERT(buffCount < buffLen);
829 if(FCGX_PutStr(buffPtr, buffCount, stream) < 0)
831 streamCount += buffCount;
832 } else if(buffCount < 0) {
835 f += specifierLength;
836 } /* while(f != fStop) */
841 if(auxBuffPtr != NULL) free(auxBuffPtr);
846 * Copy n characters from *srcPtr to *destPtr, then increment
847 * both *srcPtr and *destPtr by n.
849 static void CopyAndAdvance(char **destPtr, char **srcPtr, int n)
851 char *dest = *destPtr;
854 for (i = 0; i < n; i++)
861 *----------------------------------------------------------------------
865 * Flushes any buffered output.
867 * Server-push is a legitimate application of FCGX_FFlush.
868 * Otherwise, FCGX_FFlush is not very useful, since FCGX_Accept
869 * does it implicitly. FCGX_FFlush may reduce performance
870 * by increasing the total number of operating system calls
871 * the application makes.
874 * EOF (-1) if an error occurred.
876 *----------------------------------------------------------------------
878 int FCGX_FFlush(FCGX_Stream *stream)
880 if(stream->isClosed || stream->isReader)
882 stream->emptyBuffProc(stream, FALSE);
883 return (stream->isClosed) ? -1 : 0;
887 *----------------------------------------------------------------------
891 * Performs FCGX_FFlush and closes the stream.
893 * This is not a very useful operation, since FCGX_Accept
894 * does it implicitly. Closing the out stream before the
895 * err stream results in an extra write if there's nothing
896 * in the err stream, and therefore reduces performance.
899 * EOF (-1) if an error occurred.
901 *----------------------------------------------------------------------
903 int FCGX_FClose(FCGX_Stream *stream)
905 if (stream == NULL) return 0;
907 if(!stream->wasFCloseCalled) {
908 if(!stream->isReader) {
909 stream->emptyBuffProc(stream, TRUE);
911 stream->wasFCloseCalled = TRUE;
912 stream->isClosed = TRUE;
913 if(stream->isReader) {
914 stream->wrNext = stream->stop = stream->rdNext;
916 stream->rdNext = stream->stop = stream->wrNext;
919 return (stream->FCGI_errno == 0) ? 0 : EOF;
923 *----------------------------------------------------------------------
927 * An error has occurred; save the error code in the stream
928 * for diagnostic purposes and set the stream state so that
929 * reads return EOF and writes have no effect.
931 *----------------------------------------------------------------------
933 static void SetError(FCGX_Stream *stream, int FCGI_errno)
936 * Preserve only the first error.
938 if(stream->FCGI_errno == 0) {
939 stream->FCGI_errno = FCGI_errno;
940 stream->isClosed = TRUE;
945 *----------------------------------------------------------------------
949 * Return the stream error code. 0 means no error, > 0
950 * is an errno(2) error, < 0 is an FCGX_errno error.
952 *----------------------------------------------------------------------
954 int FCGX_GetError(FCGX_Stream *stream) {
955 return stream->FCGI_errno;
959 *----------------------------------------------------------------------
963 * Clear the stream error code and end-of-file indication.
965 *----------------------------------------------------------------------
967 void FCGX_ClearError(FCGX_Stream *stream) {
968 stream->FCGI_errno = 0;
970 * stream->isClosed = FALSE;
971 * XXX: should clear isClosed but work is needed to make it safe
972 * to do so. For example, if an application calls FClose, gets
973 * an I/O error on the write, calls ClearError and retries
974 * the FClose, FClose (really EmptyBuffProc) will write a second
975 * EOF record. If an application calls PutChar instead of FClose
976 * after the ClearError, the application will write more data.
977 * The stream's state must discriminate between various states
978 * of the stream that are now all lumped under isClosed.
983 *======================================================================
985 *======================================================================
989 * A vector of pointers representing the parameters received
990 * by a FastCGI application server, with the vector's length
991 * and last valid element so adding new parameters is efficient.
994 typedef struct Params {
995 FCGX_ParamArray vec; /* vector of strings */
996 int length; /* number of string vec can hold */
997 char **cur; /* current item in vec; *cur == NULL */
999 typedef Params *ParamsPtr;
1002 *----------------------------------------------------------------------
1006 * Creates a new Params structure.
1009 * Pointer to the new structure.
1011 *----------------------------------------------------------------------
1013 static ParamsPtr NewParams(int length)
1016 result = (Params *)Malloc(sizeof(Params));
1017 result->vec = (char **)Malloc(length * sizeof(char *));
1018 result->length = length;
1019 result->cur = result->vec;
1020 *result->cur = NULL;
1025 *----------------------------------------------------------------------
1029 * Frees a Params structure and all the parameters it contains.
1032 * env becomes invalid.
1034 *----------------------------------------------------------------------
1036 static void FreeParams(ParamsPtr *paramsPtrPtr)
1038 ParamsPtr paramsPtr = *paramsPtrPtr;
1040 if(paramsPtr == NULL) {
1043 for (p = paramsPtr->vec; p < paramsPtr->cur; p++) {
1046 free(paramsPtr->vec);
1048 *paramsPtrPtr = NULL;
1052 *----------------------------------------------------------------------
1056 * Add a name/value pair to a Params structure.
1062 * Parameters structure updated.
1064 *----------------------------------------------------------------------
1066 static void PutParam(ParamsPtr paramsPtr, char *nameValue)
1070 *paramsPtr->cur++ = nameValue;
1071 size = paramsPtr->cur - paramsPtr->vec;
1072 if(size >= paramsPtr->length) {
1073 paramsPtr->length *= 2;
1074 paramsPtr->vec = (FCGX_ParamArray)realloc(paramsPtr->vec, paramsPtr->length * sizeof(char *));
1075 paramsPtr->cur = paramsPtr->vec + size;
1077 *paramsPtr->cur = NULL;
1081 *----------------------------------------------------------------------
1083 * FCGX_GetParam -- obtain value of FCGI parameter in environment
1087 * Value bound to name, NULL if name not present in the
1088 * environment envp. Caller must not mutate the result
1089 * or retain it past the end of this request.
1091 *----------------------------------------------------------------------
1093 char *FCGX_GetParam(const char *name, FCGX_ParamArray envp)
1098 if (name == NULL || envp == NULL) return NULL;
1102 for (p = envp; *p; ++p) {
1103 if((strncmp(name, *p, len) == 0) && ((*p)[len] == '=')) {
1111 *----------------------------------------------------------------------
1113 * Start of FastCGI-specific code
1115 *----------------------------------------------------------------------
1119 *----------------------------------------------------------------------
1123 * Reads FastCGI name-value pairs from stream until EOF. Converts
1124 * each pair to name=value format and adds it to Params structure.
1126 *----------------------------------------------------------------------
1128 static int ReadParams(Params *paramsPtr, FCGX_Stream *stream)
1130 int nameLen, valueLen;
1131 unsigned char lenBuff[3];
1134 while((nameLen = FCGX_GetChar(stream)) != EOF) {
1136 * Read name length (one or four bytes) and value length
1137 * (one or four bytes) from stream.
1139 if((nameLen & 0x80) != 0) {
1140 if(FCGX_GetStr((char *) &lenBuff[0], 3, stream) != 3) {
1141 SetError(stream, FCGX_PARAMS_ERROR);
1144 nameLen = ((nameLen & 0x7f) << 24) + (lenBuff[0] << 16)
1145 + (lenBuff[1] << 8) + lenBuff[2];
1147 if((valueLen = FCGX_GetChar(stream)) == EOF) {
1148 SetError(stream, FCGX_PARAMS_ERROR);
1151 if((valueLen & 0x80) != 0) {
1152 if(FCGX_GetStr((char *) &lenBuff[0], 3, stream) != 3) {
1153 SetError(stream, FCGX_PARAMS_ERROR);
1156 valueLen = ((valueLen & 0x7f) << 24) + (lenBuff[0] << 16)
1157 + (lenBuff[1] << 8) + lenBuff[2];
1160 * nameLen and valueLen are now valid; read the name and value
1161 * from stream and construct a standard environment entry.
1163 nameValue = (char *)Malloc(nameLen + valueLen + 2);
1164 if(FCGX_GetStr(nameValue, nameLen, stream) != nameLen) {
1165 SetError(stream, FCGX_PARAMS_ERROR);
1169 *(nameValue + nameLen) = '=';
1170 if(FCGX_GetStr(nameValue + nameLen + 1, valueLen, stream)
1172 SetError(stream, FCGX_PARAMS_ERROR);
1176 *(nameValue + nameLen + valueLen + 1) = '\0';
1177 PutParam(paramsPtr, nameValue);
1183 *----------------------------------------------------------------------
1187 * Constructs an FCGI_Header struct.
1189 *----------------------------------------------------------------------
1191 static FCGI_Header MakeHeader(
1198 ASSERT(contentLength >= 0 && contentLength <= FCGI_MAX_LENGTH);
1199 ASSERT(paddingLength >= 0 && paddingLength <= 0xff);
1200 header.version = FCGI_VERSION_1;
1201 header.type = (unsigned char) type;
1202 header.requestIdB1 = (unsigned char) ((requestId >> 8) & 0xff);
1203 header.requestIdB0 = (unsigned char) ((requestId ) & 0xff);
1204 header.contentLengthB1 = (unsigned char) ((contentLength >> 8) & 0xff);
1205 header.contentLengthB0 = (unsigned char) ((contentLength ) & 0xff);
1206 header.paddingLength = (unsigned char) paddingLength;
1207 header.reserved = 0;
1212 *----------------------------------------------------------------------
1214 * MakeEndRequestBody --
1216 * Constructs an FCGI_EndRequestBody struct.
1218 *----------------------------------------------------------------------
1220 static FCGI_EndRequestBody MakeEndRequestBody(
1224 FCGI_EndRequestBody body;
1225 body.appStatusB3 = (unsigned char) ((appStatus >> 24) & 0xff);
1226 body.appStatusB2 = (unsigned char) ((appStatus >> 16) & 0xff);
1227 body.appStatusB1 = (unsigned char) ((appStatus >> 8) & 0xff);
1228 body.appStatusB0 = (unsigned char) ((appStatus ) & 0xff);
1229 body.protocolStatus = (unsigned char) protocolStatus;
1230 memset(body.reserved, 0, sizeof(body.reserved));
1235 *----------------------------------------------------------------------
1237 * MakeUnknownTypeBody --
1239 * Constructs an FCGI_MakeUnknownTypeBody struct.
1241 *----------------------------------------------------------------------
1243 static FCGI_UnknownTypeBody MakeUnknownTypeBody(
1246 FCGI_UnknownTypeBody body;
1247 body.type = (unsigned char) type;
1248 memset(body.reserved, 0, sizeof(body.reserved));
1253 *----------------------------------------------------------------------
1257 * Returns the smallest integer greater than or equal to n
1258 * that's a multiple of 8.
1260 *----------------------------------------------------------------------
1262 static int AlignInt8(unsigned n) {
1263 return (n + 7) & (UINT_MAX - 7);
1267 *----------------------------------------------------------------------
1271 * Returns the smallest pointer greater than or equal to p
1272 * that's a multiple of 8.
1274 *----------------------------------------------------------------------
1276 static unsigned char *AlignPtr8(unsigned char *p) {
1277 unsigned long u = (unsigned long) p;
1278 u = ((u + 7) & (ULONG_MAX - 7)) - u;
1284 * State associated with a stream
1286 typedef struct FCGX_Stream_Data {
1287 unsigned char *buff; /* buffer after alignment */
1288 int bufflen; /* number of bytes buff can store */
1289 unsigned char *mBuff; /* buffer as returned by Malloc */
1290 unsigned char *buffStop; /* reader: last valid byte + 1 of entire buffer.
1291 * stop generally differs from buffStop for
1292 * readers because of record structure.
1293 * writer: buff + bufflen */
1294 int type; /* reader: FCGI_PARAMS or FCGI_STDIN
1295 * writer: FCGI_STDOUT or FCGI_STDERR */
1296 int eorStop; /* reader: stop stream at end-of-record */
1297 int skip; /* reader: don't deliver content bytes */
1298 int contentLen; /* reader: bytes of unread content */
1299 int paddingLen; /* reader: bytes of unread padding */
1300 int isAnythingWritten; /* writer: data has been written to ipcFd */
1301 int rawWrite; /* writer: write data without stream headers */
1302 FCGX_Request *reqDataPtr; /* request data not specific to one stream */
1306 *----------------------------------------------------------------------
1308 * WriteCloseRecords --
1310 * Writes an EOF record for the stream content if necessary.
1311 * If this is the last writer to close, writes an FCGI_END_REQUEST
1314 *----------------------------------------------------------------------
1316 static void WriteCloseRecords(struct FCGX_Stream *stream)
1318 FCGX_Stream_Data *data = (FCGX_Stream_Data *)stream->data;
1320 * Enter rawWrite mode so final records won't be encapsulated as
1323 data->rawWrite = TRUE;
1325 * Generate EOF for stream content if needed.
1327 if(!(data->type == FCGI_STDERR
1328 && stream->wrNext == data->buff
1329 && !data->isAnythingWritten)) {
1331 header = MakeHeader(data->type, data->reqDataPtr->requestId, 0, 0);
1332 FCGX_PutStr((char *) &header, sizeof(header), stream);
1335 * Generate FCGI_END_REQUEST record if needed.
1337 if(data->reqDataPtr->nWriters == 1) {
1338 FCGI_EndRequestRecord endRequestRecord;
1339 endRequestRecord.header = MakeHeader(FCGI_END_REQUEST,
1340 data->reqDataPtr->requestId,
1341 sizeof(endRequestRecord.body), 0);
1342 endRequestRecord.body = MakeEndRequestBody(
1343 data->reqDataPtr->appStatus, FCGI_REQUEST_COMPLETE);
1344 FCGX_PutStr((char *) &endRequestRecord,
1345 sizeof(endRequestRecord), stream);
1347 data->reqDataPtr->nWriters--;
1352 static int write_it_all(int fd, char *buf, int len)
1357 wrote = OS_Write(fd, buf, len);
1367 *----------------------------------------------------------------------
1371 * Encapsulates any buffered stream content in a FastCGI
1372 * record. Writes the data, making the buffer empty.
1374 *----------------------------------------------------------------------
1376 static void EmptyBuffProc(struct FCGX_Stream *stream, int doClose)
1378 FCGX_Stream_Data *data = (FCGX_Stream_Data *)stream->data;
1381 * If the buffer contains stream data, fill in the header.
1382 * Pad the record to a multiple of 8 bytes in length. Padding
1383 * can't overflow the buffer because the buffer is a multiple
1384 * of 8 bytes in length. If the buffer contains no stream
1385 * data, reclaim the space reserved for the header.
1387 if(!data->rawWrite) {
1388 cLen = stream->wrNext - data->buff - sizeof(FCGI_Header);
1390 eLen = AlignInt8(cLen);
1392 * Giving the padding a well-defined value keeps Purify happy.
1394 memset(stream->wrNext, 0, eLen - cLen);
1395 stream->wrNext += eLen - cLen;
1396 *((FCGI_Header *) data->buff)
1397 = MakeHeader(data->type,
1398 data->reqDataPtr->requestId, cLen, eLen - cLen);
1400 stream->wrNext = data->buff;
1404 WriteCloseRecords(stream);
1406 if (stream->wrNext != data->buff) {
1407 data->isAnythingWritten = TRUE;
1408 if (write_it_all(data->reqDataPtr->ipcFd, (char *)data->buff, stream->wrNext - data->buff) < 0) {
1409 SetError(stream, OS_Errno);
1412 stream->wrNext = data->buff;
1415 * The buffer is empty.
1417 if(!data->rawWrite) {
1418 stream->wrNext += sizeof(FCGI_Header);
1423 * Return codes for Process* functions
1425 #define STREAM_RECORD 0
1427 #define BEGIN_RECORD 2
1428 #define MGMT_RECORD 3
1431 *----------------------------------------------------------------------
1433 * ProcessManagementRecord --
1435 * Reads and responds to a management record. The only type of
1436 * management record this library understands is FCGI_GET_VALUES.
1437 * The only variables that this library's FCGI_GET_VALUES
1438 * understands are FCGI_MAX_CONNS, FCGI_MAX_REQS, and FCGI_MPXS_CONNS.
1439 * Ignore other FCGI_GET_VALUES variables; respond to other
1440 * management records with a FCGI_UNKNOWN_TYPE record.
1442 *----------------------------------------------------------------------
1444 static int ProcessManagementRecord(int type, FCGX_Stream *stream)
1446 FCGX_Stream_Data *data = (FCGX_Stream_Data *)stream->data;
1447 ParamsPtr paramsPtr = NewParams(3);
1449 char response[64]; /* 64 = 8 + 3*(1+1+14+1)* + padding */
1450 char *responseP = &response[FCGI_HEADER_LEN];
1451 char *name, value = '\0';
1453 if(type == FCGI_GET_VALUES) {
1454 ReadParams(paramsPtr, stream);
1455 if((FCGX_GetError(stream) != 0) || (data->contentLen != 0)) {
1456 FreeParams(¶msPtr);
1457 return FCGX_PROTOCOL_ERROR;
1459 for (pPtr = paramsPtr->vec; pPtr < paramsPtr->cur; pPtr++) {
1461 *(strchr(name, '=')) = '\0';
1462 if(strcmp(name, FCGI_MAX_CONNS) == 0) {
1464 } else if(strcmp(name, FCGI_MAX_REQS) == 0) {
1466 } else if(strcmp(name, FCGI_MPXS_CONNS) == 0) {
1473 sprintf(responseP, "%c%c%s%c", len, 1, name, value);
1474 responseP += len + 3;
1477 len = responseP - &response[FCGI_HEADER_LEN];
1478 paddedLen = AlignInt8(len);
1479 *((FCGI_Header *) response)
1480 = MakeHeader(FCGI_GET_VALUES_RESULT, FCGI_NULL_REQUEST_ID,
1481 len, paddedLen - len);
1482 FreeParams(¶msPtr);
1484 paddedLen = len = sizeof(FCGI_UnknownTypeBody);
1485 ((FCGI_UnknownTypeRecord *) response)->header
1486 = MakeHeader(FCGI_UNKNOWN_TYPE, FCGI_NULL_REQUEST_ID,
1488 ((FCGI_UnknownTypeRecord *) response)->body
1489 = MakeUnknownTypeBody(type);
1491 if (write_it_all(data->reqDataPtr->ipcFd, response, FCGI_HEADER_LEN + paddedLen) < 0) {
1492 SetError(stream, OS_Errno);
1500 *----------------------------------------------------------------------
1502 * ProcessBeginRecord --
1504 * Reads an FCGI_BEGIN_REQUEST record.
1507 * BEGIN_RECORD for normal return. FCGX_PROTOCOL_ERROR for
1508 * protocol error. SKIP for attempt to multiplex
1509 * connection. -1 for error from write (errno in stream).
1512 * In case of BEGIN_RECORD return, stores requestId, role,
1513 * keepConnection values, and sets isBeginProcessed = TRUE.
1515 *----------------------------------------------------------------------
1517 static int ProcessBeginRecord(int requestId, FCGX_Stream *stream)
1519 FCGX_Stream_Data *data = (FCGX_Stream_Data *)stream->data;
1520 FCGI_BeginRequestBody body;
1521 if(requestId == 0 || data->contentLen != sizeof(body)) {
1522 return FCGX_PROTOCOL_ERROR;
1524 if(data->reqDataPtr->isBeginProcessed) {
1526 * The Web server is multiplexing the connection. This library
1527 * doesn't know how to handle multiplexing, so respond with
1528 * FCGI_END_REQUEST{protocolStatus = FCGI_CANT_MPX_CONN}
1530 FCGI_EndRequestRecord endRequestRecord;
1531 endRequestRecord.header = MakeHeader(FCGI_END_REQUEST,
1532 requestId, sizeof(endRequestRecord.body), 0);
1533 endRequestRecord.body
1534 = MakeEndRequestBody(0, FCGI_CANT_MPX_CONN);
1535 if (write_it_all(data->reqDataPtr->ipcFd, (char *)&endRequestRecord, sizeof(endRequestRecord)) < 0) {
1536 SetError(stream, OS_Errno);
1543 * Accept this new request. Read the record body.
1545 data->reqDataPtr->requestId = requestId;
1546 if(FCGX_GetStr((char *) &body, sizeof(body), stream)
1548 return FCGX_PROTOCOL_ERROR;
1550 data->reqDataPtr->keepConnection = (body.flags & FCGI_KEEP_CONN);
1551 data->reqDataPtr->role = (body.roleB1 << 8) + body.roleB0;
1552 data->reqDataPtr->isBeginProcessed = TRUE;
1553 return BEGIN_RECORD;
1557 *----------------------------------------------------------------------
1561 * Interprets FCGI_Header. Processes FCGI_BEGIN_REQUEST and
1562 * management records here; extracts information from stream
1563 * records (FCGI_PARAMS, FCGI_STDIN) into stream.
1566 * >= 0 for a normal return, < 0 for error
1569 * XXX: Many (more than there used to be).
1570 * If !stream->isRequestIdSet, ProcessHeader initializes
1571 * stream->requestId from header and sets stream->isRequestIdSet
1572 * to TRUE. ProcessHeader also sets stream->contentLen to header's
1573 * contentLength, and sets stream->paddingLen to the header's
1576 *----------------------------------------------------------------------
1578 static int ProcessHeader(FCGI_Header header, FCGX_Stream *stream)
1580 FCGX_Stream_Data *data = (FCGX_Stream_Data *)stream->data;
1582 if(header.version != FCGI_VERSION_1) {
1583 return FCGX_UNSUPPORTED_VERSION;
1585 requestId = (header.requestIdB1 << 8)
1586 + header.requestIdB0;
1587 data->contentLen = (header.contentLengthB1 << 8)
1588 + header.contentLengthB0;
1589 data->paddingLen = header.paddingLength;
1590 if(header.type == FCGI_BEGIN_REQUEST) {
1591 return ProcessBeginRecord(requestId, stream);
1593 if(requestId == FCGI_NULL_REQUEST_ID) {
1594 return ProcessManagementRecord(header.type, stream);
1596 if(requestId != data->reqDataPtr->requestId) {
1599 if(header.type != data->type) {
1600 return FCGX_PROTOCOL_ERROR;
1602 return STREAM_RECORD;
1606 *----------------------------------------------------------------------
1610 * Reads bytes from the ipcFd, supplies bytes to a stream client.
1612 *----------------------------------------------------------------------
1614 static void FillBuffProc(FCGX_Stream *stream)
1616 FCGX_Stream_Data *data = (FCGX_Stream_Data *)stream->data;
1623 * If data->buff is empty, do a read.
1625 if(stream->rdNext == data->buffStop) {
1626 count = OS_Read(data->reqDataPtr->ipcFd, (char *)data->buff,
1629 SetError(stream, (count == 0 ? FCGX_PROTOCOL_ERROR : OS_Errno));
1632 stream->rdNext = data->buff;
1633 data->buffStop = data->buff + count;
1636 * Now data->buff is not empty. If the current record contains
1637 * more content bytes, deliver all that are present in data->buff.
1639 if(data->contentLen > 0) {
1640 count = min(data->contentLen, data->buffStop - stream->rdNext);
1641 data->contentLen -= count;
1643 stream->wrNext = stream->stop = stream->rdNext + count;
1646 stream->rdNext += count;
1647 if(data->contentLen > 0) {
1655 * If the current record (whose content has been fully consumed by
1656 * the client) was padded, skip over the padding bytes.
1658 if(data->paddingLen > 0) {
1659 count = min(data->paddingLen, data->buffStop - stream->rdNext);
1660 data->paddingLen -= count;
1661 stream->rdNext += count;
1662 if(data->paddingLen > 0) {
1667 * All done with the current record, including the padding.
1668 * If we're in a recursive call from ProcessHeader, deliver EOF.
1671 stream->stop = stream->rdNext;
1672 stream->isClosed = TRUE;
1676 * Fill header with bytes from the input buffer.
1678 count = min((int)sizeof(header) - headerLen,
1679 data->buffStop - stream->rdNext);
1680 memcpy(((char *)(&header)) + headerLen, stream->rdNext, count);
1682 stream->rdNext += count;
1683 if(headerLen < sizeof(header)) {
1688 * Interpret header. eorStop prevents ProcessHeader from reading
1689 * past the end-of-record when using stream to read content.
1691 data->eorStop = TRUE;
1692 stream->stop = stream->rdNext;
1693 status = ProcessHeader(header, stream);
1694 data->eorStop = FALSE;
1695 stream->isClosed = FALSE;
1699 * If this stream record header marked the end of stream
1700 * data deliver EOF to the stream client, otherwise loop
1703 * XXX: If this is final stream and
1704 * stream->rdNext != data->buffStop, buffered
1705 * data is next request (server pipelining)?
1707 if(data->contentLen == 0) {
1708 stream->wrNext = stream->stop = stream->rdNext;
1709 stream->isClosed = TRUE;
1718 * If this header marked the beginning of a new
1719 * request, return role information to caller.
1727 SetError(stream, status);
1735 *----------------------------------------------------------------------
1739 * Creates a stream to read or write from an open ipcFd.
1740 * The stream performs reads/writes of up to bufflen bytes.
1742 *----------------------------------------------------------------------
1744 static FCGX_Stream *NewStream(
1745 FCGX_Request *reqDataPtr, int bufflen, int isReader, int streamType)
1748 * XXX: It would be a lot cleaner to have a NewStream that only
1749 * knows about the type FCGX_Stream, with all other
1750 * necessary data passed in. It appears that not just
1751 * data and the two procs are needed for initializing stream,
1752 * but also data->buff and data->buffStop. This has implications
1753 * for procs that want to swap buffers, too.
1755 FCGX_Stream *stream = (FCGX_Stream *)Malloc(sizeof(FCGX_Stream));
1756 FCGX_Stream_Data *data = (FCGX_Stream_Data *)Malloc(sizeof(FCGX_Stream_Data));
1757 data->reqDataPtr = reqDataPtr;
1758 bufflen = AlignInt8(min(max(bufflen, 32), FCGI_MAX_LENGTH + 1));
1759 data->bufflen = bufflen;
1760 data->mBuff = (unsigned char *)Malloc(bufflen);
1761 data->buff = AlignPtr8(data->mBuff);
1762 if(data->buff != data->mBuff) {
1766 data->buffStop = data->buff;
1768 data->buffStop = data->buff + data->bufflen;
1770 data->type = streamType;
1771 data->eorStop = FALSE;
1773 data->contentLen = 0;
1774 data->paddingLen = 0;
1775 data->isAnythingWritten = FALSE;
1776 data->rawWrite = FALSE;
1778 stream->data = data;
1779 stream->isReader = isReader;
1780 stream->isClosed = FALSE;
1781 stream->wasFCloseCalled = FALSE;
1782 stream->FCGI_errno = 0;
1784 stream->fillBuffProc = FillBuffProc;
1785 stream->emptyBuffProc = NULL;
1786 stream->rdNext = data->buff;
1787 stream->stop = stream->rdNext;
1788 stream->stopUnget = data->buff;
1789 stream->wrNext = stream->stop;
1791 stream->fillBuffProc = NULL;
1792 stream->emptyBuffProc = EmptyBuffProc;
1793 stream->wrNext = data->buff + sizeof(FCGI_Header);
1794 stream->stop = data->buffStop;
1795 stream->stopUnget = NULL;
1796 stream->rdNext = stream->stop;
1802 *----------------------------------------------------------------------
1804 * FCGX_FreeStream --
1806 * Frees all storage allocated when *streamPtr was created,
1807 * and nulls out *streamPtr.
1809 *----------------------------------------------------------------------
1811 void FCGX_FreeStream(FCGX_Stream **streamPtr)
1813 FCGX_Stream *stream = *streamPtr;
1814 FCGX_Stream_Data *data;
1815 if(stream == NULL) {
1818 data = (FCGX_Stream_Data *)stream->data;
1819 data->reqDataPtr = NULL;
1827 *----------------------------------------------------------------------
1831 * Re-initializes the stream to read data of the specified type.
1833 *----------------------------------------------------------------------
1835 static FCGX_Stream *SetReaderType(FCGX_Stream *stream, int streamType)
1837 FCGX_Stream_Data *data = (FCGX_Stream_Data *)stream->data;
1838 ASSERT(stream->isReader);
1839 data->type = streamType;
1840 data->eorStop = FALSE;
1842 data->contentLen = 0;
1843 data->paddingLen = 0;
1844 stream->wrNext = stream->stop = stream->rdNext;
1845 stream->isClosed = FALSE;
1850 *----------------------------------------------------------------------
1854 * Creates a stream to read streamType records for the given
1855 * request. The stream performs OS reads of up to bufflen bytes.
1857 *----------------------------------------------------------------------
1859 static FCGX_Stream *NewReader(FCGX_Request *reqDataPtr, int bufflen, int streamType)
1861 return NewStream(reqDataPtr, bufflen, TRUE, streamType);
1865 *----------------------------------------------------------------------
1869 * Creates a stream to write streamType FastCGI records, using
1870 * the ipcFd and RequestId contained in *reqDataPtr.
1871 * The stream performs OS writes of up to bufflen bytes.
1873 *----------------------------------------------------------------------
1875 static FCGX_Stream *NewWriter(FCGX_Request *reqDataPtr, int bufflen, int streamType)
1877 return NewStream(reqDataPtr, bufflen, FALSE, streamType);
1881 *----------------------------------------------------------------------
1883 * FCGX_CreateWriter --
1885 * Creates a stream to write streamType FastCGI records, using
1886 * the given ipcFd and request Id. This function is provided
1887 * for use by cgi-fcgi. In order to be defensive against misuse,
1888 * this function leaks a little storage; cgi-fcgi doesn't care.
1890 *----------------------------------------------------------------------
1892 FCGX_Stream *FCGX_CreateWriter(
1898 FCGX_Request *reqDataPtr = (FCGX_Request *)Malloc(sizeof(FCGX_Request));
1899 reqDataPtr->ipcFd = ipcFd;
1900 reqDataPtr->requestId = requestId;
1902 * Suppress writing an FCGI_END_REQUEST record.
1904 reqDataPtr->nWriters = 2;
1905 return NewWriter(reqDataPtr, bufflen, streamType);
1909 *======================================================================
1911 *======================================================================
1915 *----------------------------------------------------------------------
1919 * This routine determines if the process is running as a CGI or
1920 * FastCGI process. The distinction is made by determining whether
1921 * FCGI_LISTENSOCK_FILENO is a listener ipcFd or the end of a
1922 * pipe (ie. standard in).
1925 * TRUE if the process is a CGI process, FALSE if FastCGI.
1927 *----------------------------------------------------------------------
1929 int FCGX_IsCGI(void)
1931 if (isFastCGI != -1) {
1935 if (!libInitialized) {
1936 int rc = FCGX_Init();
1938 /* exit() isn't great, but hey */
1939 exit((rc < 0) ? rc : -rc);
1943 isFastCGI = OS_IsFcgi(FCGI_LISTENSOCK_FILENO);
1949 *----------------------------------------------------------------------
1953 * Finishes the current request from the HTTP server.
1957 * Finishes the request accepted by (and frees any
1958 * storage allocated by) the previous call to FCGX_Accept.
1960 * DO NOT retain pointers to the envp array or any strings
1961 * contained in it (e.g. to the result of calling FCGX_GetParam),
1962 * since these will be freed by the next call to FCGX_Finish
1965 *----------------------------------------------------------------------
1968 void FCGX_Finish(void)
1970 FCGX_Finish_r(&the_request);
1974 *----------------------------------------------------------------------
1978 * Finishes the current request from the HTTP server.
1982 * Finishes the request accepted by (and frees any
1983 * storage allocated by) the previous call to FCGX_Accept.
1985 * DO NOT retain pointers to the envp array or any strings
1986 * contained in it (e.g. to the result of calling FCGX_GetParam),
1987 * since these will be freed by the next call to FCGX_Finish
1990 *----------------------------------------------------------------------
1992 void FCGX_Finish_r(FCGX_Request *reqDataPtr)
1996 if (reqDataPtr == NULL) {
2000 close = !reqDataPtr->keepConnection;
2002 /* This should probably use a 'status' member instead of 'in' */
2003 if (reqDataPtr->in) {
2004 close |= FCGX_FClose(reqDataPtr->err);
2005 close |= FCGX_FClose(reqDataPtr->out);
2007 close |= FCGX_GetError(reqDataPtr->in);
2010 FCGX_Free(reqDataPtr, close);
2013 void FCGX_Free(FCGX_Request * request, int close)
2015 if (request == NULL)
2018 FCGX_FreeStream(&request->in);
2019 FCGX_FreeStream(&request->out);
2020 FCGX_FreeStream(&request->err);
2021 FreeParams(&request->paramsPtr);
2024 OS_IpcClose(request->ipcFd);
2025 request->ipcFd = -1;
2029 int FCGX_OpenSocket(const char *path, int backlog)
2031 int rc = OS_CreateLocalIpcFd(path, backlog);
2032 if (rc == FCGI_LISTENSOCK_FILENO && isFastCGI == 0) {
2033 /* XXX probably need to call OS_LibInit() again for Win */
2039 int FCGX_InitRequest(FCGX_Request *request, int sock, int flags)
2041 memset(request, 0, sizeof(FCGX_Request));
2043 /* @@@ Should check that sock is open and listening */
2044 request->listen_sock = sock;
2046 /* @@@ Should validate against "known" flags */
2047 request->flags = flags;
2049 request->ipcFd = -1;
2055 *----------------------------------------------------------------------
2059 * Initilize the FCGX library. This is called by FCGX_Accept()
2060 * but must be called by the user when using FCGX_Accept_r().
2063 * 0 for successful call.
2065 *----------------------------------------------------------------------
2071 if (libInitialized) {
2075 FCGX_InitRequest(&the_request, FCGI_LISTENSOCK_FILENO, 0);
2077 if (OS_LibInit(NULL) == -1) {
2078 return OS_Errno ? OS_Errno : -9997;
2081 p = getenv("FCGI_WEB_SERVER_ADDRS");
2082 webServerAddressList = p ? StringCopy(p) : NULL;
2089 *----------------------------------------------------------------------
2093 * Accepts a new request from the HTTP server.
2096 * 0 for successful call, -1 for error.
2100 * Finishes the request accepted by (and frees any
2101 * storage allocated by) the previous call to FCGX_Accept.
2102 * Creates input, output, and error streams and
2103 * assigns them to *in, *out, and *err respectively.
2104 * Creates a parameters data structure to be accessed
2105 * via getenv(3) (if assigned to environ) or by FCGX_GetParam
2106 * and assigns it to *envp.
2108 * DO NOT retain pointers to the envp array or any strings
2109 * contained in it (e.g. to the result of calling FCGX_GetParam),
2110 * since these will be freed by the next call to FCGX_Finish
2113 *----------------------------------------------------------------------
2120 FCGX_ParamArray *envp)
2124 if (! libInitialized) {
2131 rc = FCGX_Accept_r(&the_request);
2133 *in = the_request.in;
2134 *out = the_request.out;
2135 *err = the_request.err;
2136 *envp = the_request.envp;
2142 *----------------------------------------------------------------------
2146 * Accepts a new request from the HTTP server.
2149 * 0 for successful call, -1 for error.
2153 * Finishes the request accepted by (and frees any
2154 * storage allocated by) the previous call to FCGX_Accept.
2155 * Creates input, output, and error streams and
2156 * assigns them to *in, *out, and *err respectively.
2157 * Creates a parameters data structure to be accessed
2158 * via getenv(3) (if assigned to environ) or by FCGX_GetParam
2159 * and assigns it to *envp.
2161 * DO NOT retain pointers to the envp array or any strings
2162 * contained in it (e.g. to the result of calling FCGX_GetParam),
2163 * since these will be freed by the next call to FCGX_Finish
2166 *----------------------------------------------------------------------
2168 int FCGX_Accept_r(FCGX_Request *reqDataPtr)
2170 if (!libInitialized) {
2174 /* Finish the current request, if any. */
2175 FCGX_Finish_r(reqDataPtr);
2179 * If a connection isn't open, accept a new connection (blocking).
2180 * If an OS error occurs in accepting the connection,
2181 * return -1 to the caller, who should exit.
2183 if (reqDataPtr->ipcFd < 0) {
2184 int fail_on_intr = reqDataPtr->flags & FCGI_FAIL_ACCEPT_ON_INTR;
2186 reqDataPtr->ipcFd = OS_Accept(reqDataPtr->listen_sock, fail_on_intr, webServerAddressList);
2187 if (reqDataPtr->ipcFd < 0) {
2188 return (errno > 0) ? (0 - errno) : -9999;
2192 * A connection is open. Read from the connection in order to
2193 * get the request's role and environment. If protocol or other
2194 * errors occur, close the connection and try again.
2196 reqDataPtr->isBeginProcessed = FALSE;
2197 reqDataPtr->in = NewReader(reqDataPtr, 8192, 0);
2198 FillBuffProc(reqDataPtr->in);
2199 if(!reqDataPtr->isBeginProcessed) {
2204 switch(reqDataPtr->role) {
2205 case FCGI_RESPONDER:
2206 roleStr = "FCGI_ROLE=RESPONDER";
2208 case FCGI_AUTHORIZER:
2209 roleStr = "FCGI_ROLE=AUTHORIZER";
2212 roleStr = "FCGI_ROLE=FILTER";
2217 reqDataPtr->paramsPtr = NewParams(30);
2218 PutParam(reqDataPtr->paramsPtr, StringCopy(roleStr));
2220 SetReaderType(reqDataPtr->in, FCGI_PARAMS);
2221 if(ReadParams(reqDataPtr->paramsPtr, reqDataPtr->in) >= 0) {
2223 * Finished reading the environment. No errors occurred, so
2224 * leave the connection-retry loop.
2230 * Close the connection and try again.
2233 FCGX_Free(reqDataPtr, 1);
2237 * Build the remaining data structures representing the new
2238 * request and return successfully to the caller.
2240 SetReaderType(reqDataPtr->in, FCGI_STDIN);
2241 reqDataPtr->out = NewWriter(reqDataPtr, 8192, FCGI_STDOUT);
2242 reqDataPtr->err = NewWriter(reqDataPtr, 512, FCGI_STDERR);
2243 reqDataPtr->nWriters = 2;
2244 reqDataPtr->envp = reqDataPtr->paramsPtr->vec;
2249 *----------------------------------------------------------------------
2251 * FCGX_StartFilterData --
2253 * stream is an input stream for a FCGI_FILTER request.
2254 * stream is positioned at EOF on FCGI_STDIN.
2255 * Repositions stream to the start of FCGI_DATA.
2256 * If the preconditions are not met (e.g. FCGI_STDIN has not
2257 * been read to EOF) sets the stream error code to
2258 * FCGX_CALL_SEQ_ERROR.
2261 * 0 for a normal return, < 0 for error
2263 *----------------------------------------------------------------------
2266 int FCGX_StartFilterData(FCGX_Stream *stream)
2268 FCGX_Stream_Data *data = (FCGX_Stream_Data *)stream->data;
2269 if(data->reqDataPtr->role != FCGI_FILTER
2270 || !stream->isReader
2271 || !stream->isClosed
2272 || data->type != FCGI_STDIN) {
2273 SetError(stream, FCGX_CALL_SEQ_ERROR);
2276 SetReaderType(stream, FCGI_DATA);
2281 *----------------------------------------------------------------------
2283 * FCGX_SetExitStatus --
2285 * Sets the exit status for stream's request. The exit status
2286 * is the status code the request would have exited with, had
2287 * the request been run as a CGI program. You can call
2288 * SetExitStatus several times during a request; the last call
2289 * before the request ends determines the value.
2291 *----------------------------------------------------------------------
2294 void FCGX_SetExitStatus(int status, FCGX_Stream *stream)
2296 FCGX_Stream_Data *data = (FCGX_Stream_Data *)stream->data;
2297 data->reqDataPtr->appStatus = status;