get_proxy_from_uri.js 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. // copy from https://github.com/request/request/blob/90cf8c743bb9fd6a4cb683a56fb7844c6b316866/lib/getProxyFromURI.js
  2. 'use strict'
  3. function formatHostname(hostname) {
  4. // canonicalize the hostname, so that 'oogle.com' won't match 'google.com'
  5. return hostname.replace(/^\.*/, '.').toLowerCase()
  6. }
  7. function parseNoProxyZone(zone) {
  8. zone = zone.trim().toLowerCase()
  9. var zoneParts = zone.split(':', 2)
  10. , zoneHost = formatHostname(zoneParts[0])
  11. , zonePort = zoneParts[1]
  12. , hasPort = zone.indexOf(':') > -1
  13. return {hostname: zoneHost, port: zonePort, hasPort: hasPort}
  14. }
  15. function uriInNoProxy(uri, noProxy) {
  16. var port = uri.port || (uri.protocol === 'https:' ? '443' : '80')
  17. , hostname = formatHostname(uri.hostname)
  18. , noProxyList = noProxy.split(',')
  19. // iterate through the noProxyList until it finds a match.
  20. return noProxyList.map(parseNoProxyZone).some(function(noProxyZone) {
  21. var isMatchedAt = hostname.indexOf(noProxyZone.hostname)
  22. , hostnameMatched = (
  23. isMatchedAt > -1 &&
  24. (isMatchedAt === hostname.length - noProxyZone.hostname.length)
  25. )
  26. if (noProxyZone.hasPort) {
  27. return (port === noProxyZone.port) && hostnameMatched
  28. }
  29. return hostnameMatched
  30. })
  31. }
  32. function getProxyFromURI(uri) {
  33. // Decide the proper request proxy to use based on the request URI object and the
  34. // environmental variables (NO_PROXY, HTTP_PROXY, etc.)
  35. // respect NO_PROXY environment variables (see: http://lynx.isc.org/current/breakout/lynx_help/keystrokes/environments.html)
  36. var noProxy = process.env.NO_PROXY || process.env.no_proxy || ''
  37. // if the noProxy is a wildcard then return null
  38. if (noProxy === '*') {
  39. return null
  40. }
  41. // if the noProxy is not empty and the uri is found return null
  42. if (noProxy !== '' && uriInNoProxy(uri, noProxy)) {
  43. return null
  44. }
  45. // Check for HTTP or HTTPS Proxy in environment Else default to null
  46. if (uri.protocol === 'http:') {
  47. return process.env.HTTP_PROXY ||
  48. process.env.http_proxy || null
  49. }
  50. if (uri.protocol === 'https:') {
  51. return process.env.HTTPS_PROXY ||
  52. process.env.https_proxy ||
  53. process.env.HTTP_PROXY ||
  54. process.env.http_proxy || null
  55. }
  56. // if none of that works, return null
  57. // (What uri protocol are you using then?)
  58. return null
  59. }
  60. module.exports = getProxyFromURI