Debian Codegraph @

smburi.py

raw
1 #!/usr/bin/python3
2
3 ## system-config-printer
4
5 ## Copyright (C) 2006, 2007, 2008, 2009, 2011, 2012 Red Hat, Inc.
6 ## Copyright (C) 2006, 2007 Florian Festi <[email protected]>
7 ## Copyright (C) 2006, 2007, 2008, 2009 Tim Waugh <[email protected]>
8
9 ## This program is free software; you can redistribute it and/or modify
10 ## it under the terms of the GNU General Public License as published by
11 ## the Free Software Foundation; either version 2 of the License, or
12 ## (at your option) any later version.
13
14 ## This program is distributed in the hope that it will be useful,
15 ## but WITHOUT ANY WARRANTY; without even the implied warranty of
16 ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 ## GNU General Public License for more details.
18
19 ## You should have received a copy of the GNU General Public License
20 ## along with this program; if not, write to the Free Software
21 ## Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
22
23 import urllib.parse
24
25 def urlquote (x):
26 q = urllib.parse.quote (x)
27 for c in ["/", "@", ":"]:
28 q = q.replace (c, "%%%02X" % ord (c))
29
30 return q
31
32 class SMBURI:
33 def __init__ (self,
34 uri=None,
35 group='', host='', share='', user='', password=''):
36 if uri:
37 if group or host or share or user or password:
38 raise RuntimeError
39
40 if uri.startswith ("smb://"):
41 uri = uri[6:]
42
43 self.uri = uri
44 else:
45 self.uri = self._construct (group, host, share,
46 user=user, password=password)
47
48 def _construct (self, group, host, share, user='', password=''):
49 uri_password = ''
50 if password:
51 uri_password = ':' + urlquote (password)
52 if user:
53 uri_password += '@'
54 uri = "%s%s%s" % (urlquote (user),
55 uri_password,
56 urlquote (group))
57 if len (group) > 0:
58 uri += '/'
59 uri += urlquote (host)
60 if len (share) > 0:
61 uri += "/" + urlquote (share)
62 return uri
63
64 def get_uri (self):
65 return self.uri
66
67 def sanitize_uri (self):
68 group, host, share, user, password = self.separate ()
69 return self._construct (group, host, share)
70
71 def separate (self):
72 uri = self.get_uri ()
73 user = ''
74 password = ''
75 auth = uri.find ('@')
76 if auth != -1:
77 u = uri[:auth].find(':')
78 if u != -1:
79 user = uri[:u]
80 password = uri[u + 1:auth]
81 else:
82 user = uri[:auth]
83 uri = uri[auth + 1:]
84 sep = uri.count ('/')
85 group = ''
86 if sep == 2:
87 g = uri.find('/')
88 group = uri[:g]
89 uri = uri[g + 1:]
90 if sep < 1:
91 host = ''
92 else:
93 h = uri.find('/')
94 host = uri[:h]
95 uri = uri[h + 1:]
96 p = host.find(':')
97 if p != -1:
98 host = host[:p]
99 share = uri
100 return (urllib.parse.unquote (group), urllib.parse.unquote (host),
101 urllib.parse.unquote (share),
102 urllib.parse.unquote (user), urllib.parse.unquote (password))