Merge "fix convert failed caused by NoneType 'createopts'"
[tools/mic.git] / mic / utils / proxy.py
1 #!/usr/bin/python -tt
2 #
3 # Copyright (c) 2010, 2011 Intel, Inc.
4 #
5 # This program is free software; you can redistribute it and/or modify it
6 # under the terms of the GNU General Public License as published by the Free
7 # Software Foundation; version 2 of the License
8 #
9 # This program is distributed in the hope that it will be useful, but
10 # WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
11 # or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
12 # for more details.
13 #
14 # You should have received a copy of the GNU General Public License along
15 # with this program; if not, write to the Free Software Foundation, Inc., 59
16 # Temple Place - Suite 330, Boston, MA 02111-1307, USA.
17
18 import os
19 import urlparse
20
21 _my_proxies = {}
22 _my_noproxy = None
23 _my_noproxy_list = []
24
25 def set_proxy_environ():
26     global _my_noproxy, _my_proxies
27     if not _my_proxies:
28         return
29     for key in _my_proxies.keys():
30         os.environ[key + "_proxy"] = _my_proxies[key]
31     if not _my_noproxy:
32         return
33     os.environ["no_proxy"] = _my_noproxy
34
35 def unset_proxy_environ():
36    if os.environ.has_key("http_proxy"):
37        del os.environ["http_proxy"]
38    if os.environ.has_key("https_proxy"):
39        del os.environ["https_proxy"]
40    if os.environ.has_key("ftp_proxy"):
41        del os.environ["ftp_proxy"]
42    if os.environ.has_key("all_proxy"):
43        del os.environ["all_proxy"]
44    if os.environ.has_key("no_proxy"):
45        del os.environ["no_proxy"]
46    if os.environ.has_key("HTTP_PROXY"):
47        del os.environ["HTTP_PROXY"]
48    if os.environ.has_key("HTTPS_PROXY"):
49        del os.environ["HTTPS_PROXY"]
50    if os.environ.has_key("FTP_PROXY"):
51        del os.environ["FTP_PROXY"]
52    if os.environ.has_key("ALL_PROXY"):
53        del os.environ["ALL_PROXY"]
54    if os.environ.has_key("NO_PROXY"):
55        del os.environ["NO_PROXY"]
56
57 def _set_proxies(proxy = None, no_proxy = None):
58     """Return a dictionary of scheme -> proxy server URL mappings."""
59     global _my_noproxy, _my_proxies
60     _my_proxies = {}
61     _my_noproxy = None
62     proxies = []
63     if proxy:
64        proxies.append(("http_proxy", proxy))
65     if no_proxy:
66        proxies.append(("no_proxy", no_proxy))
67
68     """Get proxy settings from environment variables if not provided"""
69     if not proxy and not no_proxy:
70        proxies = os.environ.items()
71
72        """ Remove proxy env variables, urllib2 can't handle them correctly """
73        unset_proxy_environ()
74
75     for name, value in proxies:
76         name = name.lower()
77         if value and name[-6:] == '_proxy':
78             if name[0:2] != "no":
79                 _my_proxies[name[:-6]] = value
80             else:
81                 _my_noproxy = value
82
83 def _ip_to_int(ip):
84     ipint=0
85     shift=24
86     for dec in ip.split("."):
87         ipint |= int(dec) << shift
88         shift -= 8
89     return ipint
90
91 def _int_to_ip(val):
92     ipaddr=""
93     shift=0
94     for i in range(4):
95         dec = val >> shift
96         dec &= 0xff
97         ipaddr = ".%d%s" % (dec, ipaddr)
98         shift += 8
99     return ipaddr[1:]
100
101 def _isip(host):
102     if host.replace(".", "").isdigit():
103         return True
104     return False
105
106 def _set_noproxy_list():
107     global _my_noproxy, _my_noproxy_list
108     _my_noproxy_list = []
109     if not _my_noproxy:
110         return
111     for item in _my_noproxy.split(","):
112         item = item.strip()
113         if not item:
114             continue
115         if item[0] != '.' and item.find("/") == -1:
116             """ Need to match it """
117             _my_noproxy_list.append({"match":0,"needle":item})
118         elif item[0] == '.':
119             """ Need to match at tail """
120             _my_noproxy_list.append({"match":1,"needle":item})
121         elif item.find("/") > 3:
122             """ IP/MASK, need to match at head """
123             needle = item[0:item.find("/")].strip()
124             ip = _ip_to_int(needle)
125             netmask = 0
126             mask = item[item.find("/")+1:].strip()
127
128             if mask.isdigit():
129                 netmask = int(mask)
130                 netmask = ~((1<<(32-netmask)) - 1)
131                 ip &= netmask
132             else:
133                 shift=24
134                 netmask=0
135                 for dec in mask.split("."):
136                     netmask |= int(dec) << shift
137                     shift -= 8
138                 ip &= netmask
139             _my_noproxy_list.append({"match":2,"needle":ip,"netmask":netmask})
140
141 def _isnoproxy(url):
142     (scheme, host, path, parm, query, frag) = urlparse.urlparse(url)
143     if '@' in host:
144         user_pass, host = host.split('@', 1)
145     if ':' in host:
146         host, port = host.split(':', 1)
147     hostisip = _isip(host)
148     for item in _my_noproxy_list:
149         if hostisip and item["match"] <= 1:
150             continue
151         if item["match"] == 2 and hostisip:
152             if (_ip_to_int(host) & item["netmask"]) == item["needle"]:
153                 return True
154         if item["match"] == 0:
155             if host == item["needle"]:
156                 return True
157         if item["match"] == 1:
158             if host.rfind(item["needle"]) > 0:
159                 return True
160     return False
161
162 def set_proxies(proxy = None, no_proxy = None):
163     _set_proxies(proxy, no_proxy)
164     _set_noproxy_list()
165     set_proxy_environ()
166
167 def get_proxy_for(url):
168     if url[0:4] == "file" or _isnoproxy(url):
169         return None
170     type = url[0:url.index(":")]
171     proxy = None
172     if _my_proxies.has_key(type):
173         proxy = _my_proxies[type]
174     elif _my_proxies.has_key("http"):
175         proxy = _my_proxies["http"]
176     else:
177         proxy = None
178     return proxy
179