222
schangxiang@126.com
2025-06-13 6a8393408d8cefcea02b7a598967de8dc1e565c2
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
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
'use strict';
 
/**
 * Module exports.
 */
 
module.exports = exports = PacProxyAgent;
 
/**
 * Supported "protocols". Delegates out to the `get-uri` module.
 */
 
var getUri = require('get-uri');
Object.defineProperty(exports, 'protocols', {
  enumerable: true,
  configurable: true,
  get: function () { return Object.keys(getUri.protocols); }
});
 
/**
 * Module dependencies.
 */
 
var net = require('net');
var tls = require('tls');
var crypto = require('crypto');
var parse = require('url').parse;
var format = require('url').format;
var Agent = require('agent-base');
var HttpProxyAgent = require('http-proxy-agent');
var HttpsProxyAgent = require('https-proxy-agent');
var SocksProxyAgent = require('socks-proxy-agent');
var PacResolver = require('pac-resolver');
var getRawBody = require('raw-body');
var inherits = require('util').inherits;
var debug = require('debug')('pac-proxy-agent');
 
/**
 * The `PacProxyAgent` class.
 *
 * A few different "protocol" modes are supported (supported protocols are
 * backed by the `get-uri` module):
 *
 *   - "pac+data", "data" - refers to an embedded "data:" URI
 *   - "pac+file", "file" - refers to a local file
 *   - "pac+ftp", "ftp" - refers to a file located on an FTP server
 *   - "pac+http", "http" - refers to an HTTP endpoint
 *   - "pac+https", "https" - refers to an HTTPS endpoint
 *
 * @api public
 */
 
function PacProxyAgent (uri, opts) {
  if (!(this instanceof PacProxyAgent)) return new PacProxyAgent(uri, opts);
 
  // was an options object passed in first?
  if ('object' === typeof uri) {
    opts = uri;
 
    // result of a url.parse() call?
    if (opts.href) {
      if (opts.path && !opts.pathname) {
        opts.pathname = opts.path;
      }
      opts.slashes = true;
      uri = format(opts);
    } else {
      uri = opts.uri;
    }
  }
  if (!opts) opts = {};
 
  if (!uri) throw new Error('a PAC file URI must be specified!');
  debug('creating PacProxyAgent with URI %o and options %o', uri, opts);
 
  Agent.call(this, connect);
 
  // strip the "pac+" prefix
  this.uri = uri.replace(/^pac\+/i, '');
 
  this.sandbox = opts.sandbox;
 
  this.proxy = opts;
 
  this.cache = this._resolver = null;
}
inherits(PacProxyAgent, Agent);
 
/**
 * Loads the PAC proxy file from the source if necessary, and returns
 * a generated `FindProxyForURL()` resolver function to use.
 *
 * @param {Function} fn callback function
 * @api private
 */
 
PacProxyAgent.prototype.loadResolver = function (fn) {
  var self = this;
 
  // kick things off by attempting to (re)load the contents of the PAC file URI
  this.loadPacFile(onpacfile);
 
  // loadPacFile() callback function
  function onpacfile (err, code) {
    if (err) {
      if ('ENOTMODIFIED' == err.code) {
        debug('got ENOTMODIFIED response, reusing previous proxy resolver');
        fn(null, self._resolver);
      } else {
        fn(err);
      }
      return;
    }
 
    // create a sha1 hash of the JS code
    var hash = crypto.createHash('sha1').update(code).digest('hex');
 
    if (self._resolver && self._resolver.hash == hash) {
      debug('same sha1 hash for code - contents have not changed, reusing previous proxy resolver');
      fn(null, self._resolver);
      return;
    }
 
    // cache the resolver
    debug('creating new proxy resolver instance');
    self._resolver = new PacResolver(code, {
      filename: self.uri,
      sandbox: self.sandbox
    });
 
    // store that sha1 hash on the resolver instance
    // for future comparison purposes
    self._resolver.hash = hash;
 
    fn(null, self._resolver);
  }
};
 
/**
 * Loads the contents of the PAC proxy file.
 *
 * @param {Function} fn callback function
 * @api private
 */
 
PacProxyAgent.prototype.loadPacFile = function (fn) {
  debug('loading PAC file: %o', this.uri);
  var self = this;
 
  // delegate out to the `get-uri` module
  var opts = {};
  if (this.cache) {
    opts.cache = this.cache;
  }
  getUri(this.uri, opts, onstream);
 
  function onstream (err, rs) {
    if (err) return fn(err);
    debug('got stream.Readable instance for URI');
    self.cache = rs;
    getRawBody(rs, 'utf8', onbuffer);
  }
 
  function onbuffer (err, buf) {
    if (err) return fn(err);
    debug('read %o byte PAC file from URI', buf.length);
    fn(null, buf);
  }
};
 
/**
 * Called when the node-core HTTP client library is creating a new HTTP request.
 *
 * @api public
 */
 
function connect (req, opts, fn) {
  var url;
  var host;
  var self = this;
  var secure = Boolean(opts.secureEndpoint);
 
  // first we need get a generated FindProxyForURL() function,
  // either cached or retreived from the source
  this.loadResolver(onresolver);
 
  // `loadResolver()` callback function
  function onresolver (err, FindProxyForURL) {
    if (err) return fn(err);
 
    // calculate the `url` parameter
    var defaultPort = secure ? 443 : 80;
    var path = req.path;
    var firstQuestion = path.indexOf('?');
    var search;
    if (-1 != firstQuestion) {
      search = path.substring(firstQuestion);
      path = path.substring(0, firstQuestion);
    }
    url = format(Object.assign({}, opts, {
      protocol: secure ? 'https:' : 'http:',
      pathname: path,
      search: search,
 
      // need to use `hostname` instead of `host` otherwise `port` is ignored
      hostname: opts.host,
      host: null,
 
      // set `port` to null when it is the protocol default port (80 / 443)
      port: defaultPort == opts.port ? null : opts.port
    }));
 
    // calculate the `host` parameter
    host = parse(url).hostname;
 
    debug('url: %o, host: %o', url, host);
    FindProxyForURL(url, host, onproxy);
  }
 
  // `FindProxyForURL()` callback function
  function onproxy (err, proxy) {
    if (err) return fn(err);
 
    // default to "DIRECT" if a falsey value was returned (or nothing)
    if (!proxy) proxy = 'DIRECT';
 
    var proxies = String(proxy).trim().split(/\s*;\s*/g).filter(Boolean);
 
    // XXX: right now, only the first proxy specified will be used
    var first = proxies[0];
    debug('using proxy: %o', first);
 
    var agent;
    var parts = first.split(/\s+/);
    var type = parts[0];
 
    if ('DIRECT' == type) {
      // direct connection to the destination endpoint
      var socket;
      if (secure) {
        socket = tls.connect(opts);
      } else {
        socket = net.connect(opts);
      }
      return fn(null, socket);
    } else if ('SOCKS' == type) {
      // use a SOCKS proxy
      agent = new SocksProxyAgent('socks://' + parts[1]);
    } else if ('PROXY' == type || 'HTTPS' == type) {
      // use an HTTP or HTTPS proxy
      // http://dev.chromium.org/developers/design-documents/secure-web-proxy
      var proxyURL = ('HTTPS' === type ? 'https' : 'http') + '://' + parts[1];
      var proxy = Object.assign({}, self.proxy, parse(proxyURL));
      if (secure) {
        agent = new HttpsProxyAgent(proxy);
      } else {
        agent = new HttpProxyAgent(proxy);
      }
    } else {
      throw new Error('Unknown proxy type: ' + type);
    }
    if (agent) agent.callback(req, opts, fn);
  }
}