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