Fix a bug a that caused the lib to crash under certain circumstances when an error...
[catagits/fcgi2.git] / libfcgi / fcgiapp.c
1 /*
2  * fcgiapp.c --
3  *
4  *      FastCGI application library: request-at-a-time
5  *
6  *
7  * Copyright (c) 1996 Open Market, Inc.
8  *
9  * See the file "LICENSE.TERMS" for information on usage and redistribution
10  * of this file, and for a DISCLAIMER OF ALL WARRANTIES.
11  *
12  */
13 #ifndef lint
14 static const char rcsid[] = "$Id: fcgiapp.c,v 1.33 2001/12/12 14:12:26 robs Exp $";
15 #endif /* not lint */
16
17 #include <assert.h>
18 #include <errno.h>
19 #include <fcntl.h>      /* for fcntl */
20 #include <math.h>
21 #include <memory.h>     /* for memchr() */
22 #include <stdarg.h>
23 #include <stdio.h>
24 #include <stdlib.h>
25 #include <string.h>
26 #include <sys/types.h>
27
28 #include "fcgi_config.h"
29
30 #ifdef HAVE_SYS_SOCKET_H
31 #include <sys/socket.h> /* for getpeername */
32 #endif
33
34 #ifdef HAVE_SYS_TIME_H
35 #include <sys/time.h>
36 #endif
37
38 #ifdef HAVE_UNISTD_H
39 #include <unistd.h>
40 #endif
41
42 #ifdef HAVE_LIMITS_H
43 #include <limits.h>
44 #endif
45
46 #ifdef _WIN32
47 #define DLLAPI  __declspec(dllexport)
48 #endif
49
50 #include "fcgimisc.h"
51 #include "fastcgi.h"
52 #include "fcgios.h"
53 #include "fcgiapp.h"
54
55 /*
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.
59  */
60 #ifdef HAVE_VA_ARG_LONG_DOUBLE_BUG
61 #define LONG_DOUBLE double
62 #else
63 #define LONG_DOUBLE long double
64 #endif
65
66 /*
67  * Globals
68  */
69 static int libInitialized = 0;
70 static int isFastCGI = -1;
71 static char *webServerAddressList = NULL;
72 static FCGX_Request the_request;
73
74 void FCGX_ShutdownPending(void)
75 {
76     OS_ShutdownPending();
77 }
78
79 static void *Malloc(size_t size)
80 {
81     void *result = malloc(size);
82     ASSERT(size == 0 || result != NULL);
83     return result;
84 }
85
86 static char *StringCopy(char *str)
87 {
88     int strLen = strlen(str);
89     char *newString = (char *)Malloc(strLen + 1);
90     memcpy(newString, str, strLen);
91     newString[strLen] = '\000';
92     return newString;
93 }
94
95
96 /*
97  *----------------------------------------------------------------------
98  *
99  * FCGX_GetChar --
100  *
101  *      Reads a byte from the input stream and returns it.
102  *
103  * Results:
104  *      The byte, or EOF (-1) if the end of input has been reached.
105  *
106  *----------------------------------------------------------------------
107  */
108 int FCGX_GetChar(FCGX_Stream *stream)
109 {
110     if(stream->rdNext != stream->stop)
111         return *stream->rdNext++;
112     if(stream->isClosed || !stream->isReader)
113         return EOF;
114     stream->fillBuffProc(stream);
115     if (stream->isClosed)
116         return EOF;
117     stream->stopUnget = stream->rdNext;
118     if(stream->rdNext != stream->stop)
119         return *stream->rdNext++;
120     ASSERT(stream->isClosed); /* bug in fillBufProc if not */
121     return EOF;
122 }
123
124 /*
125  *----------------------------------------------------------------------
126  *
127  * FCGX_GetStr --
128  *
129  *      Reads up to n consecutive bytes from the input stream
130  *      into the character array str.  Performs no interpretation
131  *      of the input bytes.
132  *
133  * Results:
134  *      Number of bytes read.  If result is smaller than n,
135  *      the end of input has been reached.
136  *
137  *----------------------------------------------------------------------
138  */
139 int FCGX_GetStr(char *str, int n, FCGX_Stream *stream)
140 {
141     int m, bytesMoved;
142
143     if(n <= 0) {
144         return 0;
145     }
146     /*
147      * Fast path: n bytes are already available
148      */
149     if(n <= (stream->stop - stream->rdNext)) {
150         memcpy(str, stream->rdNext, n);
151         stream->rdNext += n;
152         return n;
153     }
154     /*
155      * General case: stream is closed or buffer fill procedure
156      * needs to be called
157      */
158     bytesMoved = 0;
159     for (;;) {
160         if(stream->rdNext != stream->stop) {
161             m = min(n - bytesMoved, stream->stop - stream->rdNext);
162             memcpy(str, stream->rdNext, m);
163             bytesMoved += m;
164             stream->rdNext += m;
165             if(bytesMoved == n)
166                 return bytesMoved;
167             str += m;
168         }
169         if(stream->isClosed || !stream->isReader)
170             return bytesMoved;
171         stream->fillBuffProc(stream);
172         if (stream->isClosed)
173             return bytesMoved;
174
175         stream->stopUnget = stream->rdNext;
176     }
177 }
178
179 /*
180  *----------------------------------------------------------------------
181  *
182  * FCGX_GetLine --
183  *
184  *      Reads up to n-1 consecutive bytes from the input stream
185  *      into the character array str.  Stops before n-1 bytes
186  *      have been read if '\n' or EOF is read.  The terminating '\n'
187  *      is copied to str.  After copying the last byte into str,
188  *      stores a '\0' terminator.
189  *
190  * Results:
191  *      NULL if EOF is the first thing read from the input stream,
192  *      str otherwise.
193  *
194  *----------------------------------------------------------------------
195  */
196 char *FCGX_GetLine(char *str, int n, FCGX_Stream *stream)
197 {
198     int c;
199     char *p = str;
200
201     n--;
202     while (n > 0) {
203         c = FCGX_GetChar(stream);
204         if(c == EOF) {
205             if(p == str)
206                 return NULL;
207             else
208                 break;
209         }
210         *p++ = (char) c;
211         n--;
212         if(c == '\n')
213             break;
214     }
215     *p = '\0';
216     return str;
217 }
218
219 /*
220  *----------------------------------------------------------------------
221  *
222  * FCGX_UnGetChar --
223  *
224  *      Pushes back the character c onto the input stream.  One
225  *      character of pushback is guaranteed once a character
226  *      has been read.  No pushback is possible for EOF.
227  *
228  * Results:
229  *      Returns c if the pushback succeeded, EOF if not.
230  *
231  *----------------------------------------------------------------------
232  */
233 int FCGX_UnGetChar(int c, FCGX_Stream *stream) {
234     if(c == EOF
235             || stream->isClosed
236             || !stream->isReader
237             || stream->rdNext == stream->stopUnget)
238         return EOF;
239     --(stream->rdNext);
240     *stream->rdNext = (unsigned char) c;
241     return c;
242 }
243
244 /*
245  *----------------------------------------------------------------------
246  *
247  * FCGX_HasSeenEOF --
248  *
249  *      Returns EOF if end-of-file has been detected while reading
250  *      from stream; otherwise returns 0.
251  *
252  *      Note that FCGX_HasSeenEOF(s) may return 0, yet an immediately
253  *      following FCGX_GetChar(s) may return EOF.  This function, like
254  *      the standard C stdio function feof, does not provide the
255  *      ability to peek ahead.
256  *
257  * Results:
258  *      EOF if end-of-file has been detected, 0 if not.
259  *
260  *----------------------------------------------------------------------
261  */
262 int FCGX_HasSeenEOF(FCGX_Stream *stream) {
263     return (stream->isClosed) ? EOF : 0;
264 }
265
266 /*
267  *----------------------------------------------------------------------
268  *
269  * FCGX_PutChar --
270  *
271  *      Writes a byte to the output stream.
272  *
273  * Results:
274  *      The byte, or EOF (-1) if an error occurred.
275  *
276  *----------------------------------------------------------------------
277  */
278 int FCGX_PutChar(int c, FCGX_Stream *stream)
279 {
280     if(stream->wrNext != stream->stop)
281         return (*stream->wrNext++ = (unsigned char) c);
282     if(stream->isClosed || stream->isReader)
283         return EOF;
284     stream->emptyBuffProc(stream, FALSE);
285     if(stream->wrNext != stream->stop)
286         return (*stream->wrNext++ = (unsigned char) c);
287     ASSERT(stream->isClosed); /* bug in emptyBuffProc if not */
288     return EOF;
289 }
290
291 /*
292  *----------------------------------------------------------------------
293  *
294  * FCGX_PutStr --
295  *
296  *      Writes n consecutive bytes from the character array str
297  *      into the output stream.  Performs no interpretation
298  *      of the output bytes.
299  *
300  * Results:
301  *      Number of bytes written (n) for normal return,
302  *      EOF (-1) if an error occurred.
303  *
304  *----------------------------------------------------------------------
305  */
306 int FCGX_PutStr(const char *str, int n, FCGX_Stream *stream)
307 {
308     int m, bytesMoved;
309
310     /*
311      * Fast path: room for n bytes in the buffer
312      */
313     if(n <= (stream->stop - stream->wrNext)) {
314         memcpy(stream->wrNext, str, n);
315         stream->wrNext += n;
316         return n;
317     }
318     /*
319      * General case: stream is closed or buffer empty procedure
320      * needs to be called
321      */
322     bytesMoved = 0;
323     for (;;) {
324         if(stream->wrNext != stream->stop) {
325             m = min(n - bytesMoved, stream->stop - stream->wrNext);
326             memcpy(stream->wrNext, str, m);
327             bytesMoved += m;
328             stream->wrNext += m;
329             if(bytesMoved == n)
330                 return bytesMoved;
331             str += m;
332         }
333         if(stream->isClosed || stream->isReader)
334             return -1;
335         stream->emptyBuffProc(stream, FALSE);
336     }
337 }
338
339 /*
340  *----------------------------------------------------------------------
341  *
342  * FCGX_PutS --
343  *
344  *      Writes a character string to the output stream.
345  *
346  * Results:
347  *      number of bytes written for normal return,
348  *      EOF (-1) if an error occurred.
349  *
350  *----------------------------------------------------------------------
351  */
352 int FCGX_PutS(const char *str, FCGX_Stream *stream)
353 {
354     return FCGX_PutStr(str, strlen(str), stream);
355 }
356
357 /*
358  *----------------------------------------------------------------------
359  *
360  * FCGX_FPrintF --
361  *
362  *      Performs output formatting and writes the results
363  *      to the output stream.
364  *
365  * Results:
366  *      number of bytes written for normal return,
367  *      EOF (-1) if an error occurred.
368  *
369  *----------------------------------------------------------------------
370  */
371 int FCGX_FPrintF(FCGX_Stream *stream, const char *format, ...)
372 {
373     int result;
374     va_list ap;
375     va_start(ap, format);
376     result = FCGX_VFPrintF(stream, format, ap);
377     va_end(ap);
378     return result;
379 }
380
381 /*
382  *----------------------------------------------------------------------
383  *
384  * FCGX_VFPrintF --
385  *
386  *      Performs output formatting and writes the results
387  *      to the output stream.
388  *
389  * Results:
390  *      number of bytes written for normal return,
391  *      EOF (-1) if an error occurred.
392  *
393  *----------------------------------------------------------------------
394  */
395
396 #define PRINTF_BUFFLEN 100
397     /*
398      * More than sufficient space for all unmodified conversions
399      * except %s and %f.
400      */
401 #define FMT_BUFFLEN 25
402     /*
403      * Max size of a format specifier is 1 + 5 + 7 + 7 + 2 + 1 + slop
404      */
405 static void CopyAndAdvance(char **destPtr, char **srcPtr, int n);
406
407 int FCGX_VFPrintF(FCGX_Stream *stream, const char *format, va_list arg)
408 {
409     char *f, *fStop, *percentPtr, *p, *fmtBuffPtr, *buffPtr;
410     int op, performedOp, sizeModifier, buffCount = 0, buffLen, specifierLength;
411     int fastPath, n, auxBuffLen = 0, buffReqd, minWidth, precision, exp;
412     char *auxBuffPtr = NULL;
413     int streamCount = 0;
414     char fmtBuff[FMT_BUFFLEN];
415     char buff[PRINTF_BUFFLEN];
416
417     int intArg;
418     short shortArg;
419     long longArg;
420     unsigned unsignedArg;
421     unsigned long uLongArg;
422     unsigned short uShortArg;
423     char *charPtrArg = NULL;
424     void *voidPtrArg;
425     int *intPtrArg;
426     long *longPtrArg;
427     short *shortPtrArg;
428     double doubleArg = 0.0;
429     LONG_DOUBLE lDoubleArg = 0.0L;
430
431     fmtBuff[0] = '%';
432     f = (char *) format;
433     fStop = f + strlen(f);
434     while (f != fStop) {
435         percentPtr = (char *)memchr(f, '%', fStop - f);
436         if(percentPtr == NULL) percentPtr = fStop;
437         if(percentPtr != f) {
438             if(FCGX_PutStr(f, percentPtr - f, stream) < 0)
439                 goto ErrorReturn;
440             streamCount += percentPtr - f;
441             f = percentPtr;
442             if(f == fStop) break;
443         }
444         fastPath = TRUE;
445         /*
446          * The following loop always executes either once or twice.
447          */
448         for (;;) {
449             if(fastPath) {
450                 /*
451                  * Fast path: Scan optimistically, hoping that no flags,
452                  * minimum field width, or precision are specified.
453                  * Use the preallocated buffer, which is large enough
454                  * for all fast path cases.  If the conversion specifier
455                  * is really more complex, run the loop a second time
456                  * using the slow path.
457                  * Note that fast path execution of %s bypasses the buffer
458                  * and %f is not attempted on the fast path due to
459                  * its large buffering requirements.
460                  */
461                 op = *(percentPtr + 1);
462                 switch(op) {
463                     case 'l':
464                     case 'L':
465                     case 'h':
466                         sizeModifier = op;
467                         op = *(percentPtr + 2);
468                         fmtBuff[1] = (char) sizeModifier;
469                         fmtBuff[2] = (char) op;
470                         fmtBuff[3] = '\0';
471                         specifierLength = 3;
472                         break;
473                     default:
474                         sizeModifier = ' ';
475                         fmtBuff[1] = (char) op;
476                         fmtBuff[2] = '\0';
477                         specifierLength = 2;
478                         break;
479                 }
480                 buffPtr = buff;
481                 buffLen = PRINTF_BUFFLEN;
482             } else {
483                 /*
484                  * Slow path: Scan the conversion specifier and construct
485                  * a new format string, compute an upper bound on the
486                  * amount of buffering that sprintf will require,
487                  * and allocate a larger buffer if necessary.
488                  */
489                 p = percentPtr + 1;
490                 fmtBuffPtr = &fmtBuff[1];
491                 /*
492                  * Scan flags
493                  */
494                 n = strspn(p, "-0+ #");
495                 if(n > 5)
496                     goto ErrorReturn;
497                 CopyAndAdvance(&fmtBuffPtr, &p, n);
498                 /*
499                  * Scan minimum field width
500                  */
501                 n = strspn(p, "0123456789");
502                 if(n == 0) {
503                     if(*p == '*') {
504                         minWidth = va_arg(arg, int);
505                         if(abs(minWidth) > 999999)
506                             goto ErrorReturn;
507                         /*
508                          * The following use of strlen rather than the
509                          * value returned from sprintf is because SUNOS4
510                          * returns a char * instead of an int count.
511                          */
512                         sprintf(fmtBuffPtr, "%d", minWidth);
513                         fmtBuffPtr += strlen(fmtBuffPtr);
514                         p++;
515                     } else {
516                         minWidth = 0;
517                     }
518                 } else if(n <= 6) {
519                     minWidth = strtol(p, NULL, 10);
520                     CopyAndAdvance(&fmtBuffPtr, &p, n);
521                 } else {
522                     goto ErrorReturn;
523                 }
524                 /*
525                  * Scan precision
526                  */
527                 if(*p == '.') {
528                     CopyAndAdvance(&fmtBuffPtr, &p, 1);
529                     n = strspn(p, "0123456789");
530                     if(n == 0) {
531                         if(*p == '*') {
532                             precision = va_arg(arg, int);
533                             if(precision < 0) precision = 0;
534                             if(precision > 999999)
535                                 goto ErrorReturn;
536                         /*
537                          * The following use of strlen rather than the
538                          * value returned from sprintf is because SUNOS4
539                          * returns a char * instead of an int count.
540                          */
541                             sprintf(fmtBuffPtr, "%d", precision);
542                             fmtBuffPtr += strlen(fmtBuffPtr);
543                             p++;
544                         } else {
545                             precision = 0;
546                         }
547                     } else if(n <= 6) {
548                         precision = strtol(p, NULL, 10);
549                         CopyAndAdvance(&fmtBuffPtr, &p, n);
550                     } else {
551                         goto ErrorReturn;
552                     }
553                 } else {
554                     precision = -1;
555                 }
556                 /*
557                  * Scan size modifier and conversion operation
558                  */
559                 switch(*p) {
560                     case 'l':
561                     case 'L':
562                     case 'h':
563                         sizeModifier = *p;
564                         CopyAndAdvance(&fmtBuffPtr, &p, 1);
565                         break;
566                     default:
567                         sizeModifier = ' ';
568                         break;
569                 }
570                 op = *p;
571                 CopyAndAdvance(&fmtBuffPtr, &p, 1);
572                 ASSERT(fmtBuffPtr - fmtBuff < FMT_BUFFLEN);
573                 *fmtBuffPtr = '\0';
574                 specifierLength = p - percentPtr;
575                 /*
576                  * Bound the required buffer size.  For s and f
577                  * conversions this requires examining the argument.
578                  */
579                 switch(op) {
580                     case 'd':
581                     case 'i':
582                     case 'u':
583                     case 'o':
584                     case 'x':
585                     case 'X':
586                     case 'c':
587                     case 'p':
588                         buffReqd = max(precision, 46);
589                         break;
590                     case 's':
591                         charPtrArg = va_arg(arg, char *);
592                         if (!charPtrArg) charPtrArg = "(null)";
593                         if(precision == -1) {
594                             buffReqd = strlen(charPtrArg);
595                         } else {
596                             p = (char *)memchr(charPtrArg, '\0', precision);
597                             buffReqd =
598                               (p == NULL) ? precision : p - charPtrArg;
599                         }
600                         break;
601                     case 'f':
602                         switch(sizeModifier) {
603                             case ' ':
604                                 doubleArg = va_arg(arg, double);
605                                                 frexp(doubleArg, &exp);
606                                 break;
607                             case 'L':
608                                 lDoubleArg = va_arg(arg, LONG_DOUBLE);
609                                 /* XXX Need to check for the presence of 
610                                  * frexpl() and use it if available */
611                                                 frexp((double) lDoubleArg, &exp);
612                                 break;
613                             default:
614                                 goto ErrorReturn;
615                         }
616                         if(precision == -1) precision = 6;
617                         buffReqd = precision + 3 + ((exp > 0) ? exp/3 : 0);
618                         break;
619                     case 'e':
620                     case 'E':
621                     case 'g':
622                     case 'G':
623                         if(precision == -1) precision = 6;
624                         buffReqd = precision + 8;
625                         break;
626                     case 'n':
627                     case '%':
628                     default:
629                         goto ErrorReturn;
630                         break;
631                 }
632                 buffReqd = max(buffReqd + 10, minWidth);
633                 /*
634                  * Allocate the buffer
635                  */
636                 if(buffReqd <= PRINTF_BUFFLEN) {
637                     buffPtr = buff;
638                     buffLen = PRINTF_BUFFLEN;
639                 } else {
640                     if(auxBuffPtr == NULL || buffReqd > auxBuffLen) {
641                         if(auxBuffPtr != NULL) free(auxBuffPtr);
642                         auxBuffPtr = (char *)Malloc(buffReqd);
643                         auxBuffLen = buffReqd;
644                         if(auxBuffPtr == NULL)
645                             goto ErrorReturn;
646                     }
647                     buffPtr = auxBuffPtr;
648                     buffLen = auxBuffLen;
649                 }
650             }
651             /*
652              * This giant switch statement requires the following variables
653              * to be set up: op, sizeModifier, arg, buffPtr, fmtBuff.
654              * When fastPath == FALSE and op == 's' or 'f', the argument
655              * has been read into charPtrArg, doubleArg, or lDoubleArg.
656              * The statement produces the boolean performedOp, TRUE iff
657              * the op/sizeModifier were executed and argument consumed;
658              * if performedOp, the characters written into buffPtr[]
659              * and the character count buffCount (== EOF meaning error).
660              *
661              * The switch cases are arranged in the same order as in the
662              * description of fprintf in section 15.11 of Harbison and Steele.
663              */
664             performedOp = TRUE;
665             switch(op) {
666                 case 'd':
667                 case 'i':
668                     switch(sizeModifier) {
669                         case ' ':
670                             intArg = va_arg(arg, int);
671                             sprintf(buffPtr, fmtBuff, intArg);
672                             buffCount = strlen(buffPtr);
673                             break;
674                         case 'l':
675                             longArg = va_arg(arg, long);
676                             sprintf(buffPtr, fmtBuff, longArg);
677                             buffCount = strlen(buffPtr);
678                             break;
679                         case 'h':
680                             shortArg = (short) va_arg(arg, int);
681                             sprintf(buffPtr, fmtBuff, shortArg);
682                             buffCount = strlen(buffPtr);
683                             break;
684                         default:
685                             goto ErrorReturn;
686                     }
687                     break;
688                 case 'u':
689                 case 'o':
690                 case 'x':
691                 case 'X':
692                     switch(sizeModifier) {
693                         case ' ':
694                             unsignedArg = va_arg(arg, unsigned);
695                             sprintf(buffPtr, fmtBuff, unsignedArg);
696                             buffCount = strlen(buffPtr);
697                             break;
698                         case 'l':
699                             uLongArg = va_arg(arg, unsigned long);
700                             sprintf(buffPtr, fmtBuff, uLongArg);
701                             buffCount = strlen(buffPtr);
702                             break;
703                         case 'h':
704                             uShortArg = (unsigned short) va_arg(arg, int);
705                             sprintf(buffPtr, fmtBuff, uShortArg);
706                             buffCount = strlen(buffPtr);
707                             break;
708                         default:
709                             goto ErrorReturn;
710                     }
711                     break;
712                 case 'c':
713                     switch(sizeModifier) {
714                         case ' ':
715                             intArg = va_arg(arg, int);
716                             sprintf(buffPtr, fmtBuff, intArg);
717                             buffCount = strlen(buffPtr);
718                             break;
719                         case 'l':
720                             /*
721                              * XXX: Allowed by ISO C Amendment 1, but
722                              * many platforms don't yet support wint_t
723                              */
724                             goto ErrorReturn;
725                     default:
726                             goto ErrorReturn;
727                     }
728                     break;
729                 case 's':
730                     switch(sizeModifier) {
731                         case ' ':
732                             if(fastPath) {
733                                 buffPtr = va_arg(arg, char *);
734                                 buffCount = strlen(buffPtr);
735                                 buffLen = buffCount + 1;
736                             } else {
737                                 sprintf(buffPtr, fmtBuff, charPtrArg);
738                                 buffCount = strlen(buffPtr);
739                             }
740                             break;
741                         case 'l':
742                             /*
743                              * XXX: Don't know how to convert a sequence
744                              * of wide characters into a byte stream, or
745                              * even how to predict the buffering required.
746                              */
747                             goto ErrorReturn;
748                         default:
749                             goto ErrorReturn;
750                     }
751                     break;
752                 case 'p':
753                     if(sizeModifier != ' ')
754                         goto ErrorReturn;
755                     voidPtrArg = va_arg(arg, void *);
756                     sprintf(buffPtr, fmtBuff, voidPtrArg);
757                     buffCount = strlen(buffPtr);
758                     break;
759                 case 'n':
760                     switch(sizeModifier) {
761                         case ' ':
762                             intPtrArg = va_arg(arg, int *);
763                             *intPtrArg = streamCount;
764                             break;
765                         case 'l':
766                             longPtrArg = va_arg(arg, long *);
767                             *longPtrArg = streamCount;
768                             break;
769                         case 'h':
770                             shortPtrArg = (short *) va_arg(arg, short *);
771                             *shortPtrArg = (short) streamCount;
772                             break;
773                         default:
774                             goto ErrorReturn;
775                     }
776                     buffCount = 0;
777                     break;
778                 case 'f':
779                     if(fastPath) {
780                         performedOp = FALSE;
781                         break;
782                     }
783                     switch(sizeModifier) {
784                         case ' ':
785                             sprintf(buffPtr, fmtBuff, doubleArg);
786                             buffCount = strlen(buffPtr);
787                             break;
788                         case 'L':
789                             sprintf(buffPtr, fmtBuff, lDoubleArg);
790                             buffCount = strlen(buffPtr);
791                             break;
792                         default:
793                             goto ErrorReturn;
794                     }
795                     break;
796                 case 'e':
797                 case 'E':
798                 case 'g':
799                 case 'G':
800                     switch(sizeModifier) {
801                         case ' ':
802                             doubleArg = va_arg(arg, double);
803                             sprintf(buffPtr, fmtBuff, doubleArg);
804                             buffCount = strlen(buffPtr);
805                             break;
806                         case 'L':
807                             lDoubleArg = va_arg(arg, LONG_DOUBLE);
808                             sprintf(buffPtr, fmtBuff, lDoubleArg);
809                             buffCount = strlen(buffPtr);
810                             break;
811                         default:
812                             goto ErrorReturn;
813                     }
814                     break;
815                 case '%':
816                     if(sizeModifier != ' ')
817                         goto ErrorReturn;
818                     buff[0] = '%';
819                     buffCount = 1;
820                     break;
821                 case '\0':
822                     goto ErrorReturn;
823                 default:
824                     performedOp = FALSE;
825                     break;
826             } /* switch(op) */
827             if(performedOp) break;
828             if(!fastPath)
829                 goto ErrorReturn;
830             fastPath = FALSE;
831         } /* for (;;) */
832         ASSERT(buffCount < buffLen);
833         if(buffCount > 0) {
834             if(FCGX_PutStr(buffPtr, buffCount, stream) < 0)
835                 goto ErrorReturn;
836             streamCount += buffCount;
837         } else if(buffCount < 0) {
838             goto ErrorReturn;
839         }
840         f += specifierLength;
841     } /* while(f != fStop) */
842     goto NormalReturn;
843   ErrorReturn:
844     streamCount = -1;
845   NormalReturn:
846     if(auxBuffPtr != NULL) free(auxBuffPtr);
847     return streamCount;
848 }
849
850 /*
851  * Copy n characters from *srcPtr to *destPtr, then increment
852  * both *srcPtr and *destPtr by n.
853  */
854 static void CopyAndAdvance(char **destPtr, char **srcPtr, int n)
855 {
856     char *dest = *destPtr;
857     char *src = *srcPtr;
858     int i;
859     for (i = 0; i < n; i++)
860         *dest++ = *src++;
861     *destPtr = dest;
862     *srcPtr = src;
863 }
864
865 /*
866  *----------------------------------------------------------------------
867  *
868  * FCGX_FFlush --
869  *
870  *      Flushes any buffered output.
871  *
872  *      Server-push is a legitimate application of FCGX_FFlush.
873  *      Otherwise, FCGX_FFlush is not very useful, since FCGX_Accept
874  *      does it implicitly.  FCGX_FFlush may reduce performance
875  *      by increasing the total number of operating system calls
876  *      the application makes.
877  *
878  * Results:
879  *      EOF (-1) if an error occurred.
880  *
881  *----------------------------------------------------------------------
882  */
883 int FCGX_FFlush(FCGX_Stream *stream)
884 {
885     if(stream->isClosed || stream->isReader)
886         return 0;
887     stream->emptyBuffProc(stream, FALSE);
888     return (stream->isClosed) ? -1 : 0;
889 }
890
891 /*
892  *----------------------------------------------------------------------
893  *
894  * FCGX_FClose --
895  *
896  *      Performs FCGX_FFlush and closes the stream.
897  *
898  *      This is not a very useful operation, since FCGX_Accept
899  *      does it implicitly.  Closing the out stream before the
900  *      err stream results in an extra write if there's nothing
901  *      in the err stream, and therefore reduces performance.
902  *
903  * Results:
904  *      EOF (-1) if an error occurred.
905  *
906  *----------------------------------------------------------------------
907  */
908 int FCGX_FClose(FCGX_Stream *stream)
909 {
910     if (stream == NULL) return 0;
911
912     if(!stream->wasFCloseCalled) {
913         if(!stream->isReader) {
914             stream->emptyBuffProc(stream, TRUE);
915         }
916         stream->wasFCloseCalled = TRUE;
917         stream->isClosed = TRUE;
918         if(stream->isReader) {
919             stream->wrNext = stream->stop = stream->rdNext;
920         } else {
921             stream->rdNext = stream->stop = stream->wrNext;
922         }
923     }
924     return (stream->FCGI_errno == 0) ? 0 : EOF;
925 }
926
927 /*
928  *----------------------------------------------------------------------
929  *
930  * SetError --
931  *
932  *      An error has occurred; save the error code in the stream
933  *      for diagnostic purposes and set the stream state so that
934  *      reads return EOF and writes have no effect.
935  *
936  *----------------------------------------------------------------------
937  */
938 static void SetError(FCGX_Stream *stream, int FCGI_errno)
939 {
940     /*
941      * Preserve only the first error.
942      */
943     if(stream->FCGI_errno == 0) {
944         stream->FCGI_errno = FCGI_errno;
945         stream->isClosed = TRUE;
946     }
947 }
948
949 /*
950  *----------------------------------------------------------------------
951  *
952  * FCGX_GetError --
953  *
954  *      Return the stream error code.  0 means no error, > 0
955  *      is an errno(2) error, < 0 is an FCGX_errno error.
956  *
957  *----------------------------------------------------------------------
958  */
959 int FCGX_GetError(FCGX_Stream *stream) {
960     return stream->FCGI_errno;
961 }
962
963 /*
964  *----------------------------------------------------------------------
965  *
966  * FCGX_ClearError --
967  *
968  *      Clear the stream error code and end-of-file indication.
969  *
970  *----------------------------------------------------------------------
971  */
972 void FCGX_ClearError(FCGX_Stream *stream) {
973     stream->FCGI_errno = 0;
974     /*
975      * stream->isClosed = FALSE;
976      * XXX: should clear isClosed but work is needed to make it safe
977      * to do so.  For example, if an application calls FClose, gets
978      * an I/O error on the write, calls ClearError and retries
979      * the FClose, FClose (really EmptyBuffProc) will write a second
980      * EOF record.  If an application calls PutChar instead of FClose
981      * after the ClearError, the application will write more data.
982      * The stream's state must discriminate between various states
983      * of the stream that are now all lumped under isClosed.
984      */
985 }
986
987 /*
988  *======================================================================
989  * Parameters
990  *======================================================================
991  */
992
993 /*
994  * A vector of pointers representing the parameters received
995  * by a FastCGI application server, with the vector's length
996  * and last valid element so adding new parameters is efficient.
997  */
998
999 typedef struct Params {
1000     FCGX_ParamArray vec;    /* vector of strings */
1001     int length;             /* number of string vec can hold */
1002     char **cur;             /* current item in vec; *cur == NULL */
1003 } Params;
1004 typedef Params *ParamsPtr;
1005
1006 /*
1007  *----------------------------------------------------------------------
1008  *
1009  * NewParams --
1010  *
1011  *      Creates a new Params structure.
1012  *
1013  * Results:
1014  *      Pointer to the new structure.
1015  *
1016  *----------------------------------------------------------------------
1017  */
1018 static ParamsPtr NewParams(int length)
1019 {
1020     ParamsPtr result;
1021     result = (Params *)Malloc(sizeof(Params));
1022     result->vec = (char **)Malloc(length * sizeof(char *));
1023     result->length = length;
1024     result->cur = result->vec;
1025     *result->cur = NULL;
1026     return result;
1027 }
1028
1029 /*
1030  *----------------------------------------------------------------------
1031  *
1032  * FreeParams --
1033  *
1034  *      Frees a Params structure and all the parameters it contains.
1035  *
1036  * Side effects:
1037  *      env becomes invalid.
1038  *
1039  *----------------------------------------------------------------------
1040  */
1041 static void FreeParams(ParamsPtr *paramsPtrPtr)
1042 {
1043     ParamsPtr paramsPtr = *paramsPtrPtr;
1044     char **p;
1045     if(paramsPtr == NULL) {
1046         return;
1047     }
1048     for (p = paramsPtr->vec; p < paramsPtr->cur; p++) {
1049         free(*p);
1050     }
1051     free(paramsPtr->vec);
1052     free(paramsPtr);
1053     *paramsPtrPtr = NULL;
1054 }
1055
1056 /*
1057  *----------------------------------------------------------------------
1058  *
1059  * PutParam --
1060  *
1061  *      Add a name/value pair to a Params structure.
1062  *
1063  * Results:
1064  *      None.
1065  *
1066  * Side effects:
1067  *      Parameters structure updated.
1068  *
1069  *----------------------------------------------------------------------
1070  */
1071 static void PutParam(ParamsPtr paramsPtr, char *nameValue)
1072 {
1073     int size;
1074
1075     *paramsPtr->cur++ = nameValue;
1076     size = paramsPtr->cur - paramsPtr->vec;
1077     if(size >= paramsPtr->length) {
1078         paramsPtr->length *= 2;
1079         paramsPtr->vec = (FCGX_ParamArray)realloc(paramsPtr->vec, paramsPtr->length * sizeof(char *));
1080         paramsPtr->cur = paramsPtr->vec + size;
1081     }
1082     *paramsPtr->cur = NULL;
1083 }
1084
1085 /*
1086  *----------------------------------------------------------------------
1087  *
1088  * FCGX_GetParam -- obtain value of FCGI parameter in environment
1089  *
1090  *
1091  * Results:
1092  *      Value bound to name, NULL if name not present in the
1093  *      environment envp.  Caller must not mutate the result
1094  *      or retain it past the end of this request.
1095  *
1096  *----------------------------------------------------------------------
1097  */
1098 char *FCGX_GetParam(const char *name, FCGX_ParamArray envp)
1099 {
1100     int len;
1101     char **p;
1102
1103         if (name == NULL || envp == NULL) return NULL;
1104
1105     len = strlen(name);
1106
1107     for (p = envp; *p; ++p) {
1108         if((strncmp(name, *p, len) == 0) && ((*p)[len] == '=')) {
1109             return *p+len+1;
1110         }
1111     }
1112     return NULL;
1113 }
1114
1115 /*
1116  *----------------------------------------------------------------------
1117  *
1118  * Start of FastCGI-specific code
1119  *
1120  *----------------------------------------------------------------------
1121  */
1122
1123 /*
1124  *----------------------------------------------------------------------
1125  *
1126  * ReadParams --
1127  *
1128  *      Reads FastCGI name-value pairs from stream until EOF.  Converts
1129  *      each pair to name=value format and adds it to Params structure.
1130  *
1131  *----------------------------------------------------------------------
1132  */
1133 static int ReadParams(Params *paramsPtr, FCGX_Stream *stream)
1134 {
1135     int nameLen, valueLen;
1136     unsigned char lenBuff[3];
1137     char *nameValue;
1138
1139     while((nameLen = FCGX_GetChar(stream)) != EOF) {
1140         /*
1141          * Read name length (one or four bytes) and value length
1142          * (one or four bytes) from stream.
1143          */
1144         if((nameLen & 0x80) != 0) {
1145             if(FCGX_GetStr((char *) &lenBuff[0], 3, stream) != 3) {
1146                 SetError(stream, FCGX_PARAMS_ERROR);
1147                 return -1;
1148             }
1149             nameLen = ((nameLen & 0x7f) << 24) + (lenBuff[0] << 16)
1150                     + (lenBuff[1] << 8) + lenBuff[2];
1151         }
1152         if((valueLen = FCGX_GetChar(stream)) == EOF) {
1153             SetError(stream, FCGX_PARAMS_ERROR);
1154             return -1;
1155         }
1156         if((valueLen & 0x80) != 0) {
1157             if(FCGX_GetStr((char *) &lenBuff[0], 3, stream) != 3) {
1158                 SetError(stream, FCGX_PARAMS_ERROR);
1159                 return -1;
1160             }
1161             valueLen = ((valueLen & 0x7f) << 24) + (lenBuff[0] << 16)
1162                     + (lenBuff[1] << 8) + lenBuff[2];
1163         }
1164         /*
1165          * nameLen and valueLen are now valid; read the name and value
1166          * from stream and construct a standard environment entry.
1167          */
1168         nameValue = (char *)Malloc(nameLen + valueLen + 2);
1169         if(FCGX_GetStr(nameValue, nameLen, stream) != nameLen) {
1170             SetError(stream, FCGX_PARAMS_ERROR);
1171             free(nameValue);
1172             return -1;
1173         }
1174         *(nameValue + nameLen) = '=';
1175         if(FCGX_GetStr(nameValue + nameLen + 1, valueLen, stream)
1176                 != valueLen) {
1177             SetError(stream, FCGX_PARAMS_ERROR);
1178             free(nameValue);
1179             return -1;
1180         }
1181         *(nameValue + nameLen + valueLen + 1) = '\0';
1182         PutParam(paramsPtr, nameValue);
1183     }
1184     return 0;
1185 }
1186
1187 /*
1188  *----------------------------------------------------------------------
1189  *
1190  * MakeHeader --
1191  *
1192  *      Constructs an FCGI_Header struct.
1193  *
1194  *----------------------------------------------------------------------
1195  */
1196 static FCGI_Header MakeHeader(
1197         int type,
1198         int requestId,
1199         int contentLength,
1200         int paddingLength)
1201 {
1202     FCGI_Header header;
1203     ASSERT(contentLength >= 0 && contentLength <= FCGI_MAX_LENGTH);
1204     ASSERT(paddingLength >= 0 && paddingLength <= 0xff);
1205     header.version = FCGI_VERSION_1;
1206     header.type             = (unsigned char) type;
1207     header.requestIdB1      = (unsigned char) ((requestId     >> 8) & 0xff);
1208     header.requestIdB0      = (unsigned char) ((requestId         ) & 0xff);
1209     header.contentLengthB1  = (unsigned char) ((contentLength >> 8) & 0xff);
1210     header.contentLengthB0  = (unsigned char) ((contentLength     ) & 0xff);
1211     header.paddingLength    = (unsigned char) paddingLength;
1212     header.reserved         =  0;
1213     return header;
1214 }
1215
1216 /*
1217  *----------------------------------------------------------------------
1218  *
1219  * MakeEndRequestBody --
1220  *
1221  *      Constructs an FCGI_EndRequestBody struct.
1222  *
1223  *----------------------------------------------------------------------
1224  */
1225 static FCGI_EndRequestBody MakeEndRequestBody(
1226         int appStatus,
1227         int protocolStatus)
1228 {
1229     FCGI_EndRequestBody body;
1230     body.appStatusB3    = (unsigned char) ((appStatus >> 24) & 0xff);
1231     body.appStatusB2    = (unsigned char) ((appStatus >> 16) & 0xff);
1232     body.appStatusB1    = (unsigned char) ((appStatus >>  8) & 0xff);
1233     body.appStatusB0    = (unsigned char) ((appStatus      ) & 0xff);
1234     body.protocolStatus = (unsigned char) protocolStatus;
1235     memset(body.reserved, 0, sizeof(body.reserved));
1236     return body;
1237 }
1238
1239 /*
1240  *----------------------------------------------------------------------
1241  *
1242  * MakeUnknownTypeBody --
1243  *
1244  *      Constructs an FCGI_MakeUnknownTypeBody struct.
1245  *
1246  *----------------------------------------------------------------------
1247  */
1248 static FCGI_UnknownTypeBody MakeUnknownTypeBody(
1249         int type)
1250 {
1251     FCGI_UnknownTypeBody body;
1252     body.type = (unsigned char) type;
1253     memset(body.reserved, 0, sizeof(body.reserved));
1254     return body;
1255 }
1256
1257 /*
1258  *----------------------------------------------------------------------
1259  *
1260  * AlignInt8 --
1261  *
1262  *      Returns the smallest integer greater than or equal to n
1263  *      that's a multiple of 8.
1264  *
1265  *----------------------------------------------------------------------
1266  */
1267 static int AlignInt8(unsigned n) {
1268     return (n + 7) & (UINT_MAX - 7);
1269 }
1270
1271 /*
1272  *----------------------------------------------------------------------
1273  *
1274  * AlignPtr8 --
1275  *
1276  *      Returns the smallest pointer greater than or equal to p
1277  *      that's a multiple of 8.
1278  *
1279  *----------------------------------------------------------------------
1280  */
1281 static unsigned char *AlignPtr8(unsigned char *p) {
1282     unsigned long u = (unsigned long) p;
1283     u = ((u + 7) & (ULONG_MAX - 7)) - u;
1284     return p + u;
1285 }
1286
1287
1288 /*
1289  * State associated with a stream
1290  */
1291 typedef struct FCGX_Stream_Data {
1292     unsigned char *buff;      /* buffer after alignment */
1293     int bufflen;              /* number of bytes buff can store */
1294     unsigned char *mBuff;     /* buffer as returned by Malloc */
1295     unsigned char *buffStop;  /* reader: last valid byte + 1 of entire buffer.
1296                                * stop generally differs from buffStop for
1297                                * readers because of record structure.
1298                                * writer: buff + bufflen */
1299     int type;                 /* reader: FCGI_PARAMS or FCGI_STDIN
1300                                * writer: FCGI_STDOUT or FCGI_STDERR */
1301     int eorStop;              /* reader: stop stream at end-of-record */
1302     int skip;                 /* reader: don't deliver content bytes */
1303     int contentLen;           /* reader: bytes of unread content */
1304     int paddingLen;           /* reader: bytes of unread padding */
1305     int isAnythingWritten;    /* writer: data has been written to ipcFd */
1306     int rawWrite;             /* writer: write data without stream headers */
1307     FCGX_Request *reqDataPtr; /* request data not specific to one stream */
1308 } FCGX_Stream_Data;
1309
1310 /*
1311  *----------------------------------------------------------------------
1312  *
1313  * WriteCloseRecords --
1314  *
1315  *      Writes an EOF record for the stream content if necessary.
1316  *      If this is the last writer to close, writes an FCGI_END_REQUEST
1317  *      record.
1318  *
1319  *----------------------------------------------------------------------
1320  */
1321 static void WriteCloseRecords(struct FCGX_Stream *stream)
1322 {
1323     FCGX_Stream_Data *data = (FCGX_Stream_Data *)stream->data;
1324     /*
1325      * Enter rawWrite mode so final records won't be encapsulated as
1326      * stream data.
1327      */
1328     data->rawWrite = TRUE;
1329     /*
1330      * Generate EOF for stream content if needed.
1331      */
1332     if(!(data->type == FCGI_STDERR
1333             && stream->wrNext == data->buff
1334             && !data->isAnythingWritten)) {
1335         FCGI_Header header;
1336         header = MakeHeader(data->type, data->reqDataPtr->requestId, 0, 0);
1337         FCGX_PutStr((char *) &header, sizeof(header), stream);
1338     };
1339     /*
1340      * Generate FCGI_END_REQUEST record if needed.
1341      */
1342     if(data->reqDataPtr->nWriters == 1) {
1343         FCGI_EndRequestRecord endRequestRecord;
1344         endRequestRecord.header = MakeHeader(FCGI_END_REQUEST,
1345                 data->reqDataPtr->requestId,
1346                 sizeof(endRequestRecord.body), 0);
1347         endRequestRecord.body = MakeEndRequestBody(
1348                 data->reqDataPtr->appStatus, FCGI_REQUEST_COMPLETE);
1349         FCGX_PutStr((char *) &endRequestRecord,
1350                 sizeof(endRequestRecord), stream);
1351     }
1352     data->reqDataPtr->nWriters--;
1353 }
1354
1355
1356
1357 static int write_it_all(int fd, char *buf, int len)
1358 {
1359     int wrote;
1360
1361     while (len) {
1362         wrote = OS_Write(fd, buf, len);
1363         if (wrote < 0)
1364             return wrote;
1365         len -= wrote;
1366         buf += wrote;
1367     }
1368     return len;
1369 }
1370
1371 /*
1372  *----------------------------------------------------------------------
1373  *
1374  * EmptyBuffProc --
1375  *
1376  *      Encapsulates any buffered stream content in a FastCGI
1377  *      record.  Writes the data, making the buffer empty.
1378  *
1379  *----------------------------------------------------------------------
1380  */
1381 static void EmptyBuffProc(struct FCGX_Stream *stream, int doClose)
1382 {
1383     FCGX_Stream_Data *data = (FCGX_Stream_Data *)stream->data;
1384     int cLen, eLen;
1385     /*
1386      * If the buffer contains stream data, fill in the header.
1387      * Pad the record to a multiple of 8 bytes in length.  Padding
1388      * can't overflow the buffer because the buffer is a multiple
1389      * of 8 bytes in length.  If the buffer contains no stream
1390      * data, reclaim the space reserved for the header.
1391      */
1392     if(!data->rawWrite) {
1393         cLen = stream->wrNext - data->buff - sizeof(FCGI_Header);
1394         if(cLen > 0) {
1395             eLen = AlignInt8(cLen);
1396             /*
1397              * Giving the padding a well-defined value keeps Purify happy.
1398              */
1399             memset(stream->wrNext, 0, eLen - cLen);
1400             stream->wrNext += eLen - cLen;
1401             *((FCGI_Header *) data->buff)
1402                     = MakeHeader(data->type,
1403                             data->reqDataPtr->requestId, cLen, eLen - cLen);
1404         } else {
1405             stream->wrNext = data->buff;
1406         }
1407     }
1408     if(doClose) {
1409         WriteCloseRecords(stream);
1410     };
1411     if (stream->wrNext != data->buff) {
1412         data->isAnythingWritten = TRUE;
1413         if (write_it_all(data->reqDataPtr->ipcFd, (char *)data->buff, stream->wrNext - data->buff) < 0) {
1414             SetError(stream, OS_Errno);
1415             return;
1416         }
1417         stream->wrNext = data->buff;
1418     }
1419     /*
1420      * The buffer is empty.
1421      */
1422     if(!data->rawWrite) {
1423         stream->wrNext += sizeof(FCGI_Header);
1424     }
1425 }
1426
1427 /*
1428  * Return codes for Process* functions
1429  */
1430 #define STREAM_RECORD 0
1431 #define SKIP          1
1432 #define BEGIN_RECORD  2
1433 #define MGMT_RECORD   3
1434
1435 /*
1436  *----------------------------------------------------------------------
1437  *
1438  * ProcessManagementRecord --
1439  *
1440  *      Reads and responds to a management record.  The only type of
1441  *      management record this library understands is FCGI_GET_VALUES.
1442  *      The only variables that this library's FCGI_GET_VALUES
1443  *      understands are FCGI_MAX_CONNS, FCGI_MAX_REQS, and FCGI_MPXS_CONNS.
1444  *      Ignore other FCGI_GET_VALUES variables; respond to other
1445  *      management records with a FCGI_UNKNOWN_TYPE record.
1446  *
1447  *----------------------------------------------------------------------
1448  */
1449 static int ProcessManagementRecord(int type, FCGX_Stream *stream)
1450 {
1451     FCGX_Stream_Data *data = (FCGX_Stream_Data *)stream->data;
1452     ParamsPtr paramsPtr = NewParams(3);
1453     char **pPtr;
1454     char response[64]; /* 64 = 8 + 3*(1+1+14+1)* + padding */
1455     char *responseP = &response[FCGI_HEADER_LEN];
1456     char *name, value = '\0';
1457     int len, paddedLen;
1458     if(type == FCGI_GET_VALUES) {
1459         ReadParams(paramsPtr, stream);
1460         if((FCGX_GetError(stream) != 0) || (data->contentLen != 0)) {
1461             FreeParams(&paramsPtr);
1462             return FCGX_PROTOCOL_ERROR;
1463         }
1464         for (pPtr = paramsPtr->vec; pPtr < paramsPtr->cur; pPtr++) {
1465             name = *pPtr;
1466             *(strchr(name, '=')) = '\0';
1467             if(strcmp(name, FCGI_MAX_CONNS) == 0) {
1468                 value = '1';
1469             } else if(strcmp(name, FCGI_MAX_REQS) == 0) {
1470                 value = '1';
1471             } else if(strcmp(name, FCGI_MPXS_CONNS) == 0) {
1472                 value = '0';
1473             } else {
1474                 name = NULL;
1475             }
1476             if(name != NULL) {
1477                 len = strlen(name);
1478                 sprintf(responseP, "%c%c%s%c", len, 1, name, value);
1479                 responseP += len + 3;
1480             }
1481         }
1482         len = responseP - &response[FCGI_HEADER_LEN];
1483         paddedLen = AlignInt8(len);
1484         *((FCGI_Header *) response)
1485             = MakeHeader(FCGI_GET_VALUES_RESULT, FCGI_NULL_REQUEST_ID,
1486                          len, paddedLen - len);
1487         FreeParams(&paramsPtr);
1488     } else {
1489         paddedLen = len = sizeof(FCGI_UnknownTypeBody);
1490         ((FCGI_UnknownTypeRecord *) response)->header
1491             = MakeHeader(FCGI_UNKNOWN_TYPE, FCGI_NULL_REQUEST_ID,
1492                          len, 0);
1493         ((FCGI_UnknownTypeRecord *) response)->body
1494             = MakeUnknownTypeBody(type);
1495     }
1496     if (write_it_all(data->reqDataPtr->ipcFd, response, FCGI_HEADER_LEN + paddedLen) < 0) {
1497         SetError(stream, OS_Errno);
1498         return -1;
1499     }
1500
1501     return MGMT_RECORD;
1502 }
1503
1504 /*
1505  *----------------------------------------------------------------------
1506  *
1507  * ProcessBeginRecord --
1508  *
1509  *      Reads an FCGI_BEGIN_REQUEST record.
1510  *
1511  * Results:
1512  *      BEGIN_RECORD for normal return.  FCGX_PROTOCOL_ERROR for
1513  *      protocol error.  SKIP for attempt to multiplex
1514  *      connection.  -1 for error from write (errno in stream).
1515  *
1516  * Side effects:
1517  *      In case of BEGIN_RECORD return, stores requestId, role,
1518  *      keepConnection values, and sets isBeginProcessed = TRUE.
1519  *
1520  *----------------------------------------------------------------------
1521  */
1522 static int ProcessBeginRecord(int requestId, FCGX_Stream *stream)
1523 {
1524     FCGX_Stream_Data *data = (FCGX_Stream_Data *)stream->data;
1525     FCGI_BeginRequestBody body;
1526     if(requestId == 0 || data->contentLen != sizeof(body)) {
1527         return FCGX_PROTOCOL_ERROR;
1528     }
1529     if(data->reqDataPtr->isBeginProcessed) {
1530         /*
1531          * The Web server is multiplexing the connection.  This library
1532          * doesn't know how to handle multiplexing, so respond with
1533          * FCGI_END_REQUEST{protocolStatus = FCGI_CANT_MPX_CONN}
1534          */
1535         FCGI_EndRequestRecord endRequestRecord;
1536         endRequestRecord.header = MakeHeader(FCGI_END_REQUEST,
1537                 requestId, sizeof(endRequestRecord.body), 0);
1538         endRequestRecord.body
1539                 = MakeEndRequestBody(0, FCGI_CANT_MPX_CONN);
1540         if (write_it_all(data->reqDataPtr->ipcFd, (char *)&endRequestRecord, sizeof(endRequestRecord)) < 0) {
1541             SetError(stream, OS_Errno);
1542             return -1;
1543         }
1544
1545         return SKIP;
1546     }
1547     /*
1548      * Accept this new request.  Read the record body.
1549      */
1550     data->reqDataPtr->requestId = requestId;
1551     if(FCGX_GetStr((char *) &body, sizeof(body), stream)
1552             != sizeof(body)) {
1553         return FCGX_PROTOCOL_ERROR;
1554     }
1555     data->reqDataPtr->keepConnection = (body.flags & FCGI_KEEP_CONN);
1556     data->reqDataPtr->role = (body.roleB1 << 8) + body.roleB0;
1557     data->reqDataPtr->isBeginProcessed = TRUE;
1558     return BEGIN_RECORD;
1559 }
1560
1561 /*
1562  *----------------------------------------------------------------------
1563  *
1564  * ProcessHeader --
1565  *
1566  *      Interprets FCGI_Header.  Processes FCGI_BEGIN_REQUEST and
1567  *      management records here; extracts information from stream
1568  *      records (FCGI_PARAMS, FCGI_STDIN) into stream.
1569  *
1570  * Results:
1571  *      >= 0 for a normal return, < 0 for error
1572  *
1573  * Side effects:
1574  *      XXX: Many (more than there used to be).
1575  *      If !stream->isRequestIdSet, ProcessHeader initializes
1576  *      stream->requestId from header and sets stream->isRequestIdSet
1577  *      to TRUE.  ProcessHeader also sets stream->contentLen to header's
1578  *      contentLength, and sets stream->paddingLen to the header's
1579  *      paddingLength.
1580  *
1581  *----------------------------------------------------------------------
1582  */
1583 static int ProcessHeader(FCGI_Header header, FCGX_Stream *stream)
1584 {
1585     FCGX_Stream_Data *data = (FCGX_Stream_Data *)stream->data;
1586     int requestId;
1587     if(header.version != FCGI_VERSION_1) {
1588         return FCGX_UNSUPPORTED_VERSION;
1589     }
1590     requestId =        (header.requestIdB1 << 8)
1591                          + header.requestIdB0;
1592     data->contentLen = (header.contentLengthB1 << 8)
1593                          + header.contentLengthB0;
1594     data->paddingLen = header.paddingLength;
1595     if(header.type == FCGI_BEGIN_REQUEST) {
1596         return ProcessBeginRecord(requestId, stream);
1597     }
1598     if(requestId  == FCGI_NULL_REQUEST_ID) {
1599         return ProcessManagementRecord(header.type, stream);
1600     }
1601     if(requestId != data->reqDataPtr->requestId) {
1602         return SKIP;
1603     }
1604     if(header.type != data->type) {
1605         return FCGX_PROTOCOL_ERROR;
1606     }
1607     return STREAM_RECORD;
1608 }
1609
1610 /*
1611  *----------------------------------------------------------------------
1612  *
1613  * FillBuffProc --
1614  *
1615  *      Reads bytes from the ipcFd, supplies bytes to a stream client.
1616  *
1617  *----------------------------------------------------------------------
1618  */
1619 static void FillBuffProc(FCGX_Stream *stream)
1620 {
1621     FCGX_Stream_Data *data = (FCGX_Stream_Data *)stream->data;
1622     FCGI_Header header;
1623     int headerLen = 0;
1624     int status, count;
1625
1626     for (;;) {
1627         /*
1628          * If data->buff is empty, do a read.
1629          */
1630         if(stream->rdNext == data->buffStop) {
1631             count = OS_Read(data->reqDataPtr->ipcFd, (char *)data->buff,
1632                             data->bufflen);
1633             if(count <= 0) {
1634                 SetError(stream, (count == 0 ? FCGX_PROTOCOL_ERROR : OS_Errno));
1635                 return;
1636             }
1637             stream->rdNext = data->buff;
1638             data->buffStop = data->buff + count;
1639         }
1640         /*
1641          * Now data->buff is not empty.  If the current record contains
1642          * more content bytes, deliver all that are present in data->buff.
1643          */
1644         if(data->contentLen > 0) {
1645             count = min(data->contentLen, data->buffStop - stream->rdNext);
1646             data->contentLen -= count;
1647             if(!data->skip) {
1648                 stream->wrNext = stream->stop = stream->rdNext + count;
1649                 return;
1650             } else {
1651                 stream->rdNext += count;
1652                 if(data->contentLen > 0) {
1653                     continue;
1654                 } else {
1655                     data->skip = FALSE;
1656                 }
1657             }
1658         }
1659         /*
1660          * If the current record (whose content has been fully consumed by
1661          * the client) was padded, skip over the padding bytes.
1662          */
1663         if(data->paddingLen > 0) {
1664             count = min(data->paddingLen, data->buffStop - stream->rdNext);
1665             data->paddingLen -= count;
1666             stream->rdNext += count;
1667             if(data->paddingLen > 0) {
1668                 continue;
1669             }
1670         }
1671         /*
1672          * All done with the current record, including the padding.
1673          * If we're in a recursive call from ProcessHeader, deliver EOF.
1674          */
1675         if(data->eorStop) {
1676             stream->stop = stream->rdNext;
1677             stream->isClosed = TRUE;
1678             return;
1679         }
1680         /*
1681          * Fill header with bytes from the input buffer.
1682          */
1683         count = min((int)sizeof(header) - headerLen,
1684                         data->buffStop - stream->rdNext);
1685         memcpy(((char *)(&header)) + headerLen, stream->rdNext, count);
1686         headerLen += count;
1687         stream->rdNext += count;
1688         if(headerLen < sizeof(header)) {
1689             continue;
1690         };
1691         headerLen = 0;
1692         /*
1693          * Interpret header.  eorStop prevents ProcessHeader from reading
1694          * past the end-of-record when using stream to read content.
1695          */
1696         data->eorStop = TRUE;
1697         stream->stop = stream->rdNext;
1698         status = ProcessHeader(header, stream);
1699         data->eorStop = FALSE;
1700         stream->isClosed = FALSE;
1701         switch(status) {
1702             case STREAM_RECORD:
1703                 /*
1704                  * If this stream record header marked the end of stream
1705                  * data deliver EOF to the stream client, otherwise loop
1706                  * and deliver data.
1707                  *
1708                  * XXX: If this is final stream and
1709                  * stream->rdNext != data->buffStop, buffered
1710                  * data is next request (server pipelining)?
1711                  */
1712                 if(data->contentLen == 0) {
1713                     stream->wrNext = stream->stop = stream->rdNext;
1714                     stream->isClosed = TRUE;
1715                     return;
1716                 }
1717                 break;
1718             case SKIP:
1719                 data->skip = TRUE;
1720                 break;
1721             case BEGIN_RECORD:
1722                 /*
1723                  * If this header marked the beginning of a new
1724                  * request, return role information to caller.
1725                  */
1726                 return;
1727                 break;
1728             case MGMT_RECORD:
1729                 break;
1730             default:
1731                 ASSERT(status < 0);
1732                 SetError(stream, status);
1733                 return;
1734                 break;
1735         }
1736     }
1737 }
1738
1739 /*
1740  *----------------------------------------------------------------------
1741  *
1742  * NewStream --
1743  *
1744  *      Creates a stream to read or write from an open ipcFd.
1745  *      The stream performs reads/writes of up to bufflen bytes.
1746  *
1747  *----------------------------------------------------------------------
1748  */
1749 static FCGX_Stream *NewStream(
1750         FCGX_Request *reqDataPtr, int bufflen, int isReader, int streamType)
1751 {
1752     /*
1753      * XXX: It would be a lot cleaner to have a NewStream that only
1754      * knows about the type FCGX_Stream, with all other
1755      * necessary data passed in.  It appears that not just
1756      * data and the two procs are needed for initializing stream,
1757      * but also data->buff and data->buffStop.  This has implications
1758      * for procs that want to swap buffers, too.
1759      */
1760     FCGX_Stream *stream = (FCGX_Stream *)Malloc(sizeof(FCGX_Stream));
1761     FCGX_Stream_Data *data = (FCGX_Stream_Data *)Malloc(sizeof(FCGX_Stream_Data));
1762     data->reqDataPtr = reqDataPtr;
1763     bufflen = AlignInt8(min(max(bufflen, 32), FCGI_MAX_LENGTH + 1));
1764     data->bufflen = bufflen;
1765     data->mBuff = (unsigned char *)Malloc(bufflen);
1766     data->buff = AlignPtr8(data->mBuff);
1767     if(data->buff != data->mBuff) {
1768         data->bufflen -= 8;
1769     }
1770     if(isReader) {
1771         data->buffStop = data->buff;
1772     } else {
1773         data->buffStop = data->buff + data->bufflen;
1774     }
1775     data->type = streamType;
1776     data->eorStop = FALSE;
1777     data->skip = FALSE;
1778     data->contentLen = 0;
1779     data->paddingLen = 0;
1780     data->isAnythingWritten = FALSE;
1781     data->rawWrite = FALSE;
1782
1783     stream->data = data;
1784     stream->isReader = isReader;
1785     stream->isClosed = FALSE;
1786     stream->wasFCloseCalled = FALSE;
1787     stream->FCGI_errno = 0;
1788     if(isReader) {
1789         stream->fillBuffProc = FillBuffProc;
1790         stream->emptyBuffProc = NULL;
1791         stream->rdNext = data->buff;
1792         stream->stop = stream->rdNext;
1793         stream->stopUnget = data->buff;
1794         stream->wrNext = stream->stop;
1795     } else {
1796         stream->fillBuffProc = NULL;
1797         stream->emptyBuffProc = EmptyBuffProc;
1798         stream->wrNext = data->buff + sizeof(FCGI_Header);
1799         stream->stop = data->buffStop;
1800         stream->stopUnget = NULL;
1801         stream->rdNext = stream->stop;
1802     }
1803     return stream;
1804 }
1805
1806 /*
1807  *----------------------------------------------------------------------
1808  *
1809  * FCGX_FreeStream --
1810  *
1811  *      Frees all storage allocated when *streamPtr was created,
1812  *      and nulls out *streamPtr.
1813  *
1814  *----------------------------------------------------------------------
1815  */
1816 void FCGX_FreeStream(FCGX_Stream **streamPtr)
1817 {
1818     FCGX_Stream *stream = *streamPtr;
1819     FCGX_Stream_Data *data;
1820     if(stream == NULL) {
1821         return;
1822     }
1823     data = (FCGX_Stream_Data *)stream->data;
1824     data->reqDataPtr = NULL;
1825     free(data->mBuff);
1826     free(data);
1827     free(stream);
1828     *streamPtr = NULL;
1829 }
1830
1831 /*
1832  *----------------------------------------------------------------------
1833  *
1834  * SetReaderType --
1835  *
1836  *      Re-initializes the stream to read data of the specified type.
1837  *
1838  *----------------------------------------------------------------------
1839  */
1840 static FCGX_Stream *SetReaderType(FCGX_Stream *stream, int streamType)
1841 {
1842     FCGX_Stream_Data *data = (FCGX_Stream_Data *)stream->data;
1843     ASSERT(stream->isReader);
1844     data->type = streamType;
1845     data->eorStop = FALSE;
1846     data->skip = FALSE;
1847     data->contentLen = 0;
1848     data->paddingLen = 0;
1849     stream->wrNext = stream->stop = stream->rdNext;
1850     stream->isClosed = FALSE;
1851     return stream;
1852 }
1853
1854 /*
1855  *----------------------------------------------------------------------
1856  *
1857  * NewReader --
1858  *
1859  *      Creates a stream to read streamType records for the given
1860  *      request.  The stream performs OS reads of up to bufflen bytes.
1861  *
1862  *----------------------------------------------------------------------
1863  */
1864 static FCGX_Stream *NewReader(FCGX_Request *reqDataPtr, int bufflen, int streamType)
1865 {
1866     return NewStream(reqDataPtr, bufflen, TRUE, streamType);
1867 }
1868
1869 /*
1870  *----------------------------------------------------------------------
1871  *
1872  * NewWriter --
1873  *
1874  *      Creates a stream to write streamType FastCGI records, using
1875  *      the ipcFd and RequestId contained in *reqDataPtr.
1876  *      The stream performs OS writes of up to bufflen bytes.
1877  *
1878  *----------------------------------------------------------------------
1879  */
1880 static FCGX_Stream *NewWriter(FCGX_Request *reqDataPtr, int bufflen, int streamType)
1881 {
1882     return NewStream(reqDataPtr, bufflen, FALSE, streamType);
1883 }
1884
1885 /*
1886  *----------------------------------------------------------------------
1887  *
1888  * FCGX_CreateWriter --
1889  *
1890  *      Creates a stream to write streamType FastCGI records, using
1891  *      the given ipcFd and request Id.  This function is provided
1892  *      for use by cgi-fcgi.  In order to be defensive against misuse,
1893  *      this function leaks a little storage; cgi-fcgi doesn't care.
1894  *
1895  *----------------------------------------------------------------------
1896  */
1897 FCGX_Stream *FCGX_CreateWriter(
1898         int ipcFd,
1899         int requestId,
1900         int bufflen,
1901         int streamType)
1902 {
1903     FCGX_Request *reqDataPtr = (FCGX_Request *)Malloc(sizeof(FCGX_Request));
1904     reqDataPtr->ipcFd = ipcFd;
1905     reqDataPtr->requestId = requestId;
1906     /*
1907      * Suppress writing an FCGI_END_REQUEST record.
1908      */
1909     reqDataPtr->nWriters = 2;
1910     return NewWriter(reqDataPtr, bufflen, streamType);
1911 }
1912
1913 /*
1914  *======================================================================
1915  * Control
1916  *======================================================================
1917  */
1918
1919 /*
1920  *----------------------------------------------------------------------
1921  *
1922  * FCGX_IsCGI --
1923  *
1924  *      This routine determines if the process is running as a CGI or
1925  *      FastCGI process.  The distinction is made by determining whether
1926  *      FCGI_LISTENSOCK_FILENO is a listener ipcFd or the end of a
1927  *      pipe (ie. standard in).
1928  *
1929  * Results:
1930  *      TRUE if the process is a CGI process, FALSE if FastCGI.
1931  *
1932  *----------------------------------------------------------------------
1933  */
1934 int FCGX_IsCGI(void)
1935 {
1936     if (isFastCGI != -1) {
1937         return !isFastCGI;
1938     }
1939
1940     if (!libInitialized) {
1941         int rc = FCGX_Init();
1942         if (rc) {
1943             /* exit() isn't great, but hey */
1944             exit((rc < 0) ? rc : -rc);
1945         }
1946     }
1947
1948     isFastCGI = OS_IsFcgi(FCGI_LISTENSOCK_FILENO);
1949
1950     return !isFastCGI;
1951 }
1952
1953 /*
1954  *----------------------------------------------------------------------
1955  *
1956  * FCGX_Finish --
1957  *
1958  *      Finishes the current request from the HTTP server.
1959  *
1960  * Side effects:
1961  *
1962  *      Finishes the request accepted by (and frees any
1963  *      storage allocated by) the previous call to FCGX_Accept.
1964  *
1965  *      DO NOT retain pointers to the envp array or any strings
1966  *      contained in it (e.g. to the result of calling FCGX_GetParam),
1967  *      since these will be freed by the next call to FCGX_Finish
1968  *      or FCGX_Accept.
1969  *
1970  *----------------------------------------------------------------------
1971  */
1972
1973 void FCGX_Finish(void)
1974 {
1975     FCGX_Finish_r(&the_request);
1976 }
1977
1978 /*
1979  *----------------------------------------------------------------------
1980  *
1981  * FCGX_Finish_r --
1982  *
1983  *      Finishes the current request from the HTTP server.
1984  *
1985  * Side effects:
1986  *
1987  *      Finishes the request accepted by (and frees any
1988  *      storage allocated by) the previous call to FCGX_Accept.
1989  *
1990  *      DO NOT retain pointers to the envp array or any strings
1991  *      contained in it (e.g. to the result of calling FCGX_GetParam),
1992  *      since these will be freed by the next call to FCGX_Finish
1993  *      or FCGX_Accept.
1994  *
1995  *----------------------------------------------------------------------
1996  */
1997 void FCGX_Finish_r(FCGX_Request *reqDataPtr)
1998 {
1999     int close;
2000
2001     if (reqDataPtr == NULL) {
2002         return;
2003     }
2004
2005     close = !reqDataPtr->keepConnection;
2006
2007     /* This should probably use a 'status' member instead of 'in' */
2008     if (reqDataPtr->in) {
2009         close |= FCGX_FClose(reqDataPtr->err);
2010         close |= FCGX_FClose(reqDataPtr->out);
2011
2012         close |= FCGX_GetError(reqDataPtr->in);
2013     }
2014
2015     FCGX_Free(reqDataPtr, close);
2016 }
2017
2018 void FCGX_Free(FCGX_Request * request, int close)
2019 {
2020     if (request == NULL) 
2021         return;
2022
2023     FCGX_FreeStream(&request->in);
2024     FCGX_FreeStream(&request->out);
2025     FCGX_FreeStream(&request->err);
2026     FreeParams(&request->paramsPtr);
2027
2028     if (close) {
2029         OS_IpcClose(request->ipcFd);
2030         request->ipcFd = -1;
2031     }
2032 }
2033
2034 int FCGX_OpenSocket(const char *path, int backlog)
2035 {
2036     int rc = OS_CreateLocalIpcFd(path, backlog);
2037     if (rc == FCGI_LISTENSOCK_FILENO && isFastCGI == 0) {
2038         /* XXX probably need to call OS_LibInit() again for Win */
2039         isFastCGI = 1;
2040     }
2041     return rc;
2042 }
2043
2044 int FCGX_InitRequest(FCGX_Request *request, int sock, int flags)
2045 {
2046     memset(request, 0, sizeof(FCGX_Request));
2047
2048     /* @@@ Should check that sock is open and listening */
2049     request->listen_sock = sock;
2050
2051     /* @@@ Should validate against "known" flags */
2052     request->flags = flags;
2053
2054     request->ipcFd = -1;
2055
2056     return 0;
2057 }
2058
2059 /*
2060  *----------------------------------------------------------------------
2061  *
2062  * FCGX_Init --
2063  *
2064  *      Initilize the FCGX library.  This is called by FCGX_Accept()
2065  *      but must be called by the user when using FCGX_Accept_r().
2066  *
2067  * Results:
2068  *          0 for successful call.
2069  *
2070  *----------------------------------------------------------------------
2071  */
2072 int FCGX_Init(void)
2073 {
2074     char *p;
2075
2076     if (libInitialized) {
2077         return 0;
2078     }
2079
2080     FCGX_InitRequest(&the_request, FCGI_LISTENSOCK_FILENO, 0);
2081
2082     if (OS_LibInit(NULL) == -1) {
2083         return OS_Errno ? OS_Errno : -9997;
2084     }
2085
2086     p = getenv("FCGI_WEB_SERVER_ADDRS");
2087     webServerAddressList = p ? StringCopy(p) : NULL;
2088
2089     libInitialized = 1;
2090     return 0;
2091 }
2092
2093 /*
2094  *----------------------------------------------------------------------
2095  *
2096  * FCGX_Accept --
2097  *
2098  *      Accepts a new request from the HTTP server.
2099  *
2100  * Results:
2101  *      0 for successful call, -1 for error.
2102  *
2103  * Side effects:
2104  *
2105  *      Finishes the request accepted by (and frees any
2106  *      storage allocated by) the previous call to FCGX_Accept.
2107  *      Creates input, output, and error streams and
2108  *      assigns them to *in, *out, and *err respectively.
2109  *      Creates a parameters data structure to be accessed
2110  *      via getenv(3) (if assigned to environ) or by FCGX_GetParam
2111  *      and assigns it to *envp.
2112  *
2113  *      DO NOT retain pointers to the envp array or any strings
2114  *      contained in it (e.g. to the result of calling FCGX_GetParam),
2115  *      since these will be freed by the next call to FCGX_Finish
2116  *      or FCGX_Accept.
2117  *
2118  *----------------------------------------------------------------------
2119  */
2120
2121 int FCGX_Accept(
2122         FCGX_Stream **in,
2123         FCGX_Stream **out,
2124         FCGX_Stream **err,
2125         FCGX_ParamArray *envp)
2126 {
2127     int rc;
2128
2129     if (! libInitialized) {
2130         rc = FCGX_Init();
2131         if (rc) {
2132             return rc;
2133         }
2134     }
2135
2136     rc = FCGX_Accept_r(&the_request);
2137
2138     *in = the_request.in;
2139     *out = the_request.out;
2140     *err = the_request.err;
2141     *envp = the_request.envp;
2142
2143     return rc;
2144 }
2145
2146 /*
2147  *----------------------------------------------------------------------
2148  *
2149  * FCGX_Accept_r --
2150  *
2151  *      Accepts a new request from the HTTP server.
2152  *
2153  * Results:
2154  *      0 for successful call, -1 for error.
2155  *
2156  * Side effects:
2157  *
2158  *      Finishes the request accepted by (and frees any
2159  *      storage allocated by) the previous call to FCGX_Accept.
2160  *      Creates input, output, and error streams and
2161  *      assigns them to *in, *out, and *err respectively.
2162  *      Creates a parameters data structure to be accessed
2163  *      via getenv(3) (if assigned to environ) or by FCGX_GetParam
2164  *      and assigns it to *envp.
2165  *
2166  *      DO NOT retain pointers to the envp array or any strings
2167  *      contained in it (e.g. to the result of calling FCGX_GetParam),
2168  *      since these will be freed by the next call to FCGX_Finish
2169  *      or FCGX_Accept.
2170  *
2171  *----------------------------------------------------------------------
2172  */
2173 int FCGX_Accept_r(FCGX_Request *reqDataPtr)
2174 {
2175     if (!libInitialized) {
2176         return -9998;
2177     }
2178
2179     /* Finish the current request, if any. */
2180     FCGX_Finish_r(reqDataPtr);
2181
2182     for (;;) {
2183         /*
2184          * If a connection isn't open, accept a new connection (blocking).
2185          * If an OS error occurs in accepting the connection,
2186          * return -1 to the caller, who should exit.
2187          */
2188         if (reqDataPtr->ipcFd < 0) {
2189             int fail_on_intr = reqDataPtr->flags & FCGI_FAIL_ACCEPT_ON_INTR;
2190
2191             reqDataPtr->ipcFd = OS_Accept(reqDataPtr->listen_sock, fail_on_intr, webServerAddressList);
2192             if (reqDataPtr->ipcFd < 0) {
2193                 return (errno > 0) ? (0 - errno) : -9999;
2194             }
2195         }
2196         /*
2197          * A connection is open.  Read from the connection in order to
2198          * get the request's role and environment.  If protocol or other
2199          * errors occur, close the connection and try again.
2200          */
2201         reqDataPtr->isBeginProcessed = FALSE;
2202         reqDataPtr->in = NewReader(reqDataPtr, 8192, 0);
2203         FillBuffProc(reqDataPtr->in);
2204         if(!reqDataPtr->isBeginProcessed) {
2205             goto TryAgain;
2206         }
2207         {
2208             char *roleStr;
2209             switch(reqDataPtr->role) {
2210                 case FCGI_RESPONDER:
2211                     roleStr = "FCGI_ROLE=RESPONDER";
2212                     break;
2213                 case FCGI_AUTHORIZER:
2214                     roleStr = "FCGI_ROLE=AUTHORIZER";
2215                     break;
2216                 case FCGI_FILTER:
2217                     roleStr = "FCGI_ROLE=FILTER";
2218                     break;
2219                 default:
2220                     goto TryAgain;
2221             }
2222             reqDataPtr->paramsPtr = NewParams(30);
2223             PutParam(reqDataPtr->paramsPtr, StringCopy(roleStr));
2224         }
2225         SetReaderType(reqDataPtr->in, FCGI_PARAMS);
2226         if(ReadParams(reqDataPtr->paramsPtr, reqDataPtr->in) >= 0) {
2227             /*
2228              * Finished reading the environment.  No errors occurred, so
2229              * leave the connection-retry loop.
2230              */
2231             break;
2232         }
2233
2234         /*
2235          * Close the connection and try again.
2236          */
2237 TryAgain:
2238         FCGX_Free(reqDataPtr, 1);
2239
2240     } /* for (;;) */
2241     /*
2242      * Build the remaining data structures representing the new
2243      * request and return successfully to the caller.
2244      */
2245     SetReaderType(reqDataPtr->in, FCGI_STDIN);
2246     reqDataPtr->out = NewWriter(reqDataPtr, 8192, FCGI_STDOUT);
2247     reqDataPtr->err = NewWriter(reqDataPtr, 512, FCGI_STDERR);
2248     reqDataPtr->nWriters = 2;
2249     reqDataPtr->envp = reqDataPtr->paramsPtr->vec;
2250     return 0;
2251 }
2252
2253 /*
2254  *----------------------------------------------------------------------
2255  *
2256  * FCGX_StartFilterData --
2257  *
2258  *      stream is an input stream for a FCGI_FILTER request.
2259  *      stream is positioned at EOF on FCGI_STDIN.
2260  *      Repositions stream to the start of FCGI_DATA.
2261  *      If the preconditions are not met (e.g. FCGI_STDIN has not
2262  *      been read to EOF) sets the stream error code to
2263  *      FCGX_CALL_SEQ_ERROR.
2264  *
2265  * Results:
2266  *      0 for a normal return, < 0 for error
2267  *
2268  *----------------------------------------------------------------------
2269  */
2270
2271 int FCGX_StartFilterData(FCGX_Stream *stream)
2272 {
2273     FCGX_Stream_Data *data = (FCGX_Stream_Data *)stream->data;
2274     if(data->reqDataPtr->role != FCGI_FILTER
2275             || !stream->isReader
2276             || !stream->isClosed
2277             || data->type != FCGI_STDIN) {
2278         SetError(stream, FCGX_CALL_SEQ_ERROR);
2279         return -1;
2280     }
2281     SetReaderType(stream, FCGI_DATA);
2282     return 0;
2283 }
2284
2285 /*
2286  *----------------------------------------------------------------------
2287  *
2288  * FCGX_SetExitStatus --
2289  *
2290  *      Sets the exit status for stream's request. The exit status
2291  *      is the status code the request would have exited with, had
2292  *      the request been run as a CGI program.  You can call
2293  *      SetExitStatus several times during a request; the last call
2294  *      before the request ends determines the value.
2295  *
2296  *----------------------------------------------------------------------
2297  */
2298
2299 void FCGX_SetExitStatus(int status, FCGX_Stream *stream)
2300 {
2301     FCGX_Stream_Data *data = (FCGX_Stream_Data *)stream->data;
2302     data->reqDataPtr->appStatus = status;
2303 }
2304