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