Runs new HTTP Server and attaches Inspector Proxy to it. Requires are inlined here because we don't want to import them when someone needs only InspectorProxy instance (without starting new HTTP server).
324099
function runInspectorProxy(port: number) {
  const inspectorProxy = new InspectorProxy();
  const app = require('connect')();
  app.use(inspectorProxy.processRequest.bind(inspectorProxy));

  const httpServer = require('http').createServer(app);
  httpServer.listen(port, '127.0.0.1', () => {
    inspectorProxy.addWebSocketListener(httpServer);
  });
}
1178973
def make_server(host, port, app=None, threaded=False, processes=1,
                request_handler=None, passthrough_errors=False,
                ssl_context=None):
    
    if threaded and processes > 1:
        raise ValueError("cannot have a multithreaded and "
                         "multi process server.")
    elif threaded:
        return ThreadedWSGIServer(host, port, app, request_handler,
                                  passthrough_errors, ssl_context)
    elif processes > 1:
        return ForkingWSGIServer(host, port, app, processes, request_handler,
                                 passthrough_errors, ssl_context)
    else:
        return BaseWSGIServer(host, port, app, request_handler,
                              passthrough_errors, ssl_context)
49780
def create_http(_url = nil)


      if !request_endpoint.nil?
       _url = request_endpoint
      end


      if _url.nil? || _url[0] =~ /^\//
        our_uri = URI.parse(site)
      else
        our_uri = URI.parse(_url)
      end


      if proxy.nil?
        http_object = Net::HTTP.new(our_uri.host, our_uri.port)
      else
        proxy_uri = proxy.is_a?(URI) ? proxy : URI.parse(proxy)
        http_object = Net::HTTP.new(our_uri.host, our_uri.port, proxy_uri.host, proxy_uri.port, proxy_uri.user, proxy_uri.password)
      end

      http_object.use_ssl = (our_uri.scheme == 'https')

      if @options[:ca_file] || CA_FILE
        http_object.ca_file = @options[:ca_file] || CA_FILE
        http_object.verify_mode = OpenSSL::SSL::VERIFY_PEER
        http_object.verify_depth = 5
      else
        http_object.verify_mode = OpenSSL::SSL::VERIFY_NONE
      end

      http_object.read_timeout = http_object.open_timeout = @options[:timeout] || 30
      http_object.open_timeout = @options[:open_timeout] if @options[:open_timeout]
      http_object.ssl_version = @options[:ssl_version] if @options[:ssl_version]
      http_object.set_debug_output(debug_output) if debug_output

      http_object
    end
59316
def __enableProxy(self):
        
        os.environ[
            "HTTP_PROXY"] = self.httpProxy()
        os.environ[
            "HTTPS_PROXY"] = self.httpsProxy()

        os.environ["REQUESTS_CA_BUNDLE"] = os.path.join(
            os.path.dirname(
                os.path.abspath(__file__)),
            "cert.pem")
1038051
public static <R, W> HttpServerInterceptorChain<R, W, R, W> start() {
        return new HttpServerInterceptorChain<>(new TransformingInterceptor<R, W, R, W>() {
            @Override
            public RequestHandler<R, W> intercept(RequestHandler<R, W> handler) {
                return handler;
            }
        });
    }
890168
protected HttpTunnel newHttpTunnel(HttpRequest request, HttpResponse response, InetAddress iaddr, int port, int timeoutMS) throws IOException
    {
        try
        {
            Socket socket=null;
            InputStream in=null;
            
            String chained_proxy_host=System.getProperty("http.proxyHost");
            if (chained_proxy_host==null)
            {
                socket= new Socket(iaddr, port);
                socket.setSoTimeout(timeoutMS);
                socket.setTcpNoDelay(true);
            }
            else
            {
                int chained_proxy_port = Integer.getInteger("http.proxyPort", 8888).intValue();
                
                Socket chain_socket= new Socket(chained_proxy_host, chained_proxy_port);
                chain_socket.setSoTimeout(timeoutMS);
                chain_socket.setTcpNoDelay(true);
                if (log.isDebugEnabled()) log.debug("chain proxy socket="+chain_socket);
                
                LineInput line_in = new LineInput(chain_socket.getInputStream());
                byte[] connect= request.toString().getBytes(org.browsermob.proxy.jetty.util.StringUtil.__ISO_8859_1);
                chain_socket.getOutputStream().write(connect);
                
                String chain_response_line = line_in.readLine();
                HttpFields chain_response = new HttpFields();
                chain_response.read(line_in);
                
                // decode response
                int space0 = chain_response_line.indexOf(' ');
                if (space0>0 && space0+1<chain_response_line.length())
                {
                    int space1 = chain_response_line.indexOf(' ',space0+1);
                    
                    if (space1>space0)
                    {
                        int code=Integer.parseInt(chain_response_line.substring(space0+1,space1));
                        
                        if (code>=200 && code<300)
                        {
                            socket=chain_socket;
                            in=line_in;
                        }
                        else
                        {
                            Enumeration iter = chain_response.getFieldNames();
                            while (iter.hasMoreElements())
                            {
                                String name=(String)iter.nextElement();
                                if (!_DontProxyHeaders.containsKey(name))
                                {
                                    Enumeration values = chain_response.getValues(name);
                                    while(values.hasMoreElements())
                                    {
                                        String value=(String)values.nextElement();
                                        response.setField(name, value);
                                    }
                                }
                            }
                            response.sendError(code);
                            if (!chain_socket.isClosed())
                                chain_socket.close();
                        }
                    }
                }
            }
            
            if (socket==null)
                return null;
            HttpTunnel tunnel=new HttpTunnel(socket,in,null);
            return tunnel;
        }
        catch(IOException e)
        {
            log.debug(e);
            response.sendError(HttpResponse.__400_Bad_Request);
            return null;
        }
    }
284618
def do_initial_operations(self):
        
        if not self.request_hc_path_corresponds():
            # the http URI of the request is not the same of the one specified by the admin for the hc proxy,
            # so I do not answer
            # For example the admin setup the http proxy URI like: "http://127.0.0.1:8080:/my_hc_path/" and the URI of
            # the requests asks for "http://127.0.0.1:8080:/another_hc_path/"
            return
        self.set_coap_uri()
        self.client = HelperClient(server=(self.coap_uri.host, self.coap_uri.port))
643138
function startServer(argv, httpPort, httpsPort, certs) {
  console.log('Launching proxy server...');
  console.log('   http: ' + httpPort);
  console.log('  https: ' + httpsPort);

  // Injects a node stream by buffering all data, transforming it, and writing
  // it back out.
  // Module IDs are assigned on demand and rotate 0-126.
  var nextModuleId = 0;
  function injectStream(url, source, target) {
    var moduleId = nextModuleId++;
    if (nextModuleId >= 127) {
      nextModuleId = 0;
    }
    var sourceCode = '';
    source.on('data', function(chunk) {
      sourceCode += chunk;
    });
    source.on('end', function() {
      try {
        var targetCode = transformCode(moduleId, url, sourceCode, argv);
        target.end(targetCode);
      } catch (e) {
        console.log('Error during transformation, writing through.');
        console.log(e);
        target.end(sourceCode);
      }
    });
  };

  // Handles both HTTP and HTTPS requests.
  function handler(req, res) {
    // Support both the ?url= mode and the X-WTF-URL header.
    var targetUrl;
    if (req.headers['x-wtf-url']) {
      targetUrl = req.headers['x-wtf-url'];
    } else {
      var parsedUrl = url.parse(req.url, true);
      var query = parsedUrl.query;
      targetUrl = query.url;
    }
    if (!targetUrl || targetUrl.indexOf('http') != 0) {
      res.writeHead(404, ['Content-Type', 'text/plain']);
      res.end();
      return;
    }

    res.on('error', function(e) {
      console.log('ERROR (source): ' + e);
    });

    var targetModule = targetUrl.indexOf('https') == 0 ? https : http;
    targetModule.get(targetUrl, function(originalRes) {
      // Eat errors, otherwise the app will die.
      originalRes.on('error', function(e) {
        console.log('ERROR (target): ' + e);
      });

      // Pull out content type to see if we are interested in it.
      var supportedContentType = false;
      var contentType = originalRes.headers['content-type'];
      if (contentType && contentType.indexOf(';') != 0) {
        contentType = contentType.substr(0, contentType.indexOf(';'));
      }
      switch (contentType) {
        case 'text/javascript':
        case 'application/javascript':
          supportedContentType = true;
          break;
      }

      // Also parse the URL - some servers don't return content type for some
      // reason.
      var supportedPath = false;
      var contentUrl = url.parse(targetUrl);
      if (path.extname(contentUrl.pathname) == '.js') {
        supportedPath = true;
      }

      if (supportedContentType || supportedPath) {
        var headers = [];
        for (var key in originalRes.headers) {
          if (key == 'content-length') {
            continue;
          }
          headers.push([key, originalRes.headers[key]]);
        }
        res.writeHead(originalRes.statusCode, headers);
        injectStream(targetUrl, originalRes, res);
      } else {
        console.log('Pass-through: ' + targetUrl, contentType);
        res.writeHead(originalRes.statusCode, originalRes.headers);
        originalRes.pipe(res);
      }
    }).on('error', function(e) {
      console.log(e);
      res.writeHead(404, ['Content-Type', 'text/plain']);
      res.end(e.message);
    });
  };

  // HTTP server.
  var httpServer = http.createServer(handler);
  httpServer.listen(httpPort);

  // HTTPS server.
  var httpsServer = https.createServer({
    key: certs.privateKey,
    cert: certs.certificate
  }, handler);
  httpsServer.listen(httpsPort);

  console.log('Server ready, use ctrl-c to exit...');
  console.log('');
}
412658
public <X> X newProxy(Class<X> interfaces) {
		return (X) newProxy(new Class[] {interfaces});
	}
530595
public HttpClient build() {
		HttpClient httpClient = new HttpClient();
		
		if (proxyHost != null) {
			ProxyHost h;
			if (proxyPort == -1) {
				h = new ProxyHost(proxyHost);
			} else {
				h = new ProxyHost(proxyHost, proxyPort);
			}
			httpClient.getHostConfiguration().setProxyHost(h);
		}

		if (basicAuthUsername != null) {
			httpClient.getParams().setAuthenticationPreemptive(authenticationPreemprive);
			AuthScope authscope = new AuthScope(
					basicAuthHost == null ? AuthScope.ANY_HOST : basicAuthHost,
					basicAuthPort == -1 ? AuthScope.ANY_PORT : basicAuthPort);
			Credentials credentials = new UsernamePasswordCredentials(basicAuthUsername, basicAuthPassword);
			httpClient.getState().setCredentials(authscope, credentials);
		}
		
		if (sslHostConfig != null) {
			sslHostConfigs.put(secureHost, sslHostConfig);
		}
		
		for (Entry<String, SslHostConfig> entry : sslHostConfigs.entrySet()) {
			String host = entry.getKey();
			SslHostConfig config = entry.getValue();
            AuthSSLProtocolSocketFactory factory = new AuthSSLProtocolSocketFactory(
					config.keyStoreUrl, config.keyStorePassword,
					config.trustKeyStoreUrl, config.trustKeyStorePassword);
            if (sslEnabledProtocols != null) {
                factory.setEnabledProtocols(sslEnabledProtocols);
            }
			Protocol protocol = createProtocol(factory, config);
			httpClient.getHostConfiguration().setHost(host, config.securePort, protocol);
		}

        httpClient.getParams().setSoTimeout(soTimeout);
        httpClient.getParams().setConnectionManagerTimeout(connectionManagerTimeout);
        httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(connectionTimeout);
		
		return httpClient;
	}
1355677
private void setupProxyIfNeeded(HttpClientBuilder builder) {
        if (httpProxy != null) {
            builder.setProxy(new HttpHost(httpProxy.getHost(),httpProxy.getPort()));
            if (httpProxy.getUser() != null) {
                AuthScope proxyAuthScope = new AuthScope(httpProxy.getHost(),httpProxy.getPort());
                UsernamePasswordCredentials proxyCredentials = new UsernamePasswordCredentials(httpProxy.getUser(),httpProxy.getPass());
                CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
                credentialsProvider.setCredentials(proxyAuthScope,proxyCredentials);
                builder.setDefaultCredentialsProvider(credentialsProvider);
            }
        }
    }
1263354
function HttpsProxyAgent (opts) {
  if (!(this instanceof HttpsProxyAgent)) return new HttpsProxyAgent(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!');
  debug('creating new HttpsProxyAgent instance: %o', opts);
  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 ? /^https:?$/i.test(proxy.protocol) : 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;
    delete proxy.pathname;
  }

  this.proxy = proxy;
}
481231
def importExistingServerCertificate(self, alias, certPassword, certFile):
        """"""
        url = self._url + "/sslcertificates/importExistingServerCertificate"
        files = {}
        files['certFile'] = certFile
        params = {
            "f" : "json",
            "alias" : alias,
            "certPassword" : certPassword
        }
        return self._post(url=url,
                            param_dict=params,
                            securityHandler=self._securityHandler,
                            files=files,
                            proxy_url=self._proxy_url,
                            proxy_port=self._proxy_port)
1216837
def run(cutouts, hostname="localhost", port=DEFAULT_PORT):
  """"""
  def handler(*args):
    return ViewerServerHandler(cutouts, *args)

  myServer = HTTPServer((hostname, port), handler)
  print("Viewer server listening to http://{}:{}".format(hostname, port))
  try:
    myServer.serve_forever()
  except KeyboardInterrupt:
    # extra \n to prevent display of "^CContinuing"
    print("\nContinuing program execution...")
  finally:
    myServer.server_close()
601083
def addServer(self, normalPort, sslPort, f, name):
        
        tcp = internet.TCPServer(normalPort, f)
        tcp.setName(name)
        self.servers.append(tcp)
        if sslPort is not None:
            ssl = internet.SSLServer(sslPort, f, contextFactory=self.sslfac)
            ssl.setName(name+'s')
            self.servers.append(ssl)
175033
def run(self):
        
        server_address = (self.host, self.port)
        threading = True
        if threading:
            httpd_cls = type('WSGIServer', (ThreadingMixIn, WSGIServer), {})
        else:
            httpd_cls = WSGIServer
        self.httpd = httpd_cls(server_address, WSGIRequestHandler, ipv6=False)
        wsgi_handler = get_internal_wsgi_application()
        self.httpd.set_app(wsgi_handler)
        self.is_ready.set()
        self.httpd.serve_forever()
482531
public void activate(InetAddress host, int port, Collection<String> nonProxyHosts) {
        for (String scheme : new String[] {"http", "https"}) {
            String currentProxyHost = System.getProperty(scheme + ".proxyHost");
            String currentProxyPort = System.getProperty(scheme + ".proxyPort");
            if (currentProxyHost != null) {
                originalProxies.put(scheme, new InetSocketAddress(currentProxyHost, Integer.parseInt(currentProxyPort)));
            }
            System.setProperty(scheme + ".proxyHost", new InetSocketAddress(host, port).getHostString());
            System.setProperty(scheme + ".proxyPort", Integer.toString(port));
        }

        String currentNonProxyHosts = System.getProperty("http.nonProxyHosts");
        if (currentNonProxyHosts == null) {
            originalNonProxyHosts.clear();
        } else {
            for (String nonProxyHost : Splitter.on('|').split(currentNonProxyHosts)) {
                originalNonProxyHosts.add(nonProxyHost);
            }
        }
        System.setProperty("http.nonProxyHosts", Joiner.on('|').join(nonProxyHosts));
    }