Exemplo n.º 1
0
def pac_context_for_url(url, proxy_auth=None):
    """
    This context manager provides a simple way to add rudimentary PAC functionality
    to code that cannot be modified to use :class:`PACSession`,
    but obeys the ``HTTP_PROXY`` and ``HTTPS_PROXY`` environment variables.

    Upon entering this context, PAC discovery occurs with default parameters.
    If a PAC is found, then it's asked for the proxy to use for the given URL.
    The proxy environment variables are then set accordingly.

    Note that this provides a very simplified PAC experience that's insufficient for some scenarios.

    :param url: Consult the PAC for the proxy to use for this URL.
    :param requests.auth.HTTPProxyAuth proxy_auth: Username and password proxy authentication.
    """
    prev_http_proxy, prev_https_proxy = os.environ.get(
        'HTTP_PROXY'), os.environ.get('HTTPS_PROXY')
    pac = get_pac()
    if pac:
        resolver = ProxyResolver(pac, proxy_auth=proxy_auth)
        proxies = resolver.get_proxy_for_requests(url)
        # Cannot set None for environ. (#27)
        os.environ['HTTP_PROXY'] = proxies.get('http') or ''
        os.environ['HTTPS_PROXY'] = proxies.get('https') or ''
    yield
    if prev_http_proxy:
        os.environ['HTTP_PROXY'] = prev_http_proxy
    elif 'HTTP_PROXY' in os.environ:
        del os.environ['HTTP_PROXY']
    if prev_https_proxy:
        os.environ['HTTPS_PROXY'] = prev_https_proxy
    elif 'HTTPS_PROXY' in os.environ:
        del os.environ['HTTPS_PROXY']
Exemplo n.º 2
0
class AutomaticProxy(Proxy):
    """
    The AutomaticProxy relies on proxy auto-config files (or PAC files).

    The PAC file can be retrieved from a web address, or its JavaScript
    content can be directly passed to the constructor.

    If the pac_url and the js arguments are both missing:
       - macOS: pypac will automatically try to retrieve
                the default PAC file address in the system preferences
       - Windows: pypac will automatically try to retrieve
                  the default PAC file address in the registry
    """

    category = "Automatic"

    def __init__(self, pac_url: str = None, js: str = None, **kwargs: Any) -> None:
        super().__init__(**kwargs)
        if pac_url and "://" not in pac_url:
            pac_url = "http://" + pac_url
        self.pac_url = pac_url
        self._js = js
        self._pac_file = get_pac(
            url=pac_url,
            js=js,
            allowed_content_types=[
                "application/octet-stream",
                "application/x-ns-proxy-autoconfig",
                "application/x-javascript-config",
            ],
        )
        self._resolver = ProxyResolver(self._pac_file)

    def settings(self, url: str = None, **kwargs: Any) -> Dict[str, Any]:
        return self._resolver.get_proxy_for_requests(url)
Exemplo n.º 3
0
def pac_context_for_url(url, proxy_auth=None):
    """
    This context manager provides a simple way to add rudimentary PAC functionality
    to code that cannot be modified to use :class:`PACSession`,
    but obeys the ``HTTP_PROXY`` and ``HTTPS_PROXY`` environment variables.

    Upon entering this context, PAC discovery occurs with default parameters.
    If a PAC is found, then it's asked for the proxy to use for the given URL.
    The proxy environment variables are then set accordingly.

    Note that this provides a very simplified PAC experience that's insufficient for some scenarios.

    :param url: Consult the PAC for the proxy to use for this URL.
    :param requests.auth.HTTPProxyAuth proxy_auth: Username and password proxy authentication.
    """
    prev_http_proxy, prev_https_proxy = os.environ.get('HTTP_PROXY'), os.environ.get('HTTPS_PROXY')
    pac = get_pac()
    if pac:
        resolver = ProxyResolver(pac, proxy_auth=proxy_auth)
        proxies = resolver.get_proxy_for_requests(url)
        # Cannot set None for environ. (#27)
        os.environ['HTTP_PROXY'] = proxies.get('http') or ''
        os.environ['HTTPS_PROXY'] = proxies.get('https') or ''
    yield
    if prev_http_proxy:
        os.environ['HTTP_PROXY'] = prev_http_proxy
    elif 'HTTP_PROXY' in os.environ:
        del os.environ['HTTP_PROXY']
    if prev_https_proxy:
        os.environ['HTTPS_PROXY'] = prev_https_proxy
    elif 'HTTPS_PROXY' in os.environ:
        del os.environ['HTTPS_PROXY']
Exemplo n.º 4
0
    def resolve_proxy(self, target_url=None):
        if not self.proxy:
            return None
        elif self.proxy == PROXY_TYPE_PAC:
            pac_file = PacAPI.get_pac()
            if not pac_file:
                return None
            proxy_resolver = PacProxyResolver(pac_file)

            url_to_resolve = target_url
            if not url_to_resolve and self.api:
                url_to_resolve = self.api
            if not url_to_resolve:
                url_to_resolve = PROXY_PAC_DEFAULT_URL

            return proxy_resolver.get_proxy_for_requests(url_to_resolve)
        else:
            return {'http': self.proxy, 'https': self.proxy, 'ftp': self.proxy}
Exemplo n.º 5
0
class AutomaticProxy(Proxy):
    """
    The AutomaticProxy relies on proxy auto-config files (or PAC files).

    The PAC file can be retrieved from a web address, or its JavaScript
    content can be directly passed to the constructor.

    If the pac_url and the js arguments are both missing:
       - macOS: pypac will automatically try to retrieve
                the default PAC file address in the system preferences
       - Windows: pypac will automatically try to retrieve
                  the default PAC file address in the registry
    """

    category = "Automatic"

    def __init__(self, *, url: str = "", pac_url: str = "") -> None:
        args: Dict[str, Any] = {}

        if pac_url:
            # Load the PAC file as PyPAC won't do it for us
            if pac_url.startswith("file:"):
                with open(pac_url.replace("file://", "")) as pac:
                    args["js"] = pac.read()
            else:
                args["url"] = pac_url
                args["allowed_content_types"] = [
                    "application/octet-stream",
                    "application/x-ns-proxy-autoconfig",
                    "application/x-javascript-config",
                ]

        self.pac_url = pac_url
        self._pac_file = get_pac(**args)
        self._resolver = ProxyResolver(self._pac_file)

    def settings(self, *, url: str = None) -> Dict[str, Any]:
        ret: Dict[str, Any] = self._resolver.get_proxy_for_requests(url)
        return ret
Exemplo n.º 6
0
class AutomaticProxy(Proxy):
    """
    The AutomaticProxy relies on proxy auto-config files (or PAC files).

    The PAC file can be retrieved from a web address, or its JavaScript
    content can be directly passed to the constructor.

    If the pac_url and the js arguments are both missing:
       - macOS: pypac will automatically try to retrieve
                the default PAC file address in the system preferences
       - Windows: pypac will automatically try to retrieve
                  the default PAC file address in the registry
    """

    category = "Automatic"

    def __init__(self,
                 pac_url: str = None,
                 js: str = None,
                 **kwargs: Any) -> None:
        super().__init__(**kwargs)
        if pac_url and "://" not in pac_url:
            pac_url = "http://" + pac_url
        self.pac_url = pac_url
        self._js = js
        self._pac_file = get_pac(
            url=pac_url,
            js=js,
            allowed_content_types=[
                "application/octet-stream",
                "application/x-ns-proxy-autoconfig",
                "application/x-javascript-config",
            ],
        )
        self._resolver = ProxyResolver(self._pac_file)

    def settings(self, url: str = None, **kwargs: Any) -> Dict[str, Any]:
        return self._resolver.get_proxy_for_requests(url)