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