1 |
|
2 |
|
3 |
|
4 |
|
5 |
|
6 | var url = require('url');
|
7 | var LRU = require('lru-cache');
|
8 | var HttpProxyAgent = require('http-proxy-agent');
|
9 | var HttpsProxyAgent = require('https-proxy-agent');
|
10 | var SocksProxyAgent = require('socks-proxy-agent');
|
11 |
|
12 |
|
13 |
|
14 |
|
15 |
|
16 | exports = module.exports = proxy;
|
17 |
|
18 |
|
19 |
|
20 |
|
21 |
|
22 |
|
23 |
|
24 |
|
25 | var cacheSize = 20;
|
26 |
|
27 |
|
28 |
|
29 |
|
30 |
|
31 | exports.cache = new LRU(cacheSize);
|
32 |
|
33 |
|
34 |
|
35 |
|
36 |
|
37 | exports.proxies = {
|
38 | http: httpOrHttpsProxy,
|
39 | https: httpOrHttpsProxy,
|
40 | socks: socksProxy
|
41 | };
|
42 |
|
43 |
|
44 |
|
45 |
|
46 |
|
47 |
|
48 |
|
49 |
|
50 |
|
51 |
|
52 |
|
53 |
|
54 |
|
55 |
|
56 | function proxy (uri, secure) {
|
57 |
|
58 |
|
59 | var proxyParsed = uri;
|
60 | if ('string' == typeof uri) {
|
61 | proxyParsed = url.parse(uri);
|
62 | }
|
63 |
|
64 |
|
65 | var protocol = proxyParsed.protocol;
|
66 | if (!protocol) {
|
67 | var types = [];
|
68 | for (var type in proxies) types.push(type);
|
69 | throw new TypeError('you must specify a string "protocol" for the proxy type (' + types.join(', ') + ')');
|
70 | }
|
71 |
|
72 |
|
73 | if (':' == protocol[protocol.length - 1]) {
|
74 | protocol = protocol.substring(0, protocol.length - 1);
|
75 | }
|
76 |
|
77 |
|
78 | var proxyFn = exports.proxies[protocol];
|
79 | if ('function' != typeof proxyFn) {
|
80 | throw new TypeError('unsupported proxy protocol: "' + protocol + '"');
|
81 | }
|
82 |
|
83 |
|
84 |
|
85 |
|
86 | var proxyUri = url.format({
|
87 | protocol: protocol + ':',
|
88 | slashes: true,
|
89 | hostname: proxyParsed.hostname || proxyParsed.host,
|
90 | port: proxyParsed.port
|
91 | });
|
92 |
|
93 |
|
94 | var key = proxyUri;
|
95 | if (secure) key += ' secure';
|
96 |
|
97 |
|
98 | var agent = exports.cache.get(key);
|
99 | if (!agent) {
|
100 |
|
101 | agent = proxyFn(proxyParsed, secure);
|
102 | if (agent) exports.cache.set(key, agent);
|
103 | } else {
|
104 |
|
105 | }
|
106 |
|
107 | return agent;
|
108 | }
|
109 |
|
110 |
|
111 |
|
112 |
|
113 |
|
114 |
|
115 |
|
116 | function httpOrHttpsProxy (proxy, secure) {
|
117 | if (secure) {
|
118 |
|
119 | return new HttpsProxyAgent(proxy);
|
120 | } else {
|
121 |
|
122 | return new HttpProxyAgent(proxy);
|
123 | }
|
124 | }
|
125 |
|
126 |
|
127 |
|
128 |
|
129 |
|
130 |
|
131 |
|
132 | function socksProxy (proxy, secure) {
|
133 | return new SocksProxyAgent(proxy, secure);
|
134 | }
|