1 # Copyright (c) 2014 Intel, Inc.
3 # This program is free software; you can redistribute it and/or modify it
4 # under the terms of the GNU General Public License as published by the Free
5 # Software Foundation; version 2 of the License
7 # This program is distributed in the hope that it will be useful, but
8 # WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
9 # or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
12 # You should have received a copy of the GNU General Public License along
13 # with this program; if not, write to the Free Software Foundation, Inc., 59
14 # Temple Place - Suite 330, Boston, MA 02111-1307, USA.
17 This module provides a class SafeURL which can contain url/user/password read
18 from config file, and hide plain user and password when it print to screen
21 import urllib.request, urllib.parse, urllib.error
22 from urllib.parse import urlsplit, urlunsplit
25 def join_userpass(href, user, passwd):
26 """Return authenticated URL with user and passwd embeded"""
27 if not user and not passwd:
31 userpass = '%s:%s' % (urllib.parse.quote(user, safe=''),
32 urllib.parse.quote(passwd, safe=''))
34 userpass = urllib.parse.quote(user, safe='')
36 parts = urlsplit(href)
37 netloc = '%s@%s' % (userpass, parts[1])
40 return urlunsplit(comps)
43 def split_userpass(href):
44 """Returns (href, user, passwd) of an authenticated URL"""
45 parts = urlsplit(href)
49 return href, None, None
51 userpass, netloc = netloc.split('@', 1)
53 user, passwd = [ urllib.parse.unquote(i)
54 for i in userpass.split(':', 1) ]
56 user, passwd = userpass, None
60 return urlunsplit(comps), user, passwd
64 '''SafeURL can hide user info when it's printed to console.
65 Use property full to get url with user info
67 def __new__(cls, urlstring, user=None, passwd=None):
68 """Imuutable object"""
69 href, user1, passwd1 = split_userpass(urlstring)
70 user = user if user else user1
71 passwd = passwd if passwd else passwd1
73 obj = super(SafeURL, cls).__new__(cls, href)
76 obj.full = join_userpass(href, user, passwd)
78 parts = urlsplit(href)
82 obj.host = parts.hostname
86 def join(self, *path):
87 """Returns a new SafeURL with new path. Search part is removed since
88 after join path is changed, keep the same search part is useless.
90 idx = self.full.find('?')
91 url = self.full if idx < 0 else self.full[:idx]
92 return SafeURL(os.path.join(url.rstrip('/'), *path))