[go: up one dir, main page]

File: cgi-fcgi.c

package info (click to toggle)
libfcgi 2.4.5-0.1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 1,296 kB
  • sloc: ansic: 4,946; java: 872; cpp: 292; makefile: 178; perl: 145; sh: 4
file content (901 lines) | stat: -rw-r--r-- 26,199 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
/*
 * cgifcgi.c --
 *
 *	CGI to FastCGI bridge
 *
 *
 * Copyright (c) 1996 Open Market, Inc.
 *
 * See the file "LICENSE" for information on usage and redistribution
 * of this file, and for a DISCLAIMER OF ALL WARRANTIES.
 *
 */

#include <assert.h>
#include <ctype.h>
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#ifndef _WIN32
#include <sys/wait.h>
#endif
#include <signal.h>

#include "fcgi_config.h"

#ifdef HAVE_NETDB_H
#include <netdb.h>
#endif

#ifdef _WIN32
#include <stdlib.h>
#include <io.h>
#elif defined(__APPLE__)
#include <crt_externs.h>
#define environ (*_NSGetEnviron())
#else
extern char **environ;
#endif

#ifdef HAVE_SYS_PARAM_H
#include <sys/param.h>
#endif

#ifdef HAVE_SYS_TIME_H
#include <sys/time.h>
#endif

#ifdef HAVE_UNISTD_H
#include <unistd.h>
#endif

#include "fcgimisc.h"
#include "fcgiapp.h"
#include "fastcgi.h"
#include "fcgios.h"


static int wsReadPending = 0;
static int fcgiReadPending = 0;
static int fcgiWritePending = 0;

static void ScheduleIo(void);


/*
 * Simple buffer (not ring buffer) type, used by all event handlers.
 */
#define BUFFLEN 8192
typedef struct {
    char *next;
    char *stop;
    char buff[BUFFLEN];
} Buffer;

/*
 *----------------------------------------------------------------------
 *
 * GetPtr --
 *
 *      Returns a count of the number of characters available
 *      in the buffer (at most n) and advances past these
 *      characters.  Stores a pointer to the first of these
 *      characters in *ptr.
 *
 *----------------------------------------------------------------------
 */

static int GetPtr(char **ptr, int n, Buffer *pBuf)
{
    int result;
    *ptr = pBuf->next;
    result = min(n, pBuf->stop - pBuf->next);
    pBuf->next += result;
    return result;
}

/*
 *----------------------------------------------------------------------
 *
 * MakeHeader --
 *
 *      Constructs an FCGI_Header struct.
 *
 *----------------------------------------------------------------------
 */
static FCGI_Header MakeHeader(
        int type,
        int requestId,
        int contentLength,
        int paddingLength)
{
    FCGI_Header header;
    ASSERT(contentLength >= 0 && contentLength <= FCGI_MAX_LENGTH);
    ASSERT(paddingLength >= 0 && paddingLength <= 0xff);
    header.version = FCGI_VERSION_1;
    header.type             = (unsigned char) type;
    header.requestIdB1      = (unsigned char) ((requestId     >> 8) & 0xff);
    header.requestIdB0      = (unsigned char) ((requestId         ) & 0xff);
    header.contentLengthB1  = (unsigned char) ((contentLength >> 8) & 0xff);
    header.contentLengthB0  = (unsigned char) ((contentLength     ) & 0xff);
    header.paddingLength    = (unsigned char) paddingLength;
    header.reserved         =  0;
    return header;
}

/*
 *----------------------------------------------------------------------
 *
 * MakeBeginRequestBody --
 *
 *      Constructs an FCGI_BeginRequestBody record.
 *
 *----------------------------------------------------------------------
 */
static FCGI_BeginRequestBody MakeBeginRequestBody(
        int role,
        int keepConnection)
{
    FCGI_BeginRequestBody body;
    ASSERT((role >> 16) == 0);
    body.roleB1 = (unsigned char) ((role >>  8) & 0xff);
    body.roleB0 = (unsigned char) (role         & 0xff);
    body.flags  = (unsigned char) ((keepConnection) ? FCGI_KEEP_CONN : 0);
    memset(body.reserved, 0, sizeof(body.reserved));
    return body;
}


static int bytesToRead;    /* number of bytes to read from Web Server */
static int appServerSock = -1;  /* Socket connected to FastCGI application,
                                 * used by AppServerReadHandler and
                                 * AppServerWriteHandler. */
static Buffer fromAS;      /* Bytes read from the FCGI application server. */
static FCGI_Header header; /* Header of the current record.  Is global
                            * since read may return a partial header. */
static int headerLen = 0;  /* Number of valid bytes contained in header.
                            * If headerLen < sizeof(header),
                            * AppServerReadHandler is reading a record header;
                            * otherwise it is reading bytes of record content
                            * or padding. */
static int contentLen;     /* If headerLen == sizeof(header), contentLen
                            * is the number of content bytes still to be
                            * read. */
static int paddingLen;     /* If headerLen == sizeof(header), paddingLen
                            * is the number of padding bytes still
                            * to be read. */
static int requestId;      /* RequestId of the current request.
                            * Set by main. */
static FCGI_EndRequestBody erBody;
static int readingEndRequestBody = FALSE;
                           /* If readingEndRequestBody, erBody contains
                            * partial content: contentLen more bytes need
                            * to be read. */
static int exitStatus = 0;
static int exitStatusSet = FALSE;

static int stdinFds[3];


/*
 *----------------------------------------------------------------------
 *
 * FCGIexit --
 *
 *      FCGIexit provides a single point of exit.  It's main use is for
 *      application debug when porting to other operating systems.
 *
 *----------------------------------------------------------------------
 */
static void FCGIexit(int exitCode)
{
    if(appServerSock != -1) {
        OS_Close(appServerSock, TRUE);
	appServerSock = -1;
    }
    OS_LibShutdown();
    exit(exitCode);
}

#undef exit
#define exit FCGIexit


/*
 *----------------------------------------------------------------------
 *
 * AppServerReadHandler --
 *
 *      Reads data from the FCGI application server and (blocking)
 *      writes all of it to the Web server.  Exits the program upon
 *      reading EOF from the FCGI application server.  Called only when
 *      there's data ready to read from the application server.
 *
 *----------------------------------------------------------------------
 */

static void AppServerReadHandler(ClientData dc, int bytesRead)
{
    int count, outFD;
    char *ptr;

    /* Touch unused parameters to avoid warnings */
    dc = NULL;

    assert(fcgiReadPending == TRUE);
    fcgiReadPending = FALSE;
    count = bytesRead;

    if(count <= 0) {
        if(count < 0) {
            exit(OS_Errno);
        }
        if(headerLen > 0 || paddingLen > 0) {
            exit(FCGX_PROTOCOL_ERROR);
        }
	if(appServerSock != -1) {
	    OS_Close(appServerSock, TRUE);
	    appServerSock = -1;
	}
        /*
         * XXX: Shouldn't be here if exitStatusSet.
         */
        exit((exitStatusSet) ? exitStatus : FCGX_PROTOCOL_ERROR);
    }
    fromAS.stop = fromAS.next + count;
    while(fromAS.next != fromAS.stop) {
        /*
         * fromAS is not empty.  What to do with the contents?
         */
        if(headerLen < sizeof(header)) {
            /*
             * First priority is to complete the header.
             */
            count = GetPtr(&ptr, sizeof(header) - headerLen, &fromAS);
            assert(count > 0);
            memcpy(&header + headerLen, ptr, count);
            headerLen += count;
            if(headerLen < sizeof(header)) {
                break;
            }
            if(header.version != FCGI_VERSION_1) {
                exit(FCGX_UNSUPPORTED_VERSION);
	    }
            if((header.requestIdB1 << 8) + header.requestIdB0 != requestId) {
                exit(FCGX_PROTOCOL_ERROR);
	    }
            contentLen = (header.contentLengthB1 << 8)
                         + header.contentLengthB0;
            paddingLen =  header.paddingLength;
	} else {
            /*
             * Header is complete (possibly from previous call).  What now?
             */
            switch(header.type) {
	        case FCGI_STDOUT:
                case FCGI_STDERR:
                    /*
                     * Write the buffered content to stdout or stderr.
                     * Blocking writes are OK here; can't prevent a slow
                     * client from tying up the app server without buffering
                     * output in temporary files.
                     */
                    count = GetPtr(&ptr, contentLen, &fromAS);
                    contentLen -= count;
                    if(count > 0) {
                        outFD = (header.type == FCGI_STDOUT) ?
                                    STDOUT_FILENO : STDERR_FILENO;
                        if(OS_Write(outFD, ptr, count) < 0) {
                            exit(OS_Errno);
                        }
	            }
                    break;
                case FCGI_END_REQUEST:
                    if(!readingEndRequestBody) {
                        if(contentLen != sizeof(erBody)) {
                            exit(FCGX_PROTOCOL_ERROR);
		        }
                        readingEndRequestBody = TRUE;
		    }
                    count = GetPtr(&ptr, contentLen, &fromAS);
                    if(count > 0) {
                        memcpy(&erBody + sizeof(erBody) - contentLen,
                                ptr, count);
                        contentLen -= count;
		    }
                    if(contentLen == 0) {
                        if(erBody.protocolStatus != FCGI_REQUEST_COMPLETE) {
                            /*
                             * XXX: What to do with FCGI_OVERLOADED?
                             */
                            exit(FCGX_PROTOCOL_ERROR);
			}
                        exitStatus = (erBody.appStatusB3 << 24)
                                   + (erBody.appStatusB2 << 16)
                                   + (erBody.appStatusB1 <<  8)
                                   + (erBody.appStatusB0      );
                        exitStatusSet = TRUE;
                        readingEndRequestBody = FALSE;
	            }
                    break;
                case FCGI_GET_VALUES_RESULT:
                    /* coming soon */
                case FCGI_UNKNOWN_TYPE:
                    /* coming soon */
                default:
                    exit(FCGX_PROTOCOL_ERROR);
	    }
            if(contentLen == 0) {
                if(paddingLen > 0) {
                    paddingLen -= GetPtr(&ptr, paddingLen, &fromAS);
		}
                /*
                 * If we've processed all the data and skipped all the
                 * padding, discard the header and look for the next one.
                 */
                if(paddingLen == 0) {
                    headerLen = 0;
	        }
	    }
        } /* headerLen >= sizeof(header) */
    } /*while*/
    ScheduleIo();
}

static Buffer fromWS;   /* Buffer for data read from Web server
                         * and written to FastCGI application. Used
                         * by WebServerReadHandler and
                         * AppServerWriteHandler. */
static int webServerReadHandlerEOF;
                        /* TRUE iff WebServerReadHandler has read EOF from
                         * the Web server. Used in main to prevent
                         * rescheduling WebServerReadHandler. */

static void WriteStdinEof(void)
{
    static int stdin_eof_sent = 0;

    if (stdin_eof_sent)
    	return;

    *((FCGI_Header *)fromWS.stop) = MakeHeader(FCGI_STDIN, requestId, 0, 0);
    fromWS.stop += sizeof(FCGI_Header);
    stdin_eof_sent = 1;
}

/*
 *----------------------------------------------------------------------
 *
 * WebServerReadHandler --
 *
 *      Non-blocking reads data from the Web server into the fromWS
 *      buffer.  Called only when fromWS is empty, no EOF has been
 *      received from the Web server, and there's data available to read.
 *
 *----------------------------------------------------------------------
 */

static void WebServerReadHandler(ClientData dc, int bytesRead)
{
    /* Touch unused parameters to avoid warnings */
    dc = NULL;

    assert(fromWS.next == fromWS.stop);
    assert(fromWS.next == &fromWS.buff[0]);
    assert(wsReadPending == TRUE);
    wsReadPending = FALSE;

    if(bytesRead < 0) {
        exit(OS_Errno);
    }
    FCGI_Header *header = (FCGI_Header *) &fromWS.buff[0];
    *header = MakeHeader(FCGI_STDIN, requestId, bytesRead, 0);
    bytesToRead -= bytesRead;
    fromWS.stop = &fromWS.buff[sizeof(FCGI_Header) + bytesRead];
    webServerReadHandlerEOF = (bytesRead == 0);

    if (bytesToRead <= 0)
	WriteStdinEof();

    ScheduleIo();
}

/*
 *----------------------------------------------------------------------
 *
 * AppServerWriteHandler --
 *
 *      Non-blocking writes data from the fromWS buffer to the FCGI
 *      application server.  Called only when fromWS is non-empty
 *      and the socket is ready to accept some data.
 *
 *----------------------------------------------------------------------
 */

static void AppServerWriteHandler(ClientData dc, int bytesWritten)
{
    int length = fromWS.stop - fromWS.next;

    /* Touch unused parameters to avoid warnings */
    dc = NULL;

    assert(length > 0);
    assert(fcgiWritePending == TRUE);

    fcgiWritePending = FALSE;
    if(bytesWritten < 0) {
        exit(OS_Errno);
    }
    if((int)bytesWritten < length) {
        fromWS.next += bytesWritten;
    } else {
        fromWS.stop = fromWS.next = &fromWS.buff[0];
    }

    ScheduleIo();
}


/*
 * ScheduleIo --
 *
 *      This functions is responsible for scheduling all I/O to move
 *      data between a web server and a FastCGI application.
 *
 * Results:
 *      None.
 *
 * Side effects:
 *      This routine will signal the ioEvent upon completion.
 *
 */
static void ScheduleIo(void)
{
    int length;

    /*
     * Move data between standard in and the FastCGI connection.
     */
    if(!fcgiWritePending && appServerSock != -1 &&
       ((length = fromWS.stop - fromWS.next) != 0)) {
	if(OS_AsyncWrite(appServerSock, 0, fromWS.next, length,
			 AppServerWriteHandler,
			 (ClientData)(intptr_t)appServerSock) == -1) {
	    FCGIexit(OS_Errno);
	} else {
	    fcgiWritePending = TRUE;
	}
    }

    /*
     * Schedule a read from the FastCGI application if there's not
     * one pending and there's room in the buffer.
     */
    if(!fcgiReadPending && appServerSock != -1) {
	fromAS.next = &fromAS.buff[0];

	if(OS_AsyncRead(appServerSock, 0, fromAS.next, BUFFLEN,
			AppServerReadHandler,
			(ClientData)(intptr_t)appServerSock) == -1) {
	    FCGIexit(OS_Errno);
	} else {
	    fcgiReadPending = TRUE;
	}
    }

    /*
     * Schedule a read from standard in if necessary.
     */
    if((bytesToRead > 0) && !webServerReadHandlerEOF && !wsReadPending &&
       !fcgiWritePending &&
       fromWS.next == &fromWS.buff[0]) {
	if(OS_AsyncReadStdin(fromWS.next + sizeof(FCGI_Header),
			     BUFFLEN - sizeof(FCGI_Header),
			     WebServerReadHandler, STDIN_FILENO)== -1) {
	    FCGIexit(OS_Errno);
	} else {
	    wsReadPending = TRUE;
	}
    }
}


/*
 *----------------------------------------------------------------------
 *
 * FCGI_Start --
 *
 *      Starts nServers copies of FCGI application appPath, all
 *      listening to a Unix Domain socket at bindPath.
 *
 *----------------------------------------------------------------------
 */

static void FCGI_Start(char *bindPath, char *appPath, int nServers)
{
    int listenFd, i;

    /* @@@ Should be able to pick up the backlog as an arg */
    if((listenFd = OS_CreateLocalIpcFd(bindPath, 5)) == -1) {
        exit(OS_Errno);
    }

    if(access(appPath, X_OK) == -1) {
	fprintf(stderr, "%s is not executable\n", appPath);
	exit(1);
    }

    /*
     * Create the server processes
     */
    for(i = 0; i < nServers; i++) {
        if(OS_SpawnChild(appPath, listenFd) == -1) {
            exit(OS_Errno);
	}
    }
    OS_Close(listenFd, TRUE);
}

/*
 *----------------------------------------------------------------------
 *
 * FCGIUtil_BuildNameValueHeader --
 *
 *      Builds a name-value pair header from the name length
 *      and the value length.  Stores the header into *headerBuffPtr,
 *      and stores the length of the header into *headerLenPtr.
 *
 * Side effects:
 *      Stores header's length (at most 8) into *headerLenPtr,
 *      and stores the header itself into
 *      headerBuffPtr[0 .. *headerLenPtr - 1].
 *
 *----------------------------------------------------------------------
 */
static void FCGIUtil_BuildNameValueHeader(
        int nameLen,
        int valueLen,
        unsigned char *headerBuffPtr,
        int *headerLenPtr) {
    unsigned char *startHeaderBuffPtr = headerBuffPtr;

    ASSERT(nameLen >= 0);
    if (nameLen < 0x80) {
        *headerBuffPtr++ = (unsigned char) nameLen;
    } else {
        *headerBuffPtr++ = (unsigned char) ((nameLen >> 24) | 0x80);
        *headerBuffPtr++ = (unsigned char) (nameLen >> 16);
        *headerBuffPtr++ = (unsigned char) (nameLen >> 8);
        *headerBuffPtr++ = (unsigned char) nameLen;
    }
    ASSERT(valueLen >= 0);
    if (valueLen < 0x80) {
        *headerBuffPtr++ = (unsigned char) valueLen;
    } else {
        *headerBuffPtr++ = (unsigned char) ((valueLen >> 24) | 0x80);
        *headerBuffPtr++ = (unsigned char) (valueLen >> 16);
        *headerBuffPtr++ = (unsigned char) (valueLen >> 8);
        *headerBuffPtr++ = (unsigned char) valueLen;
    }
    *headerLenPtr = headerBuffPtr - startHeaderBuffPtr;
}


#define MAXARGS	16
static int ParseArgs(int argc, char *argv[],
        int *doBindPtr, int *doStartPtr,
        char *connectPathPtr, char *appPathPtr, int *nServersPtr, int *doDaemonPtr) {
    int	    i,
	    x,
	    err = 0,
	    ac;
    char    *tp1,
	    *tp2,
	    *av[MAXARGS];
    FILE    *fp;
    char    line[BUFSIZ];

    *doBindPtr = TRUE;
    *doStartPtr = TRUE;
    *connectPathPtr = '\0';
    *appPathPtr = '\0';
    *nServersPtr = 0;
    *doDaemonPtr = TRUE;

    for(i = 0; i < MAXARGS; i++)
        av[i] = NULL;
    for(i = 1; i < argc; i++) {
        if(argv[i][0] == '-') {
            if(!strcmp(argv[i], "-f")) {
		if(++i == argc) {
		    fprintf(stderr,
                            "Missing command file name after -f\n");
		    return 1;
		}
		if((fp = fopen(argv[i], "r")) == NULL) {
		    fprintf(stderr, "Cannot open command file %s\n", argv[i]);
		    return 1;
		}
		ac = 1;
		while(fgets(line, BUFSIZ, fp)) {
		    if(line[0] == '#') {
			continue;
		    }
		    if((tp1 = (char *) strrchr(line,'\n')) != NULL) {
			*tp1-- = 0;
			while(*tp1 == ' ' || *tp1 =='\t') {
			    *tp1-- = 0;
		        }
		    } else {
			fprintf(stderr, "Line to long\n");
			return 1;
		    }
		    tp1 = line;
		    while(tp1) {
			if((tp2 = strchr(tp1, ' ')) != NULL) {
			    *tp2++ =  0;
		        }
    			if(ac >= MAXARGS) {
			    fprintf(stderr,
                                    "To many arguments, "
                                    "%d is max from a file\n", MAXARGS);
				exit(-1);
			}
			if((av[ac] = (char *)malloc(strlen(tp1)+1)) == NULL) {
			    fprintf(stderr, "Cannot allocate %d bytes\n",
				        (int)strlen(tp1)+1);
			    exit(-1);
			}
			strcpy(av[ac++], tp1);
			tp1 = tp2;
		    }
		}
		fclose(fp);
		err = ParseArgs(ac, av, doBindPtr, doStartPtr,
                        connectPathPtr, appPathPtr, nServersPtr, doDaemonPtr);
		for(x = 1; x < ac; x++) {
		    ASSERT(av[x] != NULL);
		    free(av[x]);
	        }
		return err;
#ifdef _WIN32
	    } else if (!strcmp(argv[i], "-jitcgi")) {
	        DebugBreak();
	    } else if (!strcmp(argv[i], "-dbgfcgi")) {
	        putenv("DEBUG_FCGI=TRUE");
#endif
	    } else if(!strcmp(argv[i], "-start")) {
		*doBindPtr = FALSE;
	    } else if(!strcmp(argv[i], "-bind")) {
		*doStartPtr = FALSE;
	    } else if(!strcmp(argv[i], "-connect")) {
                if(++i == argc) {
	            fprintf(stderr,
                            "Missing connection name after -connect\n");
                    err++;
                } 
                else if (strlen(argv[i]) < MAXPATHLEN) {
                    strcpy(connectPathPtr, argv[i]);
                }
            	else {
                	fprintf(stderr, "bind path too long (>=%d): %s\n", 
                			MAXPATHLEN, argv[i]);
                	err++;
            	}
	    } else if(!strcmp(argv[i], "-supervise")) {
		*doDaemonPtr = FALSE;
	    } else {
		fprintf(stderr, "Unknown option %s\n", argv[i]);
		err++;
	    }
	} 
        else if (*appPathPtr == '\0') {
            if (strlen(argv[i]) < MAXPATHLEN) {
            strcpy(appPathPtr, argv[i]);
        	}
        	else {
            	fprintf(stderr, "bind path too long (>=%d): %s\n", 
            			MAXPATHLEN, argv[i]);
            	err++;
        	}
        } 
        else if(isdigit((int)argv[i][0]) && *nServersPtr == 0) {
            *nServersPtr = atoi(argv[i]);
            if(*nServersPtr <= 0) {
                fprintf(stderr, "Number of servers must be greater than 0\n");
                err++;
            }
        } else {
            fprintf(stderr, "Unknown argument %s\n", argv[i]);
            err++;
        }
    }
    if(*doStartPtr && *appPathPtr == 0) {
        fprintf(stderr, "Missing application pathname\n");
        err++;
    }
    if(*connectPathPtr == 0) {
	fprintf(stderr, "Missing -connect <connName>\n");
	err++;
    } else if(strchr(connectPathPtr, ':')) {
/*
 * XXX: Test to see if we can use IP connect locally...
        This hack lets me test the ability to create a local process listening
	to a TCP/IP port for connections and subsequently connect to the app
	like we do for Unix domain and named pipes.

        if(*doStartPtr && *doBindPtr) {
	    fprintf(stderr,
                    "<connName> of form hostName:portNumber "
                    "requires -start or -bind\n");
	    err++;
        }
 */
    }
    if(*nServersPtr == 0) {
        *nServersPtr = 1;
    }
    return err;
}

void handle_shutdown(int s)
{
    /* Kill our children processes */
    signal(s, SIG_IGN);
#ifndef _WIN32
    kill(0, s);
#endif

    exit(0);
}

int main(int argc, char **argv)
{
    char **envp = environ;
    int count;
    FCGX_Stream *paramsStream;
    unsigned char headerBuff[8];
    int headerLen, valueLen;
    char *equalPtr;
    FCGI_BeginRequestRecord beginRecord;
    int	doBind, doStart, nServers, doDaemon;
    char appPath[MAXPATHLEN], bindPath[MAXPATHLEN];
    int pid;

    if(ParseArgs(argc, argv, &doBind, &doStart,
		   (char *) &bindPath, (char *) &appPath, &nServers, &doDaemon)) {
	fprintf(stderr,
"Usage:\n"
"    cgi-fcgi -f <cmdPath> , or\n"
"    cgi-fcgi -connect <connName> <appPath> [<nServers>] , or\n"
"    cgi-fcgi -start -connect [-supervise] <connName> <appPath> [<nServers>] , or\n"
"    cgi-fcgi -bind -connect <connName> ,\n"
"where <connName> is either the pathname of a UNIX domain socket\n"
"or (if -bind is given) a hostName:portNumber specification\n"
"or (if -start is given) a :portNumber specification (uses local host).\n"
"-supervise is for running with runit or daemontools.\n");
	exit(1);
    }

    if(OS_LibInit(stdinFds)) {
        fprintf(stderr, "Error initializing OS library: %lu\n", (long unsigned int)OS_Errno);
	exit(0);
    }

    equalPtr = getenv("CONTENT_LENGTH");
    if(equalPtr != NULL) {
        bytesToRead = atoi(equalPtr);
    } else {
        bytesToRead = 0;
    }

#ifndef _WIN32
    /* Become a process group leader */
    setsid();

    /* Register our signal handler */
    signal(SIGHUP, handle_shutdown);
#endif
    signal(SIGINT, handle_shutdown);
    signal(SIGTERM, handle_shutdown);

    if(doBind) {
        appServerSock = OS_FcgiConnect(bindPath);
    }
    if(doStart && (!doBind || appServerSock < 0)) {
        FCGI_Start(bindPath, appPath, nServers);
        if(!doBind) {
#ifndef _WIN32
            if(!doDaemon) {
                for(pid=nServers; pid != 0; pid--) {
                    wait(0);
                }
            }
#endif
            signal(SIGTERM, SIG_IGN);
#ifndef _WIN32
            kill(0, SIGTERM);
#endif
            exit(0);
        } else {
            appServerSock = OS_FcgiConnect(bindPath);
	}
    }
    if(appServerSock < 0) {
        fprintf(stderr, "Could not connect to %s\n", bindPath);
        exit(OS_Errno);
    }
    /*
     * Set an arbitrary non-null FCGI RequestId
     */
    requestId = 1;
    /*
     * XXX: Send FCGI_GET_VALUES
     */

    /*
     * XXX: Receive FCGI_GET_VALUES_RESULT
     */

    /*
     * Send FCGI_BEGIN_REQUEST (XXX: hack, separate write)
     */
    beginRecord.header = MakeHeader(FCGI_BEGIN_REQUEST, requestId,
            sizeof(beginRecord.body), 0);
    beginRecord.body = MakeBeginRequestBody(FCGI_RESPONDER, FALSE);
    count = OS_Write(appServerSock, (char *)&beginRecord, sizeof(beginRecord));
    if(count != sizeof(beginRecord)) {
        exit(OS_Errno);
    }
    /*
     * Send environment to the FCGI application server
     */
    paramsStream = FCGX_CreateWriter(appServerSock, requestId, 8192, FCGI_PARAMS);
    for( ; *envp != NULL; envp++) {
        equalPtr = strchr(*envp, '=');
        if(equalPtr  == NULL) {
            exit(1000);
        }
        valueLen = strlen(equalPtr + 1);
        FCGIUtil_BuildNameValueHeader(
                equalPtr - *envp,
                valueLen,
                &headerBuff[0],
                &headerLen);
        if(FCGX_PutStr((char *) &headerBuff[0], headerLen, paramsStream) < 0
                || FCGX_PutStr(*envp, equalPtr - *envp, paramsStream) < 0
                || FCGX_PutStr(equalPtr + 1, valueLen, paramsStream) < 0) {
            exit(FCGX_GetError(paramsStream));
        }
    }
    FCGX_FClose(paramsStream);
    FCGX_FreeStream(&paramsStream);
    /*
     * Perform the event loop until AppServerReadHander sees FCGI_END_REQUEST
     */
    fromWS.stop = fromWS.next = &fromWS.buff[0];
    webServerReadHandlerEOF = FALSE;
    OS_SetFlags(appServerSock, O_NONBLOCK);

    if (bytesToRead <= 0)
	WriteStdinEof();

    ScheduleIo();

    while(!exitStatusSet) {
        /*
	 * NULL = wait forever (or at least until there's something
	 *        to do.
	 */
        OS_DoIo(NULL);
    }
    if(exitStatusSet) {
        FCGIexit(exitStatus);
    } else {
        FCGIexit(999);
    }

    return 0;
}