index.js
6.68 KB
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
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
'use strict'
var net = require('net')
, tls = require('tls')
, http = require('http')
, https = require('https')
, events = require('events')
, assert = require('assert')
, util = require('util')
;
exports.httpOverHttp = httpOverHttp
exports.httpsOverHttp = httpsOverHttp
exports.httpOverHttps = httpOverHttps
exports.httpsOverHttps = httpsOverHttps
function httpOverHttp(options) {
var agent = new TunnelingAgent(options)
agent.request = http.request
return agent
}
function httpsOverHttp(options) {
var agent = new TunnelingAgent(options)
agent.request = http.request
agent.createSocket = createSecureSocket
agent.defaultPort = 443
return agent
}
function httpOverHttps(options) {
var agent = new TunnelingAgent(options)
agent.request = https.request
return agent
}
function httpsOverHttps(options) {
var agent = new TunnelingAgent(options)
agent.request = https.request
agent.createSocket = createSecureSocket
agent.defaultPort = 443
return agent
}
function TunnelingAgent(options) {
var self = this
self.options = options || {}
self.proxyOptions = self.options.proxy || {}
self.maxSockets = self.options.maxSockets || http.Agent.defaultMaxSockets
self.requests = []
self.sockets = []
self.on('free', function onFree(socket, host, port) {
for (var i = 0, len = self.requests.length; i < len; ++i) {
var pending = self.requests[i]
if (pending.host === host && pending.port === port) {
// Detect the request to connect same origin server,
// reuse the connection.
self.requests.splice(i, 1)
pending.request.onSocket(socket)
return
}
}
socket.destroy()
self.removeSocket(socket)
})
}
util.inherits(TunnelingAgent, events.EventEmitter)
TunnelingAgent.prototype.addRequest = function addRequest(req, options) {
var self = this
// Legacy API: addRequest(req, host, port, path)
if (typeof options === 'string') {
options = {
host: options,
port: arguments[2],
path: arguments[3]
};
}
if (self.sockets.length >= this.maxSockets) {
// We are over limit so we'll add it to the queue.
self.requests.push({host: options.host, port: options.port, request: req})
return
}
// If we are under maxSockets create a new one.
self.createConnection({host: options.host, port: options.port, request: req})
}
TunnelingAgent.prototype.createConnection = function createConnection(pending) {
var self = this
self.createSocket(pending, function(socket) {
socket.on('free', onFree)
socket.on('close', onCloseOrRemove)
socket.on('agentRemove', onCloseOrRemove)
pending.request.onSocket(socket)
function onFree() {
self.emit('free', socket, pending.host, pending.port)
}
function onCloseOrRemove(err) {
self.removeSocket(socket)
socket.removeListener('free', onFree)
socket.removeListener('close', onCloseOrRemove)
socket.removeListener('agentRemove', onCloseOrRemove)
}
})
}
TunnelingAgent.prototype.createSocket = function createSocket(options, cb) {
var self = this
var placeholder = {}
self.sockets.push(placeholder)
var connectOptions = mergeOptions({}, self.proxyOptions,
{ method: 'CONNECT'
, path: options.host + ':' + options.port
, agent: false
}
)
if (connectOptions.proxyAuth) {
connectOptions.headers = connectOptions.headers || {}
connectOptions.headers['Proxy-Authorization'] = 'Basic ' +
new Buffer(connectOptions.proxyAuth).toString('base64')
}
debug('making CONNECT request')
var connectReq = self.request(connectOptions)
connectReq.useChunkedEncodingByDefault = false // for v0.6
connectReq.once('response', onResponse) // for v0.6
connectReq.once('upgrade', onUpgrade) // for v0.6
connectReq.once('connect', onConnect) // for v0.7 or later
connectReq.once('error', onError)
connectReq.end()
function onResponse(res) {
// Very hacky. This is necessary to avoid http-parser leaks.
res.upgrade = true
}
function onUpgrade(res, socket, head) {
// Hacky.
process.nextTick(function() {
onConnect(res, socket, head)
})
}
function onConnect(res, socket, head) {
connectReq.removeAllListeners()
socket.removeAllListeners()
if (res.statusCode === 200) {
assert.equal(head.length, 0)
debug('tunneling connection has established')
self.sockets[self.sockets.indexOf(placeholder)] = socket
cb(socket)
} else {
debug('tunneling socket could not be established, statusCode=%d', res.statusCode)
var error = new Error('tunneling socket could not be established, ' + 'statusCode=' + res.statusCode)
error.code = 'ECONNRESET'
options.request.emit('error', error)
self.removeSocket(placeholder)
}
}
function onError(cause) {
connectReq.removeAllListeners()
debug('tunneling socket could not be established, cause=%s\n', cause.message, cause.stack)
var error = new Error('tunneling socket could not be established, ' + 'cause=' + cause.message)
error.code = 'ECONNRESET'
options.request.emit('error', error)
self.removeSocket(placeholder)
}
}
TunnelingAgent.prototype.removeSocket = function removeSocket(socket) {
var pos = this.sockets.indexOf(socket)
if (pos === -1) return
this.sockets.splice(pos, 1)
var pending = this.requests.shift()
if (pending) {
// If we have pending requests and a socket gets closed a new one
// needs to be created to take over in the pool for the one that closed.
this.createConnection(pending)
}
}
function createSecureSocket(options, cb) {
var self = this
TunnelingAgent.prototype.createSocket.call(self, options, function(socket) {
// 0 is dummy port for v0.6
var secureSocket = tls.connect(0, mergeOptions({}, self.options,
{ servername: options.host
, socket: socket
}
))
self.sockets[self.sockets.indexOf(socket)] = secureSocket
cb(secureSocket)
})
}
function mergeOptions(target) {
for (var i = 1, len = arguments.length; i < len; ++i) {
var overrides = arguments[i]
if (typeof overrides === 'object') {
var keys = Object.keys(overrides)
for (var j = 0, keyLen = keys.length; j < keyLen; ++j) {
var k = keys[j]
if (overrides[k] !== undefined) {
target[k] = overrides[k]
}
}
}
}
return target
}
var debug
if (process.env.NODE_DEBUG && /\btunnel\b/.test(process.env.NODE_DEBUG)) {
debug = function() {
var args = Array.prototype.slice.call(arguments)
if (typeof args[0] === 'string') {
args[0] = 'TUNNEL: ' + args[0]
} else {
args.unshift('TUNNEL:')
}
console.error.apply(console, args)
}
} else {
debug = function() {}
}
exports.debug = debug // for test