Debian Codegraph @

python/proton/_url.py

raw
1 #
2 # Licensed to the Apache Software Foundation (ASF) under one
3 # or more contributor license agreements. See the NOTICE file
4 # distributed with this work for additional information
5 # regarding copyright ownership. The ASF licenses this file
6 # to you under the Apache License, Version 2.0 (the
7 # "License"); you may not use this file except in compliance
8 # with the License. You may obtain a copy of the License at
9 #
10 # http://www.apache.org/licenses/LICENSE-2.0
11 #
12 # Unless required by applicable law or agreed to in writing,
13 # software distributed under the License is distributed on an
14 # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15 # KIND, either express or implied. See the License for the
16 # specific language governing permissions and limitations
17 # under the License.
18 #
19
20 from __future__ import absolute_import
21
22 import socket
23
24 from urllib.parse import urlparse, urlunparse, quote, unquote
25
26
27 class Url(object):
28 """
29 **DEPRECATED** Simple URL parser/constructor.
30
31 .. deprecated:: 0.27
32 Use a ``str`` containing the URL instead.
33
34 Handles URLs of the form:
35
36 ``<scheme>://<user>:<password>@<host>:<port>/<path>``
37
38 All components can be ``None`` if not specified in the URL string.
39
40 The port can be specified as a service name, e.g. 'amqp' in the
41 URL string but :class:`Url.Port` always gives the integer value.
42
43 .. warning:: The placement of user and password in URLs is not
44 recommended. It can result in credentials leaking out in program
45 logs. Use connection configuration attributes instead.
46
47 :ivar scheme: Url scheme e.g. 'amqp' or 'amqps'
48 :ivar username: Username
49 :ivar ~.password: Password
50 :ivar ~.host: Host name, ipv6 literal or ipv4 dotted quad.
51 :ivar ~.port: Integer port.
52 :ivar host_port: Returns host:port
53
54 :param url: URL string to parse.
55 :type url: ``str``
56 :param defaults: If ``True``, fill in missing default values in the URL.
57 If ``False``, you can fill them in later by calling self.defaults()
58 :type defaults: ``bool``
59 :param kwargs: scheme, user, password, host, port, path.
60 If specified, replaces corresponding part in url string.
61 """
62
63 AMQPS = "amqps"
64 """URL scheme for the AMQP protocol secured with SSL."""
65
66 AMQP = "amqp"
67 """URL scheme for the AMQP protocol."""
68
69 class Port(int):
70 """An integer port number that can be constructed from a service name string"""
71
72 def __new__(cls, value):
73 """
74 :param value: integer port number or string service name.
75 """
76 port = super(Url.Port, cls).__new__(cls, cls._port_int(value))
77 setattr(port, 'name', str(value))
78 return port
79
80 def __eq__(self, x):
81 return str(self) == x or int(self) == x
82
83 def __ne__(self, x):
84 return not self == x
85
86 def __str__(self):
87 return str(self.name)
88
89 @staticmethod
90 def _port_int(value):
91 """Convert service, an integer or a service name, into an integer port number."""
92 try:
93 return int(value)
94 except ValueError:
95 try:
96 return socket.getservbyname(value)
97 except socket.error:
98 # Not every system has amqp/amqps defined as a service
99 if value == Url.AMQPS:
100 return 5671
101 elif value == Url.AMQP:
102 return 5672
103 else:
104 raise ValueError("Not a valid port number or service name: '%s'" % value)
105
106 def __init__(self, url=None, defaults=True, **kwargs):
107 if isinstance(url, Url):
108 self.scheme = url.scheme
109 self.username = url.username
110 self.password = url.password
111 self._host = url._host
112 self._port = url._port
113 self._path = url._path
114 self._params = url._params
115 self._query = url._query
116 self._fragment = url._fragment
117 elif url:
118 if not url.startswith('//'):
119 p = url.partition(':')
120 if '/' in p[0] or not p[2].startswith('//'):
121 url = '//' + url
122 u = urlparse(url)
123 if not u:
124 raise ValueError("Invalid URL '%s'" % url)
125 self.scheme = None if not u.scheme else u.scheme
126 self.username = u.username and unquote(u.username)
127 self.password = u.password and unquote(u.password)
128 (self._host, self._port) = self._parse_host_port(u.netloc)
129 self._path = None if not u.path else u.path
130 self._params = u.params
131 self._query = u.query
132 self._fragment = u.fragment
133 else:
134 self.scheme = None
135 self.username = None
136 self.password = None
137 self._host = None
138 self._port = None
139 self._path = None
140 self._params = None
141 self._query = None
142 self._fragment = None
143 for k in kwargs: # Let kwargs override values parsed from url
144 getattr(self, k) # Check for invalid kwargs
145 setattr(self, k, kwargs[k])
146 if defaults:
147 self.defaults()
148
149 @staticmethod
150 def _parse_host_port(nl):
151 hostport = nl.split('@')[-1]
152 hostportsplit = hostport.split(']')
153 beforebrace = hostportsplit[0]
154 afterbrace = hostportsplit[-1]
155
156 if len(hostportsplit) == 1:
157 beforebrace = ''
158 else:
159 beforebrace += ']'
160 if ':' in afterbrace:
161 afterbracesplit = afterbrace.split(':')
162 port = afterbracesplit[1]
163 host = (beforebrace + afterbracesplit[0]).lower()
164 if not port:
165 port = None
166 else:
167 host = (beforebrace + afterbrace).lower()
168 port = None
169 if not host:
170 host = None
171 return host, port
172
173 @property
174 def path(self):
175 """
176 The path segment of a URL
177
178 :type: ``str``
179 """
180 return self._path if not self._path or self._path[0] != '/' else self._path[1:]
181
182 @path.setter
183 def path(self, p):
184 self._path = p if p[0] == '/' else '/' + p
185
186 @staticmethod
187 def _ipv6literal(s):
188 return s.startswith('[') and s.endswith(']')
189
190 @property
191 def host(self):
192 """
193 The host segment of a URL
194
195 :type: ``str``
196 """
197 if self._host and self._ipv6literal(self._host):
198 return self._host[1:-1]
199 else:
200 return self._host
201
202 @host.setter
203 def host(self, h):
204 if ':' in h and not self._ipv6literal(h):
205 self._host = '[' + h + ']'
206 else:
207 self._host = h
208
209 @property
210 def port(self):
211 """
212 The port number segment of a URL.
213
214 :type: :class:`Url.Port`
215 """
216 return self._port and Url.Port(self._port)
217
218 @port.setter
219 def port(self, p):
220 self._port = p
221
222 @property
223 def _netloc(self):
224 hostport = ''
225 if self._host:
226 hostport = self._host
227 if self._port:
228 hostport += ':'
229 hostport += str(self._port)
230 userpart = ''
231 if self.username:
232 userpart += quote(self.username)
233 if self.password:
234 userpart += ':'
235 userpart += quote(self.password)
236 if self.username or self.password:
237 userpart += '@'
238 return userpart + hostport
239
240 def __str__(self):
241 if self.scheme \
242 and not self._netloc and not self._path \
243 and not self._params and not self._query and not self._fragment:
244 return self.scheme + '://'
245 return urlunparse((self.scheme or '', self._netloc or '', self._path or '',
246 self._params or '', self._query or '', self._fragment or ''))
247
248 def __repr__(self):
249 return "Url('%s')" % self
250
251 def __eq__(self, x):
252 return str(self) == str(x)
253
254 def __ne__(self, x):
255 return not self == x
256
257 def defaults(self):
258 """
259 Fill in missing values (scheme, host or port) with defaults
260 :return: self
261 """
262 self.scheme = self.scheme or self.AMQP
263 self._host = self._host or '0.0.0.0'
264 self._port = self._port or self.Port(self.scheme)
265 return self