-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
108 lines (93 loc) · 3.08 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
var http = require('http');
var https = require('https');
var through = require('through');
var parseArgs = require('./lib/parse_args.js');
var insert = require('./lib/insert');
var nextTick = typeof setImmediate !== 'undefined'
? setImmediate
: process.nextTick
;
module.exports = function (opts, cb) {
if (typeof opts === 'function') {
cb = opts;
opts = {};
}
if (!opts) opts = {};
if (typeof opts === 'object' && opts.listen) opts = { server: opts };
var ssl = Boolean(opts.key || opts.pfx);
var connectionEvent = ssl ? 'secureConnection' : 'connection';
var server = opts.server || (ssl
? https.createServer(opts)
: http.createServer()
);
server.on(connectionEvent, function (stream) {
var src = stream._bouncyStream = stealthBuffer();
// hack to work around a node 0.10 bug:
// https://github.com/joyent/node/commit/e11668b244ee62d9997d4871f368075b8abf8d45
if (/^v0\.10\.\d+$/.test(process.version)) {
var ondata = stream.ondata;
var onend = stream.onend;
stream.ondata = function (buf, i, j) {
var res = ondata(buf, i, j);
src.write(buf.slice(i, j));
return res;
};
stream.onend = function () {
var res = onend();
src.end();
return res;
};
}
else stream.pipe(src);
});
server.on('upgrade', onrequest);
server.on('request', onrequest);
return server;
function onrequest (req, res) {
var src = req.connection._bouncyStream;
if (src._handled) return;
src._handled = true;
var bounce = function (dst) {
var args = {};
if (!dst || typeof dst.pipe !== 'function') {
args = parseArgs(arguments);
dst = args.stream;
}
if (!dst) dst = through();
function destroy () {
src.destroy();
dst.destroy();
}
src.on('error', destroy);
dst.on('error', destroy);
var s = args.headers || args.method || args.path
? src.pipe(insert(args))
: src
;
s.pipe(dst).pipe(req.connection);
nextTick(function () { src._resume() });
return dst;
};
if (cb.length === 2) cb(req, bounce)
else cb(req, res, bounce)
}
};
function stealthBuffer () {
// the raw_ok test doesn't pass without this shim
// instead of just using through() and then immediately calling .pause()
var tr = through(write, end);
var buffer = [];
tr._resume = function () {
buffer.forEach(tr.queue.bind(tr));
buffer = undefined;
};
return tr;
function write (buf) {
if (buffer) buffer.push(buf)
else this.queue(buf)
}
function end () {
if (buffer) buffer.push(null)
else this.queue(null)
}
}