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.33 2001/12/12 14:12:26 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 if (stream->isClosed)
117 stream->stopUnget = stream->rdNext;
118 if(stream->rdNext != stream->stop)
119 return *stream->rdNext++;
120 ASSERT(stream->isClosed); /* bug in fillBufProc if not */
125 *----------------------------------------------------------------------
129 * Reads up to n consecutive bytes from the input stream
130 * into the character array str. Performs no interpretation
131 * of the input bytes.
134 * Number of bytes read. If result is smaller than n,
135 * the end of input has been reached.
137 *----------------------------------------------------------------------
139 int FCGX_GetStr(char *str, int n, FCGX_Stream *stream)
147 * Fast path: n bytes are already available
149 if(n <= (stream->stop - stream->rdNext)) {
150 memcpy(str, stream->rdNext, n);
155 * General case: stream is closed or buffer fill procedure
160 if(stream->rdNext != stream->stop) {
161 m = min(n - bytesMoved, stream->stop - stream->rdNext);
162 memcpy(str, stream->rdNext, m);
169 if(stream->isClosed || !stream->isReader)
171 stream->fillBuffProc(stream);
172 if (stream->isClosed)
175 stream->stopUnget = stream->rdNext;
180 *----------------------------------------------------------------------
184 * Reads up to n-1 consecutive bytes from the input stream
185 * into the character array str. Stops before n-1 bytes
186 * have been read if '\n' or EOF is read. The terminating '\n'
187 * is copied to str. After copying the last byte into str,
188 * stores a '\0' terminator.
191 * NULL if EOF is the first thing read from the input stream,
194 *----------------------------------------------------------------------
196 char *FCGX_GetLine(char *str, int n, FCGX_Stream *stream)
203 c = FCGX_GetChar(stream);
220 *----------------------------------------------------------------------
224 * Pushes back the character c onto the input stream. One
225 * character of pushback is guaranteed once a character
226 * has been read. No pushback is possible for EOF.
229 * Returns c if the pushback succeeded, EOF if not.
231 *----------------------------------------------------------------------
233 int FCGX_UnGetChar(int c, FCGX_Stream *stream) {
237 || stream->rdNext == stream->stopUnget)
240 *stream->rdNext = (unsigned char) c;
245 *----------------------------------------------------------------------
249 * Returns EOF if end-of-file has been detected while reading
250 * from stream; otherwise returns 0.
252 * Note that FCGX_HasSeenEOF(s) may return 0, yet an immediately
253 * following FCGX_GetChar(s) may return EOF. This function, like
254 * the standard C stdio function feof, does not provide the
255 * ability to peek ahead.
258 * EOF if end-of-file has been detected, 0 if not.
260 *----------------------------------------------------------------------
262 int FCGX_HasSeenEOF(FCGX_Stream *stream) {
263 return (stream->isClosed) ? EOF : 0;
267 *----------------------------------------------------------------------
271 * Writes a byte to the output stream.
274 * The byte, or EOF (-1) if an error occurred.
276 *----------------------------------------------------------------------
278 int FCGX_PutChar(int c, FCGX_Stream *stream)
280 if(stream->wrNext != stream->stop)
281 return (*stream->wrNext++ = (unsigned char) c);
282 if(stream->isClosed || stream->isReader)
284 stream->emptyBuffProc(stream, FALSE);
285 if(stream->wrNext != stream->stop)
286 return (*stream->wrNext++ = (unsigned char) c);
287 ASSERT(stream->isClosed); /* bug in emptyBuffProc if not */
292 *----------------------------------------------------------------------
296 * Writes n consecutive bytes from the character array str
297 * into the output stream. Performs no interpretation
298 * of the output bytes.
301 * Number of bytes written (n) for normal return,
302 * EOF (-1) if an error occurred.
304 *----------------------------------------------------------------------
306 int FCGX_PutStr(const char *str, int n, FCGX_Stream *stream)
311 * Fast path: room for n bytes in the buffer
313 if(n <= (stream->stop - stream->wrNext)) {
314 memcpy(stream->wrNext, str, n);
319 * General case: stream is closed or buffer empty procedure
324 if(stream->wrNext != stream->stop) {
325 m = min(n - bytesMoved, stream->stop - stream->wrNext);
326 memcpy(stream->wrNext, str, m);
333 if(stream->isClosed || stream->isReader)
335 stream->emptyBuffProc(stream, FALSE);
340 *----------------------------------------------------------------------
344 * Writes a character string to the output stream.
347 * number of bytes written for normal return,
348 * EOF (-1) if an error occurred.
350 *----------------------------------------------------------------------
352 int FCGX_PutS(const char *str, FCGX_Stream *stream)
354 return FCGX_PutStr(str, strlen(str), stream);
358 *----------------------------------------------------------------------
362 * Performs output formatting and writes the results
363 * to the output stream.
366 * number of bytes written for normal return,
367 * EOF (-1) if an error occurred.
369 *----------------------------------------------------------------------
371 int FCGX_FPrintF(FCGX_Stream *stream, const char *format, ...)
375 va_start(ap, format);
376 result = FCGX_VFPrintF(stream, format, ap);
382 *----------------------------------------------------------------------
386 * Performs output formatting and writes the results
387 * to the output stream.
390 * number of bytes written for normal return,
391 * EOF (-1) if an error occurred.
393 *----------------------------------------------------------------------
396 #define PRINTF_BUFFLEN 100
398 * More than sufficient space for all unmodified conversions
401 #define FMT_BUFFLEN 25
403 * Max size of a format specifier is 1 + 5 + 7 + 7 + 2 + 1 + slop
405 static void CopyAndAdvance(char **destPtr, char **srcPtr, int n);
407 int FCGX_VFPrintF(FCGX_Stream *stream, const char *format, va_list arg)
409 char *f, *fStop, *percentPtr, *p, *fmtBuffPtr, *buffPtr;
410 int op, performedOp, sizeModifier, buffCount = 0, buffLen, specifierLength;
411 int fastPath, n, auxBuffLen = 0, buffReqd, minWidth, precision, exp;
412 char *auxBuffPtr = NULL;
414 char fmtBuff[FMT_BUFFLEN];
415 char buff[PRINTF_BUFFLEN];
420 unsigned unsignedArg;
421 unsigned long uLongArg;
422 unsigned short uShortArg;
423 char *charPtrArg = NULL;
428 double doubleArg = 0.0;
429 LONG_DOUBLE lDoubleArg = 0.0L;
433 fStop = f + strlen(f);
435 percentPtr = (char *)memchr(f, '%', fStop - f);
436 if(percentPtr == NULL) percentPtr = fStop;
437 if(percentPtr != f) {
438 if(FCGX_PutStr(f, percentPtr - f, stream) < 0)
440 streamCount += percentPtr - f;
442 if(f == fStop) break;
446 * The following loop always executes either once or twice.
451 * Fast path: Scan optimistically, hoping that no flags,
452 * minimum field width, or precision are specified.
453 * Use the preallocated buffer, which is large enough
454 * for all fast path cases. If the conversion specifier
455 * is really more complex, run the loop a second time
456 * using the slow path.
457 * Note that fast path execution of %s bypasses the buffer
458 * and %f is not attempted on the fast path due to
459 * its large buffering requirements.
461 op = *(percentPtr + 1);
467 op = *(percentPtr + 2);
468 fmtBuff[1] = (char) sizeModifier;
469 fmtBuff[2] = (char) op;
475 fmtBuff[1] = (char) op;
481 buffLen = PRINTF_BUFFLEN;
484 * Slow path: Scan the conversion specifier and construct
485 * a new format string, compute an upper bound on the
486 * amount of buffering that sprintf will require,
487 * and allocate a larger buffer if necessary.
490 fmtBuffPtr = &fmtBuff[1];
494 n = strspn(p, "-0+ #");
497 CopyAndAdvance(&fmtBuffPtr, &p, n);
499 * Scan minimum field width
501 n = strspn(p, "0123456789");
504 minWidth = va_arg(arg, int);
505 if(abs(minWidth) > 999999)
508 * The following use of strlen rather than the
509 * value returned from sprintf is because SUNOS4
510 * returns a char * instead of an int count.
512 sprintf(fmtBuffPtr, "%d", minWidth);
513 fmtBuffPtr += strlen(fmtBuffPtr);
519 minWidth = strtol(p, NULL, 10);
520 CopyAndAdvance(&fmtBuffPtr, &p, n);
528 CopyAndAdvance(&fmtBuffPtr, &p, 1);
529 n = strspn(p, "0123456789");
532 precision = va_arg(arg, int);
533 if(precision < 0) precision = 0;
534 if(precision > 999999)
537 * The following use of strlen rather than the
538 * value returned from sprintf is because SUNOS4
539 * returns a char * instead of an int count.
541 sprintf(fmtBuffPtr, "%d", precision);
542 fmtBuffPtr += strlen(fmtBuffPtr);
548 precision = strtol(p, NULL, 10);
549 CopyAndAdvance(&fmtBuffPtr, &p, n);
557 * Scan size modifier and conversion operation
564 CopyAndAdvance(&fmtBuffPtr, &p, 1);
571 CopyAndAdvance(&fmtBuffPtr, &p, 1);
572 ASSERT(fmtBuffPtr - fmtBuff < FMT_BUFFLEN);
574 specifierLength = p - percentPtr;
576 * Bound the required buffer size. For s and f
577 * conversions this requires examining the argument.
588 buffReqd = max(precision, 46);
591 charPtrArg = va_arg(arg, char *);
592 if (!charPtrArg) charPtrArg = "(null)";
593 if(precision == -1) {
594 buffReqd = strlen(charPtrArg);
596 p = (char *)memchr(charPtrArg, '\0', precision);
598 (p == NULL) ? precision : p - charPtrArg;
602 switch(sizeModifier) {
604 doubleArg = va_arg(arg, double);
605 frexp(doubleArg, &exp);
608 lDoubleArg = va_arg(arg, LONG_DOUBLE);
609 /* XXX Need to check for the presence of
610 * frexpl() and use it if available */
611 frexp((double) lDoubleArg, &exp);
616 if(precision == -1) precision = 6;
617 buffReqd = precision + 3 + ((exp > 0) ? exp/3 : 0);
623 if(precision == -1) precision = 6;
624 buffReqd = precision + 8;
632 buffReqd = max(buffReqd + 10, minWidth);
634 * Allocate the buffer
636 if(buffReqd <= PRINTF_BUFFLEN) {
638 buffLen = PRINTF_BUFFLEN;
640 if(auxBuffPtr == NULL || buffReqd > auxBuffLen) {
641 if(auxBuffPtr != NULL) free(auxBuffPtr);
642 auxBuffPtr = (char *)Malloc(buffReqd);
643 auxBuffLen = buffReqd;
644 if(auxBuffPtr == NULL)
647 buffPtr = auxBuffPtr;
648 buffLen = auxBuffLen;
652 * This giant switch statement requires the following variables
653 * to be set up: op, sizeModifier, arg, buffPtr, fmtBuff.
654 * When fastPath == FALSE and op == 's' or 'f', the argument
655 * has been read into charPtrArg, doubleArg, or lDoubleArg.
656 * The statement produces the boolean performedOp, TRUE iff
657 * the op/sizeModifier were executed and argument consumed;
658 * if performedOp, the characters written into buffPtr[]
659 * and the character count buffCount (== EOF meaning error).
661 * The switch cases are arranged in the same order as in the
662 * description of fprintf in section 15.11 of Harbison and Steele.
668 switch(sizeModifier) {
670 intArg = va_arg(arg, int);
671 sprintf(buffPtr, fmtBuff, intArg);
672 buffCount = strlen(buffPtr);
675 longArg = va_arg(arg, long);
676 sprintf(buffPtr, fmtBuff, longArg);
677 buffCount = strlen(buffPtr);
680 shortArg = (short) va_arg(arg, int);
681 sprintf(buffPtr, fmtBuff, shortArg);
682 buffCount = strlen(buffPtr);
692 switch(sizeModifier) {
694 unsignedArg = va_arg(arg, unsigned);
695 sprintf(buffPtr, fmtBuff, unsignedArg);
696 buffCount = strlen(buffPtr);
699 uLongArg = va_arg(arg, unsigned long);
700 sprintf(buffPtr, fmtBuff, uLongArg);
701 buffCount = strlen(buffPtr);
704 uShortArg = (unsigned short) va_arg(arg, int);
705 sprintf(buffPtr, fmtBuff, uShortArg);
706 buffCount = strlen(buffPtr);
713 switch(sizeModifier) {
715 intArg = va_arg(arg, int);
716 sprintf(buffPtr, fmtBuff, intArg);
717 buffCount = strlen(buffPtr);
721 * XXX: Allowed by ISO C Amendment 1, but
722 * many platforms don't yet support wint_t
730 switch(sizeModifier) {
733 buffPtr = va_arg(arg, char *);
734 buffCount = strlen(buffPtr);
735 buffLen = buffCount + 1;
737 sprintf(buffPtr, fmtBuff, charPtrArg);
738 buffCount = strlen(buffPtr);
743 * XXX: Don't know how to convert a sequence
744 * of wide characters into a byte stream, or
745 * even how to predict the buffering required.
753 if(sizeModifier != ' ')
755 voidPtrArg = va_arg(arg, void *);
756 sprintf(buffPtr, fmtBuff, voidPtrArg);
757 buffCount = strlen(buffPtr);
760 switch(sizeModifier) {
762 intPtrArg = va_arg(arg, int *);
763 *intPtrArg = streamCount;
766 longPtrArg = va_arg(arg, long *);
767 *longPtrArg = streamCount;
770 shortPtrArg = (short *) va_arg(arg, short *);
771 *shortPtrArg = (short) streamCount;
783 switch(sizeModifier) {
785 sprintf(buffPtr, fmtBuff, doubleArg);
786 buffCount = strlen(buffPtr);
789 sprintf(buffPtr, fmtBuff, lDoubleArg);
790 buffCount = strlen(buffPtr);
800 switch(sizeModifier) {
802 doubleArg = va_arg(arg, double);
803 sprintf(buffPtr, fmtBuff, doubleArg);
804 buffCount = strlen(buffPtr);
807 lDoubleArg = va_arg(arg, LONG_DOUBLE);
808 sprintf(buffPtr, fmtBuff, lDoubleArg);
809 buffCount = strlen(buffPtr);
816 if(sizeModifier != ' ')
827 if(performedOp) break;
832 ASSERT(buffCount < buffLen);
834 if(FCGX_PutStr(buffPtr, buffCount, stream) < 0)
836 streamCount += buffCount;
837 } else if(buffCount < 0) {
840 f += specifierLength;
841 } /* while(f != fStop) */
846 if(auxBuffPtr != NULL) free(auxBuffPtr);
851 * Copy n characters from *srcPtr to *destPtr, then increment
852 * both *srcPtr and *destPtr by n.
854 static void CopyAndAdvance(char **destPtr, char **srcPtr, int n)
856 char *dest = *destPtr;
859 for (i = 0; i < n; i++)
866 *----------------------------------------------------------------------
870 * Flushes any buffered output.
872 * Server-push is a legitimate application of FCGX_FFlush.
873 * Otherwise, FCGX_FFlush is not very useful, since FCGX_Accept
874 * does it implicitly. FCGX_FFlush may reduce performance
875 * by increasing the total number of operating system calls
876 * the application makes.
879 * EOF (-1) if an error occurred.
881 *----------------------------------------------------------------------
883 int FCGX_FFlush(FCGX_Stream *stream)
885 if(stream->isClosed || stream->isReader)
887 stream->emptyBuffProc(stream, FALSE);
888 return (stream->isClosed) ? -1 : 0;
892 *----------------------------------------------------------------------
896 * Performs FCGX_FFlush and closes the stream.
898 * This is not a very useful operation, since FCGX_Accept
899 * does it implicitly. Closing the out stream before the
900 * err stream results in an extra write if there's nothing
901 * in the err stream, and therefore reduces performance.
904 * EOF (-1) if an error occurred.
906 *----------------------------------------------------------------------
908 int FCGX_FClose(FCGX_Stream *stream)
910 if (stream == NULL) return 0;
912 if(!stream->wasFCloseCalled) {
913 if(!stream->isReader) {
914 stream->emptyBuffProc(stream, TRUE);
916 stream->wasFCloseCalled = TRUE;
917 stream->isClosed = TRUE;
918 if(stream->isReader) {
919 stream->wrNext = stream->stop = stream->rdNext;
921 stream->rdNext = stream->stop = stream->wrNext;
924 return (stream->FCGI_errno == 0) ? 0 : EOF;
928 *----------------------------------------------------------------------
932 * An error has occurred; save the error code in the stream
933 * for diagnostic purposes and set the stream state so that
934 * reads return EOF and writes have no effect.
936 *----------------------------------------------------------------------
938 static void SetError(FCGX_Stream *stream, int FCGI_errno)
941 * Preserve only the first error.
943 if(stream->FCGI_errno == 0) {
944 stream->FCGI_errno = FCGI_errno;
945 stream->isClosed = TRUE;
950 *----------------------------------------------------------------------
954 * Return the stream error code. 0 means no error, > 0
955 * is an errno(2) error, < 0 is an FCGX_errno error.
957 *----------------------------------------------------------------------
959 int FCGX_GetError(FCGX_Stream *stream) {
960 return stream->FCGI_errno;
964 *----------------------------------------------------------------------
968 * Clear the stream error code and end-of-file indication.
970 *----------------------------------------------------------------------
972 void FCGX_ClearError(FCGX_Stream *stream) {
973 stream->FCGI_errno = 0;
975 * stream->isClosed = FALSE;
976 * XXX: should clear isClosed but work is needed to make it safe
977 * to do so. For example, if an application calls FClose, gets
978 * an I/O error on the write, calls ClearError and retries
979 * the FClose, FClose (really EmptyBuffProc) will write a second
980 * EOF record. If an application calls PutChar instead of FClose
981 * after the ClearError, the application will write more data.
982 * The stream's state must discriminate between various states
983 * of the stream that are now all lumped under isClosed.
988 *======================================================================
990 *======================================================================
994 * A vector of pointers representing the parameters received
995 * by a FastCGI application server, with the vector's length
996 * and last valid element so adding new parameters is efficient.
999 typedef struct Params {
1000 FCGX_ParamArray vec; /* vector of strings */
1001 int length; /* number of string vec can hold */
1002 char **cur; /* current item in vec; *cur == NULL */
1004 typedef Params *ParamsPtr;
1007 *----------------------------------------------------------------------
1011 * Creates a new Params structure.
1014 * Pointer to the new structure.
1016 *----------------------------------------------------------------------
1018 static ParamsPtr NewParams(int length)
1021 result = (Params *)Malloc(sizeof(Params));
1022 result->vec = (char **)Malloc(length * sizeof(char *));
1023 result->length = length;
1024 result->cur = result->vec;
1025 *result->cur = NULL;
1030 *----------------------------------------------------------------------
1034 * Frees a Params structure and all the parameters it contains.
1037 * env becomes invalid.
1039 *----------------------------------------------------------------------
1041 static void FreeParams(ParamsPtr *paramsPtrPtr)
1043 ParamsPtr paramsPtr = *paramsPtrPtr;
1045 if(paramsPtr == NULL) {
1048 for (p = paramsPtr->vec; p < paramsPtr->cur; p++) {
1051 free(paramsPtr->vec);
1053 *paramsPtrPtr = NULL;
1057 *----------------------------------------------------------------------
1061 * Add a name/value pair to a Params structure.
1067 * Parameters structure updated.
1069 *----------------------------------------------------------------------
1071 static void PutParam(ParamsPtr paramsPtr, char *nameValue)
1075 *paramsPtr->cur++ = nameValue;
1076 size = paramsPtr->cur - paramsPtr->vec;
1077 if(size >= paramsPtr->length) {
1078 paramsPtr->length *= 2;
1079 paramsPtr->vec = (FCGX_ParamArray)realloc(paramsPtr->vec, paramsPtr->length * sizeof(char *));
1080 paramsPtr->cur = paramsPtr->vec + size;
1082 *paramsPtr->cur = NULL;
1086 *----------------------------------------------------------------------
1088 * FCGX_GetParam -- obtain value of FCGI parameter in environment
1092 * Value bound to name, NULL if name not present in the
1093 * environment envp. Caller must not mutate the result
1094 * or retain it past the end of this request.
1096 *----------------------------------------------------------------------
1098 char *FCGX_GetParam(const char *name, FCGX_ParamArray envp)
1103 if (name == NULL || envp == NULL) return NULL;
1107 for (p = envp; *p; ++p) {
1108 if((strncmp(name, *p, len) == 0) && ((*p)[len] == '=')) {
1116 *----------------------------------------------------------------------
1118 * Start of FastCGI-specific code
1120 *----------------------------------------------------------------------
1124 *----------------------------------------------------------------------
1128 * Reads FastCGI name-value pairs from stream until EOF. Converts
1129 * each pair to name=value format and adds it to Params structure.
1131 *----------------------------------------------------------------------
1133 static int ReadParams(Params *paramsPtr, FCGX_Stream *stream)
1135 int nameLen, valueLen;
1136 unsigned char lenBuff[3];
1139 while((nameLen = FCGX_GetChar(stream)) != EOF) {
1141 * Read name length (one or four bytes) and value length
1142 * (one or four bytes) from stream.
1144 if((nameLen & 0x80) != 0) {
1145 if(FCGX_GetStr((char *) &lenBuff[0], 3, stream) != 3) {
1146 SetError(stream, FCGX_PARAMS_ERROR);
1149 nameLen = ((nameLen & 0x7f) << 24) + (lenBuff[0] << 16)
1150 + (lenBuff[1] << 8) + lenBuff[2];
1152 if((valueLen = FCGX_GetChar(stream)) == EOF) {
1153 SetError(stream, FCGX_PARAMS_ERROR);
1156 if((valueLen & 0x80) != 0) {
1157 if(FCGX_GetStr((char *) &lenBuff[0], 3, stream) != 3) {
1158 SetError(stream, FCGX_PARAMS_ERROR);
1161 valueLen = ((valueLen & 0x7f) << 24) + (lenBuff[0] << 16)
1162 + (lenBuff[1] << 8) + lenBuff[2];
1165 * nameLen and valueLen are now valid; read the name and value
1166 * from stream and construct a standard environment entry.
1168 nameValue = (char *)Malloc(nameLen + valueLen + 2);
1169 if(FCGX_GetStr(nameValue, nameLen, stream) != nameLen) {
1170 SetError(stream, FCGX_PARAMS_ERROR);
1174 *(nameValue + nameLen) = '=';
1175 if(FCGX_GetStr(nameValue + nameLen + 1, valueLen, stream)
1177 SetError(stream, FCGX_PARAMS_ERROR);
1181 *(nameValue + nameLen + valueLen + 1) = '\0';
1182 PutParam(paramsPtr, nameValue);
1188 *----------------------------------------------------------------------
1192 * Constructs an FCGI_Header struct.
1194 *----------------------------------------------------------------------
1196 static FCGI_Header MakeHeader(
1203 ASSERT(contentLength >= 0 && contentLength <= FCGI_MAX_LENGTH);
1204 ASSERT(paddingLength >= 0 && paddingLength <= 0xff);
1205 header.version = FCGI_VERSION_1;
1206 header.type = (unsigned char) type;
1207 header.requestIdB1 = (unsigned char) ((requestId >> 8) & 0xff);
1208 header.requestIdB0 = (unsigned char) ((requestId ) & 0xff);
1209 header.contentLengthB1 = (unsigned char) ((contentLength >> 8) & 0xff);
1210 header.contentLengthB0 = (unsigned char) ((contentLength ) & 0xff);
1211 header.paddingLength = (unsigned char) paddingLength;
1212 header.reserved = 0;
1217 *----------------------------------------------------------------------
1219 * MakeEndRequestBody --
1221 * Constructs an FCGI_EndRequestBody struct.
1223 *----------------------------------------------------------------------
1225 static FCGI_EndRequestBody MakeEndRequestBody(
1229 FCGI_EndRequestBody body;
1230 body.appStatusB3 = (unsigned char) ((appStatus >> 24) & 0xff);
1231 body.appStatusB2 = (unsigned char) ((appStatus >> 16) & 0xff);
1232 body.appStatusB1 = (unsigned char) ((appStatus >> 8) & 0xff);
1233 body.appStatusB0 = (unsigned char) ((appStatus ) & 0xff);
1234 body.protocolStatus = (unsigned char) protocolStatus;
1235 memset(body.reserved, 0, sizeof(body.reserved));
1240 *----------------------------------------------------------------------
1242 * MakeUnknownTypeBody --
1244 * Constructs an FCGI_MakeUnknownTypeBody struct.
1246 *----------------------------------------------------------------------
1248 static FCGI_UnknownTypeBody MakeUnknownTypeBody(
1251 FCGI_UnknownTypeBody body;
1252 body.type = (unsigned char) type;
1253 memset(body.reserved, 0, sizeof(body.reserved));
1258 *----------------------------------------------------------------------
1262 * Returns the smallest integer greater than or equal to n
1263 * that's a multiple of 8.
1265 *----------------------------------------------------------------------
1267 static int AlignInt8(unsigned n) {
1268 return (n + 7) & (UINT_MAX - 7);
1272 *----------------------------------------------------------------------
1276 * Returns the smallest pointer greater than or equal to p
1277 * that's a multiple of 8.
1279 *----------------------------------------------------------------------
1281 static unsigned char *AlignPtr8(unsigned char *p) {
1282 unsigned long u = (unsigned long) p;
1283 u = ((u + 7) & (ULONG_MAX - 7)) - u;
1289 * State associated with a stream
1291 typedef struct FCGX_Stream_Data {
1292 unsigned char *buff; /* buffer after alignment */
1293 int bufflen; /* number of bytes buff can store */
1294 unsigned char *mBuff; /* buffer as returned by Malloc */
1295 unsigned char *buffStop; /* reader: last valid byte + 1 of entire buffer.
1296 * stop generally differs from buffStop for
1297 * readers because of record structure.
1298 * writer: buff + bufflen */
1299 int type; /* reader: FCGI_PARAMS or FCGI_STDIN
1300 * writer: FCGI_STDOUT or FCGI_STDERR */
1301 int eorStop; /* reader: stop stream at end-of-record */
1302 int skip; /* reader: don't deliver content bytes */
1303 int contentLen; /* reader: bytes of unread content */
1304 int paddingLen; /* reader: bytes of unread padding */
1305 int isAnythingWritten; /* writer: data has been written to ipcFd */
1306 int rawWrite; /* writer: write data without stream headers */
1307 FCGX_Request *reqDataPtr; /* request data not specific to one stream */
1311 *----------------------------------------------------------------------
1313 * WriteCloseRecords --
1315 * Writes an EOF record for the stream content if necessary.
1316 * If this is the last writer to close, writes an FCGI_END_REQUEST
1319 *----------------------------------------------------------------------
1321 static void WriteCloseRecords(struct FCGX_Stream *stream)
1323 FCGX_Stream_Data *data = (FCGX_Stream_Data *)stream->data;
1325 * Enter rawWrite mode so final records won't be encapsulated as
1328 data->rawWrite = TRUE;
1330 * Generate EOF for stream content if needed.
1332 if(!(data->type == FCGI_STDERR
1333 && stream->wrNext == data->buff
1334 && !data->isAnythingWritten)) {
1336 header = MakeHeader(data->type, data->reqDataPtr->requestId, 0, 0);
1337 FCGX_PutStr((char *) &header, sizeof(header), stream);
1340 * Generate FCGI_END_REQUEST record if needed.
1342 if(data->reqDataPtr->nWriters == 1) {
1343 FCGI_EndRequestRecord endRequestRecord;
1344 endRequestRecord.header = MakeHeader(FCGI_END_REQUEST,
1345 data->reqDataPtr->requestId,
1346 sizeof(endRequestRecord.body), 0);
1347 endRequestRecord.body = MakeEndRequestBody(
1348 data->reqDataPtr->appStatus, FCGI_REQUEST_COMPLETE);
1349 FCGX_PutStr((char *) &endRequestRecord,
1350 sizeof(endRequestRecord), stream);
1352 data->reqDataPtr->nWriters--;
1357 static int write_it_all(int fd, char *buf, int len)
1362 wrote = OS_Write(fd, buf, len);
1372 *----------------------------------------------------------------------
1376 * Encapsulates any buffered stream content in a FastCGI
1377 * record. Writes the data, making the buffer empty.
1379 *----------------------------------------------------------------------
1381 static void EmptyBuffProc(struct FCGX_Stream *stream, int doClose)
1383 FCGX_Stream_Data *data = (FCGX_Stream_Data *)stream->data;
1386 * If the buffer contains stream data, fill in the header.
1387 * Pad the record to a multiple of 8 bytes in length. Padding
1388 * can't overflow the buffer because the buffer is a multiple
1389 * of 8 bytes in length. If the buffer contains no stream
1390 * data, reclaim the space reserved for the header.
1392 if(!data->rawWrite) {
1393 cLen = stream->wrNext - data->buff - sizeof(FCGI_Header);
1395 eLen = AlignInt8(cLen);
1397 * Giving the padding a well-defined value keeps Purify happy.
1399 memset(stream->wrNext, 0, eLen - cLen);
1400 stream->wrNext += eLen - cLen;
1401 *((FCGI_Header *) data->buff)
1402 = MakeHeader(data->type,
1403 data->reqDataPtr->requestId, cLen, eLen - cLen);
1405 stream->wrNext = data->buff;
1409 WriteCloseRecords(stream);
1411 if (stream->wrNext != data->buff) {
1412 data->isAnythingWritten = TRUE;
1413 if (write_it_all(data->reqDataPtr->ipcFd, (char *)data->buff, stream->wrNext - data->buff) < 0) {
1414 SetError(stream, OS_Errno);
1417 stream->wrNext = data->buff;
1420 * The buffer is empty.
1422 if(!data->rawWrite) {
1423 stream->wrNext += sizeof(FCGI_Header);
1428 * Return codes for Process* functions
1430 #define STREAM_RECORD 0
1432 #define BEGIN_RECORD 2
1433 #define MGMT_RECORD 3
1436 *----------------------------------------------------------------------
1438 * ProcessManagementRecord --
1440 * Reads and responds to a management record. The only type of
1441 * management record this library understands is FCGI_GET_VALUES.
1442 * The only variables that this library's FCGI_GET_VALUES
1443 * understands are FCGI_MAX_CONNS, FCGI_MAX_REQS, and FCGI_MPXS_CONNS.
1444 * Ignore other FCGI_GET_VALUES variables; respond to other
1445 * management records with a FCGI_UNKNOWN_TYPE record.
1447 *----------------------------------------------------------------------
1449 static int ProcessManagementRecord(int type, FCGX_Stream *stream)
1451 FCGX_Stream_Data *data = (FCGX_Stream_Data *)stream->data;
1452 ParamsPtr paramsPtr = NewParams(3);
1454 char response[64]; /* 64 = 8 + 3*(1+1+14+1)* + padding */
1455 char *responseP = &response[FCGI_HEADER_LEN];
1456 char *name, value = '\0';
1458 if(type == FCGI_GET_VALUES) {
1459 ReadParams(paramsPtr, stream);
1460 if((FCGX_GetError(stream) != 0) || (data->contentLen != 0)) {
1461 FreeParams(¶msPtr);
1462 return FCGX_PROTOCOL_ERROR;
1464 for (pPtr = paramsPtr->vec; pPtr < paramsPtr->cur; pPtr++) {
1466 *(strchr(name, '=')) = '\0';
1467 if(strcmp(name, FCGI_MAX_CONNS) == 0) {
1469 } else if(strcmp(name, FCGI_MAX_REQS) == 0) {
1471 } else if(strcmp(name, FCGI_MPXS_CONNS) == 0) {
1478 sprintf(responseP, "%c%c%s%c", len, 1, name, value);
1479 responseP += len + 3;
1482 len = responseP - &response[FCGI_HEADER_LEN];
1483 paddedLen = AlignInt8(len);
1484 *((FCGI_Header *) response)
1485 = MakeHeader(FCGI_GET_VALUES_RESULT, FCGI_NULL_REQUEST_ID,
1486 len, paddedLen - len);
1487 FreeParams(¶msPtr);
1489 paddedLen = len = sizeof(FCGI_UnknownTypeBody);
1490 ((FCGI_UnknownTypeRecord *) response)->header
1491 = MakeHeader(FCGI_UNKNOWN_TYPE, FCGI_NULL_REQUEST_ID,
1493 ((FCGI_UnknownTypeRecord *) response)->body
1494 = MakeUnknownTypeBody(type);
1496 if (write_it_all(data->reqDataPtr->ipcFd, response, FCGI_HEADER_LEN + paddedLen) < 0) {
1497 SetError(stream, OS_Errno);
1505 *----------------------------------------------------------------------
1507 * ProcessBeginRecord --
1509 * Reads an FCGI_BEGIN_REQUEST record.
1512 * BEGIN_RECORD for normal return. FCGX_PROTOCOL_ERROR for
1513 * protocol error. SKIP for attempt to multiplex
1514 * connection. -1 for error from write (errno in stream).
1517 * In case of BEGIN_RECORD return, stores requestId, role,
1518 * keepConnection values, and sets isBeginProcessed = TRUE.
1520 *----------------------------------------------------------------------
1522 static int ProcessBeginRecord(int requestId, FCGX_Stream *stream)
1524 FCGX_Stream_Data *data = (FCGX_Stream_Data *)stream->data;
1525 FCGI_BeginRequestBody body;
1526 if(requestId == 0 || data->contentLen != sizeof(body)) {
1527 return FCGX_PROTOCOL_ERROR;
1529 if(data->reqDataPtr->isBeginProcessed) {
1531 * The Web server is multiplexing the connection. This library
1532 * doesn't know how to handle multiplexing, so respond with
1533 * FCGI_END_REQUEST{protocolStatus = FCGI_CANT_MPX_CONN}
1535 FCGI_EndRequestRecord endRequestRecord;
1536 endRequestRecord.header = MakeHeader(FCGI_END_REQUEST,
1537 requestId, sizeof(endRequestRecord.body), 0);
1538 endRequestRecord.body
1539 = MakeEndRequestBody(0, FCGI_CANT_MPX_CONN);
1540 if (write_it_all(data->reqDataPtr->ipcFd, (char *)&endRequestRecord, sizeof(endRequestRecord)) < 0) {
1541 SetError(stream, OS_Errno);
1548 * Accept this new request. Read the record body.
1550 data->reqDataPtr->requestId = requestId;
1551 if(FCGX_GetStr((char *) &body, sizeof(body), stream)
1553 return FCGX_PROTOCOL_ERROR;
1555 data->reqDataPtr->keepConnection = (body.flags & FCGI_KEEP_CONN);
1556 data->reqDataPtr->role = (body.roleB1 << 8) + body.roleB0;
1557 data->reqDataPtr->isBeginProcessed = TRUE;
1558 return BEGIN_RECORD;
1562 *----------------------------------------------------------------------
1566 * Interprets FCGI_Header. Processes FCGI_BEGIN_REQUEST and
1567 * management records here; extracts information from stream
1568 * records (FCGI_PARAMS, FCGI_STDIN) into stream.
1571 * >= 0 for a normal return, < 0 for error
1574 * XXX: Many (more than there used to be).
1575 * If !stream->isRequestIdSet, ProcessHeader initializes
1576 * stream->requestId from header and sets stream->isRequestIdSet
1577 * to TRUE. ProcessHeader also sets stream->contentLen to header's
1578 * contentLength, and sets stream->paddingLen to the header's
1581 *----------------------------------------------------------------------
1583 static int ProcessHeader(FCGI_Header header, FCGX_Stream *stream)
1585 FCGX_Stream_Data *data = (FCGX_Stream_Data *)stream->data;
1587 if(header.version != FCGI_VERSION_1) {
1588 return FCGX_UNSUPPORTED_VERSION;
1590 requestId = (header.requestIdB1 << 8)
1591 + header.requestIdB0;
1592 data->contentLen = (header.contentLengthB1 << 8)
1593 + header.contentLengthB0;
1594 data->paddingLen = header.paddingLength;
1595 if(header.type == FCGI_BEGIN_REQUEST) {
1596 return ProcessBeginRecord(requestId, stream);
1598 if(requestId == FCGI_NULL_REQUEST_ID) {
1599 return ProcessManagementRecord(header.type, stream);
1601 if(requestId != data->reqDataPtr->requestId) {
1604 if(header.type != data->type) {
1605 return FCGX_PROTOCOL_ERROR;
1607 return STREAM_RECORD;
1611 *----------------------------------------------------------------------
1615 * Reads bytes from the ipcFd, supplies bytes to a stream client.
1617 *----------------------------------------------------------------------
1619 static void FillBuffProc(FCGX_Stream *stream)
1621 FCGX_Stream_Data *data = (FCGX_Stream_Data *)stream->data;
1628 * If data->buff is empty, do a read.
1630 if(stream->rdNext == data->buffStop) {
1631 count = OS_Read(data->reqDataPtr->ipcFd, (char *)data->buff,
1634 SetError(stream, (count == 0 ? FCGX_PROTOCOL_ERROR : OS_Errno));
1637 stream->rdNext = data->buff;
1638 data->buffStop = data->buff + count;
1641 * Now data->buff is not empty. If the current record contains
1642 * more content bytes, deliver all that are present in data->buff.
1644 if(data->contentLen > 0) {
1645 count = min(data->contentLen, data->buffStop - stream->rdNext);
1646 data->contentLen -= count;
1648 stream->wrNext = stream->stop = stream->rdNext + count;
1651 stream->rdNext += count;
1652 if(data->contentLen > 0) {
1660 * If the current record (whose content has been fully consumed by
1661 * the client) was padded, skip over the padding bytes.
1663 if(data->paddingLen > 0) {
1664 count = min(data->paddingLen, data->buffStop - stream->rdNext);
1665 data->paddingLen -= count;
1666 stream->rdNext += count;
1667 if(data->paddingLen > 0) {
1672 * All done with the current record, including the padding.
1673 * If we're in a recursive call from ProcessHeader, deliver EOF.
1676 stream->stop = stream->rdNext;
1677 stream->isClosed = TRUE;
1681 * Fill header with bytes from the input buffer.
1683 count = min((int)sizeof(header) - headerLen,
1684 data->buffStop - stream->rdNext);
1685 memcpy(((char *)(&header)) + headerLen, stream->rdNext, count);
1687 stream->rdNext += count;
1688 if(headerLen < sizeof(header)) {
1693 * Interpret header. eorStop prevents ProcessHeader from reading
1694 * past the end-of-record when using stream to read content.
1696 data->eorStop = TRUE;
1697 stream->stop = stream->rdNext;
1698 status = ProcessHeader(header, stream);
1699 data->eorStop = FALSE;
1700 stream->isClosed = FALSE;
1704 * If this stream record header marked the end of stream
1705 * data deliver EOF to the stream client, otherwise loop
1708 * XXX: If this is final stream and
1709 * stream->rdNext != data->buffStop, buffered
1710 * data is next request (server pipelining)?
1712 if(data->contentLen == 0) {
1713 stream->wrNext = stream->stop = stream->rdNext;
1714 stream->isClosed = TRUE;
1723 * If this header marked the beginning of a new
1724 * request, return role information to caller.
1732 SetError(stream, status);
1740 *----------------------------------------------------------------------
1744 * Creates a stream to read or write from an open ipcFd.
1745 * The stream performs reads/writes of up to bufflen bytes.
1747 *----------------------------------------------------------------------
1749 static FCGX_Stream *NewStream(
1750 FCGX_Request *reqDataPtr, int bufflen, int isReader, int streamType)
1753 * XXX: It would be a lot cleaner to have a NewStream that only
1754 * knows about the type FCGX_Stream, with all other
1755 * necessary data passed in. It appears that not just
1756 * data and the two procs are needed for initializing stream,
1757 * but also data->buff and data->buffStop. This has implications
1758 * for procs that want to swap buffers, too.
1760 FCGX_Stream *stream = (FCGX_Stream *)Malloc(sizeof(FCGX_Stream));
1761 FCGX_Stream_Data *data = (FCGX_Stream_Data *)Malloc(sizeof(FCGX_Stream_Data));
1762 data->reqDataPtr = reqDataPtr;
1763 bufflen = AlignInt8(min(max(bufflen, 32), FCGI_MAX_LENGTH + 1));
1764 data->bufflen = bufflen;
1765 data->mBuff = (unsigned char *)Malloc(bufflen);
1766 data->buff = AlignPtr8(data->mBuff);
1767 if(data->buff != data->mBuff) {
1771 data->buffStop = data->buff;
1773 data->buffStop = data->buff + data->bufflen;
1775 data->type = streamType;
1776 data->eorStop = FALSE;
1778 data->contentLen = 0;
1779 data->paddingLen = 0;
1780 data->isAnythingWritten = FALSE;
1781 data->rawWrite = FALSE;
1783 stream->data = data;
1784 stream->isReader = isReader;
1785 stream->isClosed = FALSE;
1786 stream->wasFCloseCalled = FALSE;
1787 stream->FCGI_errno = 0;
1789 stream->fillBuffProc = FillBuffProc;
1790 stream->emptyBuffProc = NULL;
1791 stream->rdNext = data->buff;
1792 stream->stop = stream->rdNext;
1793 stream->stopUnget = data->buff;
1794 stream->wrNext = stream->stop;
1796 stream->fillBuffProc = NULL;
1797 stream->emptyBuffProc = EmptyBuffProc;
1798 stream->wrNext = data->buff + sizeof(FCGI_Header);
1799 stream->stop = data->buffStop;
1800 stream->stopUnget = NULL;
1801 stream->rdNext = stream->stop;
1807 *----------------------------------------------------------------------
1809 * FCGX_FreeStream --
1811 * Frees all storage allocated when *streamPtr was created,
1812 * and nulls out *streamPtr.
1814 *----------------------------------------------------------------------
1816 void FCGX_FreeStream(FCGX_Stream **streamPtr)
1818 FCGX_Stream *stream = *streamPtr;
1819 FCGX_Stream_Data *data;
1820 if(stream == NULL) {
1823 data = (FCGX_Stream_Data *)stream->data;
1824 data->reqDataPtr = NULL;
1832 *----------------------------------------------------------------------
1836 * Re-initializes the stream to read data of the specified type.
1838 *----------------------------------------------------------------------
1840 static FCGX_Stream *SetReaderType(FCGX_Stream *stream, int streamType)
1842 FCGX_Stream_Data *data = (FCGX_Stream_Data *)stream->data;
1843 ASSERT(stream->isReader);
1844 data->type = streamType;
1845 data->eorStop = FALSE;
1847 data->contentLen = 0;
1848 data->paddingLen = 0;
1849 stream->wrNext = stream->stop = stream->rdNext;
1850 stream->isClosed = FALSE;
1855 *----------------------------------------------------------------------
1859 * Creates a stream to read streamType records for the given
1860 * request. The stream performs OS reads of up to bufflen bytes.
1862 *----------------------------------------------------------------------
1864 static FCGX_Stream *NewReader(FCGX_Request *reqDataPtr, int bufflen, int streamType)
1866 return NewStream(reqDataPtr, bufflen, TRUE, streamType);
1870 *----------------------------------------------------------------------
1874 * Creates a stream to write streamType FastCGI records, using
1875 * the ipcFd and RequestId contained in *reqDataPtr.
1876 * The stream performs OS writes of up to bufflen bytes.
1878 *----------------------------------------------------------------------
1880 static FCGX_Stream *NewWriter(FCGX_Request *reqDataPtr, int bufflen, int streamType)
1882 return NewStream(reqDataPtr, bufflen, FALSE, streamType);
1886 *----------------------------------------------------------------------
1888 * FCGX_CreateWriter --
1890 * Creates a stream to write streamType FastCGI records, using
1891 * the given ipcFd and request Id. This function is provided
1892 * for use by cgi-fcgi. In order to be defensive against misuse,
1893 * this function leaks a little storage; cgi-fcgi doesn't care.
1895 *----------------------------------------------------------------------
1897 FCGX_Stream *FCGX_CreateWriter(
1903 FCGX_Request *reqDataPtr = (FCGX_Request *)Malloc(sizeof(FCGX_Request));
1904 reqDataPtr->ipcFd = ipcFd;
1905 reqDataPtr->requestId = requestId;
1907 * Suppress writing an FCGI_END_REQUEST record.
1909 reqDataPtr->nWriters = 2;
1910 return NewWriter(reqDataPtr, bufflen, streamType);
1914 *======================================================================
1916 *======================================================================
1920 *----------------------------------------------------------------------
1924 * This routine determines if the process is running as a CGI or
1925 * FastCGI process. The distinction is made by determining whether
1926 * FCGI_LISTENSOCK_FILENO is a listener ipcFd or the end of a
1927 * pipe (ie. standard in).
1930 * TRUE if the process is a CGI process, FALSE if FastCGI.
1932 *----------------------------------------------------------------------
1934 int FCGX_IsCGI(void)
1936 if (isFastCGI != -1) {
1940 if (!libInitialized) {
1941 int rc = FCGX_Init();
1943 /* exit() isn't great, but hey */
1944 exit((rc < 0) ? rc : -rc);
1948 isFastCGI = OS_IsFcgi(FCGI_LISTENSOCK_FILENO);
1954 *----------------------------------------------------------------------
1958 * Finishes the current request from the HTTP server.
1962 * Finishes the request accepted by (and frees any
1963 * storage allocated by) the previous call to FCGX_Accept.
1965 * DO NOT retain pointers to the envp array or any strings
1966 * contained in it (e.g. to the result of calling FCGX_GetParam),
1967 * since these will be freed by the next call to FCGX_Finish
1970 *----------------------------------------------------------------------
1973 void FCGX_Finish(void)
1975 FCGX_Finish_r(&the_request);
1979 *----------------------------------------------------------------------
1983 * Finishes the current request from the HTTP server.
1987 * Finishes the request accepted by (and frees any
1988 * storage allocated by) the previous call to FCGX_Accept.
1990 * DO NOT retain pointers to the envp array or any strings
1991 * contained in it (e.g. to the result of calling FCGX_GetParam),
1992 * since these will be freed by the next call to FCGX_Finish
1995 *----------------------------------------------------------------------
1997 void FCGX_Finish_r(FCGX_Request *reqDataPtr)
2001 if (reqDataPtr == NULL) {
2005 close = !reqDataPtr->keepConnection;
2007 /* This should probably use a 'status' member instead of 'in' */
2008 if (reqDataPtr->in) {
2009 close |= FCGX_FClose(reqDataPtr->err);
2010 close |= FCGX_FClose(reqDataPtr->out);
2012 close |= FCGX_GetError(reqDataPtr->in);
2015 FCGX_Free(reqDataPtr, close);
2018 void FCGX_Free(FCGX_Request * request, int close)
2020 if (request == NULL)
2023 FCGX_FreeStream(&request->in);
2024 FCGX_FreeStream(&request->out);
2025 FCGX_FreeStream(&request->err);
2026 FreeParams(&request->paramsPtr);
2029 OS_IpcClose(request->ipcFd);
2030 request->ipcFd = -1;
2034 int FCGX_OpenSocket(const char *path, int backlog)
2036 int rc = OS_CreateLocalIpcFd(path, backlog);
2037 if (rc == FCGI_LISTENSOCK_FILENO && isFastCGI == 0) {
2038 /* XXX probably need to call OS_LibInit() again for Win */
2044 int FCGX_InitRequest(FCGX_Request *request, int sock, int flags)
2046 memset(request, 0, sizeof(FCGX_Request));
2048 /* @@@ Should check that sock is open and listening */
2049 request->listen_sock = sock;
2051 /* @@@ Should validate against "known" flags */
2052 request->flags = flags;
2054 request->ipcFd = -1;
2060 *----------------------------------------------------------------------
2064 * Initilize the FCGX library. This is called by FCGX_Accept()
2065 * but must be called by the user when using FCGX_Accept_r().
2068 * 0 for successful call.
2070 *----------------------------------------------------------------------
2076 if (libInitialized) {
2080 FCGX_InitRequest(&the_request, FCGI_LISTENSOCK_FILENO, 0);
2082 if (OS_LibInit(NULL) == -1) {
2083 return OS_Errno ? OS_Errno : -9997;
2086 p = getenv("FCGI_WEB_SERVER_ADDRS");
2087 webServerAddressList = p ? StringCopy(p) : NULL;
2094 *----------------------------------------------------------------------
2098 * Accepts a new request from the HTTP server.
2101 * 0 for successful call, -1 for error.
2105 * Finishes the request accepted by (and frees any
2106 * storage allocated by) the previous call to FCGX_Accept.
2107 * Creates input, output, and error streams and
2108 * assigns them to *in, *out, and *err respectively.
2109 * Creates a parameters data structure to be accessed
2110 * via getenv(3) (if assigned to environ) or by FCGX_GetParam
2111 * and assigns it to *envp.
2113 * DO NOT retain pointers to the envp array or any strings
2114 * contained in it (e.g. to the result of calling FCGX_GetParam),
2115 * since these will be freed by the next call to FCGX_Finish
2118 *----------------------------------------------------------------------
2125 FCGX_ParamArray *envp)
2129 if (! libInitialized) {
2136 rc = FCGX_Accept_r(&the_request);
2138 *in = the_request.in;
2139 *out = the_request.out;
2140 *err = the_request.err;
2141 *envp = the_request.envp;
2147 *----------------------------------------------------------------------
2151 * Accepts a new request from the HTTP server.
2154 * 0 for successful call, -1 for error.
2158 * Finishes the request accepted by (and frees any
2159 * storage allocated by) the previous call to FCGX_Accept.
2160 * Creates input, output, and error streams and
2161 * assigns them to *in, *out, and *err respectively.
2162 * Creates a parameters data structure to be accessed
2163 * via getenv(3) (if assigned to environ) or by FCGX_GetParam
2164 * and assigns it to *envp.
2166 * DO NOT retain pointers to the envp array or any strings
2167 * contained in it (e.g. to the result of calling FCGX_GetParam),
2168 * since these will be freed by the next call to FCGX_Finish
2171 *----------------------------------------------------------------------
2173 int FCGX_Accept_r(FCGX_Request *reqDataPtr)
2175 if (!libInitialized) {
2179 /* Finish the current request, if any. */
2180 FCGX_Finish_r(reqDataPtr);
2184 * If a connection isn't open, accept a new connection (blocking).
2185 * If an OS error occurs in accepting the connection,
2186 * return -1 to the caller, who should exit.
2188 if (reqDataPtr->ipcFd < 0) {
2189 int fail_on_intr = reqDataPtr->flags & FCGI_FAIL_ACCEPT_ON_INTR;
2191 reqDataPtr->ipcFd = OS_Accept(reqDataPtr->listen_sock, fail_on_intr, webServerAddressList);
2192 if (reqDataPtr->ipcFd < 0) {
2193 return (errno > 0) ? (0 - errno) : -9999;
2197 * A connection is open. Read from the connection in order to
2198 * get the request's role and environment. If protocol or other
2199 * errors occur, close the connection and try again.
2201 reqDataPtr->isBeginProcessed = FALSE;
2202 reqDataPtr->in = NewReader(reqDataPtr, 8192, 0);
2203 FillBuffProc(reqDataPtr->in);
2204 if(!reqDataPtr->isBeginProcessed) {
2209 switch(reqDataPtr->role) {
2210 case FCGI_RESPONDER:
2211 roleStr = "FCGI_ROLE=RESPONDER";
2213 case FCGI_AUTHORIZER:
2214 roleStr = "FCGI_ROLE=AUTHORIZER";
2217 roleStr = "FCGI_ROLE=FILTER";
2222 reqDataPtr->paramsPtr = NewParams(30);
2223 PutParam(reqDataPtr->paramsPtr, StringCopy(roleStr));
2225 SetReaderType(reqDataPtr->in, FCGI_PARAMS);
2226 if(ReadParams(reqDataPtr->paramsPtr, reqDataPtr->in) >= 0) {
2228 * Finished reading the environment. No errors occurred, so
2229 * leave the connection-retry loop.
2235 * Close the connection and try again.
2238 FCGX_Free(reqDataPtr, 1);
2242 * Build the remaining data structures representing the new
2243 * request and return successfully to the caller.
2245 SetReaderType(reqDataPtr->in, FCGI_STDIN);
2246 reqDataPtr->out = NewWriter(reqDataPtr, 8192, FCGI_STDOUT);
2247 reqDataPtr->err = NewWriter(reqDataPtr, 512, FCGI_STDERR);
2248 reqDataPtr->nWriters = 2;
2249 reqDataPtr->envp = reqDataPtr->paramsPtr->vec;
2254 *----------------------------------------------------------------------
2256 * FCGX_StartFilterData --
2258 * stream is an input stream for a FCGI_FILTER request.
2259 * stream is positioned at EOF on FCGI_STDIN.
2260 * Repositions stream to the start of FCGI_DATA.
2261 * If the preconditions are not met (e.g. FCGI_STDIN has not
2262 * been read to EOF) sets the stream error code to
2263 * FCGX_CALL_SEQ_ERROR.
2266 * 0 for a normal return, < 0 for error
2268 *----------------------------------------------------------------------
2271 int FCGX_StartFilterData(FCGX_Stream *stream)
2273 FCGX_Stream_Data *data = (FCGX_Stream_Data *)stream->data;
2274 if(data->reqDataPtr->role != FCGI_FILTER
2275 || !stream->isReader
2276 || !stream->isClosed
2277 || data->type != FCGI_STDIN) {
2278 SetError(stream, FCGX_CALL_SEQ_ERROR);
2281 SetReaderType(stream, FCGI_DATA);
2286 *----------------------------------------------------------------------
2288 * FCGX_SetExitStatus --
2290 * Sets the exit status for stream's request. The exit status
2291 * is the status code the request would have exited with, had
2292 * the request been run as a CGI program. You can call
2293 * SetExitStatus several times during a request; the last call
2294 * before the request ends determines the value.
2296 *----------------------------------------------------------------------
2299 void FCGX_SetExitStatus(int status, FCGX_Stream *stream)
2301 FCGX_Stream_Data *data = (FCGX_Stream_Data *)stream->data;
2302 data->reqDataPtr->appStatus = status;