forked from TooTallNate/node-http-proxy-agent
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhttp-proxy-agent.js
94 lines (74 loc) · 2.45 KB
/
http-proxy-agent.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
/**
* Module dependencies.
*/
var net = require('net');
var tls = require('tls');
var url = require('url');
var extend = require('extend');
var Agent = require('agent-base');
var inherits = require('util').inherits;
/**
* Module exports.
*/
module.exports = HttpProxyAgent;
/**
* The `HttpProxyAgent` implements an HTTP Agent subclass that connects to the
* specified "HTTP proxy server" in order to proxy HTTP requests.
*
* @api public
*/
function HttpProxyAgent (opts) {
if (!(this instanceof HttpProxyAgent)) return new HttpProxyAgent(opts);
if ('string' == typeof opts) opts = url.parse(opts);
if (!opts) throw new Error('an HTTP(S) proxy server `host` and `port` must be specified!');
Agent.call(this, connect);
var proxy = extend({}, opts);
// if `true`, then connect to the proxy server over TLS. defaults to `false`.
this.secureProxy = proxy.protocol ? proxy.protocol == 'https:' : false;
// prefer `hostname` over `host`, and set the `port` if needed
proxy.host = proxy.hostname || proxy.host;
proxy.port = +proxy.port || (this.secureProxy ? 443 : 80);
if (proxy.host && proxy.path) {
// if both a `host` and `path` are specified then it's most likely the
// result of a `url.parse()` call... we need to remove the `path` portion so
// that `net.connect()` doesn't attempt to open that as a unix socket file.
delete proxy.path;
}
this.proxy = proxy;
}
inherits(HttpProxyAgent, Agent);
/**
* Default options for the "connect" opts object.
*/
var defaults = { port: 80 };
/**
* Called when the node-core HTTP client library is creating a new HTTP request.
*
* @api public
*/
function connect (req, _opts, fn) {
var proxy = this.proxy;
var secureProxy = this.secureProxy;
// these `opts` are the connect options to connect to the destination endpoint
var opts = extend({}, proxy, defaults, _opts);
// change the `http.ClientRequest` instance's "path" field
// to the absolute path of the URL that will be requested
var absolute = url.format(extend(url.parse(req.path),{
protocol: 'http:',
hostname: opts.hostname || opts.host,
port: opts.port,
}));
req.path = absolute;
// inject the `Proxy-Authorization` header if necessary
var auth = proxy.auth;
if (auth) {
req.setHeader('Proxy-Authorization', 'Basic ' + new Buffer(auth).toString('base64'));
}
var socket;
if (secureProxy) {
socket = tls.connect(proxy);
} else {
socket = net.connect(proxy);
}
fn(null, socket);
};