source: sasview/src/sas/sasgui/guiframe/proxy.py @ c155a16

ESS_GUIESS_GUI_DocsESS_GUI_batch_fittingESS_GUI_bumps_abstractionESS_GUI_iss1116ESS_GUI_iss879ESS_GUI_iss959ESS_GUI_openclESS_GUI_orderingESS_GUI_sync_sascalccostrafo411magnetic_scattrelease-4.2.2ticket-1009ticket-1094-headlessticket-1242-2d-resolutionticket-1243ticket-1249ticket885unittest-saveload
Last change on this file since c155a16 was c155a16, checked in by Ricardo Ferraz Leal <ricleal@…>, 7 years ago

Logging is now logger

  • Property mode set to 100644
File size: 6.1 KB
Line 
1#!/usr/bin/env python
2# -*- coding: utf-8 -*-
3import urllib2
4import sys
5import json
6import logging
7import re
8
9
10logger = logging.getLogger()
11
12'''
13HTTP Proxy parser and Connection
14
15connect() function:
16    - auto detects proxy in windows, osx
17    - in ux systems, the http_proxy enviroment variable must be set
18    - if it fails, try to find the proxy.pac address.
19      - parses the file, and looks up for all possible proxies
20'''
21
22
23class Connection(object):
24
25    def __init__(self, url, timeout):
26        self.url = url
27        self.timeout = timeout
28
29    def _get_addresses_of_proxy_pac(self):
30        """
31        Return a list of possible auto proxy .pac files being used,
32        based on the system registry (win32) or system preferences (OSX).
33        @return: list of urls
34        """
35        pac_files = []
36        if sys.platform == 'win32':
37            try:
38                import _winreg as winreg  # used from python 2.0-2.6
39            except:
40                import winreg  # used from python 2.7 onwards
41            net = winreg.OpenKey(
42                winreg.HKEY_CURRENT_USER,
43                "Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings"
44            )
45            n_subs, n_vals, last_mod = winreg.QueryInfoKey(net)
46            subkeys = {}
47            for i in range(n_vals):
48                this_name, this_val, this_type = winreg.EnumValue(net, i)
49                subkeys[this_name] = this_val
50            if 'AutoConfigURL' in subkeys.keys() and len(subkeys['AutoConfigURL']) > 0:
51                pac_files.append(subkeys['AutoConfigURL'])
52        elif sys.platform == 'darwin':
53            import plistlib
54            sys_prefs = plistlib.readPlist(
55                '/Library/Preferences/SystemConfiguration/preferences.plist')
56            networks = sys_prefs['NetworkServices']
57            # loop through each possible network (e.g. Ethernet, Airport...)
58            for network in networks.items():
59                # the first part is a long identifier
60                net_key, network = network
61                if 'ProxyAutoConfigURLString' in network['Proxies'].keys():
62                    pac_files.append(
63                        network['Proxies']['ProxyAutoConfigURLString'])
64        return list(set(pac_files))  # remove redundant ones
65
66    def _parse_proxy_pac(self, pac_urls_list):
67        '''
68        For every pac file url in pac_urls_list, it tryes to connect.
69        If the connection is successful parses the file in search for
70        http proxies.
71        @param pac_urls_list: List with urls for the pac files
72        @return: list with all found http proxies
73        '''
74        proxy_url_list = []
75        for this_pac_url in pac_urls_list:
76            logger.debug('Trying pac file (%s)...' % this_pac_url)
77            try:
78                response = urllib2.urlopen(
79                    this_pac_url, timeout=self.timeout)
80                logger.debug('Succeeded (%s)...' % this_pac_url)
81            except Exception:
82                logger.debug('Failled (%s)...' % this_pac_url)
83                continue
84            pacStr = response.read()
85            possProxies = re.findall(
86                r"PROXY\s([^\s;,:]+:[0-9]{1,5})[^0-9]", pacStr + '\n')
87            for thisPoss in possProxies:
88                prox_url = 'http://' + thisPoss
89                proxy_dic = {'http': prox_url}
90                proxy_url_list.append(proxy_dic)
91        return proxy_url_list
92
93    def _set_proxy(self,proxy_dic=None):
94        '''
95        Sets connection proxy.
96        if proxy_dic is None get's teh proxy from the system.
97        To disable autodetected proxy pass an empty dictionary: {}
98        @param proxy_dic: format: {'http': 'http://www.example.com:3128/'}               
99        '''
100        if proxy_dic is None:
101            # The default is to read the list of proxies from the environment variables <protocol>_proxy.
102            # If no proxy environment variables are set, then in a Windows environment proxy settings are
103            # obtained from the registry's Internet Settings section, and in a Mac OS X environment proxy
104            # information is retrieved from the OS X System Configuration
105            # Framework.
106            proxy = urllib2.ProxyHandler()
107        else:
108            # If proxies is given, it must be a dictionary mapping protocol names to
109            # URLs of proxies.
110            proxy = urllib2.ProxyHandler(proxy_dic)
111        opener = urllib2.build_opener(proxy)
112        urllib2.install_opener(opener)
113   
114   
115   
116   
117    def connect(self):
118        '''
119        Performs the request and gets a response from self.url
120        @return: response object from urllib2.urlopen
121        '''
122        req = urllib2.Request(self.url)
123        response = None
124        try:
125            logger.debug("Trying Direct connection to %s..."%self.url)
126            response = urllib2.urlopen(req, timeout=self.timeout)
127        except Exception, e:
128            logger.debug("Failed!")
129            logger.debug(e)
130            try:
131                logger.debug("Trying to use system proxy if it exists...")
132                self._set_proxy()
133                response = urllib2.urlopen(req, timeout=self.timeout)
134            except Exception, e:
135                logger.debug("Failed!")
136                logger.debug(e)
137                pac_urls = self._get_addresses_of_proxy_pac()
138                proxy_urls = self._parse_proxy_pac(pac_urls)
139                for proxy in proxy_urls:
140                    try:
141                        logger.debug("Trying to use the proxy %s found in proxy.pac configuration"%proxy)
142                        self._set_proxy(proxy)
143                        response = urllib2.urlopen(req, timeout=self.timeout)
144                    except Exception, e:
145                        logger.debug("Failed!")
146                        logger.debug(e)
147        if response is not None:
148            logger.debug("The connection to %s was successful."%self.url)
149        else:
150            logger.warning("Connection to %s failed..."%self.url)
151        return response
152
153
154if __name__ == "__main__":
155    from pprint import pprint
156    c = Connection()
157    response = c.connect()
158    if response is not None:
159        print 50 * '-'
160        content = json.loads(response.read().strip())
161        pprint(content)
Note: See TracBrowser for help on using the repository browser.