4 * CGI to FastCGI bridge
7 * Copyright (c) 1996 Open Market, Inc.
9 * See the file "LICENSE.TERMS" for information on usage and redistribution
10 * of this file, and for a DISCLAIMER OF ALL WARRANTIES.
14 static const char rcsid[] = "$Id: cgi-fcgi.c,v 1.12 2001/06/22 02:19:55 robs Exp $";
26 #include "fcgi_config.h"
35 extern char **environ;
38 #ifdef HAVE_SYS_PARAM_H
39 #include <sys/param.h>
42 #ifdef HAVE_SYS_TIME_H
46 #if defined HAVE_UNISTD_H
52 #include "fcgiappmisc.h"
57 static int wsReadPending = 0;
58 static int fcgiReadPending = 0;
59 static int fcgiWritePending = 0;
61 static void ScheduleIo(void);
65 * Simple buffer (not ring buffer) type, used by all event handlers.
75 *----------------------------------------------------------------------
79 * Returns a count of the number of characters available
80 * in the buffer (at most n) and advances past these
81 * characters. Stores a pointer to the first of these
84 *----------------------------------------------------------------------
87 static int GetPtr(char **ptr, int n, Buffer *pBuf)
91 result = min(n, pBuf->stop - pBuf->next);
97 *----------------------------------------------------------------------
101 * Constructs an FCGI_Header struct.
103 *----------------------------------------------------------------------
105 static FCGI_Header MakeHeader(
112 ASSERT(contentLength >= 0 && contentLength <= FCGI_MAX_LENGTH);
113 ASSERT(paddingLength >= 0 && paddingLength <= 0xff);
114 header.version = FCGI_VERSION_1;
115 header.type = (unsigned char) type;
116 header.requestIdB1 = (unsigned char) ((requestId >> 8) & 0xff);
117 header.requestIdB0 = (unsigned char) ((requestId ) & 0xff);
118 header.contentLengthB1 = (unsigned char) ((contentLength >> 8) & 0xff);
119 header.contentLengthB0 = (unsigned char) ((contentLength ) & 0xff);
120 header.paddingLength = (unsigned char) paddingLength;
126 *----------------------------------------------------------------------
128 * MakeBeginRequestBody --
130 * Constructs an FCGI_BeginRequestBody record.
132 *----------------------------------------------------------------------
134 static FCGI_BeginRequestBody MakeBeginRequestBody(
138 FCGI_BeginRequestBody body;
139 ASSERT((role >> 16) == 0);
140 body.roleB1 = (unsigned char) ((role >> 8) & 0xff);
141 body.roleB0 = (unsigned char) (role & 0xff);
142 body.flags = (unsigned char) ((keepConnection) ? FCGI_KEEP_CONN : 0);
143 memset(body.reserved, 0, sizeof(body.reserved));
148 static int bytesToRead; /* number of bytes to read from Web Server */
149 static int appServerSock = -1; /* Socket connected to FastCGI application,
150 * used by AppServerReadHandler and
151 * AppServerWriteHandler. */
152 static Buffer fromAS; /* Bytes read from the FCGI application server. */
153 static FCGI_Header header; /* Header of the current record. Is global
154 * since read may return a partial header. */
155 static int headerLen = 0; /* Number of valid bytes contained in header.
156 * If headerLen < sizeof(header),
157 * AppServerReadHandler is reading a record header;
158 * otherwise it is reading bytes of record content
160 static int contentLen; /* If headerLen == sizeof(header), contentLen
161 * is the number of content bytes still to be
163 static int paddingLen; /* If headerLen == sizeof(header), paddingLen
164 * is the number of padding bytes still
166 static int requestId; /* RequestId of the current request.
168 static FCGI_EndRequestBody erBody;
169 static int readingEndRequestBody = FALSE;
170 /* If readingEndRequestBody, erBody contains
171 * partial content: contentLen more bytes need
173 static int exitStatus = 0;
174 static int exitStatusSet = FALSE;
176 static int stdinFds[3];
180 *----------------------------------------------------------------------
184 * FCGIexit provides a single point of exit. It's main use is for
185 * application debug when porting to other operating systems.
187 *----------------------------------------------------------------------
189 static void FCGIexit(int exitCode)
191 if(appServerSock != -1) {
192 OS_Close(appServerSock);
200 #define exit FCGIexit
204 *----------------------------------------------------------------------
206 * AppServerReadHandler --
208 * Reads data from the FCGI application server and (blocking)
209 * writes all of it to the Web server. Exits the program upon
210 * reading EOF from the FCGI application server. Called only when
211 * there's data ready to read from the application server.
213 *----------------------------------------------------------------------
216 static void AppServerReadHandler(ClientData dc, int bytesRead)
221 /* Touch unused parameters to avoid warnings */
224 assert(fcgiReadPending == TRUE);
225 fcgiReadPending = FALSE;
232 if(headerLen > 0 || paddingLen > 0) {
233 exit(FCGX_PROTOCOL_ERROR);
235 if(appServerSock != -1) {
236 OS_Close(appServerSock);
240 * XXX: Shouldn't be here if exitStatusSet.
242 exit((exitStatusSet) ? exitStatus : FCGX_PROTOCOL_ERROR);
244 fromAS.stop = fromAS.next + count;
245 while(fromAS.next != fromAS.stop) {
247 * fromAS is not empty. What to do with the contents?
249 if(headerLen < sizeof(header)) {
251 * First priority is to complete the header.
253 count = GetPtr(&ptr, sizeof(header) - headerLen, &fromAS);
255 memcpy(&header + headerLen, ptr, count);
257 if(headerLen < sizeof(header)) {
260 if(header.version != FCGI_VERSION_1) {
261 exit(FCGX_UNSUPPORTED_VERSION);
263 if((header.requestIdB1 << 8) + header.requestIdB0 != requestId) {
264 exit(FCGX_PROTOCOL_ERROR);
266 contentLen = (header.contentLengthB1 << 8)
267 + header.contentLengthB0;
268 paddingLen = header.paddingLength;
271 * Header is complete (possibly from previous call). What now?
273 switch(header.type) {
277 * Write the buffered content to stdout or stderr.
278 * Blocking writes are OK here; can't prevent a slow
279 * client from tying up the app server without buffering
280 * output in temporary files.
282 count = GetPtr(&ptr, contentLen, &fromAS);
285 outFD = (header.type == FCGI_STDOUT) ?
286 STDOUT_FILENO : STDERR_FILENO;
287 if(OS_Write(outFD, ptr, count) < 0) {
292 case FCGI_END_REQUEST:
293 if(!readingEndRequestBody) {
294 if(contentLen != sizeof(erBody)) {
295 exit(FCGX_PROTOCOL_ERROR);
297 readingEndRequestBody = TRUE;
299 count = GetPtr(&ptr, contentLen, &fromAS);
301 memcpy(&erBody + sizeof(erBody) - contentLen,
305 if(contentLen == 0) {
306 if(erBody.protocolStatus != FCGI_REQUEST_COMPLETE) {
308 * XXX: What to do with FCGI_OVERLOADED?
310 exit(FCGX_PROTOCOL_ERROR);
312 exitStatus = (erBody.appStatusB3 << 24)
313 + (erBody.appStatusB2 << 16)
314 + (erBody.appStatusB1 << 8)
315 + (erBody.appStatusB0 );
316 exitStatusSet = TRUE;
317 readingEndRequestBody = FALSE;
320 case FCGI_GET_VALUES_RESULT:
322 case FCGI_UNKNOWN_TYPE:
325 exit(FCGX_PROTOCOL_ERROR);
327 if(contentLen == 0) {
329 paddingLen -= GetPtr(&ptr, paddingLen, &fromAS);
332 * If we've processed all the data and skipped all the
333 * padding, discard the header and look for the next one.
335 if(paddingLen == 0) {
339 } /* headerLen >= sizeof(header) */
344 static Buffer fromWS; /* Buffer for data read from Web server
345 * and written to FastCGI application. Used
346 * by WebServerReadHandler and
347 * AppServerWriteHandler. */
348 static int webServerReadHandlerEOF;
349 /* TRUE iff WebServerReadHandler has read EOF from
350 * the Web server. Used in main to prevent
351 * rescheduling WebServerReadHandler. */
353 static void WriteStdinEof(void)
355 static int stdin_eof_sent = 0;
360 *((FCGI_Header *)fromWS.stop) = MakeHeader(FCGI_STDIN, requestId, 0, 0);
361 fromWS.stop += sizeof(FCGI_Header);
366 *----------------------------------------------------------------------
368 * WebServerReadHandler --
370 * Non-blocking reads data from the Web server into the fromWS
371 * buffer. Called only when fromWS is empty, no EOF has been
372 * received from the Web server, and there's data available to read.
374 *----------------------------------------------------------------------
377 static void WebServerReadHandler(ClientData dc, int bytesRead)
379 /* Touch unused parameters to avoid warnings */
382 assert(fromWS.next == fromWS.stop);
383 assert(fromWS.next == &fromWS.buff[0]);
384 assert(wsReadPending == TRUE);
385 wsReadPending = FALSE;
390 *((FCGI_Header *) &fromWS.buff[0])
391 = MakeHeader(FCGI_STDIN, requestId, bytesRead, 0);
392 bytesToRead -= bytesRead;
393 fromWS.stop = &fromWS.buff[sizeof(FCGI_Header) + bytesRead];
394 webServerReadHandlerEOF = (bytesRead == 0);
396 if (bytesToRead <= 0)
403 *----------------------------------------------------------------------
405 * AppServerWriteHandler --
407 * Non-blocking writes data from the fromWS buffer to the FCGI
408 * application server. Called only when fromWS is non-empty
409 * and the socket is ready to accept some data.
411 *----------------------------------------------------------------------
414 static void AppServerWriteHandler(ClientData dc, int bytesWritten)
416 int length = fromWS.stop - fromWS.next;
418 /* Touch unused parameters to avoid warnings */
422 assert(fcgiWritePending == TRUE);
424 fcgiWritePending = FALSE;
425 if(bytesWritten < 0) {
428 if((int)bytesWritten < length) {
429 fromWS.next += bytesWritten;
431 fromWS.stop = fromWS.next = &fromWS.buff[0];
441 * This functions is responsible for scheduling all I/O to move
442 * data between a web server and a FastCGI application.
448 * This routine will signal the ioEvent upon completion.
451 static void ScheduleIo(void)
456 * Move data between standard in and the FastCGI connection.
458 if(!fcgiWritePending && appServerSock != -1 &&
459 ((length = fromWS.stop - fromWS.next) != 0)) {
460 if(OS_AsyncWrite(appServerSock, 0, fromWS.next, length,
461 AppServerWriteHandler,
462 (ClientData)appServerSock) == -1) {
465 fcgiWritePending = TRUE;
470 * Schedule a read from the FastCGI application if there's not
471 * one pending and there's room in the buffer.
473 if(!fcgiReadPending && appServerSock != -1) {
474 fromAS.next = &fromAS.buff[0];
476 if(OS_AsyncRead(appServerSock, 0, fromAS.next, BUFFLEN,
477 AppServerReadHandler,
478 (ClientData)appServerSock) == -1) {
481 fcgiReadPending = TRUE;
486 * Schedule a read from standard in if necessary.
488 if((bytesToRead > 0) && !webServerReadHandlerEOF && !wsReadPending &&
490 fromWS.next == &fromWS.buff[0]) {
491 if(OS_AsyncReadStdin(fromWS.next + sizeof(FCGI_Header),
492 BUFFLEN - sizeof(FCGI_Header),
493 WebServerReadHandler, STDIN_FILENO)== -1) {
496 wsReadPending = TRUE;
503 *----------------------------------------------------------------------
507 * Starts nServers copies of FCGI application appPath, all
508 * listening to a Unix Domain socket at bindPath.
510 *----------------------------------------------------------------------
513 static void FCGI_Start(char *bindPath, char *appPath, int nServers)
517 /* @@@ Should be able to pick up the backlog as an arg */
518 if((listenFd = OS_CreateLocalIpcFd(bindPath, 5)) == -1) {
522 if(access(appPath, X_OK) == -1) {
523 fprintf(stderr, "%s is not executable\n", appPath);
528 * Create the server processes
530 for(i = 0; i < nServers; i++) {
531 if(OS_SpawnChild(appPath, listenFd) == -1) {
539 *----------------------------------------------------------------------
541 * FCGIUtil_BuildNameValueHeader --
543 * Builds a name-value pair header from the name length
544 * and the value length. Stores the header into *headerBuffPtr,
545 * and stores the length of the header into *headerLenPtr.
548 * Stores header's length (at most 8) into *headerLenPtr,
549 * and stores the header itself into
550 * headerBuffPtr[0 .. *headerLenPtr - 1].
552 *----------------------------------------------------------------------
554 static void FCGIUtil_BuildNameValueHeader(
557 unsigned char *headerBuffPtr,
559 unsigned char *startHeaderBuffPtr = headerBuffPtr;
561 ASSERT(nameLen >= 0);
562 if (nameLen < 0x80) {
563 *headerBuffPtr++ = (unsigned char) nameLen;
565 *headerBuffPtr++ = (unsigned char) ((nameLen >> 24) | 0x80);
566 *headerBuffPtr++ = (unsigned char) (nameLen >> 16);
567 *headerBuffPtr++ = (unsigned char) (nameLen >> 8);
568 *headerBuffPtr++ = (unsigned char) nameLen;
570 ASSERT(valueLen >= 0);
571 if (valueLen < 0x80) {
572 *headerBuffPtr++ = (unsigned char) valueLen;
574 *headerBuffPtr++ = (unsigned char) ((valueLen >> 24) | 0x80);
575 *headerBuffPtr++ = (unsigned char) (valueLen >> 16);
576 *headerBuffPtr++ = (unsigned char) (valueLen >> 8);
577 *headerBuffPtr++ = (unsigned char) valueLen;
579 *headerLenPtr = headerBuffPtr - startHeaderBuffPtr;
584 static int ParseArgs(int argc, char *argv[],
585 int *doBindPtr, int *doStartPtr,
586 char *connectPathPtr, char *appPathPtr, int *nServersPtr) {
599 *connectPathPtr = '\0';
603 for(i = 0; i < MAXARGS; i++)
605 for(i = 1; i < argc; i++) {
606 if(argv[i][0] == '-') {
607 if(!strcmp(argv[i], "-f")) {
610 "Missing command file name after -f\n");
613 if((fp = fopen(argv[i], "r")) == NULL) {
614 fprintf(stderr, "Cannot open command file %s\n", argv[i]);
618 while(fgets(line, BUFSIZ, fp)) {
622 if((tp1 = (char *) strrchr(line,'\n')) != NULL) {
624 while(*tp1 == ' ' || *tp1 =='\t') {
628 fprintf(stderr, "Line to long\n");
633 if((tp2 = strchr(tp1, ' ')) != NULL) {
638 "To many arguments, "
639 "%d is max from a file\n", MAXARGS);
642 if((av[ac] = (char *)malloc(strlen(tp1)+1)) == NULL) {
643 fprintf(stderr, "Cannot allocate %d bytes\n",
647 strcpy(av[ac++], tp1);
651 err = ParseArgs(ac, av, doBindPtr, doStartPtr,
652 connectPathPtr, appPathPtr, nServersPtr);
653 for(x = 1; x < ac; x++) {
654 ASSERT(av[x] != NULL);
659 } else if (!strcmp(argv[i], "-jitcgi")) {
661 } else if (!strcmp(argv[i], "-dbgfcgi")) {
662 putenv("DEBUG_FCGI=TRUE");
664 } else if(!strcmp(argv[i], "-start")) {
666 } else if(!strcmp(argv[i], "-bind")) {
668 } else if(!strcmp(argv[i], "-connect")) {
671 "Missing connection name after -connect\n");
674 strcpy(connectPathPtr, argv[i]);
677 fprintf(stderr, "Unknown option %s\n", argv[i]);
680 } else if(*appPathPtr == '\0') {
681 strcpy(appPathPtr, argv[i]);
682 } else if(isdigit((int)argv[i][0]) && *nServersPtr == 0) {
683 *nServersPtr = atoi(argv[i]);
684 if(*nServersPtr <= 0) {
685 fprintf(stderr, "Number of servers must be greater than 0\n");
689 fprintf(stderr, "Unknown argument %s\n", argv[i]);
693 if(*doStartPtr && *appPathPtr == 0) {
694 fprintf(stderr, "Missing application pathname\n");
697 if(*connectPathPtr == 0) {
698 fprintf(stderr, "Missing -connect <connName>\n");
700 } else if(strchr(connectPathPtr, ':')) {
702 * XXX: Test to see if we can use IP connect locally...
703 This hack lets me test the ability to create a local process listening
704 to a TCP/IP port for connections and subsequently connect to the app
705 like we do for Unix domain and named pipes.
707 if(*doStartPtr && *doBindPtr) {
709 "<connName> of form hostName:portNumber "
710 "requires -start or -bind\n");
715 if(*nServersPtr == 0) {
721 int main(int argc, char **argv)
723 char **envp = environ;
725 FCGX_Stream *paramsStream;
727 unsigned char headerBuff[8];
728 int headerLen, valueLen;
730 FCGI_BeginRequestRecord beginRecord;
731 int doBind, doStart, nServers;
732 char appPath[MAXPATHLEN], bindPath[MAXPATHLEN];
734 if(ParseArgs(argc, argv, &doBind, &doStart,
735 (char *) &bindPath, (char *) &appPath, &nServers)) {
738 " cgi-fcgi -f <cmdPath> , or\n"
739 " cgi-fcgi -connect <connName> <appPath> [<nServers>] , or\n"
740 " cgi-fcgi -start -connect <connName> <appPath> [<nServers>] , or\n"
741 " cgi-fcgi -bind -connect <connName> ,\n"
742 "where <connName> is either the pathname of a UNIX domain socket\n"
743 "or (if -bind is given) a hostName:portNumber specification\n"
744 "or (if -start is given) a :portNumber specification (uses local host).\n");
748 if(OS_LibInit(stdinFds)) {
749 fprintf(stderr, "Error initializing OS library: %d\n", OS_Errno);
753 equalPtr = getenv("CONTENT_LENGTH");
754 if(equalPtr != NULL) {
755 bytesToRead = atoi(equalPtr);
761 appServerSock = OS_FcgiConnect(bindPath);
763 if(doStart && (!doBind || appServerSock < 0)) {
764 FCGI_Start(bindPath, appPath, nServers);
768 appServerSock = OS_FcgiConnect(bindPath);
771 if(appServerSock < 0) {
772 fprintf(stderr, "Could not connect to %s\n", bindPath);
776 * Set an arbitrary non-null FCGI RequestId
780 * XXX: Send FCGI_GET_VALUES
784 * XXX: Receive FCGI_GET_VALUES_RESULT
788 * Send FCGI_BEGIN_REQUEST (XXX: hack, separate write)
790 beginRecord.header = MakeHeader(FCGI_BEGIN_REQUEST, requestId,
791 sizeof(beginRecord.body), 0);
792 beginRecord.body = MakeBeginRequestBody(FCGI_RESPONDER, FALSE);
793 count = OS_Write(appServerSock, (char *)&beginRecord, sizeof(beginRecord));
794 if(count != sizeof(beginRecord)) {
798 * Send environment to the FCGI application server
800 paramsStream = CreateWriter(appServerSock, requestId, 8192, FCGI_PARAMS);
801 for( ; *envp != NULL; envp++) {
802 equalPtr = strchr(*envp, '=');
803 if(equalPtr == NULL) {
806 valueLen = strlen(equalPtr + 1);
807 FCGIUtil_BuildNameValueHeader(
812 if(FCGX_PutStr((char *) &headerBuff[0], headerLen, paramsStream) < 0
813 || FCGX_PutStr(*envp, equalPtr - *envp, paramsStream) < 0
814 || FCGX_PutStr(equalPtr + 1, valueLen, paramsStream) < 0) {
815 exit(FCGX_GetError(paramsStream));
818 FCGX_FClose(paramsStream);
819 FreeStream(¶msStream);
821 * Perform the event loop until AppServerReadHander sees FCGI_END_REQUEST
823 fromWS.stop = fromWS.next = &fromWS.buff[0];
824 webServerReadHandlerEOF = FALSE;
826 * XXX: might want to use numFDs in the os library.
828 numFDs = max(appServerSock, STDIN_FILENO) + 1;
829 OS_SetFlags(appServerSock, O_NONBLOCK);
831 if (bytesToRead <= 0)
836 while(!exitStatusSet) {
838 * NULL = wait forever (or at least until there's something
844 FCGIexit(exitStatus);