pax_global_header00006660000000000000000000000064132370730030014510gustar00rootroot0000000000000052 comment=291264639ab81dae7e994bf82081ce095505920f node-fastcgi-1.3.3/000077500000000000000000000000001323707300300140575ustar00rootroot00000000000000node-fastcgi-1.3.3/.gitignore000066400000000000000000000001461323707300300160500ustar00rootroot00000000000000#npm node_modules npm-debug.log #yarn yarn.lock #Istanbul coverage folder coverage #Examples *.log node-fastcgi-1.3.3/.npmignore000066400000000000000000000001501323707300300160520ustar00rootroot00000000000000#git repo example test #npm node_modules #Codestyle rules .jscsrc #continous integration .travis.yml node-fastcgi-1.3.3/.travis.yml000066400000000000000000000002261323707300300161700ustar00rootroot00000000000000sudo: false language: node_js node_js: - '4' - '5' - '6' - '7' - '8' - '9' - 'node' after_script: - npm run coveralls node-fastcgi-1.3.3/LICENSE000066400000000000000000000021211323707300300150600ustar00rootroot00000000000000The MIT License (MIT) Copyright (c) 2016 Fabio Massaioli and other contributors Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. node-fastcgi-1.3.3/README.md000066400000000000000000000211621323707300300153400ustar00rootroot00000000000000node-fastcgi ============ [![Build Status](https://travis-ci.org/fbbdev/node-fastcgi.svg?branch=master)](https://travis-ci.org/fbbdev/node-fastcgi) [![Coverage Status](https://coveralls.io/repos/github/fbbdev/node-fastcgi/badge.svg?branch=master)](https://coveralls.io/github/fbbdev/node-fastcgi?branch=master) [![Dependency Status](https://gemnasium.com/fbbdev/node-fastcgi.svg)](https://gemnasium.com/fbbdev/node-fastcgi) [![devDependency Status](https://david-dm.org/fbbdev/node-fastcgi/dev-status.svg)](https://david-dm.org/fbbdev/node-fastcgi#info=devDependencies) [![MIT License](http://img.shields.io/badge/license-MIT-blue.svg?style=flat)](LICENSE) [![NPM](https://nodei.co/npm/node-fastcgi.png?downloads=true)](https://nodei.co/npm/node-fastcgi/) This module is a drop-in replacement for node's standard http module (server only). Code written for a http server should work without changes with FastCGI. It can be used to build FastCGI applications or to convert existing node applications to FastCGI. The implementation is fully compliant with the [FastCGI 1.0 Specification](https://fast-cgi.github.io/spec). Example ------- ```javascript var fcgi = require('node-fastcgi'); fcgi.createServer(function(req, res) { if (req.method === 'GET') { res.writeHead(200, { 'Content-Type': 'text/plain' }); res.end("It's working"); } else if (req.method === 'POST') { res.writeHead(200, { 'Content-Type': 'text/plain' }); var body = ""; req.on('data', function(data) { body += data.toString(); }); req.on('end', function() { res.end("Received data:\n" + body); }); } else { res.writeHead(501); res.end(); } }).listen(); ``` Server constructor ------------------ The `createServer` function takes four **optional** parameters: - `responder`: callback for FastCGI responder requests (normal HTTP requests, listener for the `'request'` event). - `authorizer`: callback for FastCGI authorizer requests (listener for the `'authorize'` event) - `filter`: callback for FastCGI filter requests (listener for the `'filter'` event) - `config`: server configuration `config` is an object with the following defaults: ```js { maxConns: 2000, maxReqs: 2000, multiplex: true, valueMap: {} } ``` `maxConns` is the maximum number of connections accepted by the server. This limit is not enforced, it is only used to provide the FCGI_MAX_CONNS value when queried by a FCGI_GET_VALUES record. `maxReqs` is the maximum number of total concurrent requests accepted by the server (over all connections). The limit is not enforced, but compliant clients should respect it, so do not set it too low. This setting is used to provide the FCGI_MAX_REQS value. `multiplex` enables or disables request multiplexing on a single connection. This setting is used to provide the FCGI_MPXS_CONNS value. `valueMap` maps FastCGI value names to keys in the `config` object. For more information read [the next section](#fastcgi-values) FastCGI values -------------- FastCGI clients can query configuration values from applications with FCGI_GET_VALUES records. Those records contain a sequence of key-value pairs with empty values; the application must fetch the corresponding values for each key and send the data back to the client. This module retrieves automatically values for standard keys (`FCGI_MAX_CONNS`, `FCGI_MAX_REQS`, `FCGI_MPXS_CONNS`) from server configuration. To provide additional values, add them to the configuration object and add entries to the `valueMap` option mapping value names to keys in the config object. For example: ```js fcgi.createServer(function (req, res) { /* ... */ }, { additionalValue: 1350, valueMap: { 'ADDITIONAL_VALUE': 'additionalValue' } }); ``` **WARNING: This `valueMap` thing is complete nonsense and is definitely going to change in the next release.** Listening for connections ------------------------- When a FastCGI service is started, the stdin descriptor (fd 0) [is replaced by a bound socket](https://fast-cgi.github.io/spec#accepting-transport-connections). The service application can then start listening on that socket and accept connections. This is done automatically when you call the `listen` method on the server object without arguments, or with a callback as the only argument. The `isService` function is provided to check whether the listen method can be called without arguments. **WARNING: The function always returns false on windows.** ```js if (fcgi.isService()) { fcgi.createServer(/* ... */).listen(); } else { console.log("This script must be run as a FastCGI service"); } ``` Request URL components ---------------------- The `url` property of the request object is taken from the `REQUEST_URI` CGI variable, which is non-standard. If `REQUEST_URI` is missing, the url is built by joining three CGI variables: - [`SCRIPT_NAME`](https://tools.ietf.org/html/rfc3875#section-4.1.13) - [`PATH_INFO`](https://tools.ietf.org/html/rfc3875#section-4.1.5) - [`QUERY_STRING`](https://tools.ietf.org/html/rfc3875#section-4.1.7) For more information read [section 4.1](https://tools.ietf.org/html/rfc3875#section-4.1) of the CGI spec. Raw CGI variables can be accessed through the `params` property of the socket object. More information [here](#the-socket-object). Authorizer and filter requests ------------------------------ Authorizer requests may have no url. Response objects for the authorizer role come with the `Content-Type` header already set to `text/plain` and expose three additional methods: - `setVariable(name, value)`: sets CGI variables to be passed to subsequent request handlers. - `allow()`: sends a 200 (OK) status code and closes the response - `deny()`: sends a 403 (Forbidden) status code and closes the response Filter requests have an additional data stream exposed by the `dataStream` property of [the socket object](#the-socket-object) (`req.socket.dataStream`). The socket object ----------------- The socket object exposed in requests and responses implements the `stream.Duplex` interface. It exposes the FastCGI stdin stream (request body) and translates writes to stdout FastCGI records. The object also emulates the public API of `net.Socket`. Address fields contain HTTP server and client address and port (`localAddress`, `localPort`, `remoteAddress`, `remotePort` properties and the `address` method). The socket object exposes three additional properties: - `params` is a dictionary of raw CGI params. - `dataStream` implements `stream.Readable`, exposes the FastCGI data stream for the filter role. - `errorStream` implements `stream.Writable`, translates writes to stderr FastCGI Records. http module compatibility ------------------------- The API is almost compatible with the http module from node v0.12 all the way to v6.x (the current series). Only the server API is implemented. Differences: - A FastCGI server will never emit `'checkContinue'` and `'connect'` events because `CONNECT` method and `Expect: 100-continue` headers should be handled by the front-end http server - The `'upgrade'` event is not currently implemented. Typically upgrade/websocket requests won't work with FastCGI applications because of input/output buffering. - `server.listen()` can be called without arguments (or with a callback as the only argument) to listen on the default FastCGI socket `{ fd: 0 }`. - `server.maxHeadersCount` is useless - `req.socket` [is not a real socket](#the-socket-object). - `req.trailers` will always be empty: CGI scripts never receive trailers - `res.writeContinue()` works as expected but should not be used. See first item License ======= The MIT License (MIT) Copyright (c) 2016 Fabio Massaioli and other contributors Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. node-fastcgi-1.3.3/example/000077500000000000000000000000001323707300300155125ustar00rootroot00000000000000node-fastcgi-1.3.3/example/cgiFallback.js000077500000000000000000000042701323707300300202400ustar00rootroot00000000000000#!/usr/bin/env node /** * Copyright (c) 2016 Fabio Massaioli and other contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of * the Software, and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ // To run this example: // > npm install puffnfresh/node-cgi // > ./cgiFallback.js 2> /dev/null 'use strict'; var fcgi = require('../index.js'), cgi = require('node-cgi'), fs = require('fs'); function log(msg) { fs.appendFileSync('cgiFallback.log', msg); } var createServer = fcgi.createServer; // check if we're running as a FastCGI service; if not, switch to plain CGI. if (!fcgi.isService()) createServer = cgi.createServer; createServer(function (req, res) { res.writeHead(200, { 'Content-Type': 'text/plain', }); res.end("It's working!\n"); }).listen(function () { log('Listening\n'); }); process.on('uncaughtException', function (err) { log(err.stack + '\n\n'); process.exit(1); }); process.on('exit', function () { log('Exit - Uptime:' + process.uptime() + '\n\n'); }); process.on('SIGTERM', function () { log('SIGTERM\n'); process.exit(0); }); process.on('SIGINT', function () { log('SIGINT\n'); process.exit(0); }); process.on('SIGUSR1', function () { log('SIGUSR1\n'); }); node-fastcgi-1.3.3/example/fileServer.js000077500000000000000000000045241323707300300201660ustar00rootroot00000000000000#!/usr/bin/env node /** * Copyright (c) 2016 Fabio Massaioli and other contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of * the Software, and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ 'use strict'; var fcgi = require('../index.js'), fs = require('fs'); function log(msg) { fs.appendFileSync('fileServer.log', msg); } fcgi.createServer(function (req, res) { var path = req.url.slice(1); fs.stat(path, function (err, stat) { if (err) { res.writeHead(500, { 'Content-Type': 'text/plain; charset=utf-8', 'Content-Length': err.stack.length }); res.end(err.stack + '\n'); } else { var stream = fs.createReadStream(path); res.writeHead(200, { 'Content-Type': 'application/octet-stream', 'Content-Length': stat.size }); stream.pipe(res); } }); }).listen(function () { log('Listening\n'); }); process.on('uncaughtException', function (err) { log(err.stack + '\n\n'); process.exit(1); }); process.on('exit', function () { log('Exit - Uptime:' + process.uptime() + '\n\n'); }); process.on('SIGTERM', function () { log('SIGTERM\n'); process.exit(0); }); process.on('SIGINT', function () { log('SIGINT\n'); process.exit(0); }); process.on('SIGUSR1', function () { log('SIGUSR1\n'); }); node-fastcgi-1.3.3/example/integration.js000077500000000000000000000067121323707300300204040ustar00rootroot00000000000000#!/usr/bin/env node /** * Copyright (c) 2016 Fabio Massaioli, Robert Groh and other contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the 'Software'), to deal in * the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of * the Software, and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ 'use strict'; var path = require('path'), fcgiFramework = require('../index.js'); //this we want to test var port = 8080; var socketPath = path.join(__dirname, 'echoServer'); try { require('fs').unlinkSync(socketPath); } catch (err) { //ignore if file doesn't exists if (err.code !== 'ENOENT') { throw err; } } function answerWithError(res, err) { res.writeHead(500, { 'Content-Type': 'text/plain; charset=utf-8', 'Content-Length': err.stack.length + 1 }); res.end(err.stack + '\n'); } fcgiFramework.createServer(function echo(req, res) { var requestData; req.on('data', function (data) { requestData = requestData + data; }); req.on('end', function writeReqAsJson() { var echoData, size; try { var strippedRequest = require('lodash').omit(req, 'client', 'connection', 'buffer', 'socket', '_events', '_readableState', 'data'); strippedRequest.cgiParams = req.socket.params; strippedRequest.data = requestData; echoData = JSON.stringify(strippedRequest, null, 4); //hopefully only here will an error be thrown size = Buffer.byteLength(echoData, 'utf8'); res.writeHead(200, { 'Content-Type': 'application/json; charset=utf-8', 'Content-Length': size }); res.end(echoData); } catch (err) { answerWithError(res, err); } }); req.on('error', answerWithError.bind(undefined, res)); }).listen(socketPath, function cgiStarted(err) { console.log('cgi app listen on socket: ' + socketPath); if (err) { throw err; } else { var http = require('http'); var fcgiHandler = require('fcgi-handler'); var server = http.createServer(function (req, res) { fcgiHandler.connect({ path: socketPath }, function (err, fcgiProcess) { if (err) { throw err; } else { //route all request to fcgi application fcgiProcess.handle(req, res, { /*empty Options*/ }); } }); }); server.listen(port, function() { console.log('http server listening on port: ' + port); }); } }); node-fastcgi-1.3.3/index.js000066400000000000000000000050561323707300300155320ustar00rootroot00000000000000/** * Copyright (c) 2016 Fabio Massaioli and other contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of * the Software, and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ 'use strict'; var fs = require('fs'), http = require('http'); var server = require('./lib/server.js'), response = require('./lib/response.js'); exports.Server = server.Server; // NOTE: http module compatibility exports.IncomingMessage = http.IncomingMessage; exports.OutgoingMessage = http.OutgoingMessage; exports.ServerResponse = response.ServerResponse; exports.AuthorizerResponse = response.AuthorizerResponse; /** * function createServer([responder], [authorizer], [filter], [config]) * Creates and returns a FastCGI server object. Compatible with http.createServer * * Arguments: * - responder (optional): callback for FastCGI responder requests (normal HTTP requests, 'request' event) * - authorizer (optional): callback for FastCGI authorizer requests ('authorize' event) * - filter (optional): callback for FastCGI filter requests ('filter' event) * - config (optional): server configuration (default: { maxConns: 2000, maxReqs: 2000, multiplex: true, valueMap: {} }) */ exports.createServer = function (responder, authorizer, filter, config) { return new server.Server(responder, authorizer, filter, config); }; if (process.platform === "win32") { exports.isService = function () { return false; // On windows we need to call GetStdHandle(-10) // from kernel32.dll } } else { exports.isService = function () { return fs.fstatSync(process.stdin.fd).isSocket(); } } node-fastcgi-1.3.3/lib/000077500000000000000000000000001323707300300146255ustar00rootroot00000000000000node-fastcgi-1.3.3/lib/request.js000066400000000000000000000165261323707300300166650ustar00rootroot00000000000000/** * Copyright (c) 2016 Fabio Massaioli and other contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of * the Software, and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ 'use strict'; var fcgi = require('fastcgi-stream'), http = require('http'), util = require('util'), streams = require('./streams.js'), response = require('./response.js'); var InputStream = streams.InputStream, OutputStream = streams.OutputStream, IOStream = streams.IOStream; var Response = response.Response, AuthorizerResponse = response.AuthorizerResponse; exports.Request = Request; /** * function Request(conn, id, role, keepalive) * Represents a FastCGI request. Emulates net.Socket API. */ function Request(conn, id, role, keepalive) { IOStream.call(this, conn, id); this._role = role; this._keepAlive = keepalive; this._stdinComplete = false; this._dataComplete = false; this._req = null; this._res = null; this.params = {}; this.dataStream = new InputStream(); // NOTE: data stream for filter requests this.errorStream = new OutputStream(conn, id, fcgi.records.StdErr); this.on('drain', function () { if (this._res) { this._res.emit('drain'); } }); this.once('finish', function () { if (this._res) { this._res.detachSocket(this); this._res = null; } this.destroy(); }); this.on('close', this.errorStream._close.bind(this.errorStream)); } util.inherits(Request, IOStream); Request.prototype._param = function (name, value) { this.params[name] = value; }; var HEADER_EXPR = /^HTTP_/; var UNDERSCORE_EXPR = /_/g; function makeUrl(params) { if (params.REQUEST_URI && params.REQUEST_URI.length) { return params.REQUEST_URI; } else { var url = ''; if (params.SCRIPT_NAME) { url += params.SCRIPT_NAME; } if (params.PATH_INFO) { url += params.PATH_INFO; } if (params.QUERY_STRING) { url += '?' + params.QUERY_STRING; } return url; } } Request.prototype._createReqRes = function () { this._req = new http.IncomingMessage(this); if (this.params.SERVER_PROTOCOL) { this._req.httpVersion = this.params.SERVER_PROTOCOL.slice(5); var numbers = this._req.httpVersion.split('.'); this._req.httpVersionMajor = parseInt(numbers[0]); this._req.httpVersionMinor = parseInt(numbers[1]); } this._req.url = makeUrl(this.params); var raw = this._req.rawHeaders, dest = this._req.headers; for (var param in this.params) { if (HEADER_EXPR.test(param) || param === 'CONTENT_LENGTH' || param === 'CONTENT_TYPE') { var name = param.replace(HEADER_EXPR, '').replace(UNDERSCORE_EXPR, '-'); // Ignore HTTP_CONTENT_TYPE and HTTP_CONTENT_LENGTH if (HEADER_EXPR.test(param) && (name.toLowerCase() === 'content-type' || name.toLowerCase() === 'content-length')) continue; var value = this.params[param]; raw.push(name, value); this._req._addHeaderLine(name, value, dest); } } this._req.method = this.params.REQUEST_METHOD || 'GET'; this._req.complete = this._stdinComplete && this._dataComplete; this.on('data', function (data) { if (this._req) { if (!this._req.push(data)) { this.pause(); } } }); this.on('end', function () { if (this._req) { this._req.push(null); } }); this.pause(); if (this._role === fcgi.records.BeginRequest.roles.AUTHORIZER) { this._res = new AuthorizerResponse(this._req); } else { this._res = new Response(this._req); } this._res.shouldKeepAlive = this.params.HTTP_CONNECTION === 'keep-alive'; this._res.assignSocket(this); var self = this; this._res.on('finish', function () { self.end(); }); // NOTE: Backward compatibility this._req.data = this.dataStream; this._req.cgiParams = this.params; this._res.stdout = this; this._res.stderr = this.errorStream; if (this._req.complete) { process.nextTick(this._req.emit.bind(this._req, 'complete')); } return { req: this._req, res: this._res }; } Request.prototype._abort = function (err) { if (this._req) { this._req.emit('aborted') } this.destroy(err); }; // net.Socket API emulation Object.defineProperties(Request.prototype, { "bufferSize": { get: function () { return this._conn.bufferSize; } }, "bytesRead": { get: function () { return this._conn.bytesRead; } }, "bytesWritten": { get: function () { return this._conn.bytesWritten } }, "localAddress": { get: function () { return this.params.SERVER_ADDR || '::'; } }, "localPort": { get: function () { return parseInt(this.params.SERVER_PORT) || 0; } }, "remoteAddress": { get: function () { return this.params.REMOTE_ADDR || '::'; } }, "remoteFamily": { get: function() { return this.remoteAddress.indexOf('.') !== -1 ? 'IPv4' : 'IPv6'; } }, "remotePort": { get: function () { return parseInt(this.params.REMOTE_PORT) || 0; } }, "destroyed": { get: function () { return !this._open; } } }); Request.prototype.address = function () { return { address: this.localAddress, family: this.localAddress.indexOf('.') !== -1 ? 'IPv4' : 'IPv6', port: this.localPort }; }; Request.prototype.destroy = function (err) { if (this._open) { this._close(err ? true : false); this._conn.endRequest(this._id, err ? 1 : 0); } } Request.prototype.ref = function () { return this._conn.ref(); } Request.prototype.unref = function () { return this._conn.unref(); } Request.prototype.setKeepAlive = function () { return this._conn.setKeepAlive.apply(this._conn, arguments); } Request.prototype.setNoDelay = function () { return this._conn.setNoDelay.apply(this._conn, arguments); } Request.prototype.setTimeout = function (msecs, callback) { if (callback) this.once('timeout', callback); return this._conn.setTimeout(msecs); }; node-fastcgi-1.3.3/lib/response.js000066400000000000000000000060551323707300300170270ustar00rootroot00000000000000/** * Copyright (c) 2016 Fabio Massaioli and other contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of * the Software, and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ 'use strict'; var http = require('http'), util = require('util'); exports.Response = Response; exports.AuthorizerResponse = AuthorizerResponse; /** * function Response(req) * FastCGI response. Inherits http.ServerResponse */ function Response(req) { if (!(this instanceof Response)) { return new Response(req); } this._storeHeader = function (statusLine, headers) { if (!this.getHeader('transfer-encoding')) { // This is required to prevent nodejs using chunked-encoding // when no content-length header is present this.removeHeader('transfer-encoding'); } return http.ServerResponse.prototype._storeHeader.call( this, statusLine.replace('HTTP/1.1', 'Status:'), headers); }; this.writeContinue = function (cb) { this._writeRaw('Status: 100 Continue' + CRLF + CRLF, 'ascii', cb); this._sent100 = true; }; http.ServerResponse.call(this, req); } util.inherits(Response, http.ServerResponse); /** * function AuthorizerResponse(req) * FastCGI authorizer response. Inherits Response * This object has three special methods: * - function setVariable(name, value): translates to setHeader('Variable-' + name, value) * - function allow(): calls end() with status code 200 and no body * - function deny(): calls end() with status code 403 and no body */ function AuthorizerResponse(req) { if (!(this instanceof AuthorizerResponse)) { return new AuthorizerResponse(req); } Response.call(this, req); this.setHeader('Content-type', 'text/plain'); } util.inherits(AuthorizerResponse, Response); AuthorizerResponse.prototype.setVariable = function (name, value) { this.setHeader('Variable-' + name, value); }; AuthorizerResponse.prototype.allow = function () { this.statusCode = 200; this.end(); }; AuthorizerResponse.prototype.deny = function () { this.statusCode = 403; this.end(); }; node-fastcgi-1.3.3/lib/server.js000066400000000000000000000256571323707300300165100ustar00rootroot00000000000000/** * Copyright (c) 2016 Fabio Massaioli and other contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of * the Software, and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ 'use strict'; var net = require('net'), util = require('util'), fcgi = require('fastcgi-stream'), Request = require('./request.js').Request; exports.Server = Server; var VALUE_MAP = { 'FCGI_MAX_CONNS': 'maxConns', 'FCGI_MAX_REQS': 'maxReqs', 'FCGI_MPXS_CONNS': 'multiplex' }; function isFunction(obj) { return typeof obj === 'function'; } /** * function Server([responder], [authorizer], [filter], [config]) * FastCGI server object. Compatible with http.Server * * Arguments: * - responder (optional): callback for FastCGI responder requests (normal HTTP requests, 'request' event) * - authorizer (optional): callback for FastCGI authorizer requests ('authorize' event) * - filter (optional): callback for FastCGI filter requests ('filter' event) * - config (optional): server configuration (default: { maxConns: 2000, maxReqs: 2000, multiplex: true, valueMap: {} }) */ function Server(responder, authorizer, filter, config) { if (!(this instanceof Server)) { return new Server(responder, authorizer, filter, config); } net.Server.call(this, { allowHalfOpen: false }); config = config || (isFunction(filter) ? {} : filter || (isFunction(authorizer) ? {} : authorizer || (isFunction(responder) ? {} : responder || {}))); config.maxConns = parseInt(config.maxConns) || 2000; config.maxReqs = parseInt(config.maxReqs) || 2000; if (config.multiplex === undefined) { config.multiplex = true; } else { config.multiplex = config.multiplex ? true : false; } config.valueMap = config.valueMap || {}; for (var v in VALUE_MAP) { config.valueMap[v] = VALUE_MAP[v]; } this.config = config; this.maxHeadersCount = 0; this.timeout = 2 * 60 * 1000; if (isFunction(responder)) { this.on('request', responder); } if (isFunction(authorizer)) { this.on('authorize', authorizer); } if (isFunction(filter)) { this.on('filter', filter); } this.on('connection', connectionListener); } util.inherits(Server, net.Server); /** * server.listen = function([options...], [callback]) * Starts listening on default FastCGI socket. * Forwards to net.Server.listen if called with options. * * Arguments: * - options (optional): net.Server.listen options * - callback (optional): this parameter will be added as a listener * for the 'listening' event. */ Server.prototype.listen = function (callback) { if (arguments.length > 0 && !isFunction(callback)) { return net.Server.prototype.listen.apply(this, arguments); } return net.Server.prototype.listen.call(this, process.stdin, callback); }; Server.prototype.setTimeout = function (msecs, callback) { this.timeout = msecs; if (callback) { this.on('timeout', callback); } }; function connectionListener(socket) { var stream = new fcgi.FastCGIStream(socket), requests = {}; function endRequest(id, status, reason) { if (reason === undefined) { reason = fcgi.records.EndRequest.protocolStatus.REQUEST_COMPLETE; } if (socket.writable && !socket.destroyed) { stream.writeRecord( id, new fcgi.records.EndRequest(status, reason)); if (id in requests && !requests[id]._keepAlive) { socket.end(); } } delete requests[id]; } function abortAll(hadError) { for (var id in requests) { requests[id]._abort(hadError); } } socket.stream = stream; socket.endRequest = endRequest; var self = this; if (this.timeout) { socket.setTimeout(this.timeout); } socket.on('timeout', function () { var reqSocketTimeout = false, reqTimeout = false, resTimeout = false, serverTimeout = false; for (var id in requests) { var request = requests[id]; reqSocketTimeout = reqSocketTimeout || request.emit('timeout', socket); reqTimeout = reqTimeout || (request._req && request._req.emit('timeout', request)); resTimeout = resTimeout || (request._res && request._res.emit('timeout', request)); } serverTimeout = self.emit('timeout', socket); if (!reqSocketTimeout && !reqTimeout && !resTimeout && !serverTimeout) { socket.destroy(); } }); socket.once('error', function (err) { this.on('error', function () {}) if (!self.emit('clientError', err, this)) { this.destroy(err); } }); socket.on('close', abortAll); stream.on('record', function (id, record) { if (record.TYPE == fcgi.records.GetValues.TYPE) { var result = []; record.values.forEach(function (v) { if (v === 'FCGI_MPXS_CONNS') { result.push([v, self.config.multiplex ? "1" : "0"]); } else if (v in self.config.valueMap) { result.push([v, self.config[self.config.valueMap[v]].toString()]); } }); stream.writeRecord(id, new fcgi.records.GetValuesResult(result)); } else if (record.TYPE == fcgi.records.BeginRequest.TYPE) { if (id in requests) { // Request id already in use self.emit('protocolError', new Error("Request id " + id + " already in use")); return; } if (!self.config.multiplex && requests.length > 0) { endRequest(id, 1, fcgi.records.EndRequest.protocolStatus.CANT_MPX_CONN); return; } var keepAlive = record.flags & fcgi.records.BeginRequest.flags.KEEP_CONN; switch (record.role) { case fcgi.records.BeginRequest.roles.RESPONDER: if (self.listeners('request').length < 1) { endRequest(id, 1, fcgi.records.EndRequest.protocolStatus.UNKNOWN_ROLE); if (!keepAlive) { socket.end(); } return; } break; case fcgi.records.BeginRequest.roles.AUTHORIZER: if (self.listeners('authorize').length < 1) { endRequest(id, 1, fcgi.records.EndRequest.protocolStatus.UNKNOWN_ROLE); if (!keepAlive) { socket.end(); } return; } break; case fcgi.records.BeginRequest.roles.FILTER: if (self.listeners('filter').length < 1) { endRequest(id, 1, fcgi.records.EndRequest.protocolStatus.UNKNOWN_ROLE); if (!keepAlive) { socket.end(); } return; } break; default: endRequest(id, 1, fcgi.records.EndRequest.protocolStatus.UNKNOWN_ROLE); if (!keepAlive) { socket.end(); } return; } requests[id] = new Request(socket, id, record.role, keepAlive); } else { if (!(id in requests)) { // Invalid request id, ignore record self.emit('protocolError', new Error("Request id " + id + " is invalid, ignoring record")); return; } return recordHandler.call(self, socket, requests[id], record); } }); } function recordHandler(conn, req, record) { switch (record.TYPE) { case fcgi.records.AbortRequest.TYPE: req._abort(); return; case fcgi.records.Params.TYPE: record.params.forEach(function (p) { p.length !== p.toString().length ? req._param(p[0], p[1]) : req._param(p.toString(), ""); }); if (record.params.length === 0) { switch (req._role) { case fcgi.records.BeginRequest.roles.RESPONDER: req.dataStream._data(null); req._dataComplete = true; var reqRes = req._createReqRes(); this.emit('request', reqRes.req, reqRes.res); break; case fcgi.records.BeginRequest.roles.AUTHORIZER: req.dataStream._data(null); req._dataComplete = true; var reqRes = req._createReqRes(); this.emit('authorize', reqRes.req, reqRes.res); break; case fcgi.records.BeginRequest.roles.FILTER: var reqRes = req._createReqRes(); this.emit('filter', reqRes.req, reqRes.res); break; } } return; case fcgi.records.StdIn.TYPE: if (req._stdinComplete) { return; } if (record.data.length > 0) { req._data(record.data); } else { req._data(null); req._stdinComplete = true; if (req._req) { req._req.complete = req._stdinComplete && req._dataComplete; // NOTE: Backward compatibility if (req._req.complete) { req._req.emit('complete'); } } } return; case fcgi.records.Data.TYPE: if (req._dataComplete) { return; } if (record.data.length > 0) { req.dataStream._data(record.data); } else { req.dataStream._data(null); req._dataComplete = true; if (req._req) { req._req.complete = req._stdinComplete && req._dataComplete; // NOTE: Backward compatibility if (req._req.complete) { req._req.emit('complete'); } } } return; } } node-fastcgi-1.3.3/lib/streams.js000066400000000000000000000112351323707300300166430ustar00rootroot00000000000000/** * Copyright (c) 2016 Fabio Massaioli and other contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of * the Software, and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ 'use strict'; var stream = require('stream'), util = require('util'), fcgi = require('fastcgi-stream'); exports.InputStream = InputStream; exports.OutputStream = OutputStream; exports.IOStream = IOStream; /** * function InputStream([buffer]) * Readable stream interface for FastCGI input streams */ function InputStream() { stream.Readable.call(this); this._buffer = []; this._canPush = true; } util.inherits(InputStream, stream.Readable); InputStream.prototype._data = function (chunk) { if (this._canPush) { this._canPush = this.push(chunk); } else { this._buffer.push(chunk); } }; InputStream.prototype._read = function (size) { while (this._buffer.length && (this._canPush = this.push(this._buffer.shift()))); }; /** * function OutputStream(conn, type) * Writable stream interface for FastCGI output streams */ function OutputStream(conn, id, recordType) { stream.Writable.call(this); this.recordType = recordType || fcgi.records.StdOut; this._conn = conn; this._id = id; this._open = true; this.on('finish', function () { this._conn.stream.writeRecord( this._id, new this.recordType()); }); } util.inherits(OutputStream, stream.Writable); OutputStream.prototype._close = function (hadError) { if (this._open) { this._open = false; this.emit('close', hadError ? true : false); } }; OutputStream.prototype._write = function (chunk, encoding, callback) { var chunks = []; if (!Buffer.isBuffer(chunk)) { chunk = new Buffer(chunk, encoding); } if (chunk.length === 0) { callback.call(this); return; } if (chunk.length <= 65535) { chunks.push(chunk); } else { var splits = Math.floor(chunk.length / 65535); var start = 0; for (var i = 0; i < splits; ++i) { chunks.push(chunk.slice(start, start += 65535)); } chunks.push(chunk.slice(start, chunk.length)); } while (chunks.length > 1) { this._conn.stream.writeRecord( this._id, new this.recordType(chunks.shift())); } this._conn.stream.writeRecord( this._id, new this.recordType(chunks.shift()), callback.bind(this)); }; OutputStream.prototype.write = function () { if (!this._open) { this.emit('error', new Error("Output stream is not open")); return; } return stream.Writable.prototype.write.apply(this, arguments); } OutputStream.prototype.end = function () { if (!this._open) { this.emit('error', new Error("Output stream is not open")); return; } return stream.Writable.prototype.end.apply(this, arguments); } /** * function IOStream([buffer]) * Duplex stream interface for FastCGI input streams */ function IOStream(conn, id, recordType) { stream.Duplex.call(this); this.recordType = recordType || fcgi.records.StdOut; this._buffer = []; this._canPush = true; this._conn = conn; this._id = id; this._open = true; this.on('finish', function () { this._conn.stream.writeRecord( this._id, new this.recordType()); }); } util.inherits(IOStream, stream.Duplex); IOStream.prototype._data = InputStream.prototype._data; IOStream.prototype._read = InputStream.prototype._read; IOStream.prototype._close = OutputStream.prototype._close; IOStream.prototype._write = OutputStream.prototype._write; IOStream.prototype.write = OutputStream.prototype.write; IOStream.prototype.end = OutputStream.prototype.end; node-fastcgi-1.3.3/package.json000066400000000000000000000024731323707300300163530ustar00rootroot00000000000000{ "name": "node-fastcgi", "version": "1.3.3", "description": "Create FastCGI applications in node. Near drop-in replacement for node's http module.", "keywords": [ "fcgi", "fastcgi", "server" ], "homepage": "https://github.com/fbbdev/node-fastcgi", "author": { "name": "Fabio Massaioli", "email": "fabio.massaioli@gmail.com" }, "license": "MIT", "main": "./index.js", "engines": { "node": ">= 0.12" }, "dependencies": { "fastcgi-stream": "^1.0.0" }, "repository": { "type": "git", "url": "https://github.com/fbbdev/node-fastcgi.git" }, "devDependencies": { "chai": "^4.1.2", "coveralls": "^3.0.0", "fcgi-handler": "git+https://github.com/aredridel/fcgi-handler.git#afe16eae560280d5dd84241d0c45e5db0f939d25", "istanbul": "^0.4.3", "lodash": "^4.9.0", "mocha": "^5.0.0", "mocha-lcov-reporter": "^1.2.0", "request": "^2.70.0" }, "scripts": { "test": "./node_modules/.bin/mocha --exit ./test/mocha/integration", "coveralls": "./node_modules/.bin/istanbul cover --report lcovonly ./node_modules/mocha/bin/_mocha -- --exit ./test/mocha/integration && cat ./coverage/lcov.info | ./node_modules/.bin/coveralls" } } node-fastcgi-1.3.3/test/000077500000000000000000000000001323707300300150365ustar00rootroot00000000000000node-fastcgi-1.3.3/test/mocha/000077500000000000000000000000001323707300300161255ustar00rootroot00000000000000node-fastcgi-1.3.3/test/mocha/integration/000077500000000000000000000000001323707300300204505ustar00rootroot00000000000000node-fastcgi-1.3.3/test/mocha/integration/echo.js000066400000000000000000000213421323707300300217260ustar00rootroot00000000000000/** * Copyright (c) 2016 Fabio Massaioli, Robert Groh and other contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the 'Software'), to deal in * the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of * the Software, and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ 'use strict'; /*global describe, it, before, after */ /*jshint node: true */ /*jshint expr: true*/ var expect = require('chai').expect, request = require('request'), path = require('path'); var fcgiFramework = require('../../../index.js'); //this we want to test function randomInt(low, high) { return Math.floor(Math.random() * (high - low + 1) + low); } describe('echo Server', function setup() { var port = 0, //will choose a random (and hopefully free) port socketPath = path.join(__dirname, 'echoServer_Socket' + randomInt(1000, 2000)); before(function startFastCgiApplication(done) { function answerWithError(res, err) { res.writeHead(500, { 'Content-Type': 'text/plain; charset=utf-8', 'Content-Length': err.stack.length + 1 }); res.end(err.stack + '\n'); } fcgiFramework.createServer(function echo(req, res) { var requestData; req.on('data', function (data) { if (requestData === undefined) { requestData = data.toString(); } else { requestData = requestData + data.toString(); } }); req.on('end', function writeReqAsJson() { var echoData, size, strippedRequest = require('lodash').omit(req, 'client', 'connection', 'buffer', 'socket', '_events', '_readableState', 'data'); strippedRequest.cgiParams = req.socket.params; strippedRequest.data = requestData; try { echoData = JSON.stringify(strippedRequest, null, 4); //hopefully only here will an error be thrown size = Buffer.byteLength(echoData, 'utf8'); res.writeHead(200, { 'Content-Type': 'application/json; charset=utf-8', 'Content-Length': size }); res.end(echoData); } catch (err) { answerWithError(res, err); } }); req.on('error', answerWithError.bind(undefined, res)); }).listen(socketPath, function cgiStarted(err) { if (err) { done(err); } else { console.log('cgi app listen on socket:' + socketPath); var http = require('http'); var fcgiHandler = require('fcgi-handler'); var server = http.createServer(function (req, res) { fcgiHandler.connect({ path: socketPath }, function (err, fcgiProcess) { if (err) { answerWithError(res, err); } else { //route all request to fcgi application fcgiProcess.handle(req, res, { /*empty Options*/ }); } }); }); server.listen(port, function httpServerStarted(err) { port = server.address().port; done(err); }); } }); }); it('should answer with the request', function checkResponse(done) { request({ uri: 'http://localhost:' + port, method: 'GET' }, function (err, res, body) { expect(res.statusCode).to.be.equal(200); expect(res.headers['content-type']).to.be.equal('application/json; charset=utf-8'); var echo = JSON.parse(body); expect(echo).to.have.nested.property('cgiParams.PATH_INFO', '/'); expect(echo).to.have.nested.property('cgiParams.SERVER_PROTOCOL', 'HTTP/1.1'); expect(echo).to.have.nested.property('cgiParams.SERVER_SOFTWARE', 'Node/' + process.version); expect(echo).to.have.nested.property('cgiParams.REQUEST_METHOD', this.method); expect(echo).to.have.nested.property('cgiParams.QUERY_STRING', ''); expect(echo).to.have.nested.property('cgiParams.HTTP_HOST', 'localhost:' + port); done(err); }); }); it('should answer with the request data', function checkResponse(done) { var requestPath = '/push/somthing/here'; request({ baseUrl: 'http://localhost:' + port, url: requestPath, method: 'POST', body: 'Some data.' }, function (err, res, body) { expect(res.statusCode).to.be.equal(200); expect(res.headers['content-type']).to.be.equal('application/json; charset=utf-8'); var echo = JSON.parse(body); expect(echo).to.have.nested.property('cgiParams.PATH_INFO', requestPath); expect(echo).to.have.nested.property('cgiParams.REQUEST_METHOD', this.method); expect(echo).to.have.nested.property('data', this.body.toString()); done(err); }); }); it('should answer with the request querystring', function checkResponse(done) { var requestPath = '/query/something'; request({ baseUrl: 'http://localhost:' + port, url: requestPath, method: 'GET', qs: { a: 'b', ca: 'd' } }, function (err, res, body) { expect(res.statusCode).to.be.equal(200); expect(res.headers['content-type']).to.be.equal('application/json; charset=utf-8'); var echo = JSON.parse(body); expect(echo).to.have.nested.property('cgiParams.PATH_INFO', requestPath); expect(echo).to.have.nested.property('url', requestPath + '?a=b&ca=d'); done(err); }); }); it('should answer with the request auth', function checkResponse(done) { request({ uri: 'http://localhost:' + port, method: 'GET', auth: { user: 'ArthurDent', pass: 'I think I\'m a sofa...' } }, function (err, res, body) { expect(res.statusCode).to.be.equal(200); expect(res.headers['content-type']).to.be.equal('application/json; charset=utf-8'); var echo = JSON.parse(body); expect(echo).to.have.nested.property('headers.authorization', 'Basic QXJ0aHVyRGVudDpJIHRoaW5rIEknbSBhIHNvZmEuLi4='); done(err); }); }); it('should answer with correct request header names', function checkResponse(done) { var hdr1 = 'test1', hdr2 = 'test2', cl = '23', ct = 'text/plain'; request({ uri: 'http://localhost:' + port, method: 'GET', headers: { 'x_testhdr': hdr1, // XXX: Using underscores because fcgi-handler 'x_test_hdr': hdr2, // passes hyphens in CGI params 'content-length': cl, 'content-type': 'text/plain' } }, function (err, res, body) { expect(res.statusCode).to.be.equal(200); expect(res.headers['content-type']).to.be.equal('application/json; charset=utf-8'); var echo = JSON.parse(body); expect(echo).to.have.nested.property('headers.x-testhdr', hdr1); expect(echo).to.have.nested.property('headers.x-test-hdr', hdr2); expect(echo).to.have.nested.property('headers.content-length', cl); expect(echo).to.have.nested.property('headers.content-type', ct); done(err); }); }); after(function removeSocketPath(done) { require('fs').unlink(socketPath, done); }); }); node-fastcgi-1.3.3/test/mocha/integration/multiwrite.js000066400000000000000000000101311323707300300232070ustar00rootroot00000000000000/** * Copyright (c) 2016 Fabio Massaioli, Robert Groh and other contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the 'Software'), to deal in * the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of * the Software, and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ 'use strict'; /*global describe, it, before, after */ /*jshint node: true */ /*jshint expr: true*/ var expect = require('chai').expect, request = require('request'), path = require('path'); var fcgiFramework = require('../../../index.js'); //this we want to test function randomInt(low, high) { return Math.floor(Math.random() * (high - low + 1) + low); } describe('multiwrite Server', function setup() { var port = 0, //will choose a random (and hopefully free) port socketPath = path.join(__dirname, 'multiwriteServer_Socket' + randomInt(1000, 2000)); before(function startFastCgiApplication(done) { function answerWithError(res, err) { res.writeHead(500, { 'Content-Type': 'text/plain; charset=utf-8', 'Content-Length': err.stack.length + 1 }); res.end(err.stack + '\n'); } fcgiFramework.createServer(function multiwrite(req, res) { req.resume(); req.on('end', function () { try { res.writeHead(200, { 'Content-Type': 'text/plain; charset=utf-8', 'Content-Length': 3 }); res.write("a"); res.write("b"); res.end("c"); } catch (err) { answerWithError(res, err); } }); req.on('error', answerWithError.bind(undefined, res)); }).listen(socketPath, function cgiStarted(err) { if (err) { done(err); } else { console.log('cgi app listen on socket:' + socketPath); var http = require('http'); var fcgiHandler = require('fcgi-handler'); var server = http.createServer(function (req, res) { fcgiHandler.connect({ path: socketPath }, function (err, fcgiProcess) { if (err) { answerWithError(res, err); } else { //route all request to fcgi application fcgiProcess.handle(req, res, { /*empty Options*/ }); } }); }); server.listen(port, function httpServerStarted(err) { port = server.address().port; done(err); }); } }); }); it('should answer with the expected response', function checkResponse(done) { request({ uri: 'http://localhost:' + port, method: 'GET' }, function (err, res, body) { expect(res.statusCode).to.be.equal(200); expect(body).to.be.equal("abc"); done(err); }); }); after(function removeSocketPath(done) { require('fs').unlink(socketPath, done); }); }); node-fastcgi-1.3.3/test/mocha/integration/multiwrite_no_content_length.js000066400000000000000000000101001323707300300267720ustar00rootroot00000000000000/** * Copyright (c) 2016 Fabio Massaioli, Robert Groh and other contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the 'Software'), to deal in * the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of * the Software, and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ 'use strict'; /*global describe, it, before, after */ /*jshint node: true */ /*jshint expr: true*/ var expect = require('chai').expect, request = require('request'), path = require('path'); var fcgiFramework = require('../../../index.js'); //this we want to test function randomInt(low, high) { return Math.floor(Math.random() * (high - low + 1) + low); } describe('multiwrite Server (no content-length)', function setup() { var port = 0, //will choose a random (and hopefully free) port socketPath = path.join(__dirname, 'multiwriteServer_Socket' + randomInt(1000, 2000)); before(function startFastCgiApplication(done) { function answerWithError(res, err) { res.writeHead(500, { 'Content-Type': 'text/plain; charset=utf-8', 'Content-Length': err.stack.length + 1 }); res.end(err.stack + '\n'); } fcgiFramework.createServer(function multiwrite(req, res) { req.resume(); req.on('end', function () { try { res.writeHead(200, { 'Content-Type': 'text/plain; charset=utf-8' }); res.write("a"); res.write("b"); res.end("c"); } catch (err) { answerWithError(res, err); } }); req.on('error', answerWithError.bind(undefined, res)); }).listen(socketPath, function cgiStarted(err) { if (err) { done(err); } else { console.log('cgi app listen on socket:' + socketPath); var http = require('http'); var fcgiHandler = require('fcgi-handler'); var server = http.createServer(function (req, res) { fcgiHandler.connect({ path: socketPath }, function (err, fcgiProcess) { if (err) { answerWithError(res, err); } else { //route all request to fcgi application fcgiProcess.handle(req, res, { /*empty Options*/ }); } }); }); server.listen(port, function httpServerStarted(err) { port = server.address().port; done(err); }); } }); }); it('should answer with the expected response', function checkResponse(done) { request({ uri: 'http://localhost:' + port, method: 'GET' }, function (err, res, body) { expect(res.statusCode).to.be.equal(200); expect(body).to.be.equal("abc"); done(err); }); }); after(function removeSocketPath(done) { require('fs').unlink(socketPath, done); }); });