lib/deceiver.js000066400000015102151140372230007435 0ustar00var assert = require('assert'); var util = require('util'); var Buffer = require('buffer').Buffer; // Node.js version var mode = /^v0\.8\./.test(process.version) ? 'rusty' : /^v0\.(9|10)\./.test(process.version) ? 'old' : /^v0\.12\./.test(process.version) ? 'normal' : 'modern'; var HTTPParser; var methods; var reverseMethods; var kOnHeaders; var kOnHeadersComplete; var kOnMessageComplete; var kOnBody; if (mode === 'normal' || mode === 'modern') { HTTPParser = process.binding('http_parser').HTTPParser; methods = HTTPParser.methods; // v6 if (!methods) methods = process.binding('http_parser').methods; reverseMethods = {}; methods.forEach(function(method, index) { reverseMethods[method] = index; }); kOnHeaders = HTTPParser.kOnHeaders | 0; kOnHeadersComplete = HTTPParser.kOnHeadersComplete | 0; kOnMessageComplete = HTTPParser.kOnMessageComplete | 0; kOnBody = HTTPParser.kOnBody | 0; } else { kOnHeaders = 'onHeaders'; kOnHeadersComplete = 'onHeadersComplete'; kOnMessageComplete = 'onMessageComplete'; kOnBody = 'onBody'; } function Deceiver(socket, options) { this.socket = socket; this.options = options || {}; this.isClient = this.options.isClient; } module.exports = Deceiver; Deceiver.create = function create(stream, options) { return new Deceiver(stream, options); }; Deceiver.prototype._toHeaderList = function _toHeaderList(object) { var out = []; var keys = Object.keys(object); for (var i = 0; i < keys.length; i++) out.push(keys[i], object[keys[i]]); return out; }; Deceiver.prototype._isUpgrade = function _isUpgrade(request) { return request.method === 'CONNECT' || request.headers.upgrade || request.headers.connection && /(^|\W)upgrade(\W|$)/i.test(request.headers.connection); }; // TODO(indutny): support CONNECT if (mode === 'modern') { /* function parserOnHeadersComplete(versionMajor, versionMinor, headers, method, url, statusCode, statusMessage, upgrade, shouldKeepAlive) { */ Deceiver.prototype.emitRequest = function emitRequest(request) { var parser = this.socket.parser; assert(parser, 'No parser present'); parser.execute = null; var self = this; var method = reverseMethods[request.method]; parser.execute = function execute() { self._skipExecute(this); this[kOnHeadersComplete](1, 1, self._toHeaderList(request.headers), method, request.path, 0, '', self._isUpgrade(request), true); return 0; }; this._emitEmpty(); }; Deceiver.prototype.emitResponse = function emitResponse(response) { var parser = this.socket.parser; assert(parser, 'No parser present'); parser.execute = null; var self = this; parser.execute = function execute() { self._skipExecute(this); this[kOnHeadersComplete](1, 1, self._toHeaderList(response.headers), response.path, response.code, response.status, response.reason || '', self._isUpgrade(response), true); return 0; }; this._emitEmpty(); }; } else { /* `function parserOnHeadersComplete(info) {` info = { .versionMajor, .versionMinor, .url, .headers, .method, .statusCode, .statusMessage, .upgrade, .shouldKeepAlive } */ Deceiver.prototype.emitRequest = function emitRequest(request) { var parser = this.socket.parser; assert(parser, 'No parser present'); var method = request.method; if (reverseMethods) method = reverseMethods[method]; var info = { versionMajor: 1, versionMinor: 1, url: request.path, headers: this._toHeaderList(request.headers), method: method, statusCode: 0, statusMessage: '', upgrade: this._isUpgrade(request), shouldKeepAlive: true }; var self = this; parser.execute = function execute() { self._skipExecute(this); this[kOnHeadersComplete](info); return 0; }; this._emitEmpty(); }; Deceiver.prototype.emitResponse = function emitResponse(response) { var parser = this.socket.parser; assert(parser, 'No parser present'); var info = { versionMajor: 1, versionMinor: 1, url: response.path, headers: this._toHeaderList(response.headers), method: false, statusCode: response.status, statusMessage: response.reason || '', upgrade: this._isUpgrade(response), shouldKeepAlive: true }; var self = this; parser.execute = function execute() { self._skipExecute(this); this[kOnHeadersComplete](info); return 0; }; this._emitEmpty(); }; } Deceiver.prototype._skipExecute = function _skipExecute(parser) { var self = this; var oldExecute = parser.constructor.prototype.execute; var oldFinish = parser.constructor.prototype.finish; parser.execute = null; parser.finish = null; parser.execute = function execute(buffer, start, len) { // Parser reuse if (this.socket !== self.socket) { this.execute = oldExecute; this.finish = oldFinish; return this.execute(buffer, start, len); } if (start !== undefined) buffer = buffer.slice(start, start + len); self.emitBody(buffer); return len; }; parser.finish = function finish() { // Parser reuse if (this.socket !== self.socket) { this.execute = oldExecute; this.finish = oldFinish; return this.finish(); } this.execute = oldExecute; this.finish = oldFinish; self.emitMessageComplete(); }; }; Deceiver.prototype.emitBody = function emitBody(buffer) { var parser = this.socket.parser; assert(parser, 'No parser present'); parser[kOnBody](buffer, 0, buffer.length); }; Deceiver.prototype._emitEmpty = function _emitEmpty() { // Emit data to force out handling of UPGRADE var empty = new Buffer(0); if (this.socket.ondata) this.socket.ondata(empty, 0, 0); else this.socket.emit('data', empty); }; Deceiver.prototype.emitMessageComplete = function emitMessageComplete() { var parser = this.socket.parser; assert(parser, 'No parser present'); parser[kOnMessageComplete](); }; test/api-test.js000066400000011554151140372230007615 0ustar00var assert = require('assert'); var net = require('net'); var http = require('http'); var streamPair = require('stream-pair'); var thing = require('handle-thing'); var httpDeceiver = require('../'); describe('HTTP Deceiver', function() { var handle; var pair; var socket; var deceiver; beforeEach(function() { pair = streamPair.create(); handle = thing.create(pair.other); socket = new net.Socket({ handle: handle }); // For v0.8 socket.readable = true; socket.writable = true; deceiver = httpDeceiver.create(socket); }); it('should emit request', function(done) { var server = http.createServer(); server.emit('connection', socket); server.on('request', function(req, res) { assert.equal(req.method, 'PUT'); assert.equal(req.url, '/hello'); assert.deepEqual(req.headers, { a: 'b' }); done(); }); deceiver.emitRequest({ method: 'PUT', path: '/hello', headers: { a: 'b' } }); }); it('should emit response', function(done) { var agent = new http.Agent(); agent.createConnection = function createConnection() { return socket; }; var client = http.request({ method: 'POST', path: '/ok', agent: agent }, function(res) { assert.equal(res.statusCode, 421); assert.deepEqual(res.headers, { a: 'b' }); done(); }); process.nextTick(function() { deceiver.emitResponse({ status: 421, reason: 'F', headers: { a: 'b' } }); }); }); it('should override .execute and .finish', function(done) { var server = http.createServer(); server.emit('connection', socket); server.on('request', function(req, res) { assert.equal(req.method, 'PUT'); assert.equal(req.url, '/hello'); assert.deepEqual(req.headers, { a: 'b' }); var actual = ''; req.on('data', function(chunk) { actual += chunk; }); req.once('end', function() { assert.equal(actual, 'hello world'); done(); }); }); deceiver.emitRequest({ method: 'PUT', path: '/hello', headers: { a: 'b' } }); pair.write('hello'); pair.end(' world'); }); it('should work with reusing parser', function(done) { var server = http.createServer(); server.emit('connection', socket); function secondRequest() { pair = streamPair.create(); handle = thing.create(pair.other); socket = new net.Socket({ handle: handle }); // For v0.8 socket.readable = true; socket.writable = true; server.emit('connection', socket); pair.end('PUT /second HTTP/1.1\r\nContent-Length:11\r\n\r\nhello world'); } server.on('request', function(req, res) { var actual = ''; req.on('data', function(chunk) { actual += chunk; }); req.once('end', function() { assert.equal(actual, 'hello world'); if (req.url === '/first') secondRequest(); else done(); }); }); deceiver.emitRequest({ method: 'PUT', path: '/first', headers: { a: 'b' } }); pair.write('hello'); pair.end(' world'); }); it('should emit CONNECT request', function(done) { var server = http.createServer(); server.emit('connection', socket); server.on('connect', function(req, socket, bodyHead) { assert.equal(req.method, 'CONNECT'); assert.equal(req.url, '/hello'); done(); }); deceiver.emitRequest({ method: 'CONNECT', path: '/hello', headers: { } }); }); it('should emit Upgrade request', function(done) { var server = http.createServer(); server.emit('connection', socket); server.on('upgrade', function(req, socket, bodyHead) { assert.equal(req.method, 'POST'); assert.equal(req.url, '/hello'); socket.on('data', function(chunk) { assert.equal(chunk + '', 'hm'); done(); }); }); deceiver.emitRequest({ method: 'POST', path: '/hello', headers: { 'upgrade': 'websocket' } }); pair.write('hm'); }); it('should emit Upgrade response', function(done) { var agent = new http.Agent(); agent.createConnection = function createConnection() { return socket; }; var client = http.request({ method: 'POST', path: '/ok', headers: { connection: 'upgrade', upgrade: 'websocket' }, agent: agent }, function(res) { assert(false); }); client.on('upgrade', function(res, socket) { assert.equal(res.statusCode, 421); done(); }); process.nextTick(function() { deceiver.emitResponse({ status: 421, reason: 'F', headers: { upgrade: 'websocket' } }); }); }); }); .npmignore000066400000000034151140372230006540 0ustar00node_modules/ npm-debug.log .travis.yml000066400000000074151140372230006656 0ustar00language: node_js node_js: - "0.10" - "0.12" - "iojs" README.md000066400000002523151140372230006025 0ustar00# HTTP Deceiver [![Build Status](https://secure.travis-ci.org/indutny/http-deceiver.png)](http://travis-ci.org/indutny/http-deceiver) [![NPM version](https://badge.fury.io/js/http-deceiver.svg)](http://badge.fury.io/js/http-deceiver) Deceive! ## LICENSE This software is licensed under the MIT License. Copyright Fedor Indutny, 2015. 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. package.json000066400000002713151140372230007035 0ustar00{ "_args": [ [ "http-deceiver@1.2.7", "/home/freeclou/app.optimyar.com/backend" ] ], "_from": "http-deceiver@1.2.7", "_id": "http-deceiver@1.2.7", "_inBundle": false, "_integrity": "sha1-+nFolEq5pRnTN8sL7HKE3D5yPYc=", "_location": "/http-deceiver", "_phantomChildren": {}, "_requested": { "type": "version", "registry": true, "raw": "http-deceiver@1.2.7", "name": "http-deceiver", "escapedName": "http-deceiver", "rawSpec": "1.2.7", "saveSpec": null, "fetchSpec": "1.2.7" }, "_requiredBy": [ "/spdy" ], "_resolved": "https://registry.npmjs.org/http-deceiver/-/http-deceiver-1.2.7.tgz", "_spec": "1.2.7", "_where": "/home/freeclou/app.optimyar.com/backend", "author": { "name": "Fedor Indutny", "email": "fedor@indutny.com" }, "bugs": { "url": "https://github.com/indutny/http-deceiver/issues" }, "description": "Deceive HTTP parser", "devDependencies": { "handle-thing": "^1.0.1", "mocha": "^2.2.5", "readable-stream": "^2.0.1", "stream-pair": "^1.0.0" }, "homepage": "https://github.com/indutny/http-deceiver#readme", "keywords": [ "http", "net", "deceive" ], "license": "MIT", "main": "lib/deceiver.js", "name": "http-deceiver", "repository": { "type": "git", "url": "git+ssh://git@github.com/indutny/http-deceiver.git" }, "scripts": { "test": "mocha --reporter=spec test/*-test.js" }, "version": "1.2.7" }