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