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.
15 static const char rcsid[] = "$Id: cgi-fcgi.c,v 1.2 1999/01/30 22:33:23 roberts Exp $";
19 #if defined HAVE_UNISTD_H || defined __linux__
31 #ifdef HAVE_SYS_TIME_H
34 #ifdef HAVE_SYS_PARAM_H
35 #include <sys/param.h>
39 #include "fcgiappmisc.h"
41 #include "fcgi_config.h"
44 static int wsReadPending = 0;
45 static int fcgiReadPending = 0;
46 static int fcgiWritePending = 0;
48 static void ScheduleIo(void);
52 * Simple buffer (not ring buffer) type, used by all event handlers.
62 *----------------------------------------------------------------------
66 * Returns a count of the number of characters available
67 * in the buffer (at most n) and advances past these
68 * characters. Stores a pointer to the first of these
71 *----------------------------------------------------------------------
74 static int GetPtr(char **ptr, int n, Buffer *pBuf)
78 result = min(n, pBuf->stop - pBuf->next);
84 *----------------------------------------------------------------------
88 * Constructs an FCGI_Header struct.
90 *----------------------------------------------------------------------
92 static FCGI_Header MakeHeader(
99 ASSERT(contentLength >= 0 && contentLength <= FCGI_MAX_LENGTH);
100 ASSERT(paddingLength >= 0 && paddingLength <= 0xff);
101 header.version = FCGI_VERSION_1;
103 header.requestIdB1 = (requestId >> 8) & 0xff;
104 header.requestIdB0 = (requestId ) & 0xff;
105 header.contentLengthB1 = (contentLength >> 8) & 0xff;
106 header.contentLengthB0 = (contentLength ) & 0xff;
107 header.paddingLength = paddingLength;
113 *----------------------------------------------------------------------
115 * MakeBeginRequestBody --
117 * Constructs an FCGI_BeginRequestBody record.
119 *----------------------------------------------------------------------
121 static FCGI_BeginRequestBody MakeBeginRequestBody(
125 FCGI_BeginRequestBody body;
126 ASSERT((role >> 16) == 0);
127 body.roleB1 = (role >> 8) & 0xff;
128 body.roleB0 = (role ) & 0xff;
129 body.flags = (keepConnection) ? FCGI_KEEP_CONN : 0;
130 memset(body.reserved, 0, sizeof(body.reserved));
135 static int bytesToRead; /* number of bytes to read from Web Server */
136 static int appServerSock = -1; /* Socket connected to FastCGI application,
137 * used by AppServerReadHandler and
138 * AppServerWriteHandler. */
139 static Buffer fromAS; /* Bytes read from the FCGI application server. */
140 static FCGI_Header header; /* Header of the current record. Is global
141 * since read may return a partial header. */
142 static int headerLen = 0; /* Number of valid bytes contained in header.
143 * If headerLen < sizeof(header),
144 * AppServerReadHandler is reading a record header;
145 * otherwise it is reading bytes of record content
147 static int contentLen; /* If headerLen == sizeof(header), contentLen
148 * is the number of content bytes still to be
150 static int paddingLen; /* If headerLen == sizeof(header), paddingLen
151 * is the number of padding bytes still
153 static int requestId; /* RequestId of the current request.
155 static FCGI_EndRequestBody erBody;
156 static int readingEndRequestBody = FALSE;
157 /* If readingEndRequestBody, erBody contains
158 * partial content: contentLen more bytes need
160 static int exitStatus = 0;
161 static int exitStatusSet = FALSE;
163 static int stdinFds[3];
167 *----------------------------------------------------------------------
171 * FCGIexit provides a single point of exit. It's main use is for
172 * application debug when porting to other operating systems.
174 *----------------------------------------------------------------------
176 static void FCGIexit(int exitCode)
178 if(appServerSock != -1) {
179 OS_Close(appServerSock);
187 #define exit FCGIexit
191 *----------------------------------------------------------------------
193 * AppServerReadHandler --
195 * Reads data from the FCGI application server and (blocking)
196 * writes all of it to the Web server. Exits the program upon
197 * reading EOF from the FCGI application server. Called only when
198 * there's data ready to read from the application server.
200 *----------------------------------------------------------------------
203 static void AppServerReadHandler(ClientData clientData, int bytesRead)
208 assert(fcgiReadPending == TRUE);
209 fcgiReadPending = FALSE;
216 if(headerLen > 0 || paddingLen > 0) {
217 exit(FCGX_PROTOCOL_ERROR);
219 if(appServerSock != -1) {
220 OS_Close(appServerSock);
224 * XXX: Shouldn't be here if exitStatusSet.
226 exit((exitStatusSet) ? exitStatus : FCGX_PROTOCOL_ERROR);
228 fromAS.stop = fromAS.next + count;
229 while(fromAS.next != fromAS.stop) {
231 * fromAS is not empty. What to do with the contents?
233 if(headerLen < sizeof(header)) {
235 * First priority is to complete the header.
237 count = GetPtr(&ptr, sizeof(header) - headerLen, &fromAS);
239 memcpy(&header + headerLen, ptr, count);
241 if(headerLen < sizeof(header)) {
244 if(header.version != FCGI_VERSION_1) {
245 exit(FCGX_UNSUPPORTED_VERSION);
247 if((header.requestIdB1 << 8) + header.requestIdB0 != requestId) {
248 exit(FCGX_PROTOCOL_ERROR);
250 contentLen = (header.contentLengthB1 << 8)
251 + header.contentLengthB0;
252 paddingLen = header.paddingLength;
255 * Header is complete (possibly from previous call). What now?
257 switch(header.type) {
261 * Write the buffered content to stdout or stderr.
262 * Blocking writes are OK here; can't prevent a slow
263 * client from tying up the app server without buffering
264 * output in temporary files.
266 count = GetPtr(&ptr, contentLen, &fromAS);
269 outFD = (header.type == FCGI_STDOUT) ?
270 STDOUT_FILENO : STDERR_FILENO;
271 if(OS_Write(outFD, ptr, count) < 0) {
276 case FCGI_END_REQUEST:
277 if(!readingEndRequestBody) {
278 if(contentLen != sizeof(erBody)) {
279 exit(FCGX_PROTOCOL_ERROR);
281 readingEndRequestBody = TRUE;
283 count = GetPtr(&ptr, contentLen, &fromAS);
285 memcpy(&erBody + sizeof(erBody) - contentLen,
289 if(contentLen == 0) {
290 if(erBody.protocolStatus != FCGI_REQUEST_COMPLETE) {
292 * XXX: What to do with FCGI_OVERLOADED?
294 exit(FCGX_PROTOCOL_ERROR);
296 exitStatus = (erBody.appStatusB3 << 24)
297 + (erBody.appStatusB2 << 16)
298 + (erBody.appStatusB1 << 8)
299 + (erBody.appStatusB0 );
300 exitStatusSet = TRUE;
301 readingEndRequestBody = FALSE;
304 case FCGI_GET_VALUES_RESULT:
306 case FCGI_UNKNOWN_TYPE:
309 exit(FCGX_PROTOCOL_ERROR);
311 if(contentLen == 0) {
313 paddingLen -= GetPtr(&ptr, paddingLen, &fromAS);
316 * If we've processed all the data and skipped all the
317 * padding, discard the header and look for the next one.
319 if(paddingLen == 0) {
323 } /* headerLen >= sizeof(header) */
328 static Buffer fromWS; /* Buffer for data read from Web server
329 * and written to FastCGI application. Used
330 * by WebServerReadHandler and
331 * AppServerWriteHandler. */
332 static int webServerReadHandlerEOF;
333 /* TRUE iff WebServerReadHandler has read EOF from
334 * the Web server. Used in main to prevent
335 * rescheduling WebServerReadHandler. */
338 *----------------------------------------------------------------------
340 * WebServerReadHandler --
342 * Non-blocking reads data from the Web server into the fromWS
343 * buffer. Called only when fromWS is empty, no EOF has been
344 * received from the Web server, and there's data available to read.
346 *----------------------------------------------------------------------
349 static void WebServerReadHandler(ClientData clientData, int bytesRead)
351 assert(fromWS.next == fromWS.stop);
352 assert(fromWS.next == &fromWS.buff[0]);
353 assert(wsReadPending == TRUE);
354 wsReadPending = FALSE;
359 *((FCGI_Header *) &fromWS.buff[0])
360 = MakeHeader(FCGI_STDIN, requestId, bytesRead, 0);
361 bytesToRead -= bytesRead;
362 fromWS.stop = &fromWS.buff[sizeof(FCGI_Header) + bytesRead];
363 webServerReadHandlerEOF = (bytesRead == 0);
368 *----------------------------------------------------------------------
370 * AppServerWriteHandler --
372 * Non-blocking writes data from the fromWS buffer to the FCGI
373 * application server. Called only when fromWS is non-empty
374 * and the socket is ready to accept some data.
376 *----------------------------------------------------------------------
379 static void AppServerWriteHandler(ClientData clientData, int bytesWritten)
381 int length = fromWS.stop - fromWS.next;
384 assert(fcgiWritePending == TRUE);
386 fcgiWritePending = FALSE;
387 if(bytesWritten < 0) {
390 if((int)bytesWritten < length) {
391 fromWS.next += bytesWritten;
393 fromWS.stop = fromWS.next = &fromWS.buff[0];
403 * This functions is responsible for scheduling all I/O to move
404 * data between a web server and a FastCGI application.
410 * This routine will signal the ioEvent upon completion.
413 static void ScheduleIo(void)
418 * Move data between standard in and the FastCGI connection.
420 if(!fcgiWritePending && appServerSock != -1 &&
421 ((length = fromWS.stop - fromWS.next) != 0)) {
422 if(OS_AsyncWrite(appServerSock, 0, fromWS.next, length,
423 AppServerWriteHandler,
424 (ClientData)appServerSock) == -1) {
427 fcgiWritePending = TRUE;
432 * Schedule a read from the FastCGI application if there's not
433 * one pending and there's room in the buffer.
435 if(!fcgiReadPending && appServerSock != -1) {
436 fromAS.next = &fromAS.buff[0];
438 if(OS_AsyncRead(appServerSock, 0, fromAS.next, BUFFLEN,
439 AppServerReadHandler,
440 (ClientData)appServerSock) == -1) {
443 fcgiReadPending = TRUE;
448 * Schedule a read from standard in if necessary.
450 if((bytesToRead > 0) && !webServerReadHandlerEOF && !wsReadPending &&
452 fromWS.next == &fromWS.buff[0]) {
453 if(OS_AsyncReadStdin(fromWS.next + sizeof(FCGI_Header),
454 BUFFLEN - sizeof(FCGI_Header),
455 WebServerReadHandler, STDIN_FILENO)== -1) {
458 wsReadPending = TRUE;
465 *----------------------------------------------------------------------
469 * Starts nServers copies of FCGI application appPath, all
470 * listening to a Unix Domain socket at bindPath.
472 *----------------------------------------------------------------------
475 static void FCGI_Start(char *bindPath, char *appPath, int nServers)
479 if((listenFd = OS_CreateLocalIpcFd(bindPath)) == -1) {
483 if(access(appPath, X_OK) == -1) {
484 fprintf(stderr, "%s is not executable\n", appPath);
489 * Create the server processes
491 for(i = 0; i < nServers; i++) {
492 if(OS_SpawnChild(appPath, listenFd) == -1) {
500 *----------------------------------------------------------------------
502 * FCGIUtil_BuildNameValueHeader --
504 * Builds a name-value pair header from the name length
505 * and the value length. Stores the header into *headerBuffPtr,
506 * and stores the length of the header into *headerLenPtr.
509 * Stores header's length (at most 8) into *headerLenPtr,
510 * and stores the header itself into
511 * headerBuffPtr[0 .. *headerLenPtr - 1].
513 *----------------------------------------------------------------------
515 static buildNameValueHeaderCalls = 0; /* XXX: for testing */
517 static void FCGIUtil_BuildNameValueHeader(
520 unsigned char *headerBuffPtr,
522 unsigned char *startHeaderBuffPtr = headerBuffPtr;
524 ASSERT(nameLen >= 0);
525 if(nameLen < 0x80 && (buildNameValueHeaderCalls & 1) == 0) {
526 *headerBuffPtr++ = nameLen;
528 *headerBuffPtr++ = (nameLen >> 24) | 0x80;
529 *headerBuffPtr++ = (nameLen >> 16);
530 *headerBuffPtr++ = (nameLen >> 8);
531 *headerBuffPtr++ = nameLen;
533 ASSERT(valueLen >= 0);
534 if(valueLen < 0x80 && (buildNameValueHeaderCalls & 2) == 0) {
535 *headerBuffPtr++ = valueLen;
537 *headerBuffPtr++ = (valueLen >> 24) | 0x80;
538 *headerBuffPtr++ = (valueLen >> 16);
539 *headerBuffPtr++ = (valueLen >> 8);
540 *headerBuffPtr++ = valueLen;
542 *headerLenPtr = headerBuffPtr - startHeaderBuffPtr;
543 buildNameValueHeaderCalls++;
548 static int ParseArgs(int argc, char *argv[],
549 int *doBindPtr, int *doStartPtr,
550 char *connectPathPtr, char *appPathPtr, int *nServersPtr) {
563 *connectPathPtr = '\0';
567 for(i = 0; i < MAXARGS; i++)
569 for(i = 1; i < argc; i++) {
570 if(argv[i][0] == '-') {
571 if(!strcmp(argv[i], "-f")) {
574 "Missing command file name after -f\n");
577 if((fp = fopen(argv[i], "r")) == NULL) {
578 fprintf(stderr, "Cannot open command file %s\n", argv[i]);
582 while(fgets(line, BUFSIZ, fp)) {
586 if((tp1 = (char *) strrchr(line,'\n')) != NULL) {
588 while(*tp1 == ' ' || *tp1 =='\t') {
592 fprintf(stderr, "Line to long\n");
597 if((tp2 = strchr(tp1, ' ')) != NULL) {
602 "To many arguments, "
603 "%d is max from a file\n", MAXARGS);
606 if((av[ac] = malloc(strlen(tp1)+1)) == NULL) {
607 fprintf(stderr, "Cannot allocate %d bytes\n",
611 strcpy(av[ac++], tp1);
615 err = ParseArgs(ac, av, doBindPtr, doStartPtr,
616 connectPathPtr, appPathPtr, nServersPtr);
617 for(x = 1; x < ac; x++) {
618 ASSERT(av[x] != NULL);
623 } else if (!strcmp(argv[i], "-jitcgi")) {
625 } else if (!strcmp(argv[i], "-dbgfcgi")) {
626 putenv("DEBUG_FCGI=TRUE");
628 } else if(!strcmp(argv[i], "-start")) {
630 } else if(!strcmp(argv[i], "-bind")) {
632 } else if(!strcmp(argv[i], "-connect")) {
635 "Missing connection name after -connect\n");
638 strcpy(connectPathPtr, argv[i]);
641 fprintf(stderr, "Unknown option %s\n", argv[i]);
644 } else if(*appPathPtr == '\0') {
645 strcpy(appPathPtr, argv[i]);
646 } else if(isdigit(argv[i][0]) && *nServersPtr == 0) {
647 *nServersPtr = atoi(argv[i]);
648 if(*nServersPtr <= 0) {
649 fprintf(stderr, "Number of servers must be greater than 0\n");
653 fprintf(stderr, "Unknown argument %s\n", argv[i]);
657 if(*doStartPtr && *appPathPtr == 0) {
658 fprintf(stderr, "Missing application pathname\n");
661 if(*connectPathPtr == 0) {
662 fprintf(stderr, "Missing -connect <connName>\n");
664 } else if(strchr(connectPathPtr, ':')) {
666 * XXX: Test to see if we can use IP connect locally...
667 This hack lets me test the ability to create a local process listening
668 to a TCP/IP port for connections and subsequently connect to the app
669 like we do for Unix domain and named pipes.
671 if(*doStartPtr && *doBindPtr) {
673 "<connName> of form hostName:portNumber "
674 "requires -start or -bind\n");
679 if(*nServersPtr == 0) {
685 void main(int argc, char **argv, char **envp)
688 FCGX_Stream *paramsStream;
690 unsigned char headerBuff[8];
691 int headerLen, valueLen;
693 FCGI_BeginRequestRecord beginRecord;
694 int doBind, doStart, nServers;
695 char appPath[MAXPATHLEN], bindPath[MAXPATHLEN];
697 if(ParseArgs(argc, argv, &doBind, &doStart,
698 (char *) &bindPath, (char *) &appPath, &nServers)) {
701 " cgi-fcgi -f <cmdPath> , or\n"
702 " cgi-fcgi -connect <connName> <appPath> [<nServers>] , or\n"
703 " cgi-fcgi -start -connect <connName> <appPath> [<nServers>] , or\n"
704 " cgi-fcgi -bind -connect <connName> ,\n"
705 "where <connName> is either the pathname of a UNIX domain socket\n"
706 "or (if -bind is given) a hostName:portNumber specification\n"
707 "or (if -start is given) a :portNumber specification (uses local host).\n");
711 if(OS_LibInit(stdinFds)) {
712 fprintf(stderr, "Error initializing OS library: %d\n", OS_Errno);
716 equalPtr = getenv("CONTENT_LENGTH");
717 if(equalPtr != NULL) {
718 bytesToRead = atoi(equalPtr);
724 appServerSock = OS_FcgiConnect(bindPath);
726 if(doStart && (!doBind || appServerSock < 0)) {
727 FCGI_Start(bindPath, appPath, nServers);
731 appServerSock = OS_FcgiConnect(bindPath);
734 if(appServerSock < 0) {
735 fprintf(stderr, "Could not connect to %s\n", bindPath);
739 * Set an arbitrary non-null FCGI RequestId
743 * XXX: Send FCGI_GET_VALUES
747 * XXX: Receive FCGI_GET_VALUES_RESULT
751 * Send FCGI_BEGIN_REQUEST (XXX: hack, separate write)
753 beginRecord.header = MakeHeader(FCGI_BEGIN_REQUEST, requestId,
754 sizeof(beginRecord.body), 0);
755 beginRecord.body = MakeBeginRequestBody(FCGI_RESPONDER, FALSE);
756 count = OS_Write(appServerSock, (char *)&beginRecord, sizeof(beginRecord));
757 if(count != sizeof(beginRecord)) {
761 * Send environment to the FCGI application server
763 paramsStream = CreateWriter(appServerSock, requestId, 8192, FCGI_PARAMS);
764 for( ; *envp != NULL; envp++) {
765 equalPtr = strchr(*envp, '=');
766 if(equalPtr == NULL) {
769 valueLen = strlen(equalPtr + 1);
770 FCGIUtil_BuildNameValueHeader(
775 if(FCGX_PutStr((char *) &headerBuff[0], headerLen, paramsStream) < 0
776 || FCGX_PutStr(*envp, equalPtr - *envp, paramsStream) < 0
777 || FCGX_PutStr(equalPtr + 1, valueLen, paramsStream) < 0) {
778 exit(FCGX_GetError(paramsStream));
781 FCGX_FClose(paramsStream);
782 FreeStream(¶msStream);
784 * Perform the event loop until AppServerReadHander sees FCGI_END_REQUEST
786 fromWS.stop = fromWS.next = &fromWS.buff[0];
787 webServerReadHandlerEOF = FALSE;
789 * XXX: might want to use numFDs in the os library.
791 numFDs = max(appServerSock, STDIN_FILENO) + 1;
792 OS_SetFlags(appServerSock, O_NONBLOCK);
795 while(!exitStatusSet) {
797 * NULL = wait forever (or at least until there's something
803 FCGIexit(exitStatus);