Check if proxy conf exists and update
16286
def _proxy_conf_file(proxyfile, test):
    '''
    
    '''
    changes_old = []
    changes_new = []
    success = True
    if not os.path.exists(proxyfile):
        try:
            if not test:
                changes_new.append(_write_proxy_conf(proxyfile))
                msg = 'Salt Proxy: Wrote proxy conf {0}'.format(proxyfile)
            else:
                msg = 'Salt Proxy: Update required to proxy conf {0}' \
                    .format(proxyfile)
        except (OSError, IOError) as err:
            success = False
            msg = 'Salt Proxy: Error writing proxy file {0}'.format(err)
            log.error(msg)
            changes_new.append(msg)
        changes_new.append(msg)
        log.debug(msg)
    else:
        msg = 'Salt Proxy: {0} already exists, skipping'.format(proxyfile)
        changes_old.append(msg)
        log.debug(msg)
    return success, changes_new, changes_old
510190
def update(self, **kwargs):
        
        if 'useProxyServer' in kwargs and kwargs['useProxyServer'] == 'enabled':
            if 'proxyServerPool' not in kwargs:
                error = 'Missing proxyServerPool parameter value.'
                raise MissingUpdateParameter(error)
        if hasattr(self, 'useProxyServer'):
            if getattr(self, 'useProxyServer') == 'enabled' and 'proxyServerPool' not in self.__dict__:
                error = 'Missing proxyServerPool parameter value.'
                raise MissingUpdateParameter(error)

        self._update(**kwargs)

        return self
16993
def _update(self, **kwargs):
        
        updated = False
        if 'proxy_server' in kwargs:
            proxy_server = kwargs.get('proxy_server')
            if not proxy_server and self._inspected_service_ref:
                self.protocol_agent_values.pop('inspected_service_ref', None)
                updated = True
            elif isinstance(proxy_server, ProxyServer):
                # Need the inspected service reference for the protocol
                enabled_services = {svc.name:svc.href for svc in proxy_server.inspected_services}
                
                if self.protocol_agent.name not in enabled_services:
                    raise MissingDependency('The specified ProxyServer %r does not enable '
                        'the required protocol %s' % (proxy_server.name, self.protocol_agent.name))
                
                if self._inspected_service_ref != enabled_services.get(self.protocol_agent.name):
                    self.protocol_agent_values['inspected_service_ref'] = enabled_services.get(
                        self.protocol_agent.name)
                    updated = True
        return updated
847350
def _GetProxies(self):
    """"""
    # Detect proxies from the OS environment.
    result = client_utils.FindProxies()

    # Also try to connect directly if all proxies fail.
    result.append("")

    # Also try all proxies configured in the config system.
    result.extend(config.CONFIG["Client.proxy_servers"])

    return result
1080455
def just_find_proxy(pacfile, url, host=None):
  
  if not os.path.isfile(pacfile):
    raise IOError('Pac file does not exist: {}'.format(pacfile))
  init()
  parse_pac(pacfile)
  proxy = find_proxy(url,host)
  cleanup()
  return proxy
352192
def acquire_proxy(self, host, port, use_ssl=False, host_key=None,
                      tunnel=True):
        '''
        '''
        if self._host_filter and not self._host_filter.test(host):
            connection = yield from \
                super().acquire(host, port, use_ssl, host_key)

            return connection

        host_key = host_key or (host, port, use_ssl)
        proxy_host, proxy_port = self._proxy_address

        connection = yield from super().acquire(
            proxy_host, proxy_port, self._proxy_ssl, host_key=host_key
        )
        connection.proxied = True

        _logger.debug('Request for proxy connection.')

        if connection.closed():
            _logger.debug('Connecting to proxy.')
            yield from connection.connect()

            if tunnel:
                yield from self._establish_tunnel(connection, (host, port))

            if use_ssl:
                ssl_connection = yield from connection.start_tls(self._ssl_context)
                ssl_connection.proxied = True
                ssl_connection.tunneled = True

                self._connection_map[ssl_connection] = connection
                connection.wrapped_connection = ssl_connection

                return ssl_connection

        if connection.wrapped_connection:
            ssl_connection = connection.wrapped_connection
            self._connection_map[ssl_connection] = connection
            return ssl_connection
        else:
            return connection
831629
def init(opts):
    '''
    
    '''
    if CONFIG_BASE_URL in opts['proxy']:
        CONFIG[CONFIG_BASE_URL] = opts['proxy'][CONFIG_BASE_URL]
    else:
        log.error('missing proxy property %s', CONFIG_BASE_URL)
    log.debug('CONFIG: %s', CONFIG)
223339
def _is_updated(old_conf, new_conf):
    '''
    
    '''
    changed = {}

    # Dirty json hacking to get parameters in the same format
    new_conf = _json_to_unicode(salt.utils.json.loads(
        salt.utils.json.dumps(new_conf, ensure_ascii=False)))
    old_conf = salt.utils.json.loads(salt.utils.json.dumps(old_conf, ensure_ascii=False))

    for key, value in old_conf.items():
        oldval = six.text_type(value).lower()
        if key in new_conf:
            newval = six.text_type(new_conf[key]).lower()
        if oldval == 'null' or oldval == 'none':
            oldval = ''
        if key in new_conf and newval != oldval:
            changed[key] = {'old': oldval, 'new': newval}
    return changed
552124
def from_dict(config):
        '''
        
        '''
        return ProxyConfig(
            http=config.get('httpProxy'),
            https=config.get('httpsProxy'),
            ftp=config.get('ftpProxy'),
            no_proxy=config.get('noProxy'),
        )
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');
		}
	}
411496
def _configure_proxy(self):
        """"""
        if os.getenv('HTTP_PROXY') or os.getenv('HTTPS_PROXY'):
            # TODO: is this appropriate?
            # don't change proxy settings if the OS already has them configured.
            return True

        proxy_enabled = False
        if self.args.proxy_host is not None and self.args.proxy_port is not None:
            if self.args.proxy_user is not None and self.args.proxy_pass is not None:
                proxy_user = quote(self.args.proxy_user, safe='~')
                proxy_pass = quote(self.args.proxy_pass, safe='~')

                # proxy url with auth
                proxy_url = '{}:{}@{}:{}'.format(
                    proxy_user, proxy_pass, self.args.proxy_host, self.args.proxy_port
                )
            else:
                # proxy url without auth
                proxy_url = '{}:{}'.format(self.args.proxy_host, self.args.proxy_port)

            os.putenv('HTTP_PROXY', 'http://{}'.format(proxy_url))
            os.putenv('HTTPS_PROXY', 'https://{}'.format(proxy_url))

            print(
                'Using Proxy Server: {}{}:{}.'.format(
                    c.Fore.CYAN, self.args.proxy_host, self.args.proxy_port
                )
            )
            proxy_enabled = True
        return proxy_enabled
889217
protected function configureEgressProxy()
    {
        if (!Environment::getEnv('SS_OUTBOUND_PROXY')
            || !Environment::getEnv('SS_OUTBOUND_PROXY_PORT')
        ) {
            return;
        }

        $proxy = Environment::getEnv('SS_OUTBOUND_PROXY');
        $proxyPort = Environment::getEnv('SS_OUTBOUND_PROXY_PORT');

        /*
         * This sets the environment variables so they are available in
         * external calls executed by exec() such as curl.
         * Environment::setEnv() would only availabe in context of SilverStripe.
         * Environment::getEnv() will fallback to getenv() and will therefore
         * fetch the variables
         */
        putenv('http_proxy=' .  $proxy . ':' . $proxyPort);
        putenv('https_proxy=' . $proxy . ':' . $proxyPort);
    }
748253
public static void applyProxy(Proxy use) {
    System.setProperty("java.net.useSystemProxies", "false");
    System.setProperty("http.proxyHost", use.getIp());
    System.setProperty("http.proxyPort", String.valueOf(use.getPort()));
    System.setProperty("https.proxyHost", use.getIp());
    System.setProperty("https.proxyPort", String.valueOf(use.getPort()));
  }
1204727
def get_proxies(self):
        
        # Get proxy from ENV or Config
        proxies = None
        proxy_auth = None
        no_proxy = os.environ.get('NO_PROXY')
        logger.debug("NO PROXY: %s", no_proxy)

        # CONF PROXY TAKES PRECEDENCE OVER ENV PROXY
        conf_proxy = self.config.proxy
        if ((conf_proxy is not None and
             conf_proxy.lower() != 'None'.lower() and
             conf_proxy != "")):
            if '@' in conf_proxy:
                scheme = conf_proxy.split(':')[0] + '://'
                logger.debug("Proxy Scheme: %s", scheme)
                location = conf_proxy.split('@')[1]
                logger.debug("Proxy Location: %s", location)
                username = conf_proxy.split(
                    '@')[0].split(':')[1].replace('/', '')
                logger.debug("Proxy User: %s", username)
                password = conf_proxy.split('@')[0].split(':')[2]
                proxy_auth = requests.auth._basic_auth_str(username, password)
                conf_proxy = scheme + location
            logger.debug("CONF Proxy: %s", conf_proxy)
            proxies = {"https": conf_proxy}

        # HANDLE NO PROXY CONF PROXY EXCEPTION VERBIAGE
        if no_proxy and conf_proxy:
            logger.debug("You have environment variable NO_PROXY set "
                         "as well as 'proxy' set in your configuration file. "
                         "NO_PROXY environment variable will be ignored.")

        # IF NO CONF PROXY, GET ENV PROXY AND NO PROXY
        if proxies is None:
            env_proxy = os.environ.get('HTTPS_PROXY')
            if env_proxy:
                if '@' in env_proxy:
                    scheme = env_proxy.split(':')[0] + '://'
                    logger.debug("Proxy Scheme: %s", scheme)
                    location = env_proxy.split('@')[1]
                    logger.debug("Proxy Location: %s", location)
                    username = env_proxy.split('@')[0].split(':')[1].replace('/', '')
                    logger.debug("Proxy User: %s", username)
                    password = env_proxy.split('@')[0].split(':')[2]
                    proxy_auth = requests.auth._basic_auth_str(username, password)
                    env_proxy = scheme + location
                logger.debug("ENV Proxy: %s", env_proxy)
                proxies = {"https": env_proxy}
            if no_proxy:
                insights_service_host = urlparse(self.base_url).hostname
                logger.debug('Found NO_PROXY set. Checking NO_PROXY %s against base URL %s.', no_proxy, insights_service_host)
                for no_proxy_host in no_proxy.split(','):
                    logger.debug('Checking %s against %s', no_proxy_host, insights_service_host)
                    if no_proxy_host == '*':
                        proxies = None
                        proxy_auth = None
                        logger.debug('Found NO_PROXY asterisk(*) wildcard, disabling all proxies.')
                        break
                    elif no_proxy_host.startswith('.') or no_proxy_host.startswith('*'):
                        if insights_service_host.endswith(no_proxy_host.replace('*', '')):
                            proxies = None
                            proxy_auth = None
                            logger.debug('Found NO_PROXY range %s matching %s', no_proxy_host, insights_service_host)
                            break
                    elif no_proxy_host == insights_service_host:
                        proxies = None
                        proxy_auth = None
                        logger.debug('Found NO_PROXY %s exactly matching %s', no_proxy_host, insights_service_host)
                        break

        self.proxies = proxies
        self.proxy_auth = proxy_auth
150515
def update(self, password=values.unset):
        
        return self._proxy.update(password=password, )
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();
      });
    });
  });
}
736389
def validate_proxy_args(cls, *args):
        """"""
        supplied_proxies = Counter((not arg for arg in (*args,))).get(False)
        if not supplied_proxies:
            return
        elif supplied_proxies > 1:
            raise RaccoonException("Must specify only one of the following:\n"
                                   "--tor-routing, --proxy-list, --proxy")