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