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.16 2003/06/22 02:02:33 robs Exp $";
25 #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
56 static int wsReadPending = 0;
57 static int fcgiReadPending = 0;
58 static int fcgiWritePending = 0;
60 static void ScheduleIo(void);
64 * Simple buffer (not ring buffer) type, used by all event handlers.
74 *----------------------------------------------------------------------
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
83 *----------------------------------------------------------------------
86 static int GetPtr(char **ptr, int n, Buffer *pBuf)
90 result = min(n, pBuf->stop - pBuf->next);
96 *----------------------------------------------------------------------
100 * Constructs an FCGI_Header struct.
102 *----------------------------------------------------------------------
104 static FCGI_Header MakeHeader(
111 ASSERT(contentLength >= 0 && contentLength <= FCGI_MAX_LENGTH);
112 ASSERT(paddingLength >= 0 && paddingLength <= 0xff);
113 header.version = FCGI_VERSION_1;
114 header.type = (unsigned char) type;
115 header.requestIdB1 = (unsigned char) ((requestId >> 8) & 0xff);
116 header.requestIdB0 = (unsigned char) ((requestId ) & 0xff);
117 header.contentLengthB1 = (unsigned char) ((contentLength >> 8) & 0xff);
118 header.contentLengthB0 = (unsigned char) ((contentLength ) & 0xff);
119 header.paddingLength = (unsigned char) paddingLength;
125 *----------------------------------------------------------------------
127 * MakeBeginRequestBody --
129 * Constructs an FCGI_BeginRequestBody record.
131 *----------------------------------------------------------------------
133 static FCGI_BeginRequestBody MakeBeginRequestBody(
137 FCGI_BeginRequestBody body;
138 ASSERT((role >> 16) == 0);
139 body.roleB1 = (unsigned char) ((role >> 8) & 0xff);
140 body.roleB0 = (unsigned char) (role & 0xff);
141 body.flags = (unsigned char) ((keepConnection) ? FCGI_KEEP_CONN : 0);
142 memset(body.reserved, 0, sizeof(body.reserved));
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
159 static int contentLen; /* If headerLen == sizeof(header), contentLen
160 * is the number of content bytes still to be
162 static int paddingLen; /* If headerLen == sizeof(header), paddingLen
163 * is the number of padding bytes still
165 static int requestId; /* RequestId of the current request.
167 static FCGI_EndRequestBody erBody;
168 static int readingEndRequestBody = FALSE;
169 /* If readingEndRequestBody, erBody contains
170 * partial content: contentLen more bytes need
172 static int exitStatus = 0;
173 static int exitStatusSet = FALSE;
175 static int stdinFds[3];
179 *----------------------------------------------------------------------
183 * FCGIexit provides a single point of exit. It's main use is for
184 * application debug when porting to other operating systems.
186 *----------------------------------------------------------------------
188 static void FCGIexit(int exitCode)
190 if(appServerSock != -1) {
191 OS_Close(appServerSock, TRUE);
199 #define exit FCGIexit
203 *----------------------------------------------------------------------
205 * AppServerReadHandler --
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.
212 *----------------------------------------------------------------------
215 static void AppServerReadHandler(ClientData dc, int bytesRead)
220 /* Touch unused parameters to avoid warnings */
223 assert(fcgiReadPending == TRUE);
224 fcgiReadPending = FALSE;
231 if(headerLen > 0 || paddingLen > 0) {
232 exit(FCGX_PROTOCOL_ERROR);
234 if(appServerSock != -1) {
235 OS_Close(appServerSock, TRUE);
239 * XXX: Shouldn't be here if exitStatusSet.
241 exit((exitStatusSet) ? exitStatus : FCGX_PROTOCOL_ERROR);
243 fromAS.stop = fromAS.next + count;
244 while(fromAS.next != fromAS.stop) {
246 * fromAS is not empty. What to do with the contents?
248 if(headerLen < sizeof(header)) {
250 * First priority is to complete the header.
252 count = GetPtr(&ptr, sizeof(header) - headerLen, &fromAS);
254 memcpy(&header + headerLen, ptr, count);
256 if(headerLen < sizeof(header)) {
259 if(header.version != FCGI_VERSION_1) {
260 exit(FCGX_UNSUPPORTED_VERSION);
262 if((header.requestIdB1 << 8) + header.requestIdB0 != requestId) {
263 exit(FCGX_PROTOCOL_ERROR);
265 contentLen = (header.contentLengthB1 << 8)
266 + header.contentLengthB0;
267 paddingLen = header.paddingLength;
270 * Header is complete (possibly from previous call). What now?
272 switch(header.type) {
276 * Write the buffered content to stdout or stderr.
277 * Blocking writes are OK here; can't prevent a slow
278 * client from tying up the app server without buffering
279 * output in temporary files.
281 count = GetPtr(&ptr, contentLen, &fromAS);
284 outFD = (header.type == FCGI_STDOUT) ?
285 STDOUT_FILENO : STDERR_FILENO;
286 if(OS_Write(outFD, ptr, count) < 0) {
291 case FCGI_END_REQUEST:
292 if(!readingEndRequestBody) {
293 if(contentLen != sizeof(erBody)) {
294 exit(FCGX_PROTOCOL_ERROR);
296 readingEndRequestBody = TRUE;
298 count = GetPtr(&ptr, contentLen, &fromAS);
300 memcpy(&erBody + sizeof(erBody) - contentLen,
304 if(contentLen == 0) {
305 if(erBody.protocolStatus != FCGI_REQUEST_COMPLETE) {
307 * XXX: What to do with FCGI_OVERLOADED?
309 exit(FCGX_PROTOCOL_ERROR);
311 exitStatus = (erBody.appStatusB3 << 24)
312 + (erBody.appStatusB2 << 16)
313 + (erBody.appStatusB1 << 8)
314 + (erBody.appStatusB0 );
315 exitStatusSet = TRUE;
316 readingEndRequestBody = FALSE;
319 case FCGI_GET_VALUES_RESULT:
321 case FCGI_UNKNOWN_TYPE:
324 exit(FCGX_PROTOCOL_ERROR);
326 if(contentLen == 0) {
328 paddingLen -= GetPtr(&ptr, paddingLen, &fromAS);
331 * If we've processed all the data and skipped all the
332 * padding, discard the header and look for the next one.
334 if(paddingLen == 0) {
338 } /* headerLen >= sizeof(header) */
343 static Buffer fromWS; /* Buffer for data read from Web server
344 * and written to FastCGI application. Used
345 * by WebServerReadHandler and
346 * AppServerWriteHandler. */
347 static int webServerReadHandlerEOF;
348 /* TRUE iff WebServerReadHandler has read EOF from
349 * the Web server. Used in main to prevent
350 * rescheduling WebServerReadHandler. */
352 static void WriteStdinEof(void)
354 static int stdin_eof_sent = 0;
359 *((FCGI_Header *)fromWS.stop) = MakeHeader(FCGI_STDIN, requestId, 0, 0);
360 fromWS.stop += sizeof(FCGI_Header);
365 *----------------------------------------------------------------------
367 * WebServerReadHandler --
369 * Non-blocking reads data from the Web server into the fromWS
370 * buffer. Called only when fromWS is empty, no EOF has been
371 * received from the Web server, and there's data available to read.
373 *----------------------------------------------------------------------
376 static void WebServerReadHandler(ClientData dc, int bytesRead)
378 /* Touch unused parameters to avoid warnings */
381 assert(fromWS.next == fromWS.stop);
382 assert(fromWS.next == &fromWS.buff[0]);
383 assert(wsReadPending == TRUE);
384 wsReadPending = FALSE;
389 *((FCGI_Header *) &fromWS.buff[0])
390 = MakeHeader(FCGI_STDIN, requestId, bytesRead, 0);
391 bytesToRead -= bytesRead;
392 fromWS.stop = &fromWS.buff[sizeof(FCGI_Header) + bytesRead];
393 webServerReadHandlerEOF = (bytesRead == 0);
395 if (bytesToRead <= 0)
402 *----------------------------------------------------------------------
404 * AppServerWriteHandler --
406 * Non-blocking writes data from the fromWS buffer to the FCGI
407 * application server. Called only when fromWS is non-empty
408 * and the socket is ready to accept some data.
410 *----------------------------------------------------------------------
413 static void AppServerWriteHandler(ClientData dc, int bytesWritten)
415 int length = fromWS.stop - fromWS.next;
417 /* Touch unused parameters to avoid warnings */
421 assert(fcgiWritePending == TRUE);
423 fcgiWritePending = FALSE;
424 if(bytesWritten < 0) {
427 if((int)bytesWritten < length) {
428 fromWS.next += bytesWritten;
430 fromWS.stop = fromWS.next = &fromWS.buff[0];
440 * This functions is responsible for scheduling all I/O to move
441 * data between a web server and a FastCGI application.
447 * This routine will signal the ioEvent upon completion.
450 static void ScheduleIo(void)
455 * Move data between standard in and the FastCGI connection.
457 if(!fcgiWritePending && appServerSock != -1 &&
458 ((length = fromWS.stop - fromWS.next) != 0)) {
459 if(OS_AsyncWrite(appServerSock, 0, fromWS.next, length,
460 AppServerWriteHandler,
461 (ClientData)appServerSock) == -1) {
464 fcgiWritePending = TRUE;
469 * Schedule a read from the FastCGI application if there's not
470 * one pending and there's room in the buffer.
472 if(!fcgiReadPending && appServerSock != -1) {
473 fromAS.next = &fromAS.buff[0];
475 if(OS_AsyncRead(appServerSock, 0, fromAS.next, BUFFLEN,
476 AppServerReadHandler,
477 (ClientData)appServerSock) == -1) {
480 fcgiReadPending = TRUE;
485 * Schedule a read from standard in if necessary.
487 if((bytesToRead > 0) && !webServerReadHandlerEOF && !wsReadPending &&
489 fromWS.next == &fromWS.buff[0]) {
490 if(OS_AsyncReadStdin(fromWS.next + sizeof(FCGI_Header),
491 BUFFLEN - sizeof(FCGI_Header),
492 WebServerReadHandler, STDIN_FILENO)== -1) {
495 wsReadPending = TRUE;
502 *----------------------------------------------------------------------
506 * Starts nServers copies of FCGI application appPath, all
507 * listening to a Unix Domain socket at bindPath.
509 *----------------------------------------------------------------------
512 static void FCGI_Start(char *bindPath, char *appPath, int nServers)
516 /* @@@ Should be able to pick up the backlog as an arg */
517 if((listenFd = OS_CreateLocalIpcFd(bindPath, 5)) == -1) {
521 if(access(appPath, X_OK) == -1) {
522 fprintf(stderr, "%s is not executable\n", appPath);
527 * Create the server processes
529 for(i = 0; i < nServers; i++) {
530 if(OS_SpawnChild(appPath, listenFd) == -1) {
534 OS_Close(listenFd, TRUE);
538 *----------------------------------------------------------------------
540 * FCGIUtil_BuildNameValueHeader --
542 * Builds a name-value pair header from the name length
543 * and the value length. Stores the header into *headerBuffPtr,
544 * and stores the length of the header into *headerLenPtr.
547 * Stores header's length (at most 8) into *headerLenPtr,
548 * and stores the header itself into
549 * headerBuffPtr[0 .. *headerLenPtr - 1].
551 *----------------------------------------------------------------------
553 static void FCGIUtil_BuildNameValueHeader(
556 unsigned char *headerBuffPtr,
558 unsigned char *startHeaderBuffPtr = headerBuffPtr;
560 ASSERT(nameLen >= 0);
561 if (nameLen < 0x80) {
562 *headerBuffPtr++ = (unsigned char) nameLen;
564 *headerBuffPtr++ = (unsigned char) ((nameLen >> 24) | 0x80);
565 *headerBuffPtr++ = (unsigned char) (nameLen >> 16);
566 *headerBuffPtr++ = (unsigned char) (nameLen >> 8);
567 *headerBuffPtr++ = (unsigned char) nameLen;
569 ASSERT(valueLen >= 0);
570 if (valueLen < 0x80) {
571 *headerBuffPtr++ = (unsigned char) valueLen;
573 *headerBuffPtr++ = (unsigned char) ((valueLen >> 24) | 0x80);
574 *headerBuffPtr++ = (unsigned char) (valueLen >> 16);
575 *headerBuffPtr++ = (unsigned char) (valueLen >> 8);
576 *headerBuffPtr++ = (unsigned char) valueLen;
578 *headerLenPtr = headerBuffPtr - startHeaderBuffPtr;
583 static int ParseArgs(int argc, char *argv[],
584 int *doBindPtr, int *doStartPtr,
585 char *connectPathPtr, char *appPathPtr, int *nServersPtr) {
598 *connectPathPtr = '\0';
602 for(i = 0; i < MAXARGS; i++)
604 for(i = 1; i < argc; i++) {
605 if(argv[i][0] == '-') {
606 if(!strcmp(argv[i], "-f")) {
609 "Missing command file name after -f\n");
612 if((fp = fopen(argv[i], "r")) == NULL) {
613 fprintf(stderr, "Cannot open command file %s\n", argv[i]);
617 while(fgets(line, BUFSIZ, fp)) {
621 if((tp1 = (char *) strrchr(line,'\n')) != NULL) {
623 while(*tp1 == ' ' || *tp1 =='\t') {
627 fprintf(stderr, "Line to long\n");
632 if((tp2 = strchr(tp1, ' ')) != NULL) {
637 "To many arguments, "
638 "%d is max from a file\n", MAXARGS);
641 if((av[ac] = (char *)malloc(strlen(tp1)+1)) == NULL) {
642 fprintf(stderr, "Cannot allocate %d bytes\n",
646 strcpy(av[ac++], tp1);
650 err = ParseArgs(ac, av, doBindPtr, doStartPtr,
651 connectPathPtr, appPathPtr, nServersPtr);
652 for(x = 1; x < ac; x++) {
653 ASSERT(av[x] != NULL);
658 } else if (!strcmp(argv[i], "-jitcgi")) {
660 } else if (!strcmp(argv[i], "-dbgfcgi")) {
661 putenv("DEBUG_FCGI=TRUE");
663 } else if(!strcmp(argv[i], "-start")) {
665 } else if(!strcmp(argv[i], "-bind")) {
667 } else if(!strcmp(argv[i], "-connect")) {
670 "Missing connection name after -connect\n");
673 strcpy(connectPathPtr, argv[i]);
676 fprintf(stderr, "Unknown option %s\n", argv[i]);
679 } else if(*appPathPtr == '\0') {
680 strcpy(appPathPtr, argv[i]);
681 } else if(isdigit((int)argv[i][0]) && *nServersPtr == 0) {
682 *nServersPtr = atoi(argv[i]);
683 if(*nServersPtr <= 0) {
684 fprintf(stderr, "Number of servers must be greater than 0\n");
688 fprintf(stderr, "Unknown argument %s\n", argv[i]);
692 if(*doStartPtr && *appPathPtr == 0) {
693 fprintf(stderr, "Missing application pathname\n");
696 if(*connectPathPtr == 0) {
697 fprintf(stderr, "Missing -connect <connName>\n");
699 } else if(strchr(connectPathPtr, ':')) {
701 * XXX: Test to see if we can use IP connect locally...
702 This hack lets me test the ability to create a local process listening
703 to a TCP/IP port for connections and subsequently connect to the app
704 like we do for Unix domain and named pipes.
706 if(*doStartPtr && *doBindPtr) {
708 "<connName> of form hostName:portNumber "
709 "requires -start or -bind\n");
714 if(*nServersPtr == 0) {
720 int main(int argc, char **argv)
722 char **envp = environ;
724 FCGX_Stream *paramsStream;
726 unsigned char headerBuff[8];
727 int headerLen, valueLen;
729 FCGI_BeginRequestRecord beginRecord;
730 int doBind, doStart, nServers;
731 char appPath[MAXPATHLEN], bindPath[MAXPATHLEN];
733 if(ParseArgs(argc, argv, &doBind, &doStart,
734 (char *) &bindPath, (char *) &appPath, &nServers)) {
737 " cgi-fcgi -f <cmdPath> , or\n"
738 " cgi-fcgi -connect <connName> <appPath> [<nServers>] , or\n"
739 " cgi-fcgi -start -connect <connName> <appPath> [<nServers>] , or\n"
740 " cgi-fcgi -bind -connect <connName> ,\n"
741 "where <connName> is either the pathname of a UNIX domain socket\n"
742 "or (if -bind is given) a hostName:portNumber specification\n"
743 "or (if -start is given) a :portNumber specification (uses local host).\n");
747 if(OS_LibInit(stdinFds)) {
748 fprintf(stderr, "Error initializing OS library: %d\n", OS_Errno);
752 equalPtr = getenv("CONTENT_LENGTH");
753 if(equalPtr != NULL) {
754 bytesToRead = atoi(equalPtr);
760 appServerSock = OS_FcgiConnect(bindPath);
762 if(doStart && (!doBind || appServerSock < 0)) {
763 FCGI_Start(bindPath, appPath, nServers);
767 appServerSock = OS_FcgiConnect(bindPath);
770 if(appServerSock < 0) {
771 fprintf(stderr, "Could not connect to %s\n", bindPath);
775 * Set an arbitrary non-null FCGI RequestId
779 * XXX: Send FCGI_GET_VALUES
783 * XXX: Receive FCGI_GET_VALUES_RESULT
787 * Send FCGI_BEGIN_REQUEST (XXX: hack, separate write)
789 beginRecord.header = MakeHeader(FCGI_BEGIN_REQUEST, requestId,
790 sizeof(beginRecord.body), 0);
791 beginRecord.body = MakeBeginRequestBody(FCGI_RESPONDER, FALSE);
792 count = OS_Write(appServerSock, (char *)&beginRecord, sizeof(beginRecord));
793 if(count != sizeof(beginRecord)) {
797 * Send environment to the FCGI application server
799 paramsStream = FCGX_CreateWriter(appServerSock, requestId, 8192, FCGI_PARAMS);
800 for( ; *envp != NULL; envp++) {
801 equalPtr = strchr(*envp, '=');
802 if(equalPtr == NULL) {
805 valueLen = strlen(equalPtr + 1);
806 FCGIUtil_BuildNameValueHeader(
811 if(FCGX_PutStr((char *) &headerBuff[0], headerLen, paramsStream) < 0
812 || FCGX_PutStr(*envp, equalPtr - *envp, paramsStream) < 0
813 || FCGX_PutStr(equalPtr + 1, valueLen, paramsStream) < 0) {
814 exit(FCGX_GetError(paramsStream));
817 FCGX_FClose(paramsStream);
818 FCGX_FreeStream(¶msStream);
820 * Perform the event loop until AppServerReadHander sees FCGI_END_REQUEST
822 fromWS.stop = fromWS.next = &fromWS.buff[0];
823 webServerReadHandlerEOF = FALSE;
825 * XXX: might want to use numFDs in the os library.
827 numFDs = max(appServerSock, STDIN_FILENO) + 1;
828 OS_SetFlags(appServerSock, O_NONBLOCK);
830 if (bytesToRead <= 0)
835 while(!exitStatusSet) {
837 * NULL = wait forever (or at least until there's something
843 FCGIexit(exitStatus);