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.
15 static const char rcsid[] = "$Id: fcgiapp.c,v 1.4 1999/07/26 04:28:08 roberts Exp $";
19 #define DLLAPI __declspec(dllexport)
23 #include <sys/types.h>
24 #ifdef HAVE_SYS_TIME_H
28 #include "fcgi_config.h"
36 #include <memory.h> /* for memchr() */
40 #ifdef HAVE_SYS_SOCKET_H
41 #include <sys/socket.h> /* for getpeername */
43 #include <fcntl.h> /* for fcntl */
47 #include "fcgiappmisc.h"
52 * This is a workaround for one version of the HP C compiler
53 * (c89 on HP-UX 9.04, also Stratus FTX), which will dump core
54 * if given 'long double' for varargs.
56 #ifdef HAVE_VA_ARG_LONG_DOUBLE_BUG
57 #define LONG_DOUBLE double
59 #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;
72 static void *Malloc(size_t size)
74 void *result = malloc(size);
75 ASSERT(size == 0 || result != NULL);
79 static char *StringCopy(char *str)
81 int strLen = strlen(str);
82 char *newString = Malloc(strLen + 1);
83 memcpy(newString, str, strLen);
84 newString[strLen] = '\000';
90 *----------------------------------------------------------------------
94 * Reads a byte from the input stream and returns it.
97 * The byte, or EOF (-1) if the end of input has been reached.
99 *----------------------------------------------------------------------
101 int FCGX_GetChar(FCGX_Stream *stream)
103 if(stream->rdNext != stream->stop)
104 return *stream->rdNext++;
105 if(stream->isClosed || !stream->isReader)
107 stream->fillBuffProc(stream);
108 stream->stopUnget = stream->rdNext;
109 if(stream->rdNext != stream->stop)
110 return *stream->rdNext++;
111 ASSERT(stream->isClosed); /* bug in fillBufProc if not */
116 *----------------------------------------------------------------------
120 * Reads up to n consecutive bytes from the input stream
121 * into the character array str. Performs no interpretation
122 * of the input bytes.
125 * Number of bytes read. If result is smaller than n,
126 * the end of input has been reached.
128 *----------------------------------------------------------------------
130 int FCGX_GetStr(char *str, int n, FCGX_Stream *stream)
138 * Fast path: n bytes are already available
140 if(n <= (stream->stop - stream->rdNext)) {
141 memcpy(str, stream->rdNext, n);
146 * General case: stream is closed or buffer fill procedure
151 if(stream->rdNext != stream->stop) {
152 m = min(n - bytesMoved, stream->stop - stream->rdNext);
153 memcpy(str, stream->rdNext, m);
160 if(stream->isClosed || !stream->isReader)
162 stream->fillBuffProc(stream);
163 stream->stopUnget = stream->rdNext;
168 *----------------------------------------------------------------------
172 * Reads up to n-1 consecutive bytes from the input stream
173 * into the character array str. Stops before n-1 bytes
174 * have been read if '\n' or EOF is read. The terminating '\n'
175 * is copied to str. After copying the last byte into str,
176 * stores a '\0' terminator.
179 * NULL if EOF is the first thing read from the input stream,
182 *----------------------------------------------------------------------
184 char *FCGX_GetLine(char *str, int n, FCGX_Stream *stream)
190 c = FCGX_GetChar(stream);
207 *----------------------------------------------------------------------
211 * Pushes back the character c onto the input stream. One
212 * character of pushback is guaranteed once a character
213 * has been read. No pushback is possible for EOF.
216 * Returns c if the pushback succeeded, EOF if not.
218 *----------------------------------------------------------------------
220 int FCGX_UnGetChar(int c, FCGX_Stream *stream) {
224 || stream->rdNext == stream->stopUnget)
232 *----------------------------------------------------------------------
236 * Returns EOF if end-of-file has been detected while reading
237 * from stream; otherwise returns 0.
239 * Note that FCGX_HasSeenEOF(s) may return 0, yet an immediately
240 * following FCGX_GetChar(s) may return EOF. This function, like
241 * the standard C stdio function feof, does not provide the
242 * ability to peek ahead.
245 * EOF if end-of-file has been detected, 0 if not.
247 *----------------------------------------------------------------------
249 int FCGX_HasSeenEOF(FCGX_Stream *stream) {
250 return (stream->isClosed) ? EOF : 0;
254 *----------------------------------------------------------------------
258 * Writes a byte to the output stream.
261 * The byte, or EOF (-1) if an error occurred.
263 *----------------------------------------------------------------------
265 int FCGX_PutChar(int c, FCGX_Stream *stream)
267 if(stream->wrNext != stream->stop)
268 return (*stream->wrNext++ = c);
269 if(stream->isClosed || stream->isReader)
271 stream->emptyBuffProc(stream, FALSE);
272 if(stream->wrNext != stream->stop)
273 return (*stream->wrNext++ = c);
274 ASSERT(stream->isClosed); /* bug in emptyBuffProc if not */
279 *----------------------------------------------------------------------
283 * Writes n consecutive bytes from the character array str
284 * into the output stream. Performs no interpretation
285 * of the output bytes.
288 * Number of bytes written (n) for normal return,
289 * EOF (-1) if an error occurred.
291 *----------------------------------------------------------------------
293 int FCGX_PutStr(const char *str, int n, FCGX_Stream *stream)
298 * Fast path: room for n bytes in the buffer
300 if(n <= (stream->stop - stream->wrNext)) {
301 memcpy(stream->wrNext, str, n);
306 * General case: stream is closed or buffer empty procedure
311 if(stream->wrNext != stream->stop) {
312 m = min(n - bytesMoved, stream->stop - stream->wrNext);
313 memcpy(stream->wrNext, str, m);
320 if(stream->isClosed || stream->isReader)
322 stream->emptyBuffProc(stream, FALSE);
327 *----------------------------------------------------------------------
331 * Writes a character string to the output stream.
334 * number of bytes written for normal return,
335 * EOF (-1) if an error occurred.
337 *----------------------------------------------------------------------
339 int FCGX_PutS(const char *str, FCGX_Stream *stream)
341 return FCGX_PutStr(str, strlen(str), stream);
345 *----------------------------------------------------------------------
349 * Performs output formatting and writes the results
350 * to the output stream.
353 * number of bytes written for normal return,
354 * EOF (-1) if an error occurred.
356 *----------------------------------------------------------------------
358 int FCGX_FPrintF(FCGX_Stream *stream, const char *format, ...)
362 va_start(ap, format);
363 result = FCGX_VFPrintF(stream, format, ap);
369 *----------------------------------------------------------------------
373 * Performs output formatting and writes the results
374 * to the output stream.
377 * number of bytes written for normal return,
378 * EOF (-1) if an error occurred.
380 *----------------------------------------------------------------------
383 #define PRINTF_BUFFLEN 100
385 * More than sufficient space for all unmodified conversions
388 #define FMT_BUFFLEN 25
390 * Max size of a format specifier is 1 + 5 + 7 + 7 + 2 + 1 + slop
392 static void CopyAndAdvance(char **destPtr, char **srcPtr, int n);
394 int FCGX_VFPrintF(FCGX_Stream *stream, const char *format, va_list arg)
396 char *f, *fStop, *percentPtr, *p, *fmtBuffPtr, *buffPtr;
397 int op, performedOp, sizeModifier, buffCount, buffLen, specifierLength;
398 int fastPath, n, auxBuffLen, buffReqd, minWidth, precision, exp;
399 char *auxBuffPtr = NULL;
401 char fmtBuff[FMT_BUFFLEN];
402 char buff[PRINTF_BUFFLEN];
407 unsigned unsignedArg;
408 unsigned long uLongArg;
409 unsigned short uShortArg;
416 LONG_DOUBLE lDoubleArg;
420 fStop = f + strlen(f);
422 percentPtr = memchr(f, '%', fStop - f);
423 if(percentPtr == NULL) percentPtr = fStop;
424 if(percentPtr != f) {
425 if(FCGX_PutStr(f, percentPtr - f, stream) < 0) goto ErrorReturn;
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+ #");
481 if(n > 5) goto ErrorReturn;
482 CopyAndAdvance(&fmtBuffPtr, &p, n);
484 * Scan minimum field width
486 n = strspn(p, "0123456789");
489 minWidth = va_arg(arg, int);
490 if(abs(minWidth) > 999999) goto ErrorReturn;
492 * The following use of strlen rather than the
493 * value returned from sprintf is because SUNOS4
494 * returns a char * instead of an int count.
496 sprintf(fmtBuffPtr, "%d", minWidth);
497 fmtBuffPtr += strlen(fmtBuffPtr);
503 minWidth = strtol(p, NULL, 10);
504 CopyAndAdvance(&fmtBuffPtr, &p, n);
512 CopyAndAdvance(&fmtBuffPtr, &p, 1);
513 n = strspn(p, "0123456789");
516 precision = va_arg(arg, int);
517 if(precision < 0) precision = 0;
518 if(precision > 999999) goto ErrorReturn;
520 * The following use of strlen rather than the
521 * value returned from sprintf is because SUNOS4
522 * returns a char * instead of an int count.
524 sprintf(fmtBuffPtr, "%d", precision);
525 fmtBuffPtr += strlen(fmtBuffPtr);
531 precision = strtol(p, NULL, 10);
532 CopyAndAdvance(&fmtBuffPtr, &p, n);
540 * Scan size modifier and conversion operation
547 CopyAndAdvance(&fmtBuffPtr, &p, 1);
554 CopyAndAdvance(&fmtBuffPtr, &p, 1);
555 ASSERT(fmtBuffPtr - fmtBuff < FMT_BUFFLEN);
557 specifierLength = p - percentPtr;
559 * Bound the required buffer size. For s and f
560 * conversions this requires examining the argument.
571 buffReqd = max(precision, 46);
574 charPtrArg = va_arg(arg, char *);
575 if(precision == -1) {
576 buffReqd = strlen(charPtrArg);
578 p = memchr(charPtrArg, '\0', precision);
580 (p == NULL) ? precision : p - charPtrArg;
584 switch(sizeModifier) {
586 doubleArg = va_arg(arg, double);
587 frexp(doubleArg, &exp);
590 lDoubleArg = va_arg(arg, LONG_DOUBLE);
591 frexp(lDoubleArg, &exp);
596 if(precision == -1) precision = 6;
597 buffReqd = precision + 3 + ((exp > 0) ? exp/3 : 0);
603 if(precision == -1) precision = 6;
604 buffReqd = precision + 8;
612 buffReqd = max(buffReqd + 10, minWidth);
614 * Allocate the buffer
616 if(buffReqd <= PRINTF_BUFFLEN) {
618 buffLen = PRINTF_BUFFLEN;
620 if(auxBuffPtr == NULL || buffReqd > auxBuffLen) {
621 if(auxBuffPtr != NULL) free(auxBuffPtr);
622 auxBuffPtr = Malloc(buffReqd);
623 auxBuffLen = buffReqd;
624 if(auxBuffPtr == NULL) goto ErrorReturn;
626 buffPtr = auxBuffPtr;
627 buffLen = auxBuffLen;
631 * This giant switch statement requires the following variables
632 * to be set up: op, sizeModifier, arg, buffPtr, fmtBuff.
633 * When fastPath == FALSE and op == 's' or 'f', the argument
634 * has been read into charPtrArg, doubleArg, or lDoubleArg.
635 * The statement produces the boolean performedOp, TRUE iff
636 * the op/sizeModifier were executed and argument consumed;
637 * if performedOp, the characters written into buffPtr[]
638 * and the character count buffCount (== EOF meaning error).
640 * The switch cases are arranged in the same order as in the
641 * description of fprintf in section 15.11 of Harbison and Steele.
647 switch(sizeModifier) {
649 intArg = va_arg(arg, int);
650 sprintf(buffPtr, fmtBuff, intArg);
651 buffCount = strlen(buffPtr);
654 longArg = va_arg(arg, long);
655 sprintf(buffPtr, fmtBuff, longArg);
656 buffCount = strlen(buffPtr);
659 shortArg = va_arg(arg, short);
660 sprintf(buffPtr, fmtBuff, shortArg);
661 buffCount = strlen(buffPtr);
671 switch(sizeModifier) {
673 unsignedArg = va_arg(arg, unsigned);
674 sprintf(buffPtr, fmtBuff, unsignedArg);
675 buffCount = strlen(buffPtr);
678 uLongArg = va_arg(arg, unsigned long);
679 sprintf(buffPtr, fmtBuff, uLongArg);
680 buffCount = strlen(buffPtr);
683 uShortArg = va_arg(arg, unsigned short);
684 sprintf(buffPtr, fmtBuff, uShortArg);
685 buffCount = strlen(buffPtr);
692 switch(sizeModifier) {
694 intArg = va_arg(arg, int);
695 sprintf(buffPtr, fmtBuff, intArg);
696 buffCount = strlen(buffPtr);
700 * XXX: Allowed by ISO C Amendment 1, but
701 * many platforms don't yet support wint_t
709 switch(sizeModifier) {
712 buffPtr = va_arg(arg, char *);
713 buffCount = strlen(buffPtr);
714 buffLen = buffCount + 1;
716 sprintf(buffPtr, fmtBuff, charPtrArg);
717 buffCount = strlen(buffPtr);
722 * XXX: Don't know how to convert a sequence
723 * of wide characters into a byte stream, or
724 * even how to predict the buffering required.
732 if(sizeModifier != ' ') goto ErrorReturn;
733 voidPtrArg = va_arg(arg, void *);
734 sprintf(buffPtr, fmtBuff, voidPtrArg);
735 buffCount = strlen(buffPtr);
738 switch(sizeModifier) {
740 intPtrArg = va_arg(arg, int *);
741 *intPtrArg = streamCount;
744 longPtrArg = va_arg(arg, long *);
745 *longPtrArg = streamCount;
748 shortPtrArg = va_arg(arg, short *);
749 *shortPtrArg = streamCount;
761 switch(sizeModifier) {
763 sprintf(buffPtr, fmtBuff, doubleArg);
764 buffCount = strlen(buffPtr);
767 sprintf(buffPtr, fmtBuff, lDoubleArg);
768 buffCount = strlen(buffPtr);
778 switch(sizeModifier) {
780 doubleArg = va_arg(arg, double);
781 sprintf(buffPtr, fmtBuff, doubleArg);
782 buffCount = strlen(buffPtr);
785 lDoubleArg = va_arg(arg, LONG_DOUBLE);
786 sprintf(buffPtr, fmtBuff, lDoubleArg);
787 buffCount = strlen(buffPtr);
794 if(sizeModifier != ' ')
805 if(performedOp) break;
806 if(!fastPath) goto ErrorReturn;
809 ASSERT(buffCount < buffLen);
811 if(FCGX_PutStr(buffPtr, buffCount, stream) < 0)
813 streamCount += buffCount;
814 } else if(buffCount < 0) {
817 f += specifierLength;
818 } /* while(f != fStop) */
823 if(auxBuffPtr != NULL) free(auxBuffPtr);
828 * Copy n characters from *srcPtr to *destPtr, then increment
829 * both *srcPtr and *destPtr by n.
831 static void CopyAndAdvance(char **destPtr, char **srcPtr, int n)
833 char *dest = *destPtr;
836 for (i = 0; i < n; i++)
843 *----------------------------------------------------------------------
847 * Flushes any buffered output.
849 * Server-push is a legitimate application of FCGX_FFlush.
850 * Otherwise, FCGX_FFlush is not very useful, since FCGX_Accept
851 * does it implicitly. FCGX_FFlush may reduce performance
852 * by increasing the total number of operating system calls
853 * the application makes.
856 * EOF (-1) if an error occurred.
858 *----------------------------------------------------------------------
860 int FCGX_FFlush(FCGX_Stream *stream)
862 if(stream->isClosed || stream->isReader)
864 stream->emptyBuffProc(stream, FALSE);
865 return (stream->isClosed) ? -1 : 0;
869 *----------------------------------------------------------------------
873 * Performs FCGX_FFlush and closes the stream.
875 * This is not a very useful operation, since FCGX_Accept
876 * does it implicitly. Closing the out stream before the
877 * err stream results in an extra write if there's nothing
878 * in the err stream, and therefore reduces performance.
881 * EOF (-1) if an error occurred.
883 *----------------------------------------------------------------------
885 int FCGX_FClose(FCGX_Stream *stream)
887 if(!stream->wasFCloseCalled) {
888 if(!stream->isReader) {
889 stream->emptyBuffProc(stream, TRUE);
891 stream->wasFCloseCalled = TRUE;
892 stream->isClosed = TRUE;
893 if(stream->isReader) {
894 stream->wrNext = stream->stop = stream->rdNext;
896 stream->rdNext = stream->stop = stream->wrNext;
899 return (stream->FCGI_errno == 0) ? 0 : EOF;
903 *----------------------------------------------------------------------
907 * An error has occurred; save the error code in the stream
908 * for diagnostic purposes and set the stream state so that
909 * reads return EOF and writes have no effect.
911 *----------------------------------------------------------------------
913 static void SetError(FCGX_Stream *stream, int FCGI_errno)
916 * Preserve only the first error.
918 if(stream->FCGI_errno == 0) {
919 stream->FCGI_errno = FCGI_errno;
920 stream->isClosed = TRUE;
925 *----------------------------------------------------------------------
929 * Return the stream error code. 0 means no error, > 0
930 * is an errno(2) error, < 0 is an FCGX_errno error.
932 *----------------------------------------------------------------------
934 int FCGX_GetError(FCGX_Stream *stream) {
935 return stream->FCGI_errno;
939 *----------------------------------------------------------------------
943 * Clear the stream error code and end-of-file indication.
945 *----------------------------------------------------------------------
947 void FCGX_ClearError(FCGX_Stream *stream) {
948 stream->FCGI_errno = 0;
950 * stream->isClosed = FALSE;
951 * XXX: should clear isClosed but work is needed to make it safe
952 * to do so. For example, if an application calls FClose, gets
953 * an I/O error on the write, calls ClearError and retries
954 * the FClose, FClose (really EmptyBuffProc) will write a second
955 * EOF record. If an application calls PutChar instead of FClose
956 * after the ClearError, the application will write more data.
957 * The stream's state must discriminate between various states
958 * of the stream that are now all lumped under isClosed.
963 *======================================================================
965 *======================================================================
969 * A vector of pointers representing the parameters received
970 * by a FastCGI application server, with the vector's length
971 * and last valid element so adding new parameters is efficient.
974 typedef struct Params {
975 FCGX_ParamArray vec; /* vector of strings */
976 int length; /* number of string vec can hold */
977 char **cur; /* current item in vec; *cur == NULL */
979 typedef Params *ParamsPtr;
982 *----------------------------------------------------------------------
986 * Creates a new Params structure.
989 * Pointer to the new structure.
991 *----------------------------------------------------------------------
993 static ParamsPtr NewParams(int length)
996 result = Malloc(sizeof(Params));
997 result->vec = (char **) Malloc(length * sizeof(char *));
998 result->length = length;
999 result->cur = result->vec;
1000 *result->cur = NULL;
1005 *----------------------------------------------------------------------
1009 * Frees a Params structure and all the parameters it contains.
1012 * paramsPtr becomes invalid.
1014 *----------------------------------------------------------------------
1016 static void FreeParams(ParamsPtr *paramsPtrPtr)
1018 ParamsPtr paramsPtr = *paramsPtrPtr;
1020 if(paramsPtr == NULL) {
1023 for (p = paramsPtr->vec; p < paramsPtr->cur; p++) {
1026 free(paramsPtr->vec);
1028 *paramsPtrPtr = NULL;
1032 *----------------------------------------------------------------------
1036 * Add a name/value pair to a Params structure.
1042 * Parameters structure updated.
1044 *----------------------------------------------------------------------
1046 static void PutParam(ParamsPtr paramsPtr, char *nameValue)
1050 *paramsPtr->cur++ = nameValue;
1051 size = paramsPtr->cur - paramsPtr->vec;
1052 if(size >= paramsPtr->length) {
1053 paramsPtr->length *= 2;
1055 realloc(paramsPtr->vec, paramsPtr->length * sizeof(char *));
1056 paramsPtr->cur = paramsPtr->vec + size;
1058 *paramsPtr->cur = NULL;
1062 *----------------------------------------------------------------------
1064 * FCGX_GetParam -- obtain value of FCGI parameter in environment
1068 * Value bound to name, NULL if name not present in the
1069 * environment envp. Caller must not mutate the result
1070 * or retain it past the end of this request.
1072 *----------------------------------------------------------------------
1074 char *FCGX_GetParam(const char *name, FCGX_ParamArray envp)
1079 if(len == 0) return NULL;
1080 for (p = envp; *p != NULL; p++) {
1081 if((strncmp(name, *p, len) == 0) && ((*p)[len] == '=')) {
1089 *----------------------------------------------------------------------
1091 * Start of FastCGI-specific code
1093 *----------------------------------------------------------------------
1097 *----------------------------------------------------------------------
1101 * Reads FastCGI name-value pairs from stream until EOF. Converts
1102 * each pair to name=value format and adds it to Params structure.
1104 *----------------------------------------------------------------------
1106 static int ReadParams(Params *paramsPtr, FCGX_Stream *stream)
1108 int nameLen, valueLen;
1109 unsigned char lenBuff[3];
1112 while((nameLen = FCGX_GetChar(stream)) != EOF) {
1114 * Read name length (one or four bytes) and value length
1115 * (one or four bytes) from stream.
1117 if((nameLen & 0x80) != 0) {
1118 if(FCGX_GetStr((char *) &lenBuff[0], 3, stream) != 3) {
1119 SetError(stream, FCGX_PARAMS_ERROR);
1122 nameLen = ((nameLen & 0x7f) << 24) + (lenBuff[0] << 16)
1123 + (lenBuff[1] << 8) + lenBuff[2];
1125 if((valueLen = FCGX_GetChar(stream)) == EOF) {
1126 SetError(stream, FCGX_PARAMS_ERROR);
1129 if((valueLen & 0x80) != 0) {
1130 if(FCGX_GetStr((char *) &lenBuff[0], 3, stream) != 3) {
1131 SetError(stream, FCGX_PARAMS_ERROR);
1134 valueLen = ((valueLen & 0x7f) << 24) + (lenBuff[0] << 16)
1135 + (lenBuff[1] << 8) + lenBuff[2];
1138 * nameLen and valueLen are now valid; read the name and value
1139 * from stream and construct a standard environment entry.
1141 nameValue = Malloc(nameLen + valueLen + 2);
1142 if(FCGX_GetStr(nameValue, nameLen, stream) != nameLen) {
1143 SetError(stream, FCGX_PARAMS_ERROR);
1147 *(nameValue + nameLen) = '=';
1148 if(FCGX_GetStr(nameValue + nameLen + 1, valueLen, stream)
1150 SetError(stream, FCGX_PARAMS_ERROR);
1154 *(nameValue + nameLen + valueLen + 1) = '\0';
1155 PutParam(paramsPtr, nameValue);
1161 *----------------------------------------------------------------------
1165 * Constructs an FCGI_Header struct.
1167 *----------------------------------------------------------------------
1169 static FCGI_Header MakeHeader(
1176 ASSERT(contentLength >= 0 && contentLength <= FCGI_MAX_LENGTH);
1177 ASSERT(paddingLength >= 0 && paddingLength <= 0xff);
1178 header.version = FCGI_VERSION_1;
1180 header.requestIdB1 = (requestId >> 8) & 0xff;
1181 header.requestIdB0 = (requestId ) & 0xff;
1182 header.contentLengthB1 = (contentLength >> 8) & 0xff;
1183 header.contentLengthB0 = (contentLength ) & 0xff;
1184 header.paddingLength = paddingLength;
1185 header.reserved = 0;
1190 *----------------------------------------------------------------------
1192 * MakeEndRequestBody --
1194 * Constructs an FCGI_EndRequestBody struct.
1196 *----------------------------------------------------------------------
1198 static FCGI_EndRequestBody MakeEndRequestBody(
1202 FCGI_EndRequestBody body;
1203 body.appStatusB3 = (appStatus >> 24) & 0xff;
1204 body.appStatusB2 = (appStatus >> 16) & 0xff;
1205 body.appStatusB1 = (appStatus >> 8) & 0xff;
1206 body.appStatusB0 = (appStatus ) & 0xff;
1207 body.protocolStatus = protocolStatus;
1208 memset(body.reserved, 0, sizeof(body.reserved));
1213 *----------------------------------------------------------------------
1215 * MakeUnknownTypeBody --
1217 * Constructs an FCGI_MakeUnknownTypeBody struct.
1219 *----------------------------------------------------------------------
1221 static FCGI_UnknownTypeBody MakeUnknownTypeBody(
1224 FCGI_UnknownTypeBody body;
1226 memset(body.reserved, 0, sizeof(body.reserved));
1231 *----------------------------------------------------------------------
1235 * Returns the smallest integer greater than or equal to n
1236 * that's a multiple of 8.
1238 *----------------------------------------------------------------------
1240 static int AlignInt8(unsigned n) {
1241 return (n + 7) & (UINT_MAX - 7);
1245 *----------------------------------------------------------------------
1249 * Returns the smallest pointer greater than or equal to p
1250 * that's a multiple of 8.
1252 *----------------------------------------------------------------------
1254 static unsigned char *AlignPtr8(unsigned char *p) {
1255 unsigned long u = (unsigned long) p;
1256 u = ((u + 7) & (ULONG_MAX - 7)) - u;
1262 * State associated with a stream
1264 typedef struct FCGX_Stream_Data {
1265 unsigned char *buff; /* buffer after alignment */
1266 int bufflen; /* number of bytes buff can store */
1267 unsigned char *mBuff; /* buffer as returned by Malloc */
1268 unsigned char *buffStop; /* reader: last valid byte + 1 of entire buffer.
1269 * stop generally differs from buffStop for
1270 * readers because of record structure.
1271 * writer: buff + bufflen */
1272 int type; /* reader: FCGI_PARAMS or FCGI_STDIN
1273 * writer: FCGI_STDOUT or FCGI_STDERR */
1274 int eorStop; /* reader: stop stream at end-of-record */
1275 int skip; /* reader: don't deliver content bytes */
1276 int contentLen; /* reader: bytes of unread content */
1277 int paddingLen; /* reader: bytes of unread padding */
1278 int isAnythingWritten; /* writer: data has been written to ipcFd */
1279 int rawWrite; /* writer: write data without stream headers */
1280 FCGX_Request *reqDataPtr; /* request data not specific to one stream */
1284 *----------------------------------------------------------------------
1286 * WriteCloseRecords --
1288 * Writes an EOF record for the stream content if necessary.
1289 * If this is the last writer to close, writes an FCGI_END_REQUEST
1292 *----------------------------------------------------------------------
1294 static void WriteCloseRecords(struct FCGX_Stream *stream)
1296 FCGX_Stream_Data *data = stream->data;
1298 * Enter rawWrite mode so final records won't be encapsulated as
1301 data->rawWrite = TRUE;
1303 * Generate EOF for stream content if needed.
1305 if(!(data->type == FCGI_STDERR
1306 && stream->wrNext == data->buff
1307 && !data->isAnythingWritten)) {
1309 header = MakeHeader(data->type, data->reqDataPtr->requestId, 0, 0);
1310 FCGX_PutStr((char *) &header, sizeof(header), stream);
1313 * Generate FCGI_END_REQUEST record if needed.
1315 if(data->reqDataPtr->nWriters == 1) {
1316 FCGI_EndRequestRecord endRequestRecord;
1317 endRequestRecord.header = MakeHeader(FCGI_END_REQUEST,
1318 data->reqDataPtr->requestId,
1319 sizeof(endRequestRecord.body), 0);
1320 endRequestRecord.body = MakeEndRequestBody(
1321 data->reqDataPtr->appStatus, FCGI_REQUEST_COMPLETE);
1322 FCGX_PutStr((char *) &endRequestRecord,
1323 sizeof(endRequestRecord), stream);
1325 data->reqDataPtr->nWriters--;
1330 static int write_it_all(int fd, char *buf, int len)
1335 wrote = OS_Write(fd, buf, len);
1345 *----------------------------------------------------------------------
1349 * Encapsulates any buffered stream content in a FastCGI
1350 * record. Writes the data, making the buffer empty.
1352 *----------------------------------------------------------------------
1354 static void EmptyBuffProc(struct FCGX_Stream *stream, int doClose)
1356 FCGX_Stream_Data *data = stream->data;
1359 * If the buffer contains stream data, fill in the header.
1360 * Pad the record to a multiple of 8 bytes in length. Padding
1361 * can't overflow the buffer because the buffer is a multiple
1362 * of 8 bytes in length. If the buffer contains no stream
1363 * data, reclaim the space reserved for the header.
1365 if(!data->rawWrite) {
1366 cLen = stream->wrNext - data->buff - sizeof(FCGI_Header);
1368 eLen = AlignInt8(cLen);
1370 * Giving the padding a well-defined value keeps Purify happy.
1372 memset(stream->wrNext, 0, eLen - cLen);
1373 stream->wrNext += eLen - cLen;
1374 *((FCGI_Header *) data->buff)
1375 = MakeHeader(data->type,
1376 data->reqDataPtr->requestId, cLen, eLen - cLen);
1378 stream->wrNext = data->buff;
1382 WriteCloseRecords(stream);
1384 if (stream->wrNext != data->buff) {
1385 data->isAnythingWritten = TRUE;
1386 if (write_it_all(data->reqDataPtr->ipcFd, (char *)data->buff, stream->wrNext - data->buff) < 0) {
1387 SetError(stream, OS_Errno);
1390 stream->wrNext = data->buff;
1393 * The buffer is empty.
1395 if(!data->rawWrite) {
1396 stream->wrNext += sizeof(FCGI_Header);
1401 * Return codes for Process* functions
1403 #define STREAM_RECORD 0
1405 #define BEGIN_RECORD 2
1406 #define MGMT_RECORD 3
1409 *----------------------------------------------------------------------
1411 * ProcessManagementRecord --
1413 * Reads and responds to a management record. The only type of
1414 * management record this library understands is FCGI_GET_VALUES.
1415 * The only variables that this library's FCGI_GET_VALUES
1416 * understands are FCGI_MAX_CONNS, FCGI_MAX_REQS, and FCGI_MPXS_CONNS.
1417 * Ignore other FCGI_GET_VALUES variables; respond to other
1418 * management records with a FCGI_UNKNOWN_TYPE record.
1420 *----------------------------------------------------------------------
1422 static int ProcessManagementRecord(int type, FCGX_Stream *stream)
1424 FCGX_Stream_Data *data = stream->data;
1425 ParamsPtr paramsPtr = NewParams(3);
1427 char response[64]; /* 64 = 8 + 3*(1+1+14+1)* + padding */
1428 char *responseP = &response[FCGI_HEADER_LEN];
1431 if(type == FCGI_GET_VALUES) {
1432 ReadParams(paramsPtr, stream);
1433 if((FCGX_GetError(stream) != 0) || (data->contentLen != 0)) {
1434 FreeParams(¶msPtr);
1435 return FCGX_PROTOCOL_ERROR;
1437 for (pPtr = paramsPtr->vec; pPtr < paramsPtr->cur; pPtr++) {
1439 *(strchr(name, '=')) = '\0';
1440 if(strcmp(name, FCGI_MAX_CONNS) == 0) {
1442 } else if(strcmp(name, FCGI_MAX_REQS) == 0) {
1444 } else if(strcmp(name, FCGI_MPXS_CONNS) == 0) {
1451 sprintf(responseP, "%c%c%s%c", len, 1, name, value);
1452 responseP += len + 3;
1455 len = responseP - &response[FCGI_HEADER_LEN];
1456 paddedLen = AlignInt8(len);
1457 *((FCGI_Header *) response)
1458 = MakeHeader(FCGI_GET_VALUES_RESULT, FCGI_NULL_REQUEST_ID,
1459 len, paddedLen - len);
1460 FreeParams(¶msPtr);
1462 paddedLen = len = sizeof(FCGI_UnknownTypeBody);
1463 ((FCGI_UnknownTypeRecord *) response)->header
1464 = MakeHeader(FCGI_UNKNOWN_TYPE, FCGI_NULL_REQUEST_ID,
1466 ((FCGI_UnknownTypeRecord *) response)->body
1467 = MakeUnknownTypeBody(type);
1469 if (write_it_all(data->reqDataPtr->ipcFd, response, FCGI_HEADER_LEN + paddedLen) < 0) {
1470 SetError(stream, OS_Errno);
1478 *----------------------------------------------------------------------
1480 * ProcessBeginRecord --
1482 * Reads an FCGI_BEGIN_REQUEST record.
1485 * BEGIN_RECORD for normal return. FCGX_PROTOCOL_ERROR for
1486 * protocol error. SKIP for attempt to multiplex
1487 * connection. -1 for error from write (errno in stream).
1490 * In case of BEGIN_RECORD return, stores requestId, role,
1491 * keepConnection values, and sets isBeginProcessed = TRUE.
1493 *----------------------------------------------------------------------
1495 static int ProcessBeginRecord(int requestId, FCGX_Stream *stream)
1497 FCGX_Stream_Data *data = stream->data;
1498 FCGI_BeginRequestBody body;
1499 if(requestId == 0 || data->contentLen != sizeof(body)) {
1500 return FCGX_PROTOCOL_ERROR;
1502 if(data->reqDataPtr->isBeginProcessed) {
1504 * The Web server is multiplexing the connection. This library
1505 * doesn't know how to handle multiplexing, so respond with
1506 * FCGI_END_REQUEST{protocolStatus = FCGI_CANT_MPX_CONN}
1508 FCGI_EndRequestRecord endRequestRecord;
1509 endRequestRecord.header = MakeHeader(FCGI_END_REQUEST,
1510 requestId, sizeof(endRequestRecord.body), 0);
1511 endRequestRecord.body
1512 = MakeEndRequestBody(0, FCGI_CANT_MPX_CONN);
1513 if (write_it_all(data->reqDataPtr->ipcFd, (char *)&endRequestRecord, sizeof(endRequestRecord)) < 0) {
1514 SetError(stream, OS_Errno);
1521 * Accept this new request. Read the record body.
1523 data->reqDataPtr->requestId = requestId;
1524 if(FCGX_GetStr((char *) &body, sizeof(body), stream)
1526 return FCGX_PROTOCOL_ERROR;
1528 data->reqDataPtr->keepConnection = (body.flags & FCGI_KEEP_CONN);
1529 data->reqDataPtr->role = (body.roleB1 << 8) + body.roleB0;
1530 data->reqDataPtr->isBeginProcessed = TRUE;
1531 return BEGIN_RECORD;
1535 *----------------------------------------------------------------------
1539 * Interprets FCGI_Header. Processes FCGI_BEGIN_REQUEST and
1540 * management records here; extracts information from stream
1541 * records (FCGI_PARAMS, FCGI_STDIN) into stream.
1544 * >= 0 for a normal return, < 0 for error
1547 * XXX: Many (more than there used to be).
1548 * If !stream->isRequestIdSet, ProcessHeader initializes
1549 * stream->requestId from header and sets stream->isRequestIdSet
1550 * to TRUE. ProcessHeader also sets stream->contentLen to header's
1551 * contentLength, and sets stream->paddingLen to the header's
1554 *----------------------------------------------------------------------
1556 static int ProcessHeader(FCGI_Header header, FCGX_Stream *stream)
1558 FCGX_Stream_Data *data = stream->data;
1560 if(header.version != FCGI_VERSION_1) {
1561 return FCGX_UNSUPPORTED_VERSION;
1563 requestId = (header.requestIdB1 << 8)
1564 + header.requestIdB0;
1565 data->contentLen = (header.contentLengthB1 << 8)
1566 + header.contentLengthB0;
1567 data->paddingLen = header.paddingLength;
1568 if(header.type == FCGI_BEGIN_REQUEST) {
1569 return ProcessBeginRecord(requestId, stream);
1571 if(requestId == FCGI_NULL_REQUEST_ID) {
1572 return ProcessManagementRecord(header.type, stream);
1574 if(requestId != data->reqDataPtr->requestId) {
1577 if(header.type != data->type) {
1578 return FCGX_PROTOCOL_ERROR;
1580 return STREAM_RECORD;
1584 *----------------------------------------------------------------------
1588 * Reads bytes from the ipcFd, supplies bytes to a stream client.
1590 *----------------------------------------------------------------------
1592 static void FillBuffProc(FCGX_Stream *stream)
1594 FCGX_Stream_Data *data = stream->data;
1601 * If data->buff is empty, do a read.
1603 if(stream->rdNext == data->buffStop) {
1604 count = OS_Read(data->reqDataPtr->ipcFd, (char *)data->buff,
1607 SetError(stream, (count == 0 ? FCGX_PROTOCOL_ERROR : OS_Errno));
1610 stream->rdNext = data->buff;
1611 data->buffStop = data->buff + count;
1614 * Now data->buff is not empty. If the current record contains
1615 * more content bytes, deliver all that are present in data->buff.
1617 if(data->contentLen > 0) {
1618 count = min(data->contentLen, data->buffStop - stream->rdNext);
1619 data->contentLen -= count;
1621 stream->wrNext = stream->stop = stream->rdNext + count;
1624 stream->rdNext += count;
1625 if(data->contentLen > 0) {
1633 * If the current record (whose content has been fully consumed by
1634 * the client) was padded, skip over the padding bytes.
1636 if(data->paddingLen > 0) {
1637 count = min(data->paddingLen, data->buffStop - stream->rdNext);
1638 data->paddingLen -= count;
1639 stream->rdNext += count;
1640 if(data->paddingLen > 0) {
1645 * All done with the current record, including the padding.
1646 * If we're in a recursive call from ProcessHeader, deliver EOF.
1649 stream->stop = stream->rdNext;
1650 stream->isClosed = TRUE;
1654 * Fill header with bytes from the input buffer.
1656 count = min((int)sizeof(header) - headerLen,
1657 data->buffStop - stream->rdNext);
1658 memcpy(((char *)(&header)) + headerLen, stream->rdNext, count);
1660 stream->rdNext += count;
1661 if(headerLen < sizeof(header)) {
1666 * Interpret header. eorStop prevents ProcessHeader from reading
1667 * past the end-of-record when using stream to read content.
1669 data->eorStop = TRUE;
1670 stream->stop = stream->rdNext;
1671 status = ProcessHeader(header, stream);
1672 data->eorStop = FALSE;
1673 stream->isClosed = FALSE;
1677 * If this stream record header marked the end of stream
1678 * data deliver EOF to the stream client, otherwise loop
1681 * XXX: If this is final stream and
1682 * stream->rdNext != data->buffStop, buffered
1683 * data is next request (server pipelining)?
1685 if(data->contentLen == 0) {
1686 stream->wrNext = stream->stop = stream->rdNext;
1687 stream->isClosed = TRUE;
1696 * If this header marked the beginning of a new
1697 * request, return role information to caller.
1705 SetError(stream, status);
1713 *----------------------------------------------------------------------
1717 * Creates a stream to read or write from an open ipcFd.
1718 * The stream performs reads/writes of up to bufflen bytes.
1720 *----------------------------------------------------------------------
1722 static FCGX_Stream *NewStream(
1723 FCGX_Request *reqDataPtr, int bufflen, int isReader, int streamType)
1726 * XXX: It would be a lot cleaner to have a NewStream that only
1727 * knows about the type FCGX_Stream, with all other
1728 * necessary data passed in. It appears that not just
1729 * data and the two procs are needed for initializing stream,
1730 * but also data->buff and data->buffStop. This has implications
1731 * for procs that want to swap buffers, too.
1733 FCGX_Stream *stream = Malloc(sizeof(FCGX_Stream));
1734 FCGX_Stream_Data *data = Malloc(sizeof(FCGX_Stream_Data));
1735 data->reqDataPtr = reqDataPtr;
1736 bufflen = AlignInt8(min(max(bufflen, 32), FCGI_MAX_LENGTH + 1));
1737 data->bufflen = bufflen;
1738 data->mBuff = Malloc(bufflen);
1739 data->buff = AlignPtr8(data->mBuff);
1740 if(data->buff != data->mBuff) {
1744 data->buffStop = data->buff;
1746 data->buffStop = data->buff + data->bufflen;
1748 data->type = streamType;
1749 data->eorStop = FALSE;
1751 data->contentLen = 0;
1752 data->paddingLen = 0;
1753 data->isAnythingWritten = FALSE;
1754 data->rawWrite = FALSE;
1756 stream->data = data;
1757 stream->isReader = isReader;
1758 stream->isClosed = FALSE;
1759 stream->wasFCloseCalled = FALSE;
1760 stream->FCGI_errno = 0;
1762 stream->fillBuffProc = FillBuffProc;
1763 stream->emptyBuffProc = NULL;
1764 stream->rdNext = data->buff;
1765 stream->stop = stream->rdNext;
1766 stream->stopUnget = data->buff;
1767 stream->wrNext = stream->stop;
1769 stream->fillBuffProc = NULL;
1770 stream->emptyBuffProc = EmptyBuffProc;
1771 stream->wrNext = data->buff + sizeof(FCGI_Header);
1772 stream->stop = data->buffStop;
1773 stream->stopUnget = NULL;
1774 stream->rdNext = stream->stop;
1780 *----------------------------------------------------------------------
1784 * Frees all storage allocated when *streamPtr was created,
1785 * and nulls out *streamPtr.
1787 *----------------------------------------------------------------------
1789 void FreeStream(FCGX_Stream **streamPtr)
1791 FCGX_Stream *stream = *streamPtr;
1792 FCGX_Stream_Data *data;
1793 if(stream == NULL) {
1796 data = stream->data;
1797 data->reqDataPtr = NULL;
1805 *----------------------------------------------------------------------
1809 * Re-initializes the stream to read data of the specified type.
1811 *----------------------------------------------------------------------
1813 static FCGX_Stream *SetReaderType(FCGX_Stream *stream, int streamType)
1815 FCGX_Stream_Data *data = stream->data;
1816 ASSERT(stream->isReader);
1817 data->type = streamType;
1818 data->eorStop = FALSE;
1820 data->contentLen = 0;
1821 data->paddingLen = 0;
1822 stream->wrNext = stream->stop = stream->rdNext;
1823 stream->isClosed = FALSE;
1828 *----------------------------------------------------------------------
1832 * Creates a stream to read streamType records for the given
1833 * request. The stream performs OS reads of up to bufflen bytes.
1835 *----------------------------------------------------------------------
1837 static FCGX_Stream *NewReader(FCGX_Request *reqDataPtr, int bufflen, int streamType)
1839 return NewStream(reqDataPtr, bufflen, TRUE, streamType);
1844 *----------------------------------------------------------------------
1848 * Creates a stream to write streamType FastCGI records, using
1849 * the ipcFd and RequestId contained in *reqDataPtr.
1850 * The stream performs OS writes of up to bufflen bytes.
1852 *----------------------------------------------------------------------
1854 static FCGX_Stream *NewWriter(FCGX_Request *reqDataPtr, int bufflen, int streamType)
1856 return NewStream(reqDataPtr, bufflen, FALSE, streamType);
1861 *----------------------------------------------------------------------
1865 * Creates a stream to write streamType FastCGI records, using
1866 * the given ipcFd and request Id. This function is provided
1867 * for use by cgi-fcgi. In order to be defensive against misuse,
1868 * this function leaks a little storage; cgi-fcgi doesn't care.
1870 *----------------------------------------------------------------------
1872 FCGX_Stream *CreateWriter(
1878 FCGX_Request *reqDataPtr = Malloc(sizeof(FCGX_Request));
1879 reqDataPtr->ipcFd = ipcFd;
1880 reqDataPtr->requestId = requestId;
1882 * Suppress writing an FCGI_END_REQUEST record.
1884 reqDataPtr->nWriters = 2;
1885 return NewWriter(reqDataPtr, bufflen, streamType);
1889 *======================================================================
1891 *======================================================================
1895 *----------------------------------------------------------------------
1899 * This routine determines if the process is running as a CGI or
1900 * FastCGI process. The distinction is made by determining whether
1901 * FCGI_LISTENSOCK_FILENO is a listener ipcFd or the end of a
1902 * pipe (ie. standard in).
1905 * TRUE if the process is a CGI process, FALSE if FastCGI.
1908 * If this is a FastCGI process there's a chance that a connection
1909 * will be accepted while performing the test. If this occurs,
1910 * the connection is saved and used later by the FCGX_Accept logic.
1912 *----------------------------------------------------------------------
1914 int FCGX_IsCGI(void)
1916 static int isFastCGI = -1;
1918 if (isFastCGI != -1) {
1922 if (!libInitialized) {
1923 int rc = FCGX_Init();
1925 /* exit() isn't great, but hey */
1926 exit((rc < 0) ? rc : -rc);
1930 isFastCGI = OS_IsFcgi();
1936 *----------------------------------------------------------------------
1940 * Finishes the current request from the HTTP server.
1944 * Finishes the request accepted by (and frees any
1945 * storage allocated by) the previous call to FCGX_Accept.
1947 * DO NOT retain pointers to the envp array or any strings
1948 * contained in it (e.g. to the result of calling FCGX_GetParam),
1949 * since these will be freed by the next call to FCGX_Finish
1952 *----------------------------------------------------------------------
1955 void FCGX_Finish(void)
1957 FCGX_Finish_r(reqDataPtr);
1961 *----------------------------------------------------------------------
1965 * Finishes the current request from the HTTP server.
1969 * Finishes the request accepted by (and frees any
1970 * storage allocated by) the previous call to FCGX_Accept.
1972 * DO NOT retain pointers to the envp array or any strings
1973 * contained in it (e.g. to the result of calling FCGX_GetParam),
1974 * since these will be freed by the next call to FCGX_Finish
1977 *----------------------------------------------------------------------
1979 void FCGX_Finish_r(FCGX_Request *reqDataPtr)
1981 if (reqDataPtr == NULL) {
1985 if (reqDataPtr->inStream) {
1986 int errStatus = FCGX_FClose(reqDataPtr->errStream);
1987 int outStatus = FCGX_FClose(reqDataPtr->outStream);
1989 if (errStatus || outStatus
1990 || FCGX_GetError(reqDataPtr->inStream)
1991 || !reqDataPtr->keepConnection)
1993 OS_IpcClose(reqDataPtr->ipcFd);
1996 ASSERT(reqDataPtr->nWriters == 0);
1998 FreeStream(&reqDataPtr->inStream);
1999 FreeStream(&reqDataPtr->outStream);
2000 FreeStream(&reqDataPtr->errStream);
2002 FreeParams(&reqDataPtr->paramsPtr);
2005 if (!reqDataPtr->keepConnection) {
2006 reqDataPtr->ipcFd = -1;
2011 void FCGX_InitRequest(FCGX_Request *request)
2013 memset(request, 0, sizeof(FCGX_Request));
2017 *----------------------------------------------------------------------
2021 * Initilize the FCGX library. This is called by FCGX_Accept()
2022 * but must be called by the user when using FCGX_Accept_r().
2025 * 0 for successful call.
2027 *----------------------------------------------------------------------
2033 if (libInitialized) {
2037 /* If our compiler doesn't play by the ISO rules for struct layout, halt. */
2038 ASSERT(sizeof(FCGI_Header) == FCGI_HEADER_LEN);
2040 memset(&reqData, 0, sizeof(FCGX_Request));
2042 if (OS_LibInit(NULL) == -1) {
2043 return OS_Errno ? OS_Errno : -9997;
2046 p = getenv("FCGI_WEB_SERVER_ADDRS");
2047 webServerAddressList = p ? StringCopy(p) : "";
2054 *----------------------------------------------------------------------
2058 * Accepts a new request from the HTTP server.
2061 * 0 for successful call, -1 for error.
2065 * Finishes the request accepted by (and frees any
2066 * storage allocated by) the previous call to FCGX_Accept.
2067 * Creates input, output, and error streams and
2068 * assigns them to *in, *out, and *err respectively.
2069 * Creates a parameters data structure to be accessed
2070 * via getenv(3) (if assigned to environ) or by FCGX_GetParam
2071 * and assigns it to *envp.
2073 * DO NOT retain pointers to the envp array or any strings
2074 * contained in it (e.g. to the result of calling FCGX_GetParam),
2075 * since these will be freed by the next call to FCGX_Finish
2078 *----------------------------------------------------------------------
2085 FCGX_ParamArray *envp)
2087 if (!libInitialized) {
2088 int rc = FCGX_Init();
2090 return (rc < 0) ? rc : -rc;
2094 return FCGX_Accept_r(in, out, err, envp, &reqData);
2098 *----------------------------------------------------------------------
2102 * Accepts a new request from the HTTP server.
2105 * 0 for successful call, -1 for error.
2109 * Finishes the request accepted by (and frees any
2110 * storage allocated by) the previous call to FCGX_Accept.
2111 * Creates input, output, and error streams and
2112 * assigns them to *in, *out, and *err respectively.
2113 * Creates a parameters data structure to be accessed
2114 * via getenv(3) (if assigned to environ) or by FCGX_GetParam
2115 * and assigns it to *envp.
2117 * DO NOT retain pointers to the envp array or any strings
2118 * contained in it (e.g. to the result of calling FCGX_GetParam),
2119 * since these will be freed by the next call to FCGX_Finish
2122 *----------------------------------------------------------------------
2128 FCGX_ParamArray *envp,
2129 FCGX_Request *reqDataPtr)
2131 if (!libInitialized) {
2135 /* Finish the current request, if any. */
2136 FCGX_Finish_r(reqDataPtr);
2140 * If a connection isn't open, accept a new connection (blocking).
2141 * If an OS error occurs in accepting the connection,
2142 * return -1 to the caller, who should exit.
2144 if (reqDataPtr->ipcFd < 0) {
2145 reqDataPtr->ipcFd = OS_FcgiIpcAccept(webServerAddressList);
2146 if (reqDataPtr->ipcFd < 0) {
2147 return (errno > 0) ? (0 - errno) : -9999;
2151 * A connection is open. Read from the connection in order to
2152 * get the request's role and environment. If protocol or other
2153 * errors occur, close the connection and try again.
2155 reqDataPtr->isBeginProcessed = FALSE;
2156 reqDataPtr->inStream = NewReader(reqDataPtr, 8192, 0);
2157 FillBuffProc(reqDataPtr->inStream);
2158 if(!reqDataPtr->isBeginProcessed) {
2163 switch(reqDataPtr->role) {
2164 case FCGI_RESPONDER:
2165 roleStr = "FCGI_ROLE=RESPONDER";
2167 case FCGI_AUTHORIZER:
2168 roleStr = "FCGI_ROLE=AUTHORIZER";
2171 roleStr = "FCGI_ROLE=FILTER";
2176 reqDataPtr->paramsPtr = NewParams(30);
2177 PutParam(reqDataPtr->paramsPtr, StringCopy(roleStr));
2179 SetReaderType(reqDataPtr->inStream, FCGI_PARAMS);
2180 if(ReadParams(reqDataPtr->paramsPtr, reqDataPtr->inStream) >= 0) {
2182 * Finished reading the environment. No errors occurred, so
2183 * leave the connection-retry loop.
2188 * Close the connection and try again.
2191 FreeParams(&reqDataPtr->paramsPtr);
2192 FreeStream(&reqDataPtr->inStream);
2193 OS_Close(reqDataPtr->ipcFd);
2194 reqDataPtr->ipcFd = -1;
2197 * Build the remaining data structures representing the new
2198 * request and return successfully to the caller.
2200 SetReaderType(reqDataPtr->inStream, FCGI_STDIN);
2201 reqDataPtr->outStream = NewWriter(reqDataPtr, 8192, FCGI_STDOUT);
2202 reqDataPtr->errStream = NewWriter(reqDataPtr, 512, FCGI_STDERR);
2203 reqDataPtr->nWriters = 2;
2204 *in = reqDataPtr->inStream;
2205 *out = reqDataPtr->outStream;
2206 *err = reqDataPtr->errStream;
2207 *envp = reqDataPtr->paramsPtr->vec;
2212 *----------------------------------------------------------------------
2214 * FCGX_StartFilterData --
2216 * stream is an input stream for a FCGI_FILTER request.
2217 * stream is positioned at EOF on FCGI_STDIN.
2218 * Repositions stream to the start of FCGI_DATA.
2219 * If the preconditions are not met (e.g. FCGI_STDIN has not
2220 * been read to EOF) sets the stream error code to
2221 * FCGX_CALL_SEQ_ERROR.
2224 * 0 for a normal return, < 0 for error
2226 *----------------------------------------------------------------------
2229 int FCGX_StartFilterData(FCGX_Stream *stream)
2231 FCGX_Stream_Data *data = stream->data;
2232 if(data->reqDataPtr->role != FCGI_FILTER
2233 || !stream->isReader
2234 || !stream->isClosed
2235 || data->type != FCGI_STDIN) {
2236 SetError(stream, FCGX_CALL_SEQ_ERROR);
2239 SetReaderType(reqDataPtr->inStream, FCGI_DATA);
2244 *----------------------------------------------------------------------
2246 * FCGX_SetExitStatus --
2248 * Sets the exit status for stream's request. The exit status
2249 * is the status code the request would have exited with, had
2250 * the request been run as a CGI program. You can call
2251 * SetExitStatus several times during a request; the last call
2252 * before the request ends determines the value.
2254 *----------------------------------------------------------------------
2257 void FCGX_SetExitStatus(int status, FCGX_Stream *stream)
2259 FCGX_Stream_Data *data = stream->data;
2260 data->reqDataPtr->appStatus = status;