Need <limits.h>
[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.21 2001/06/18 14:25:09 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 "fcgiapp.h"
51
52 #include "fcgimisc.h"
53 #include "fastcgi.h"
54 #include "fcgios.h"
55
56 /*
57  * This is a workaround for one version of the HP C compiler
58  * (c89 on HP-UX 9.04, also Stratus FTX), which will dump core
59  * if given 'long double' for varargs.
60  */
61 #ifdef HAVE_VA_ARG_LONG_DOUBLE_BUG
62 #define LONG_DOUBLE double
63 #else
64 #define LONG_DOUBLE long double
65 #endif
66
67 /*
68  * Globals
69  */
70 static int libInitialized = 0;
71 static int isFastCGI = -1;
72 static char *webServerAddressList = NULL;
73 static FCGX_Request the_request;
74
75 static void *Malloc(size_t size)
76 {
77     void *result = malloc(size);
78     ASSERT(size == 0 || result != NULL);
79     return result;
80 }
81
82 static char *StringCopy(char *str)
83 {
84     int strLen = strlen(str);
85     char *newString = (char *)Malloc(strLen + 1);
86     memcpy(newString, str, strLen);
87     newString[strLen] = '\000';
88     return newString;
89 }
90
91 \f
92 /*
93  *----------------------------------------------------------------------
94  *
95  * FCGX_GetChar --
96  *
97  *      Reads a byte from the input stream and returns it.
98  *
99  * Results:
100  *      The byte, or EOF (-1) if the end of input has been reached.
101  *
102  *----------------------------------------------------------------------
103  */
104 int FCGX_GetChar(FCGX_Stream *stream)
105 {
106     if(stream->rdNext != stream->stop)
107         return *stream->rdNext++;
108     if(stream->isClosed || !stream->isReader)
109         return EOF;
110     stream->fillBuffProc(stream);
111     stream->stopUnget = stream->rdNext;
112     if(stream->rdNext != stream->stop)
113         return *stream->rdNext++;
114     ASSERT(stream->isClosed); /* bug in fillBufProc if not */
115     return EOF;
116 }
117 \f
118 /*
119  *----------------------------------------------------------------------
120  *
121  * FCGX_GetStr --
122  *
123  *      Reads up to n consecutive bytes from the input stream
124  *      into the character array str.  Performs no interpretation
125  *      of the input bytes.
126  *
127  * Results:
128  *      Number of bytes read.  If result is smaller than n,
129  *      the end of input has been reached.
130  *
131  *----------------------------------------------------------------------
132  */
133 int FCGX_GetStr(char *str, int n, FCGX_Stream *stream)
134 {
135     int m, bytesMoved;
136
137     if(n <= 0) {
138         return 0;
139     }
140     /*
141      * Fast path: n bytes are already available
142      */
143     if(n <= (stream->stop - stream->rdNext)) {
144         memcpy(str, stream->rdNext, n);
145         stream->rdNext += n;
146         return n;
147     }
148     /*
149      * General case: stream is closed or buffer fill procedure
150      * needs to be called
151      */
152     bytesMoved = 0;
153     for (;;) {
154         if(stream->rdNext != stream->stop) {
155             m = min(n - bytesMoved, stream->stop - stream->rdNext);
156             memcpy(str, stream->rdNext, m);
157             bytesMoved += m;
158             stream->rdNext += m;
159             if(bytesMoved == n)
160                 return bytesMoved;
161             str += m;
162         }
163         if(stream->isClosed || !stream->isReader)
164             return bytesMoved;
165         stream->fillBuffProc(stream);
166         stream->stopUnget = stream->rdNext;
167     }
168 }
169 \f
170 /*
171  *----------------------------------------------------------------------
172  *
173  * FCGX_GetLine --
174  *
175  *      Reads up to n-1 consecutive bytes from the input stream
176  *      into the character array str.  Stops before n-1 bytes
177  *      have been read if '\n' or EOF is read.  The terminating '\n'
178  *      is copied to str.  After copying the last byte into str,
179  *      stores a '\0' terminator.
180  *
181  * Results:
182  *      NULL if EOF is the first thing read from the input stream,
183  *      str otherwise.
184  *
185  *----------------------------------------------------------------------
186  */
187 char *FCGX_GetLine(char *str, int n, FCGX_Stream *stream)
188 {
189     int c;
190     char *p = str;
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++ = c;
201         n--;
202         if(c == '\n')
203             break;
204     }
205     *p = '\0';
206     return str;
207 }
208 \f
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 = 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 \f
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++ = 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++ = c);
277     ASSERT(stream->isClosed); /* bug in emptyBuffProc if not */
278     return EOF;
279 }
280 \f
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 \f
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 \f
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, buffLen, specifierLength;
401     int fastPath, n, auxBuffLen, 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;
414     void *voidPtrArg;
415     int *intPtrArg;
416     long *longPtrArg;
417     short *shortPtrArg;
418     double doubleArg;
419     LONG_DOUBLE lDoubleArg;
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] = sizeModifier;
459                         fmtBuff[2] = op;
460                         fmtBuff[3] = '\0';
461                         specifierLength = 3;
462                         break;
463                     default:
464                         sizeModifier = ' ';
465                         fmtBuff[1] = 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                                 frexp(lDoubleArg, &exp);
600                                 break;
601                             default:
602                                 goto ErrorReturn;
603                         }
604                         if(precision == -1) precision = 6;
605                         buffReqd = precision + 3 + ((exp > 0) ? exp/3 : 0);
606                         break;
607                     case 'e':
608                     case 'E':
609                     case 'g':
610                     case 'G':
611                         if(precision == -1) precision = 6;
612                         buffReqd = precision + 8;
613                         break;
614                     case 'n':
615                     case '%':
616                     default:
617                         goto ErrorReturn;
618                         break;
619                 }
620                 buffReqd = max(buffReqd + 10, minWidth);
621                 /*
622                  * Allocate the buffer
623                  */
624                 if(buffReqd <= PRINTF_BUFFLEN) {
625                     buffPtr = buff;
626                     buffLen = PRINTF_BUFFLEN;
627                 } else {
628                     if(auxBuffPtr == NULL || buffReqd > auxBuffLen) {
629                         if(auxBuffPtr != NULL) free(auxBuffPtr);
630                         auxBuffPtr = (char *)Malloc(buffReqd);
631                         auxBuffLen = buffReqd;
632                         if(auxBuffPtr == NULL)
633                             goto ErrorReturn;
634                     }
635                     buffPtr = auxBuffPtr;
636                     buffLen = auxBuffLen;
637                 }
638             }
639             /*
640              * This giant switch statement requires the following variables
641              * to be set up: op, sizeModifier, arg, buffPtr, fmtBuff.
642              * When fastPath == FALSE and op == 's' or 'f', the argument
643              * has been read into charPtrArg, doubleArg, or lDoubleArg.
644              * The statement produces the boolean performedOp, TRUE iff
645              * the op/sizeModifier were executed and argument consumed;
646              * if performedOp, the characters written into buffPtr[]
647              * and the character count buffCount (== EOF meaning error).
648              *
649              * The switch cases are arranged in the same order as in the
650              * description of fprintf in section 15.11 of Harbison and Steele.
651              */
652             performedOp = TRUE;
653             switch(op) {
654                 case 'd':
655                 case 'i':
656                     switch(sizeModifier) {
657                         case ' ':
658                             intArg = va_arg(arg, int);
659                             sprintf(buffPtr, fmtBuff, intArg);
660                             buffCount = strlen(buffPtr);
661                             break;
662                         case 'l':
663                             longArg = va_arg(arg, long);
664                             sprintf(buffPtr, fmtBuff, longArg);
665                             buffCount = strlen(buffPtr);
666                             break;
667                         case 'h':
668                             shortArg = (short) va_arg(arg, int);
669                             sprintf(buffPtr, fmtBuff, shortArg);
670                             buffCount = strlen(buffPtr);
671                             break;
672                         default:
673                             goto ErrorReturn;
674                     }
675                     break;
676                 case 'u':
677                 case 'o':
678                 case 'x':
679                 case 'X':
680                     switch(sizeModifier) {
681                         case ' ':
682                             unsignedArg = va_arg(arg, unsigned);
683                             sprintf(buffPtr, fmtBuff, unsignedArg);
684                             buffCount = strlen(buffPtr);
685                             break;
686                         case 'l':
687                             uLongArg = va_arg(arg, unsigned long);
688                             sprintf(buffPtr, fmtBuff, uLongArg);
689                             buffCount = strlen(buffPtr);
690                             break;
691                         case 'h':
692                             uShortArg = (unsigned short) va_arg(arg, int);
693                             sprintf(buffPtr, fmtBuff, uShortArg);
694                             buffCount = strlen(buffPtr);
695                             break;
696                         default:
697                             goto ErrorReturn;
698                     }
699                     break;
700                 case 'c':
701                     switch(sizeModifier) {
702                         case ' ':
703                             intArg = va_arg(arg, int);
704                             sprintf(buffPtr, fmtBuff, intArg);
705                             buffCount = strlen(buffPtr);
706                             break;
707                         case 'l':
708                             /*
709                              * XXX: Allowed by ISO C Amendment 1, but
710                              * many platforms don't yet support wint_t
711                              */
712                             goto ErrorReturn;
713                     default:
714                             goto ErrorReturn;
715                     }
716                     break;
717                 case 's':
718                     switch(sizeModifier) {
719                         case ' ':
720                             if(fastPath) {
721                                 buffPtr = va_arg(arg, char *);
722                                 buffCount = strlen(buffPtr);
723                                 buffLen = buffCount + 1;
724                             } else {
725                                 sprintf(buffPtr, fmtBuff, charPtrArg);
726                                 buffCount = strlen(buffPtr);
727                             }
728                             break;
729                         case 'l':
730                             /*
731                              * XXX: Don't know how to convert a sequence
732                              * of wide characters into a byte stream, or
733                              * even how to predict the buffering required.
734                              */
735                             goto ErrorReturn;
736                         default:
737                             goto ErrorReturn;
738                     }
739                     break;
740                 case 'p':
741                     if(sizeModifier != ' ')
742                         goto ErrorReturn;
743                     voidPtrArg = va_arg(arg, void *);
744                     sprintf(buffPtr, fmtBuff, voidPtrArg);
745                     buffCount = strlen(buffPtr);
746                     break;
747                 case 'n':
748                     switch(sizeModifier) {
749                         case ' ':
750                             intPtrArg = va_arg(arg, int *);
751                             *intPtrArg = streamCount;
752                             break;
753                         case 'l':
754                             longPtrArg = va_arg(arg, long *);
755                             *longPtrArg = streamCount;
756                             break;
757                         case 'h':
758                             shortPtrArg = va_arg(arg, short *);
759                             *shortPtrArg = streamCount;
760                             break;
761                         default:
762                             goto ErrorReturn;
763                     }
764                     buffCount = 0;
765                     break;
766                 case 'f':
767                     if(fastPath) {
768                         performedOp = FALSE;
769                         break;
770                     }
771                     switch(sizeModifier) {
772                         case ' ':
773                             sprintf(buffPtr, fmtBuff, doubleArg);
774                             buffCount = strlen(buffPtr);
775                             break;
776                         case 'L':
777                             sprintf(buffPtr, fmtBuff, lDoubleArg);
778                             buffCount = strlen(buffPtr);
779                             break;
780                         default:
781                             goto ErrorReturn;
782                     }
783                     break;
784                 case 'e':
785                 case 'E':
786                 case 'g':
787                 case 'G':
788                     switch(sizeModifier) {
789                         case ' ':
790                             doubleArg = va_arg(arg, double);
791                             sprintf(buffPtr, fmtBuff, doubleArg);
792                             buffCount = strlen(buffPtr);
793                             break;
794                         case 'L':
795                             lDoubleArg = va_arg(arg, LONG_DOUBLE);
796                             sprintf(buffPtr, fmtBuff, lDoubleArg);
797                             buffCount = strlen(buffPtr);
798                             break;
799                         default:
800                             goto ErrorReturn;
801                     }
802                     break;
803                 case '%':
804                     if(sizeModifier != ' ')
805                         goto ErrorReturn;
806                     buff[0] = '%';
807                     buffCount = 1;
808                     break;
809                 case '\0':
810                     goto ErrorReturn;
811                 default:
812                     performedOp = FALSE;
813                     break;
814             } /* switch(op) */
815             if(performedOp) break;
816             if(!fastPath)
817                 goto ErrorReturn;
818             fastPath = FALSE;
819         } /* for (;;) */
820         ASSERT(buffCount < buffLen);
821         if(buffCount > 0) {
822             if(FCGX_PutStr(buffPtr, buffCount, stream) < 0)
823                 goto ErrorReturn;
824             streamCount += buffCount;
825         } else if(buffCount < 0) {
826             goto ErrorReturn;
827         }
828         f += specifierLength;
829     } /* while(f != fStop) */
830     goto NormalReturn;
831   ErrorReturn:
832     streamCount = -1;
833   NormalReturn:
834     if(auxBuffPtr != NULL) free(auxBuffPtr);
835     return streamCount;
836 }
837
838 /*
839  * Copy n characters from *srcPtr to *destPtr, then increment
840  * both *srcPtr and *destPtr by n.
841  */
842 static void CopyAndAdvance(char **destPtr, char **srcPtr, int n)
843 {
844     char *dest = *destPtr;
845     char *src = *srcPtr;
846     int i;
847     for (i = 0; i < n; i++)
848         *dest++ = *src++;
849     *destPtr = dest;
850     *srcPtr = src;
851 }
852 \f
853 /*
854  *----------------------------------------------------------------------
855  *
856  * FCGX_FFlush --
857  *
858  *      Flushes any buffered output.
859  *
860  *      Server-push is a legitimate application of FCGX_FFlush.
861  *      Otherwise, FCGX_FFlush is not very useful, since FCGX_Accept
862  *      does it implicitly.  FCGX_FFlush may reduce performance
863  *      by increasing the total number of operating system calls
864  *      the application makes.
865  *
866  * Results:
867  *      EOF (-1) if an error occurred.
868  *
869  *----------------------------------------------------------------------
870  */
871 int FCGX_FFlush(FCGX_Stream *stream)
872 {
873     if(stream->isClosed || stream->isReader)
874         return 0;
875     stream->emptyBuffProc(stream, FALSE);
876     return (stream->isClosed) ? -1 : 0;
877 }
878 \f
879 /*
880  *----------------------------------------------------------------------
881  *
882  * FCGX_FClose --
883  *
884  *      Performs FCGX_FFlush and closes the stream.
885  *
886  *      This is not a very useful operation, since FCGX_Accept
887  *      does it implicitly.  Closing the out stream before the
888  *      err stream results in an extra write if there's nothing
889  *      in the err stream, and therefore reduces performance.
890  *
891  * Results:
892  *      EOF (-1) if an error occurred.
893  *
894  *----------------------------------------------------------------------
895  */
896 int FCGX_FClose(FCGX_Stream *stream)
897 {
898     if (stream == NULL) return 0;
899
900     if(!stream->wasFCloseCalled) {
901         if(!stream->isReader) {
902             stream->emptyBuffProc(stream, TRUE);
903         }
904         stream->wasFCloseCalled = TRUE;
905         stream->isClosed = TRUE;
906         if(stream->isReader) {
907             stream->wrNext = stream->stop = stream->rdNext;
908         } else {
909             stream->rdNext = stream->stop = stream->wrNext;
910         }
911     }
912     return (stream->FCGI_errno == 0) ? 0 : EOF;
913 }
914 \f
915 /*
916  *----------------------------------------------------------------------
917  *
918  * SetError --
919  *
920  *      An error has occurred; save the error code in the stream
921  *      for diagnostic purposes and set the stream state so that
922  *      reads return EOF and writes have no effect.
923  *
924  *----------------------------------------------------------------------
925  */
926 static void SetError(FCGX_Stream *stream, int FCGI_errno)
927 {
928     /*
929      * Preserve only the first error.
930      */
931     if(stream->FCGI_errno == 0) {
932         stream->FCGI_errno = FCGI_errno;
933         stream->isClosed = TRUE;
934     }
935 }
936
937 /*
938  *----------------------------------------------------------------------
939  *
940  * FCGX_GetError --
941  *
942  *      Return the stream error code.  0 means no error, > 0
943  *      is an errno(2) error, < 0 is an FCGX_errno error.
944  *
945  *----------------------------------------------------------------------
946  */
947 int FCGX_GetError(FCGX_Stream *stream) {
948     return stream->FCGI_errno;
949 }
950
951 /*
952  *----------------------------------------------------------------------
953  *
954  * FCGX_ClearError --
955  *
956  *      Clear the stream error code and end-of-file indication.
957  *
958  *----------------------------------------------------------------------
959  */
960 void FCGX_ClearError(FCGX_Stream *stream) {
961     stream->FCGI_errno = 0;
962     /*
963      * stream->isClosed = FALSE;
964      * XXX: should clear isClosed but work is needed to make it safe
965      * to do so.  For example, if an application calls FClose, gets
966      * an I/O error on the write, calls ClearError and retries
967      * the FClose, FClose (really EmptyBuffProc) will write a second
968      * EOF record.  If an application calls PutChar instead of FClose
969      * after the ClearError, the application will write more data.
970      * The stream's state must discriminate between various states
971      * of the stream that are now all lumped under isClosed.
972      */
973 }
974 \f
975 /*
976  *======================================================================
977  * Parameters
978  *======================================================================
979  */
980
981 /*
982  * A vector of pointers representing the parameters received
983  * by a FastCGI application server, with the vector's length
984  * and last valid element so adding new parameters is efficient.
985  */
986
987 typedef struct Params {
988     FCGX_ParamArray vec;    /* vector of strings */
989     int length;             /* number of string vec can hold */
990     char **cur;             /* current item in vec; *cur == NULL */
991 } Params;
992 typedef Params *ParamsPtr;
993 \f
994 /*
995  *----------------------------------------------------------------------
996  *
997  * NewParams --
998  *
999  *      Creates a new Params structure.
1000  *
1001  * Results:
1002  *      Pointer to the new structure.
1003  *
1004  *----------------------------------------------------------------------
1005  */
1006 static ParamsPtr NewParams(int length)
1007 {
1008     ParamsPtr result;
1009     result = (Params *)Malloc(sizeof(Params));
1010     result->vec = (char **)Malloc(length * sizeof(char *));
1011     result->length = length;
1012     result->cur = result->vec;
1013     *result->cur = NULL;
1014     return result;
1015 }
1016 \f
1017 /*
1018  *----------------------------------------------------------------------
1019  *
1020  * FreeParams --
1021  *
1022  *      Frees a Params structure and all the parameters it contains.
1023  *
1024  * Side effects:
1025  *      env becomes invalid.
1026  *
1027  *----------------------------------------------------------------------
1028  */
1029 static void FreeParams(ParamsPtr *paramsPtrPtr)
1030 {
1031     ParamsPtr paramsPtr = *paramsPtrPtr;
1032     char **p;
1033     if(paramsPtr == NULL) {
1034         return;
1035     }
1036     for (p = paramsPtr->vec; p < paramsPtr->cur; p++) {
1037         free(*p);
1038     }
1039     free(paramsPtr->vec);
1040     free(paramsPtr);
1041     *paramsPtrPtr = NULL;
1042 }
1043 \f
1044 /*
1045  *----------------------------------------------------------------------
1046  *
1047  * PutParam --
1048  *
1049  *      Add a name/value pair to a Params structure.
1050  *
1051  * Results:
1052  *      None.
1053  *
1054  * Side effects:
1055  *      Parameters structure updated.
1056  *
1057  *----------------------------------------------------------------------
1058  */
1059 static void PutParam(ParamsPtr paramsPtr, char *nameValue)
1060 {
1061     int size;
1062
1063     *paramsPtr->cur++ = nameValue;
1064     size = paramsPtr->cur - paramsPtr->vec;
1065     if(size >= paramsPtr->length) {
1066         paramsPtr->length *= 2;
1067         paramsPtr->vec = (FCGX_ParamArray)realloc(paramsPtr->vec, paramsPtr->length * sizeof(char *));
1068         paramsPtr->cur = paramsPtr->vec + size;
1069     }
1070     *paramsPtr->cur = NULL;
1071 }
1072 \f
1073 /*
1074  *----------------------------------------------------------------------
1075  *
1076  * FCGX_GetParam -- obtain value of FCGI parameter in environment
1077  *
1078  *
1079  * Results:
1080  *      Value bound to name, NULL if name not present in the
1081  *      environment envp.  Caller must not mutate the result
1082  *      or retain it past the end of this request.
1083  *
1084  *----------------------------------------------------------------------
1085  */
1086 char *FCGX_GetParam(const char *name, FCGX_ParamArray envp)
1087 {
1088     int len;
1089     char **p;
1090
1091         if (name == NULL || envp == NULL) return NULL;
1092
1093     len = strlen(name);
1094
1095     for (p = envp; *p; ++p) {
1096         if((strncmp(name, *p, len) == 0) && ((*p)[len] == '=')) {
1097             return *p+len+1;
1098         }
1099     }
1100     return NULL;
1101 }
1102 \f
1103 /*
1104  *----------------------------------------------------------------------
1105  *
1106  * Start of FastCGI-specific code
1107  *
1108  *----------------------------------------------------------------------
1109  */
1110 \f
1111 /*
1112  *----------------------------------------------------------------------
1113  *
1114  * ReadParams --
1115  *
1116  *      Reads FastCGI name-value pairs from stream until EOF.  Converts
1117  *      each pair to name=value format and adds it to Params structure.
1118  *
1119  *----------------------------------------------------------------------
1120  */
1121 static int ReadParams(Params *paramsPtr, FCGX_Stream *stream)
1122 {
1123     int nameLen, valueLen;
1124     unsigned char lenBuff[3];
1125     char *nameValue;
1126
1127     while((nameLen = FCGX_GetChar(stream)) != EOF) {
1128         /*
1129          * Read name length (one or four bytes) and value length
1130          * (one or four bytes) from stream.
1131          */
1132         if((nameLen & 0x80) != 0) {
1133             if(FCGX_GetStr((char *) &lenBuff[0], 3, stream) != 3) {
1134                 SetError(stream, FCGX_PARAMS_ERROR);
1135                 return -1;
1136             }
1137             nameLen = ((nameLen & 0x7f) << 24) + (lenBuff[0] << 16)
1138                     + (lenBuff[1] << 8) + lenBuff[2];
1139         }
1140         if((valueLen = FCGX_GetChar(stream)) == EOF) {
1141             SetError(stream, FCGX_PARAMS_ERROR);
1142             return -1;
1143         }
1144         if((valueLen & 0x80) != 0) {
1145             if(FCGX_GetStr((char *) &lenBuff[0], 3, stream) != 3) {
1146                 SetError(stream, FCGX_PARAMS_ERROR);
1147                 return -1;
1148             }
1149             valueLen = ((valueLen & 0x7f) << 24) + (lenBuff[0] << 16)
1150                     + (lenBuff[1] << 8) + lenBuff[2];
1151         }
1152         /*
1153          * nameLen and valueLen are now valid; read the name and value
1154          * from stream and construct a standard environment entry.
1155          */
1156         nameValue = (char *)Malloc(nameLen + valueLen + 2);
1157         if(FCGX_GetStr(nameValue, nameLen, stream) != nameLen) {
1158             SetError(stream, FCGX_PARAMS_ERROR);
1159             free(nameValue);
1160             return -1;
1161         }
1162         *(nameValue + nameLen) = '=';
1163         if(FCGX_GetStr(nameValue + nameLen + 1, valueLen, stream)
1164                 != valueLen) {
1165             SetError(stream, FCGX_PARAMS_ERROR);
1166             free(nameValue);
1167             return -1;
1168         }
1169         *(nameValue + nameLen + valueLen + 1) = '\0';
1170         PutParam(paramsPtr, nameValue);
1171     }
1172     return 0;
1173 }
1174 \f
1175 /*
1176  *----------------------------------------------------------------------
1177  *
1178  * MakeHeader --
1179  *
1180  *      Constructs an FCGI_Header struct.
1181  *
1182  *----------------------------------------------------------------------
1183  */
1184 static FCGI_Header MakeHeader(
1185         int type,
1186         int requestId,
1187         int contentLength,
1188         int paddingLength)
1189 {
1190     FCGI_Header header;
1191     ASSERT(contentLength >= 0 && contentLength <= FCGI_MAX_LENGTH);
1192     ASSERT(paddingLength >= 0 && paddingLength <= 0xff);
1193     header.version = FCGI_VERSION_1;
1194     header.type             =  type;
1195     header.requestIdB1      = (requestId      >> 8) & 0xff;
1196     header.requestIdB0      = (requestId          ) & 0xff;
1197     header.contentLengthB1  = (contentLength  >> 8) & 0xff;
1198     header.contentLengthB0  = (contentLength      ) & 0xff;
1199     header.paddingLength    =  paddingLength;
1200     header.reserved         =  0;
1201     return header;
1202 }
1203 \f
1204 /*
1205  *----------------------------------------------------------------------
1206  *
1207  * MakeEndRequestBody --
1208  *
1209  *      Constructs an FCGI_EndRequestBody struct.
1210  *
1211  *----------------------------------------------------------------------
1212  */
1213 static FCGI_EndRequestBody MakeEndRequestBody(
1214         int appStatus,
1215         int protocolStatus)
1216 {
1217     FCGI_EndRequestBody body;
1218     body.appStatusB3 = (appStatus >> 24) & 0xff;
1219     body.appStatusB2 = (appStatus >> 16) & 0xff;
1220     body.appStatusB1 = (appStatus >>  8) & 0xff;
1221     body.appStatusB0 = (appStatus      ) & 0xff;
1222     body.protocolStatus = protocolStatus;
1223     memset(body.reserved, 0, sizeof(body.reserved));
1224     return body;
1225 }
1226 \f
1227 /*
1228  *----------------------------------------------------------------------
1229  *
1230  * MakeUnknownTypeBody --
1231  *
1232  *      Constructs an FCGI_MakeUnknownTypeBody struct.
1233  *
1234  *----------------------------------------------------------------------
1235  */
1236 static FCGI_UnknownTypeBody MakeUnknownTypeBody(
1237         int type)
1238 {
1239     FCGI_UnknownTypeBody body;
1240     body.type = type;
1241     memset(body.reserved, 0, sizeof(body.reserved));
1242     return body;
1243 }
1244 \f
1245 /*
1246  *----------------------------------------------------------------------
1247  *
1248  * AlignInt8 --
1249  *
1250  *      Returns the smallest integer greater than or equal to n
1251  *      that's a multiple of 8.
1252  *
1253  *----------------------------------------------------------------------
1254  */
1255 static int AlignInt8(unsigned n) {
1256     return (n + 7) & (UINT_MAX - 7);
1257 }
1258
1259 /*
1260  *----------------------------------------------------------------------
1261  *
1262  * AlignPtr8 --
1263  *
1264  *      Returns the smallest pointer greater than or equal to p
1265  *      that's a multiple of 8.
1266  *
1267  *----------------------------------------------------------------------
1268  */
1269 static unsigned char *AlignPtr8(unsigned char *p) {
1270     unsigned long u = (unsigned long) p;
1271     u = ((u + 7) & (ULONG_MAX - 7)) - u;
1272     return p + u;
1273 }
1274 \f
1275
1276 /*
1277  * State associated with a stream
1278  */
1279 typedef struct FCGX_Stream_Data {
1280     unsigned char *buff;      /* buffer after alignment */
1281     int bufflen;              /* number of bytes buff can store */
1282     unsigned char *mBuff;     /* buffer as returned by Malloc */
1283     unsigned char *buffStop;  /* reader: last valid byte + 1 of entire buffer.
1284                                * stop generally differs from buffStop for
1285                                * readers because of record structure.
1286                                * writer: buff + bufflen */
1287     int type;                 /* reader: FCGI_PARAMS or FCGI_STDIN
1288                                * writer: FCGI_STDOUT or FCGI_STDERR */
1289     int eorStop;              /* reader: stop stream at end-of-record */
1290     int skip;                 /* reader: don't deliver content bytes */
1291     int contentLen;           /* reader: bytes of unread content */
1292     int paddingLen;           /* reader: bytes of unread padding */
1293     int isAnythingWritten;    /* writer: data has been written to ipcFd */
1294     int rawWrite;             /* writer: write data without stream headers */
1295     FCGX_Request *reqDataPtr; /* request data not specific to one stream */
1296 } FCGX_Stream_Data;
1297 \f
1298 /*
1299  *----------------------------------------------------------------------
1300  *
1301  * WriteCloseRecords --
1302  *
1303  *      Writes an EOF record for the stream content if necessary.
1304  *      If this is the last writer to close, writes an FCGI_END_REQUEST
1305  *      record.
1306  *
1307  *----------------------------------------------------------------------
1308  */
1309 static void WriteCloseRecords(struct FCGX_Stream *stream)
1310 {
1311     FCGX_Stream_Data *data = (FCGX_Stream_Data *)stream->data;
1312     /*
1313      * Enter rawWrite mode so final records won't be encapsulated as
1314      * stream data.
1315      */
1316     data->rawWrite = TRUE;
1317     /*
1318      * Generate EOF for stream content if needed.
1319      */
1320     if(!(data->type == FCGI_STDERR
1321             && stream->wrNext == data->buff
1322             && !data->isAnythingWritten)) {
1323         FCGI_Header header;
1324         header = MakeHeader(data->type, data->reqDataPtr->requestId, 0, 0);
1325         FCGX_PutStr((char *) &header, sizeof(header), stream);
1326     };
1327     /*
1328      * Generate FCGI_END_REQUEST record if needed.
1329      */
1330     if(data->reqDataPtr->nWriters == 1) {
1331         FCGI_EndRequestRecord endRequestRecord;
1332         endRequestRecord.header = MakeHeader(FCGI_END_REQUEST,
1333                 data->reqDataPtr->requestId,
1334                 sizeof(endRequestRecord.body), 0);
1335         endRequestRecord.body = MakeEndRequestBody(
1336                 data->reqDataPtr->appStatus, FCGI_REQUEST_COMPLETE);
1337         FCGX_PutStr((char *) &endRequestRecord,
1338                 sizeof(endRequestRecord), stream);
1339     }
1340     data->reqDataPtr->nWriters--;
1341 }
1342 \f
1343
1344
1345 static int write_it_all(int fd, char *buf, int len)
1346 {
1347     int wrote;
1348
1349     while (len) {
1350         wrote = OS_Write(fd, buf, len);
1351         if (wrote < 0)
1352             return wrote;
1353         len -= wrote;
1354         buf += wrote;
1355     }
1356     return len;
1357 }
1358
1359 /*
1360  *----------------------------------------------------------------------
1361  *
1362  * EmptyBuffProc --
1363  *
1364  *      Encapsulates any buffered stream content in a FastCGI
1365  *      record.  Writes the data, making the buffer empty.
1366  *
1367  *----------------------------------------------------------------------
1368  */
1369 static void EmptyBuffProc(struct FCGX_Stream *stream, int doClose)
1370 {
1371     FCGX_Stream_Data *data = (FCGX_Stream_Data *)stream->data;
1372     int cLen, eLen;
1373     /*
1374      * If the buffer contains stream data, fill in the header.
1375      * Pad the record to a multiple of 8 bytes in length.  Padding
1376      * can't overflow the buffer because the buffer is a multiple
1377      * of 8 bytes in length.  If the buffer contains no stream
1378      * data, reclaim the space reserved for the header.
1379      */
1380     if(!data->rawWrite) {
1381         cLen = stream->wrNext - data->buff - sizeof(FCGI_Header);
1382         if(cLen > 0) {
1383             eLen = AlignInt8(cLen);
1384             /*
1385              * Giving the padding a well-defined value keeps Purify happy.
1386              */
1387             memset(stream->wrNext, 0, eLen - cLen);
1388             stream->wrNext += eLen - cLen;
1389             *((FCGI_Header *) data->buff)
1390                     = MakeHeader(data->type,
1391                             data->reqDataPtr->requestId, cLen, eLen - cLen);
1392         } else {
1393             stream->wrNext = data->buff;
1394         }
1395     }
1396     if(doClose) {
1397         WriteCloseRecords(stream);
1398     };
1399     if (stream->wrNext != data->buff) {
1400         data->isAnythingWritten = TRUE;
1401         if (write_it_all(data->reqDataPtr->ipcFd, (char *)data->buff, stream->wrNext - data->buff) < 0) {
1402             SetError(stream, OS_Errno);
1403             return;
1404         }
1405         stream->wrNext = data->buff;
1406     }
1407     /*
1408      * The buffer is empty.
1409      */
1410     if(!data->rawWrite) {
1411         stream->wrNext += sizeof(FCGI_Header);
1412     }
1413 }
1414 \f
1415 /*
1416  * Return codes for Process* functions
1417  */
1418 #define STREAM_RECORD 0
1419 #define SKIP          1
1420 #define BEGIN_RECORD  2
1421 #define MGMT_RECORD   3
1422
1423 /*
1424  *----------------------------------------------------------------------
1425  *
1426  * ProcessManagementRecord --
1427  *
1428  *      Reads and responds to a management record.  The only type of
1429  *      management record this library understands is FCGI_GET_VALUES.
1430  *      The only variables that this library's FCGI_GET_VALUES
1431  *      understands are FCGI_MAX_CONNS, FCGI_MAX_REQS, and FCGI_MPXS_CONNS.
1432  *      Ignore other FCGI_GET_VALUES variables; respond to other
1433  *      management records with a FCGI_UNKNOWN_TYPE record.
1434  *
1435  *----------------------------------------------------------------------
1436  */
1437 static int ProcessManagementRecord(int type, FCGX_Stream *stream)
1438 {
1439     FCGX_Stream_Data *data = (FCGX_Stream_Data *)stream->data;
1440     ParamsPtr paramsPtr = NewParams(3);
1441     char **pPtr;
1442     char response[64]; /* 64 = 8 + 3*(1+1+14+1)* + padding */
1443     char *responseP = &response[FCGI_HEADER_LEN];
1444     char *name, value;
1445     int len, paddedLen;
1446     if(type == FCGI_GET_VALUES) {
1447         ReadParams(paramsPtr, stream);
1448         if((FCGX_GetError(stream) != 0) || (data->contentLen != 0)) {
1449             FreeParams(&paramsPtr);
1450             return FCGX_PROTOCOL_ERROR;
1451         }
1452         for (pPtr = paramsPtr->vec; pPtr < paramsPtr->cur; pPtr++) {
1453             name = *pPtr;
1454             *(strchr(name, '=')) = '\0';
1455             if(strcmp(name, FCGI_MAX_CONNS) == 0) {
1456                 value = '1';
1457             } else if(strcmp(name, FCGI_MAX_REQS) == 0) {
1458                 value = '1';
1459             } else if(strcmp(name, FCGI_MPXS_CONNS) == 0) {
1460                 value = '0';
1461             } else {
1462                 name = NULL;
1463             }
1464             if(name != NULL) {
1465                 len = strlen(name);
1466                 sprintf(responseP, "%c%c%s%c", len, 1, name, value);
1467                 responseP += len + 3;
1468             }
1469         }
1470         len = responseP - &response[FCGI_HEADER_LEN];
1471         paddedLen = AlignInt8(len);
1472         *((FCGI_Header *) response)
1473             = MakeHeader(FCGI_GET_VALUES_RESULT, FCGI_NULL_REQUEST_ID,
1474                          len, paddedLen - len);
1475         FreeParams(&paramsPtr);
1476     } else {
1477         paddedLen = len = sizeof(FCGI_UnknownTypeBody);
1478         ((FCGI_UnknownTypeRecord *) response)->header
1479             = MakeHeader(FCGI_UNKNOWN_TYPE, FCGI_NULL_REQUEST_ID,
1480                          len, 0);
1481         ((FCGI_UnknownTypeRecord *) response)->body
1482             = MakeUnknownTypeBody(type);
1483     }
1484     if (write_it_all(data->reqDataPtr->ipcFd, response, FCGI_HEADER_LEN + paddedLen) < 0) {
1485         SetError(stream, OS_Errno);
1486         return -1;
1487     }
1488
1489     return MGMT_RECORD;
1490 }
1491 \f
1492 /*
1493  *----------------------------------------------------------------------
1494  *
1495  * ProcessBeginRecord --
1496  *
1497  *      Reads an FCGI_BEGIN_REQUEST record.
1498  *
1499  * Results:
1500  *      BEGIN_RECORD for normal return.  FCGX_PROTOCOL_ERROR for
1501  *      protocol error.  SKIP for attempt to multiplex
1502  *      connection.  -1 for error from write (errno in stream).
1503  *
1504  * Side effects:
1505  *      In case of BEGIN_RECORD return, stores requestId, role,
1506  *      keepConnection values, and sets isBeginProcessed = TRUE.
1507  *
1508  *----------------------------------------------------------------------
1509  */
1510 static int ProcessBeginRecord(int requestId, FCGX_Stream *stream)
1511 {
1512     FCGX_Stream_Data *data = (FCGX_Stream_Data *)stream->data;
1513     FCGI_BeginRequestBody body;
1514     if(requestId == 0 || data->contentLen != sizeof(body)) {
1515         return FCGX_PROTOCOL_ERROR;
1516     }
1517     if(data->reqDataPtr->isBeginProcessed) {
1518         /*
1519          * The Web server is multiplexing the connection.  This library
1520          * doesn't know how to handle multiplexing, so respond with
1521          * FCGI_END_REQUEST{protocolStatus = FCGI_CANT_MPX_CONN}
1522          */
1523         FCGI_EndRequestRecord endRequestRecord;
1524         endRequestRecord.header = MakeHeader(FCGI_END_REQUEST,
1525                 requestId, sizeof(endRequestRecord.body), 0);
1526         endRequestRecord.body
1527                 = MakeEndRequestBody(0, FCGI_CANT_MPX_CONN);
1528         if (write_it_all(data->reqDataPtr->ipcFd, (char *)&endRequestRecord, sizeof(endRequestRecord)) < 0) {
1529             SetError(stream, OS_Errno);
1530             return -1;
1531         }
1532
1533         return SKIP;
1534     }
1535     /*
1536      * Accept this new request.  Read the record body.
1537      */
1538     data->reqDataPtr->requestId = requestId;
1539     if(FCGX_GetStr((char *) &body, sizeof(body), stream)
1540             != sizeof(body)) {
1541         return FCGX_PROTOCOL_ERROR;
1542     }
1543     data->reqDataPtr->keepConnection = (body.flags & FCGI_KEEP_CONN);
1544     data->reqDataPtr->role = (body.roleB1 << 8) + body.roleB0;
1545     data->reqDataPtr->isBeginProcessed = TRUE;
1546     return BEGIN_RECORD;
1547 }
1548 \f
1549 /*
1550  *----------------------------------------------------------------------
1551  *
1552  * ProcessHeader --
1553  *
1554  *      Interprets FCGI_Header.  Processes FCGI_BEGIN_REQUEST and
1555  *      management records here; extracts information from stream
1556  *      records (FCGI_PARAMS, FCGI_STDIN) into stream.
1557  *
1558  * Results:
1559  *      >= 0 for a normal return, < 0 for error
1560  *
1561  * Side effects:
1562  *      XXX: Many (more than there used to be).
1563  *      If !stream->isRequestIdSet, ProcessHeader initializes
1564  *      stream->requestId from header and sets stream->isRequestIdSet
1565  *      to TRUE.  ProcessHeader also sets stream->contentLen to header's
1566  *      contentLength, and sets stream->paddingLen to the header's
1567  *      paddingLength.
1568  *
1569  *----------------------------------------------------------------------
1570  */
1571 static int ProcessHeader(FCGI_Header header, FCGX_Stream *stream)
1572 {
1573     FCGX_Stream_Data *data = (FCGX_Stream_Data *)stream->data;
1574     int requestId;
1575     if(header.version != FCGI_VERSION_1) {
1576         return FCGX_UNSUPPORTED_VERSION;
1577     }
1578     requestId =        (header.requestIdB1 << 8)
1579                          + header.requestIdB0;
1580     data->contentLen = (header.contentLengthB1 << 8)
1581                          + header.contentLengthB0;
1582     data->paddingLen = header.paddingLength;
1583     if(header.type == FCGI_BEGIN_REQUEST) {
1584         return ProcessBeginRecord(requestId, stream);
1585     }
1586     if(requestId  == FCGI_NULL_REQUEST_ID) {
1587         return ProcessManagementRecord(header.type, stream);
1588     }
1589     if(requestId != data->reqDataPtr->requestId) {
1590         return SKIP;
1591     }
1592     if(header.type != data->type) {
1593         return FCGX_PROTOCOL_ERROR;
1594     }
1595     return STREAM_RECORD;
1596 }
1597 \f
1598 /*
1599  *----------------------------------------------------------------------
1600  *
1601  * FillBuffProc --
1602  *
1603  *      Reads bytes from the ipcFd, supplies bytes to a stream client.
1604  *
1605  *----------------------------------------------------------------------
1606  */
1607 static void FillBuffProc(FCGX_Stream *stream)
1608 {
1609     FCGX_Stream_Data *data = (FCGX_Stream_Data *)stream->data;
1610     FCGI_Header header;
1611     int headerLen = 0;
1612     int status, count;
1613
1614     for (;;) {
1615         /*
1616          * If data->buff is empty, do a read.
1617          */
1618         if(stream->rdNext == data->buffStop) {
1619             count = OS_Read(data->reqDataPtr->ipcFd, (char *)data->buff,
1620                             data->bufflen);
1621             if(count <= 0) {
1622                 SetError(stream, (count == 0 ? FCGX_PROTOCOL_ERROR : OS_Errno));
1623                 return;
1624             }
1625             stream->rdNext = data->buff;
1626             data->buffStop = data->buff + count;
1627         }
1628         /*
1629          * Now data->buff is not empty.  If the current record contains
1630          * more content bytes, deliver all that are present in data->buff.
1631          */
1632         if(data->contentLen > 0) {
1633             count = min(data->contentLen, data->buffStop - stream->rdNext);
1634             data->contentLen -= count;
1635             if(!data->skip) {
1636                 stream->wrNext = stream->stop = stream->rdNext + count;
1637                 return;
1638             } else {
1639                 stream->rdNext += count;
1640                 if(data->contentLen > 0) {
1641                     continue;
1642                 } else {
1643                     data->skip = FALSE;
1644                 }
1645             }
1646         }
1647         /*
1648          * If the current record (whose content has been fully consumed by
1649          * the client) was padded, skip over the padding bytes.
1650          */
1651         if(data->paddingLen > 0) {
1652             count = min(data->paddingLen, data->buffStop - stream->rdNext);
1653             data->paddingLen -= count;
1654             stream->rdNext += count;
1655             if(data->paddingLen > 0) {
1656                 continue;
1657             }
1658         }
1659         /*
1660          * All done with the current record, including the padding.
1661          * If we're in a recursive call from ProcessHeader, deliver EOF.
1662          */
1663         if(data->eorStop) {
1664             stream->stop = stream->rdNext;
1665             stream->isClosed = TRUE;
1666             return;
1667         }
1668         /*
1669          * Fill header with bytes from the input buffer.
1670          */
1671         count = min((int)sizeof(header) - headerLen,
1672                         data->buffStop - stream->rdNext);
1673         memcpy(((char *)(&header)) + headerLen, stream->rdNext, count);
1674         headerLen += count;
1675         stream->rdNext += count;
1676         if(headerLen < sizeof(header)) {
1677             continue;
1678         };
1679         headerLen = 0;
1680         /*
1681          * Interpret header.  eorStop prevents ProcessHeader from reading
1682          * past the end-of-record when using stream to read content.
1683          */
1684         data->eorStop = TRUE;
1685         stream->stop = stream->rdNext;
1686         status = ProcessHeader(header, stream);
1687         data->eorStop = FALSE;
1688         stream->isClosed = FALSE;
1689         switch(status) {
1690             case STREAM_RECORD:
1691                 /*
1692                  * If this stream record header marked the end of stream
1693                  * data deliver EOF to the stream client, otherwise loop
1694                  * and deliver data.
1695                  *
1696                  * XXX: If this is final stream and
1697                  * stream->rdNext != data->buffStop, buffered
1698                  * data is next request (server pipelining)?
1699                  */
1700                 if(data->contentLen == 0) {
1701                     stream->wrNext = stream->stop = stream->rdNext;
1702                     stream->isClosed = TRUE;
1703                     return;
1704                 }
1705                 break;
1706             case SKIP:
1707                 data->skip = TRUE;
1708                 break;
1709             case BEGIN_RECORD:
1710                 /*
1711                  * If this header marked the beginning of a new
1712                  * request, return role information to caller.
1713                  */
1714                 return;
1715                 break;
1716             case MGMT_RECORD:
1717                 break;
1718             default:
1719                 ASSERT(status < 0);
1720                 SetError(stream, status);
1721                 return;
1722                 break;
1723         }
1724     }
1725 }
1726 \f
1727 /*
1728  *----------------------------------------------------------------------
1729  *
1730  * NewStream --
1731  *
1732  *      Creates a stream to read or write from an open ipcFd.
1733  *      The stream performs reads/writes of up to bufflen bytes.
1734  *
1735  *----------------------------------------------------------------------
1736  */
1737 static FCGX_Stream *NewStream(
1738         FCGX_Request *reqDataPtr, int bufflen, int isReader, int streamType)
1739 {
1740     /*
1741      * XXX: It would be a lot cleaner to have a NewStream that only
1742      * knows about the type FCGX_Stream, with all other
1743      * necessary data passed in.  It appears that not just
1744      * data and the two procs are needed for initializing stream,
1745      * but also data->buff and data->buffStop.  This has implications
1746      * for procs that want to swap buffers, too.
1747      */
1748     FCGX_Stream *stream = (FCGX_Stream *)Malloc(sizeof(FCGX_Stream));
1749     FCGX_Stream_Data *data = (FCGX_Stream_Data *)Malloc(sizeof(FCGX_Stream_Data));
1750     data->reqDataPtr = reqDataPtr;
1751     bufflen = AlignInt8(min(max(bufflen, 32), FCGI_MAX_LENGTH + 1));
1752     data->bufflen = bufflen;
1753     data->mBuff = (unsigned char *)Malloc(bufflen);
1754     data->buff = AlignPtr8(data->mBuff);
1755     if(data->buff != data->mBuff) {
1756         data->bufflen -= 8;
1757     }
1758     if(isReader) {
1759         data->buffStop = data->buff;
1760     } else {
1761         data->buffStop = data->buff + data->bufflen;
1762     }
1763     data->type = streamType;
1764     data->eorStop = FALSE;
1765     data->skip = FALSE;
1766     data->contentLen = 0;
1767     data->paddingLen = 0;
1768     data->isAnythingWritten = FALSE;
1769     data->rawWrite = FALSE;
1770
1771     stream->data = data;
1772     stream->isReader = isReader;
1773     stream->isClosed = FALSE;
1774     stream->wasFCloseCalled = FALSE;
1775     stream->FCGI_errno = 0;
1776     if(isReader) {
1777         stream->fillBuffProc = FillBuffProc;
1778         stream->emptyBuffProc = NULL;
1779         stream->rdNext = data->buff;
1780         stream->stop = stream->rdNext;
1781         stream->stopUnget = data->buff;
1782         stream->wrNext = stream->stop;
1783     } else {
1784         stream->fillBuffProc = NULL;
1785         stream->emptyBuffProc = EmptyBuffProc;
1786         stream->wrNext = data->buff + sizeof(FCGI_Header);
1787         stream->stop = data->buffStop;
1788         stream->stopUnget = NULL;
1789         stream->rdNext = stream->stop;
1790     }
1791     return stream;
1792 }
1793 \f
1794 /*
1795  *----------------------------------------------------------------------
1796  *
1797  * FreeStream --
1798  *
1799  *      Frees all storage allocated when *streamPtr was created,
1800  *      and nulls out *streamPtr.
1801  *
1802  *----------------------------------------------------------------------
1803  */
1804 void FreeStream(FCGX_Stream **streamPtr)
1805 {
1806     FCGX_Stream *stream = *streamPtr;
1807     FCGX_Stream_Data *data;
1808     if(stream == NULL) {
1809         return;
1810     }
1811     data = (FCGX_Stream_Data *)stream->data;
1812     data->reqDataPtr = NULL;
1813     free(data->mBuff);
1814     free(data);
1815     free(stream);
1816     *streamPtr = NULL;
1817 }
1818 \f
1819 /*
1820  *----------------------------------------------------------------------
1821  *
1822  * SetReaderType --
1823  *
1824  *      Re-initializes the stream to read data of the specified type.
1825  *
1826  *----------------------------------------------------------------------
1827  */
1828 static FCGX_Stream *SetReaderType(FCGX_Stream *stream, int streamType)
1829 {
1830     FCGX_Stream_Data *data = (FCGX_Stream_Data *)stream->data;
1831     ASSERT(stream->isReader);
1832     data->type = streamType;
1833     data->eorStop = FALSE;
1834     data->skip = FALSE;
1835     data->contentLen = 0;
1836     data->paddingLen = 0;
1837     stream->wrNext = stream->stop = stream->rdNext;
1838     stream->isClosed = FALSE;
1839     return stream;
1840 }
1841 \f
1842 /*
1843  *----------------------------------------------------------------------
1844  *
1845  * NewReader --
1846  *
1847  *      Creates a stream to read streamType records for the given
1848  *      request.  The stream performs OS reads of up to bufflen bytes.
1849  *
1850  *----------------------------------------------------------------------
1851  */
1852 static FCGX_Stream *NewReader(FCGX_Request *reqDataPtr, int bufflen, int streamType)
1853 {
1854     return NewStream(reqDataPtr, bufflen, TRUE, streamType);
1855 }
1856
1857
1858 /*
1859  *----------------------------------------------------------------------
1860  *
1861  * NewWriter --
1862  *
1863  *      Creates a stream to write streamType FastCGI records, using
1864  *      the ipcFd and RequestId contained in *reqDataPtr.
1865  *      The stream performs OS writes of up to bufflen bytes.
1866  *
1867  *----------------------------------------------------------------------
1868  */
1869 static FCGX_Stream *NewWriter(FCGX_Request *reqDataPtr, int bufflen, int streamType)
1870 {
1871     return NewStream(reqDataPtr, bufflen, FALSE, streamType);
1872 }
1873
1874
1875 /*
1876  *----------------------------------------------------------------------
1877  *
1878  * 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 *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 \f
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 \f
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     if (reqDataPtr == NULL) {
1990         return;
1991     }
1992
1993     /* This should probably use a 'status' member instead of 'in' */
1994     if (reqDataPtr->in) {
1995         int errStatus = FCGX_FClose(reqDataPtr->err);
1996         int outStatus = FCGX_FClose(reqDataPtr->out);
1997
1998         if (errStatus || outStatus || FCGX_GetError(reqDataPtr->in))
1999         {
2000             OS_IpcClose(reqDataPtr->ipcFd);
2001             reqDataPtr->ipcFd = -1;
2002         }
2003     }
2004
2005     FCGX_Free(reqDataPtr);
2006 }
2007
2008 void FCGX_Free(FCGX_Request * request)
2009 {
2010     if (request == NULL) 
2011         return;
2012
2013     FreeStream(&request->in);
2014     FreeStream(&request->out);
2015     FreeStream(&request->err);
2016     FreeParams(&request->paramsPtr);
2017
2018     if (!request->keepConnection)
2019     {
2020         OS_IpcClose(request->ipcFd);
2021         request->ipcFd = -1;
2022     }
2023 }
2024
2025 int FCGX_OpenSocket(const char *path, int backlog)
2026 {
2027     int rc = OS_CreateLocalIpcFd(path, backlog);
2028     if (rc == FCGI_LISTENSOCK_FILENO && isFastCGI == 0) {
2029         /* XXX probably need to call OS_LibInit() again for Win */
2030         isFastCGI = 1;
2031     }
2032     return rc;
2033 }
2034
2035 int FCGX_InitRequest(FCGX_Request *request, int sock, int flags)
2036 {
2037     memset(request, 0, sizeof(FCGX_Request));
2038
2039     /* @@@ Should check that sock is open and listening */
2040     request->listen_sock = sock;
2041
2042     /* @@@ Should validate against "known" flags */
2043     request->flags = flags;
2044
2045     request->ipcFd = -1;
2046
2047     return 0;
2048 }
2049
2050 /*
2051  *----------------------------------------------------------------------
2052  *
2053  * FCGX_Init --
2054  *
2055  *      Initilize the FCGX library.  This is called by FCGX_Accept()
2056  *      but must be called by the user when using FCGX_Accept_r().
2057  *
2058  * Results:
2059  *          0 for successful call.
2060  *
2061  *----------------------------------------------------------------------
2062  */
2063 int FCGX_Init(void)
2064 {
2065     char *p;
2066
2067     if (libInitialized) {
2068         return 0;
2069     }
2070
2071     /* If our compiler doesn't play by the ISO rules for struct layout, halt. */
2072     ASSERT(sizeof(FCGI_Header) == FCGI_HEADER_LEN);
2073
2074     FCGX_InitRequest(&the_request, FCGI_LISTENSOCK_FILENO, 0);
2075
2076     if (OS_LibInit(NULL) == -1) {
2077         return OS_Errno ? OS_Errno : -9997;
2078     }
2079
2080     p = getenv("FCGI_WEB_SERVER_ADDRS");
2081     webServerAddressList = p ? StringCopy(p) : NULL;
2082
2083     libInitialized = 1;
2084     return 0;
2085 }
2086
2087 /*
2088  *----------------------------------------------------------------------
2089  *
2090  * FCGX_Accept --
2091  *
2092  *      Accepts a new request from the HTTP server.
2093  *
2094  * Results:
2095  *      0 for successful call, -1 for error.
2096  *
2097  * Side effects:
2098  *
2099  *      Finishes the request accepted by (and frees any
2100  *      storage allocated by) the previous call to FCGX_Accept.
2101  *      Creates input, output, and error streams and
2102  *      assigns them to *in, *out, and *err respectively.
2103  *      Creates a parameters data structure to be accessed
2104  *      via getenv(3) (if assigned to environ) or by FCGX_GetParam
2105  *      and assigns it to *envp.
2106  *
2107  *      DO NOT retain pointers to the envp array or any strings
2108  *      contained in it (e.g. to the result of calling FCGX_GetParam),
2109  *      since these will be freed by the next call to FCGX_Finish
2110  *      or FCGX_Accept.
2111  *
2112  *----------------------------------------------------------------------
2113  */
2114
2115 int FCGX_Accept(
2116         FCGX_Stream **in,
2117         FCGX_Stream **out,
2118         FCGX_Stream **err,
2119         FCGX_ParamArray *envp)
2120 {
2121     int rc;
2122
2123     if (!libInitialized) {
2124         if ((rc = FCGX_Init())) {
2125             return (rc < 0) ? rc : -rc;
2126         }
2127     }
2128
2129     rc = FCGX_Accept_r(&the_request);
2130
2131     *in = the_request.in;
2132     *out = the_request.out;
2133     *err = the_request.err;
2134     *envp = the_request.envp;
2135
2136     return rc;
2137 }
2138
2139 /*
2140  *----------------------------------------------------------------------
2141  *
2142  * FCGX_Accept_r --
2143  *
2144  *      Accepts a new request from the HTTP server.
2145  *
2146  * Results:
2147  *      0 for successful call, -1 for error.
2148  *
2149  * Side effects:
2150  *
2151  *      Finishes the request accepted by (and frees any
2152  *      storage allocated by) the previous call to FCGX_Accept.
2153  *      Creates input, output, and error streams and
2154  *      assigns them to *in, *out, and *err respectively.
2155  *      Creates a parameters data structure to be accessed
2156  *      via getenv(3) (if assigned to environ) or by FCGX_GetParam
2157  *      and assigns it to *envp.
2158  *
2159  *      DO NOT retain pointers to the envp array or any strings
2160  *      contained in it (e.g. to the result of calling FCGX_GetParam),
2161  *      since these will be freed by the next call to FCGX_Finish
2162  *      or FCGX_Accept.
2163  *
2164  *----------------------------------------------------------------------
2165  */
2166 int FCGX_Accept_r(FCGX_Request *reqDataPtr)
2167 {
2168     if (!libInitialized) {
2169         return -9998;
2170     }
2171
2172     /* Finish the current request, if any. */
2173     FCGX_Finish_r(reqDataPtr);
2174
2175     for (;;) {
2176         /*
2177          * If a connection isn't open, accept a new connection (blocking).
2178          * If an OS error occurs in accepting the connection,
2179          * return -1 to the caller, who should exit.
2180          */
2181         if (reqDataPtr->ipcFd < 0) {
2182             int fail_on_intr = reqDataPtr->flags & FCGI_FAIL_ACCEPT_ON_INTR;
2183
2184             reqDataPtr->ipcFd = OS_Accept(reqDataPtr->listen_sock, fail_on_intr, webServerAddressList);
2185             if (reqDataPtr->ipcFd < 0) {
2186                 return (errno > 0) ? (0 - errno) : -9999;
2187             }
2188         }
2189         /*
2190          * A connection is open.  Read from the connection in order to
2191          * get the request's role and environment.  If protocol or other
2192          * errors occur, close the connection and try again.
2193          */
2194         reqDataPtr->isBeginProcessed = FALSE;
2195         reqDataPtr->in = NewReader(reqDataPtr, 8192, 0);
2196         FillBuffProc(reqDataPtr->in);
2197         if(!reqDataPtr->isBeginProcessed) {
2198             goto TryAgain;
2199         }
2200         {
2201             char *roleStr;
2202             switch(reqDataPtr->role) {
2203                 case FCGI_RESPONDER:
2204                     roleStr = "FCGI_ROLE=RESPONDER";
2205                     break;
2206                 case FCGI_AUTHORIZER:
2207                     roleStr = "FCGI_ROLE=AUTHORIZER";
2208                     break;
2209                 case FCGI_FILTER:
2210                     roleStr = "FCGI_ROLE=FILTER";
2211                     break;
2212                 default:
2213                     goto TryAgain;
2214             }
2215             reqDataPtr->paramsPtr = NewParams(30);
2216             PutParam(reqDataPtr->paramsPtr, StringCopy(roleStr));
2217         }
2218         SetReaderType(reqDataPtr->in, FCGI_PARAMS);
2219         if(ReadParams(reqDataPtr->paramsPtr, reqDataPtr->in) >= 0) {
2220             /*
2221              * Finished reading the environment.  No errors occurred, so
2222              * leave the connection-retry loop.
2223              */
2224             break;
2225         }
2226
2227         /*
2228          * Close the connection and try again.
2229          */
2230 TryAgain:
2231         FCGX_Free(reqDataPtr);
2232
2233     } /* for (;;) */
2234     /*
2235      * Build the remaining data structures representing the new
2236      * request and return successfully to the caller.
2237      */
2238     SetReaderType(reqDataPtr->in, FCGI_STDIN);
2239     reqDataPtr->out = NewWriter(reqDataPtr, 8192, FCGI_STDOUT);
2240     reqDataPtr->err = NewWriter(reqDataPtr, 512, FCGI_STDERR);
2241     reqDataPtr->nWriters = 2;
2242     reqDataPtr->envp = reqDataPtr->paramsPtr->vec;
2243     return 0;
2244 }
2245 \f
2246 /*
2247  *----------------------------------------------------------------------
2248  *
2249  * FCGX_StartFilterData --
2250  *
2251  *      stream is an input stream for a FCGI_FILTER request.
2252  *      stream is positioned at EOF on FCGI_STDIN.
2253  *      Repositions stream to the start of FCGI_DATA.
2254  *      If the preconditions are not met (e.g. FCGI_STDIN has not
2255  *      been read to EOF) sets the stream error code to
2256  *      FCGX_CALL_SEQ_ERROR.
2257  *
2258  * Results:
2259  *      0 for a normal return, < 0 for error
2260  *
2261  *----------------------------------------------------------------------
2262  */
2263
2264 int FCGX_StartFilterData(FCGX_Stream *stream)
2265 {
2266     FCGX_Stream_Data *data = (FCGX_Stream_Data *)stream->data;
2267     if(data->reqDataPtr->role != FCGI_FILTER
2268             || !stream->isReader
2269             || !stream->isClosed
2270             || data->type != FCGI_STDIN) {
2271         SetError(stream, FCGX_CALL_SEQ_ERROR);
2272         return -1;
2273     }
2274     SetReaderType(stream, FCGI_DATA);
2275     return 0;
2276 }
2277 \f
2278 /*
2279  *----------------------------------------------------------------------
2280  *
2281  * FCGX_SetExitStatus --
2282  *
2283  *      Sets the exit status for stream's request. The exit status
2284  *      is the status code the request would have exited with, had
2285  *      the request been run as a CGI program.  You can call
2286  *      SetExitStatus several times during a request; the last call
2287  *      before the request ends determines the value.
2288  *
2289  *----------------------------------------------------------------------
2290  */
2291
2292 void FCGX_SetExitStatus(int status, FCGX_Stream *stream)
2293 {
2294     FCGX_Stream_Data *data = (FCGX_Stream_Data *)stream->data;
2295     data->reqDataPtr->appStatus = status;
2296 }
2297