Delete not needed M$ VC++ file.
[catagits/fcgi2.git] / cgi-fcgi / cgi-fcgi.c
1 /*
2  * cgifcgi.c --
3  *
4  *      CGI to FastCGI bridge
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: cgi-fcgi.c,v 1.10 1999/08/27 19:39:17 roberts Exp $";
15 #endif /* not lint */
16
17 #include "fcgi_config.h"
18
19 #include <assert.h>
20 #include <ctype.h>
21 #include <errno.h>
22 #include <fcntl.h>
23 #include <stdio.h>
24 #include <stdlib.h>
25 #include <string.h>
26
27 #ifdef HAVE_NETDB_H
28 #include <netdb.h>
29 #endif
30
31 #ifdef _WIN32
32 #include <stdlib.h>
33 #else
34 extern char **environ;
35 #endif
36
37 #ifdef HAVE_SYS_PARAM_H
38 #include <sys/param.h>
39 #endif
40
41 #ifdef HAVE_SYS_TIME_H
42 #include <sys/time.h>
43 #endif
44
45 #if defined HAVE_UNISTD_H
46 #include <unistd.h>
47 #endif
48
49 #include "fcgimisc.h"
50 #include "fcgiapp.h"
51 #include "fcgiappmisc.h"
52 #include "fastcgi.h"
53 #include "fcgios.h"
54
55
56 static int wsReadPending = 0;
57 static int fcgiReadPending = 0;
58 static int fcgiWritePending = 0;
59
60 static void ScheduleIo(void);
61
62 \f
63 /*
64  * Simple buffer (not ring buffer) type, used by all event handlers.
65  */
66 #define BUFFLEN 8192
67 typedef struct {
68     char *next;
69     char *stop;
70     char buff[BUFFLEN];
71 } Buffer;
72
73 /*
74  *----------------------------------------------------------------------
75  *
76  * GetPtr --
77  *
78  *      Returns a count of the number of characters available
79  *      in the buffer (at most n) and advances past these
80  *      characters.  Stores a pointer to the first of these
81  *      characters in *ptr.
82  *
83  *----------------------------------------------------------------------
84  */
85
86 static int GetPtr(char **ptr, int n, Buffer *pBuf)
87 {
88     int result;
89     *ptr = pBuf->next;
90     result = min(n, pBuf->stop - pBuf->next);
91     pBuf->next += result;
92     return result;
93 }
94 \f
95 /*
96  *----------------------------------------------------------------------
97  *
98  * MakeHeader --
99  *
100  *      Constructs an FCGI_Header struct.
101  *
102  *----------------------------------------------------------------------
103  */
104 static FCGI_Header MakeHeader(
105         int type,
106         int requestId,
107         int contentLength,
108         int paddingLength)
109 {
110     FCGI_Header header;
111     ASSERT(contentLength >= 0 && contentLength <= FCGI_MAX_LENGTH);
112     ASSERT(paddingLength >= 0 && paddingLength <= 0xff);
113     header.version = FCGI_VERSION_1;
114     header.type             =  type;
115     header.requestIdB1      = (requestId      >> 8) & 0xff;
116     header.requestIdB0      = (requestId          ) & 0xff;
117     header.contentLengthB1  = (contentLength  >> 8) & 0xff;
118     header.contentLengthB0  = (contentLength      ) & 0xff;
119     header.paddingLength    =  paddingLength;
120     header.reserved         =  0;
121     return header;
122 }
123 \f
124 /*
125  *----------------------------------------------------------------------
126  *
127  * MakeBeginRequestBody --
128  *
129  *      Constructs an FCGI_BeginRequestBody record.
130  *
131  *----------------------------------------------------------------------
132  */
133 static FCGI_BeginRequestBody MakeBeginRequestBody(
134         int role,
135         int keepConnection)
136 {
137     FCGI_BeginRequestBody body;
138     ASSERT((role >> 16) == 0);
139     body.roleB1 = (role >>  8) & 0xff;
140     body.roleB0 = (role      ) & 0xff;
141     body.flags = (keepConnection) ? FCGI_KEEP_CONN : 0;
142     memset(body.reserved, 0, sizeof(body.reserved));
143     return body;
144 }
145
146 \f
147 static int bytesToRead;    /* number of bytes to read from Web Server */
148 static int appServerSock = -1;  /* Socket connected to FastCGI application,
149                                  * used by AppServerReadHandler and
150                                  * AppServerWriteHandler. */
151 static Buffer fromAS;      /* Bytes read from the FCGI application server. */
152 static FCGI_Header header; /* Header of the current record.  Is global
153                             * since read may return a partial header. */
154 static int headerLen = 0;  /* Number of valid bytes contained in header.
155                             * If headerLen < sizeof(header),
156                             * AppServerReadHandler is reading a record header;
157                             * otherwise it is reading bytes of record content
158                             * or padding. */
159 static int contentLen;     /* If headerLen == sizeof(header), contentLen
160                             * is the number of content bytes still to be
161                             * read. */
162 static int paddingLen;     /* If headerLen == sizeof(header), paddingLen
163                             * is the number of padding bytes still
164                             * to be read. */
165 static int requestId;      /* RequestId of the current request.
166                             * Set by main. */
167 static FCGI_EndRequestBody erBody;
168 static int readingEndRequestBody = FALSE;
169                            /* If readingEndRequestBody, erBody contains
170                             * partial content: contentLen more bytes need
171                             * to be read. */
172 static int exitStatus = 0;
173 static int exitStatusSet = FALSE;
174
175 static int stdinFds[3];
176
177 \f
178 /*
179  *----------------------------------------------------------------------
180  *
181  * FCGIexit --
182  *
183  *      FCGIexit provides a single point of exit.  It's main use is for
184  *      application debug when porting to other operating systems.
185  *
186  *----------------------------------------------------------------------
187  */
188 static void FCGIexit(int exitCode)
189 {
190     if(appServerSock != -1) {
191         OS_Close(appServerSock);
192         appServerSock = -1;
193     }
194     OS_LibShutdown();
195     exit(exitCode);
196 }
197
198 #undef exit
199 #define exit FCGIexit
200
201 \f
202 /*
203  *----------------------------------------------------------------------
204  *
205  * AppServerReadHandler --
206  *
207  *      Reads data from the FCGI application server and (blocking)
208  *      writes all of it to the Web server.  Exits the program upon
209  *      reading EOF from the FCGI application server.  Called only when
210  *      there's data ready to read from the application server.
211  *
212  *----------------------------------------------------------------------
213  */
214
215 static void AppServerReadHandler(ClientData clientData, int bytesRead)
216 {
217     int count, outFD;
218     char *ptr;
219
220     assert(fcgiReadPending == TRUE);
221     fcgiReadPending = FALSE;
222     count = bytesRead;
223
224     if(count <= 0) {
225         if(count < 0) {
226             exit(OS_Errno);
227         }
228         if(headerLen > 0 || paddingLen > 0) {
229             exit(FCGX_PROTOCOL_ERROR);
230         }
231         if(appServerSock != -1) {
232             OS_Close(appServerSock);
233             appServerSock = -1;
234         }
235         /*
236          * XXX: Shouldn't be here if exitStatusSet.
237          */
238         exit((exitStatusSet) ? exitStatus : FCGX_PROTOCOL_ERROR);
239     }
240     fromAS.stop = fromAS.next + count;
241     while(fromAS.next != fromAS.stop) {
242         /*
243          * fromAS is not empty.  What to do with the contents?
244          */
245         if(headerLen < sizeof(header)) {
246             /*
247              * First priority is to complete the header.
248              */
249             count = GetPtr(&ptr, sizeof(header) - headerLen, &fromAS);
250             assert(count > 0);
251             memcpy(&header + headerLen, ptr, count);
252             headerLen += count;
253             if(headerLen < sizeof(header)) {
254                 break;
255             }
256             if(header.version != FCGI_VERSION_1) {
257                 exit(FCGX_UNSUPPORTED_VERSION);
258             }
259             if((header.requestIdB1 << 8) + header.requestIdB0 != requestId) {
260                 exit(FCGX_PROTOCOL_ERROR);
261             }
262             contentLen = (header.contentLengthB1 << 8)
263                          + header.contentLengthB0;
264             paddingLen =  header.paddingLength;
265         } else {
266             /*
267              * Header is complete (possibly from previous call).  What now?
268              */
269             switch(header.type) {
270                 case FCGI_STDOUT:
271                 case FCGI_STDERR:
272                     /*
273                      * Write the buffered content to stdout or stderr.
274                      * Blocking writes are OK here; can't prevent a slow
275                      * client from tying up the app server without buffering
276                      * output in temporary files.
277                      */
278                     count = GetPtr(&ptr, contentLen, &fromAS);
279                     contentLen -= count;
280                     if(count > 0) {
281                         outFD = (header.type == FCGI_STDOUT) ?
282                                     STDOUT_FILENO : STDERR_FILENO;
283                         if(OS_Write(outFD, ptr, count) < 0) {
284                             exit(OS_Errno);
285                         }
286                     }
287                     break;
288                 case FCGI_END_REQUEST:
289                     if(!readingEndRequestBody) {
290                         if(contentLen != sizeof(erBody)) {
291                             exit(FCGX_PROTOCOL_ERROR);
292                         }
293                         readingEndRequestBody = TRUE;
294                     }
295                     count = GetPtr(&ptr, contentLen, &fromAS);
296                     if(count > 0) {
297                         memcpy(&erBody + sizeof(erBody) - contentLen,
298                                 ptr, count);
299                         contentLen -= count;
300                     }
301                     if(contentLen == 0) {
302                         if(erBody.protocolStatus != FCGI_REQUEST_COMPLETE) {
303                             /*
304                              * XXX: What to do with FCGI_OVERLOADED?
305                              */
306                             exit(FCGX_PROTOCOL_ERROR);
307                         }
308                         exitStatus = (erBody.appStatusB3 << 24)
309                                    + (erBody.appStatusB2 << 16)
310                                    + (erBody.appStatusB1 <<  8)
311                                    + (erBody.appStatusB0      );
312                         exitStatusSet = TRUE;
313                         readingEndRequestBody = FALSE;
314                     }
315                     break;
316                 case FCGI_GET_VALUES_RESULT:
317                     /* coming soon */
318                 case FCGI_UNKNOWN_TYPE:
319                     /* coming soon */
320                 default:
321                     exit(FCGX_PROTOCOL_ERROR);
322             }
323             if(contentLen == 0) {
324                 if(paddingLen > 0) {
325                     paddingLen -= GetPtr(&ptr, paddingLen, &fromAS);
326                 }
327                 /*
328                  * If we've processed all the data and skipped all the
329                  * padding, discard the header and look for the next one.
330                  */
331                 if(paddingLen == 0) {
332                     headerLen = 0;
333                 }
334             }
335         } /* headerLen >= sizeof(header) */
336     } /*while*/
337     ScheduleIo();
338 }
339 \f
340 static Buffer fromWS;   /* Buffer for data read from Web server
341                          * and written to FastCGI application. Used
342                          * by WebServerReadHandler and
343                          * AppServerWriteHandler. */
344 static int webServerReadHandlerEOF;
345                         /* TRUE iff WebServerReadHandler has read EOF from
346                          * the Web server. Used in main to prevent
347                          * rescheduling WebServerReadHandler. */
348
349 static void WriteStdinEof(void)
350 {
351     static int stdin_eof_sent = 0;
352
353     if (stdin_eof_sent)
354         return;
355
356     *((FCGI_Header *)fromWS.stop) = MakeHeader(FCGI_STDIN, requestId, 0, 0);
357     fromWS.stop += sizeof(FCGI_Header);
358     stdin_eof_sent = 1;
359 }
360
361 /*
362  *----------------------------------------------------------------------
363  *
364  * WebServerReadHandler --
365  *
366  *      Non-blocking reads data from the Web server into the fromWS
367  *      buffer.  Called only when fromWS is empty, no EOF has been
368  *      received from the Web server, and there's data available to read.
369  *
370  *----------------------------------------------------------------------
371  */
372
373 static void WebServerReadHandler(ClientData clientData, int bytesRead)
374 {
375     assert(fromWS.next == fromWS.stop);
376     assert(fromWS.next == &fromWS.buff[0]);
377     assert(wsReadPending == TRUE);
378     wsReadPending = FALSE;
379
380     if(bytesRead < 0) {
381         exit(OS_Errno);
382     }
383     *((FCGI_Header *) &fromWS.buff[0])
384             = MakeHeader(FCGI_STDIN, requestId, bytesRead, 0);
385     bytesToRead -= bytesRead;
386     fromWS.stop = &fromWS.buff[sizeof(FCGI_Header) + bytesRead];
387     webServerReadHandlerEOF = (bytesRead == 0);
388
389     if (bytesToRead <= 0)
390         WriteStdinEof();
391
392     ScheduleIo();
393 }
394 \f
395 /*
396  *----------------------------------------------------------------------
397  *
398  * AppServerWriteHandler --
399  *
400  *      Non-blocking writes data from the fromWS buffer to the FCGI
401  *      application server.  Called only when fromWS is non-empty
402  *      and the socket is ready to accept some data.
403  *
404  *----------------------------------------------------------------------
405  */
406
407 static void AppServerWriteHandler(ClientData clientData, int bytesWritten)
408 {
409     int length = fromWS.stop - fromWS.next;
410
411     assert(length > 0);
412     assert(fcgiWritePending == TRUE);
413
414     fcgiWritePending = FALSE;
415     if(bytesWritten < 0) {
416         exit(OS_Errno);
417     }
418     if((int)bytesWritten < length) {
419         fromWS.next += bytesWritten;
420     } else {
421         fromWS.stop = fromWS.next = &fromWS.buff[0];
422     }
423
424     ScheduleIo();
425 }
426
427 \f
428 /*
429  * ScheduleIo --
430  *
431  *      This functions is responsible for scheduling all I/O to move
432  *      data between a web server and a FastCGI application.
433  *
434  * Results:
435  *      None.
436  *
437  * Side effects:
438  *      This routine will signal the ioEvent upon completion.
439  *
440  */
441 static void ScheduleIo(void)
442 {
443     int length;
444
445     /*
446      * Move data between standard in and the FastCGI connection.
447      */
448     if(!fcgiWritePending && appServerSock != -1 &&
449        ((length = fromWS.stop - fromWS.next) != 0)) {
450         if(OS_AsyncWrite(appServerSock, 0, fromWS.next, length,
451                          AppServerWriteHandler,
452                          (ClientData)appServerSock) == -1) {
453             FCGIexit(OS_Errno);
454         } else {
455             fcgiWritePending = TRUE;
456         }
457     }
458
459     /*
460      * Schedule a read from the FastCGI application if there's not
461      * one pending and there's room in the buffer.
462      */
463     if(!fcgiReadPending && appServerSock != -1) {
464         fromAS.next = &fromAS.buff[0];
465
466         if(OS_AsyncRead(appServerSock, 0, fromAS.next, BUFFLEN,
467                         AppServerReadHandler,
468                         (ClientData)appServerSock) == -1) {
469             FCGIexit(OS_Errno);
470         } else {
471             fcgiReadPending = TRUE;
472         }
473     }
474
475     /*
476      * Schedule a read from standard in if necessary.
477      */
478     if((bytesToRead > 0) && !webServerReadHandlerEOF && !wsReadPending &&
479        !fcgiWritePending &&
480        fromWS.next == &fromWS.buff[0]) {
481         if(OS_AsyncReadStdin(fromWS.next + sizeof(FCGI_Header),
482                              BUFFLEN - sizeof(FCGI_Header),
483                              WebServerReadHandler, STDIN_FILENO)== -1) {
484             FCGIexit(OS_Errno);
485         } else {
486             wsReadPending = TRUE;
487         }
488     }
489 }
490
491 \f
492 /*
493  *----------------------------------------------------------------------
494  *
495  * FCGI_Start --
496  *
497  *      Starts nServers copies of FCGI application appPath, all
498  *      listening to a Unix Domain socket at bindPath.
499  *
500  *----------------------------------------------------------------------
501  */
502
503 static void FCGI_Start(char *bindPath, char *appPath, int nServers)
504 {
505     int listenFd, i;
506
507     /* @@@ Should be able to pick up the backlog as an arg */
508     if((listenFd = OS_CreateLocalIpcFd(bindPath, 5)) == -1) {
509         exit(OS_Errno);
510     }
511
512     if(access(appPath, X_OK) == -1) {
513         fprintf(stderr, "%s is not executable\n", appPath);
514         exit(1);
515     }
516
517     /*
518      * Create the server processes
519      */
520     for(i = 0; i < nServers; i++) {
521         if(OS_SpawnChild(appPath, listenFd) == -1) {
522             exit(OS_Errno);
523         }
524     }
525     OS_Close(listenFd);
526 }
527 \f
528 /*
529  *----------------------------------------------------------------------
530  *
531  * FCGIUtil_BuildNameValueHeader --
532  *
533  *      Builds a name-value pair header from the name length
534  *      and the value length.  Stores the header into *headerBuffPtr,
535  *      and stores the length of the header into *headerLenPtr.
536  *
537  * Side effects:
538  *      Stores header's length (at most 8) into *headerLenPtr,
539  *      and stores the header itself into
540  *      headerBuffPtr[0 .. *headerLenPtr - 1].
541  *
542  *----------------------------------------------------------------------
543  */
544 static void FCGIUtil_BuildNameValueHeader(
545         int nameLen,
546         int valueLen,
547         unsigned char *headerBuffPtr,
548         int *headerLenPtr) {
549     unsigned char *startHeaderBuffPtr = headerBuffPtr;
550
551     ASSERT(nameLen >= 0);
552     if (nameLen < 0x80) {
553         *headerBuffPtr++ = nameLen;
554     } else {
555         *headerBuffPtr++ = (nameLen >> 24) | 0x80;
556         *headerBuffPtr++ = (nameLen >> 16);
557         *headerBuffPtr++ = (nameLen >> 8);
558         *headerBuffPtr++ = nameLen;
559     }
560     ASSERT(valueLen >= 0);
561     if (valueLen < 0x80) {
562         *headerBuffPtr++ = valueLen;
563     } else {
564         *headerBuffPtr++ = (valueLen >> 24) | 0x80;
565         *headerBuffPtr++ = (valueLen >> 16);
566         *headerBuffPtr++ = (valueLen >> 8);
567         *headerBuffPtr++ = valueLen;
568     }
569     *headerLenPtr = headerBuffPtr - startHeaderBuffPtr;
570 }
571 \f
572
573 #define MAXARGS 16
574 static int ParseArgs(int argc, char *argv[],
575         int *doBindPtr, int *doStartPtr,
576         char *connectPathPtr, char *appPathPtr, int *nServersPtr) {
577     int     i,
578             x,
579             err = 0,
580             ac;
581     char    *tp1,
582             *tp2,
583             *av[MAXARGS];
584     FILE    *fp;
585     char    line[BUFSIZ];
586
587     *doBindPtr = TRUE;
588     *doStartPtr = TRUE;
589     *connectPathPtr = '\0';
590     *appPathPtr = '\0';
591     *nServersPtr = 0;
592
593     for(i = 0; i < MAXARGS; i++)
594         av[i] = NULL;
595     for(i = 1; i < argc; i++) {
596         if(argv[i][0] == '-') {
597             if(!strcmp(argv[i], "-f")) {
598                 if(++i == argc) {
599                     fprintf(stderr,
600                             "Missing command file name after -f\n");
601                     return 1;
602                 }
603                 if((fp = fopen(argv[i], "r")) == NULL) {
604                     fprintf(stderr, "Cannot open command file %s\n", argv[i]);
605                     return 1;
606                 }
607                 ac = 1;
608                 while(fgets(line, BUFSIZ, fp)) {
609                     if(line[0] == '#') {
610                         continue;
611                     }
612                     if((tp1 = (char *) strrchr(line,'\n')) != NULL) {
613                         *tp1-- = 0;
614                         while(*tp1 == ' ' || *tp1 =='\t') {
615                             *tp1-- = 0;
616                         }
617                     } else {
618                         fprintf(stderr, "Line to long\n");
619                         return 1;
620                     }
621                     tp1 = line;
622                     while(tp1) {
623                         if((tp2 = strchr(tp1, ' ')) != NULL) {
624                             *tp2++ =  0;
625                         }
626                         if(ac >= MAXARGS) {
627                             fprintf(stderr,
628                                     "To many arguments, "
629                                     "%d is max from a file\n", MAXARGS);
630                                 exit(-1);
631                         }
632                         if((av[ac] = (char *)malloc(strlen(tp1)+1)) == NULL) {
633                             fprintf(stderr, "Cannot allocate %d bytes\n",
634                                     strlen(tp1)+1);
635                             exit(-1);
636                         }
637                         strcpy(av[ac++], tp1);
638                         tp1 = tp2;
639                     }
640                 }
641                 err = ParseArgs(ac, av, doBindPtr, doStartPtr,
642                         connectPathPtr, appPathPtr, nServersPtr);
643                 for(x = 1; x < ac; x++) {
644                     ASSERT(av[x] != NULL);
645                     free(av[x]);
646                 }
647                 return err;
648 #ifdef _WIN32
649             } else if (!strcmp(argv[i], "-jitcgi")) {
650                 DebugBreak();
651             } else if (!strcmp(argv[i], "-dbgfcgi")) {
652                 putenv("DEBUG_FCGI=TRUE");
653 #endif
654             } else if(!strcmp(argv[i], "-start")) {
655                 *doBindPtr = FALSE;
656             } else if(!strcmp(argv[i], "-bind")) {
657                 *doStartPtr = FALSE;
658             } else if(!strcmp(argv[i], "-connect")) {
659                 if(++i == argc) {
660                     fprintf(stderr,
661                             "Missing connection name after -connect\n");
662                     err++;
663                 } else {
664                     strcpy(connectPathPtr, argv[i]);
665                 }
666             } else {
667                 fprintf(stderr, "Unknown option %s\n", argv[i]);
668                 err++;
669             }
670         } else if(*appPathPtr == '\0') {
671             strcpy(appPathPtr, argv[i]);
672         } else if(isdigit((int)argv[i][0]) && *nServersPtr == 0) {
673             *nServersPtr = atoi(argv[i]);
674             if(*nServersPtr <= 0) {
675                 fprintf(stderr, "Number of servers must be greater than 0\n");
676                 err++;
677             }
678         } else {
679             fprintf(stderr, "Unknown argument %s\n", argv[i]);
680             err++;
681         }
682     }
683     if(*doStartPtr && *appPathPtr == 0) {
684         fprintf(stderr, "Missing application pathname\n");
685         err++;
686     }
687     if(*connectPathPtr == 0) {
688         fprintf(stderr, "Missing -connect <connName>\n");
689         err++;
690     } else if(strchr(connectPathPtr, ':')) {
691 /*
692  * XXX: Test to see if we can use IP connect locally...
693         This hack lets me test the ability to create a local process listening
694         to a TCP/IP port for connections and subsequently connect to the app
695         like we do for Unix domain and named pipes.
696
697         if(*doStartPtr && *doBindPtr) {
698             fprintf(stderr,
699                     "<connName> of form hostName:portNumber "
700                     "requires -start or -bind\n");
701             err++;
702         }
703  */
704     }
705     if(*nServersPtr == 0) {
706         *nServersPtr = 1;
707     }
708     return err;
709 }
710 \f
711 int main(int argc, char **argv)
712 {
713     char **envp = environ;
714     int count;
715     FCGX_Stream *paramsStream;
716     int numFDs;
717     unsigned char headerBuff[8];
718     int headerLen, valueLen;
719     char *equalPtr;
720     FCGI_BeginRequestRecord beginRecord;
721     int doBind, doStart, nServers;
722     char appPath[MAXPATHLEN], bindPath[MAXPATHLEN];
723
724     if(ParseArgs(argc, argv, &doBind, &doStart,
725                    (char *) &bindPath, (char *) &appPath, &nServers)) {
726         fprintf(stderr,
727 "Usage:\n"
728 "    cgi-fcgi -f <cmdPath> , or\n"
729 "    cgi-fcgi -connect <connName> <appPath> [<nServers>] , or\n"
730 "    cgi-fcgi -start -connect <connName> <appPath> [<nServers>] , or\n"
731 "    cgi-fcgi -bind -connect <connName> ,\n"
732 "where <connName> is either the pathname of a UNIX domain socket\n"
733 "or (if -bind is given) a hostName:portNumber specification\n"
734 "or (if -start is given) a :portNumber specification (uses local host).\n");
735         exit(1);
736     }
737
738     if(OS_LibInit(stdinFds)) {
739         fprintf(stderr, "Error initializing OS library: %d\n", OS_Errno);
740         exit(0);
741     }
742
743     equalPtr = getenv("CONTENT_LENGTH");
744     if(equalPtr != NULL) {
745         bytesToRead = atoi(equalPtr);
746     } else {
747         bytesToRead = 0;
748     }
749
750     if(doBind) {
751         appServerSock = OS_FcgiConnect(bindPath);
752     }
753     if(doStart && (!doBind || appServerSock < 0)) {
754         FCGI_Start(bindPath, appPath, nServers);
755         if(!doBind) {
756             exit(0);
757         } else {
758             appServerSock = OS_FcgiConnect(bindPath);
759         }
760     }
761     if(appServerSock < 0) {
762         fprintf(stderr, "Could not connect to %s\n", bindPath);
763         exit(OS_Errno);
764     }
765     /*
766      * Set an arbitrary non-null FCGI RequestId
767      */
768     requestId = 1;
769     /*
770      * XXX: Send FCGI_GET_VALUES
771      */
772
773     /*
774      * XXX: Receive FCGI_GET_VALUES_RESULT
775      */
776
777     /*
778      * Send FCGI_BEGIN_REQUEST (XXX: hack, separate write)
779      */
780     beginRecord.header = MakeHeader(FCGI_BEGIN_REQUEST, requestId,
781             sizeof(beginRecord.body), 0);
782     beginRecord.body = MakeBeginRequestBody(FCGI_RESPONDER, FALSE);
783     count = OS_Write(appServerSock, (char *)&beginRecord, sizeof(beginRecord));
784     if(count != sizeof(beginRecord)) {
785         exit(OS_Errno);
786     }
787     /*
788      * Send environment to the FCGI application server
789      */
790     paramsStream = CreateWriter(appServerSock, requestId, 8192, FCGI_PARAMS);
791     for( ; *envp != NULL; envp++) {
792         equalPtr = strchr(*envp, '=');
793         if(equalPtr  == NULL) {
794             exit(1000);
795         }
796         valueLen = strlen(equalPtr + 1);
797         FCGIUtil_BuildNameValueHeader(
798                 equalPtr - *envp,
799                 valueLen,
800                 &headerBuff[0],
801                 &headerLen);
802         if(FCGX_PutStr((char *) &headerBuff[0], headerLen, paramsStream) < 0
803                 || FCGX_PutStr(*envp, equalPtr - *envp, paramsStream) < 0
804                 || FCGX_PutStr(equalPtr + 1, valueLen, paramsStream) < 0) {
805             exit(FCGX_GetError(paramsStream));
806         }
807     }
808     FCGX_FClose(paramsStream);
809     FreeStream(&paramsStream);
810     /*
811      * Perform the event loop until AppServerReadHander sees FCGI_END_REQUEST
812      */
813     fromWS.stop = fromWS.next = &fromWS.buff[0];
814     webServerReadHandlerEOF = FALSE;
815     /*
816      * XXX: might want to use numFDs in the os library.
817      */
818     numFDs = max(appServerSock, STDIN_FILENO) + 1;
819     OS_SetFlags(appServerSock, O_NONBLOCK);
820
821     if (bytesToRead <= 0)
822         WriteStdinEof();
823
824     ScheduleIo();
825
826     while(!exitStatusSet) {
827         /*
828          * NULL = wait forever (or at least until there's something
829          *        to do.
830          */
831         OS_DoIo(NULL);
832     }
833     if(exitStatusSet) {
834         FCGIexit(exitStatus);
835     } else {
836         FCGIexit(999);
837     }
838
839     return 0;
840 }