Proxy or serve not found based on the decision
19383
function onDecision(err, target) {
    //
    // If there was no target then this is a 404 by definition
    // even if it exists in the public registry because of a
    // potential whitelist.
    //
    if (err || !target) {
      return self.notFound(req, res, err || { message: 'Unknown pkg: ' + pkg });
    }

    // if X-Forwarded-Host is set, npm returns 404 {"error":"not_found","reason":"no_db_file"}
    if (req.headers["x-forwarded-host"]) delete req.headers["x-forwarded-host"];

    //
    // If we get a valid target then we can proxy to it
    //
    self.log.info('[decide] %s - %s %s %s %j', address, req.method, req.url, target.vhost || target.host || target.hostname, req.headers);

    self.emit('headers', req, req.headers, target);

    req.headers.host = target.vhost || target.host || target.hostname;
    proxy.web(req, res, {
      target: target.href
    });
  }
515007
def _update_proxy(self, change):
        
        if change['type'] in ['event', 'update'] and self.proxy_is_active:
            handler = getattr(self.proxy, 'set_' + change['name'], None)
            if handler is not None:
                handler(change['value'])
1070025
async def set_http_proxy(cls, url: typing.Optional[str]):
        """"""
        await cls.set_config("http_proxy", "" if url is None else url)
1276319
function initApiProxy() {
  if (build.verbose)
    console.log('Proxying paths...');
  lodash.forEach(build.proxyMap, function (proxyOpts, urlPath) {
    if (build.verbose)
      console.log('  - url: "' + urlPath + '"');
    app.use(urlPath, proxy(proxyOpts));
    // e.g. `app.use('/api', proxy({target: "http://localhost:4321/api", 
    // changeOrigin: true});`
  });
}
600790
def get_proxy_ticket_for(self, service):
        

        if not settings.CAS_PROXY_CALLBACK:
            raise CasConfigException("No proxy callback set in settings")

        params = {'pgt': self.tgt, 'targetService': service}

        url = (urljoin(settings.CAS_SERVER_URL, 'proxy') + '?' +
               urlencode(params))

        page = urlopen(url)

        try:
            response = page.read()
            tree = ElementTree.fromstring(response)
            if tree[0].tag.endswith('proxySuccess'):
                return tree[0][0].text
            else:
                logger.warning('Failed to get proxy ticket')
                raise CasTicketException('Failed to get proxy ticket: %s' % \
                                         tree[0].text.strip())
        finally:
            page.close()
910207
private void checkProxyBasicOptions(ProxyInfoParams params,
    List<VOMSAttribute> listVOMSAttributes, File proxyFilePath,
    X509Certificate[] proxyChain) {

    if (params.containsOption(PrintOption.TYPE)
      && !params.containsOption(PrintOption.ALL_OPTIONS)) {

      logger.printMessage(proxyTypeAsString(proxyChain[0]));
    }

    if (params.containsOption(PrintOption.SUBJECT)
      && !params.containsOption(PrintOption.ALL_OPTIONS)) {

      logger.printMessage(OpensslNameUtilities
        .getOpensslSubjectString(proxyChain[0].getSubjectX500Principal()));
    }

    if (params.containsOption(PrintOption.ISSUER)
      || params.containsOption(PrintOption.IDENTITY)
      && !params.containsOption(PrintOption.ALL_OPTIONS)) {

      logger.printMessage(OpensslNameUtilities
        .getOpensslSubjectString(proxyChain[0].getIssuerX500Principal()));
    }

    if (params.containsOption(PrintOption.PROXY_PATH)
      && !params.containsOption(PrintOption.ALL_OPTIONS)) {
      logger.printMessage(proxyFilePath.getAbsolutePath());
    }

    if (params.containsOption(PrintOption.CHAIN)) {

      printProxyChain(proxyChain);

      logger.printMessage("=== Proxy Information ===");
      printProxyStandardInfo(proxyFilePath);

      if (params.containsOption(PrintOption.ALL_OPTIONS)) {
        printAC(listVOMSAttributes);
      }

      logger.printMessage("");
    }

    if (params.containsOption(PrintOption.TEXT)) {
      if (!params.containsOption(PrintOption.ALL_OPTIONS)
        && !params.containsOption(PrintOption.CHAIN)) {
        printProxyStandardInfo(proxyFilePath);
        logger.printMessage("");
      }

      int chainLength = 1;
      if (params.containsOption(PrintOption.CHAIN))
        chainLength = proxyChain.length;
      for (int i = chainLength - 1; i >= 0; i--) {
        logger.printMessage("Certificate:");
        logger.printMessage(CertificateUtils.format(proxyChain[i],
          FormatMode.FULL));
        logger.printMessage("");
      }
    }

    if (params.containsOption(PrintOption.KEYSIZE)
      && !params.containsOption(PrintOption.ALL_OPTIONS)) {
      logger.printMessage(getKeySize(proxyChain[0]));
    }

    if (params.containsOption(PrintOption.KEYUSAGE)
      && !params.containsOption(PrintOption.ALL_OPTIONS)) {
      tabularFormatted("key usage", getProxyKeyUsages());
    }

    if (params.containsOption(PrintOption.TIMELEFT)
      && !params.containsOption(PrintOption.ALL_OPTIONS)) {

      Date notAfter = proxyCredential.getCertificate().getNotAfter();

      long notAfterinMSec = TimeUtils.getTimeLeft(notAfter);

      long notAfterInSec = TimeUnit.MILLISECONDS.toSeconds(notAfterinMSec);

      logger.printMessage(String.valueOf(notAfterInSec));
    }

  }
1019791
def request(self, method, url, proxies=None, **kwargs):
        
        if not self._tried_get_pac:
            self.get_pac()

        # Whether we obtained or are trying to obtain a proxy from the PAC.
        # PAC is not in use if this request has proxies provided as a parameter, or if the session has disabled PAC.
        using_pac = proxies is None and self._proxy_resolver and self.pac_enabled

        if using_pac:
            proxies = self._proxy_resolver.get_proxy_for_requests(url)

        while True:
            proxy_url = list(proxies.values())[0] if proxies else None
            try:
                response = super(PACSession, self).request(method, url, proxies=proxies, **kwargs)
            except Exception as request_exc:
                # Use PAC's proxy failover rules if the proxy used for the request is from the PAC,
                # and this exception represents a proxy failure.
                if using_pac and proxy_url and self._exc_proxy_failure_filter(request_exc):
                    try:
                        proxies = self.do_proxy_failover(proxy_url, url)
                        continue
                    except ProxyConfigExhaustedError:
                        # No failover option, not even DIRECT. Bubble up original exception.
                        self._proxy_resolver.unban_all()
                raise request_exc  # In PY2, just saying 'raise' may re-raise ProxyConfigExhaustedError.

            # Use PAC's proxy failover rules if the proxy used for the request is from the PAC,
            # and this response represents a proxy failure.
            if using_pac and proxy_url and self._response_proxy_failure_filter(response):
                try:
                    proxies = self.do_proxy_failover(proxy_url, url)
                    continue
                except ProxyConfigExhaustedError:
                    # No failover option, not even DIRECT. Return response as-is.
                    self._proxy_resolver.unban_all()
                    return response

            return response
414325
function proxyServerMidleware(req, res, next) {
    // Check if static resource exist
    var sfile = path.join(req.app.get('static resource'), req.path);
    if(fs.existsSync(sfile)) {
        return next();
    }
    // Proxy request
    // --------------
    // buffer so that it won't be lost,
    // !!This is confilced with `methodOverride()`
    var buffer = httpProxy.buffer(req);
    var proxySetting = req.app.get('proxy setting');
    // Do process
    ProxyInstance.proxyRequest(req, res, {
        host: proxySetting.remote.host,
        port: proxySetting.remote.port,
        buffer: buffer
    });
}
361473
def use(proxy, options = {}, &block)
      proxy = Moneta.const_get(proxy) if Symbol === proxy
      raise ArgumentError, 'You must give a Class or a Symbol' unless Class === proxy
      @proxies.unshift [proxy, options, block]
      nil
    end
284913
def supports_proxies(*proxy_types):
    '''
    
    '''
    def _supports_proxies(fn):
        @wraps(fn)
        def __supports_proxies(*args, **kwargs):
            proxy_type = get_proxy_type()
            if proxy_type not in proxy_types:
                raise CommandExecutionError(
                    '\'{0}\' proxy is not supported by function {1}'
                    ''.format(proxy_type, fn.__name__))
            return fn(*args, **salt.utils.args.clean_kwargs(**kwargs))
        return __supports_proxies
    return _supports_proxies
92586
function serve (root, opts) {
  opts = Object.assign({}, opts)

  assert(root, 'root directory is required to serve files')

  // options
  debug('static "%s" %j', root, opts)
  opts.root = resolve(root)
  if (opts.index !== false) opts.index = opts.index || 'index.html'

  if (!opts.defer) {
    return async function serve (ctx, next) {
      let done = false

      if (ctx.method === 'HEAD' || ctx.method === 'GET') {
        try {
          done = await send(ctx, ctx.path, opts)
        } catch (err) {
          if (err.status !== 404) {
            throw err
          }
        }
      }

      if (!done) {
        await next()
      }
    }
  }

  return async function serve (ctx, next) {
    await next()

    if (ctx.method !== 'HEAD' && ctx.method !== 'GET') return
    // response is already handled
    if (ctx.body != null || ctx.status !== 404) return // eslint-disable-line

    try {
      await send(ctx, ctx.path, opts)
    } catch (err) {
      if (err.status !== 404) {
        throw err
      }
    }
  }
}
969347
def enable_proxy(self, host, port):
        """"""

        self.proxy = [host, _number(port)]
        self.proxy_enabled = True
219485
def _get_proxy_target(service_instance):
    '''
    
    '''
    proxy_type = get_proxy_type()
    if not salt.utils.vmware.is_connection_to_a_vcenter(service_instance):
        raise CommandExecutionError('\'_get_proxy_target\' not supported '
                                    'when connected via the ESXi host')
    reference = None
    if proxy_type == 'esxcluster':
        host, username, password, protocol, port, mechanism, principal, \
            domain, datacenter, cluster = _get_esxcluster_proxy_details()

        dc_ref = salt.utils.vmware.get_datacenter(service_instance, datacenter)
        reference = salt.utils.vmware.get_cluster(dc_ref, cluster)
    elif proxy_type == 'esxdatacenter':
        # esxdatacenter proxy
        host, username, password, protocol, port, mechanism, principal, \
            domain, datacenter = _get_esxdatacenter_proxy_details()

        reference = salt.utils.vmware.get_datacenter(service_instance,
                                                     datacenter)
    elif proxy_type == 'vcenter':
        # vcenter proxy - the target is the root folder
        reference = salt.utils.vmware.get_root_folder(service_instance)
    elif proxy_type == 'esxi':
        # esxi proxy
        details = __proxy__['esxi.get_details']()
        if 'vcenter' not in details:
            raise InvalidEntityError('Proxies connected directly to ESXi '
                                     'hosts are not supported')
        references = salt.utils.vmware.get_hosts(
            service_instance, host_names=details['esxi_host'])
        if not references:
            raise VMwareObjectRetrievalError(
                'ESXi host \'{0}\' was not found'.format(details['esxi_host']))
        reference = references[0]
    log.trace('reference = %s', reference)
    return reference
422211
def _passes_filter(self, proxy):


        '''  '''
        
        ''' validate proxy based on provided filters '''
        if self.allowed_countries is not None and proxy['country'] not in self.allowed_countries:
            return False
        if self.denied_countries is not None and  proxy['country'] in self.denied_countries:
            return False
        if self.https_only and proxy['https'] == False:
            return False

        if not self.all_ports and str(proxy.port) not in self.ports:
            return False

        return True
1179373
def set_proxy(self, proxy):
        
        # TODO: Validate proxy url format

        if proxy is None:
            self.driver.proxies = {'http': None,
                                   'https': None
                                   }
        else:
            self.driver.proxies = {'http': proxy,
                                   'https': proxy
                                   }

        self.current_proxy = proxy
322453
async def get_object_proxy_location(self, client, pid):
        
        try:
            return (await client.describe(pid)).get("DataONE-Proxy")
        except d1_common.types.exceptions.DataONEException:
            # Workaround for older GMNs that return 500 instead of 404 for describe()
            pass
400157
function proxyHttps(){
  httpServer.on('connect', function(req, socket, upgradeHead){
    var hostname = req.url.split(':')[0];
    log.debug('Create internal https server for ' + hostname);
    createInternalHttpsServer(hostname, function (err, httpsServerPort) {
      if (err) {
        log.error('Failed to create internal https proxy');
        log.error(err);
        return;
      }
      // get proxy https server
      var netClient = net.createConnection(httpsServerPort);

      netClient.on('connect', function(){
        log.info('connect to https server successfully!');
        socket.write( "HTTP/1.1 200 Connection established\r\nProxy-agent: Netscape-Proxy/1.1\r\n\r\n");
      });

      socket.on('data', function(chunk){
        netClient.write(chunk);
      });
      socket.on('end', function(){
        netClient.end();
      });
      socket.on('close', function(){
        netClient.end();
      });
      socket.on('error', function(err){
        log.error('socket error ' + err.message);
        netClient.end();
      });

      netClient.on('data', function(chunk){
        socket.write(chunk);
      });
      netClient.on('end', function(){
        socket.end();
      });
      netClient.on('close', function(){
        socket.end();
      });
      netClient.on('error', function(err){
        log.error('netClient error ' + err.message);
        socket.end();
      });
    });
  });
}