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.28 2001/08/30 22:27:51 robs Exp $";
19 #include <fcntl.h> /* for fcntl */
21 #include <memory.h> /* for memchr() */
26 #include <sys/types.h>
28 #include "fcgi_config.h"
30 #ifdef HAVE_SYS_SOCKET_H
31 #include <sys/socket.h> /* for getpeername */
34 #ifdef HAVE_SYS_TIME_H
47 #define DLLAPI __declspec(dllexport)
56 * This is a workaround for one version of the HP C compiler
57 * (c89 on HP-UX 9.04, also Stratus FTX), which will dump core
58 * if given 'long double' for varargs.
60 #ifdef HAVE_VA_ARG_LONG_DOUBLE_BUG
61 #define LONG_DOUBLE double
63 #define LONG_DOUBLE long double
69 static int libInitialized = 0;
70 static int isFastCGI = -1;
71 static char *webServerAddressList = NULL;
72 static FCGX_Request the_request;
74 static void *Malloc(size_t size)
76 void *result = malloc(size);
77 ASSERT(size == 0 || result != NULL);
81 static char *StringCopy(char *str)
83 int strLen = strlen(str);
84 char *newString = (char *)Malloc(strLen + 1);
85 memcpy(newString, str, strLen);
86 newString[strLen] = '\000';
92 *----------------------------------------------------------------------
96 * Reads a byte from the input stream and returns it.
99 * The byte, or EOF (-1) if the end of input has been reached.
101 *----------------------------------------------------------------------
103 int FCGX_GetChar(FCGX_Stream *stream)
105 if(stream->rdNext != stream->stop)
106 return *stream->rdNext++;
107 if(stream->isClosed || !stream->isReader)
109 stream->fillBuffProc(stream);
110 stream->stopUnget = stream->rdNext;
111 if(stream->rdNext != stream->stop)
112 return *stream->rdNext++;
113 ASSERT(stream->isClosed); /* bug in fillBufProc if not */
118 *----------------------------------------------------------------------
122 * Reads up to n consecutive bytes from the input stream
123 * into the character array str. Performs no interpretation
124 * of the input bytes.
127 * Number of bytes read. If result is smaller than n,
128 * the end of input has been reached.
130 *----------------------------------------------------------------------
132 int FCGX_GetStr(char *str, int n, FCGX_Stream *stream)
140 * Fast path: n bytes are already available
142 if(n <= (stream->stop - stream->rdNext)) {
143 memcpy(str, stream->rdNext, n);
148 * General case: stream is closed or buffer fill procedure
153 if(stream->rdNext != stream->stop) {
154 m = min(n - bytesMoved, stream->stop - stream->rdNext);
155 memcpy(str, stream->rdNext, m);
162 if(stream->isClosed || !stream->isReader)
164 stream->fillBuffProc(stream);
165 stream->stopUnget = stream->rdNext;
170 *----------------------------------------------------------------------
174 * Reads up to n-1 consecutive bytes from the input stream
175 * into the character array str. Stops before n-1 bytes
176 * have been read if '\n' or EOF is read. The terminating '\n'
177 * is copied to str. After copying the last byte into str,
178 * stores a '\0' terminator.
181 * NULL if EOF is the first thing read from the input stream,
184 *----------------------------------------------------------------------
186 char *FCGX_GetLine(char *str, int n, FCGX_Stream *stream)
193 c = FCGX_GetChar(stream);
210 *----------------------------------------------------------------------
214 * Pushes back the character c onto the input stream. One
215 * character of pushback is guaranteed once a character
216 * has been read. No pushback is possible for EOF.
219 * Returns c if the pushback succeeded, EOF if not.
221 *----------------------------------------------------------------------
223 int FCGX_UnGetChar(int c, FCGX_Stream *stream) {
227 || stream->rdNext == stream->stopUnget)
230 *stream->rdNext = (unsigned char) c;
235 *----------------------------------------------------------------------
239 * Returns EOF if end-of-file has been detected while reading
240 * from stream; otherwise returns 0.
242 * Note that FCGX_HasSeenEOF(s) may return 0, yet an immediately
243 * following FCGX_GetChar(s) may return EOF. This function, like
244 * the standard C stdio function feof, does not provide the
245 * ability to peek ahead.
248 * EOF if end-of-file has been detected, 0 if not.
250 *----------------------------------------------------------------------
252 int FCGX_HasSeenEOF(FCGX_Stream *stream) {
253 return (stream->isClosed) ? EOF : 0;
257 *----------------------------------------------------------------------
261 * Writes a byte to the output stream.
264 * The byte, or EOF (-1) if an error occurred.
266 *----------------------------------------------------------------------
268 int FCGX_PutChar(int c, FCGX_Stream *stream)
270 if(stream->wrNext != stream->stop)
271 return (*stream->wrNext++ = (unsigned char) c);
272 if(stream->isClosed || stream->isReader)
274 stream->emptyBuffProc(stream, FALSE);
275 if(stream->wrNext != stream->stop)
276 return (*stream->wrNext++ = (unsigned char) c);
277 ASSERT(stream->isClosed); /* bug in emptyBuffProc if not */
282 *----------------------------------------------------------------------
286 * Writes n consecutive bytes from the character array str
287 * into the output stream. Performs no interpretation
288 * of the output bytes.
291 * Number of bytes written (n) for normal return,
292 * EOF (-1) if an error occurred.
294 *----------------------------------------------------------------------
296 int FCGX_PutStr(const char *str, int n, FCGX_Stream *stream)
301 * Fast path: room for n bytes in the buffer
303 if(n <= (stream->stop - stream->wrNext)) {
304 memcpy(stream->wrNext, str, n);
309 * General case: stream is closed or buffer empty procedure
314 if(stream->wrNext != stream->stop) {
315 m = min(n - bytesMoved, stream->stop - stream->wrNext);
316 memcpy(stream->wrNext, str, m);
323 if(stream->isClosed || stream->isReader)
325 stream->emptyBuffProc(stream, FALSE);
330 *----------------------------------------------------------------------
334 * Writes a character string to the output stream.
337 * number of bytes written for normal return,
338 * EOF (-1) if an error occurred.
340 *----------------------------------------------------------------------
342 int FCGX_PutS(const char *str, FCGX_Stream *stream)
344 return FCGX_PutStr(str, strlen(str), stream);
348 *----------------------------------------------------------------------
352 * Performs output formatting and writes the results
353 * to the output stream.
356 * number of bytes written for normal return,
357 * EOF (-1) if an error occurred.
359 *----------------------------------------------------------------------
361 int FCGX_FPrintF(FCGX_Stream *stream, const char *format, ...)
365 va_start(ap, format);
366 result = FCGX_VFPrintF(stream, format, ap);
372 *----------------------------------------------------------------------
376 * Performs output formatting and writes the results
377 * to the output stream.
380 * number of bytes written for normal return,
381 * EOF (-1) if an error occurred.
383 *----------------------------------------------------------------------
386 #define PRINTF_BUFFLEN 100
388 * More than sufficient space for all unmodified conversions
391 #define FMT_BUFFLEN 25
393 * Max size of a format specifier is 1 + 5 + 7 + 7 + 2 + 1 + slop
395 static void CopyAndAdvance(char **destPtr, char **srcPtr, int n);
397 int FCGX_VFPrintF(FCGX_Stream *stream, const char *format, va_list arg)
399 char *f, *fStop, *percentPtr, *p, *fmtBuffPtr, *buffPtr;
400 int op, performedOp, sizeModifier, buffCount = 0, buffLen, specifierLength;
401 int fastPath, n, auxBuffLen = 0, buffReqd, minWidth, precision, exp;
402 char *auxBuffPtr = NULL;
404 char fmtBuff[FMT_BUFFLEN];
405 char buff[PRINTF_BUFFLEN];
410 unsigned unsignedArg;
411 unsigned long uLongArg;
412 unsigned short uShortArg;
413 char *charPtrArg = NULL;
418 double doubleArg = 0.0;
419 LONG_DOUBLE lDoubleArg = 0.0L;
423 fStop = f + strlen(f);
425 percentPtr = (char *)memchr(f, '%', fStop - f);
426 if(percentPtr == NULL) percentPtr = fStop;
427 if(percentPtr != f) {
428 if(FCGX_PutStr(f, percentPtr - f, stream) < 0)
430 streamCount += percentPtr - f;
432 if(f == fStop) break;
436 * The following loop always executes either once or twice.
441 * Fast path: Scan optimistically, hoping that no flags,
442 * minimum field width, or precision are specified.
443 * Use the preallocated buffer, which is large enough
444 * for all fast path cases. If the conversion specifier
445 * is really more complex, run the loop a second time
446 * using the slow path.
447 * Note that fast path execution of %s bypasses the buffer
448 * and %f is not attempted on the fast path due to
449 * its large buffering requirements.
451 op = *(percentPtr + 1);
457 op = *(percentPtr + 2);
458 fmtBuff[1] = (char) sizeModifier;
459 fmtBuff[2] = (char) op;
465 fmtBuff[1] = (char) op;
471 buffLen = PRINTF_BUFFLEN;
474 * Slow path: Scan the conversion specifier and construct
475 * a new format string, compute an upper bound on the
476 * amount of buffering that sprintf will require,
477 * and allocate a larger buffer if necessary.
480 fmtBuffPtr = &fmtBuff[1];
484 n = strspn(p, "-0+ #");
487 CopyAndAdvance(&fmtBuffPtr, &p, n);
489 * Scan minimum field width
491 n = strspn(p, "0123456789");
494 minWidth = va_arg(arg, int);
495 if(abs(minWidth) > 999999)
498 * The following use of strlen rather than the
499 * value returned from sprintf is because SUNOS4
500 * returns a char * instead of an int count.
502 sprintf(fmtBuffPtr, "%d", minWidth);
503 fmtBuffPtr += strlen(fmtBuffPtr);
509 minWidth = strtol(p, NULL, 10);
510 CopyAndAdvance(&fmtBuffPtr, &p, n);
518 CopyAndAdvance(&fmtBuffPtr, &p, 1);
519 n = strspn(p, "0123456789");
522 precision = va_arg(arg, int);
523 if(precision < 0) precision = 0;
524 if(precision > 999999)
527 * The following use of strlen rather than the
528 * value returned from sprintf is because SUNOS4
529 * returns a char * instead of an int count.
531 sprintf(fmtBuffPtr, "%d", precision);
532 fmtBuffPtr += strlen(fmtBuffPtr);
538 precision = strtol(p, NULL, 10);
539 CopyAndAdvance(&fmtBuffPtr, &p, n);
547 * Scan size modifier and conversion operation
554 CopyAndAdvance(&fmtBuffPtr, &p, 1);
561 CopyAndAdvance(&fmtBuffPtr, &p, 1);
562 ASSERT(fmtBuffPtr - fmtBuff < FMT_BUFFLEN);
564 specifierLength = p - percentPtr;
566 * Bound the required buffer size. For s and f
567 * conversions this requires examining the argument.
578 buffReqd = max(precision, 46);
581 charPtrArg = va_arg(arg, char *);
582 if (!charPtrArg) charPtrArg = "(null)";
583 if(precision == -1) {
584 buffReqd = strlen(charPtrArg);
586 p = (char *)memchr(charPtrArg, '\0', precision);
588 (p == NULL) ? precision : p - charPtrArg;
592 switch(sizeModifier) {
594 doubleArg = va_arg(arg, double);
595 frexp(doubleArg, &exp);
598 lDoubleArg = va_arg(arg, LONG_DOUBLE);
599 /* XXX Need to check for the presence of
600 * frexpl() and use it if available */
601 frexp((double) lDoubleArg, &exp);
606 if(precision == -1) precision = 6;
607 buffReqd = precision + 3 + ((exp > 0) ? exp/3 : 0);
613 if(precision == -1) precision = 6;
614 buffReqd = precision + 8;
622 buffReqd = max(buffReqd + 10, minWidth);
624 * Allocate the buffer
626 if(buffReqd <= PRINTF_BUFFLEN) {
628 buffLen = PRINTF_BUFFLEN;
630 if(auxBuffPtr == NULL || buffReqd > auxBuffLen) {
631 if(auxBuffPtr != NULL) free(auxBuffPtr);
632 auxBuffPtr = (char *)Malloc(buffReqd);
633 auxBuffLen = buffReqd;
634 if(auxBuffPtr == NULL)
637 buffPtr = auxBuffPtr;
638 buffLen = auxBuffLen;
642 * This giant switch statement requires the following variables
643 * to be set up: op, sizeModifier, arg, buffPtr, fmtBuff.
644 * When fastPath == FALSE and op == 's' or 'f', the argument
645 * has been read into charPtrArg, doubleArg, or lDoubleArg.
646 * The statement produces the boolean performedOp, TRUE iff
647 * the op/sizeModifier were executed and argument consumed;
648 * if performedOp, the characters written into buffPtr[]
649 * and the character count buffCount (== EOF meaning error).
651 * The switch cases are arranged in the same order as in the
652 * description of fprintf in section 15.11 of Harbison and Steele.
658 switch(sizeModifier) {
660 intArg = va_arg(arg, int);
661 sprintf(buffPtr, fmtBuff, intArg);
662 buffCount = strlen(buffPtr);
665 longArg = va_arg(arg, long);
666 sprintf(buffPtr, fmtBuff, longArg);
667 buffCount = strlen(buffPtr);
670 shortArg = (short) va_arg(arg, int);
671 sprintf(buffPtr, fmtBuff, shortArg);
672 buffCount = strlen(buffPtr);
682 switch(sizeModifier) {
684 unsignedArg = va_arg(arg, unsigned);
685 sprintf(buffPtr, fmtBuff, unsignedArg);
686 buffCount = strlen(buffPtr);
689 uLongArg = va_arg(arg, unsigned long);
690 sprintf(buffPtr, fmtBuff, uLongArg);
691 buffCount = strlen(buffPtr);
694 uShortArg = (unsigned short) va_arg(arg, int);
695 sprintf(buffPtr, fmtBuff, uShortArg);
696 buffCount = strlen(buffPtr);
703 switch(sizeModifier) {
705 intArg = va_arg(arg, int);
706 sprintf(buffPtr, fmtBuff, intArg);
707 buffCount = strlen(buffPtr);
711 * XXX: Allowed by ISO C Amendment 1, but
712 * many platforms don't yet support wint_t
720 switch(sizeModifier) {
723 buffPtr = va_arg(arg, char *);
724 buffCount = strlen(buffPtr);
725 buffLen = buffCount + 1;
727 sprintf(buffPtr, fmtBuff, charPtrArg);
728 buffCount = strlen(buffPtr);
733 * XXX: Don't know how to convert a sequence
734 * of wide characters into a byte stream, or
735 * even how to predict the buffering required.
743 if(sizeModifier != ' ')
745 voidPtrArg = va_arg(arg, void *);
746 sprintf(buffPtr, fmtBuff, voidPtrArg);
747 buffCount = strlen(buffPtr);
750 switch(sizeModifier) {
752 intPtrArg = va_arg(arg, int *);
753 *intPtrArg = streamCount;
756 longPtrArg = va_arg(arg, long *);
757 *longPtrArg = streamCount;
760 shortPtrArg = (short *) va_arg(arg, short *);
761 *shortPtrArg = (short) streamCount;
773 switch(sizeModifier) {
775 sprintf(buffPtr, fmtBuff, doubleArg);
776 buffCount = strlen(buffPtr);
779 sprintf(buffPtr, fmtBuff, lDoubleArg);
780 buffCount = strlen(buffPtr);
790 switch(sizeModifier) {
792 doubleArg = va_arg(arg, double);
793 sprintf(buffPtr, fmtBuff, doubleArg);
794 buffCount = strlen(buffPtr);
797 lDoubleArg = va_arg(arg, LONG_DOUBLE);
798 sprintf(buffPtr, fmtBuff, lDoubleArg);
799 buffCount = strlen(buffPtr);
806 if(sizeModifier != ' ')
817 if(performedOp) break;
822 ASSERT(buffCount < buffLen);
824 if(FCGX_PutStr(buffPtr, buffCount, stream) < 0)
826 streamCount += buffCount;
827 } else if(buffCount < 0) {
830 f += specifierLength;
831 } /* while(f != fStop) */
836 if(auxBuffPtr != NULL) free(auxBuffPtr);
841 * Copy n characters from *srcPtr to *destPtr, then increment
842 * both *srcPtr and *destPtr by n.
844 static void CopyAndAdvance(char **destPtr, char **srcPtr, int n)
846 char *dest = *destPtr;
849 for (i = 0; i < n; i++)
856 *----------------------------------------------------------------------
860 * Flushes any buffered output.
862 * Server-push is a legitimate application of FCGX_FFlush.
863 * Otherwise, FCGX_FFlush is not very useful, since FCGX_Accept
864 * does it implicitly. FCGX_FFlush may reduce performance
865 * by increasing the total number of operating system calls
866 * the application makes.
869 * EOF (-1) if an error occurred.
871 *----------------------------------------------------------------------
873 int FCGX_FFlush(FCGX_Stream *stream)
875 if(stream->isClosed || stream->isReader)
877 stream->emptyBuffProc(stream, FALSE);
878 return (stream->isClosed) ? -1 : 0;
882 *----------------------------------------------------------------------
886 * Performs FCGX_FFlush and closes the stream.
888 * This is not a very useful operation, since FCGX_Accept
889 * does it implicitly. Closing the out stream before the
890 * err stream results in an extra write if there's nothing
891 * in the err stream, and therefore reduces performance.
894 * EOF (-1) if an error occurred.
896 *----------------------------------------------------------------------
898 int FCGX_FClose(FCGX_Stream *stream)
900 if (stream == NULL) return 0;
902 if(!stream->wasFCloseCalled) {
903 if(!stream->isReader) {
904 stream->emptyBuffProc(stream, TRUE);
906 stream->wasFCloseCalled = TRUE;
907 stream->isClosed = TRUE;
908 if(stream->isReader) {
909 stream->wrNext = stream->stop = stream->rdNext;
911 stream->rdNext = stream->stop = stream->wrNext;
914 return (stream->FCGI_errno == 0) ? 0 : EOF;
918 *----------------------------------------------------------------------
922 * An error has occurred; save the error code in the stream
923 * for diagnostic purposes and set the stream state so that
924 * reads return EOF and writes have no effect.
926 *----------------------------------------------------------------------
928 static void SetError(FCGX_Stream *stream, int FCGI_errno)
931 * Preserve only the first error.
933 if(stream->FCGI_errno == 0) {
934 stream->FCGI_errno = FCGI_errno;
935 stream->isClosed = TRUE;
940 *----------------------------------------------------------------------
944 * Return the stream error code. 0 means no error, > 0
945 * is an errno(2) error, < 0 is an FCGX_errno error.
947 *----------------------------------------------------------------------
949 int FCGX_GetError(FCGX_Stream *stream) {
950 return stream->FCGI_errno;
954 *----------------------------------------------------------------------
958 * Clear the stream error code and end-of-file indication.
960 *----------------------------------------------------------------------
962 void FCGX_ClearError(FCGX_Stream *stream) {
963 stream->FCGI_errno = 0;
965 * stream->isClosed = FALSE;
966 * XXX: should clear isClosed but work is needed to make it safe
967 * to do so. For example, if an application calls FClose, gets
968 * an I/O error on the write, calls ClearError and retries
969 * the FClose, FClose (really EmptyBuffProc) will write a second
970 * EOF record. If an application calls PutChar instead of FClose
971 * after the ClearError, the application will write more data.
972 * The stream's state must discriminate between various states
973 * of the stream that are now all lumped under isClosed.
978 *======================================================================
980 *======================================================================
984 * A vector of pointers representing the parameters received
985 * by a FastCGI application server, with the vector's length
986 * and last valid element so adding new parameters is efficient.
989 typedef struct Params {
990 FCGX_ParamArray vec; /* vector of strings */
991 int length; /* number of string vec can hold */
992 char **cur; /* current item in vec; *cur == NULL */
994 typedef Params *ParamsPtr;
997 *----------------------------------------------------------------------
1001 * Creates a new Params structure.
1004 * Pointer to the new structure.
1006 *----------------------------------------------------------------------
1008 static ParamsPtr NewParams(int length)
1011 result = (Params *)Malloc(sizeof(Params));
1012 result->vec = (char **)Malloc(length * sizeof(char *));
1013 result->length = length;
1014 result->cur = result->vec;
1015 *result->cur = NULL;
1020 *----------------------------------------------------------------------
1024 * Frees a Params structure and all the parameters it contains.
1027 * env becomes invalid.
1029 *----------------------------------------------------------------------
1031 static void FreeParams(ParamsPtr *paramsPtrPtr)
1033 ParamsPtr paramsPtr = *paramsPtrPtr;
1035 if(paramsPtr == NULL) {
1038 for (p = paramsPtr->vec; p < paramsPtr->cur; p++) {
1041 free(paramsPtr->vec);
1043 *paramsPtrPtr = NULL;
1047 *----------------------------------------------------------------------
1051 * Add a name/value pair to a Params structure.
1057 * Parameters structure updated.
1059 *----------------------------------------------------------------------
1061 static void PutParam(ParamsPtr paramsPtr, char *nameValue)
1065 *paramsPtr->cur++ = nameValue;
1066 size = paramsPtr->cur - paramsPtr->vec;
1067 if(size >= paramsPtr->length) {
1068 paramsPtr->length *= 2;
1069 paramsPtr->vec = (FCGX_ParamArray)realloc(paramsPtr->vec, paramsPtr->length * sizeof(char *));
1070 paramsPtr->cur = paramsPtr->vec + size;
1072 *paramsPtr->cur = NULL;
1076 *----------------------------------------------------------------------
1078 * FCGX_GetParam -- obtain value of FCGI parameter in environment
1082 * Value bound to name, NULL if name not present in the
1083 * environment envp. Caller must not mutate the result
1084 * or retain it past the end of this request.
1086 *----------------------------------------------------------------------
1088 char *FCGX_GetParam(const char *name, FCGX_ParamArray envp)
1093 if (name == NULL || envp == NULL) return NULL;
1097 for (p = envp; *p; ++p) {
1098 if((strncmp(name, *p, len) == 0) && ((*p)[len] == '=')) {
1106 *----------------------------------------------------------------------
1108 * Start of FastCGI-specific code
1110 *----------------------------------------------------------------------
1114 *----------------------------------------------------------------------
1118 * Reads FastCGI name-value pairs from stream until EOF. Converts
1119 * each pair to name=value format and adds it to Params structure.
1121 *----------------------------------------------------------------------
1123 static int ReadParams(Params *paramsPtr, FCGX_Stream *stream)
1125 int nameLen, valueLen;
1126 unsigned char lenBuff[3];
1129 while((nameLen = FCGX_GetChar(stream)) != EOF) {
1131 * Read name length (one or four bytes) and value length
1132 * (one or four bytes) from stream.
1134 if((nameLen & 0x80) != 0) {
1135 if(FCGX_GetStr((char *) &lenBuff[0], 3, stream) != 3) {
1136 SetError(stream, FCGX_PARAMS_ERROR);
1139 nameLen = ((nameLen & 0x7f) << 24) + (lenBuff[0] << 16)
1140 + (lenBuff[1] << 8) + lenBuff[2];
1142 if((valueLen = FCGX_GetChar(stream)) == EOF) {
1143 SetError(stream, FCGX_PARAMS_ERROR);
1146 if((valueLen & 0x80) != 0) {
1147 if(FCGX_GetStr((char *) &lenBuff[0], 3, stream) != 3) {
1148 SetError(stream, FCGX_PARAMS_ERROR);
1151 valueLen = ((valueLen & 0x7f) << 24) + (lenBuff[0] << 16)
1152 + (lenBuff[1] << 8) + lenBuff[2];
1155 * nameLen and valueLen are now valid; read the name and value
1156 * from stream and construct a standard environment entry.
1158 nameValue = (char *)Malloc(nameLen + valueLen + 2);
1159 if(FCGX_GetStr(nameValue, nameLen, stream) != nameLen) {
1160 SetError(stream, FCGX_PARAMS_ERROR);
1164 *(nameValue + nameLen) = '=';
1165 if(FCGX_GetStr(nameValue + nameLen + 1, valueLen, stream)
1167 SetError(stream, FCGX_PARAMS_ERROR);
1171 *(nameValue + nameLen + valueLen + 1) = '\0';
1172 PutParam(paramsPtr, nameValue);
1178 *----------------------------------------------------------------------
1182 * Constructs an FCGI_Header struct.
1184 *----------------------------------------------------------------------
1186 static FCGI_Header MakeHeader(
1193 ASSERT(contentLength >= 0 && contentLength <= FCGI_MAX_LENGTH);
1194 ASSERT(paddingLength >= 0 && paddingLength <= 0xff);
1195 header.version = FCGI_VERSION_1;
1196 header.type = (unsigned char) type;
1197 header.requestIdB1 = (unsigned char) ((requestId >> 8) & 0xff);
1198 header.requestIdB0 = (unsigned char) ((requestId ) & 0xff);
1199 header.contentLengthB1 = (unsigned char) ((contentLength >> 8) & 0xff);
1200 header.contentLengthB0 = (unsigned char) ((contentLength ) & 0xff);
1201 header.paddingLength = (unsigned char) paddingLength;
1202 header.reserved = 0;
1207 *----------------------------------------------------------------------
1209 * MakeEndRequestBody --
1211 * Constructs an FCGI_EndRequestBody struct.
1213 *----------------------------------------------------------------------
1215 static FCGI_EndRequestBody MakeEndRequestBody(
1219 FCGI_EndRequestBody body;
1220 body.appStatusB3 = (unsigned char) ((appStatus >> 24) & 0xff);
1221 body.appStatusB2 = (unsigned char) ((appStatus >> 16) & 0xff);
1222 body.appStatusB1 = (unsigned char) ((appStatus >> 8) & 0xff);
1223 body.appStatusB0 = (unsigned char) ((appStatus ) & 0xff);
1224 body.protocolStatus = (unsigned char) protocolStatus;
1225 memset(body.reserved, 0, sizeof(body.reserved));
1230 *----------------------------------------------------------------------
1232 * MakeUnknownTypeBody --
1234 * Constructs an FCGI_MakeUnknownTypeBody struct.
1236 *----------------------------------------------------------------------
1238 static FCGI_UnknownTypeBody MakeUnknownTypeBody(
1241 FCGI_UnknownTypeBody body;
1242 body.type = (unsigned char) type;
1243 memset(body.reserved, 0, sizeof(body.reserved));
1248 *----------------------------------------------------------------------
1252 * Returns the smallest integer greater than or equal to n
1253 * that's a multiple of 8.
1255 *----------------------------------------------------------------------
1257 static int AlignInt8(unsigned n) {
1258 return (n + 7) & (UINT_MAX - 7);
1262 *----------------------------------------------------------------------
1266 * Returns the smallest pointer greater than or equal to p
1267 * that's a multiple of 8.
1269 *----------------------------------------------------------------------
1271 static unsigned char *AlignPtr8(unsigned char *p) {
1272 unsigned long u = (unsigned long) p;
1273 u = ((u + 7) & (ULONG_MAX - 7)) - u;
1279 * State associated with a stream
1281 typedef struct FCGX_Stream_Data {
1282 unsigned char *buff; /* buffer after alignment */
1283 int bufflen; /* number of bytes buff can store */
1284 unsigned char *mBuff; /* buffer as returned by Malloc */
1285 unsigned char *buffStop; /* reader: last valid byte + 1 of entire buffer.
1286 * stop generally differs from buffStop for
1287 * readers because of record structure.
1288 * writer: buff + bufflen */
1289 int type; /* reader: FCGI_PARAMS or FCGI_STDIN
1290 * writer: FCGI_STDOUT or FCGI_STDERR */
1291 int eorStop; /* reader: stop stream at end-of-record */
1292 int skip; /* reader: don't deliver content bytes */
1293 int contentLen; /* reader: bytes of unread content */
1294 int paddingLen; /* reader: bytes of unread padding */
1295 int isAnythingWritten; /* writer: data has been written to ipcFd */
1296 int rawWrite; /* writer: write data without stream headers */
1297 FCGX_Request *reqDataPtr; /* request data not specific to one stream */
1301 *----------------------------------------------------------------------
1303 * WriteCloseRecords --
1305 * Writes an EOF record for the stream content if necessary.
1306 * If this is the last writer to close, writes an FCGI_END_REQUEST
1309 *----------------------------------------------------------------------
1311 static void WriteCloseRecords(struct FCGX_Stream *stream)
1313 FCGX_Stream_Data *data = (FCGX_Stream_Data *)stream->data;
1315 * Enter rawWrite mode so final records won't be encapsulated as
1318 data->rawWrite = TRUE;
1320 * Generate EOF for stream content if needed.
1322 if(!(data->type == FCGI_STDERR
1323 && stream->wrNext == data->buff
1324 && !data->isAnythingWritten)) {
1326 header = MakeHeader(data->type, data->reqDataPtr->requestId, 0, 0);
1327 FCGX_PutStr((char *) &header, sizeof(header), stream);
1330 * Generate FCGI_END_REQUEST record if needed.
1332 if(data->reqDataPtr->nWriters == 1) {
1333 FCGI_EndRequestRecord endRequestRecord;
1334 endRequestRecord.header = MakeHeader(FCGI_END_REQUEST,
1335 data->reqDataPtr->requestId,
1336 sizeof(endRequestRecord.body), 0);
1337 endRequestRecord.body = MakeEndRequestBody(
1338 data->reqDataPtr->appStatus, FCGI_REQUEST_COMPLETE);
1339 FCGX_PutStr((char *) &endRequestRecord,
1340 sizeof(endRequestRecord), stream);
1342 data->reqDataPtr->nWriters--;
1347 static int write_it_all(int fd, char *buf, int len)
1352 wrote = OS_Write(fd, buf, len);
1362 *----------------------------------------------------------------------
1366 * Encapsulates any buffered stream content in a FastCGI
1367 * record. Writes the data, making the buffer empty.
1369 *----------------------------------------------------------------------
1371 static void EmptyBuffProc(struct FCGX_Stream *stream, int doClose)
1373 FCGX_Stream_Data *data = (FCGX_Stream_Data *)stream->data;
1376 * If the buffer contains stream data, fill in the header.
1377 * Pad the record to a multiple of 8 bytes in length. Padding
1378 * can't overflow the buffer because the buffer is a multiple
1379 * of 8 bytes in length. If the buffer contains no stream
1380 * data, reclaim the space reserved for the header.
1382 if(!data->rawWrite) {
1383 cLen = stream->wrNext - data->buff - sizeof(FCGI_Header);
1385 eLen = AlignInt8(cLen);
1387 * Giving the padding a well-defined value keeps Purify happy.
1389 memset(stream->wrNext, 0, eLen - cLen);
1390 stream->wrNext += eLen - cLen;
1391 *((FCGI_Header *) data->buff)
1392 = MakeHeader(data->type,
1393 data->reqDataPtr->requestId, cLen, eLen - cLen);
1395 stream->wrNext = data->buff;
1399 WriteCloseRecords(stream);
1401 if (stream->wrNext != data->buff) {
1402 data->isAnythingWritten = TRUE;
1403 if (write_it_all(data->reqDataPtr->ipcFd, (char *)data->buff, stream->wrNext - data->buff) < 0) {
1404 SetError(stream, OS_Errno);
1407 stream->wrNext = data->buff;
1410 * The buffer is empty.
1412 if(!data->rawWrite) {
1413 stream->wrNext += sizeof(FCGI_Header);
1418 * Return codes for Process* functions
1420 #define STREAM_RECORD 0
1422 #define BEGIN_RECORD 2
1423 #define MGMT_RECORD 3
1426 *----------------------------------------------------------------------
1428 * ProcessManagementRecord --
1430 * Reads and responds to a management record. The only type of
1431 * management record this library understands is FCGI_GET_VALUES.
1432 * The only variables that this library's FCGI_GET_VALUES
1433 * understands are FCGI_MAX_CONNS, FCGI_MAX_REQS, and FCGI_MPXS_CONNS.
1434 * Ignore other FCGI_GET_VALUES variables; respond to other
1435 * management records with a FCGI_UNKNOWN_TYPE record.
1437 *----------------------------------------------------------------------
1439 static int ProcessManagementRecord(int type, FCGX_Stream *stream)
1441 FCGX_Stream_Data *data = (FCGX_Stream_Data *)stream->data;
1442 ParamsPtr paramsPtr = NewParams(3);
1444 char response[64]; /* 64 = 8 + 3*(1+1+14+1)* + padding */
1445 char *responseP = &response[FCGI_HEADER_LEN];
1446 char *name, value = '\0';
1448 if(type == FCGI_GET_VALUES) {
1449 ReadParams(paramsPtr, stream);
1450 if((FCGX_GetError(stream) != 0) || (data->contentLen != 0)) {
1451 FreeParams(¶msPtr);
1452 return FCGX_PROTOCOL_ERROR;
1454 for (pPtr = paramsPtr->vec; pPtr < paramsPtr->cur; pPtr++) {
1456 *(strchr(name, '=')) = '\0';
1457 if(strcmp(name, FCGI_MAX_CONNS) == 0) {
1459 } else if(strcmp(name, FCGI_MAX_REQS) == 0) {
1461 } else if(strcmp(name, FCGI_MPXS_CONNS) == 0) {
1468 sprintf(responseP, "%c%c%s%c", len, 1, name, value);
1469 responseP += len + 3;
1472 len = responseP - &response[FCGI_HEADER_LEN];
1473 paddedLen = AlignInt8(len);
1474 *((FCGI_Header *) response)
1475 = MakeHeader(FCGI_GET_VALUES_RESULT, FCGI_NULL_REQUEST_ID,
1476 len, paddedLen - len);
1477 FreeParams(¶msPtr);
1479 paddedLen = len = sizeof(FCGI_UnknownTypeBody);
1480 ((FCGI_UnknownTypeRecord *) response)->header
1481 = MakeHeader(FCGI_UNKNOWN_TYPE, FCGI_NULL_REQUEST_ID,
1483 ((FCGI_UnknownTypeRecord *) response)->body
1484 = MakeUnknownTypeBody(type);
1486 if (write_it_all(data->reqDataPtr->ipcFd, response, FCGI_HEADER_LEN + paddedLen) < 0) {
1487 SetError(stream, OS_Errno);
1495 *----------------------------------------------------------------------
1497 * ProcessBeginRecord --
1499 * Reads an FCGI_BEGIN_REQUEST record.
1502 * BEGIN_RECORD for normal return. FCGX_PROTOCOL_ERROR for
1503 * protocol error. SKIP for attempt to multiplex
1504 * connection. -1 for error from write (errno in stream).
1507 * In case of BEGIN_RECORD return, stores requestId, role,
1508 * keepConnection values, and sets isBeginProcessed = TRUE.
1510 *----------------------------------------------------------------------
1512 static int ProcessBeginRecord(int requestId, FCGX_Stream *stream)
1514 FCGX_Stream_Data *data = (FCGX_Stream_Data *)stream->data;
1515 FCGI_BeginRequestBody body;
1516 if(requestId == 0 || data->contentLen != sizeof(body)) {
1517 return FCGX_PROTOCOL_ERROR;
1519 if(data->reqDataPtr->isBeginProcessed) {
1521 * The Web server is multiplexing the connection. This library
1522 * doesn't know how to handle multiplexing, so respond with
1523 * FCGI_END_REQUEST{protocolStatus = FCGI_CANT_MPX_CONN}
1525 FCGI_EndRequestRecord endRequestRecord;
1526 endRequestRecord.header = MakeHeader(FCGI_END_REQUEST,
1527 requestId, sizeof(endRequestRecord.body), 0);
1528 endRequestRecord.body
1529 = MakeEndRequestBody(0, FCGI_CANT_MPX_CONN);
1530 if (write_it_all(data->reqDataPtr->ipcFd, (char *)&endRequestRecord, sizeof(endRequestRecord)) < 0) {
1531 SetError(stream, OS_Errno);
1538 * Accept this new request. Read the record body.
1540 data->reqDataPtr->requestId = requestId;
1541 if(FCGX_GetStr((char *) &body, sizeof(body), stream)
1543 return FCGX_PROTOCOL_ERROR;
1545 data->reqDataPtr->keepConnection = (body.flags & FCGI_KEEP_CONN);
1546 data->reqDataPtr->role = (body.roleB1 << 8) + body.roleB0;
1547 data->reqDataPtr->isBeginProcessed = TRUE;
1548 return BEGIN_RECORD;
1552 *----------------------------------------------------------------------
1556 * Interprets FCGI_Header. Processes FCGI_BEGIN_REQUEST and
1557 * management records here; extracts information from stream
1558 * records (FCGI_PARAMS, FCGI_STDIN) into stream.
1561 * >= 0 for a normal return, < 0 for error
1564 * XXX: Many (more than there used to be).
1565 * If !stream->isRequestIdSet, ProcessHeader initializes
1566 * stream->requestId from header and sets stream->isRequestIdSet
1567 * to TRUE. ProcessHeader also sets stream->contentLen to header's
1568 * contentLength, and sets stream->paddingLen to the header's
1571 *----------------------------------------------------------------------
1573 static int ProcessHeader(FCGI_Header header, FCGX_Stream *stream)
1575 FCGX_Stream_Data *data = (FCGX_Stream_Data *)stream->data;
1577 if(header.version != FCGI_VERSION_1) {
1578 return FCGX_UNSUPPORTED_VERSION;
1580 requestId = (header.requestIdB1 << 8)
1581 + header.requestIdB0;
1582 data->contentLen = (header.contentLengthB1 << 8)
1583 + header.contentLengthB0;
1584 data->paddingLen = header.paddingLength;
1585 if(header.type == FCGI_BEGIN_REQUEST) {
1586 return ProcessBeginRecord(requestId, stream);
1588 if(requestId == FCGI_NULL_REQUEST_ID) {
1589 return ProcessManagementRecord(header.type, stream);
1591 if(requestId != data->reqDataPtr->requestId) {
1594 if(header.type != data->type) {
1595 return FCGX_PROTOCOL_ERROR;
1597 return STREAM_RECORD;
1601 *----------------------------------------------------------------------
1605 * Reads bytes from the ipcFd, supplies bytes to a stream client.
1607 *----------------------------------------------------------------------
1609 static void FillBuffProc(FCGX_Stream *stream)
1611 FCGX_Stream_Data *data = (FCGX_Stream_Data *)stream->data;
1618 * If data->buff is empty, do a read.
1620 if(stream->rdNext == data->buffStop) {
1621 count = OS_Read(data->reqDataPtr->ipcFd, (char *)data->buff,
1624 SetError(stream, (count == 0 ? FCGX_PROTOCOL_ERROR : OS_Errno));
1627 stream->rdNext = data->buff;
1628 data->buffStop = data->buff + count;
1631 * Now data->buff is not empty. If the current record contains
1632 * more content bytes, deliver all that are present in data->buff.
1634 if(data->contentLen > 0) {
1635 count = min(data->contentLen, data->buffStop - stream->rdNext);
1636 data->contentLen -= count;
1638 stream->wrNext = stream->stop = stream->rdNext + count;
1641 stream->rdNext += count;
1642 if(data->contentLen > 0) {
1650 * If the current record (whose content has been fully consumed by
1651 * the client) was padded, skip over the padding bytes.
1653 if(data->paddingLen > 0) {
1654 count = min(data->paddingLen, data->buffStop - stream->rdNext);
1655 data->paddingLen -= count;
1656 stream->rdNext += count;
1657 if(data->paddingLen > 0) {
1662 * All done with the current record, including the padding.
1663 * If we're in a recursive call from ProcessHeader, deliver EOF.
1666 stream->stop = stream->rdNext;
1667 stream->isClosed = TRUE;
1671 * Fill header with bytes from the input buffer.
1673 count = min((int)sizeof(header) - headerLen,
1674 data->buffStop - stream->rdNext);
1675 memcpy(((char *)(&header)) + headerLen, stream->rdNext, count);
1677 stream->rdNext += count;
1678 if(headerLen < sizeof(header)) {
1683 * Interpret header. eorStop prevents ProcessHeader from reading
1684 * past the end-of-record when using stream to read content.
1686 data->eorStop = TRUE;
1687 stream->stop = stream->rdNext;
1688 status = ProcessHeader(header, stream);
1689 data->eorStop = FALSE;
1690 stream->isClosed = FALSE;
1694 * If this stream record header marked the end of stream
1695 * data deliver EOF to the stream client, otherwise loop
1698 * XXX: If this is final stream and
1699 * stream->rdNext != data->buffStop, buffered
1700 * data is next request (server pipelining)?
1702 if(data->contentLen == 0) {
1703 stream->wrNext = stream->stop = stream->rdNext;
1704 stream->isClosed = TRUE;
1713 * If this header marked the beginning of a new
1714 * request, return role information to caller.
1722 SetError(stream, status);
1730 *----------------------------------------------------------------------
1734 * Creates a stream to read or write from an open ipcFd.
1735 * The stream performs reads/writes of up to bufflen bytes.
1737 *----------------------------------------------------------------------
1739 static FCGX_Stream *NewStream(
1740 FCGX_Request *reqDataPtr, int bufflen, int isReader, int streamType)
1743 * XXX: It would be a lot cleaner to have a NewStream that only
1744 * knows about the type FCGX_Stream, with all other
1745 * necessary data passed in. It appears that not just
1746 * data and the two procs are needed for initializing stream,
1747 * but also data->buff and data->buffStop. This has implications
1748 * for procs that want to swap buffers, too.
1750 FCGX_Stream *stream = (FCGX_Stream *)Malloc(sizeof(FCGX_Stream));
1751 FCGX_Stream_Data *data = (FCGX_Stream_Data *)Malloc(sizeof(FCGX_Stream_Data));
1752 data->reqDataPtr = reqDataPtr;
1753 bufflen = AlignInt8(min(max(bufflen, 32), FCGI_MAX_LENGTH + 1));
1754 data->bufflen = bufflen;
1755 data->mBuff = (unsigned char *)Malloc(bufflen);
1756 data->buff = AlignPtr8(data->mBuff);
1757 if(data->buff != data->mBuff) {
1761 data->buffStop = data->buff;
1763 data->buffStop = data->buff + data->bufflen;
1765 data->type = streamType;
1766 data->eorStop = FALSE;
1768 data->contentLen = 0;
1769 data->paddingLen = 0;
1770 data->isAnythingWritten = FALSE;
1771 data->rawWrite = FALSE;
1773 stream->data = data;
1774 stream->isReader = isReader;
1775 stream->isClosed = FALSE;
1776 stream->wasFCloseCalled = FALSE;
1777 stream->FCGI_errno = 0;
1779 stream->fillBuffProc = FillBuffProc;
1780 stream->emptyBuffProc = NULL;
1781 stream->rdNext = data->buff;
1782 stream->stop = stream->rdNext;
1783 stream->stopUnget = data->buff;
1784 stream->wrNext = stream->stop;
1786 stream->fillBuffProc = NULL;
1787 stream->emptyBuffProc = EmptyBuffProc;
1788 stream->wrNext = data->buff + sizeof(FCGI_Header);
1789 stream->stop = data->buffStop;
1790 stream->stopUnget = NULL;
1791 stream->rdNext = stream->stop;
1797 *----------------------------------------------------------------------
1799 * FCGX_FreeStream --
1801 * Frees all storage allocated when *streamPtr was created,
1802 * and nulls out *streamPtr.
1804 *----------------------------------------------------------------------
1806 void FCGX_FreeStream(FCGX_Stream **streamPtr)
1808 FCGX_Stream *stream = *streamPtr;
1809 FCGX_Stream_Data *data;
1810 if(stream == NULL) {
1813 data = (FCGX_Stream_Data *)stream->data;
1814 data->reqDataPtr = NULL;
1822 *----------------------------------------------------------------------
1826 * Re-initializes the stream to read data of the specified type.
1828 *----------------------------------------------------------------------
1830 static FCGX_Stream *SetReaderType(FCGX_Stream *stream, int streamType)
1832 FCGX_Stream_Data *data = (FCGX_Stream_Data *)stream->data;
1833 ASSERT(stream->isReader);
1834 data->type = streamType;
1835 data->eorStop = FALSE;
1837 data->contentLen = 0;
1838 data->paddingLen = 0;
1839 stream->wrNext = stream->stop = stream->rdNext;
1840 stream->isClosed = FALSE;
1845 *----------------------------------------------------------------------
1849 * Creates a stream to read streamType records for the given
1850 * request. The stream performs OS reads of up to bufflen bytes.
1852 *----------------------------------------------------------------------
1854 static FCGX_Stream *NewReader(FCGX_Request *reqDataPtr, int bufflen, int streamType)
1856 return NewStream(reqDataPtr, bufflen, TRUE, streamType);
1860 *----------------------------------------------------------------------
1864 * Creates a stream to write streamType FastCGI records, using
1865 * the ipcFd and RequestId contained in *reqDataPtr.
1866 * The stream performs OS writes of up to bufflen bytes.
1868 *----------------------------------------------------------------------
1870 static FCGX_Stream *NewWriter(FCGX_Request *reqDataPtr, int bufflen, int streamType)
1872 return NewStream(reqDataPtr, bufflen, FALSE, streamType);
1876 *----------------------------------------------------------------------
1878 * FCGX_CreateWriter --
1880 * Creates a stream to write streamType FastCGI records, using
1881 * the given ipcFd and request Id. This function is provided
1882 * for use by cgi-fcgi. In order to be defensive against misuse,
1883 * this function leaks a little storage; cgi-fcgi doesn't care.
1885 *----------------------------------------------------------------------
1887 FCGX_Stream *FCGX_CreateWriter(
1893 FCGX_Request *reqDataPtr = (FCGX_Request *)Malloc(sizeof(FCGX_Request));
1894 reqDataPtr->ipcFd = ipcFd;
1895 reqDataPtr->requestId = requestId;
1897 * Suppress writing an FCGI_END_REQUEST record.
1899 reqDataPtr->nWriters = 2;
1900 return NewWriter(reqDataPtr, bufflen, streamType);
1904 *======================================================================
1906 *======================================================================
1910 *----------------------------------------------------------------------
1914 * This routine determines if the process is running as a CGI or
1915 * FastCGI process. The distinction is made by determining whether
1916 * FCGI_LISTENSOCK_FILENO is a listener ipcFd or the end of a
1917 * pipe (ie. standard in).
1920 * TRUE if the process is a CGI process, FALSE if FastCGI.
1922 *----------------------------------------------------------------------
1924 int FCGX_IsCGI(void)
1926 if (isFastCGI != -1) {
1930 if (!libInitialized) {
1931 int rc = FCGX_Init();
1933 /* exit() isn't great, but hey */
1934 exit((rc < 0) ? rc : -rc);
1938 isFastCGI = OS_IsFcgi(FCGI_LISTENSOCK_FILENO);
1944 *----------------------------------------------------------------------
1948 * Finishes the current request from the HTTP server.
1952 * Finishes the request accepted by (and frees any
1953 * storage allocated by) the previous call to FCGX_Accept.
1955 * DO NOT retain pointers to the envp array or any strings
1956 * contained in it (e.g. to the result of calling FCGX_GetParam),
1957 * since these will be freed by the next call to FCGX_Finish
1960 *----------------------------------------------------------------------
1963 void FCGX_Finish(void)
1965 FCGX_Finish_r(&the_request);
1969 *----------------------------------------------------------------------
1973 * Finishes the current request from the HTTP server.
1977 * Finishes the request accepted by (and frees any
1978 * storage allocated by) the previous call to FCGX_Accept.
1980 * DO NOT retain pointers to the envp array or any strings
1981 * contained in it (e.g. to the result of calling FCGX_GetParam),
1982 * since these will be freed by the next call to FCGX_Finish
1985 *----------------------------------------------------------------------
1987 void FCGX_Finish_r(FCGX_Request *reqDataPtr)
1991 if (reqDataPtr == NULL) {
1995 close = !reqDataPtr->keepConnection;
1997 /* This should probably use a 'status' member instead of 'in' */
1998 if (reqDataPtr->in) {
1999 close |= FCGX_FClose(reqDataPtr->err);
2000 close |= FCGX_FClose(reqDataPtr->out);
2002 close |= FCGX_GetError(reqDataPtr->in);
2005 FCGX_Free(reqDataPtr, close);
2008 void FCGX_Free(FCGX_Request * request, int close)
2010 if (request == NULL)
2013 FCGX_FreeStream(&request->in);
2014 FCGX_FreeStream(&request->out);
2015 FCGX_FreeStream(&request->err);
2016 FreeParams(&request->paramsPtr);
2019 OS_IpcClose(request->ipcFd);
2020 request->ipcFd = -1;
2024 int FCGX_OpenSocket(const char *path, int backlog)
2026 int rc = OS_CreateLocalIpcFd(path, backlog);
2027 if (rc == FCGI_LISTENSOCK_FILENO && isFastCGI == 0) {
2028 /* XXX probably need to call OS_LibInit() again for Win */
2034 int FCGX_InitRequest(FCGX_Request *request, int sock, int flags)
2036 memset(request, 0, sizeof(FCGX_Request));
2038 /* @@@ Should check that sock is open and listening */
2039 request->listen_sock = sock;
2041 /* @@@ Should validate against "known" flags */
2042 request->flags = flags;
2044 request->ipcFd = -1;
2050 *----------------------------------------------------------------------
2054 * Initilize the FCGX library. This is called by FCGX_Accept()
2055 * but must be called by the user when using FCGX_Accept_r().
2058 * 0 for successful call.
2060 *----------------------------------------------------------------------
2066 if (libInitialized) {
2070 FCGX_InitRequest(&the_request, FCGI_LISTENSOCK_FILENO, 0);
2072 if (OS_LibInit(NULL) == -1) {
2073 return OS_Errno ? OS_Errno : -9997;
2076 p = getenv("FCGI_WEB_SERVER_ADDRS");
2077 webServerAddressList = p ? StringCopy(p) : NULL;
2084 *----------------------------------------------------------------------
2088 * Accepts a new request from the HTTP server.
2091 * 0 for successful call, -1 for error.
2095 * Finishes the request accepted by (and frees any
2096 * storage allocated by) the previous call to FCGX_Accept.
2097 * Creates input, output, and error streams and
2098 * assigns them to *in, *out, and *err respectively.
2099 * Creates a parameters data structure to be accessed
2100 * via getenv(3) (if assigned to environ) or by FCGX_GetParam
2101 * and assigns it to *envp.
2103 * DO NOT retain pointers to the envp array or any strings
2104 * contained in it (e.g. to the result of calling FCGX_GetParam),
2105 * since these will be freed by the next call to FCGX_Finish
2108 *----------------------------------------------------------------------
2115 FCGX_ParamArray *envp)
2119 if (! libInitialized) {
2126 rc = FCGX_Accept_r(&the_request);
2128 *in = the_request.in;
2129 *out = the_request.out;
2130 *err = the_request.err;
2131 *envp = the_request.envp;
2137 *----------------------------------------------------------------------
2141 * Accepts a new request from the HTTP server.
2144 * 0 for successful call, -1 for error.
2148 * Finishes the request accepted by (and frees any
2149 * storage allocated by) the previous call to FCGX_Accept.
2150 * Creates input, output, and error streams and
2151 * assigns them to *in, *out, and *err respectively.
2152 * Creates a parameters data structure to be accessed
2153 * via getenv(3) (if assigned to environ) or by FCGX_GetParam
2154 * and assigns it to *envp.
2156 * DO NOT retain pointers to the envp array or any strings
2157 * contained in it (e.g. to the result of calling FCGX_GetParam),
2158 * since these will be freed by the next call to FCGX_Finish
2161 *----------------------------------------------------------------------
2163 int FCGX_Accept_r(FCGX_Request *reqDataPtr)
2165 if (!libInitialized) {
2169 /* Finish the current request, if any. */
2170 FCGX_Finish_r(reqDataPtr);
2174 * If a connection isn't open, accept a new connection (blocking).
2175 * If an OS error occurs in accepting the connection,
2176 * return -1 to the caller, who should exit.
2178 if (reqDataPtr->ipcFd < 0) {
2179 int fail_on_intr = reqDataPtr->flags & FCGI_FAIL_ACCEPT_ON_INTR;
2181 reqDataPtr->ipcFd = OS_Accept(reqDataPtr->listen_sock, fail_on_intr, webServerAddressList);
2182 if (reqDataPtr->ipcFd < 0) {
2183 return (errno > 0) ? (0 - errno) : -9999;
2187 * A connection is open. Read from the connection in order to
2188 * get the request's role and environment. If protocol or other
2189 * errors occur, close the connection and try again.
2191 reqDataPtr->isBeginProcessed = FALSE;
2192 reqDataPtr->in = NewReader(reqDataPtr, 8192, 0);
2193 FillBuffProc(reqDataPtr->in);
2194 if(!reqDataPtr->isBeginProcessed) {
2199 switch(reqDataPtr->role) {
2200 case FCGI_RESPONDER:
2201 roleStr = "FCGI_ROLE=RESPONDER";
2203 case FCGI_AUTHORIZER:
2204 roleStr = "FCGI_ROLE=AUTHORIZER";
2207 roleStr = "FCGI_ROLE=FILTER";
2212 reqDataPtr->paramsPtr = NewParams(30);
2213 PutParam(reqDataPtr->paramsPtr, StringCopy(roleStr));
2215 SetReaderType(reqDataPtr->in, FCGI_PARAMS);
2216 if(ReadParams(reqDataPtr->paramsPtr, reqDataPtr->in) >= 0) {
2218 * Finished reading the environment. No errors occurred, so
2219 * leave the connection-retry loop.
2225 * Close the connection and try again.
2228 FCGX_Free(reqDataPtr, 1);
2232 * Build the remaining data structures representing the new
2233 * request and return successfully to the caller.
2235 SetReaderType(reqDataPtr->in, FCGI_STDIN);
2236 reqDataPtr->out = NewWriter(reqDataPtr, 8192, FCGI_STDOUT);
2237 reqDataPtr->err = NewWriter(reqDataPtr, 512, FCGI_STDERR);
2238 reqDataPtr->nWriters = 2;
2239 reqDataPtr->envp = reqDataPtr->paramsPtr->vec;
2244 *----------------------------------------------------------------------
2246 * FCGX_StartFilterData --
2248 * stream is an input stream for a FCGI_FILTER request.
2249 * stream is positioned at EOF on FCGI_STDIN.
2250 * Repositions stream to the start of FCGI_DATA.
2251 * If the preconditions are not met (e.g. FCGI_STDIN has not
2252 * been read to EOF) sets the stream error code to
2253 * FCGX_CALL_SEQ_ERROR.
2256 * 0 for a normal return, < 0 for error
2258 *----------------------------------------------------------------------
2261 int FCGX_StartFilterData(FCGX_Stream *stream)
2263 FCGX_Stream_Data *data = (FCGX_Stream_Data *)stream->data;
2264 if(data->reqDataPtr->role != FCGI_FILTER
2265 || !stream->isReader
2266 || !stream->isClosed
2267 || data->type != FCGI_STDIN) {
2268 SetError(stream, FCGX_CALL_SEQ_ERROR);
2271 SetReaderType(stream, FCGI_DATA);
2276 *----------------------------------------------------------------------
2278 * FCGX_SetExitStatus --
2280 * Sets the exit status for stream's request. The exit status
2281 * is the status code the request would have exited with, had
2282 * the request been run as a CGI program. You can call
2283 * SetExitStatus several times during a request; the last call
2284 * before the request ends determines the value.
2286 *----------------------------------------------------------------------
2289 void FCGX_SetExitStatus(int status, FCGX_Stream *stream)
2291 FCGX_Stream_Data *data = (FCGX_Stream_Data *)stream->data;
2292 data->reqDataPtr->appStatus = status;