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.6 1999/07/27 13:56:59 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"
47 extern char **environ;
50 static int wsReadPending = 0;
51 static int fcgiReadPending = 0;
52 static int fcgiWritePending = 0;
54 static void ScheduleIo(void);
58 * Simple buffer (not ring buffer) type, used by all event handlers.
68 *----------------------------------------------------------------------
72 * Returns a count of the number of characters available
73 * in the buffer (at most n) and advances past these
74 * characters. Stores a pointer to the first of these
77 *----------------------------------------------------------------------
80 static int GetPtr(char **ptr, int n, Buffer *pBuf)
84 result = min(n, pBuf->stop - pBuf->next);
90 *----------------------------------------------------------------------
94 * Constructs an FCGI_Header struct.
96 *----------------------------------------------------------------------
98 static FCGI_Header MakeHeader(
105 ASSERT(contentLength >= 0 && contentLength <= FCGI_MAX_LENGTH);
106 ASSERT(paddingLength >= 0 && paddingLength <= 0xff);
107 header.version = FCGI_VERSION_1;
109 header.requestIdB1 = (requestId >> 8) & 0xff;
110 header.requestIdB0 = (requestId ) & 0xff;
111 header.contentLengthB1 = (contentLength >> 8) & 0xff;
112 header.contentLengthB0 = (contentLength ) & 0xff;
113 header.paddingLength = paddingLength;
119 *----------------------------------------------------------------------
121 * MakeBeginRequestBody --
123 * Constructs an FCGI_BeginRequestBody record.
125 *----------------------------------------------------------------------
127 static FCGI_BeginRequestBody MakeBeginRequestBody(
131 FCGI_BeginRequestBody body;
132 ASSERT((role >> 16) == 0);
133 body.roleB1 = (role >> 8) & 0xff;
134 body.roleB0 = (role ) & 0xff;
135 body.flags = (keepConnection) ? FCGI_KEEP_CONN : 0;
136 memset(body.reserved, 0, sizeof(body.reserved));
141 static int bytesToRead; /* number of bytes to read from Web Server */
142 static int appServerSock = -1; /* Socket connected to FastCGI application,
143 * used by AppServerReadHandler and
144 * AppServerWriteHandler. */
145 static Buffer fromAS; /* Bytes read from the FCGI application server. */
146 static FCGI_Header header; /* Header of the current record. Is global
147 * since read may return a partial header. */
148 static int headerLen = 0; /* Number of valid bytes contained in header.
149 * If headerLen < sizeof(header),
150 * AppServerReadHandler is reading a record header;
151 * otherwise it is reading bytes of record content
153 static int contentLen; /* If headerLen == sizeof(header), contentLen
154 * is the number of content bytes still to be
156 static int paddingLen; /* If headerLen == sizeof(header), paddingLen
157 * is the number of padding bytes still
159 static int requestId; /* RequestId of the current request.
161 static FCGI_EndRequestBody erBody;
162 static int readingEndRequestBody = FALSE;
163 /* If readingEndRequestBody, erBody contains
164 * partial content: contentLen more bytes need
166 static int exitStatus = 0;
167 static int exitStatusSet = FALSE;
169 static int stdinFds[3];
173 *----------------------------------------------------------------------
177 * FCGIexit provides a single point of exit. It's main use is for
178 * application debug when porting to other operating systems.
180 *----------------------------------------------------------------------
182 static void FCGIexit(int exitCode)
184 if(appServerSock != -1) {
185 OS_Close(appServerSock);
193 #define exit FCGIexit
197 *----------------------------------------------------------------------
199 * AppServerReadHandler --
201 * Reads data from the FCGI application server and (blocking)
202 * writes all of it to the Web server. Exits the program upon
203 * reading EOF from the FCGI application server. Called only when
204 * there's data ready to read from the application server.
206 *----------------------------------------------------------------------
209 static void AppServerReadHandler(ClientData clientData, int bytesRead)
214 assert(fcgiReadPending == TRUE);
215 fcgiReadPending = FALSE;
222 if(headerLen > 0 || paddingLen > 0) {
223 exit(FCGX_PROTOCOL_ERROR);
225 if(appServerSock != -1) {
226 OS_Close(appServerSock);
230 * XXX: Shouldn't be here if exitStatusSet.
232 exit((exitStatusSet) ? exitStatus : FCGX_PROTOCOL_ERROR);
234 fromAS.stop = fromAS.next + count;
235 while(fromAS.next != fromAS.stop) {
237 * fromAS is not empty. What to do with the contents?
239 if(headerLen < sizeof(header)) {
241 * First priority is to complete the header.
243 count = GetPtr(&ptr, sizeof(header) - headerLen, &fromAS);
245 memcpy(&header + headerLen, ptr, count);
247 if(headerLen < sizeof(header)) {
250 if(header.version != FCGI_VERSION_1) {
251 exit(FCGX_UNSUPPORTED_VERSION);
253 if((header.requestIdB1 << 8) + header.requestIdB0 != requestId) {
254 exit(FCGX_PROTOCOL_ERROR);
256 contentLen = (header.contentLengthB1 << 8)
257 + header.contentLengthB0;
258 paddingLen = header.paddingLength;
261 * Header is complete (possibly from previous call). What now?
263 switch(header.type) {
267 * Write the buffered content to stdout or stderr.
268 * Blocking writes are OK here; can't prevent a slow
269 * client from tying up the app server without buffering
270 * output in temporary files.
272 count = GetPtr(&ptr, contentLen, &fromAS);
275 outFD = (header.type == FCGI_STDOUT) ?
276 STDOUT_FILENO : STDERR_FILENO;
277 if(OS_Write(outFD, ptr, count) < 0) {
282 case FCGI_END_REQUEST:
283 if(!readingEndRequestBody) {
284 if(contentLen != sizeof(erBody)) {
285 exit(FCGX_PROTOCOL_ERROR);
287 readingEndRequestBody = TRUE;
289 count = GetPtr(&ptr, contentLen, &fromAS);
291 memcpy(&erBody + sizeof(erBody) - contentLen,
295 if(contentLen == 0) {
296 if(erBody.protocolStatus != FCGI_REQUEST_COMPLETE) {
298 * XXX: What to do with FCGI_OVERLOADED?
300 exit(FCGX_PROTOCOL_ERROR);
302 exitStatus = (erBody.appStatusB3 << 24)
303 + (erBody.appStatusB2 << 16)
304 + (erBody.appStatusB1 << 8)
305 + (erBody.appStatusB0 );
306 exitStatusSet = TRUE;
307 readingEndRequestBody = FALSE;
310 case FCGI_GET_VALUES_RESULT:
312 case FCGI_UNKNOWN_TYPE:
315 exit(FCGX_PROTOCOL_ERROR);
317 if(contentLen == 0) {
319 paddingLen -= GetPtr(&ptr, paddingLen, &fromAS);
322 * If we've processed all the data and skipped all the
323 * padding, discard the header and look for the next one.
325 if(paddingLen == 0) {
329 } /* headerLen >= sizeof(header) */
334 static Buffer fromWS; /* Buffer for data read from Web server
335 * and written to FastCGI application. Used
336 * by WebServerReadHandler and
337 * AppServerWriteHandler. */
338 static int webServerReadHandlerEOF;
339 /* TRUE iff WebServerReadHandler has read EOF from
340 * the Web server. Used in main to prevent
341 * rescheduling WebServerReadHandler. */
344 *----------------------------------------------------------------------
346 * WebServerReadHandler --
348 * Non-blocking reads data from the Web server into the fromWS
349 * buffer. Called only when fromWS is empty, no EOF has been
350 * received from the Web server, and there's data available to read.
352 *----------------------------------------------------------------------
355 static void WebServerReadHandler(ClientData clientData, int bytesRead)
357 assert(fromWS.next == fromWS.stop);
358 assert(fromWS.next == &fromWS.buff[0]);
359 assert(wsReadPending == TRUE);
360 wsReadPending = FALSE;
365 *((FCGI_Header *) &fromWS.buff[0])
366 = MakeHeader(FCGI_STDIN, requestId, bytesRead, 0);
367 bytesToRead -= bytesRead;
368 fromWS.stop = &fromWS.buff[sizeof(FCGI_Header) + bytesRead];
369 webServerReadHandlerEOF = (bytesRead == 0);
374 *----------------------------------------------------------------------
376 * AppServerWriteHandler --
378 * Non-blocking writes data from the fromWS buffer to the FCGI
379 * application server. Called only when fromWS is non-empty
380 * and the socket is ready to accept some data.
382 *----------------------------------------------------------------------
385 static void AppServerWriteHandler(ClientData clientData, int bytesWritten)
387 int length = fromWS.stop - fromWS.next;
390 assert(fcgiWritePending == TRUE);
392 fcgiWritePending = FALSE;
393 if(bytesWritten < 0) {
396 if((int)bytesWritten < length) {
397 fromWS.next += bytesWritten;
399 fromWS.stop = fromWS.next = &fromWS.buff[0];
409 * This functions is responsible for scheduling all I/O to move
410 * data between a web server and a FastCGI application.
416 * This routine will signal the ioEvent upon completion.
419 static void ScheduleIo(void)
424 * Move data between standard in and the FastCGI connection.
426 if(!fcgiWritePending && appServerSock != -1 &&
427 ((length = fromWS.stop - fromWS.next) != 0)) {
428 if(OS_AsyncWrite(appServerSock, 0, fromWS.next, length,
429 AppServerWriteHandler,
430 (ClientData)appServerSock) == -1) {
433 fcgiWritePending = TRUE;
438 * Schedule a read from the FastCGI application if there's not
439 * one pending and there's room in the buffer.
441 if(!fcgiReadPending && appServerSock != -1) {
442 fromAS.next = &fromAS.buff[0];
444 if(OS_AsyncRead(appServerSock, 0, fromAS.next, BUFFLEN,
445 AppServerReadHandler,
446 (ClientData)appServerSock) == -1) {
449 fcgiReadPending = TRUE;
454 * Schedule a read from standard in if necessary.
456 if((bytesToRead > 0) && !webServerReadHandlerEOF && !wsReadPending &&
458 fromWS.next == &fromWS.buff[0]) {
459 if(OS_AsyncReadStdin(fromWS.next + sizeof(FCGI_Header),
460 BUFFLEN - sizeof(FCGI_Header),
461 WebServerReadHandler, STDIN_FILENO)== -1) {
464 wsReadPending = TRUE;
471 *----------------------------------------------------------------------
475 * Starts nServers copies of FCGI application appPath, all
476 * listening to a Unix Domain socket at bindPath.
478 *----------------------------------------------------------------------
481 static void FCGI_Start(char *bindPath, char *appPath, int nServers)
485 if((listenFd = OS_CreateLocalIpcFd(bindPath)) == -1) {
489 if(access(appPath, X_OK) == -1) {
490 fprintf(stderr, "%s is not executable\n", appPath);
495 * Create the server processes
497 for(i = 0; i < nServers; i++) {
498 if(OS_SpawnChild(appPath, listenFd) == -1) {
506 *----------------------------------------------------------------------
508 * FCGIUtil_BuildNameValueHeader --
510 * Builds a name-value pair header from the name length
511 * and the value length. Stores the header into *headerBuffPtr,
512 * and stores the length of the header into *headerLenPtr.
515 * Stores header's length (at most 8) into *headerLenPtr,
516 * and stores the header itself into
517 * headerBuffPtr[0 .. *headerLenPtr - 1].
519 *----------------------------------------------------------------------
521 static void FCGIUtil_BuildNameValueHeader(
524 unsigned char *headerBuffPtr,
526 unsigned char *startHeaderBuffPtr = headerBuffPtr;
528 ASSERT(nameLen >= 0);
529 if (nameLen < 0x80 == 0) {
530 *headerBuffPtr++ = nameLen;
532 *headerBuffPtr++ = (nameLen >> 24) | 0x80;
533 *headerBuffPtr++ = (nameLen >> 16);
534 *headerBuffPtr++ = (nameLen >> 8);
535 *headerBuffPtr++ = nameLen;
537 ASSERT(valueLen >= 0);
538 if (valueLen < 0x80 == 0) {
539 *headerBuffPtr++ = valueLen;
541 *headerBuffPtr++ = (valueLen >> 24) | 0x80;
542 *headerBuffPtr++ = (valueLen >> 16);
543 *headerBuffPtr++ = (valueLen >> 8);
544 *headerBuffPtr++ = valueLen;
546 *headerLenPtr = headerBuffPtr - startHeaderBuffPtr;
551 static int ParseArgs(int argc, char *argv[],
552 int *doBindPtr, int *doStartPtr,
553 char *connectPathPtr, char *appPathPtr, int *nServersPtr) {
566 *connectPathPtr = '\0';
570 for(i = 0; i < MAXARGS; i++)
572 for(i = 1; i < argc; i++) {
573 if(argv[i][0] == '-') {
574 if(!strcmp(argv[i], "-f")) {
577 "Missing command file name after -f\n");
580 if((fp = fopen(argv[i], "r")) == NULL) {
581 fprintf(stderr, "Cannot open command file %s\n", argv[i]);
585 while(fgets(line, BUFSIZ, fp)) {
589 if((tp1 = (char *) strrchr(line,'\n')) != NULL) {
591 while(*tp1 == ' ' || *tp1 =='\t') {
595 fprintf(stderr, "Line to long\n");
600 if((tp2 = strchr(tp1, ' ')) != NULL) {
605 "To many arguments, "
606 "%d is max from a file\n", MAXARGS);
609 if((av[ac] = malloc(strlen(tp1)+1)) == NULL) {
610 fprintf(stderr, "Cannot allocate %d bytes\n",
614 strcpy(av[ac++], tp1);
618 err = ParseArgs(ac, av, doBindPtr, doStartPtr,
619 connectPathPtr, appPathPtr, nServersPtr);
620 for(x = 1; x < ac; x++) {
621 ASSERT(av[x] != NULL);
626 } else if (!strcmp(argv[i], "-jitcgi")) {
628 } else if (!strcmp(argv[i], "-dbgfcgi")) {
629 putenv("DEBUG_FCGI=TRUE");
631 } else if(!strcmp(argv[i], "-start")) {
633 } else if(!strcmp(argv[i], "-bind")) {
635 } else if(!strcmp(argv[i], "-connect")) {
638 "Missing connection name after -connect\n");
641 strcpy(connectPathPtr, argv[i]);
644 fprintf(stderr, "Unknown option %s\n", argv[i]);
647 } else if(*appPathPtr == '\0') {
648 strcpy(appPathPtr, argv[i]);
649 } else if(isdigit(argv[i][0]) && *nServersPtr == 0) {
650 *nServersPtr = atoi(argv[i]);
651 if(*nServersPtr <= 0) {
652 fprintf(stderr, "Number of servers must be greater than 0\n");
656 fprintf(stderr, "Unknown argument %s\n", argv[i]);
660 if(*doStartPtr && *appPathPtr == 0) {
661 fprintf(stderr, "Missing application pathname\n");
664 if(*connectPathPtr == 0) {
665 fprintf(stderr, "Missing -connect <connName>\n");
667 } else if(strchr(connectPathPtr, ':')) {
669 * XXX: Test to see if we can use IP connect locally...
670 This hack lets me test the ability to create a local process listening
671 to a TCP/IP port for connections and subsequently connect to the app
672 like we do for Unix domain and named pipes.
674 if(*doStartPtr && *doBindPtr) {
676 "<connName> of form hostName:portNumber "
677 "requires -start or -bind\n");
682 if(*nServersPtr == 0) {
688 int main(int argc, char **argv)
690 char **envp = environ;
692 FCGX_Stream *paramsStream;
694 unsigned char headerBuff[8];
695 int headerLen, valueLen;
697 FCGI_BeginRequestRecord beginRecord;
698 int doBind, doStart, nServers;
699 char appPath[MAXPATHLEN], bindPath[MAXPATHLEN];
701 if(ParseArgs(argc, argv, &doBind, &doStart,
702 (char *) &bindPath, (char *) &appPath, &nServers)) {
705 " cgi-fcgi -f <cmdPath> , or\n"
706 " cgi-fcgi -connect <connName> <appPath> [<nServers>] , or\n"
707 " cgi-fcgi -start -connect <connName> <appPath> [<nServers>] , or\n"
708 " cgi-fcgi -bind -connect <connName> ,\n"
709 "where <connName> is either the pathname of a UNIX domain socket\n"
710 "or (if -bind is given) a hostName:portNumber specification\n"
711 "or (if -start is given) a :portNumber specification (uses local host).\n");
715 if(OS_LibInit(stdinFds)) {
716 fprintf(stderr, "Error initializing OS library: %d\n", OS_Errno);
720 equalPtr = getenv("CONTENT_LENGTH");
721 if(equalPtr != NULL) {
722 bytesToRead = atoi(equalPtr);
728 appServerSock = OS_FcgiConnect(bindPath);
730 if(doStart && (!doBind || appServerSock < 0)) {
731 FCGI_Start(bindPath, appPath, nServers);
735 appServerSock = OS_FcgiConnect(bindPath);
738 if(appServerSock < 0) {
739 fprintf(stderr, "Could not connect to %s\n", bindPath);
743 * Set an arbitrary non-null FCGI RequestId
747 * XXX: Send FCGI_GET_VALUES
751 * XXX: Receive FCGI_GET_VALUES_RESULT
755 * Send FCGI_BEGIN_REQUEST (XXX: hack, separate write)
757 beginRecord.header = MakeHeader(FCGI_BEGIN_REQUEST, requestId,
758 sizeof(beginRecord.body), 0);
759 beginRecord.body = MakeBeginRequestBody(FCGI_RESPONDER, FALSE);
760 count = OS_Write(appServerSock, (char *)&beginRecord, sizeof(beginRecord));
761 if(count != sizeof(beginRecord)) {
765 * Send environment to the FCGI application server
767 paramsStream = CreateWriter(appServerSock, requestId, 8192, FCGI_PARAMS);
768 for( ; *envp != NULL; envp++) {
769 equalPtr = strchr(*envp, '=');
770 if(equalPtr == NULL) {
773 valueLen = strlen(equalPtr + 1);
774 FCGIUtil_BuildNameValueHeader(
779 if(FCGX_PutStr((char *) &headerBuff[0], headerLen, paramsStream) < 0
780 || FCGX_PutStr(*envp, equalPtr - *envp, paramsStream) < 0
781 || FCGX_PutStr(equalPtr + 1, valueLen, paramsStream) < 0) {
782 exit(FCGX_GetError(paramsStream));
785 FCGX_FClose(paramsStream);
786 FreeStream(¶msStream);
788 * Perform the event loop until AppServerReadHander sees FCGI_END_REQUEST
790 fromWS.stop = fromWS.next = &fromWS.buff[0];
791 webServerReadHandlerEOF = FALSE;
793 * XXX: might want to use numFDs in the os library.
795 numFDs = max(appServerSock, STDIN_FILENO) + 1;
796 OS_SetFlags(appServerSock, O_NONBLOCK);
799 while(!exitStatusSet) {
801 * NULL = wait forever (or at least until there's something
807 FCGIexit(exitStatus);