Merge release-0.28.17 from 'tools/mic'
[platform/upstream/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 from mic import msger
22
23 _my_proxies = {}
24 _my_noproxy = None
25 _my_noproxy_list = []
26
27 def set_proxy_environ():
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
107     #solve in /etc/enviroment contains command like `echo 165.xxx.xxx.{1..255} | sed 's/ /,/g'``
108     _my_noproxy_bak = _my_noproxy
109     start = _my_noproxy.find("`")
110     while(start < len(_my_noproxy) and start != -1):
111         start = _my_noproxy.find("`",start)
112         end = _my_noproxy.find("`",start+1)
113         cmd = _my_noproxy[start+1:end]
114         pstr = _my_noproxy[start:end+1]
115         start = end + 1
116
117         _my_noproxy=_my_noproxy.replace(pstr,len(pstr)*" ")
118         try:
119             c_result = os.popen(cmd).readlines()
120             if len(c_result) == 0:
121                 continue
122         except Exception as e:
123             msger.warning(str(e))
124             continue
125         to_list = c_result[0].strip("\n").split(",")
126         _my_noproxy_list.extend(to_list)
127
128     for item in _my_noproxy.split(","):
129         item = item.strip()
130         if not item:
131             continue
132
133         if item[0] != '.' and item.find("/") == -1:
134             # Need to match it
135             _my_noproxy_list.append({"match":0, "needle":item})
136
137         elif item[0] == '.':
138             # Need to match at tail
139             _my_noproxy_list.append({"match":1, "needle":item})
140
141         elif item.find("/") > 3:
142             # IP/MASK, need to match at head
143             needle = item[0:item.find("/")].strip()
144             ip = _ip_to_int(needle)
145             netmask = 0
146             mask = item[item.find("/")+1:].strip()
147
148             if mask.isdigit():
149                 netmask = int(mask)
150                 netmask = ~((1<<(32-netmask)) - 1)
151                 ip &= netmask
152             else:
153                 shift = 24
154                 netmask = 0
155                 for dec in mask.split("."):
156                     if not dec.isdigit():
157                         continue
158                     netmask |= int(dec) << shift
159                     shift -= 8
160                 ip &= netmask
161
162             _my_noproxy_list.append({"match":2, "needle":ip, "netmask":netmask})
163     _my_noproxy = _my_noproxy_bak
164
165 def _isnoproxy(url):
166     host = urlparse.urlparse(url)[1]
167     # urlparse.urlparse(url) returns (scheme, host, path, parm, query, frag)
168
169     if '@' in host:
170         user_pass, host = host.split('@', 1)
171
172     if ':' in host:
173         host, port = host.split(':', 1)
174
175     hostisip = _isip(host)
176     for item in _my_noproxy_list:
177         if hostisip and item["match"] == 1:
178             continue
179
180         if item["match"] == 2 and hostisip:
181             if (_ip_to_int(host) & item["netmask"]) == item["needle"]:
182                 return True
183
184         if item["match"] == 0:
185             if host == item["needle"]:
186                 return True
187
188         if item["match"] == 1:
189             if re.match(r".*%s$" % item["needle"], host):
190                 return True
191
192     return False
193
194 def set_proxies(proxy = None, no_proxy = None):
195     _set_proxies(proxy, no_proxy)
196     _set_noproxy_list()
197     set_proxy_environ()
198
199 def get_proxy_for(url):
200     if url.startswith('file:') or _isnoproxy(url):
201         return None
202
203     type = url[0:url.index(":")]
204     proxy = None
205     if _my_proxies.has_key(type):
206         proxy = _my_proxies[type]
207     elif _my_proxies.has_key("http"):
208         proxy = _my_proxies["http"]
209     else:
210         proxy = None
211
212     return proxy