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.19 2001/06/03 21:46:43 robs Exp $";
17 #include "fcgi_config.h"
20 #define DLLAPI __declspec(dllexport)
25 #include <fcntl.h> /* for fcntl */
27 #include <memory.h> /* for memchr() */
32 #include <sys/types.h>
34 #ifdef HAVE_SYS_SOCKET_H
35 #include <sys/socket.h> /* for getpeername */
38 #ifdef HAVE_SYS_TIME_H
47 #include "fcgiappmisc.h"
53 * This is a workaround for one version of the HP C compiler
54 * (c89 on HP-UX 9.04, also Stratus FTX), which will dump core
55 * if given 'long double' for varargs.
57 #ifdef HAVE_VA_ARG_LONG_DOUBLE_BUG
58 #define LONG_DOUBLE double
60 #define LONG_DOUBLE long double
66 static int libInitialized = 0;
67 static int isFastCGI = -1;
68 static char *webServerAddressList = NULL;
69 static FCGX_Request the_request;
71 static void *Malloc(size_t size)
73 void *result = malloc(size);
74 ASSERT(size == 0 || result != NULL);
78 static char *StringCopy(char *str)
80 int strLen = strlen(str);
81 char *newString = (char *)Malloc(strLen + 1);
82 memcpy(newString, str, strLen);
83 newString[strLen] = '\000';
89 *----------------------------------------------------------------------
93 * Reads a byte from the input stream and returns it.
96 * The byte, or EOF (-1) if the end of input has been reached.
98 *----------------------------------------------------------------------
100 int FCGX_GetChar(FCGX_Stream *stream)
102 if(stream->rdNext != stream->stop)
103 return *stream->rdNext++;
104 if(stream->isClosed || !stream->isReader)
106 stream->fillBuffProc(stream);
107 stream->stopUnget = stream->rdNext;
108 if(stream->rdNext != stream->stop)
109 return *stream->rdNext++;
110 ASSERT(stream->isClosed); /* bug in fillBufProc if not */
115 *----------------------------------------------------------------------
119 * Reads up to n consecutive bytes from the input stream
120 * into the character array str. Performs no interpretation
121 * of the input bytes.
124 * Number of bytes read. If result is smaller than n,
125 * the end of input has been reached.
127 *----------------------------------------------------------------------
129 int FCGX_GetStr(char *str, int n, FCGX_Stream *stream)
137 * Fast path: n bytes are already available
139 if(n <= (stream->stop - stream->rdNext)) {
140 memcpy(str, stream->rdNext, n);
145 * General case: stream is closed or buffer fill procedure
150 if(stream->rdNext != stream->stop) {
151 m = min(n - bytesMoved, stream->stop - stream->rdNext);
152 memcpy(str, stream->rdNext, m);
159 if(stream->isClosed || !stream->isReader)
161 stream->fillBuffProc(stream);
162 stream->stopUnget = stream->rdNext;
167 *----------------------------------------------------------------------
171 * Reads up to n-1 consecutive bytes from the input stream
172 * into the character array str. Stops before n-1 bytes
173 * have been read if '\n' or EOF is read. The terminating '\n'
174 * is copied to str. After copying the last byte into str,
175 * stores a '\0' terminator.
178 * NULL if EOF is the first thing read from the input stream,
181 *----------------------------------------------------------------------
183 char *FCGX_GetLine(char *str, int n, FCGX_Stream *stream)
189 c = FCGX_GetChar(stream);
206 *----------------------------------------------------------------------
210 * Pushes back the character c onto the input stream. One
211 * character of pushback is guaranteed once a character
212 * has been read. No pushback is possible for EOF.
215 * Returns c if the pushback succeeded, EOF if not.
217 *----------------------------------------------------------------------
219 int FCGX_UnGetChar(int c, FCGX_Stream *stream) {
223 || stream->rdNext == stream->stopUnget)
231 *----------------------------------------------------------------------
235 * Returns EOF if end-of-file has been detected while reading
236 * from stream; otherwise returns 0.
238 * Note that FCGX_HasSeenEOF(s) may return 0, yet an immediately
239 * following FCGX_GetChar(s) may return EOF. This function, like
240 * the standard C stdio function feof, does not provide the
241 * ability to peek ahead.
244 * EOF if end-of-file has been detected, 0 if not.
246 *----------------------------------------------------------------------
248 int FCGX_HasSeenEOF(FCGX_Stream *stream) {
249 return (stream->isClosed) ? EOF : 0;
253 *----------------------------------------------------------------------
257 * Writes a byte to the output stream.
260 * The byte, or EOF (-1) if an error occurred.
262 *----------------------------------------------------------------------
264 int FCGX_PutChar(int c, FCGX_Stream *stream)
266 if(stream->wrNext != stream->stop)
267 return (*stream->wrNext++ = c);
268 if(stream->isClosed || stream->isReader)
270 stream->emptyBuffProc(stream, FALSE);
271 if(stream->wrNext != stream->stop)
272 return (*stream->wrNext++ = c);
273 ASSERT(stream->isClosed); /* bug in emptyBuffProc if not */
278 *----------------------------------------------------------------------
282 * Writes n consecutive bytes from the character array str
283 * into the output stream. Performs no interpretation
284 * of the output bytes.
287 * Number of bytes written (n) for normal return,
288 * EOF (-1) if an error occurred.
290 *----------------------------------------------------------------------
292 int FCGX_PutStr(const char *str, int n, FCGX_Stream *stream)
297 * Fast path: room for n bytes in the buffer
299 if(n <= (stream->stop - stream->wrNext)) {
300 memcpy(stream->wrNext, str, n);
305 * General case: stream is closed or buffer empty procedure
310 if(stream->wrNext != stream->stop) {
311 m = min(n - bytesMoved, stream->stop - stream->wrNext);
312 memcpy(stream->wrNext, str, m);
319 if(stream->isClosed || stream->isReader)
321 stream->emptyBuffProc(stream, FALSE);
326 *----------------------------------------------------------------------
330 * Writes a character string to the output stream.
333 * number of bytes written for normal return,
334 * EOF (-1) if an error occurred.
336 *----------------------------------------------------------------------
338 int FCGX_PutS(const char *str, FCGX_Stream *stream)
340 return FCGX_PutStr(str, strlen(str), stream);
344 *----------------------------------------------------------------------
348 * Performs output formatting and writes the results
349 * to the output stream.
352 * number of bytes written for normal return,
353 * EOF (-1) if an error occurred.
355 *----------------------------------------------------------------------
357 int FCGX_FPrintF(FCGX_Stream *stream, const char *format, ...)
361 va_start(ap, format);
362 result = FCGX_VFPrintF(stream, format, ap);
368 *----------------------------------------------------------------------
372 * Performs output formatting and writes the results
373 * to the output stream.
376 * number of bytes written for normal return,
377 * EOF (-1) if an error occurred.
379 *----------------------------------------------------------------------
382 #define PRINTF_BUFFLEN 100
384 * More than sufficient space for all unmodified conversions
387 #define FMT_BUFFLEN 25
389 * Max size of a format specifier is 1 + 5 + 7 + 7 + 2 + 1 + slop
391 static void CopyAndAdvance(char **destPtr, char **srcPtr, int n);
393 int FCGX_VFPrintF(FCGX_Stream *stream, const char *format, va_list arg)
395 char *f, *fStop, *percentPtr, *p, *fmtBuffPtr, *buffPtr;
396 int op, performedOp, sizeModifier, buffCount, buffLen, specifierLength;
397 int fastPath, n, auxBuffLen, buffReqd, minWidth, precision, exp;
398 char *auxBuffPtr = NULL;
400 char fmtBuff[FMT_BUFFLEN];
401 char buff[PRINTF_BUFFLEN];
406 unsigned unsignedArg;
407 unsigned long uLongArg;
408 unsigned short uShortArg;
415 LONG_DOUBLE lDoubleArg;
419 fStop = f + strlen(f);
421 percentPtr = (char *)memchr(f, '%', fStop - f);
422 if(percentPtr == NULL) percentPtr = fStop;
423 if(percentPtr != f) {
424 if(FCGX_PutStr(f, percentPtr - f, stream) < 0)
426 streamCount += percentPtr - f;
428 if(f == fStop) break;
432 * The following loop always executes either once or twice.
437 * Fast path: Scan optimistically, hoping that no flags,
438 * minimum field width, or precision are specified.
439 * Use the preallocated buffer, which is large enough
440 * for all fast path cases. If the conversion specifier
441 * is really more complex, run the loop a second time
442 * using the slow path.
443 * Note that fast path execution of %s bypasses the buffer
444 * and %f is not attempted on the fast path due to
445 * its large buffering requirements.
447 op = *(percentPtr + 1);
453 op = *(percentPtr + 2);
454 fmtBuff[1] = sizeModifier;
467 buffLen = PRINTF_BUFFLEN;
470 * Slow path: Scan the conversion specifier and construct
471 * a new format string, compute an upper bound on the
472 * amount of buffering that sprintf will require,
473 * and allocate a larger buffer if necessary.
476 fmtBuffPtr = &fmtBuff[1];
480 n = strspn(p, "-0+ #");
483 CopyAndAdvance(&fmtBuffPtr, &p, n);
485 * Scan minimum field width
487 n = strspn(p, "0123456789");
490 minWidth = va_arg(arg, int);
491 if(abs(minWidth) > 999999)
494 * The following use of strlen rather than the
495 * value returned from sprintf is because SUNOS4
496 * returns a char * instead of an int count.
498 sprintf(fmtBuffPtr, "%d", minWidth);
499 fmtBuffPtr += strlen(fmtBuffPtr);
505 minWidth = strtol(p, NULL, 10);
506 CopyAndAdvance(&fmtBuffPtr, &p, n);
514 CopyAndAdvance(&fmtBuffPtr, &p, 1);
515 n = strspn(p, "0123456789");
518 precision = va_arg(arg, int);
519 if(precision < 0) precision = 0;
520 if(precision > 999999)
523 * The following use of strlen rather than the
524 * value returned from sprintf is because SUNOS4
525 * returns a char * instead of an int count.
527 sprintf(fmtBuffPtr, "%d", precision);
528 fmtBuffPtr += strlen(fmtBuffPtr);
534 precision = strtol(p, NULL, 10);
535 CopyAndAdvance(&fmtBuffPtr, &p, n);
543 * Scan size modifier and conversion operation
550 CopyAndAdvance(&fmtBuffPtr, &p, 1);
557 CopyAndAdvance(&fmtBuffPtr, &p, 1);
558 ASSERT(fmtBuffPtr - fmtBuff < FMT_BUFFLEN);
560 specifierLength = p - percentPtr;
562 * Bound the required buffer size. For s and f
563 * conversions this requires examining the argument.
574 buffReqd = max(precision, 46);
577 charPtrArg = va_arg(arg, char *);
578 if (!charPtrArg) charPtrArg = "(null)";
579 if(precision == -1) {
580 buffReqd = strlen(charPtrArg);
582 p = (char *)memchr(charPtrArg, '\0', precision);
584 (p == NULL) ? precision : p - charPtrArg;
588 switch(sizeModifier) {
590 doubleArg = va_arg(arg, double);
591 frexp(doubleArg, &exp);
594 lDoubleArg = va_arg(arg, LONG_DOUBLE);
595 frexp(lDoubleArg, &exp);
600 if(precision == -1) precision = 6;
601 buffReqd = precision + 3 + ((exp > 0) ? exp/3 : 0);
607 if(precision == -1) precision = 6;
608 buffReqd = precision + 8;
616 buffReqd = max(buffReqd + 10, minWidth);
618 * Allocate the buffer
620 if(buffReqd <= PRINTF_BUFFLEN) {
622 buffLen = PRINTF_BUFFLEN;
624 if(auxBuffPtr == NULL || buffReqd > auxBuffLen) {
625 if(auxBuffPtr != NULL) free(auxBuffPtr);
626 auxBuffPtr = (char *)Malloc(buffReqd);
627 auxBuffLen = buffReqd;
628 if(auxBuffPtr == NULL)
631 buffPtr = auxBuffPtr;
632 buffLen = auxBuffLen;
636 * This giant switch statement requires the following variables
637 * to be set up: op, sizeModifier, arg, buffPtr, fmtBuff.
638 * When fastPath == FALSE and op == 's' or 'f', the argument
639 * has been read into charPtrArg, doubleArg, or lDoubleArg.
640 * The statement produces the boolean performedOp, TRUE iff
641 * the op/sizeModifier were executed and argument consumed;
642 * if performedOp, the characters written into buffPtr[]
643 * and the character count buffCount (== EOF meaning error).
645 * The switch cases are arranged in the same order as in the
646 * description of fprintf in section 15.11 of Harbison and Steele.
652 switch(sizeModifier) {
654 intArg = va_arg(arg, int);
655 sprintf(buffPtr, fmtBuff, intArg);
656 buffCount = strlen(buffPtr);
659 longArg = va_arg(arg, long);
660 sprintf(buffPtr, fmtBuff, longArg);
661 buffCount = strlen(buffPtr);
664 shortArg = (short) va_arg(arg, int);
665 sprintf(buffPtr, fmtBuff, shortArg);
666 buffCount = strlen(buffPtr);
676 switch(sizeModifier) {
678 unsignedArg = va_arg(arg, unsigned);
679 sprintf(buffPtr, fmtBuff, unsignedArg);
680 buffCount = strlen(buffPtr);
683 uLongArg = va_arg(arg, unsigned long);
684 sprintf(buffPtr, fmtBuff, uLongArg);
685 buffCount = strlen(buffPtr);
688 uShortArg = (unsigned short) va_arg(arg, int);
689 sprintf(buffPtr, fmtBuff, uShortArg);
690 buffCount = strlen(buffPtr);
697 switch(sizeModifier) {
699 intArg = va_arg(arg, int);
700 sprintf(buffPtr, fmtBuff, intArg);
701 buffCount = strlen(buffPtr);
705 * XXX: Allowed by ISO C Amendment 1, but
706 * many platforms don't yet support wint_t
714 switch(sizeModifier) {
717 buffPtr = va_arg(arg, char *);
718 buffCount = strlen(buffPtr);
719 buffLen = buffCount + 1;
721 sprintf(buffPtr, fmtBuff, charPtrArg);
722 buffCount = strlen(buffPtr);
727 * XXX: Don't know how to convert a sequence
728 * of wide characters into a byte stream, or
729 * even how to predict the buffering required.
737 if(sizeModifier != ' ')
739 voidPtrArg = va_arg(arg, void *);
740 sprintf(buffPtr, fmtBuff, voidPtrArg);
741 buffCount = strlen(buffPtr);
744 switch(sizeModifier) {
746 intPtrArg = va_arg(arg, int *);
747 *intPtrArg = streamCount;
750 longPtrArg = va_arg(arg, long *);
751 *longPtrArg = streamCount;
754 shortPtrArg = va_arg(arg, short *);
755 *shortPtrArg = streamCount;
767 switch(sizeModifier) {
769 sprintf(buffPtr, fmtBuff, doubleArg);
770 buffCount = strlen(buffPtr);
773 sprintf(buffPtr, fmtBuff, lDoubleArg);
774 buffCount = strlen(buffPtr);
784 switch(sizeModifier) {
786 doubleArg = va_arg(arg, double);
787 sprintf(buffPtr, fmtBuff, doubleArg);
788 buffCount = strlen(buffPtr);
791 lDoubleArg = va_arg(arg, LONG_DOUBLE);
792 sprintf(buffPtr, fmtBuff, lDoubleArg);
793 buffCount = strlen(buffPtr);
800 if(sizeModifier != ' ')
811 if(performedOp) break;
816 ASSERT(buffCount < buffLen);
818 if(FCGX_PutStr(buffPtr, buffCount, stream) < 0)
820 streamCount += buffCount;
821 } else if(buffCount < 0) {
824 f += specifierLength;
825 } /* while(f != fStop) */
830 if(auxBuffPtr != NULL) free(auxBuffPtr);
835 * Copy n characters from *srcPtr to *destPtr, then increment
836 * both *srcPtr and *destPtr by n.
838 static void CopyAndAdvance(char **destPtr, char **srcPtr, int n)
840 char *dest = *destPtr;
843 for (i = 0; i < n; i++)
850 *----------------------------------------------------------------------
854 * Flushes any buffered output.
856 * Server-push is a legitimate application of FCGX_FFlush.
857 * Otherwise, FCGX_FFlush is not very useful, since FCGX_Accept
858 * does it implicitly. FCGX_FFlush may reduce performance
859 * by increasing the total number of operating system calls
860 * the application makes.
863 * EOF (-1) if an error occurred.
865 *----------------------------------------------------------------------
867 int FCGX_FFlush(FCGX_Stream *stream)
869 if(stream->isClosed || stream->isReader)
871 stream->emptyBuffProc(stream, FALSE);
872 return (stream->isClosed) ? -1 : 0;
876 *----------------------------------------------------------------------
880 * Performs FCGX_FFlush and closes the stream.
882 * This is not a very useful operation, since FCGX_Accept
883 * does it implicitly. Closing the out stream before the
884 * err stream results in an extra write if there's nothing
885 * in the err stream, and therefore reduces performance.
888 * EOF (-1) if an error occurred.
890 *----------------------------------------------------------------------
892 int FCGX_FClose(FCGX_Stream *stream)
894 if (stream == NULL) return 0;
896 if(!stream->wasFCloseCalled) {
897 if(!stream->isReader) {
898 stream->emptyBuffProc(stream, TRUE);
900 stream->wasFCloseCalled = TRUE;
901 stream->isClosed = TRUE;
902 if(stream->isReader) {
903 stream->wrNext = stream->stop = stream->rdNext;
905 stream->rdNext = stream->stop = stream->wrNext;
908 return (stream->FCGI_errno == 0) ? 0 : EOF;
912 *----------------------------------------------------------------------
916 * An error has occurred; save the error code in the stream
917 * for diagnostic purposes and set the stream state so that
918 * reads return EOF and writes have no effect.
920 *----------------------------------------------------------------------
922 static void SetError(FCGX_Stream *stream, int FCGI_errno)
925 * Preserve only the first error.
927 if(stream->FCGI_errno == 0) {
928 stream->FCGI_errno = FCGI_errno;
929 stream->isClosed = TRUE;
934 *----------------------------------------------------------------------
938 * Return the stream error code. 0 means no error, > 0
939 * is an errno(2) error, < 0 is an FCGX_errno error.
941 *----------------------------------------------------------------------
943 int FCGX_GetError(FCGX_Stream *stream) {
944 return stream->FCGI_errno;
948 *----------------------------------------------------------------------
952 * Clear the stream error code and end-of-file indication.
954 *----------------------------------------------------------------------
956 void FCGX_ClearError(FCGX_Stream *stream) {
957 stream->FCGI_errno = 0;
959 * stream->isClosed = FALSE;
960 * XXX: should clear isClosed but work is needed to make it safe
961 * to do so. For example, if an application calls FClose, gets
962 * an I/O error on the write, calls ClearError and retries
963 * the FClose, FClose (really EmptyBuffProc) will write a second
964 * EOF record. If an application calls PutChar instead of FClose
965 * after the ClearError, the application will write more data.
966 * The stream's state must discriminate between various states
967 * of the stream that are now all lumped under isClosed.
972 *======================================================================
974 *======================================================================
978 * A vector of pointers representing the parameters received
979 * by a FastCGI application server, with the vector's length
980 * and last valid element so adding new parameters is efficient.
983 typedef struct Params {
984 FCGX_ParamArray vec; /* vector of strings */
985 int length; /* number of string vec can hold */
986 char **cur; /* current item in vec; *cur == NULL */
988 typedef Params *ParamsPtr;
991 *----------------------------------------------------------------------
995 * Creates a new Params structure.
998 * Pointer to the new structure.
1000 *----------------------------------------------------------------------
1002 static ParamsPtr NewParams(int length)
1005 result = (Params *)Malloc(sizeof(Params));
1006 result->vec = (char **)Malloc(length * sizeof(char *));
1007 result->length = length;
1008 result->cur = result->vec;
1009 *result->cur = NULL;
1014 *----------------------------------------------------------------------
1018 * Frees a Params structure and all the parameters it contains.
1021 * env becomes invalid.
1023 *----------------------------------------------------------------------
1025 static void FreeParams(ParamsPtr *paramsPtrPtr)
1027 ParamsPtr paramsPtr = *paramsPtrPtr;
1029 if(paramsPtr == NULL) {
1032 for (p = paramsPtr->vec; p < paramsPtr->cur; p++) {
1035 free(paramsPtr->vec);
1037 *paramsPtrPtr = NULL;
1041 *----------------------------------------------------------------------
1045 * Add a name/value pair to a Params structure.
1051 * Parameters structure updated.
1053 *----------------------------------------------------------------------
1055 static void PutParam(ParamsPtr paramsPtr, char *nameValue)
1059 *paramsPtr->cur++ = nameValue;
1060 size = paramsPtr->cur - paramsPtr->vec;
1061 if(size >= paramsPtr->length) {
1062 paramsPtr->length *= 2;
1063 paramsPtr->vec = (FCGX_ParamArray)realloc(paramsPtr->vec, paramsPtr->length * sizeof(char *));
1064 paramsPtr->cur = paramsPtr->vec + size;
1066 *paramsPtr->cur = NULL;
1070 *----------------------------------------------------------------------
1072 * FCGX_GetParam -- obtain value of FCGI parameter in environment
1076 * Value bound to name, NULL if name not present in the
1077 * environment envp. Caller must not mutate the result
1078 * or retain it past the end of this request.
1080 *----------------------------------------------------------------------
1082 char *FCGX_GetParam(const char *name, FCGX_ParamArray envp)
1087 if (name == NULL || envp == NULL) return NULL;
1091 for (p = envp; *p; ++p) {
1092 if((strncmp(name, *p, len) == 0) && ((*p)[len] == '=')) {
1100 *----------------------------------------------------------------------
1102 * Start of FastCGI-specific code
1104 *----------------------------------------------------------------------
1108 *----------------------------------------------------------------------
1112 * Reads FastCGI name-value pairs from stream until EOF. Converts
1113 * each pair to name=value format and adds it to Params structure.
1115 *----------------------------------------------------------------------
1117 static int ReadParams(Params *paramsPtr, FCGX_Stream *stream)
1119 int nameLen, valueLen;
1120 unsigned char lenBuff[3];
1123 while((nameLen = FCGX_GetChar(stream)) != EOF) {
1125 * Read name length (one or four bytes) and value length
1126 * (one or four bytes) from stream.
1128 if((nameLen & 0x80) != 0) {
1129 if(FCGX_GetStr((char *) &lenBuff[0], 3, stream) != 3) {
1130 SetError(stream, FCGX_PARAMS_ERROR);
1133 nameLen = ((nameLen & 0x7f) << 24) + (lenBuff[0] << 16)
1134 + (lenBuff[1] << 8) + lenBuff[2];
1136 if((valueLen = FCGX_GetChar(stream)) == EOF) {
1137 SetError(stream, FCGX_PARAMS_ERROR);
1140 if((valueLen & 0x80) != 0) {
1141 if(FCGX_GetStr((char *) &lenBuff[0], 3, stream) != 3) {
1142 SetError(stream, FCGX_PARAMS_ERROR);
1145 valueLen = ((valueLen & 0x7f) << 24) + (lenBuff[0] << 16)
1146 + (lenBuff[1] << 8) + lenBuff[2];
1149 * nameLen and valueLen are now valid; read the name and value
1150 * from stream and construct a standard environment entry.
1152 nameValue = (char *)Malloc(nameLen + valueLen + 2);
1153 if(FCGX_GetStr(nameValue, nameLen, stream) != nameLen) {
1154 SetError(stream, FCGX_PARAMS_ERROR);
1158 *(nameValue + nameLen) = '=';
1159 if(FCGX_GetStr(nameValue + nameLen + 1, valueLen, stream)
1161 SetError(stream, FCGX_PARAMS_ERROR);
1165 *(nameValue + nameLen + valueLen + 1) = '\0';
1166 PutParam(paramsPtr, nameValue);
1172 *----------------------------------------------------------------------
1176 * Constructs an FCGI_Header struct.
1178 *----------------------------------------------------------------------
1180 static FCGI_Header MakeHeader(
1187 ASSERT(contentLength >= 0 && contentLength <= FCGI_MAX_LENGTH);
1188 ASSERT(paddingLength >= 0 && paddingLength <= 0xff);
1189 header.version = FCGI_VERSION_1;
1191 header.requestIdB1 = (requestId >> 8) & 0xff;
1192 header.requestIdB0 = (requestId ) & 0xff;
1193 header.contentLengthB1 = (contentLength >> 8) & 0xff;
1194 header.contentLengthB0 = (contentLength ) & 0xff;
1195 header.paddingLength = paddingLength;
1196 header.reserved = 0;
1201 *----------------------------------------------------------------------
1203 * MakeEndRequestBody --
1205 * Constructs an FCGI_EndRequestBody struct.
1207 *----------------------------------------------------------------------
1209 static FCGI_EndRequestBody MakeEndRequestBody(
1213 FCGI_EndRequestBody body;
1214 body.appStatusB3 = (appStatus >> 24) & 0xff;
1215 body.appStatusB2 = (appStatus >> 16) & 0xff;
1216 body.appStatusB1 = (appStatus >> 8) & 0xff;
1217 body.appStatusB0 = (appStatus ) & 0xff;
1218 body.protocolStatus = protocolStatus;
1219 memset(body.reserved, 0, sizeof(body.reserved));
1224 *----------------------------------------------------------------------
1226 * MakeUnknownTypeBody --
1228 * Constructs an FCGI_MakeUnknownTypeBody struct.
1230 *----------------------------------------------------------------------
1232 static FCGI_UnknownTypeBody MakeUnknownTypeBody(
1235 FCGI_UnknownTypeBody body;
1237 memset(body.reserved, 0, sizeof(body.reserved));
1242 *----------------------------------------------------------------------
1246 * Returns the smallest integer greater than or equal to n
1247 * that's a multiple of 8.
1249 *----------------------------------------------------------------------
1251 static int AlignInt8(unsigned n) {
1252 return (n + 7) & (UINT_MAX - 7);
1256 *----------------------------------------------------------------------
1260 * Returns the smallest pointer greater than or equal to p
1261 * that's a multiple of 8.
1263 *----------------------------------------------------------------------
1265 static unsigned char *AlignPtr8(unsigned char *p) {
1266 unsigned long u = (unsigned long) p;
1267 u = ((u + 7) & (ULONG_MAX - 7)) - u;
1273 * State associated with a stream
1275 typedef struct FCGX_Stream_Data {
1276 unsigned char *buff; /* buffer after alignment */
1277 int bufflen; /* number of bytes buff can store */
1278 unsigned char *mBuff; /* buffer as returned by Malloc */
1279 unsigned char *buffStop; /* reader: last valid byte + 1 of entire buffer.
1280 * stop generally differs from buffStop for
1281 * readers because of record structure.
1282 * writer: buff + bufflen */
1283 int type; /* reader: FCGI_PARAMS or FCGI_STDIN
1284 * writer: FCGI_STDOUT or FCGI_STDERR */
1285 int eorStop; /* reader: stop stream at end-of-record */
1286 int skip; /* reader: don't deliver content bytes */
1287 int contentLen; /* reader: bytes of unread content */
1288 int paddingLen; /* reader: bytes of unread padding */
1289 int isAnythingWritten; /* writer: data has been written to ipcFd */
1290 int rawWrite; /* writer: write data without stream headers */
1291 FCGX_Request *reqDataPtr; /* request data not specific to one stream */
1295 *----------------------------------------------------------------------
1297 * WriteCloseRecords --
1299 * Writes an EOF record for the stream content if necessary.
1300 * If this is the last writer to close, writes an FCGI_END_REQUEST
1303 *----------------------------------------------------------------------
1305 static void WriteCloseRecords(struct FCGX_Stream *stream)
1307 FCGX_Stream_Data *data = (FCGX_Stream_Data *)stream->data;
1309 * Enter rawWrite mode so final records won't be encapsulated as
1312 data->rawWrite = TRUE;
1314 * Generate EOF for stream content if needed.
1316 if(!(data->type == FCGI_STDERR
1317 && stream->wrNext == data->buff
1318 && !data->isAnythingWritten)) {
1320 header = MakeHeader(data->type, data->reqDataPtr->requestId, 0, 0);
1321 FCGX_PutStr((char *) &header, sizeof(header), stream);
1324 * Generate FCGI_END_REQUEST record if needed.
1326 if(data->reqDataPtr->nWriters == 1) {
1327 FCGI_EndRequestRecord endRequestRecord;
1328 endRequestRecord.header = MakeHeader(FCGI_END_REQUEST,
1329 data->reqDataPtr->requestId,
1330 sizeof(endRequestRecord.body), 0);
1331 endRequestRecord.body = MakeEndRequestBody(
1332 data->reqDataPtr->appStatus, FCGI_REQUEST_COMPLETE);
1333 FCGX_PutStr((char *) &endRequestRecord,
1334 sizeof(endRequestRecord), stream);
1336 data->reqDataPtr->nWriters--;
1341 static int write_it_all(int fd, char *buf, int len)
1346 wrote = OS_Write(fd, buf, len);
1356 *----------------------------------------------------------------------
1360 * Encapsulates any buffered stream content in a FastCGI
1361 * record. Writes the data, making the buffer empty.
1363 *----------------------------------------------------------------------
1365 static void EmptyBuffProc(struct FCGX_Stream *stream, int doClose)
1367 FCGX_Stream_Data *data = (FCGX_Stream_Data *)stream->data;
1370 * If the buffer contains stream data, fill in the header.
1371 * Pad the record to a multiple of 8 bytes in length. Padding
1372 * can't overflow the buffer because the buffer is a multiple
1373 * of 8 bytes in length. If the buffer contains no stream
1374 * data, reclaim the space reserved for the header.
1376 if(!data->rawWrite) {
1377 cLen = stream->wrNext - data->buff - sizeof(FCGI_Header);
1379 eLen = AlignInt8(cLen);
1381 * Giving the padding a well-defined value keeps Purify happy.
1383 memset(stream->wrNext, 0, eLen - cLen);
1384 stream->wrNext += eLen - cLen;
1385 *((FCGI_Header *) data->buff)
1386 = MakeHeader(data->type,
1387 data->reqDataPtr->requestId, cLen, eLen - cLen);
1389 stream->wrNext = data->buff;
1393 WriteCloseRecords(stream);
1395 if (stream->wrNext != data->buff) {
1396 data->isAnythingWritten = TRUE;
1397 if (write_it_all(data->reqDataPtr->ipcFd, (char *)data->buff, stream->wrNext - data->buff) < 0) {
1398 SetError(stream, OS_Errno);
1401 stream->wrNext = data->buff;
1404 * The buffer is empty.
1406 if(!data->rawWrite) {
1407 stream->wrNext += sizeof(FCGI_Header);
1412 * Return codes for Process* functions
1414 #define STREAM_RECORD 0
1416 #define BEGIN_RECORD 2
1417 #define MGMT_RECORD 3
1420 *----------------------------------------------------------------------
1422 * ProcessManagementRecord --
1424 * Reads and responds to a management record. The only type of
1425 * management record this library understands is FCGI_GET_VALUES.
1426 * The only variables that this library's FCGI_GET_VALUES
1427 * understands are FCGI_MAX_CONNS, FCGI_MAX_REQS, and FCGI_MPXS_CONNS.
1428 * Ignore other FCGI_GET_VALUES variables; respond to other
1429 * management records with a FCGI_UNKNOWN_TYPE record.
1431 *----------------------------------------------------------------------
1433 static int ProcessManagementRecord(int type, FCGX_Stream *stream)
1435 FCGX_Stream_Data *data = (FCGX_Stream_Data *)stream->data;
1436 ParamsPtr paramsPtr = NewParams(3);
1438 char response[64]; /* 64 = 8 + 3*(1+1+14+1)* + padding */
1439 char *responseP = &response[FCGI_HEADER_LEN];
1442 if(type == FCGI_GET_VALUES) {
1443 ReadParams(paramsPtr, stream);
1444 if((FCGX_GetError(stream) != 0) || (data->contentLen != 0)) {
1445 FreeParams(¶msPtr);
1446 return FCGX_PROTOCOL_ERROR;
1448 for (pPtr = paramsPtr->vec; pPtr < paramsPtr->cur; pPtr++) {
1450 *(strchr(name, '=')) = '\0';
1451 if(strcmp(name, FCGI_MAX_CONNS) == 0) {
1453 } else if(strcmp(name, FCGI_MAX_REQS) == 0) {
1455 } else if(strcmp(name, FCGI_MPXS_CONNS) == 0) {
1462 sprintf(responseP, "%c%c%s%c", len, 1, name, value);
1463 responseP += len + 3;
1466 len = responseP - &response[FCGI_HEADER_LEN];
1467 paddedLen = AlignInt8(len);
1468 *((FCGI_Header *) response)
1469 = MakeHeader(FCGI_GET_VALUES_RESULT, FCGI_NULL_REQUEST_ID,
1470 len, paddedLen - len);
1471 FreeParams(¶msPtr);
1473 paddedLen = len = sizeof(FCGI_UnknownTypeBody);
1474 ((FCGI_UnknownTypeRecord *) response)->header
1475 = MakeHeader(FCGI_UNKNOWN_TYPE, FCGI_NULL_REQUEST_ID,
1477 ((FCGI_UnknownTypeRecord *) response)->body
1478 = MakeUnknownTypeBody(type);
1480 if (write_it_all(data->reqDataPtr->ipcFd, response, FCGI_HEADER_LEN + paddedLen) < 0) {
1481 SetError(stream, OS_Errno);
1489 *----------------------------------------------------------------------
1491 * ProcessBeginRecord --
1493 * Reads an FCGI_BEGIN_REQUEST record.
1496 * BEGIN_RECORD for normal return. FCGX_PROTOCOL_ERROR for
1497 * protocol error. SKIP for attempt to multiplex
1498 * connection. -1 for error from write (errno in stream).
1501 * In case of BEGIN_RECORD return, stores requestId, role,
1502 * keepConnection values, and sets isBeginProcessed = TRUE.
1504 *----------------------------------------------------------------------
1506 static int ProcessBeginRecord(int requestId, FCGX_Stream *stream)
1508 FCGX_Stream_Data *data = (FCGX_Stream_Data *)stream->data;
1509 FCGI_BeginRequestBody body;
1510 if(requestId == 0 || data->contentLen != sizeof(body)) {
1511 return FCGX_PROTOCOL_ERROR;
1513 if(data->reqDataPtr->isBeginProcessed) {
1515 * The Web server is multiplexing the connection. This library
1516 * doesn't know how to handle multiplexing, so respond with
1517 * FCGI_END_REQUEST{protocolStatus = FCGI_CANT_MPX_CONN}
1519 FCGI_EndRequestRecord endRequestRecord;
1520 endRequestRecord.header = MakeHeader(FCGI_END_REQUEST,
1521 requestId, sizeof(endRequestRecord.body), 0);
1522 endRequestRecord.body
1523 = MakeEndRequestBody(0, FCGI_CANT_MPX_CONN);
1524 if (write_it_all(data->reqDataPtr->ipcFd, (char *)&endRequestRecord, sizeof(endRequestRecord)) < 0) {
1525 SetError(stream, OS_Errno);
1532 * Accept this new request. Read the record body.
1534 data->reqDataPtr->requestId = requestId;
1535 if(FCGX_GetStr((char *) &body, sizeof(body), stream)
1537 return FCGX_PROTOCOL_ERROR;
1539 data->reqDataPtr->keepConnection = (body.flags & FCGI_KEEP_CONN);
1540 data->reqDataPtr->role = (body.roleB1 << 8) + body.roleB0;
1541 data->reqDataPtr->isBeginProcessed = TRUE;
1542 return BEGIN_RECORD;
1546 *----------------------------------------------------------------------
1550 * Interprets FCGI_Header. Processes FCGI_BEGIN_REQUEST and
1551 * management records here; extracts information from stream
1552 * records (FCGI_PARAMS, FCGI_STDIN) into stream.
1555 * >= 0 for a normal return, < 0 for error
1558 * XXX: Many (more than there used to be).
1559 * If !stream->isRequestIdSet, ProcessHeader initializes
1560 * stream->requestId from header and sets stream->isRequestIdSet
1561 * to TRUE. ProcessHeader also sets stream->contentLen to header's
1562 * contentLength, and sets stream->paddingLen to the header's
1565 *----------------------------------------------------------------------
1567 static int ProcessHeader(FCGI_Header header, FCGX_Stream *stream)
1569 FCGX_Stream_Data *data = (FCGX_Stream_Data *)stream->data;
1571 if(header.version != FCGI_VERSION_1) {
1572 return FCGX_UNSUPPORTED_VERSION;
1574 requestId = (header.requestIdB1 << 8)
1575 + header.requestIdB0;
1576 data->contentLen = (header.contentLengthB1 << 8)
1577 + header.contentLengthB0;
1578 data->paddingLen = header.paddingLength;
1579 if(header.type == FCGI_BEGIN_REQUEST) {
1580 return ProcessBeginRecord(requestId, stream);
1582 if(requestId == FCGI_NULL_REQUEST_ID) {
1583 return ProcessManagementRecord(header.type, stream);
1585 if(requestId != data->reqDataPtr->requestId) {
1588 if(header.type != data->type) {
1589 return FCGX_PROTOCOL_ERROR;
1591 return STREAM_RECORD;
1595 *----------------------------------------------------------------------
1599 * Reads bytes from the ipcFd, supplies bytes to a stream client.
1601 *----------------------------------------------------------------------
1603 static void FillBuffProc(FCGX_Stream *stream)
1605 FCGX_Stream_Data *data = (FCGX_Stream_Data *)stream->data;
1612 * If data->buff is empty, do a read.
1614 if(stream->rdNext == data->buffStop) {
1615 count = OS_Read(data->reqDataPtr->ipcFd, (char *)data->buff,
1618 SetError(stream, (count == 0 ? FCGX_PROTOCOL_ERROR : OS_Errno));
1621 stream->rdNext = data->buff;
1622 data->buffStop = data->buff + count;
1625 * Now data->buff is not empty. If the current record contains
1626 * more content bytes, deliver all that are present in data->buff.
1628 if(data->contentLen > 0) {
1629 count = min(data->contentLen, data->buffStop - stream->rdNext);
1630 data->contentLen -= count;
1632 stream->wrNext = stream->stop = stream->rdNext + count;
1635 stream->rdNext += count;
1636 if(data->contentLen > 0) {
1644 * If the current record (whose content has been fully consumed by
1645 * the client) was padded, skip over the padding bytes.
1647 if(data->paddingLen > 0) {
1648 count = min(data->paddingLen, data->buffStop - stream->rdNext);
1649 data->paddingLen -= count;
1650 stream->rdNext += count;
1651 if(data->paddingLen > 0) {
1656 * All done with the current record, including the padding.
1657 * If we're in a recursive call from ProcessHeader, deliver EOF.
1660 stream->stop = stream->rdNext;
1661 stream->isClosed = TRUE;
1665 * Fill header with bytes from the input buffer.
1667 count = min((int)sizeof(header) - headerLen,
1668 data->buffStop - stream->rdNext);
1669 memcpy(((char *)(&header)) + headerLen, stream->rdNext, count);
1671 stream->rdNext += count;
1672 if(headerLen < sizeof(header)) {
1677 * Interpret header. eorStop prevents ProcessHeader from reading
1678 * past the end-of-record when using stream to read content.
1680 data->eorStop = TRUE;
1681 stream->stop = stream->rdNext;
1682 status = ProcessHeader(header, stream);
1683 data->eorStop = FALSE;
1684 stream->isClosed = FALSE;
1688 * If this stream record header marked the end of stream
1689 * data deliver EOF to the stream client, otherwise loop
1692 * XXX: If this is final stream and
1693 * stream->rdNext != data->buffStop, buffered
1694 * data is next request (server pipelining)?
1696 if(data->contentLen == 0) {
1697 stream->wrNext = stream->stop = stream->rdNext;
1698 stream->isClosed = TRUE;
1707 * If this header marked the beginning of a new
1708 * request, return role information to caller.
1716 SetError(stream, status);
1724 *----------------------------------------------------------------------
1728 * Creates a stream to read or write from an open ipcFd.
1729 * The stream performs reads/writes of up to bufflen bytes.
1731 *----------------------------------------------------------------------
1733 static FCGX_Stream *NewStream(
1734 FCGX_Request *reqDataPtr, int bufflen, int isReader, int streamType)
1737 * XXX: It would be a lot cleaner to have a NewStream that only
1738 * knows about the type FCGX_Stream, with all other
1739 * necessary data passed in. It appears that not just
1740 * data and the two procs are needed for initializing stream,
1741 * but also data->buff and data->buffStop. This has implications
1742 * for procs that want to swap buffers, too.
1744 FCGX_Stream *stream = (FCGX_Stream *)Malloc(sizeof(FCGX_Stream));
1745 FCGX_Stream_Data *data = (FCGX_Stream_Data *)Malloc(sizeof(FCGX_Stream_Data));
1746 data->reqDataPtr = reqDataPtr;
1747 bufflen = AlignInt8(min(max(bufflen, 32), FCGI_MAX_LENGTH + 1));
1748 data->bufflen = bufflen;
1749 data->mBuff = (unsigned char *)Malloc(bufflen);
1750 data->buff = AlignPtr8(data->mBuff);
1751 if(data->buff != data->mBuff) {
1755 data->buffStop = data->buff;
1757 data->buffStop = data->buff + data->bufflen;
1759 data->type = streamType;
1760 data->eorStop = FALSE;
1762 data->contentLen = 0;
1763 data->paddingLen = 0;
1764 data->isAnythingWritten = FALSE;
1765 data->rawWrite = FALSE;
1767 stream->data = data;
1768 stream->isReader = isReader;
1769 stream->isClosed = FALSE;
1770 stream->wasFCloseCalled = FALSE;
1771 stream->FCGI_errno = 0;
1773 stream->fillBuffProc = FillBuffProc;
1774 stream->emptyBuffProc = NULL;
1775 stream->rdNext = data->buff;
1776 stream->stop = stream->rdNext;
1777 stream->stopUnget = data->buff;
1778 stream->wrNext = stream->stop;
1780 stream->fillBuffProc = NULL;
1781 stream->emptyBuffProc = EmptyBuffProc;
1782 stream->wrNext = data->buff + sizeof(FCGI_Header);
1783 stream->stop = data->buffStop;
1784 stream->stopUnget = NULL;
1785 stream->rdNext = stream->stop;
1791 *----------------------------------------------------------------------
1795 * Frees all storage allocated when *streamPtr was created,
1796 * and nulls out *streamPtr.
1798 *----------------------------------------------------------------------
1800 void FreeStream(FCGX_Stream **streamPtr)
1802 FCGX_Stream *stream = *streamPtr;
1803 FCGX_Stream_Data *data;
1804 if(stream == NULL) {
1807 data = (FCGX_Stream_Data *)stream->data;
1808 data->reqDataPtr = NULL;
1816 *----------------------------------------------------------------------
1820 * Re-initializes the stream to read data of the specified type.
1822 *----------------------------------------------------------------------
1824 static FCGX_Stream *SetReaderType(FCGX_Stream *stream, int streamType)
1826 FCGX_Stream_Data *data = (FCGX_Stream_Data *)stream->data;
1827 ASSERT(stream->isReader);
1828 data->type = streamType;
1829 data->eorStop = FALSE;
1831 data->contentLen = 0;
1832 data->paddingLen = 0;
1833 stream->wrNext = stream->stop = stream->rdNext;
1834 stream->isClosed = FALSE;
1839 *----------------------------------------------------------------------
1843 * Creates a stream to read streamType records for the given
1844 * request. The stream performs OS reads of up to bufflen bytes.
1846 *----------------------------------------------------------------------
1848 static FCGX_Stream *NewReader(FCGX_Request *reqDataPtr, int bufflen, int streamType)
1850 return NewStream(reqDataPtr, bufflen, TRUE, streamType);
1855 *----------------------------------------------------------------------
1859 * Creates a stream to write streamType FastCGI records, using
1860 * the ipcFd and RequestId contained in *reqDataPtr.
1861 * The stream performs OS writes of up to bufflen bytes.
1863 *----------------------------------------------------------------------
1865 static FCGX_Stream *NewWriter(FCGX_Request *reqDataPtr, int bufflen, int streamType)
1867 return NewStream(reqDataPtr, bufflen, FALSE, streamType);
1872 *----------------------------------------------------------------------
1876 * Creates a stream to write streamType FastCGI records, using
1877 * the given ipcFd and request Id. This function is provided
1878 * for use by cgi-fcgi. In order to be defensive against misuse,
1879 * this function leaks a little storage; cgi-fcgi doesn't care.
1881 *----------------------------------------------------------------------
1883 FCGX_Stream *CreateWriter(
1889 FCGX_Request *reqDataPtr = (FCGX_Request *)Malloc(sizeof(FCGX_Request));
1890 reqDataPtr->ipcFd = ipcFd;
1891 reqDataPtr->requestId = requestId;
1893 * Suppress writing an FCGI_END_REQUEST record.
1895 reqDataPtr->nWriters = 2;
1896 return NewWriter(reqDataPtr, bufflen, streamType);
1900 *======================================================================
1902 *======================================================================
1906 *----------------------------------------------------------------------
1910 * This routine determines if the process is running as a CGI or
1911 * FastCGI process. The distinction is made by determining whether
1912 * FCGI_LISTENSOCK_FILENO is a listener ipcFd or the end of a
1913 * pipe (ie. standard in).
1916 * TRUE if the process is a CGI process, FALSE if FastCGI.
1918 *----------------------------------------------------------------------
1920 int FCGX_IsCGI(void)
1922 if (isFastCGI != -1) {
1926 if (!libInitialized) {
1927 int rc = FCGX_Init();
1929 /* exit() isn't great, but hey */
1930 exit((rc < 0) ? rc : -rc);
1934 isFastCGI = OS_IsFcgi(FCGI_LISTENSOCK_FILENO);
1940 *----------------------------------------------------------------------
1944 * Finishes the current request from the HTTP server.
1948 * Finishes the request accepted by (and frees any
1949 * storage allocated by) the previous call to FCGX_Accept.
1951 * DO NOT retain pointers to the envp array or any strings
1952 * contained in it (e.g. to the result of calling FCGX_GetParam),
1953 * since these will be freed by the next call to FCGX_Finish
1956 *----------------------------------------------------------------------
1959 void FCGX_Finish(void)
1961 FCGX_Finish_r(&the_request);
1965 *----------------------------------------------------------------------
1969 * Finishes the current request from the HTTP server.
1973 * Finishes the request accepted by (and frees any
1974 * storage allocated by) the previous call to FCGX_Accept.
1976 * DO NOT retain pointers to the envp array or any strings
1977 * contained in it (e.g. to the result of calling FCGX_GetParam),
1978 * since these will be freed by the next call to FCGX_Finish
1981 *----------------------------------------------------------------------
1983 void FCGX_Finish_r(FCGX_Request *reqDataPtr)
1985 if (reqDataPtr == NULL) {
1989 /* This should probably use a 'status' member instead of 'in' */
1990 if (reqDataPtr->in) {
1991 int errStatus = FCGX_FClose(reqDataPtr->err);
1992 int outStatus = FCGX_FClose(reqDataPtr->out);
1994 if (errStatus || outStatus || FCGX_GetError(reqDataPtr->in))
1996 OS_IpcClose(reqDataPtr->ipcFd);
1997 reqDataPtr->ipcFd = -1;
2001 FCGX_Free(reqDataPtr);
2004 void FCGX_Free(FCGX_Request * request)
2006 if (request == NULL)
2009 FreeStream(&request->in);
2010 FreeStream(&request->out);
2011 FreeStream(&request->err);
2012 FreeParams(&request->paramsPtr);
2014 if (!request->keepConnection)
2016 OS_IpcClose(request->ipcFd);
2017 request->ipcFd = -1;
2021 int FCGX_OpenSocket(const char *path, int backlog)
2023 int rc = OS_CreateLocalIpcFd(path, backlog);
2024 if (rc == FCGI_LISTENSOCK_FILENO && isFastCGI == 0) {
2025 /* XXX probably need to call OS_LibInit() again for Win */
2031 int FCGX_InitRequest(FCGX_Request *request, int sock, int flags)
2033 memset(request, 0, sizeof(FCGX_Request));
2035 /* @@@ Should check that sock is open and listening */
2036 request->listen_sock = sock;
2038 /* @@@ Should validate against "known" flags */
2039 request->flags = flags;
2041 request->ipcFd = -1;
2047 *----------------------------------------------------------------------
2051 * Initilize the FCGX library. This is called by FCGX_Accept()
2052 * but must be called by the user when using FCGX_Accept_r().
2055 * 0 for successful call.
2057 *----------------------------------------------------------------------
2063 if (libInitialized) {
2067 /* If our compiler doesn't play by the ISO rules for struct layout, halt. */
2068 ASSERT(sizeof(FCGI_Header) == FCGI_HEADER_LEN);
2070 FCGX_InitRequest(&the_request, FCGI_LISTENSOCK_FILENO, 0);
2072 if (OS_LibInit(NULL) == -1) {
2073 return OS_Errno ? OS_Errno : -9997;
2076 p = getenv("FCGI_WEB_SERVER_ADDRS");
2077 webServerAddressList = p ? StringCopy(p) : NULL;
2084 *----------------------------------------------------------------------
2088 * Accepts a new request from the HTTP server.
2091 * 0 for successful call, -1 for error.
2095 * Finishes the request accepted by (and frees any
2096 * storage allocated by) the previous call to FCGX_Accept.
2097 * Creates input, output, and error streams and
2098 * assigns them to *in, *out, and *err respectively.
2099 * Creates a parameters data structure to be accessed
2100 * via getenv(3) (if assigned to environ) or by FCGX_GetParam
2101 * and assigns it to *envp.
2103 * DO NOT retain pointers to the envp array or any strings
2104 * contained in it (e.g. to the result of calling FCGX_GetParam),
2105 * since these will be freed by the next call to FCGX_Finish
2108 *----------------------------------------------------------------------
2115 FCGX_ParamArray *envp)
2119 if (!libInitialized) {
2120 if ((rc = FCGX_Init())) {
2121 return (rc < 0) ? rc : -rc;
2125 rc = FCGX_Accept_r(&the_request);
2127 *in = the_request.in;
2128 *out = the_request.out;
2129 *err = the_request.err;
2130 *envp = the_request.envp;
2136 *----------------------------------------------------------------------
2140 * Accepts a new request from the HTTP server.
2143 * 0 for successful call, -1 for error.
2147 * Finishes the request accepted by (and frees any
2148 * storage allocated by) the previous call to FCGX_Accept.
2149 * Creates input, output, and error streams and
2150 * assigns them to *in, *out, and *err respectively.
2151 * Creates a parameters data structure to be accessed
2152 * via getenv(3) (if assigned to environ) or by FCGX_GetParam
2153 * and assigns it to *envp.
2155 * DO NOT retain pointers to the envp array or any strings
2156 * contained in it (e.g. to the result of calling FCGX_GetParam),
2157 * since these will be freed by the next call to FCGX_Finish
2160 *----------------------------------------------------------------------
2162 int FCGX_Accept_r(FCGX_Request *reqDataPtr)
2164 if (!libInitialized) {
2168 /* Finish the current request, if any. */
2169 FCGX_Finish_r(reqDataPtr);
2173 * If a connection isn't open, accept a new connection (blocking).
2174 * If an OS error occurs in accepting the connection,
2175 * return -1 to the caller, who should exit.
2177 if (reqDataPtr->ipcFd < 0) {
2178 int fail_on_intr = reqDataPtr->flags & FCGI_FAIL_ACCEPT_ON_INTR;
2180 reqDataPtr->ipcFd = OS_Accept(reqDataPtr->listen_sock, fail_on_intr, webServerAddressList);
2181 if (reqDataPtr->ipcFd < 0) {
2182 return (errno > 0) ? (0 - errno) : -9999;
2186 * A connection is open. Read from the connection in order to
2187 * get the request's role and environment. If protocol or other
2188 * errors occur, close the connection and try again.
2190 reqDataPtr->isBeginProcessed = FALSE;
2191 reqDataPtr->in = NewReader(reqDataPtr, 8192, 0);
2192 FillBuffProc(reqDataPtr->in);
2193 if(!reqDataPtr->isBeginProcessed) {
2198 switch(reqDataPtr->role) {
2199 case FCGI_RESPONDER:
2200 roleStr = "FCGI_ROLE=RESPONDER";
2202 case FCGI_AUTHORIZER:
2203 roleStr = "FCGI_ROLE=AUTHORIZER";
2206 roleStr = "FCGI_ROLE=FILTER";
2211 reqDataPtr->paramsPtr = NewParams(30);
2212 PutParam(reqDataPtr->paramsPtr, StringCopy(roleStr));
2214 SetReaderType(reqDataPtr->in, FCGI_PARAMS);
2215 if(ReadParams(reqDataPtr->paramsPtr, reqDataPtr->in) >= 0) {
2217 * Finished reading the environment. No errors occurred, so
2218 * leave the connection-retry loop.
2224 * Close the connection and try again.
2227 FCGX_Free(reqDataPtr);
2231 * Build the remaining data structures representing the new
2232 * request and return successfully to the caller.
2234 SetReaderType(reqDataPtr->in, FCGI_STDIN);
2235 reqDataPtr->out = NewWriter(reqDataPtr, 8192, FCGI_STDOUT);
2236 reqDataPtr->err = NewWriter(reqDataPtr, 512, FCGI_STDERR);
2237 reqDataPtr->nWriters = 2;
2238 reqDataPtr->envp = reqDataPtr->paramsPtr->vec;
2243 *----------------------------------------------------------------------
2245 * FCGX_StartFilterData --
2247 * stream is an input stream for a FCGI_FILTER request.
2248 * stream is positioned at EOF on FCGI_STDIN.
2249 * Repositions stream to the start of FCGI_DATA.
2250 * If the preconditions are not met (e.g. FCGI_STDIN has not
2251 * been read to EOF) sets the stream error code to
2252 * FCGX_CALL_SEQ_ERROR.
2255 * 0 for a normal return, < 0 for error
2257 *----------------------------------------------------------------------
2260 int FCGX_StartFilterData(FCGX_Stream *stream)
2262 FCGX_Stream_Data *data = (FCGX_Stream_Data *)stream->data;
2263 if(data->reqDataPtr->role != FCGI_FILTER
2264 || !stream->isReader
2265 || !stream->isClosed
2266 || data->type != FCGI_STDIN) {
2267 SetError(stream, FCGX_CALL_SEQ_ERROR);
2270 SetReaderType(stream, FCGI_DATA);
2275 *----------------------------------------------------------------------
2277 * FCGX_SetExitStatus --
2279 * Sets the exit status for stream's request. The exit status
2280 * is the status code the request would have exited with, had
2281 * the request been run as a CGI program. You can call
2282 * SetExitStatus several times during a request; the last call
2283 * before the request ends determines the value.
2285 *----------------------------------------------------------------------
2288 void FCGX_SetExitStatus(int status, FCGX_Stream *stream)
2290 FCGX_Stream_Data *data = (FCGX_Stream_Data *)stream->data;
2291 data->reqDataPtr->appStatus = status;