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.15 2000/10/02 12:43:13 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(len == 0) return NULL;
1088 for (p = envp; *p != NULL; p++) {
1089 if((strncmp(name, *p, len) == 0) && ((*p)[len] == '=')) {
1097 *----------------------------------------------------------------------
1099 * Start of FastCGI-specific code
1101 *----------------------------------------------------------------------
1105 *----------------------------------------------------------------------
1109 * Reads FastCGI name-value pairs from stream until EOF. Converts
1110 * each pair to name=value format and adds it to Params structure.
1112 *----------------------------------------------------------------------
1114 static int ReadParams(Params *paramsPtr, FCGX_Stream *stream)
1116 int nameLen, valueLen;
1117 unsigned char lenBuff[3];
1120 while((nameLen = FCGX_GetChar(stream)) != EOF) {
1122 * Read name length (one or four bytes) and value length
1123 * (one or four bytes) from stream.
1125 if((nameLen & 0x80) != 0) {
1126 if(FCGX_GetStr((char *) &lenBuff[0], 3, stream) != 3) {
1127 SetError(stream, FCGX_PARAMS_ERROR);
1130 nameLen = ((nameLen & 0x7f) << 24) + (lenBuff[0] << 16)
1131 + (lenBuff[1] << 8) + lenBuff[2];
1133 if((valueLen = FCGX_GetChar(stream)) == EOF) {
1134 SetError(stream, FCGX_PARAMS_ERROR);
1137 if((valueLen & 0x80) != 0) {
1138 if(FCGX_GetStr((char *) &lenBuff[0], 3, stream) != 3) {
1139 SetError(stream, FCGX_PARAMS_ERROR);
1142 valueLen = ((valueLen & 0x7f) << 24) + (lenBuff[0] << 16)
1143 + (lenBuff[1] << 8) + lenBuff[2];
1146 * nameLen and valueLen are now valid; read the name and value
1147 * from stream and construct a standard environment entry.
1149 nameValue = (char *)Malloc(nameLen + valueLen + 2);
1150 if(FCGX_GetStr(nameValue, nameLen, stream) != nameLen) {
1151 SetError(stream, FCGX_PARAMS_ERROR);
1155 *(nameValue + nameLen) = '=';
1156 if(FCGX_GetStr(nameValue + nameLen + 1, valueLen, stream)
1158 SetError(stream, FCGX_PARAMS_ERROR);
1162 *(nameValue + nameLen + valueLen + 1) = '\0';
1163 PutParam(paramsPtr, nameValue);
1169 *----------------------------------------------------------------------
1173 * Constructs an FCGI_Header struct.
1175 *----------------------------------------------------------------------
1177 static FCGI_Header MakeHeader(
1184 ASSERT(contentLength >= 0 && contentLength <= FCGI_MAX_LENGTH);
1185 ASSERT(paddingLength >= 0 && paddingLength <= 0xff);
1186 header.version = FCGI_VERSION_1;
1188 header.requestIdB1 = (requestId >> 8) & 0xff;
1189 header.requestIdB0 = (requestId ) & 0xff;
1190 header.contentLengthB1 = (contentLength >> 8) & 0xff;
1191 header.contentLengthB0 = (contentLength ) & 0xff;
1192 header.paddingLength = paddingLength;
1193 header.reserved = 0;
1198 *----------------------------------------------------------------------
1200 * MakeEndRequestBody --
1202 * Constructs an FCGI_EndRequestBody struct.
1204 *----------------------------------------------------------------------
1206 static FCGI_EndRequestBody MakeEndRequestBody(
1210 FCGI_EndRequestBody body;
1211 body.appStatusB3 = (appStatus >> 24) & 0xff;
1212 body.appStatusB2 = (appStatus >> 16) & 0xff;
1213 body.appStatusB1 = (appStatus >> 8) & 0xff;
1214 body.appStatusB0 = (appStatus ) & 0xff;
1215 body.protocolStatus = protocolStatus;
1216 memset(body.reserved, 0, sizeof(body.reserved));
1221 *----------------------------------------------------------------------
1223 * MakeUnknownTypeBody --
1225 * Constructs an FCGI_MakeUnknownTypeBody struct.
1227 *----------------------------------------------------------------------
1229 static FCGI_UnknownTypeBody MakeUnknownTypeBody(
1232 FCGI_UnknownTypeBody body;
1234 memset(body.reserved, 0, sizeof(body.reserved));
1239 *----------------------------------------------------------------------
1243 * Returns the smallest integer greater than or equal to n
1244 * that's a multiple of 8.
1246 *----------------------------------------------------------------------
1248 static int AlignInt8(unsigned n) {
1249 return (n + 7) & (UINT_MAX - 7);
1253 *----------------------------------------------------------------------
1257 * Returns the smallest pointer greater than or equal to p
1258 * that's a multiple of 8.
1260 *----------------------------------------------------------------------
1262 static unsigned char *AlignPtr8(unsigned char *p) {
1263 unsigned long u = (unsigned long) p;
1264 u = ((u + 7) & (ULONG_MAX - 7)) - u;
1270 * State associated with a stream
1272 typedef struct FCGX_Stream_Data {
1273 unsigned char *buff; /* buffer after alignment */
1274 int bufflen; /* number of bytes buff can store */
1275 unsigned char *mBuff; /* buffer as returned by Malloc */
1276 unsigned char *buffStop; /* reader: last valid byte + 1 of entire buffer.
1277 * stop generally differs from buffStop for
1278 * readers because of record structure.
1279 * writer: buff + bufflen */
1280 int type; /* reader: FCGI_PARAMS or FCGI_STDIN
1281 * writer: FCGI_STDOUT or FCGI_STDERR */
1282 int eorStop; /* reader: stop stream at end-of-record */
1283 int skip; /* reader: don't deliver content bytes */
1284 int contentLen; /* reader: bytes of unread content */
1285 int paddingLen; /* reader: bytes of unread padding */
1286 int isAnythingWritten; /* writer: data has been written to ipcFd */
1287 int rawWrite; /* writer: write data without stream headers */
1288 FCGX_Request *reqDataPtr; /* request data not specific to one stream */
1292 *----------------------------------------------------------------------
1294 * WriteCloseRecords --
1296 * Writes an EOF record for the stream content if necessary.
1297 * If this is the last writer to close, writes an FCGI_END_REQUEST
1300 *----------------------------------------------------------------------
1302 static void WriteCloseRecords(struct FCGX_Stream *stream)
1304 FCGX_Stream_Data *data = (FCGX_Stream_Data *)stream->data;
1306 * Enter rawWrite mode so final records won't be encapsulated as
1309 data->rawWrite = TRUE;
1311 * Generate EOF for stream content if needed.
1313 if(!(data->type == FCGI_STDERR
1314 && stream->wrNext == data->buff
1315 && !data->isAnythingWritten)) {
1317 header = MakeHeader(data->type, data->reqDataPtr->requestId, 0, 0);
1318 FCGX_PutStr((char *) &header, sizeof(header), stream);
1321 * Generate FCGI_END_REQUEST record if needed.
1323 if(data->reqDataPtr->nWriters == 1) {
1324 FCGI_EndRequestRecord endRequestRecord;
1325 endRequestRecord.header = MakeHeader(FCGI_END_REQUEST,
1326 data->reqDataPtr->requestId,
1327 sizeof(endRequestRecord.body), 0);
1328 endRequestRecord.body = MakeEndRequestBody(
1329 data->reqDataPtr->appStatus, FCGI_REQUEST_COMPLETE);
1330 FCGX_PutStr((char *) &endRequestRecord,
1331 sizeof(endRequestRecord), stream);
1333 data->reqDataPtr->nWriters--;
1338 static int write_it_all(int fd, char *buf, int len)
1343 wrote = OS_Write(fd, buf, len);
1353 *----------------------------------------------------------------------
1357 * Encapsulates any buffered stream content in a FastCGI
1358 * record. Writes the data, making the buffer empty.
1360 *----------------------------------------------------------------------
1362 static void EmptyBuffProc(struct FCGX_Stream *stream, int doClose)
1364 FCGX_Stream_Data *data = (FCGX_Stream_Data *)stream->data;
1367 * If the buffer contains stream data, fill in the header.
1368 * Pad the record to a multiple of 8 bytes in length. Padding
1369 * can't overflow the buffer because the buffer is a multiple
1370 * of 8 bytes in length. If the buffer contains no stream
1371 * data, reclaim the space reserved for the header.
1373 if(!data->rawWrite) {
1374 cLen = stream->wrNext - data->buff - sizeof(FCGI_Header);
1376 eLen = AlignInt8(cLen);
1378 * Giving the padding a well-defined value keeps Purify happy.
1380 memset(stream->wrNext, 0, eLen - cLen);
1381 stream->wrNext += eLen - cLen;
1382 *((FCGI_Header *) data->buff)
1383 = MakeHeader(data->type,
1384 data->reqDataPtr->requestId, cLen, eLen - cLen);
1386 stream->wrNext = data->buff;
1390 WriteCloseRecords(stream);
1392 if (stream->wrNext != data->buff) {
1393 data->isAnythingWritten = TRUE;
1394 if (write_it_all(data->reqDataPtr->ipcFd, (char *)data->buff, stream->wrNext - data->buff) < 0) {
1395 SetError(stream, OS_Errno);
1398 stream->wrNext = data->buff;
1401 * The buffer is empty.
1403 if(!data->rawWrite) {
1404 stream->wrNext += sizeof(FCGI_Header);
1409 * Return codes for Process* functions
1411 #define STREAM_RECORD 0
1413 #define BEGIN_RECORD 2
1414 #define MGMT_RECORD 3
1417 *----------------------------------------------------------------------
1419 * ProcessManagementRecord --
1421 * Reads and responds to a management record. The only type of
1422 * management record this library understands is FCGI_GET_VALUES.
1423 * The only variables that this library's FCGI_GET_VALUES
1424 * understands are FCGI_MAX_CONNS, FCGI_MAX_REQS, and FCGI_MPXS_CONNS.
1425 * Ignore other FCGI_GET_VALUES variables; respond to other
1426 * management records with a FCGI_UNKNOWN_TYPE record.
1428 *----------------------------------------------------------------------
1430 static int ProcessManagementRecord(int type, FCGX_Stream *stream)
1432 FCGX_Stream_Data *data = (FCGX_Stream_Data *)stream->data;
1433 ParamsPtr paramsPtr = NewParams(3);
1435 char response[64]; /* 64 = 8 + 3*(1+1+14+1)* + padding */
1436 char *responseP = &response[FCGI_HEADER_LEN];
1439 if(type == FCGI_GET_VALUES) {
1440 ReadParams(paramsPtr, stream);
1441 if((FCGX_GetError(stream) != 0) || (data->contentLen != 0)) {
1442 FreeParams(¶msPtr);
1443 return FCGX_PROTOCOL_ERROR;
1445 for (pPtr = paramsPtr->vec; pPtr < paramsPtr->cur; pPtr++) {
1447 *(strchr(name, '=')) = '\0';
1448 if(strcmp(name, FCGI_MAX_CONNS) == 0) {
1450 } else if(strcmp(name, FCGI_MAX_REQS) == 0) {
1452 } else if(strcmp(name, FCGI_MPXS_CONNS) == 0) {
1459 sprintf(responseP, "%c%c%s%c", len, 1, name, value);
1460 responseP += len + 3;
1463 len = responseP - &response[FCGI_HEADER_LEN];
1464 paddedLen = AlignInt8(len);
1465 *((FCGI_Header *) response)
1466 = MakeHeader(FCGI_GET_VALUES_RESULT, FCGI_NULL_REQUEST_ID,
1467 len, paddedLen - len);
1468 FreeParams(¶msPtr);
1470 paddedLen = len = sizeof(FCGI_UnknownTypeBody);
1471 ((FCGI_UnknownTypeRecord *) response)->header
1472 = MakeHeader(FCGI_UNKNOWN_TYPE, FCGI_NULL_REQUEST_ID,
1474 ((FCGI_UnknownTypeRecord *) response)->body
1475 = MakeUnknownTypeBody(type);
1477 if (write_it_all(data->reqDataPtr->ipcFd, response, FCGI_HEADER_LEN + paddedLen) < 0) {
1478 SetError(stream, OS_Errno);
1486 *----------------------------------------------------------------------
1488 * ProcessBeginRecord --
1490 * Reads an FCGI_BEGIN_REQUEST record.
1493 * BEGIN_RECORD for normal return. FCGX_PROTOCOL_ERROR for
1494 * protocol error. SKIP for attempt to multiplex
1495 * connection. -1 for error from write (errno in stream).
1498 * In case of BEGIN_RECORD return, stores requestId, role,
1499 * keepConnection values, and sets isBeginProcessed = TRUE.
1501 *----------------------------------------------------------------------
1503 static int ProcessBeginRecord(int requestId, FCGX_Stream *stream)
1505 FCGX_Stream_Data *data = (FCGX_Stream_Data *)stream->data;
1506 FCGI_BeginRequestBody body;
1507 if(requestId == 0 || data->contentLen != sizeof(body)) {
1508 return FCGX_PROTOCOL_ERROR;
1510 if(data->reqDataPtr->isBeginProcessed) {
1512 * The Web server is multiplexing the connection. This library
1513 * doesn't know how to handle multiplexing, so respond with
1514 * FCGI_END_REQUEST{protocolStatus = FCGI_CANT_MPX_CONN}
1516 FCGI_EndRequestRecord endRequestRecord;
1517 endRequestRecord.header = MakeHeader(FCGI_END_REQUEST,
1518 requestId, sizeof(endRequestRecord.body), 0);
1519 endRequestRecord.body
1520 = MakeEndRequestBody(0, FCGI_CANT_MPX_CONN);
1521 if (write_it_all(data->reqDataPtr->ipcFd, (char *)&endRequestRecord, sizeof(endRequestRecord)) < 0) {
1522 SetError(stream, OS_Errno);
1529 * Accept this new request. Read the record body.
1531 data->reqDataPtr->requestId = requestId;
1532 if(FCGX_GetStr((char *) &body, sizeof(body), stream)
1534 return FCGX_PROTOCOL_ERROR;
1536 data->reqDataPtr->keepConnection = (body.flags & FCGI_KEEP_CONN);
1537 data->reqDataPtr->role = (body.roleB1 << 8) + body.roleB0;
1538 data->reqDataPtr->isBeginProcessed = TRUE;
1539 return BEGIN_RECORD;
1543 *----------------------------------------------------------------------
1547 * Interprets FCGI_Header. Processes FCGI_BEGIN_REQUEST and
1548 * management records here; extracts information from stream
1549 * records (FCGI_PARAMS, FCGI_STDIN) into stream.
1552 * >= 0 for a normal return, < 0 for error
1555 * XXX: Many (more than there used to be).
1556 * If !stream->isRequestIdSet, ProcessHeader initializes
1557 * stream->requestId from header and sets stream->isRequestIdSet
1558 * to TRUE. ProcessHeader also sets stream->contentLen to header's
1559 * contentLength, and sets stream->paddingLen to the header's
1562 *----------------------------------------------------------------------
1564 static int ProcessHeader(FCGI_Header header, FCGX_Stream *stream)
1566 FCGX_Stream_Data *data = (FCGX_Stream_Data *)stream->data;
1568 if(header.version != FCGI_VERSION_1) {
1569 return FCGX_UNSUPPORTED_VERSION;
1571 requestId = (header.requestIdB1 << 8)
1572 + header.requestIdB0;
1573 data->contentLen = (header.contentLengthB1 << 8)
1574 + header.contentLengthB0;
1575 data->paddingLen = header.paddingLength;
1576 if(header.type == FCGI_BEGIN_REQUEST) {
1577 return ProcessBeginRecord(requestId, stream);
1579 if(requestId == FCGI_NULL_REQUEST_ID) {
1580 return ProcessManagementRecord(header.type, stream);
1582 if(requestId != data->reqDataPtr->requestId) {
1585 if(header.type != data->type) {
1586 return FCGX_PROTOCOL_ERROR;
1588 return STREAM_RECORD;
1592 *----------------------------------------------------------------------
1596 * Reads bytes from the ipcFd, supplies bytes to a stream client.
1598 *----------------------------------------------------------------------
1600 static void FillBuffProc(FCGX_Stream *stream)
1602 FCGX_Stream_Data *data = (FCGX_Stream_Data *)stream->data;
1609 * If data->buff is empty, do a read.
1611 if(stream->rdNext == data->buffStop) {
1612 count = OS_Read(data->reqDataPtr->ipcFd, (char *)data->buff,
1615 SetError(stream, (count == 0 ? FCGX_PROTOCOL_ERROR : OS_Errno));
1618 stream->rdNext = data->buff;
1619 data->buffStop = data->buff + count;
1622 * Now data->buff is not empty. If the current record contains
1623 * more content bytes, deliver all that are present in data->buff.
1625 if(data->contentLen > 0) {
1626 count = min(data->contentLen, data->buffStop - stream->rdNext);
1627 data->contentLen -= count;
1629 stream->wrNext = stream->stop = stream->rdNext + count;
1632 stream->rdNext += count;
1633 if(data->contentLen > 0) {
1641 * If the current record (whose content has been fully consumed by
1642 * the client) was padded, skip over the padding bytes.
1644 if(data->paddingLen > 0) {
1645 count = min(data->paddingLen, data->buffStop - stream->rdNext);
1646 data->paddingLen -= count;
1647 stream->rdNext += count;
1648 if(data->paddingLen > 0) {
1653 * All done with the current record, including the padding.
1654 * If we're in a recursive call from ProcessHeader, deliver EOF.
1657 stream->stop = stream->rdNext;
1658 stream->isClosed = TRUE;
1662 * Fill header with bytes from the input buffer.
1664 count = min((int)sizeof(header) - headerLen,
1665 data->buffStop - stream->rdNext);
1666 memcpy(((char *)(&header)) + headerLen, stream->rdNext, count);
1668 stream->rdNext += count;
1669 if(headerLen < sizeof(header)) {
1674 * Interpret header. eorStop prevents ProcessHeader from reading
1675 * past the end-of-record when using stream to read content.
1677 data->eorStop = TRUE;
1678 stream->stop = stream->rdNext;
1679 status = ProcessHeader(header, stream);
1680 data->eorStop = FALSE;
1681 stream->isClosed = FALSE;
1685 * If this stream record header marked the end of stream
1686 * data deliver EOF to the stream client, otherwise loop
1689 * XXX: If this is final stream and
1690 * stream->rdNext != data->buffStop, buffered
1691 * data is next request (server pipelining)?
1693 if(data->contentLen == 0) {
1694 stream->wrNext = stream->stop = stream->rdNext;
1695 stream->isClosed = TRUE;
1704 * If this header marked the beginning of a new
1705 * request, return role information to caller.
1713 SetError(stream, status);
1721 *----------------------------------------------------------------------
1725 * Creates a stream to read or write from an open ipcFd.
1726 * The stream performs reads/writes of up to bufflen bytes.
1728 *----------------------------------------------------------------------
1730 static FCGX_Stream *NewStream(
1731 FCGX_Request *reqDataPtr, int bufflen, int isReader, int streamType)
1734 * XXX: It would be a lot cleaner to have a NewStream that only
1735 * knows about the type FCGX_Stream, with all other
1736 * necessary data passed in. It appears that not just
1737 * data and the two procs are needed for initializing stream,
1738 * but also data->buff and data->buffStop. This has implications
1739 * for procs that want to swap buffers, too.
1741 FCGX_Stream *stream = (FCGX_Stream *)Malloc(sizeof(FCGX_Stream));
1742 FCGX_Stream_Data *data = (FCGX_Stream_Data *)Malloc(sizeof(FCGX_Stream_Data));
1743 data->reqDataPtr = reqDataPtr;
1744 bufflen = AlignInt8(min(max(bufflen, 32), FCGI_MAX_LENGTH + 1));
1745 data->bufflen = bufflen;
1746 data->mBuff = (unsigned char *)Malloc(bufflen);
1747 data->buff = AlignPtr8(data->mBuff);
1748 if(data->buff != data->mBuff) {
1752 data->buffStop = data->buff;
1754 data->buffStop = data->buff + data->bufflen;
1756 data->type = streamType;
1757 data->eorStop = FALSE;
1759 data->contentLen = 0;
1760 data->paddingLen = 0;
1761 data->isAnythingWritten = FALSE;
1762 data->rawWrite = FALSE;
1764 stream->data = data;
1765 stream->isReader = isReader;
1766 stream->isClosed = FALSE;
1767 stream->wasFCloseCalled = FALSE;
1768 stream->FCGI_errno = 0;
1770 stream->fillBuffProc = FillBuffProc;
1771 stream->emptyBuffProc = NULL;
1772 stream->rdNext = data->buff;
1773 stream->stop = stream->rdNext;
1774 stream->stopUnget = data->buff;
1775 stream->wrNext = stream->stop;
1777 stream->fillBuffProc = NULL;
1778 stream->emptyBuffProc = EmptyBuffProc;
1779 stream->wrNext = data->buff + sizeof(FCGI_Header);
1780 stream->stop = data->buffStop;
1781 stream->stopUnget = NULL;
1782 stream->rdNext = stream->stop;
1788 *----------------------------------------------------------------------
1792 * Frees all storage allocated when *streamPtr was created,
1793 * and nulls out *streamPtr.
1795 *----------------------------------------------------------------------
1797 void FreeStream(FCGX_Stream **streamPtr)
1799 FCGX_Stream *stream = *streamPtr;
1800 FCGX_Stream_Data *data;
1801 if(stream == NULL) {
1804 data = (FCGX_Stream_Data *)stream->data;
1805 data->reqDataPtr = NULL;
1813 *----------------------------------------------------------------------
1817 * Re-initializes the stream to read data of the specified type.
1819 *----------------------------------------------------------------------
1821 static FCGX_Stream *SetReaderType(FCGX_Stream *stream, int streamType)
1823 FCGX_Stream_Data *data = (FCGX_Stream_Data *)stream->data;
1824 ASSERT(stream->isReader);
1825 data->type = streamType;
1826 data->eorStop = FALSE;
1828 data->contentLen = 0;
1829 data->paddingLen = 0;
1830 stream->wrNext = stream->stop = stream->rdNext;
1831 stream->isClosed = FALSE;
1836 *----------------------------------------------------------------------
1840 * Creates a stream to read streamType records for the given
1841 * request. The stream performs OS reads of up to bufflen bytes.
1843 *----------------------------------------------------------------------
1845 static FCGX_Stream *NewReader(FCGX_Request *reqDataPtr, int bufflen, int streamType)
1847 return NewStream(reqDataPtr, bufflen, TRUE, streamType);
1852 *----------------------------------------------------------------------
1856 * Creates a stream to write streamType FastCGI records, using
1857 * the ipcFd and RequestId contained in *reqDataPtr.
1858 * The stream performs OS writes of up to bufflen bytes.
1860 *----------------------------------------------------------------------
1862 static FCGX_Stream *NewWriter(FCGX_Request *reqDataPtr, int bufflen, int streamType)
1864 return NewStream(reqDataPtr, bufflen, FALSE, streamType);
1869 *----------------------------------------------------------------------
1873 * Creates a stream to write streamType FastCGI records, using
1874 * the given ipcFd and request Id. This function is provided
1875 * for use by cgi-fcgi. In order to be defensive against misuse,
1876 * this function leaks a little storage; cgi-fcgi doesn't care.
1878 *----------------------------------------------------------------------
1880 FCGX_Stream *CreateWriter(
1886 FCGX_Request *reqDataPtr = (FCGX_Request *)Malloc(sizeof(FCGX_Request));
1887 reqDataPtr->ipcFd = ipcFd;
1888 reqDataPtr->requestId = requestId;
1890 * Suppress writing an FCGI_END_REQUEST record.
1892 reqDataPtr->nWriters = 2;
1893 return NewWriter(reqDataPtr, bufflen, streamType);
1897 *======================================================================
1899 *======================================================================
1903 *----------------------------------------------------------------------
1907 * This routine determines if the process is running as a CGI or
1908 * FastCGI process. The distinction is made by determining whether
1909 * FCGI_LISTENSOCK_FILENO is a listener ipcFd or the end of a
1910 * pipe (ie. standard in).
1913 * TRUE if the process is a CGI process, FALSE if FastCGI.
1915 *----------------------------------------------------------------------
1917 int FCGX_IsCGI(void)
1919 if (isFastCGI != -1) {
1923 if (!libInitialized) {
1924 int rc = FCGX_Init();
1926 /* exit() isn't great, but hey */
1927 exit((rc < 0) ? rc : -rc);
1931 isFastCGI = OS_IsFcgi(FCGI_LISTENSOCK_FILENO);
1937 *----------------------------------------------------------------------
1941 * Finishes the current request from the HTTP server.
1945 * Finishes the request accepted by (and frees any
1946 * storage allocated by) the previous call to FCGX_Accept.
1948 * DO NOT retain pointers to the envp array or any strings
1949 * contained in it (e.g. to the result of calling FCGX_GetParam),
1950 * since these will be freed by the next call to FCGX_Finish
1953 *----------------------------------------------------------------------
1956 void FCGX_Finish(void)
1958 FCGX_Finish_r(&the_request);
1962 *----------------------------------------------------------------------
1966 * Finishes the current request from the HTTP server.
1970 * Finishes the request accepted by (and frees any
1971 * storage allocated by) the previous call to FCGX_Accept.
1973 * DO NOT retain pointers to the envp array or any strings
1974 * contained in it (e.g. to the result of calling FCGX_GetParam),
1975 * since these will be freed by the next call to FCGX_Finish
1978 *----------------------------------------------------------------------
1980 void FCGX_Finish_r(FCGX_Request *reqDataPtr)
1982 if (reqDataPtr == NULL) {
1986 /* This should probably use a 'status' member instead of 'in' */
1987 if (reqDataPtr->in) {
1988 int errStatus = FCGX_FClose(reqDataPtr->err);
1989 int outStatus = FCGX_FClose(reqDataPtr->out);
1991 if (errStatus || outStatus
1992 || FCGX_GetError(reqDataPtr->in)
1993 || !reqDataPtr->keepConnection)
1995 OS_IpcClose(reqDataPtr->ipcFd);
1998 ASSERT(reqDataPtr->nWriters == 0);
2000 FreeStream(&reqDataPtr->in);
2001 reqDataPtr->in = NULL;
2003 FreeStream(&reqDataPtr->out);
2004 reqDataPtr->out = NULL;
2006 FreeStream(&reqDataPtr->err);
2007 reqDataPtr->err = NULL;
2009 FreeParams(&reqDataPtr->paramsPtr);
2010 reqDataPtr->paramsPtr = NULL;
2013 if (!reqDataPtr->keepConnection) {
2014 reqDataPtr->ipcFd = -1;
2018 int FCGX_OpenSocket(const char *path, int backlog)
2020 int rc = OS_CreateLocalIpcFd(path, backlog);
2021 if (rc == FCGI_LISTENSOCK_FILENO && isFastCGI == 0) {
2022 /* XXX probably need to call OS_LibInit() again for Win */
2028 int FCGX_InitRequest(FCGX_Request *request, int sock, int flags)
2030 memset(request, 0, sizeof(FCGX_Request));
2032 /* @@@ Should check that sock is open and listening */
2033 request->listen_sock = sock;
2035 /* @@@ Should validate against "known" flags */
2036 request->flags = flags;
2042 *----------------------------------------------------------------------
2046 * Initilize the FCGX library. This is called by FCGX_Accept()
2047 * but must be called by the user when using FCGX_Accept_r().
2050 * 0 for successful call.
2052 *----------------------------------------------------------------------
2058 if (libInitialized) {
2062 /* If our compiler doesn't play by the ISO rules for struct layout, halt. */
2063 ASSERT(sizeof(FCGI_Header) == FCGI_HEADER_LEN);
2065 FCGX_InitRequest(&the_request, FCGI_LISTENSOCK_FILENO, 0);
2067 if (OS_LibInit(NULL) == -1) {
2068 return OS_Errno ? OS_Errno : -9997;
2071 p = getenv("FCGI_WEB_SERVER_ADDRS");
2072 webServerAddressList = p ? StringCopy(p) : NULL;
2079 *----------------------------------------------------------------------
2083 * Accepts a new request from the HTTP server.
2086 * 0 for successful call, -1 for error.
2090 * Finishes the request accepted by (and frees any
2091 * storage allocated by) the previous call to FCGX_Accept.
2092 * Creates input, output, and error streams and
2093 * assigns them to *in, *out, and *err respectively.
2094 * Creates a parameters data structure to be accessed
2095 * via getenv(3) (if assigned to environ) or by FCGX_GetParam
2096 * and assigns it to *envp.
2098 * DO NOT retain pointers to the envp array or any strings
2099 * contained in it (e.g. to the result of calling FCGX_GetParam),
2100 * since these will be freed by the next call to FCGX_Finish
2103 *----------------------------------------------------------------------
2110 FCGX_ParamArray *envp)
2114 if (!libInitialized) {
2115 if ((rc = FCGX_Init())) {
2116 return (rc < 0) ? rc : -rc;
2120 rc = FCGX_Accept_r(&the_request);
2122 *in = the_request.in;
2123 *out = the_request.out;
2124 *err = the_request.err;
2125 *envp = the_request.envp;
2131 *----------------------------------------------------------------------
2135 * Accepts a new request from the HTTP server.
2138 * 0 for successful call, -1 for error.
2142 * Finishes the request accepted by (and frees any
2143 * storage allocated by) the previous call to FCGX_Accept.
2144 * Creates input, output, and error streams and
2145 * assigns them to *in, *out, and *err respectively.
2146 * Creates a parameters data structure to be accessed
2147 * via getenv(3) (if assigned to environ) or by FCGX_GetParam
2148 * and assigns it to *envp.
2150 * DO NOT retain pointers to the envp array or any strings
2151 * contained in it (e.g. to the result of calling FCGX_GetParam),
2152 * since these will be freed by the next call to FCGX_Finish
2155 *----------------------------------------------------------------------
2157 int FCGX_Accept_r(FCGX_Request *reqDataPtr)
2159 if (!libInitialized) {
2163 /* Finish the current request, if any. */
2164 FCGX_Finish_r(reqDataPtr);
2168 * If a connection isn't open, accept a new connection (blocking).
2169 * If an OS error occurs in accepting the connection,
2170 * return -1 to the caller, who should exit.
2172 if (reqDataPtr->ipcFd < 0) {
2173 int fail_on_intr = reqDataPtr->flags & FCGI_FAIL_ACCEPT_ON_INTR;
2175 reqDataPtr->ipcFd = OS_Accept(reqDataPtr->listen_sock, fail_on_intr, webServerAddressList);
2176 if (reqDataPtr->ipcFd < 0) {
2177 return (errno > 0) ? (0 - errno) : -9999;
2181 * A connection is open. Read from the connection in order to
2182 * get the request's role and environment. If protocol or other
2183 * errors occur, close the connection and try again.
2185 reqDataPtr->isBeginProcessed = FALSE;
2186 reqDataPtr->in = NewReader(reqDataPtr, 8192, 0);
2187 FillBuffProc(reqDataPtr->in);
2188 if(!reqDataPtr->isBeginProcessed) {
2193 switch(reqDataPtr->role) {
2194 case FCGI_RESPONDER:
2195 roleStr = "FCGI_ROLE=RESPONDER";
2197 case FCGI_AUTHORIZER:
2198 roleStr = "FCGI_ROLE=AUTHORIZER";
2201 roleStr = "FCGI_ROLE=FILTER";
2206 reqDataPtr->paramsPtr = NewParams(30);
2207 PutParam(reqDataPtr->paramsPtr, StringCopy(roleStr));
2209 SetReaderType(reqDataPtr->in, FCGI_PARAMS);
2210 if(ReadParams(reqDataPtr->paramsPtr, reqDataPtr->in) >= 0) {
2212 * Finished reading the environment. No errors occurred, so
2213 * leave the connection-retry loop.
2219 * Close the connection and try again.
2222 FreeParams(&reqDataPtr->paramsPtr);
2223 reqDataPtr->paramsPtr = NULL;
2225 FreeStream(&reqDataPtr->in);
2226 reqDataPtr->in = NULL;
2228 OS_Close(reqDataPtr->ipcFd);
2229 reqDataPtr->ipcFd = -1;
2232 * Build the remaining data structures representing the new
2233 * request and return successfully to the caller.
2235 SetReaderType(reqDataPtr->in, FCGI_STDIN);
2236 reqDataPtr->out = NewWriter(reqDataPtr, 8192, FCGI_STDOUT);
2237 reqDataPtr->err = NewWriter(reqDataPtr, 512, FCGI_STDERR);
2238 reqDataPtr->nWriters = 2;
2239 reqDataPtr->envp = reqDataPtr->paramsPtr->vec;
2244 *----------------------------------------------------------------------
2246 * FCGX_StartFilterData --
2248 * stream is an input stream for a FCGI_FILTER request.
2249 * stream is positioned at EOF on FCGI_STDIN.
2250 * Repositions stream to the start of FCGI_DATA.
2251 * If the preconditions are not met (e.g. FCGI_STDIN has not
2252 * been read to EOF) sets the stream error code to
2253 * FCGX_CALL_SEQ_ERROR.
2256 * 0 for a normal return, < 0 for error
2258 *----------------------------------------------------------------------
2261 int FCGX_StartFilterData(FCGX_Stream *stream)
2263 FCGX_Stream_Data *data = (FCGX_Stream_Data *)stream->data;
2264 if(data->reqDataPtr->role != FCGI_FILTER
2265 || !stream->isReader
2266 || !stream->isClosed
2267 || data->type != FCGI_STDIN) {
2268 SetError(stream, FCGX_CALL_SEQ_ERROR);
2271 SetReaderType(stream, FCGI_DATA);
2276 *----------------------------------------------------------------------
2278 * FCGX_SetExitStatus --
2280 * Sets the exit status for stream's request. The exit status
2281 * is the status code the request would have exited with, had
2282 * the request been run as a CGI program. You can call
2283 * SetExitStatus several times during a request; the last call
2284 * before the request ends determines the value.
2286 *----------------------------------------------------------------------
2289 void FCGX_SetExitStatus(int status, FCGX_Stream *stream)
2291 FCGX_Stream_Data *data = (FCGX_Stream_Data *)stream->data;
2292 data->reqDataPtr->appStatus = status;