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.8 1999/08/05 21:25:53 roberts 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 char *webServerAddressList = NULL;
68 static FCGX_Request reqData;
69 static FCGX_Request *reqDataPtr = &reqData;
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) goto ErrorReturn;
425 streamCount += percentPtr - f;
427 if(f == fStop) break;
431 * The following loop always executes either once or twice.
436 * Fast path: Scan optimistically, hoping that no flags,
437 * minimum field width, or precision are specified.
438 * Use the preallocated buffer, which is large enough
439 * for all fast path cases. If the conversion specifier
440 * is really more complex, run the loop a second time
441 * using the slow path.
442 * Note that fast path execution of %s bypasses the buffer
443 * and %f is not attempted on the fast path due to
444 * its large buffering requirements.
446 op = *(percentPtr + 1);
452 op = *(percentPtr + 2);
453 fmtBuff[1] = sizeModifier;
466 buffLen = PRINTF_BUFFLEN;
469 * Slow path: Scan the conversion specifier and construct
470 * a new format string, compute an upper bound on the
471 * amount of buffering that sprintf will require,
472 * and allocate a larger buffer if necessary.
475 fmtBuffPtr = &fmtBuff[1];
479 n = strspn(p, "-0+ #");
480 if(n > 5) goto ErrorReturn;
481 CopyAndAdvance(&fmtBuffPtr, &p, n);
483 * Scan minimum field width
485 n = strspn(p, "0123456789");
488 minWidth = va_arg(arg, int);
489 if(abs(minWidth) > 999999) goto ErrorReturn;
491 * The following use of strlen rather than the
492 * value returned from sprintf is because SUNOS4
493 * returns a char * instead of an int count.
495 sprintf(fmtBuffPtr, "%d", minWidth);
496 fmtBuffPtr += strlen(fmtBuffPtr);
502 minWidth = strtol(p, NULL, 10);
503 CopyAndAdvance(&fmtBuffPtr, &p, n);
511 CopyAndAdvance(&fmtBuffPtr, &p, 1);
512 n = strspn(p, "0123456789");
515 precision = va_arg(arg, int);
516 if(precision < 0) precision = 0;
517 if(precision > 999999) goto ErrorReturn;
519 * The following use of strlen rather than the
520 * value returned from sprintf is because SUNOS4
521 * returns a char * instead of an int count.
523 sprintf(fmtBuffPtr, "%d", precision);
524 fmtBuffPtr += strlen(fmtBuffPtr);
530 precision = strtol(p, NULL, 10);
531 CopyAndAdvance(&fmtBuffPtr, &p, n);
539 * Scan size modifier and conversion operation
546 CopyAndAdvance(&fmtBuffPtr, &p, 1);
553 CopyAndAdvance(&fmtBuffPtr, &p, 1);
554 ASSERT(fmtBuffPtr - fmtBuff < FMT_BUFFLEN);
556 specifierLength = p - percentPtr;
558 * Bound the required buffer size. For s and f
559 * conversions this requires examining the argument.
570 buffReqd = max(precision, 46);
573 charPtrArg = va_arg(arg, char *);
574 if(precision == -1) {
575 buffReqd = strlen(charPtrArg);
577 p = (char *)memchr(charPtrArg, '\0', precision);
579 (p == NULL) ? precision : p - charPtrArg;
583 switch(sizeModifier) {
585 doubleArg = va_arg(arg, double);
586 frexp(doubleArg, &exp);
589 lDoubleArg = va_arg(arg, LONG_DOUBLE);
590 frexp(lDoubleArg, &exp);
595 if(precision == -1) precision = 6;
596 buffReqd = precision + 3 + ((exp > 0) ? exp/3 : 0);
602 if(precision == -1) precision = 6;
603 buffReqd = precision + 8;
611 buffReqd = max(buffReqd + 10, minWidth);
613 * Allocate the buffer
615 if(buffReqd <= PRINTF_BUFFLEN) {
617 buffLen = PRINTF_BUFFLEN;
619 if(auxBuffPtr == NULL || buffReqd > auxBuffLen) {
620 if(auxBuffPtr != NULL) free(auxBuffPtr);
621 auxBuffPtr = (char *)Malloc(buffReqd);
622 auxBuffLen = buffReqd;
623 if(auxBuffPtr == NULL) goto ErrorReturn;
625 buffPtr = auxBuffPtr;
626 buffLen = auxBuffLen;
630 * This giant switch statement requires the following variables
631 * to be set up: op, sizeModifier, arg, buffPtr, fmtBuff.
632 * When fastPath == FALSE and op == 's' or 'f', the argument
633 * has been read into charPtrArg, doubleArg, or lDoubleArg.
634 * The statement produces the boolean performedOp, TRUE iff
635 * the op/sizeModifier were executed and argument consumed;
636 * if performedOp, the characters written into buffPtr[]
637 * and the character count buffCount (== EOF meaning error).
639 * The switch cases are arranged in the same order as in the
640 * description of fprintf in section 15.11 of Harbison and Steele.
646 switch(sizeModifier) {
648 intArg = va_arg(arg, int);
649 sprintf(buffPtr, fmtBuff, intArg);
650 buffCount = strlen(buffPtr);
653 longArg = va_arg(arg, long);
654 sprintf(buffPtr, fmtBuff, longArg);
655 buffCount = strlen(buffPtr);
658 shortArg = va_arg(arg, short);
659 sprintf(buffPtr, fmtBuff, shortArg);
660 buffCount = strlen(buffPtr);
670 switch(sizeModifier) {
672 unsignedArg = va_arg(arg, unsigned);
673 sprintf(buffPtr, fmtBuff, unsignedArg);
674 buffCount = strlen(buffPtr);
677 uLongArg = va_arg(arg, unsigned long);
678 sprintf(buffPtr, fmtBuff, uLongArg);
679 buffCount = strlen(buffPtr);
682 uShortArg = va_arg(arg, unsigned short);
683 sprintf(buffPtr, fmtBuff, uShortArg);
684 buffCount = strlen(buffPtr);
691 switch(sizeModifier) {
693 intArg = va_arg(arg, int);
694 sprintf(buffPtr, fmtBuff, intArg);
695 buffCount = strlen(buffPtr);
699 * XXX: Allowed by ISO C Amendment 1, but
700 * many platforms don't yet support wint_t
708 switch(sizeModifier) {
711 buffPtr = va_arg(arg, char *);
712 buffCount = strlen(buffPtr);
713 buffLen = buffCount + 1;
715 sprintf(buffPtr, fmtBuff, charPtrArg);
716 buffCount = strlen(buffPtr);
721 * XXX: Don't know how to convert a sequence
722 * of wide characters into a byte stream, or
723 * even how to predict the buffering required.
731 if(sizeModifier != ' ') goto ErrorReturn;
732 voidPtrArg = va_arg(arg, void *);
733 sprintf(buffPtr, fmtBuff, voidPtrArg);
734 buffCount = strlen(buffPtr);
737 switch(sizeModifier) {
739 intPtrArg = va_arg(arg, int *);
740 *intPtrArg = streamCount;
743 longPtrArg = va_arg(arg, long *);
744 *longPtrArg = streamCount;
747 shortPtrArg = va_arg(arg, short *);
748 *shortPtrArg = streamCount;
760 switch(sizeModifier) {
762 sprintf(buffPtr, fmtBuff, doubleArg);
763 buffCount = strlen(buffPtr);
766 sprintf(buffPtr, fmtBuff, lDoubleArg);
767 buffCount = strlen(buffPtr);
777 switch(sizeModifier) {
779 doubleArg = va_arg(arg, double);
780 sprintf(buffPtr, fmtBuff, doubleArg);
781 buffCount = strlen(buffPtr);
784 lDoubleArg = va_arg(arg, LONG_DOUBLE);
785 sprintf(buffPtr, fmtBuff, lDoubleArg);
786 buffCount = strlen(buffPtr);
793 if(sizeModifier != ' ')
804 if(performedOp) break;
805 if(!fastPath) goto ErrorReturn;
808 ASSERT(buffCount < buffLen);
810 if(FCGX_PutStr(buffPtr, buffCount, stream) < 0)
812 streamCount += buffCount;
813 } else if(buffCount < 0) {
816 f += specifierLength;
817 } /* while(f != fStop) */
822 if(auxBuffPtr != NULL) free(auxBuffPtr);
827 * Copy n characters from *srcPtr to *destPtr, then increment
828 * both *srcPtr and *destPtr by n.
830 static void CopyAndAdvance(char **destPtr, char **srcPtr, int n)
832 char *dest = *destPtr;
835 for (i = 0; i < n; i++)
842 *----------------------------------------------------------------------
846 * Flushes any buffered output.
848 * Server-push is a legitimate application of FCGX_FFlush.
849 * Otherwise, FCGX_FFlush is not very useful, since FCGX_Accept
850 * does it implicitly. FCGX_FFlush may reduce performance
851 * by increasing the total number of operating system calls
852 * the application makes.
855 * EOF (-1) if an error occurred.
857 *----------------------------------------------------------------------
859 int FCGX_FFlush(FCGX_Stream *stream)
861 if(stream->isClosed || stream->isReader)
863 stream->emptyBuffProc(stream, FALSE);
864 return (stream->isClosed) ? -1 : 0;
868 *----------------------------------------------------------------------
872 * Performs FCGX_FFlush and closes the stream.
874 * This is not a very useful operation, since FCGX_Accept
875 * does it implicitly. Closing the out stream before the
876 * err stream results in an extra write if there's nothing
877 * in the err stream, and therefore reduces performance.
880 * EOF (-1) if an error occurred.
882 *----------------------------------------------------------------------
884 int FCGX_FClose(FCGX_Stream *stream)
886 if(!stream->wasFCloseCalled) {
887 if(!stream->isReader) {
888 stream->emptyBuffProc(stream, TRUE);
890 stream->wasFCloseCalled = TRUE;
891 stream->isClosed = TRUE;
892 if(stream->isReader) {
893 stream->wrNext = stream->stop = stream->rdNext;
895 stream->rdNext = stream->stop = stream->wrNext;
898 return (stream->FCGI_errno == 0) ? 0 : EOF;
902 *----------------------------------------------------------------------
906 * An error has occurred; save the error code in the stream
907 * for diagnostic purposes and set the stream state so that
908 * reads return EOF and writes have no effect.
910 *----------------------------------------------------------------------
912 static void SetError(FCGX_Stream *stream, int FCGI_errno)
915 * Preserve only the first error.
917 if(stream->FCGI_errno == 0) {
918 stream->FCGI_errno = FCGI_errno;
919 stream->isClosed = TRUE;
924 *----------------------------------------------------------------------
928 * Return the stream error code. 0 means no error, > 0
929 * is an errno(2) error, < 0 is an FCGX_errno error.
931 *----------------------------------------------------------------------
933 int FCGX_GetError(FCGX_Stream *stream) {
934 return stream->FCGI_errno;
938 *----------------------------------------------------------------------
942 * Clear the stream error code and end-of-file indication.
944 *----------------------------------------------------------------------
946 void FCGX_ClearError(FCGX_Stream *stream) {
947 stream->FCGI_errno = 0;
949 * stream->isClosed = FALSE;
950 * XXX: should clear isClosed but work is needed to make it safe
951 * to do so. For example, if an application calls FClose, gets
952 * an I/O error on the write, calls ClearError and retries
953 * the FClose, FClose (really EmptyBuffProc) will write a second
954 * EOF record. If an application calls PutChar instead of FClose
955 * after the ClearError, the application will write more data.
956 * The stream's state must discriminate between various states
957 * of the stream that are now all lumped under isClosed.
962 *======================================================================
964 *======================================================================
968 * A vector of pointers representing the parameters received
969 * by a FastCGI application server, with the vector's length
970 * and last valid element so adding new parameters is efficient.
973 typedef struct Params {
974 FCGX_ParamArray vec; /* vector of strings */
975 int length; /* number of string vec can hold */
976 char **cur; /* current item in vec; *cur == NULL */
978 typedef Params *ParamsPtr;
981 *----------------------------------------------------------------------
985 * Creates a new Params structure.
988 * Pointer to the new structure.
990 *----------------------------------------------------------------------
992 static ParamsPtr NewParams(int length)
995 result = (Params *)Malloc(sizeof(Params));
996 result->vec = (char **)Malloc(length * sizeof(char *));
997 result->length = length;
998 result->cur = result->vec;
1004 *----------------------------------------------------------------------
1008 * Frees a Params structure and all the parameters it contains.
1011 * env becomes invalid.
1013 *----------------------------------------------------------------------
1015 static void FreeParams(ParamsPtr *paramsPtrPtr)
1017 ParamsPtr paramsPtr = *paramsPtrPtr;
1019 if(paramsPtr == NULL) {
1022 for (p = paramsPtr->vec; p < paramsPtr->cur; p++) {
1025 free(paramsPtr->vec);
1027 *paramsPtrPtr = NULL;
1031 *----------------------------------------------------------------------
1035 * Add a name/value pair to a Params structure.
1041 * Parameters structure updated.
1043 *----------------------------------------------------------------------
1045 static void PutParam(ParamsPtr paramsPtr, char *nameValue)
1049 *paramsPtr->cur++ = nameValue;
1050 size = paramsPtr->cur - paramsPtr->vec;
1051 if(size >= paramsPtr->length) {
1052 paramsPtr->length *= 2;
1053 paramsPtr->vec = (FCGX_ParamArray)realloc(paramsPtr->vec, paramsPtr->length * sizeof(char *));
1054 paramsPtr->cur = paramsPtr->vec + size;
1056 *paramsPtr->cur = NULL;
1060 *----------------------------------------------------------------------
1062 * FCGX_GetParam -- obtain value of FCGI parameter in environment
1066 * Value bound to name, NULL if name not present in the
1067 * environment envp. Caller must not mutate the result
1068 * or retain it past the end of this request.
1070 *----------------------------------------------------------------------
1072 char *FCGX_GetParam(const char *name, FCGX_ParamArray envp)
1077 if(len == 0) return NULL;
1078 for (p = envp; *p != NULL; p++) {
1079 if((strncmp(name, *p, len) == 0) && ((*p)[len] == '=')) {
1087 *----------------------------------------------------------------------
1089 * Start of FastCGI-specific code
1091 *----------------------------------------------------------------------
1095 *----------------------------------------------------------------------
1099 * Reads FastCGI name-value pairs from stream until EOF. Converts
1100 * each pair to name=value format and adds it to Params structure.
1102 *----------------------------------------------------------------------
1104 static int ReadParams(Params *paramsPtr, FCGX_Stream *stream)
1106 int nameLen, valueLen;
1107 unsigned char lenBuff[3];
1110 while((nameLen = FCGX_GetChar(stream)) != EOF) {
1112 * Read name length (one or four bytes) and value length
1113 * (one or four bytes) from stream.
1115 if((nameLen & 0x80) != 0) {
1116 if(FCGX_GetStr((char *) &lenBuff[0], 3, stream) != 3) {
1117 SetError(stream, FCGX_PARAMS_ERROR);
1120 nameLen = ((nameLen & 0x7f) << 24) + (lenBuff[0] << 16)
1121 + (lenBuff[1] << 8) + lenBuff[2];
1123 if((valueLen = FCGX_GetChar(stream)) == EOF) {
1124 SetError(stream, FCGX_PARAMS_ERROR);
1127 if((valueLen & 0x80) != 0) {
1128 if(FCGX_GetStr((char *) &lenBuff[0], 3, stream) != 3) {
1129 SetError(stream, FCGX_PARAMS_ERROR);
1132 valueLen = ((valueLen & 0x7f) << 24) + (lenBuff[0] << 16)
1133 + (lenBuff[1] << 8) + lenBuff[2];
1136 * nameLen and valueLen are now valid; read the name and value
1137 * from stream and construct a standard environment entry.
1139 nameValue = (char *)Malloc(nameLen + valueLen + 2);
1140 if(FCGX_GetStr(nameValue, nameLen, stream) != nameLen) {
1141 SetError(stream, FCGX_PARAMS_ERROR);
1145 *(nameValue + nameLen) = '=';
1146 if(FCGX_GetStr(nameValue + nameLen + 1, valueLen, stream)
1148 SetError(stream, FCGX_PARAMS_ERROR);
1152 *(nameValue + nameLen + valueLen + 1) = '\0';
1153 PutParam(paramsPtr, nameValue);
1159 *----------------------------------------------------------------------
1163 * Constructs an FCGI_Header struct.
1165 *----------------------------------------------------------------------
1167 static FCGI_Header MakeHeader(
1174 ASSERT(contentLength >= 0 && contentLength <= FCGI_MAX_LENGTH);
1175 ASSERT(paddingLength >= 0 && paddingLength <= 0xff);
1176 header.version = FCGI_VERSION_1;
1178 header.requestIdB1 = (requestId >> 8) & 0xff;
1179 header.requestIdB0 = (requestId ) & 0xff;
1180 header.contentLengthB1 = (contentLength >> 8) & 0xff;
1181 header.contentLengthB0 = (contentLength ) & 0xff;
1182 header.paddingLength = paddingLength;
1183 header.reserved = 0;
1188 *----------------------------------------------------------------------
1190 * MakeEndRequestBody --
1192 * Constructs an FCGI_EndRequestBody struct.
1194 *----------------------------------------------------------------------
1196 static FCGI_EndRequestBody MakeEndRequestBody(
1200 FCGI_EndRequestBody body;
1201 body.appStatusB3 = (appStatus >> 24) & 0xff;
1202 body.appStatusB2 = (appStatus >> 16) & 0xff;
1203 body.appStatusB1 = (appStatus >> 8) & 0xff;
1204 body.appStatusB0 = (appStatus ) & 0xff;
1205 body.protocolStatus = protocolStatus;
1206 memset(body.reserved, 0, sizeof(body.reserved));
1211 *----------------------------------------------------------------------
1213 * MakeUnknownTypeBody --
1215 * Constructs an FCGI_MakeUnknownTypeBody struct.
1217 *----------------------------------------------------------------------
1219 static FCGI_UnknownTypeBody MakeUnknownTypeBody(
1222 FCGI_UnknownTypeBody body;
1224 memset(body.reserved, 0, sizeof(body.reserved));
1229 *----------------------------------------------------------------------
1233 * Returns the smallest integer greater than or equal to n
1234 * that's a multiple of 8.
1236 *----------------------------------------------------------------------
1238 static int AlignInt8(unsigned n) {
1239 return (n + 7) & (UINT_MAX - 7);
1243 *----------------------------------------------------------------------
1247 * Returns the smallest pointer greater than or equal to p
1248 * that's a multiple of 8.
1250 *----------------------------------------------------------------------
1252 static unsigned char *AlignPtr8(unsigned char *p) {
1253 unsigned long u = (unsigned long) p;
1254 u = ((u + 7) & (ULONG_MAX - 7)) - u;
1260 * State associated with a stream
1262 typedef struct FCGX_Stream_Data {
1263 unsigned char *buff; /* buffer after alignment */
1264 int bufflen; /* number of bytes buff can store */
1265 unsigned char *mBuff; /* buffer as returned by Malloc */
1266 unsigned char *buffStop; /* reader: last valid byte + 1 of entire buffer.
1267 * stop generally differs from buffStop for
1268 * readers because of record structure.
1269 * writer: buff + bufflen */
1270 int type; /* reader: FCGI_PARAMS or FCGI_STDIN
1271 * writer: FCGI_STDOUT or FCGI_STDERR */
1272 int eorStop; /* reader: stop stream at end-of-record */
1273 int skip; /* reader: don't deliver content bytes */
1274 int contentLen; /* reader: bytes of unread content */
1275 int paddingLen; /* reader: bytes of unread padding */
1276 int isAnythingWritten; /* writer: data has been written to ipcFd */
1277 int rawWrite; /* writer: write data without stream headers */
1278 FCGX_Request *reqDataPtr; /* request data not specific to one stream */
1282 *----------------------------------------------------------------------
1284 * WriteCloseRecords --
1286 * Writes an EOF record for the stream content if necessary.
1287 * If this is the last writer to close, writes an FCGI_END_REQUEST
1290 *----------------------------------------------------------------------
1292 static void WriteCloseRecords(struct FCGX_Stream *stream)
1294 FCGX_Stream_Data *data = (FCGX_Stream_Data *)stream->data;
1296 * Enter rawWrite mode so final records won't be encapsulated as
1299 data->rawWrite = TRUE;
1301 * Generate EOF for stream content if needed.
1303 if(!(data->type == FCGI_STDERR
1304 && stream->wrNext == data->buff
1305 && !data->isAnythingWritten)) {
1307 header = MakeHeader(data->type, data->reqDataPtr->requestId, 0, 0);
1308 FCGX_PutStr((char *) &header, sizeof(header), stream);
1311 * Generate FCGI_END_REQUEST record if needed.
1313 if(data->reqDataPtr->nWriters == 1) {
1314 FCGI_EndRequestRecord endRequestRecord;
1315 endRequestRecord.header = MakeHeader(FCGI_END_REQUEST,
1316 data->reqDataPtr->requestId,
1317 sizeof(endRequestRecord.body), 0);
1318 endRequestRecord.body = MakeEndRequestBody(
1319 data->reqDataPtr->appStatus, FCGI_REQUEST_COMPLETE);
1320 FCGX_PutStr((char *) &endRequestRecord,
1321 sizeof(endRequestRecord), stream);
1323 data->reqDataPtr->nWriters--;
1328 static int write_it_all(int fd, char *buf, int len)
1333 wrote = OS_Write(fd, buf, len);
1343 *----------------------------------------------------------------------
1347 * Encapsulates any buffered stream content in a FastCGI
1348 * record. Writes the data, making the buffer empty.
1350 *----------------------------------------------------------------------
1352 static void EmptyBuffProc(struct FCGX_Stream *stream, int doClose)
1354 FCGX_Stream_Data *data = (FCGX_Stream_Data *)stream->data;
1357 * If the buffer contains stream data, fill in the header.
1358 * Pad the record to a multiple of 8 bytes in length. Padding
1359 * can't overflow the buffer because the buffer is a multiple
1360 * of 8 bytes in length. If the buffer contains no stream
1361 * data, reclaim the space reserved for the header.
1363 if(!data->rawWrite) {
1364 cLen = stream->wrNext - data->buff - sizeof(FCGI_Header);
1366 eLen = AlignInt8(cLen);
1368 * Giving the padding a well-defined value keeps Purify happy.
1370 memset(stream->wrNext, 0, eLen - cLen);
1371 stream->wrNext += eLen - cLen;
1372 *((FCGI_Header *) data->buff)
1373 = MakeHeader(data->type,
1374 data->reqDataPtr->requestId, cLen, eLen - cLen);
1376 stream->wrNext = data->buff;
1380 WriteCloseRecords(stream);
1382 if (stream->wrNext != data->buff) {
1383 data->isAnythingWritten = TRUE;
1384 if (write_it_all(data->reqDataPtr->ipcFd, (char *)data->buff, stream->wrNext - data->buff) < 0) {
1385 SetError(stream, OS_Errno);
1388 stream->wrNext = data->buff;
1391 * The buffer is empty.
1393 if(!data->rawWrite) {
1394 stream->wrNext += sizeof(FCGI_Header);
1399 * Return codes for Process* functions
1401 #define STREAM_RECORD 0
1403 #define BEGIN_RECORD 2
1404 #define MGMT_RECORD 3
1407 *----------------------------------------------------------------------
1409 * ProcessManagementRecord --
1411 * Reads and responds to a management record. The only type of
1412 * management record this library understands is FCGI_GET_VALUES.
1413 * The only variables that this library's FCGI_GET_VALUES
1414 * understands are FCGI_MAX_CONNS, FCGI_MAX_REQS, and FCGI_MPXS_CONNS.
1415 * Ignore other FCGI_GET_VALUES variables; respond to other
1416 * management records with a FCGI_UNKNOWN_TYPE record.
1418 *----------------------------------------------------------------------
1420 static int ProcessManagementRecord(int type, FCGX_Stream *stream)
1422 FCGX_Stream_Data *data = (FCGX_Stream_Data *)stream->data;
1423 ParamsPtr paramsPtr = NewParams(3);
1425 char response[64]; /* 64 = 8 + 3*(1+1+14+1)* + padding */
1426 char *responseP = &response[FCGI_HEADER_LEN];
1429 if(type == FCGI_GET_VALUES) {
1430 ReadParams(paramsPtr, stream);
1431 if((FCGX_GetError(stream) != 0) || (data->contentLen != 0)) {
1432 FreeParams(¶msPtr);
1433 return FCGX_PROTOCOL_ERROR;
1435 for (pPtr = paramsPtr->vec; pPtr < paramsPtr->cur; pPtr++) {
1437 *(strchr(name, '=')) = '\0';
1438 if(strcmp(name, FCGI_MAX_CONNS) == 0) {
1440 } else if(strcmp(name, FCGI_MAX_REQS) == 0) {
1442 } else if(strcmp(name, FCGI_MPXS_CONNS) == 0) {
1449 sprintf(responseP, "%c%c%s%c", len, 1, name, value);
1450 responseP += len + 3;
1453 len = responseP - &response[FCGI_HEADER_LEN];
1454 paddedLen = AlignInt8(len);
1455 *((FCGI_Header *) response)
1456 = MakeHeader(FCGI_GET_VALUES_RESULT, FCGI_NULL_REQUEST_ID,
1457 len, paddedLen - len);
1458 FreeParams(¶msPtr);
1460 paddedLen = len = sizeof(FCGI_UnknownTypeBody);
1461 ((FCGI_UnknownTypeRecord *) response)->header
1462 = MakeHeader(FCGI_UNKNOWN_TYPE, FCGI_NULL_REQUEST_ID,
1464 ((FCGI_UnknownTypeRecord *) response)->body
1465 = MakeUnknownTypeBody(type);
1467 if (write_it_all(data->reqDataPtr->ipcFd, response, FCGI_HEADER_LEN + paddedLen) < 0) {
1468 SetError(stream, OS_Errno);
1476 *----------------------------------------------------------------------
1478 * ProcessBeginRecord --
1480 * Reads an FCGI_BEGIN_REQUEST record.
1483 * BEGIN_RECORD for normal return. FCGX_PROTOCOL_ERROR for
1484 * protocol error. SKIP for attempt to multiplex
1485 * connection. -1 for error from write (errno in stream).
1488 * In case of BEGIN_RECORD return, stores requestId, role,
1489 * keepConnection values, and sets isBeginProcessed = TRUE.
1491 *----------------------------------------------------------------------
1493 static int ProcessBeginRecord(int requestId, FCGX_Stream *stream)
1495 FCGX_Stream_Data *data = (FCGX_Stream_Data *)stream->data;
1496 FCGI_BeginRequestBody body;
1497 if(requestId == 0 || data->contentLen != sizeof(body)) {
1498 return FCGX_PROTOCOL_ERROR;
1500 if(data->reqDataPtr->isBeginProcessed) {
1502 * The Web server is multiplexing the connection. This library
1503 * doesn't know how to handle multiplexing, so respond with
1504 * FCGI_END_REQUEST{protocolStatus = FCGI_CANT_MPX_CONN}
1506 FCGI_EndRequestRecord endRequestRecord;
1507 endRequestRecord.header = MakeHeader(FCGI_END_REQUEST,
1508 requestId, sizeof(endRequestRecord.body), 0);
1509 endRequestRecord.body
1510 = MakeEndRequestBody(0, FCGI_CANT_MPX_CONN);
1511 if (write_it_all(data->reqDataPtr->ipcFd, (char *)&endRequestRecord, sizeof(endRequestRecord)) < 0) {
1512 SetError(stream, OS_Errno);
1519 * Accept this new request. Read the record body.
1521 data->reqDataPtr->requestId = requestId;
1522 if(FCGX_GetStr((char *) &body, sizeof(body), stream)
1524 return FCGX_PROTOCOL_ERROR;
1526 data->reqDataPtr->keepConnection = (body.flags & FCGI_KEEP_CONN);
1527 data->reqDataPtr->role = (body.roleB1 << 8) + body.roleB0;
1528 data->reqDataPtr->isBeginProcessed = TRUE;
1529 return BEGIN_RECORD;
1533 *----------------------------------------------------------------------
1537 * Interprets FCGI_Header. Processes FCGI_BEGIN_REQUEST and
1538 * management records here; extracts information from stream
1539 * records (FCGI_PARAMS, FCGI_STDIN) into stream.
1542 * >= 0 for a normal return, < 0 for error
1545 * XXX: Many (more than there used to be).
1546 * If !stream->isRequestIdSet, ProcessHeader initializes
1547 * stream->requestId from header and sets stream->isRequestIdSet
1548 * to TRUE. ProcessHeader also sets stream->contentLen to header's
1549 * contentLength, and sets stream->paddingLen to the header's
1552 *----------------------------------------------------------------------
1554 static int ProcessHeader(FCGI_Header header, FCGX_Stream *stream)
1556 FCGX_Stream_Data *data = (FCGX_Stream_Data *)stream->data;
1558 if(header.version != FCGI_VERSION_1) {
1559 return FCGX_UNSUPPORTED_VERSION;
1561 requestId = (header.requestIdB1 << 8)
1562 + header.requestIdB0;
1563 data->contentLen = (header.contentLengthB1 << 8)
1564 + header.contentLengthB0;
1565 data->paddingLen = header.paddingLength;
1566 if(header.type == FCGI_BEGIN_REQUEST) {
1567 return ProcessBeginRecord(requestId, stream);
1569 if(requestId == FCGI_NULL_REQUEST_ID) {
1570 return ProcessManagementRecord(header.type, stream);
1572 if(requestId != data->reqDataPtr->requestId) {
1575 if(header.type != data->type) {
1576 return FCGX_PROTOCOL_ERROR;
1578 return STREAM_RECORD;
1582 *----------------------------------------------------------------------
1586 * Reads bytes from the ipcFd, supplies bytes to a stream client.
1588 *----------------------------------------------------------------------
1590 static void FillBuffProc(FCGX_Stream *stream)
1592 FCGX_Stream_Data *data = (FCGX_Stream_Data *)stream->data;
1599 * If data->buff is empty, do a read.
1601 if(stream->rdNext == data->buffStop) {
1602 count = OS_Read(data->reqDataPtr->ipcFd, (char *)data->buff,
1605 SetError(stream, (count == 0 ? FCGX_PROTOCOL_ERROR : OS_Errno));
1608 stream->rdNext = data->buff;
1609 data->buffStop = data->buff + count;
1612 * Now data->buff is not empty. If the current record contains
1613 * more content bytes, deliver all that are present in data->buff.
1615 if(data->contentLen > 0) {
1616 count = min(data->contentLen, data->buffStop - stream->rdNext);
1617 data->contentLen -= count;
1619 stream->wrNext = stream->stop = stream->rdNext + count;
1622 stream->rdNext += count;
1623 if(data->contentLen > 0) {
1631 * If the current record (whose content has been fully consumed by
1632 * the client) was padded, skip over the padding bytes.
1634 if(data->paddingLen > 0) {
1635 count = min(data->paddingLen, data->buffStop - stream->rdNext);
1636 data->paddingLen -= count;
1637 stream->rdNext += count;
1638 if(data->paddingLen > 0) {
1643 * All done with the current record, including the padding.
1644 * If we're in a recursive call from ProcessHeader, deliver EOF.
1647 stream->stop = stream->rdNext;
1648 stream->isClosed = TRUE;
1652 * Fill header with bytes from the input buffer.
1654 count = min((int)sizeof(header) - headerLen,
1655 data->buffStop - stream->rdNext);
1656 memcpy(((char *)(&header)) + headerLen, stream->rdNext, count);
1658 stream->rdNext += count;
1659 if(headerLen < sizeof(header)) {
1664 * Interpret header. eorStop prevents ProcessHeader from reading
1665 * past the end-of-record when using stream to read content.
1667 data->eorStop = TRUE;
1668 stream->stop = stream->rdNext;
1669 status = ProcessHeader(header, stream);
1670 data->eorStop = FALSE;
1671 stream->isClosed = FALSE;
1675 * If this stream record header marked the end of stream
1676 * data deliver EOF to the stream client, otherwise loop
1679 * XXX: If this is final stream and
1680 * stream->rdNext != data->buffStop, buffered
1681 * data is next request (server pipelining)?
1683 if(data->contentLen == 0) {
1684 stream->wrNext = stream->stop = stream->rdNext;
1685 stream->isClosed = TRUE;
1694 * If this header marked the beginning of a new
1695 * request, return role information to caller.
1703 SetError(stream, status);
1711 *----------------------------------------------------------------------
1715 * Creates a stream to read or write from an open ipcFd.
1716 * The stream performs reads/writes of up to bufflen bytes.
1718 *----------------------------------------------------------------------
1720 static FCGX_Stream *NewStream(
1721 FCGX_Request *reqDataPtr, int bufflen, int isReader, int streamType)
1724 * XXX: It would be a lot cleaner to have a NewStream that only
1725 * knows about the type FCGX_Stream, with all other
1726 * necessary data passed in. It appears that not just
1727 * data and the two procs are needed for initializing stream,
1728 * but also data->buff and data->buffStop. This has implications
1729 * for procs that want to swap buffers, too.
1731 FCGX_Stream *stream = (FCGX_Stream *)Malloc(sizeof(FCGX_Stream));
1732 FCGX_Stream_Data *data = (FCGX_Stream_Data *)Malloc(sizeof(FCGX_Stream_Data));
1733 data->reqDataPtr = reqDataPtr;
1734 bufflen = AlignInt8(min(max(bufflen, 32), FCGI_MAX_LENGTH + 1));
1735 data->bufflen = bufflen;
1736 data->mBuff = (unsigned char *)Malloc(bufflen);
1737 data->buff = AlignPtr8(data->mBuff);
1738 if(data->buff != data->mBuff) {
1742 data->buffStop = data->buff;
1744 data->buffStop = data->buff + data->bufflen;
1746 data->type = streamType;
1747 data->eorStop = FALSE;
1749 data->contentLen = 0;
1750 data->paddingLen = 0;
1751 data->isAnythingWritten = FALSE;
1752 data->rawWrite = FALSE;
1754 stream->data = data;
1755 stream->isReader = isReader;
1756 stream->isClosed = FALSE;
1757 stream->wasFCloseCalled = FALSE;
1758 stream->FCGI_errno = 0;
1760 stream->fillBuffProc = FillBuffProc;
1761 stream->emptyBuffProc = NULL;
1762 stream->rdNext = data->buff;
1763 stream->stop = stream->rdNext;
1764 stream->stopUnget = data->buff;
1765 stream->wrNext = stream->stop;
1767 stream->fillBuffProc = NULL;
1768 stream->emptyBuffProc = EmptyBuffProc;
1769 stream->wrNext = data->buff + sizeof(FCGI_Header);
1770 stream->stop = data->buffStop;
1771 stream->stopUnget = NULL;
1772 stream->rdNext = stream->stop;
1778 *----------------------------------------------------------------------
1782 * Frees all storage allocated when *streamPtr was created,
1783 * and nulls out *streamPtr.
1785 *----------------------------------------------------------------------
1787 void FreeStream(FCGX_Stream **streamPtr)
1789 FCGX_Stream *stream = *streamPtr;
1790 FCGX_Stream_Data *data;
1791 if(stream == NULL) {
1794 data = (FCGX_Stream_Data *)stream->data;
1795 data->reqDataPtr = NULL;
1803 *----------------------------------------------------------------------
1807 * Re-initializes the stream to read data of the specified type.
1809 *----------------------------------------------------------------------
1811 static FCGX_Stream *SetReaderType(FCGX_Stream *stream, int streamType)
1813 FCGX_Stream_Data *data = (FCGX_Stream_Data *)stream->data;
1814 ASSERT(stream->isReader);
1815 data->type = streamType;
1816 data->eorStop = FALSE;
1818 data->contentLen = 0;
1819 data->paddingLen = 0;
1820 stream->wrNext = stream->stop = stream->rdNext;
1821 stream->isClosed = FALSE;
1826 *----------------------------------------------------------------------
1830 * Creates a stream to read streamType records for the given
1831 * request. The stream performs OS reads of up to bufflen bytes.
1833 *----------------------------------------------------------------------
1835 static FCGX_Stream *NewReader(FCGX_Request *reqDataPtr, int bufflen, int streamType)
1837 return NewStream(reqDataPtr, bufflen, TRUE, streamType);
1842 *----------------------------------------------------------------------
1846 * Creates a stream to write streamType FastCGI records, using
1847 * the ipcFd and RequestId contained in *reqDataPtr.
1848 * The stream performs OS writes of up to bufflen bytes.
1850 *----------------------------------------------------------------------
1852 static FCGX_Stream *NewWriter(FCGX_Request *reqDataPtr, int bufflen, int streamType)
1854 return NewStream(reqDataPtr, bufflen, FALSE, streamType);
1859 *----------------------------------------------------------------------
1863 * Creates a stream to write streamType FastCGI records, using
1864 * the given ipcFd and request Id. This function is provided
1865 * for use by cgi-fcgi. In order to be defensive against misuse,
1866 * this function leaks a little storage; cgi-fcgi doesn't care.
1868 *----------------------------------------------------------------------
1870 FCGX_Stream *CreateWriter(
1876 FCGX_Request *reqDataPtr = (FCGX_Request *)Malloc(sizeof(FCGX_Request));
1877 reqDataPtr->ipcFd = ipcFd;
1878 reqDataPtr->requestId = requestId;
1880 * Suppress writing an FCGI_END_REQUEST record.
1882 reqDataPtr->nWriters = 2;
1883 return NewWriter(reqDataPtr, bufflen, streamType);
1887 *======================================================================
1889 *======================================================================
1893 *----------------------------------------------------------------------
1897 * This routine determines if the process is running as a CGI or
1898 * FastCGI process. The distinction is made by determining whether
1899 * FCGI_LISTENSOCK_FILENO is a listener ipcFd or the end of a
1900 * pipe (ie. standard in).
1903 * TRUE if the process is a CGI process, FALSE if FastCGI.
1906 * If this is a FastCGI process there's a chance that a connection
1907 * will be accepted while performing the test. If this occurs,
1908 * the connection is saved and used later by the FCGX_Accept logic.
1910 *----------------------------------------------------------------------
1912 int FCGX_IsCGI(void)
1914 static int isFastCGI = -1;
1916 if (isFastCGI != -1) {
1920 if (!libInitialized) {
1921 int rc = FCGX_Init();
1923 /* exit() isn't great, but hey */
1924 exit((rc < 0) ? rc : -rc);
1928 isFastCGI = OS_IsFcgi(FCGI_LISTENSOCK_FILENO);
1934 *----------------------------------------------------------------------
1938 * Finishes the current request from the HTTP server.
1942 * Finishes the request accepted by (and frees any
1943 * storage allocated by) the previous call to FCGX_Accept.
1945 * DO NOT retain pointers to the envp array or any strings
1946 * contained in it (e.g. to the result of calling FCGX_GetParam),
1947 * since these will be freed by the next call to FCGX_Finish
1950 *----------------------------------------------------------------------
1953 void FCGX_Finish(void)
1955 FCGX_Finish_r(reqDataPtr);
1959 *----------------------------------------------------------------------
1963 * Finishes the current request from the HTTP server.
1967 * Finishes the request accepted by (and frees any
1968 * storage allocated by) the previous call to FCGX_Accept.
1970 * DO NOT retain pointers to the envp array or any strings
1971 * contained in it (e.g. to the result of calling FCGX_GetParam),
1972 * since these will be freed by the next call to FCGX_Finish
1975 *----------------------------------------------------------------------
1977 void FCGX_Finish_r(FCGX_Request *reqDataPtr)
1979 if (reqDataPtr == NULL) {
1983 if (reqDataPtr->in) {
1984 int errStatus = FCGX_FClose(reqDataPtr->err);
1985 int outStatus = FCGX_FClose(reqDataPtr->out);
1987 if (errStatus || outStatus
1988 || FCGX_GetError(reqDataPtr->in)
1989 || !reqDataPtr->keepConnection)
1991 OS_IpcClose(reqDataPtr->ipcFd);
1994 ASSERT(reqDataPtr->nWriters == 0);
1996 FreeStream(&reqDataPtr->in);
1997 FreeStream(&reqDataPtr->out);
1998 FreeStream(&reqDataPtr->err);
2000 FreeParams(&reqDataPtr->paramsPtr);
2003 if (!reqDataPtr->keepConnection) {
2004 reqDataPtr->ipcFd = -1;
2008 int FCGX_OpenSocket(const char *path, int backlog)
2010 return OS_CreateLocalIpcFd(path, backlog);
2013 int FCGX_InitRequest(FCGX_Request *request, int sock, int flags)
2015 memset(request, 0, sizeof(FCGX_Request));
2017 /* @@@ Should check that sock is open and listening */
2018 request->listen_sock = sock;
2020 /* @@@ Should validate against "known" flags */
2021 request->flags = flags;
2027 *----------------------------------------------------------------------
2031 * Initilize the FCGX library. This is called by FCGX_Accept()
2032 * but must be called by the user when using FCGX_Accept_r().
2035 * 0 for successful call.
2037 *----------------------------------------------------------------------
2043 if (libInitialized) {
2047 /* If our compiler doesn't play by the ISO rules for struct layout, halt. */
2048 ASSERT(sizeof(FCGI_Header) == FCGI_HEADER_LEN);
2050 FCGX_InitRequest(&reqData, FCGI_LISTENSOCK_FILENO, 0);
2052 if (OS_LibInit(NULL) == -1) {
2053 return OS_Errno ? OS_Errno : -9997;
2056 p = getenv("FCGI_WEB_SERVER_ADDRS");
2057 webServerAddressList = p ? StringCopy(p) : "";
2064 *----------------------------------------------------------------------
2068 * Accepts a new request from the HTTP server.
2071 * 0 for successful call, -1 for error.
2075 * Finishes the request accepted by (and frees any
2076 * storage allocated by) the previous call to FCGX_Accept.
2077 * Creates input, output, and error streams and
2078 * assigns them to *in, *out, and *err respectively.
2079 * Creates a parameters data structure to be accessed
2080 * via getenv(3) (if assigned to environ) or by FCGX_GetParam
2081 * and assigns it to *envp.
2083 * DO NOT retain pointers to the envp array or any strings
2084 * contained in it (e.g. to the result of calling FCGX_GetParam),
2085 * since these will be freed by the next call to FCGX_Finish
2088 *----------------------------------------------------------------------
2095 FCGX_ParamArray *envp)
2097 if (!libInitialized) {
2098 int rc = FCGX_Init();
2100 return (rc < 0) ? rc : -rc;
2104 return FCGX_Accept_r(&reqData);
2108 *----------------------------------------------------------------------
2112 * Accepts a new request from the HTTP server.
2115 * 0 for successful call, -1 for error.
2119 * Finishes the request accepted by (and frees any
2120 * storage allocated by) the previous call to FCGX_Accept.
2121 * Creates input, output, and error streams and
2122 * assigns them to *in, *out, and *err respectively.
2123 * Creates a parameters data structure to be accessed
2124 * via getenv(3) (if assigned to environ) or by FCGX_GetParam
2125 * and assigns it to *envp.
2127 * DO NOT retain pointers to the envp array or any strings
2128 * contained in it (e.g. to the result of calling FCGX_GetParam),
2129 * since these will be freed by the next call to FCGX_Finish
2132 *----------------------------------------------------------------------
2134 int FCGX_Accept_r(FCGX_Request *reqDataPtr)
2136 FCGX_Stream **in = &reqDataPtr->in;
2137 FCGX_Stream **out = &reqDataPtr->out;
2138 FCGX_Stream **err = &reqDataPtr->err;
2139 FCGX_ParamArray *envp = &reqDataPtr->envp;
2141 if (!libInitialized) {
2145 /* Finish the current request, if any. */
2146 FCGX_Finish_r(reqDataPtr);
2150 * If a connection isn't open, accept a new connection (blocking).
2151 * If an OS error occurs in accepting the connection,
2152 * return -1 to the caller, who should exit.
2154 if (reqDataPtr->ipcFd < 0) {
2155 int fail_on_intr = reqDataPtr->flags & FCGI_FAIL_ACCEPT_ON_INTR;
2157 reqDataPtr->ipcFd = OS_Accept(reqDataPtr->listen_sock, fail_on_intr, webServerAddressList);
2158 if (reqDataPtr->ipcFd < 0) {
2159 return (errno > 0) ? (0 - errno) : -9999;
2163 * A connection is open. Read from the connection in order to
2164 * get the request's role and environment. If protocol or other
2165 * errors occur, close the connection and try again.
2167 reqDataPtr->isBeginProcessed = FALSE;
2168 reqDataPtr->in = NewReader(reqDataPtr, 8192, 0);
2169 FillBuffProc(reqDataPtr->in);
2170 if(!reqDataPtr->isBeginProcessed) {
2175 switch(reqDataPtr->role) {
2176 case FCGI_RESPONDER:
2177 roleStr = "FCGI_ROLE=RESPONDER";
2179 case FCGI_AUTHORIZER:
2180 roleStr = "FCGI_ROLE=AUTHORIZER";
2183 roleStr = "FCGI_ROLE=FILTER";
2188 reqDataPtr->paramsPtr = NewParams(30);
2189 PutParam(reqDataPtr->paramsPtr, StringCopy(roleStr));
2191 SetReaderType(reqDataPtr->in, FCGI_PARAMS);
2192 if(ReadParams(reqDataPtr->paramsPtr, reqDataPtr->in) >= 0) {
2194 * Finished reading the environment. No errors occurred, so
2195 * leave the connection-retry loop.
2200 * Close the connection and try again.
2203 FreeParams(&reqDataPtr->paramsPtr);
2204 FreeStream(&reqDataPtr->in);
2205 OS_Close(reqDataPtr->ipcFd);
2206 reqDataPtr->ipcFd = -1;
2209 * Build the remaining data structures representing the new
2210 * request and return successfully to the caller.
2212 SetReaderType(reqDataPtr->in, FCGI_STDIN);
2213 reqDataPtr->out = NewWriter(reqDataPtr, 8192, FCGI_STDOUT);
2214 reqDataPtr->err = NewWriter(reqDataPtr, 512, FCGI_STDERR);
2215 reqDataPtr->nWriters = 2;
2216 *in = reqDataPtr->in;
2217 *out = reqDataPtr->out;
2218 *err = reqDataPtr->err;
2219 *envp = reqDataPtr->paramsPtr->vec;
2224 *----------------------------------------------------------------------
2226 * FCGX_StartFilterData --
2228 * stream is an input stream for a FCGI_FILTER request.
2229 * stream is positioned at EOF on FCGI_STDIN.
2230 * Repositions stream to the start of FCGI_DATA.
2231 * If the preconditions are not met (e.g. FCGI_STDIN has not
2232 * been read to EOF) sets the stream error code to
2233 * FCGX_CALL_SEQ_ERROR.
2236 * 0 for a normal return, < 0 for error
2238 *----------------------------------------------------------------------
2241 int FCGX_StartFilterData(FCGX_Stream *stream)
2243 FCGX_Stream_Data *data = (FCGX_Stream_Data *)stream->data;
2244 if(data->reqDataPtr->role != FCGI_FILTER
2245 || !stream->isReader
2246 || !stream->isClosed
2247 || data->type != FCGI_STDIN) {
2248 SetError(stream, FCGX_CALL_SEQ_ERROR);
2251 SetReaderType(reqDataPtr->in, FCGI_DATA);
2256 *----------------------------------------------------------------------
2258 * FCGX_SetExitStatus --
2260 * Sets the exit status for stream's request. The exit status
2261 * is the status code the request would have exited with, had
2262 * the request been run as a CGI program. You can call
2263 * SetExitStatus several times during a request; the last call
2264 * before the request ends determines the value.
2266 *----------------------------------------------------------------------
2269 void FCGX_SetExitStatus(int status, FCGX_Stream *stream)
2271 FCGX_Stream_Data *data = (FCGX_Stream_Data *)stream->data;
2272 data->reqDataPtr->appStatus = status;