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