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