Remove uneeded code that was causing gcc to warn
[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.28 2001/08/30 22:27:51 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 static void *Malloc(size_t size)
75 {
76     void *result = malloc(size);
77     ASSERT(size == 0 || result != NULL);
78     return result;
79 }
80
81 static char *StringCopy(char *str)
82 {
83     int strLen = strlen(str);
84     char *newString = (char *)Malloc(strLen + 1);
85     memcpy(newString, str, strLen);
86     newString[strLen] = '\000';
87     return newString;
88 }
89
90
91 /*
92  *----------------------------------------------------------------------
93  *
94  * FCGX_GetChar --
95  *
96  *      Reads a byte from the input stream and returns it.
97  *
98  * Results:
99  *      The byte, or EOF (-1) if the end of input has been reached.
100  *
101  *----------------------------------------------------------------------
102  */
103 int FCGX_GetChar(FCGX_Stream *stream)
104 {
105     if(stream->rdNext != stream->stop)
106         return *stream->rdNext++;
107     if(stream->isClosed || !stream->isReader)
108         return EOF;
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 */
114     return EOF;
115 }
116
117 /*
118  *----------------------------------------------------------------------
119  *
120  * FCGX_GetStr --
121  *
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.
125  *
126  * Results:
127  *      Number of bytes read.  If result is smaller than n,
128  *      the end of input has been reached.
129  *
130  *----------------------------------------------------------------------
131  */
132 int FCGX_GetStr(char *str, int n, FCGX_Stream *stream)
133 {
134     int m, bytesMoved;
135
136     if(n <= 0) {
137         return 0;
138     }
139     /*
140      * Fast path: n bytes are already available
141      */
142     if(n <= (stream->stop - stream->rdNext)) {
143         memcpy(str, stream->rdNext, n);
144         stream->rdNext += n;
145         return n;
146     }
147     /*
148      * General case: stream is closed or buffer fill procedure
149      * needs to be called
150      */
151     bytesMoved = 0;
152     for (;;) {
153         if(stream->rdNext != stream->stop) {
154             m = min(n - bytesMoved, stream->stop - stream->rdNext);
155             memcpy(str, stream->rdNext, m);
156             bytesMoved += m;
157             stream->rdNext += m;
158             if(bytesMoved == n)
159                 return bytesMoved;
160             str += m;
161         }
162         if(stream->isClosed || !stream->isReader)
163             return bytesMoved;
164         stream->fillBuffProc(stream);
165         stream->stopUnget = stream->rdNext;
166     }
167 }
168
169 /*
170  *----------------------------------------------------------------------
171  *
172  * FCGX_GetLine --
173  *
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.
179  *
180  * Results:
181  *      NULL if EOF is the first thing read from the input stream,
182  *      str otherwise.
183  *
184  *----------------------------------------------------------------------
185  */
186 char *FCGX_GetLine(char *str, int n, FCGX_Stream *stream)
187 {
188     int c;
189     char *p = str;
190
191     n--;
192     while (n > 0) {
193         c = FCGX_GetChar(stream);
194         if(c == EOF) {
195             if(p == str)
196                 return NULL;
197             else
198                 break;
199         }
200         *p++ = (char) c;
201         n--;
202         if(c == '\n')
203             break;
204     }
205     *p = '\0';
206     return str;
207 }
208
209 /*
210  *----------------------------------------------------------------------
211  *
212  * FCGX_UnGetChar --
213  *
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.
217  *
218  * Results:
219  *      Returns c if the pushback succeeded, EOF if not.
220  *
221  *----------------------------------------------------------------------
222  */
223 int FCGX_UnGetChar(int c, FCGX_Stream *stream) {
224     if(c == EOF
225             || stream->isClosed
226             || !stream->isReader
227             || stream->rdNext == stream->stopUnget)
228         return EOF;
229     --(stream->rdNext);
230     *stream->rdNext = (unsigned char) c;
231     return c;
232 }
233
234 /*
235  *----------------------------------------------------------------------
236  *
237  * FCGX_HasSeenEOF --
238  *
239  *      Returns EOF if end-of-file has been detected while reading
240  *      from stream; otherwise returns 0.
241  *
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.
246  *
247  * Results:
248  *      EOF if end-of-file has been detected, 0 if not.
249  *
250  *----------------------------------------------------------------------
251  */
252 int FCGX_HasSeenEOF(FCGX_Stream *stream) {
253     return (stream->isClosed) ? EOF : 0;
254 }
255
256 /*
257  *----------------------------------------------------------------------
258  *
259  * FCGX_PutChar --
260  *
261  *      Writes a byte to the output stream.
262  *
263  * Results:
264  *      The byte, or EOF (-1) if an error occurred.
265  *
266  *----------------------------------------------------------------------
267  */
268 int FCGX_PutChar(int c, FCGX_Stream *stream)
269 {
270     if(stream->wrNext != stream->stop)
271         return (*stream->wrNext++ = (unsigned char) c);
272     if(stream->isClosed || stream->isReader)
273         return EOF;
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 */
278     return EOF;
279 }
280
281 /*
282  *----------------------------------------------------------------------
283  *
284  * FCGX_PutStr --
285  *
286  *      Writes n consecutive bytes from the character array str
287  *      into the output stream.  Performs no interpretation
288  *      of the output bytes.
289  *
290  * Results:
291  *      Number of bytes written (n) for normal return,
292  *      EOF (-1) if an error occurred.
293  *
294  *----------------------------------------------------------------------
295  */
296 int FCGX_PutStr(const char *str, int n, FCGX_Stream *stream)
297 {
298     int m, bytesMoved;
299
300     /*
301      * Fast path: room for n bytes in the buffer
302      */
303     if(n <= (stream->stop - stream->wrNext)) {
304         memcpy(stream->wrNext, str, n);
305         stream->wrNext += n;
306         return n;
307     }
308     /*
309      * General case: stream is closed or buffer empty procedure
310      * needs to be called
311      */
312     bytesMoved = 0;
313     for (;;) {
314         if(stream->wrNext != stream->stop) {
315             m = min(n - bytesMoved, stream->stop - stream->wrNext);
316             memcpy(stream->wrNext, str, m);
317             bytesMoved += m;
318             stream->wrNext += m;
319             if(bytesMoved == n)
320                 return bytesMoved;
321             str += m;
322         }
323         if(stream->isClosed || stream->isReader)
324             return -1;
325         stream->emptyBuffProc(stream, FALSE);
326     }
327 }
328
329 /*
330  *----------------------------------------------------------------------
331  *
332  * FCGX_PutS --
333  *
334  *      Writes a character string to the output stream.
335  *
336  * Results:
337  *      number of bytes written for normal return,
338  *      EOF (-1) if an error occurred.
339  *
340  *----------------------------------------------------------------------
341  */
342 int FCGX_PutS(const char *str, FCGX_Stream *stream)
343 {
344     return FCGX_PutStr(str, strlen(str), stream);
345 }
346
347 /*
348  *----------------------------------------------------------------------
349  *
350  * FCGX_FPrintF --
351  *
352  *      Performs output formatting and writes the results
353  *      to the output stream.
354  *
355  * Results:
356  *      number of bytes written for normal return,
357  *      EOF (-1) if an error occurred.
358  *
359  *----------------------------------------------------------------------
360  */
361 int FCGX_FPrintF(FCGX_Stream *stream, const char *format, ...)
362 {
363     int result;
364     va_list ap;
365     va_start(ap, format);
366     result = FCGX_VFPrintF(stream, format, ap);
367     va_end(ap);
368     return result;
369 }
370
371 /*
372  *----------------------------------------------------------------------
373  *
374  * FCGX_VFPrintF --
375  *
376  *      Performs output formatting and writes the results
377  *      to the output stream.
378  *
379  * Results:
380  *      number of bytes written for normal return,
381  *      EOF (-1) if an error occurred.
382  *
383  *----------------------------------------------------------------------
384  */
385
386 #define PRINTF_BUFFLEN 100
387     /*
388      * More than sufficient space for all unmodified conversions
389      * except %s and %f.
390      */
391 #define FMT_BUFFLEN 25
392     /*
393      * Max size of a format specifier is 1 + 5 + 7 + 7 + 2 + 1 + slop
394      */
395 static void CopyAndAdvance(char **destPtr, char **srcPtr, int n);
396
397 int FCGX_VFPrintF(FCGX_Stream *stream, const char *format, va_list arg)
398 {
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;
403     int streamCount = 0;
404     char fmtBuff[FMT_BUFFLEN];
405     char buff[PRINTF_BUFFLEN];
406
407     int intArg;
408     short shortArg;
409     long longArg;
410     unsigned unsignedArg;
411     unsigned long uLongArg;
412     unsigned short uShortArg;
413     char *charPtrArg = NULL;
414     void *voidPtrArg;
415     int *intPtrArg;
416     long *longPtrArg;
417     short *shortPtrArg;
418     double doubleArg = 0.0;
419     LONG_DOUBLE lDoubleArg = 0.0L;
420
421     fmtBuff[0] = '%';
422     f = (char *) format;
423     fStop = f + strlen(f);
424     while (f != fStop) {
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)
429                 goto ErrorReturn;
430             streamCount += percentPtr - f;
431             f = percentPtr;
432             if(f == fStop) break;
433         }
434         fastPath = TRUE;
435         /*
436          * The following loop always executes either once or twice.
437          */
438         for (;;) {
439             if(fastPath) {
440                 /*
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.
450                  */
451                 op = *(percentPtr + 1);
452                 switch(op) {
453                     case 'l':
454                     case 'L':
455                     case 'h':
456                         sizeModifier = op;
457                         op = *(percentPtr + 2);
458                         fmtBuff[1] = (char) sizeModifier;
459                         fmtBuff[2] = (char) op;
460                         fmtBuff[3] = '\0';
461                         specifierLength = 3;
462                         break;
463                     default:
464                         sizeModifier = ' ';
465                         fmtBuff[1] = (char) op;
466                         fmtBuff[2] = '\0';
467                         specifierLength = 2;
468                         break;
469                 }
470                 buffPtr = buff;
471                 buffLen = PRINTF_BUFFLEN;
472             } else {
473                 /*
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.
478                  */
479                 p = percentPtr + 1;
480                 fmtBuffPtr = &fmtBuff[1];
481                 /*
482                  * Scan flags
483                  */
484                 n = strspn(p, "-0+ #");
485                 if(n > 5)
486                     goto ErrorReturn;
487                 CopyAndAdvance(&fmtBuffPtr, &p, n);
488                 /*
489                  * Scan minimum field width
490                  */
491                 n = strspn(p, "0123456789");
492                 if(n == 0) {
493                     if(*p == '*') {
494                         minWidth = va_arg(arg, int);
495                         if(abs(minWidth) > 999999)
496                             goto ErrorReturn;
497                         /*
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.
501                          */
502                         sprintf(fmtBuffPtr, "%d", minWidth);
503                         fmtBuffPtr += strlen(fmtBuffPtr);
504                         p++;
505                     } else {
506                         minWidth = 0;
507                     }
508                 } else if(n <= 6) {
509                     minWidth = strtol(p, NULL, 10);
510                     CopyAndAdvance(&fmtBuffPtr, &p, n);
511                 } else {
512                     goto ErrorReturn;
513                 }
514                 /*
515                  * Scan precision
516                  */
517                 if(*p == '.') {
518                     CopyAndAdvance(&fmtBuffPtr, &p, 1);
519                     n = strspn(p, "0123456789");
520                     if(n == 0) {
521                         if(*p == '*') {
522                             precision = va_arg(arg, int);
523                             if(precision < 0) precision = 0;
524                             if(precision > 999999)
525                                 goto ErrorReturn;
526                         /*
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.
530                          */
531                             sprintf(fmtBuffPtr, "%d", precision);
532                             fmtBuffPtr += strlen(fmtBuffPtr);
533                             p++;
534                         } else {
535                             precision = 0;
536                         }
537                     } else if(n <= 6) {
538                         precision = strtol(p, NULL, 10);
539                         CopyAndAdvance(&fmtBuffPtr, &p, n);
540                     } else {
541                         goto ErrorReturn;
542                     }
543                 } else {
544                     precision = -1;
545                 }
546                 /*
547                  * Scan size modifier and conversion operation
548                  */
549                 switch(*p) {
550                     case 'l':
551                     case 'L':
552                     case 'h':
553                         sizeModifier = *p;
554                         CopyAndAdvance(&fmtBuffPtr, &p, 1);
555                         break;
556                     default:
557                         sizeModifier = ' ';
558                         break;
559                 }
560                 op = *p;
561                 CopyAndAdvance(&fmtBuffPtr, &p, 1);
562                 ASSERT(fmtBuffPtr - fmtBuff < FMT_BUFFLEN);
563                 *fmtBuffPtr = '\0';
564                 specifierLength = p - percentPtr;
565                 /*
566                  * Bound the required buffer size.  For s and f
567                  * conversions this requires examining the argument.
568                  */
569                 switch(op) {
570                     case 'd':
571                     case 'i':
572                     case 'u':
573                     case 'o':
574                     case 'x':
575                     case 'X':
576                     case 'c':
577                     case 'p':
578                         buffReqd = max(precision, 46);
579                         break;
580                     case 's':
581                         charPtrArg = va_arg(arg, char *);
582                         if (!charPtrArg) charPtrArg = "(null)";
583                         if(precision == -1) {
584                             buffReqd = strlen(charPtrArg);
585                         } else {
586                             p = (char *)memchr(charPtrArg, '\0', precision);
587                             buffReqd =
588                               (p == NULL) ? precision : p - charPtrArg;
589                         }
590                         break;
591                     case 'f':
592                         switch(sizeModifier) {
593                             case ' ':
594                                 doubleArg = va_arg(arg, double);
595                                                 frexp(doubleArg, &exp);
596                                 break;
597                             case 'L':
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);
602                                 break;
603                             default:
604                                 goto ErrorReturn;
605                         }
606                         if(precision == -1) precision = 6;
607                         buffReqd = precision + 3 + ((exp > 0) ? exp/3 : 0);
608                         break;
609                     case 'e':
610                     case 'E':
611                     case 'g':
612                     case 'G':
613                         if(precision == -1) precision = 6;
614                         buffReqd = precision + 8;
615                         break;
616                     case 'n':
617                     case '%':
618                     default:
619                         goto ErrorReturn;
620                         break;
621                 }
622                 buffReqd = max(buffReqd + 10, minWidth);
623                 /*
624                  * Allocate the buffer
625                  */
626                 if(buffReqd <= PRINTF_BUFFLEN) {
627                     buffPtr = buff;
628                     buffLen = PRINTF_BUFFLEN;
629                 } else {
630                     if(auxBuffPtr == NULL || buffReqd > auxBuffLen) {
631                         if(auxBuffPtr != NULL) free(auxBuffPtr);
632                         auxBuffPtr = (char *)Malloc(buffReqd);
633                         auxBuffLen = buffReqd;
634                         if(auxBuffPtr == NULL)
635                             goto ErrorReturn;
636                     }
637                     buffPtr = auxBuffPtr;
638                     buffLen = auxBuffLen;
639                 }
640             }
641             /*
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).
650              *
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.
653              */
654             performedOp = TRUE;
655             switch(op) {
656                 case 'd':
657                 case 'i':
658                     switch(sizeModifier) {
659                         case ' ':
660                             intArg = va_arg(arg, int);
661                             sprintf(buffPtr, fmtBuff, intArg);
662                             buffCount = strlen(buffPtr);
663                             break;
664                         case 'l':
665                             longArg = va_arg(arg, long);
666                             sprintf(buffPtr, fmtBuff, longArg);
667                             buffCount = strlen(buffPtr);
668                             break;
669                         case 'h':
670                             shortArg = (short) va_arg(arg, int);
671                             sprintf(buffPtr, fmtBuff, shortArg);
672                             buffCount = strlen(buffPtr);
673                             break;
674                         default:
675                             goto ErrorReturn;
676                     }
677                     break;
678                 case 'u':
679                 case 'o':
680                 case 'x':
681                 case 'X':
682                     switch(sizeModifier) {
683                         case ' ':
684                             unsignedArg = va_arg(arg, unsigned);
685                             sprintf(buffPtr, fmtBuff, unsignedArg);
686                             buffCount = strlen(buffPtr);
687                             break;
688                         case 'l':
689                             uLongArg = va_arg(arg, unsigned long);
690                             sprintf(buffPtr, fmtBuff, uLongArg);
691                             buffCount = strlen(buffPtr);
692                             break;
693                         case 'h':
694                             uShortArg = (unsigned short) va_arg(arg, int);
695                             sprintf(buffPtr, fmtBuff, uShortArg);
696                             buffCount = strlen(buffPtr);
697                             break;
698                         default:
699                             goto ErrorReturn;
700                     }
701                     break;
702                 case 'c':
703                     switch(sizeModifier) {
704                         case ' ':
705                             intArg = va_arg(arg, int);
706                             sprintf(buffPtr, fmtBuff, intArg);
707                             buffCount = strlen(buffPtr);
708                             break;
709                         case 'l':
710                             /*
711                              * XXX: Allowed by ISO C Amendment 1, but
712                              * many platforms don't yet support wint_t
713                              */
714                             goto ErrorReturn;
715                     default:
716                             goto ErrorReturn;
717                     }
718                     break;
719                 case 's':
720                     switch(sizeModifier) {
721                         case ' ':
722                             if(fastPath) {
723                                 buffPtr = va_arg(arg, char *);
724                                 buffCount = strlen(buffPtr);
725                                 buffLen = buffCount + 1;
726                             } else {
727                                 sprintf(buffPtr, fmtBuff, charPtrArg);
728                                 buffCount = strlen(buffPtr);
729                             }
730                             break;
731                         case 'l':
732                             /*
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.
736                              */
737                             goto ErrorReturn;
738                         default:
739                             goto ErrorReturn;
740                     }
741                     break;
742                 case 'p':
743                     if(sizeModifier != ' ')
744                         goto ErrorReturn;
745                     voidPtrArg = va_arg(arg, void *);
746                     sprintf(buffPtr, fmtBuff, voidPtrArg);
747                     buffCount = strlen(buffPtr);
748                     break;
749                 case 'n':
750                     switch(sizeModifier) {
751                         case ' ':
752                             intPtrArg = va_arg(arg, int *);
753                             *intPtrArg = streamCount;
754                             break;
755                         case 'l':
756                             longPtrArg = va_arg(arg, long *);
757                             *longPtrArg = streamCount;
758                             break;
759                         case 'h':
760                             shortPtrArg = (short *) va_arg(arg, short *);
761                             *shortPtrArg = (short) streamCount;
762                             break;
763                         default:
764                             goto ErrorReturn;
765                     }
766                     buffCount = 0;
767                     break;
768                 case 'f':
769                     if(fastPath) {
770                         performedOp = FALSE;
771                         break;
772                     }
773                     switch(sizeModifier) {
774                         case ' ':
775                             sprintf(buffPtr, fmtBuff, doubleArg);
776                             buffCount = strlen(buffPtr);
777                             break;
778                         case 'L':
779                             sprintf(buffPtr, fmtBuff, lDoubleArg);
780                             buffCount = strlen(buffPtr);
781                             break;
782                         default:
783                             goto ErrorReturn;
784                     }
785                     break;
786                 case 'e':
787                 case 'E':
788                 case 'g':
789                 case 'G':
790                     switch(sizeModifier) {
791                         case ' ':
792                             doubleArg = va_arg(arg, double);
793                             sprintf(buffPtr, fmtBuff, doubleArg);
794                             buffCount = strlen(buffPtr);
795                             break;
796                         case 'L':
797                             lDoubleArg = va_arg(arg, LONG_DOUBLE);
798                             sprintf(buffPtr, fmtBuff, lDoubleArg);
799                             buffCount = strlen(buffPtr);
800                             break;
801                         default:
802                             goto ErrorReturn;
803                     }
804                     break;
805                 case '%':
806                     if(sizeModifier != ' ')
807                         goto ErrorReturn;
808                     buff[0] = '%';
809                     buffCount = 1;
810                     break;
811                 case '\0':
812                     goto ErrorReturn;
813                 default:
814                     performedOp = FALSE;
815                     break;
816             } /* switch(op) */
817             if(performedOp) break;
818             if(!fastPath)
819                 goto ErrorReturn;
820             fastPath = FALSE;
821         } /* for (;;) */
822         ASSERT(buffCount < buffLen);
823         if(buffCount > 0) {
824             if(FCGX_PutStr(buffPtr, buffCount, stream) < 0)
825                 goto ErrorReturn;
826             streamCount += buffCount;
827         } else if(buffCount < 0) {
828             goto ErrorReturn;
829         }
830         f += specifierLength;
831     } /* while(f != fStop) */
832     goto NormalReturn;
833   ErrorReturn:
834     streamCount = -1;
835   NormalReturn:
836     if(auxBuffPtr != NULL) free(auxBuffPtr);
837     return streamCount;
838 }
839
840 /*
841  * Copy n characters from *srcPtr to *destPtr, then increment
842  * both *srcPtr and *destPtr by n.
843  */
844 static void CopyAndAdvance(char **destPtr, char **srcPtr, int n)
845 {
846     char *dest = *destPtr;
847     char *src = *srcPtr;
848     int i;
849     for (i = 0; i < n; i++)
850         *dest++ = *src++;
851     *destPtr = dest;
852     *srcPtr = src;
853 }
854
855 /*
856  *----------------------------------------------------------------------
857  *
858  * FCGX_FFlush --
859  *
860  *      Flushes any buffered output.
861  *
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.
867  *
868  * Results:
869  *      EOF (-1) if an error occurred.
870  *
871  *----------------------------------------------------------------------
872  */
873 int FCGX_FFlush(FCGX_Stream *stream)
874 {
875     if(stream->isClosed || stream->isReader)
876         return 0;
877     stream->emptyBuffProc(stream, FALSE);
878     return (stream->isClosed) ? -1 : 0;
879 }
880
881 /*
882  *----------------------------------------------------------------------
883  *
884  * FCGX_FClose --
885  *
886  *      Performs FCGX_FFlush and closes the stream.
887  *
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.
892  *
893  * Results:
894  *      EOF (-1) if an error occurred.
895  *
896  *----------------------------------------------------------------------
897  */
898 int FCGX_FClose(FCGX_Stream *stream)
899 {
900     if (stream == NULL) return 0;
901
902     if(!stream->wasFCloseCalled) {
903         if(!stream->isReader) {
904             stream->emptyBuffProc(stream, TRUE);
905         }
906         stream->wasFCloseCalled = TRUE;
907         stream->isClosed = TRUE;
908         if(stream->isReader) {
909             stream->wrNext = stream->stop = stream->rdNext;
910         } else {
911             stream->rdNext = stream->stop = stream->wrNext;
912         }
913     }
914     return (stream->FCGI_errno == 0) ? 0 : EOF;
915 }
916
917 /*
918  *----------------------------------------------------------------------
919  *
920  * SetError --
921  *
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.
925  *
926  *----------------------------------------------------------------------
927  */
928 static void SetError(FCGX_Stream *stream, int FCGI_errno)
929 {
930     /*
931      * Preserve only the first error.
932      */
933     if(stream->FCGI_errno == 0) {
934         stream->FCGI_errno = FCGI_errno;
935         stream->isClosed = TRUE;
936     }
937 }
938
939 /*
940  *----------------------------------------------------------------------
941  *
942  * FCGX_GetError --
943  *
944  *      Return the stream error code.  0 means no error, > 0
945  *      is an errno(2) error, < 0 is an FCGX_errno error.
946  *
947  *----------------------------------------------------------------------
948  */
949 int FCGX_GetError(FCGX_Stream *stream) {
950     return stream->FCGI_errno;
951 }
952
953 /*
954  *----------------------------------------------------------------------
955  *
956  * FCGX_ClearError --
957  *
958  *      Clear the stream error code and end-of-file indication.
959  *
960  *----------------------------------------------------------------------
961  */
962 void FCGX_ClearError(FCGX_Stream *stream) {
963     stream->FCGI_errno = 0;
964     /*
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.
974      */
975 }
976
977 /*
978  *======================================================================
979  * Parameters
980  *======================================================================
981  */
982
983 /*
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.
987  */
988
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 */
993 } Params;
994 typedef Params *ParamsPtr;
995
996 /*
997  *----------------------------------------------------------------------
998  *
999  * NewParams --
1000  *
1001  *      Creates a new Params structure.
1002  *
1003  * Results:
1004  *      Pointer to the new structure.
1005  *
1006  *----------------------------------------------------------------------
1007  */
1008 static ParamsPtr NewParams(int length)
1009 {
1010     ParamsPtr result;
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;
1016     return result;
1017 }
1018
1019 /*
1020  *----------------------------------------------------------------------
1021  *
1022  * FreeParams --
1023  *
1024  *      Frees a Params structure and all the parameters it contains.
1025  *
1026  * Side effects:
1027  *      env becomes invalid.
1028  *
1029  *----------------------------------------------------------------------
1030  */
1031 static void FreeParams(ParamsPtr *paramsPtrPtr)
1032 {
1033     ParamsPtr paramsPtr = *paramsPtrPtr;
1034     char **p;
1035     if(paramsPtr == NULL) {
1036         return;
1037     }
1038     for (p = paramsPtr->vec; p < paramsPtr->cur; p++) {
1039         free(*p);
1040     }
1041     free(paramsPtr->vec);
1042     free(paramsPtr);
1043     *paramsPtrPtr = NULL;
1044 }
1045
1046 /*
1047  *----------------------------------------------------------------------
1048  *
1049  * PutParam --
1050  *
1051  *      Add a name/value pair to a Params structure.
1052  *
1053  * Results:
1054  *      None.
1055  *
1056  * Side effects:
1057  *      Parameters structure updated.
1058  *
1059  *----------------------------------------------------------------------
1060  */
1061 static void PutParam(ParamsPtr paramsPtr, char *nameValue)
1062 {
1063     int size;
1064
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;
1071     }
1072     *paramsPtr->cur = NULL;
1073 }
1074
1075 /*
1076  *----------------------------------------------------------------------
1077  *
1078  * FCGX_GetParam -- obtain value of FCGI parameter in environment
1079  *
1080  *
1081  * Results:
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.
1085  *
1086  *----------------------------------------------------------------------
1087  */
1088 char *FCGX_GetParam(const char *name, FCGX_ParamArray envp)
1089 {
1090     int len;
1091     char **p;
1092
1093         if (name == NULL || envp == NULL) return NULL;
1094
1095     len = strlen(name);
1096
1097     for (p = envp; *p; ++p) {
1098         if((strncmp(name, *p, len) == 0) && ((*p)[len] == '=')) {
1099             return *p+len+1;
1100         }
1101     }
1102     return NULL;
1103 }
1104
1105 /*
1106  *----------------------------------------------------------------------
1107  *
1108  * Start of FastCGI-specific code
1109  *
1110  *----------------------------------------------------------------------
1111  */
1112
1113 /*
1114  *----------------------------------------------------------------------
1115  *
1116  * ReadParams --
1117  *
1118  *      Reads FastCGI name-value pairs from stream until EOF.  Converts
1119  *      each pair to name=value format and adds it to Params structure.
1120  *
1121  *----------------------------------------------------------------------
1122  */
1123 static int ReadParams(Params *paramsPtr, FCGX_Stream *stream)
1124 {
1125     int nameLen, valueLen;
1126     unsigned char lenBuff[3];
1127     char *nameValue;
1128
1129     while((nameLen = FCGX_GetChar(stream)) != EOF) {
1130         /*
1131          * Read name length (one or four bytes) and value length
1132          * (one or four bytes) from stream.
1133          */
1134         if((nameLen & 0x80) != 0) {
1135             if(FCGX_GetStr((char *) &lenBuff[0], 3, stream) != 3) {
1136                 SetError(stream, FCGX_PARAMS_ERROR);
1137                 return -1;
1138             }
1139             nameLen = ((nameLen & 0x7f) << 24) + (lenBuff[0] << 16)
1140                     + (lenBuff[1] << 8) + lenBuff[2];
1141         }
1142         if((valueLen = FCGX_GetChar(stream)) == EOF) {
1143             SetError(stream, FCGX_PARAMS_ERROR);
1144             return -1;
1145         }
1146         if((valueLen & 0x80) != 0) {
1147             if(FCGX_GetStr((char *) &lenBuff[0], 3, stream) != 3) {
1148                 SetError(stream, FCGX_PARAMS_ERROR);
1149                 return -1;
1150             }
1151             valueLen = ((valueLen & 0x7f) << 24) + (lenBuff[0] << 16)
1152                     + (lenBuff[1] << 8) + lenBuff[2];
1153         }
1154         /*
1155          * nameLen and valueLen are now valid; read the name and value
1156          * from stream and construct a standard environment entry.
1157          */
1158         nameValue = (char *)Malloc(nameLen + valueLen + 2);
1159         if(FCGX_GetStr(nameValue, nameLen, stream) != nameLen) {
1160             SetError(stream, FCGX_PARAMS_ERROR);
1161             free(nameValue);
1162             return -1;
1163         }
1164         *(nameValue + nameLen) = '=';
1165         if(FCGX_GetStr(nameValue + nameLen + 1, valueLen, stream)
1166                 != valueLen) {
1167             SetError(stream, FCGX_PARAMS_ERROR);
1168             free(nameValue);
1169             return -1;
1170         }
1171         *(nameValue + nameLen + valueLen + 1) = '\0';
1172         PutParam(paramsPtr, nameValue);
1173     }
1174     return 0;
1175 }
1176
1177 /*
1178  *----------------------------------------------------------------------
1179  *
1180  * MakeHeader --
1181  *
1182  *      Constructs an FCGI_Header struct.
1183  *
1184  *----------------------------------------------------------------------
1185  */
1186 static FCGI_Header MakeHeader(
1187         int type,
1188         int requestId,
1189         int contentLength,
1190         int paddingLength)
1191 {
1192     FCGI_Header header;
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;
1203     return header;
1204 }
1205
1206 /*
1207  *----------------------------------------------------------------------
1208  *
1209  * MakeEndRequestBody --
1210  *
1211  *      Constructs an FCGI_EndRequestBody struct.
1212  *
1213  *----------------------------------------------------------------------
1214  */
1215 static FCGI_EndRequestBody MakeEndRequestBody(
1216         int appStatus,
1217         int protocolStatus)
1218 {
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));
1226     return body;
1227 }
1228
1229 /*
1230  *----------------------------------------------------------------------
1231  *
1232  * MakeUnknownTypeBody --
1233  *
1234  *      Constructs an FCGI_MakeUnknownTypeBody struct.
1235  *
1236  *----------------------------------------------------------------------
1237  */
1238 static FCGI_UnknownTypeBody MakeUnknownTypeBody(
1239         int type)
1240 {
1241     FCGI_UnknownTypeBody body;
1242     body.type = (unsigned char) type;
1243     memset(body.reserved, 0, sizeof(body.reserved));
1244     return body;
1245 }
1246
1247 /*
1248  *----------------------------------------------------------------------
1249  *
1250  * AlignInt8 --
1251  *
1252  *      Returns the smallest integer greater than or equal to n
1253  *      that's a multiple of 8.
1254  *
1255  *----------------------------------------------------------------------
1256  */
1257 static int AlignInt8(unsigned n) {
1258     return (n + 7) & (UINT_MAX - 7);
1259 }
1260
1261 /*
1262  *----------------------------------------------------------------------
1263  *
1264  * AlignPtr8 --
1265  *
1266  *      Returns the smallest pointer greater than or equal to p
1267  *      that's a multiple of 8.
1268  *
1269  *----------------------------------------------------------------------
1270  */
1271 static unsigned char *AlignPtr8(unsigned char *p) {
1272     unsigned long u = (unsigned long) p;
1273     u = ((u + 7) & (ULONG_MAX - 7)) - u;
1274     return p + u;
1275 }
1276
1277
1278 /*
1279  * State associated with a stream
1280  */
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 */
1298 } FCGX_Stream_Data;
1299
1300 /*
1301  *----------------------------------------------------------------------
1302  *
1303  * WriteCloseRecords --
1304  *
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
1307  *      record.
1308  *
1309  *----------------------------------------------------------------------
1310  */
1311 static void WriteCloseRecords(struct FCGX_Stream *stream)
1312 {
1313     FCGX_Stream_Data *data = (FCGX_Stream_Data *)stream->data;
1314     /*
1315      * Enter rawWrite mode so final records won't be encapsulated as
1316      * stream data.
1317      */
1318     data->rawWrite = TRUE;
1319     /*
1320      * Generate EOF for stream content if needed.
1321      */
1322     if(!(data->type == FCGI_STDERR
1323             && stream->wrNext == data->buff
1324             && !data->isAnythingWritten)) {
1325         FCGI_Header header;
1326         header = MakeHeader(data->type, data->reqDataPtr->requestId, 0, 0);
1327         FCGX_PutStr((char *) &header, sizeof(header), stream);
1328     };
1329     /*
1330      * Generate FCGI_END_REQUEST record if needed.
1331      */
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);
1341     }
1342     data->reqDataPtr->nWriters--;
1343 }
1344
1345
1346
1347 static int write_it_all(int fd, char *buf, int len)
1348 {
1349     int wrote;
1350
1351     while (len) {
1352         wrote = OS_Write(fd, buf, len);
1353         if (wrote < 0)
1354             return wrote;
1355         len -= wrote;
1356         buf += wrote;
1357     }
1358     return len;
1359 }
1360
1361 /*
1362  *----------------------------------------------------------------------
1363  *
1364  * EmptyBuffProc --
1365  *
1366  *      Encapsulates any buffered stream content in a FastCGI
1367  *      record.  Writes the data, making the buffer empty.
1368  *
1369  *----------------------------------------------------------------------
1370  */
1371 static void EmptyBuffProc(struct FCGX_Stream *stream, int doClose)
1372 {
1373     FCGX_Stream_Data *data = (FCGX_Stream_Data *)stream->data;
1374     int cLen, eLen;
1375     /*
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.
1381      */
1382     if(!data->rawWrite) {
1383         cLen = stream->wrNext - data->buff - sizeof(FCGI_Header);
1384         if(cLen > 0) {
1385             eLen = AlignInt8(cLen);
1386             /*
1387              * Giving the padding a well-defined value keeps Purify happy.
1388              */
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);
1394         } else {
1395             stream->wrNext = data->buff;
1396         }
1397     }
1398     if(doClose) {
1399         WriteCloseRecords(stream);
1400     };
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);
1405             return;
1406         }
1407         stream->wrNext = data->buff;
1408     }
1409     /*
1410      * The buffer is empty.
1411      */
1412     if(!data->rawWrite) {
1413         stream->wrNext += sizeof(FCGI_Header);
1414     }
1415 }
1416
1417 /*
1418  * Return codes for Process* functions
1419  */
1420 #define STREAM_RECORD 0
1421 #define SKIP          1
1422 #define BEGIN_RECORD  2
1423 #define MGMT_RECORD   3
1424
1425 /*
1426  *----------------------------------------------------------------------
1427  *
1428  * ProcessManagementRecord --
1429  *
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.
1436  *
1437  *----------------------------------------------------------------------
1438  */
1439 static int ProcessManagementRecord(int type, FCGX_Stream *stream)
1440 {
1441     FCGX_Stream_Data *data = (FCGX_Stream_Data *)stream->data;
1442     ParamsPtr paramsPtr = NewParams(3);
1443     char **pPtr;
1444     char response[64]; /* 64 = 8 + 3*(1+1+14+1)* + padding */
1445     char *responseP = &response[FCGI_HEADER_LEN];
1446     char *name, value = '\0';
1447     int len, paddedLen;
1448     if(type == FCGI_GET_VALUES) {
1449         ReadParams(paramsPtr, stream);
1450         if((FCGX_GetError(stream) != 0) || (data->contentLen != 0)) {
1451             FreeParams(&paramsPtr);
1452             return FCGX_PROTOCOL_ERROR;
1453         }
1454         for (pPtr = paramsPtr->vec; pPtr < paramsPtr->cur; pPtr++) {
1455             name = *pPtr;
1456             *(strchr(name, '=')) = '\0';
1457             if(strcmp(name, FCGI_MAX_CONNS) == 0) {
1458                 value = '1';
1459             } else if(strcmp(name, FCGI_MAX_REQS) == 0) {
1460                 value = '1';
1461             } else if(strcmp(name, FCGI_MPXS_CONNS) == 0) {
1462                 value = '0';
1463             } else {
1464                 name = NULL;
1465             }
1466             if(name != NULL) {
1467                 len = strlen(name);
1468                 sprintf(responseP, "%c%c%s%c", len, 1, name, value);
1469                 responseP += len + 3;
1470             }
1471         }
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(&paramsPtr);
1478     } else {
1479         paddedLen = len = sizeof(FCGI_UnknownTypeBody);
1480         ((FCGI_UnknownTypeRecord *) response)->header
1481             = MakeHeader(FCGI_UNKNOWN_TYPE, FCGI_NULL_REQUEST_ID,
1482                          len, 0);
1483         ((FCGI_UnknownTypeRecord *) response)->body
1484             = MakeUnknownTypeBody(type);
1485     }
1486     if (write_it_all(data->reqDataPtr->ipcFd, response, FCGI_HEADER_LEN + paddedLen) < 0) {
1487         SetError(stream, OS_Errno);
1488         return -1;
1489     }
1490
1491     return MGMT_RECORD;
1492 }
1493
1494 /*
1495  *----------------------------------------------------------------------
1496  *
1497  * ProcessBeginRecord --
1498  *
1499  *      Reads an FCGI_BEGIN_REQUEST record.
1500  *
1501  * Results:
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).
1505  *
1506  * Side effects:
1507  *      In case of BEGIN_RECORD return, stores requestId, role,
1508  *      keepConnection values, and sets isBeginProcessed = TRUE.
1509  *
1510  *----------------------------------------------------------------------
1511  */
1512 static int ProcessBeginRecord(int requestId, FCGX_Stream *stream)
1513 {
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;
1518     }
1519     if(data->reqDataPtr->isBeginProcessed) {
1520         /*
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}
1524          */
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);
1532             return -1;
1533         }
1534
1535         return SKIP;
1536     }
1537     /*
1538      * Accept this new request.  Read the record body.
1539      */
1540     data->reqDataPtr->requestId = requestId;
1541     if(FCGX_GetStr((char *) &body, sizeof(body), stream)
1542             != sizeof(body)) {
1543         return FCGX_PROTOCOL_ERROR;
1544     }
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;
1549 }
1550
1551 /*
1552  *----------------------------------------------------------------------
1553  *
1554  * ProcessHeader --
1555  *
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.
1559  *
1560  * Results:
1561  *      >= 0 for a normal return, < 0 for error
1562  *
1563  * Side effects:
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
1569  *      paddingLength.
1570  *
1571  *----------------------------------------------------------------------
1572  */
1573 static int ProcessHeader(FCGI_Header header, FCGX_Stream *stream)
1574 {
1575     FCGX_Stream_Data *data = (FCGX_Stream_Data *)stream->data;
1576     int requestId;
1577     if(header.version != FCGI_VERSION_1) {
1578         return FCGX_UNSUPPORTED_VERSION;
1579     }
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);
1587     }
1588     if(requestId  == FCGI_NULL_REQUEST_ID) {
1589         return ProcessManagementRecord(header.type, stream);
1590     }
1591     if(requestId != data->reqDataPtr->requestId) {
1592         return SKIP;
1593     }
1594     if(header.type != data->type) {
1595         return FCGX_PROTOCOL_ERROR;
1596     }
1597     return STREAM_RECORD;
1598 }
1599
1600 /*
1601  *----------------------------------------------------------------------
1602  *
1603  * FillBuffProc --
1604  *
1605  *      Reads bytes from the ipcFd, supplies bytes to a stream client.
1606  *
1607  *----------------------------------------------------------------------
1608  */
1609 static void FillBuffProc(FCGX_Stream *stream)
1610 {
1611     FCGX_Stream_Data *data = (FCGX_Stream_Data *)stream->data;
1612     FCGI_Header header;
1613     int headerLen = 0;
1614     int status, count;
1615
1616     for (;;) {
1617         /*
1618          * If data->buff is empty, do a read.
1619          */
1620         if(stream->rdNext == data->buffStop) {
1621             count = OS_Read(data->reqDataPtr->ipcFd, (char *)data->buff,
1622                             data->bufflen);
1623             if(count <= 0) {
1624                 SetError(stream, (count == 0 ? FCGX_PROTOCOL_ERROR : OS_Errno));
1625                 return;
1626             }
1627             stream->rdNext = data->buff;
1628             data->buffStop = data->buff + count;
1629         }
1630         /*
1631          * Now data->buff is not empty.  If the current record contains
1632          * more content bytes, deliver all that are present in data->buff.
1633          */
1634         if(data->contentLen > 0) {
1635             count = min(data->contentLen, data->buffStop - stream->rdNext);
1636             data->contentLen -= count;
1637             if(!data->skip) {
1638                 stream->wrNext = stream->stop = stream->rdNext + count;
1639                 return;
1640             } else {
1641                 stream->rdNext += count;
1642                 if(data->contentLen > 0) {
1643                     continue;
1644                 } else {
1645                     data->skip = FALSE;
1646                 }
1647             }
1648         }
1649         /*
1650          * If the current record (whose content has been fully consumed by
1651          * the client) was padded, skip over the padding bytes.
1652          */
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) {
1658                 continue;
1659             }
1660         }
1661         /*
1662          * All done with the current record, including the padding.
1663          * If we're in a recursive call from ProcessHeader, deliver EOF.
1664          */
1665         if(data->eorStop) {
1666             stream->stop = stream->rdNext;
1667             stream->isClosed = TRUE;
1668             return;
1669         }
1670         /*
1671          * Fill header with bytes from the input buffer.
1672          */
1673         count = min((int)sizeof(header) - headerLen,
1674                         data->buffStop - stream->rdNext);
1675         memcpy(((char *)(&header)) + headerLen, stream->rdNext, count);
1676         headerLen += count;
1677         stream->rdNext += count;
1678         if(headerLen < sizeof(header)) {
1679             continue;
1680         };
1681         headerLen = 0;
1682         /*
1683          * Interpret header.  eorStop prevents ProcessHeader from reading
1684          * past the end-of-record when using stream to read content.
1685          */
1686         data->eorStop = TRUE;
1687         stream->stop = stream->rdNext;
1688         status = ProcessHeader(header, stream);
1689         data->eorStop = FALSE;
1690         stream->isClosed = FALSE;
1691         switch(status) {
1692             case STREAM_RECORD:
1693                 /*
1694                  * If this stream record header marked the end of stream
1695                  * data deliver EOF to the stream client, otherwise loop
1696                  * and deliver data.
1697                  *
1698                  * XXX: If this is final stream and
1699                  * stream->rdNext != data->buffStop, buffered
1700                  * data is next request (server pipelining)?
1701                  */
1702                 if(data->contentLen == 0) {
1703                     stream->wrNext = stream->stop = stream->rdNext;
1704                     stream->isClosed = TRUE;
1705                     return;
1706                 }
1707                 break;
1708             case SKIP:
1709                 data->skip = TRUE;
1710                 break;
1711             case BEGIN_RECORD:
1712                 /*
1713                  * If this header marked the beginning of a new
1714                  * request, return role information to caller.
1715                  */
1716                 return;
1717                 break;
1718             case MGMT_RECORD:
1719                 break;
1720             default:
1721                 ASSERT(status < 0);
1722                 SetError(stream, status);
1723                 return;
1724                 break;
1725         }
1726     }
1727 }
1728
1729 /*
1730  *----------------------------------------------------------------------
1731  *
1732  * NewStream --
1733  *
1734  *      Creates a stream to read or write from an open ipcFd.
1735  *      The stream performs reads/writes of up to bufflen bytes.
1736  *
1737  *----------------------------------------------------------------------
1738  */
1739 static FCGX_Stream *NewStream(
1740         FCGX_Request *reqDataPtr, int bufflen, int isReader, int streamType)
1741 {
1742     /*
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.
1749      */
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) {
1758         data->bufflen -= 8;
1759     }
1760     if(isReader) {
1761         data->buffStop = data->buff;
1762     } else {
1763         data->buffStop = data->buff + data->bufflen;
1764     }
1765     data->type = streamType;
1766     data->eorStop = FALSE;
1767     data->skip = FALSE;
1768     data->contentLen = 0;
1769     data->paddingLen = 0;
1770     data->isAnythingWritten = FALSE;
1771     data->rawWrite = FALSE;
1772
1773     stream->data = data;
1774     stream->isReader = isReader;
1775     stream->isClosed = FALSE;
1776     stream->wasFCloseCalled = FALSE;
1777     stream->FCGI_errno = 0;
1778     if(isReader) {
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;
1785     } else {
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;
1792     }
1793     return stream;
1794 }
1795
1796 /*
1797  *----------------------------------------------------------------------
1798  *
1799  * FCGX_FreeStream --
1800  *
1801  *      Frees all storage allocated when *streamPtr was created,
1802  *      and nulls out *streamPtr.
1803  *
1804  *----------------------------------------------------------------------
1805  */
1806 void FCGX_FreeStream(FCGX_Stream **streamPtr)
1807 {
1808     FCGX_Stream *stream = *streamPtr;
1809     FCGX_Stream_Data *data;
1810     if(stream == NULL) {
1811         return;
1812     }
1813     data = (FCGX_Stream_Data *)stream->data;
1814     data->reqDataPtr = NULL;
1815     free(data->mBuff);
1816     free(data);
1817     free(stream);
1818     *streamPtr = NULL;
1819 }
1820
1821 /*
1822  *----------------------------------------------------------------------
1823  *
1824  * SetReaderType --
1825  *
1826  *      Re-initializes the stream to read data of the specified type.
1827  *
1828  *----------------------------------------------------------------------
1829  */
1830 static FCGX_Stream *SetReaderType(FCGX_Stream *stream, int streamType)
1831 {
1832     FCGX_Stream_Data *data = (FCGX_Stream_Data *)stream->data;
1833     ASSERT(stream->isReader);
1834     data->type = streamType;
1835     data->eorStop = FALSE;
1836     data->skip = FALSE;
1837     data->contentLen = 0;
1838     data->paddingLen = 0;
1839     stream->wrNext = stream->stop = stream->rdNext;
1840     stream->isClosed = FALSE;
1841     return stream;
1842 }
1843
1844 /*
1845  *----------------------------------------------------------------------
1846  *
1847  * NewReader --
1848  *
1849  *      Creates a stream to read streamType records for the given
1850  *      request.  The stream performs OS reads of up to bufflen bytes.
1851  *
1852  *----------------------------------------------------------------------
1853  */
1854 static FCGX_Stream *NewReader(FCGX_Request *reqDataPtr, int bufflen, int streamType)
1855 {
1856     return NewStream(reqDataPtr, bufflen, TRUE, streamType);
1857 }
1858
1859 /*
1860  *----------------------------------------------------------------------
1861  *
1862  * NewWriter --
1863  *
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.
1867  *
1868  *----------------------------------------------------------------------
1869  */
1870 static FCGX_Stream *NewWriter(FCGX_Request *reqDataPtr, int bufflen, int streamType)
1871 {
1872     return NewStream(reqDataPtr, bufflen, FALSE, streamType);
1873 }
1874
1875 /*
1876  *----------------------------------------------------------------------
1877  *
1878  * FCGX_CreateWriter --
1879  *
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.
1884  *
1885  *----------------------------------------------------------------------
1886  */
1887 FCGX_Stream *FCGX_CreateWriter(
1888         int ipcFd,
1889         int requestId,
1890         int bufflen,
1891         int streamType)
1892 {
1893     FCGX_Request *reqDataPtr = (FCGX_Request *)Malloc(sizeof(FCGX_Request));
1894     reqDataPtr->ipcFd = ipcFd;
1895     reqDataPtr->requestId = requestId;
1896     /*
1897      * Suppress writing an FCGI_END_REQUEST record.
1898      */
1899     reqDataPtr->nWriters = 2;
1900     return NewWriter(reqDataPtr, bufflen, streamType);
1901 }
1902
1903 /*
1904  *======================================================================
1905  * Control
1906  *======================================================================
1907  */
1908
1909 /*
1910  *----------------------------------------------------------------------
1911  *
1912  * FCGX_IsCGI --
1913  *
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).
1918  *
1919  * Results:
1920  *      TRUE if the process is a CGI process, FALSE if FastCGI.
1921  *
1922  *----------------------------------------------------------------------
1923  */
1924 int FCGX_IsCGI(void)
1925 {
1926     if (isFastCGI != -1) {
1927         return !isFastCGI;
1928     }
1929
1930     if (!libInitialized) {
1931         int rc = FCGX_Init();
1932         if (rc) {
1933             /* exit() isn't great, but hey */
1934             exit((rc < 0) ? rc : -rc);
1935         }
1936     }
1937
1938     isFastCGI = OS_IsFcgi(FCGI_LISTENSOCK_FILENO);
1939
1940     return !isFastCGI;
1941 }
1942
1943 /*
1944  *----------------------------------------------------------------------
1945  *
1946  * FCGX_Finish --
1947  *
1948  *      Finishes the current request from the HTTP server.
1949  *
1950  * Side effects:
1951  *
1952  *      Finishes the request accepted by (and frees any
1953  *      storage allocated by) the previous call to FCGX_Accept.
1954  *
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
1958  *      or FCGX_Accept.
1959  *
1960  *----------------------------------------------------------------------
1961  */
1962
1963 void FCGX_Finish(void)
1964 {
1965     FCGX_Finish_r(&the_request);
1966 }
1967
1968 /*
1969  *----------------------------------------------------------------------
1970  *
1971  * FCGX_Finish_r --
1972  *
1973  *      Finishes the current request from the HTTP server.
1974  *
1975  * Side effects:
1976  *
1977  *      Finishes the request accepted by (and frees any
1978  *      storage allocated by) the previous call to FCGX_Accept.
1979  *
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
1983  *      or FCGX_Accept.
1984  *
1985  *----------------------------------------------------------------------
1986  */
1987 void FCGX_Finish_r(FCGX_Request *reqDataPtr)
1988 {
1989     int close;
1990
1991     if (reqDataPtr == NULL) {
1992         return;
1993     }
1994
1995     close = !reqDataPtr->keepConnection;
1996
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);
2001
2002         close |= FCGX_GetError(reqDataPtr->in);
2003     }
2004
2005     FCGX_Free(reqDataPtr, close);
2006 }
2007
2008 void FCGX_Free(FCGX_Request * request, int close)
2009 {
2010     if (request == NULL) 
2011         return;
2012
2013     FCGX_FreeStream(&request->in);
2014     FCGX_FreeStream(&request->out);
2015     FCGX_FreeStream(&request->err);
2016     FreeParams(&request->paramsPtr);
2017
2018     if (close) {
2019         OS_IpcClose(request->ipcFd);
2020         request->ipcFd = -1;
2021     }
2022 }
2023
2024 int FCGX_OpenSocket(const char *path, int backlog)
2025 {
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 */
2029         isFastCGI = 1;
2030     }
2031     return rc;
2032 }
2033
2034 int FCGX_InitRequest(FCGX_Request *request, int sock, int flags)
2035 {
2036     memset(request, 0, sizeof(FCGX_Request));
2037
2038     /* @@@ Should check that sock is open and listening */
2039     request->listen_sock = sock;
2040
2041     /* @@@ Should validate against "known" flags */
2042     request->flags = flags;
2043
2044     request->ipcFd = -1;
2045
2046     return 0;
2047 }
2048
2049 /*
2050  *----------------------------------------------------------------------
2051  *
2052  * FCGX_Init --
2053  *
2054  *      Initilize the FCGX library.  This is called by FCGX_Accept()
2055  *      but must be called by the user when using FCGX_Accept_r().
2056  *
2057  * Results:
2058  *          0 for successful call.
2059  *
2060  *----------------------------------------------------------------------
2061  */
2062 int FCGX_Init(void)
2063 {
2064     char *p;
2065
2066     if (libInitialized) {
2067         return 0;
2068     }
2069
2070     FCGX_InitRequest(&the_request, FCGI_LISTENSOCK_FILENO, 0);
2071
2072     if (OS_LibInit(NULL) == -1) {
2073         return OS_Errno ? OS_Errno : -9997;
2074     }
2075
2076     p = getenv("FCGI_WEB_SERVER_ADDRS");
2077     webServerAddressList = p ? StringCopy(p) : NULL;
2078
2079     libInitialized = 1;
2080     return 0;
2081 }
2082
2083 /*
2084  *----------------------------------------------------------------------
2085  *
2086  * FCGX_Accept --
2087  *
2088  *      Accepts a new request from the HTTP server.
2089  *
2090  * Results:
2091  *      0 for successful call, -1 for error.
2092  *
2093  * Side effects:
2094  *
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.
2102  *
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
2106  *      or FCGX_Accept.
2107  *
2108  *----------------------------------------------------------------------
2109  */
2110
2111 int FCGX_Accept(
2112         FCGX_Stream **in,
2113         FCGX_Stream **out,
2114         FCGX_Stream **err,
2115         FCGX_ParamArray *envp)
2116 {
2117     int rc;
2118
2119     if (! libInitialized) {
2120         rc = FCGX_Init();
2121         if (rc) {
2122             return rc;
2123         }
2124     }
2125
2126     rc = FCGX_Accept_r(&the_request);
2127
2128     *in = the_request.in;
2129     *out = the_request.out;
2130     *err = the_request.err;
2131     *envp = the_request.envp;
2132
2133     return rc;
2134 }
2135
2136 /*
2137  *----------------------------------------------------------------------
2138  *
2139  * FCGX_Accept_r --
2140  *
2141  *      Accepts a new request from the HTTP server.
2142  *
2143  * Results:
2144  *      0 for successful call, -1 for error.
2145  *
2146  * Side effects:
2147  *
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.
2155  *
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
2159  *      or FCGX_Accept.
2160  *
2161  *----------------------------------------------------------------------
2162  */
2163 int FCGX_Accept_r(FCGX_Request *reqDataPtr)
2164 {
2165     if (!libInitialized) {
2166         return -9998;
2167     }
2168
2169     /* Finish the current request, if any. */
2170     FCGX_Finish_r(reqDataPtr);
2171
2172     for (;;) {
2173         /*
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.
2177          */
2178         if (reqDataPtr->ipcFd < 0) {
2179             int fail_on_intr = reqDataPtr->flags & FCGI_FAIL_ACCEPT_ON_INTR;
2180
2181             reqDataPtr->ipcFd = OS_Accept(reqDataPtr->listen_sock, fail_on_intr, webServerAddressList);
2182             if (reqDataPtr->ipcFd < 0) {
2183                 return (errno > 0) ? (0 - errno) : -9999;
2184             }
2185         }
2186         /*
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.
2190          */
2191         reqDataPtr->isBeginProcessed = FALSE;
2192         reqDataPtr->in = NewReader(reqDataPtr, 8192, 0);
2193         FillBuffProc(reqDataPtr->in);
2194         if(!reqDataPtr->isBeginProcessed) {
2195             goto TryAgain;
2196         }
2197         {
2198             char *roleStr;
2199             switch(reqDataPtr->role) {
2200                 case FCGI_RESPONDER:
2201                     roleStr = "FCGI_ROLE=RESPONDER";
2202                     break;
2203                 case FCGI_AUTHORIZER:
2204                     roleStr = "FCGI_ROLE=AUTHORIZER";
2205                     break;
2206                 case FCGI_FILTER:
2207                     roleStr = "FCGI_ROLE=FILTER";
2208                     break;
2209                 default:
2210                     goto TryAgain;
2211             }
2212             reqDataPtr->paramsPtr = NewParams(30);
2213             PutParam(reqDataPtr->paramsPtr, StringCopy(roleStr));
2214         }
2215         SetReaderType(reqDataPtr->in, FCGI_PARAMS);
2216         if(ReadParams(reqDataPtr->paramsPtr, reqDataPtr->in) >= 0) {
2217             /*
2218              * Finished reading the environment.  No errors occurred, so
2219              * leave the connection-retry loop.
2220              */
2221             break;
2222         }
2223
2224         /*
2225          * Close the connection and try again.
2226          */
2227 TryAgain:
2228         FCGX_Free(reqDataPtr, 1);
2229
2230     } /* for (;;) */
2231     /*
2232      * Build the remaining data structures representing the new
2233      * request and return successfully to the caller.
2234      */
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;
2240     return 0;
2241 }
2242
2243 /*
2244  *----------------------------------------------------------------------
2245  *
2246  * FCGX_StartFilterData --
2247  *
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.
2254  *
2255  * Results:
2256  *      0 for a normal return, < 0 for error
2257  *
2258  *----------------------------------------------------------------------
2259  */
2260
2261 int FCGX_StartFilterData(FCGX_Stream *stream)
2262 {
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);
2269         return -1;
2270     }
2271     SetReaderType(stream, FCGI_DATA);
2272     return 0;
2273 }
2274
2275 /*
2276  *----------------------------------------------------------------------
2277  *
2278  * FCGX_SetExitStatus --
2279  *
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.
2285  *
2286  *----------------------------------------------------------------------
2287  */
2288
2289 void FCGX_SetExitStatus(int status, FCGX_Stream *stream)
2290 {
2291     FCGX_Stream_Data *data = (FCGX_Stream_Data *)stream->data;
2292     data->reqDataPtr->appStatus = status;
2293 }
2294