Merge "display all rpm debug messages in debug mode" into devel
[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 re
20 import urlparse
21
22 _my_proxies = {}
23 _my_noproxy = None
24 _my_noproxy_list = []
25
26 def set_proxy_environ():
27     global _my_noproxy, _my_proxies
28     if not _my_proxies:
29         return
30     for key in _my_proxies.keys():
31         os.environ[key + "_proxy"] = _my_proxies[key]
32     if not _my_noproxy:
33         return
34     os.environ["no_proxy"] = _my_noproxy
35
36 def unset_proxy_environ():
37     for env in ('http_proxy',
38                 'https_proxy',
39                 'ftp_proxy',
40                 'all_proxy'):
41         if env in os.environ:
42             del os.environ[env]
43
44         env_upper = env.upper()
45         if env_upper in os.environ:
46             del os.environ[env_upper]
47
48 def _set_proxies(proxy = None, no_proxy = None):
49     """Return a dictionary of scheme -> proxy server URL mappings.
50     """
51
52     global _my_noproxy, _my_proxies
53     _my_proxies = {}
54     _my_noproxy = None
55     proxies = []
56     if proxy:
57         proxies.append(("http_proxy", proxy))
58     if no_proxy:
59         proxies.append(("no_proxy", no_proxy))
60
61     # Get proxy settings from environment if not provided
62     if not proxy and not no_proxy:
63         proxies = os.environ.items()
64
65         # Remove proxy env variables, urllib2 can't handle them correctly
66         unset_proxy_environ()
67
68     for name, value in proxies:
69         name = name.lower()
70         if value and name[-6:] == '_proxy':
71             if name[0:2] != "no":
72                 _my_proxies[name[:-6]] = value
73             else:
74                 _my_noproxy = value
75
76 def _ip_to_int(ip):
77     ipint = 0
78     shift = 24
79     for dec in ip.split("."):
80         if not dec.isdigit():
81             continue
82         ipint |= int(dec) << shift
83         shift -= 8
84     return ipint
85
86 def _int_to_ip(val):
87     ipaddr = ""
88     shift = 0
89     for i in range(4):
90         dec = val >> shift
91         dec &= 0xff
92         ipaddr = ".%d%s" % (dec, ipaddr)
93         shift += 8
94     return ipaddr[1:]
95
96 def _isip(host):
97     if host.replace(".", "").isdigit():
98         return True
99     return False
100
101 def _set_noproxy_list():
102     global _my_noproxy, _my_noproxy_list
103     _my_noproxy_list = []
104     if not _my_noproxy:
105         return
106     for item in _my_noproxy.split(","):
107         item = item.strip()
108         if not item:
109             continue
110
111         if item[0] != '.' and item.find("/") == -1:
112             # Need to match it
113             _my_noproxy_list.append({"match":0, "needle":item})
114
115         elif item[0] == '.':
116             # Need to match at tail
117             _my_noproxy_list.append({"match":1, "needle":item})
118
119         elif item.find("/") > 3:
120             # IP/MASK, need to match at head
121             needle = item[0:item.find("/")].strip()
122             ip = _ip_to_int(needle)
123             netmask = 0
124             mask = item[item.find("/")+1:].strip()
125
126             if mask.isdigit():
127                 netmask = int(mask)
128                 netmask = ~((1<<(32-netmask)) - 1)
129                 ip &= netmask
130             else:
131                 shift = 24
132                 netmask = 0
133                 for dec in mask.split("."):
134                     if not dec.isdigit():
135                         continue
136                     netmask |= int(dec) << shift
137                     shift -= 8
138                 ip &= netmask
139
140             _my_noproxy_list.append({"match":2, "needle":ip, "netmask":netmask})
141
142 def _isnoproxy(url):
143     host = urlparse.urlparse(url)[1]
144     # urlparse.urlparse(url) returns (scheme, host, path, parm, query, frag)
145
146     if '@' in host:
147         user_pass, host = host.split('@', 1)
148
149     if ':' in host:
150         host, port = host.split(':', 1)
151
152     hostisip = _isip(host)
153     for item in _my_noproxy_list:
154         if hostisip and item["match"] == 1:
155             continue
156
157         if item["match"] == 2 and hostisip:
158             if (_ip_to_int(host) & item["netmask"]) == item["needle"]:
159                 return True
160
161         if item["match"] == 0:
162             if host == item["needle"]:
163                 return True
164
165         if item["match"] == 1:
166             if re.match(r".*%s$" % item["needle"], host):
167                 return True
168
169     return False
170
171 def set_proxies(proxy = None, no_proxy = None):
172     _set_proxies(proxy, no_proxy)
173     _set_noproxy_list()
174     set_proxy_environ()
175
176 def get_proxy_for(url):
177     if url.startswith('file:') or _isnoproxy(url):
178         return None
179
180     type = url[0:url.index(":")]
181     proxy = None
182     if _my_proxies.has_key(type):
183         proxy = _my_proxies[type]
184     elif _my_proxies.has_key("http"):
185         proxy = _my_proxies["http"]
186     else:
187         proxy = None
188
189     return proxy