Enable a default web proxy
969347
def enable_proxy(self, host, port):
        """"""

        self.proxy = [host, _number(port)]
        self.proxy_enabled = True
340199
def configure_proxy(self, curl_object):
        """"""
        curl_object.setopt(curl_object.PROXY, self._proxy_hostname)
        curl_object.setopt(curl_object.PROXYPORT, self._proxy_port)
        curl_object.setopt(curl_object.PROXYTYPE, curl_object.PROXYTYPE_SOCKS5)
        if self._proxy_user and self._proxy_passwd:
            curl_object.setopt(curl_object.PROXYUSERPWD, '%s:%s' % (self._proxy_user, self._proxy_port))
842290
def get_gconf_http_proxy ():
    """"""
    try:
        import gconf
    except ImportError:
        return None
    try:
        client = gconf.client_get_default()
        if client.get_bool("/system/http_proxy/use_http_proxy"):
            host = client.get_string("/system/http_proxy/host")
            port = client.get_int("/system/http_proxy/port")
            if host:
                if not port:
                    port = 8080
                return "%s:%d" % (host, port)
    except Exception as msg:
        log.debug(LOG_CHECK, "error getting HTTP proxy from gconf: %s", msg)
        pass
    return None
552124
def from_dict(config):
        '''
        
        '''
        return ProxyConfig(
            http=config.get('httpProxy'),
            https=config.get('httpsProxy'),
            ftp=config.get('ftpProxy'),
            no_proxy=config.get('noProxy'),
        )
779484
def generate_proxy(
        prefix, base_url='', verify_ssl=True, middleware=None,
        append_middleware=None, cert=None, timeout=None):
    """"""
    middleware = list(middleware or HttpProxy.proxy_middleware)
    middleware += list(append_middleware or [])

    return type('ProxyClass', (HttpProxy,), {
        'base_url': base_url,
        'reverse_urls': [(prefix, base_url)],
        'verify_ssl': verify_ssl,
        'proxy_middleware': middleware,
        'cert': cert,
        'timeout': timeout
    })
1072602
def endpoint_activate(
    endpoint_id,
    myproxy,
    myproxy_username,
    myproxy_password,
    myproxy_lifetime,
    web,
    no_browser,
    delegate_proxy,
    proxy_lifetime,
    no_autoactivate,
    force,
):
    
    default_myproxy_username = lookup_option(MYPROXY_USERNAME_OPTNAME)
    client = get_client()

    # validate options
    if web + myproxy + bool(delegate_proxy) > 1:
        raise click.UsageError(
            "--web, --myproxy, and --delegate-proxy are mutually exclusive."
        )
    if no_autoactivate and not (myproxy or web or delegate_proxy):
        raise click.UsageError(
            "--no-autoactivate requires another activation method be given."
        )
    if myproxy_username and not myproxy:
        raise click.UsageError("--myproxy-username requires --myproxy.")
    if myproxy_password and not myproxy:
        raise click.UsageError("--myproxy-password requires --myproxy.")
    # NOTE: "0" is a legitimate, though weird, value
    # In the case where someone is setting this value programatically,
    # respecting it behaves more consistently/predictably
    if myproxy_lifetime is not None and not myproxy:
        raise click.UsageError("--myproxy-lifetime requires --myproxy.")
    if no_browser and not web:
        raise click.UsageError("--no-browser requires --web.")
    if proxy_lifetime and not delegate_proxy:
        raise click.UsageError("--proxy-lifetime requires --delegate-proxy.")

    # check if endpoint is already activated unless --force
    if not force:
        res = client.endpoint_autoactivate(endpoint_id, if_expires_in=60)

        if "AlreadyActivated" == res["code"]:
            formatted_print(
                res,
                simple_text=(
                    "Endpoint is already activated. Activation "
                    "expires at {}".format(res["expire_time"])
                ),
            )
            return

    # attempt autoactivation unless --no-autoactivate
    if not no_autoactivate:

        res = client.endpoint_autoactivate(endpoint_id)

        if "AutoActivated" in res["code"]:
            formatted_print(
                res,
                simple_text=(
                    "Autoactivation succeeded with message: {}".format(res["message"])
                ),
            )
            return

        # override potentially confusing autoactivation failure response
        else:
            message = (
                "The endpoint could not be auto-activated.\n\n"
                + activation_requirements_help_text(res, endpoint_id)
            )
            res = {"message": message}

    # myproxy activation
    if myproxy:

        # get username and password
        if not (myproxy_username or default_myproxy_username):
            myproxy_username = click.prompt("Myproxy username")
        if not myproxy_password:
            myproxy_password = click.prompt("Myproxy password", hide_input=True)

        no_server_msg = (
            "This endpoint has no myproxy server "
            "and so cannot be activated through myproxy"
        )

        requirements_data = client.endpoint_get_activation_requirements(
            endpoint_id
        ).data

        if not len(requirements_data["DATA"]):
            raise click.ClickException(no_server_msg)

        for data in requirements_data["DATA"]:
            # skip non-myproxy values
            # although the API does not practice this today, in theory other
            # activation types may have fields with the same names...
            if data["type"] != "myproxy":
                continue

            if data["name"] == "passphrase":
                data["value"] = myproxy_password
            if data["name"] == "username":
                data["value"] = myproxy_username or default_myproxy_username
            if data["name"] == "hostname" and data["value"] is None:
                raise click.ClickException(no_server_msg)
            # NOTE: remember that "0" is a possible value
            if data["name"] == "lifetime_in_hours" and myproxy_lifetime is not None:
                data["value"] = str(myproxy_lifetime)

        res = client.endpoint_activate(endpoint_id, requirements_data)

    # web activation
    elif web:
        url = "https://app.globus.org/file-manager" "?origin_id={}".format(endpoint_id)
        if no_browser or is_remote_session():
            res = {"message": "Web activation url: {}".format(url), "url": url}
        else:
            webbrowser.open(url, new=1)
            res = {"message": "Browser opened to web activation page", "url": url}

    # delegate proxy activation
    elif delegate_proxy:
        requirements_data = client.endpoint_get_activation_requirements(
            endpoint_id
        ).data
        filled_requirements_data = fill_delegate_proxy_activation_requirements(
            requirements_data, delegate_proxy, lifetime_hours=proxy_lifetime or 12
        )
        res = client.endpoint_activate(endpoint_id, filled_requirements_data)

    # output
    formatted_print(res, text_format=FORMAT_TEXT_RAW, response_key="message")
163382
function getProxyUri(uri) {

	if (uri.protocol === 'https:' && env.httpsProxy || uri.protocol === 'http:' && env.httpProxy) {

		if (env.noProxy) {
			var canonicalHost = uri.host.replace(/^\.*/, '.');
			var port = uri.port || (uri.protocol === 'https:' ? '443' : '80');

			var patterns = env.noProxy.split(',');
			for (var i = patterns.length - 1; i >= 0; i--) {
				var pattern = patterns[i].trim().toLowerCase();

				// don't use a proxy at all
				if (pattern === '*') {
					return null;
				}

				// Remove leading * and make sure to have exact one leading dot (.)
				pattern = pattern.replace(/^[\*]+/, '').replace(/^\.*/, '.');

				// add port if no specified
				if (pattern.indexOf(':') === -1) {
					pattern += ':' + port;
				}

				// if host ends with pattern, no proxy should be used
				if (canonicalHost.indexOf(pattern) === canonicalHost.length - pattern.length) {
					return null;
				}
			}
		}

		if (uri.protocol === 'https:' && env.httpsProxy) {
			return env.httpsProxy;
		} else if (uri.protocol === 'http:' && env.httpProxy) {
			return env.httpProxy;
		}
	}

	return null;
}
283985
def _add_chrome_proxy_extension(
        chrome_options, proxy_string, proxy_user, proxy_pass):
    
    if not "".join(sys.argv) == "-c":
        # Single-threaded
        proxy_helper.create_proxy_zip(proxy_string, proxy_user, proxy_pass)
    else:
        # Pytest multi-threaded test
        lock = threading.Lock()
        with lock:
            time.sleep(random.uniform(0.02, 0.15))
            if not os.path.exists(PROXY_ZIP_PATH):
                proxy_helper.create_proxy_zip(
                    proxy_string, proxy_user, proxy_pass)
            time.sleep(random.uniform(0.1, 0.2))
    proxy_zip = PROXY_ZIP_PATH
    if not os.path.exists(PROXY_ZIP_PATH):
        # Handle "Permission denied" on the default proxy.zip path
        proxy_zip = PROXY_ZIP_PATH_2
    chrome_options.add_extension(proxy_zip)
    return chrome_options
1174614
function useProxyIfExternal(connectUrl) {
        if (Core.isChromeApp()) {
            return connectUrl;
        }
        var host = window.location.host;
        if (!_.startsWith(connectUrl, "http://" + host + "/") && !_.startsWith(connectUrl, "https://" + host + "/")) {
            // lets remove the http stuff
            var idx = connectUrl.indexOf("://");
            if (idx > 0) {
                connectUrl = connectUrl.substring(idx + 3);
            }
            // lets replace the : with a /
            connectUrl = connectUrl.replace(":", "/");
            connectUrl = Core.trimLeading(connectUrl, "/");
            connectUrl = Core.trimTrailing(connectUrl, "/");
            connectUrl = Core.url("/proxy/" + connectUrl);
        }
        return connectUrl;
    }
735397
function HttpsProxyingAgent(options) {
  options.tunnel = true;
  ProxyingAgent.call(this, options, https.Agent);
}
453978
def _default_make_pool(http, proxy_info):
    """"""

    if not http.ca_certs:
        http.ca_certs = _certifi_where_for_ssl_version()

    ssl_disabled = http.disable_ssl_certificate_validation

    cert_reqs = 'CERT_REQUIRED' if http.ca_certs and not ssl_disabled else None

    if isinstance(proxy_info, collections.Callable):
        proxy_info = proxy_info()
    if proxy_info:
        if proxy_info.proxy_user and proxy_info.proxy_pass:
            proxy_url = 'http://{}:{}@{}:{}/'.format(
                proxy_info.proxy_user, proxy_info.proxy_pass,
                proxy_info.proxy_host, proxy_info.proxy_port,
            )
            proxy_headers = urllib3.util.request.make_headers(
                proxy_basic_auth='{}:{}'.format(
                    proxy_info.proxy_user, proxy_info.proxy_pass,
                )
            )
        else:
            proxy_url = 'http://{}:{}/'.format(
                proxy_info.proxy_host, proxy_info.proxy_port,
            )
            proxy_headers = {}

        return urllib3.ProxyManager(
            proxy_url=proxy_url,
            proxy_headers=proxy_headers,
            ca_certs=http.ca_certs,
            cert_reqs=cert_reqs,
        )
    return urllib3.PoolManager(
        ca_certs=http.ca_certs,
        cert_reqs=cert_reqs,
    )
747690
def _allows_url (self, url_data, roboturl):
        """"""
        with cache_lock:
            if roboturl in self.cache:
                self.hits += 1
                rp = self.cache[roboturl]
                return rp.can_fetch(self.useragent, url_data.url)
            self.misses += 1
        kwargs = dict(auth=url_data.auth, session=url_data.session)
        if hasattr(url_data, "proxy") and hasattr(url_data, "proxy_type"):
            kwargs["proxies"] = {url_data.proxytype: url_data.proxy}
        rp = robotparser2.RobotFileParser(**kwargs)
        rp.set_url(roboturl)
        rp.read()
        with cache_lock:
            self.cache[roboturl] = rp
        self.add_sitemap_urls(rp, url_data, roboturl)
        return rp.can_fetch(self.useragent, url_data.url)
1297000
def proxy(opts, functions=None, returners=None, whitelist=None, utils=None):
    '''
    
    '''
    ret = LazyLoader(
        _module_dirs(opts, 'proxy'),
        opts,
        tag='proxy',
        pack={'__salt__': functions, '__ret__': returners, '__utils__': utils},
    )

    ret.pack['__proxy__'] = ret

    return ret
1001350
function loadDefault() {
  return {
    port: 8000,
    host: '127.0.0.1',
    root: './',
    logFormat: 'combined',
    middlewares: [
      {
        name: 'cors',
        cfg: {
          origin: true
        }
      },
      {
        name: 'morgan',
        cfg: {}
      },
      {
        name: 'serveStatic',
        cfg: {}
      },
      {
        name: 'serveIndex',
        cfg: {
          icons: true
        }
      }
    ]
  }
}
643794
def setup(self, proxystr='', prompting=True):
        
        self.prompting = prompting
        proxy = self.get_proxy(proxystr)
        if proxy:
            proxy_support = urllib2.ProxyHandler({"http": proxy, "ftp": proxy})
            opener = urllib2.build_opener(proxy_support, urllib2.CacheFTPHandler)
            urllib2.install_opener(opener)
586921
function setProxy($proxyhost, $proxyport, $proxyusername = '', $proxypassword = '', $proxyauthtype = 'basic') {
		if ($proxyhost) {
			$this->proxy = array(
				'host' => $proxyhost,
				'port' => $proxyport,
				'username' => $proxyusername,
				'password' => $proxypassword,
				'authtype' => $proxyauthtype
			);
			if ($proxyusername != '' && $proxypassword != '' && $proxyauthtype = 'basic') {
				$this->setHeader('Proxy-Authorization', ' Basic '.base64_encode($proxyusername.':'.$proxypassword));
			}
		} else {
			$this->debug('remove proxy');
			$proxy = null;
			unsetHeader('Proxy-Authorization');
		}
	}
399518
def set_proxy(self, proxy, update=True):
        
        update_web_driver = False
        if self.current_proxy != proxy:
            # Did we change proxies?
            update_web_driver = True

        self.current_proxy = proxy
        if proxy is None:
            # TODO: Need to be able to remove a proxy if one is set
            pass
        else:
            proxy_parts = cutil.get_proxy_parts(proxy)

            if proxy_parts.get('user') is not None:
                # Proxy has auth, create extension to add to driver
                self.opts.add_extension(self._proxy_extension(proxy_parts))
            else:
                # Use the full proxy address passed in
                self.opts.add_argument('--proxy-server={}'.format(proxy))

        # Recreate webdriver with new proxy settings
        if update_web_driver is True:
            self._update()