Debian Codegraph @

src/lazr/uri/_uri.py

raw symbols SCIP
1 # Copyright 2009 Canonical Ltd. All rights reserved.
2 #
3 # This file is part of lazr.uri
4 #
5 # lazr.uri is free software: you can redistribute it and/or modify it
6 # under the terms of the GNU Lesser General Public License as published by
7 # the Free Software Foundation, version 3 of the License.
8 #
9 # lazr.uri is distributed in the hope that it will be useful, but WITHOUT
10 # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11 # FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
12 # License for more details.
13 #
14 # You should have received a copy of the GNU Lesser General Public License
15 # along with lazr.uri. If not, see <http://www.gnu.org/licenses/>.
16
17 """Functions for working with generic syntax URIs."""
18
19 __all__ = [
20 "URI",
21 "InvalidURIError",
22 "find_uris_in_text",
23 "possible_uri_re",
24 "merge",
25 "remove_dot_segments",
26 ]
27
28 import re
29
30 try:
31 unicode
32 except NameError:
33 unicode = str
34
35 # Default port numbers for different URI schemes
36 # The registered URI schemes comes from
37 # http://www.iana.org/assignments/uri-schemes.html
38 # The default ports come from the relevant RFCs
39
40 _default_port = {
41 # Official schemes
42 "acap": "674",
43 "dav": "80",
44 "dict": "2628",
45 "dns": "53",
46 "ftp": "21",
47 "go": "1096",
48 "gopher": "70",
49 "h323": "1720",
50 "http": "80",
51 "https": "443",
52 "imap": "143",
53 "ipp": "631",
54 "iris.beep": "702",
55 "ldap": "389",
56 "mtqp": "1038",
57 "mupdate": "3905",
58 "nfs": "2049",
59 "nntp": "119",
60 "pop": "110",
61 "rtsp": "554",
62 "sip": "5060",
63 "sips": "5061",
64 "snmp": "161",
65 "soap.beep": "605",
66 "soap.beeps": "605",
67 "telnet": "23",
68 "tftp": "69",
69 "tip": "3372",
70 "vemmi": "575",
71 "xmlrpc.beep": "602",
72 "xmlrpc.beeps": "602",
73 "z39.50r": "210",
74 "z39.50s": "210",
75 # Historical schemes
76 "prospero": "1525",
77 "wais": "210",
78 # Common but unregistered schemes
79 "bzr+http": "80",
80 "bzr+ssh": "22",
81 "irc": "6667",
82 "sftp": "22",
83 "ssh": "22",
84 "svn": "3690",
85 "svn+ssh": "22",
86 }
87
88 # Regular expressions adapted from the ABNF in the RFC
89
90 scheme_re = r"(?P<scheme>[a-z][-a-z0-9+.]*)"
91
92 userinfo_re = r"(?P<userinfo>(?:[-a-z0-9._~!$&\'()*+,;=:]|%[0-9a-f]{2})*)"
93 # The following regular expression will match some IP address style
94 # host names that the RFC would not (e.g. leading zeros on the
95 # components), but is signficantly simpler.
96 host_re = (
97 r"(?P<host>[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}|"
98 r"(?:[-a-z0-9._~!$&\'()*+,;=]|%[0-9a-f]{2})*|"
99 r"\[[0-9a-z:.]+\])"
100 )
101 port_re = r"(?P<port>[0-9]*)"
102
103 authority_re = r"(?P<authority>(?:{}@)?{}(?::{})?)".format(
104 userinfo_re,
105 host_re,
106 port_re,
107 )
108
109 path_abempty_re = r"(?:/(?:[-a-z0-9._~!$&\'()*+,;=:@]|%[0-9a-f]{2})*)*"
110 path_noscheme_re = (
111 r"(?:[-a-z0-9._~!$&\'()*+,;=@]|%[0-9a-f]{2})+"
112 r"(?:/(?:[-a-z0-9._~!$&\'()*+,;=:@]|%[0-9a-f]{2})*)*"
113 )
114 path_rootless_re = (
115 r"(?:[-a-z0-9._~!$&\'()*+,;=:@]|%[0-9a-f]{2})+"
116 r"(?:/(?:[-a-z0-9._~!$&\'()*+,;=:@]|%[0-9a-f]{2})*)*"
117 )
118 path_absolute_re = r"/(?:%s)?" % path_rootless_re
119 path_empty_re = r""
120
121 hier_part_re = r"(?P<hierpart>//{}{}|{}|{}|{})".format(
122 authority_re,
123 path_abempty_re,
124 path_absolute_re,
125 path_rootless_re,
126 path_empty_re,
127 )
128
129 relative_part_re = r"(?P<relativepart>//{}{}|{}|{}|{})".format(
130 authority_re,
131 path_abempty_re,
132 path_absolute_re,
133 path_noscheme_re,
134 path_empty_re,
135 )
136
137 # Additionally we also permit square braces in the query portion to
138 # accomodate real-world URIs.
139 query_re = r"(?P<query>(?:[-a-z0-9._~!$&\'()*+,;=:@/?\[\]]|%[0-9a-f]{2})*)"
140 fragment_re = r"(?P<fragment>(?:[-a-z0-9._~!$&\'()*+,;=:@/?]|%[0-9a-f]{2})*)"
141
142 uri_re = r"{}:{}(?:\?{})?(?:#{})?$".format(
143 scheme_re,
144 hier_part_re,
145 query_re,
146 fragment_re,
147 )
148
149 relative_ref_re = r"{}(?:\?{})?(?:#{})?$".format(
150 relative_part_re,
151 query_re,
152 fragment_re,
153 )
154
155 uri_pat = re.compile(uri_re, re.IGNORECASE)
156 relative_ref_pat = re.compile(relative_ref_re, re.IGNORECASE)
157
158
159 def merge(basepath, relpath, has_authority):
160 """Merge two URI path components into a single path component.
161
162 Follows rules specified in Section 5.2.3 of RFC 3986.
163
164 The algorithm in the RFC treats the empty basepath edge case
165 differently for URIs with and without an authority section, which
166 is why the third argument is necessary.
167 """
168 if has_authority and basepath == "":
169 return "/" + relpath
170 slash = basepath.rfind("/")
171 return basepath[: slash + 1] + relpath
172
173
174 def remove_dot_segments(path):
175 """Remove '.' and '..' segments from a URI path.
176
177 Follows the rules specified in Section 5.2.4 of RFC 3986.
178 """
179 output = []
180 while path:
181 if path.startswith("../"):
182 path = path[3:]
183 elif path.startswith("./"):
184 path = path[2:]
185 elif path.startswith("/./") or path == "/.":
186 path = "/" + path[3:]
187 elif path.startswith("/../") or path == "/..":
188 path = "/" + path[4:]
189 if len(output) > 0:
190 del output[-1]
191 elif path in [".", ".."]:
192 path = ""
193 else:
194 if path.startswith("/"):
195 slash = path.find("/", 1)
196 else:
197 slash = path.find("/")
198 if slash < 0:
199 slash = len(path)
200 output.append(path[:slash])
201 path = path[slash:]
202 return "".join(output)
203
204
205 def normalise_unreserved(string):
206 """Return a version of 's' where no unreserved characters are encoded.
207
208 Unreserved characters are defined in Section 2.3 of RFC 3986.
209
210 Percent encoded sequences are normalised to upper case.
211 """
212 result = string.split("%")
213 unreserved = (
214 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
215 "abcdefghijklmnopqrstuvwxyz"
216 "0123456789-._~"
217 )
218 for index, item in enumerate(result):
219 if index == 0:
220 continue
221 try:
222 ch = int(item[:2], 16)
223 except ValueError:
224 continue
225 if chr(ch) in unreserved:
226 result[index] = chr(ch) + item[2:]
227 else:
228 result[index] = "%{:02X}{}".format(ch, item[2:])
229 return "".join(result)
230
231
232 class InvalidURIError(Exception):
233 """Invalid URI"""
234
235
236 class URI:
237 """A class that represents a URI.
238
239 This class can represent arbitrary URIs that conform to the
240 generic syntax described in RFC 3986.
241 """
242
243 def __init__(
244 self,
245 uri=None,
246 scheme=None,
247 userinfo=None,
248 host=None,
249 port=None,
250 path=None,
251 query=None,
252 fragment=None,
253 ):
254 """Create a URI instance.
255
256 Can be called with either a string URI or the component parts
257 of the URI as keyword arguments.
258
259 In either case, all arguments are expected to be appropriately
260 URI encoded.
261 """
262 assert (
263 uri is not None
264 and scheme is None
265 and userinfo is None
266 and host is None
267 and port is None
268 and path is None
269 and query is None
270 and fragment is None
271 ) or uri is None, (
272 "URI() must be called with a single string argument or "
273 "with URI components given as keyword arguments."
274 )
275
276 if uri is not None:
277 if isinstance(uri, unicode):
278 try:
279 uri.encode("ASCII")
280 except UnicodeEncodeError:
281 raise InvalidURIError(
282 "URIs must consist of ASCII characters"
283 )
284 match = uri_pat.match(uri)
285 if match is None:
286 raise InvalidURIError('"%s" is not a valid URI' % uri)
287 self.scheme = match.group("scheme")
288 self.userinfo = match.group("userinfo")
289 self.host = match.group("host")
290 self.port = match.group("port")
291 hierpart = match.group("hierpart")
292 authority = match.group("authority")
293 if authority is None:
294 self.path = hierpart
295 else:
296 # Skip past the //authority part
297 self.path = hierpart[2 + len(authority) :]
298 self.query = match.group("query")
299 self.fragment = match.group("fragment")
300 else:
301 if scheme is None:
302 raise InvalidURIError("URIs must have a scheme")
303 if host is None and (userinfo is not None or port is not None):
304 raise InvalidURIError(
305 "host must be given if userinfo or port are"
306 )
307 if path is None:
308 raise InvalidURIError("URIs must have a path")
309 self.scheme = scheme
310 self.userinfo = userinfo
311 self.host = host
312 self.port = port
313 self.path = path
314 self.query = query
315 self.fragment = fragment
316
317 self._normalise()
318
319 if (
320 self.scheme
321 in [
322 "http",
323 "https",
324 "ftp",
325 "gopher",
326 "telnet",
327 "imap",
328 "mms",
329 "rtsp",
330 "svn",
331 "svn+ssh",
332 "bzr",
333 "bzr+http",
334 "bzr+ssh",
335 ]
336 and not self.host
337 ):
338 raise InvalidURIError(
339 "%s URIs must have a host name" % self.scheme
340 )
341
342 def _normalise(self):
343 """Perform normalisation of URI components."""
344 self.scheme = self.scheme.lower()
345
346 if self.userinfo is not None:
347 self.userinfo = normalise_unreserved(self.userinfo)
348 if self.host is not None:
349 self.host = normalise_unreserved(self.host.lower())
350 if self.port == "":
351 self.port = None
352 elif self.port is not None:
353 if self.port == _default_port.get(self.scheme):
354 self.port = None
355 if self.host is not None and self.path == "":
356 self.path = "/"
357 self.path = normalise_unreserved(remove_dot_segments(self.path))
358
359 if self.query is not None:
360 self.query = normalise_unreserved(self.query)
361 if self.fragment is not None:
362 self.fragment = normalise_unreserved(self.fragment)
363
364 @property
365 def authority(self):
366 """The authority part of the URI"""
367 if self.host is None:
368 return None
369 authority = self.host
370 if self.userinfo is not None:
371 authority = "{}@{}".format(self.userinfo, authority)
372 if self.port is not None:
373 authority = "{}:{}".format(authority, self.port)
374 return authority
375
376 @property
377 def hier_part(self):
378 """The hierarchical part of the URI"""
379 authority = self.authority
380 if authority is None:
381 return self.path
382 else:
383 return "//{}{}".format(authority, self.path)
384
385 def __str__(self):
386 uri = "{}:{}".format(self.scheme, self.hier_part)
387 if self.query is not None:
388 uri += "?%s" % self.query
389 if self.fragment is not None:
390 uri += "#%s" % self.fragment
391 return uri
392
393 def __repr__(self):
394 return "{}({!r})".format(self.__class__.__name__, str(self))
395
396 def __eq__(self, other):
397 if isinstance(other, self.__class__):
398 return (
399 self.scheme == other.scheme
400 and self.authority == other.authority
401 and self.path == other.path
402 and self.query == other.query
403 and self.fragment == other.fragment
404 )
405 else:
406 return NotImplemented
407
408 def __ne__(self, other):
409 equal = self.__eq__(other)
410 if equal == NotImplemented:
411 return NotImplemented
412 else:
413 return not equal
414
415 def __hash__(self):
416 return hash(
417 (self.scheme, self.authority, self.path, self.query, self.fragment)
418 )
419
420 def replace(self, **parts):
421 """Replace one or more parts of the URI, returning the result."""
422 if not parts:
423 return self
424 baseparts = dict(
425 scheme=self.scheme,
426 userinfo=self.userinfo,
427 host=self.host,
428 port=self.port,
429 path=self.path,
430 query=self.query,
431 fragment=self.fragment,
432 )
433 baseparts.update(parts)
434 return self.__class__(**baseparts)
435
436 def resolve(self, reference):
437 """Resolve the given URI reference relative to this URI.
438
439 Uses the rules from Section 5.2 of RFC 3986 to resolve the new
440 URI.
441 """
442 # If the reference is a full URI, then return it as is.
443 try:
444 return self.__class__(reference)
445 except InvalidURIError:
446 pass
447
448 match = relative_ref_pat.match(reference)
449 if match is None:
450 raise InvalidURIError("Invalid relative reference")
451
452 parts = dict(scheme=self.scheme)
453 authority = match.group("authority")
454 if authority is not None:
455 parts["userinfo"] = match.group("userinfo")
456 parts["host"] = match.group("host")
457 parts["port"] = match.group("port")
458 # Skip over the //authority part
459 parts["path"] = remove_dot_segments(
460 match.group("relativepart")[2 + len(authority) :]
461 )
462 parts["query"] = match.group("query")
463 else:
464 path = match.group("relativepart")
465 query = match.group("query")
466 if path == "":
467 parts["path"] = self.path
468 if query is not None:
469 parts["query"] = query
470 else:
471 parts["query"] = self.query
472 else:
473 if path.startswith("/"):
474 parts["path"] = remove_dot_segments(path)
475 else:
476 parts["path"] = merge(
477 self.path, path, has_authority=self.host is not None
478 )
479 parts["path"] = remove_dot_segments(parts["path"])
480 parts["query"] = query
481 parts["userinfo"] = self.userinfo
482 parts["host"] = self.host
483 parts["port"] = self.port
484 parts["fragment"] = match.group("fragment")
485
486 return self.__class__(**parts)
487
488 def append(self, path):
489 """Append the given path to this URI.
490
491 The path must not start with a slash, but a slash is added to
492 base URI (before appending the path), in case it doesn't end
493 with a slash.
494 """
495 assert not path.startswith("/")
496 return self.ensureSlash().resolve(path)
497
498 def contains(self, other):
499 """Returns True if the URI 'other' is contained by this one."""
500 if self.scheme != other.scheme or self.authority != other.authority:
501 return False
502 if self.path == other.path:
503 return True
504 basepath = self.path
505 if not basepath.endswith("/"):
506 basepath += "/"
507 otherpath = other.path
508 if not otherpath.endswith("/"):
509 otherpath += "/"
510 return otherpath.startswith(basepath)
511
512 def underDomain(self, domain):
513 """Return True if the given domain name a parent of the URL's host."""
514 if len(domain) == 0:
515 return True
516 our_segments = self.host.split(".")
517 domain_segments = domain.split(".")
518 return our_segments[-len(domain_segments) :] == domain_segments
519
520 def ensureSlash(self):
521 """Return a URI with the path normalised to end with a slash."""
522 if self.path.endswith("/"):
523 return self
524 else:
525 return self.replace(path=self.path + "/")
526
527 def ensureNoSlash(self):
528 """Return a URI with the path normalised to not end with a slash."""
529 if self.path.endswith("/"):
530 return self.replace(path=self.path.rstrip("/"))
531 else:
532 return self
533
534
535 # Regular expression for finding URIs in a body of text:
536 #
537 # From RFC 3986 ABNF for URIs:
538 #
539 # URI = scheme ":" hier-part [ "?" query ] [ "#" fragment ]
540 # hier-part = "//" authority path-abempty
541 # / path-absolute
542 # / path-rootless
543 # / path-empty
544 #
545 # authority = [ userinfo "@" ] host [ ":" port ]
546 # userinfo = *( unreserved / pct-encoded / sub-delims / ":" )
547 # host = IP-literal / IPv4address / reg-name
548 # reg-name = *( unreserved / pct-encoded / sub-delims )
549 # port = *DIGIT
550 #
551 # path-abempty = *( "/" segment )
552 # path-absolute = "/" [ segment-nz *( "/" segment ) ]
553 # path-rootless = segment-nz *( "/" segment )
554 # path-empty = 0<pchar>
555 #
556 # segment = *pchar
557 # segment-nz = 1*pchar
558 # pchar = unreserved / pct-encoded / sub-delims / ":" / "@"
559 #
560 # query = *( pchar / "/" / "?" )
561 # fragment = *( pchar / "/" / "?" )
562 #
563 # unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"
564 # pct-encoded = "%" HEXDIG HEXDIG
565 # sub-delims = "!" / "$" / "&" / "'" / "(" / ")"
566 # / "*" / "+" / "," / ";" / "="
567 #
568 # We only match a set of known scheme names. We don't handle
569 # IP-literal either.
570 #
571 # We will simplify "unreserved / pct-encoded / sub-delims" as the
572 # following regular expression:
573 # [-a-zA-Z0-9._~%!$&'()*+,;=]
574 #
575 # We also require that the path-rootless form not begin with a
576 # colon to avoid matching strings like "http::foo" (to avoid bug
577 # #40255).
578 #
579 # The path-empty pattern is not matched either, due to false
580 # positives.
581 #
582 # Some allowed URI punctuation characters will be trimmed if they
583 # appear at the end of the URI since they may be incidental in the
584 # flow of the text.
585 #
586 # apport has at one time produced query strings containing sqaure
587 # braces (that are not percent-encoded). In RFC 2986 they seem to be
588 # allowed by section 2.2 "Reserved Characters", yet section 3.4
589 # "Query" appears to provide a strict definition of the query string
590 # that would forbid square braces. Either way, links with
591 # non-percent-encoded square braces are being used on Launchpad so
592 # it's probably best to accomodate them.
593
594 possible_uri_re = r"""
595 \b
596 (?:about|gopher|http|https|sftp|news|ftp|mailto|file|irc|jabber|xmpp)
597 :
598 (?:
599 (?:
600 # "//" authority path-abempty
601 //
602 (?: # userinfo
603 [{unreserved}:]*
604 @
605 )?
606 (?: # host
607 \d+\.\d+\.\d+\.\d+ |
608 [{unreserved}]*
609 )
610 (?: # port
611 : \d*
612 )?
613 (?: / [{unreserved}:@]* )*
614 ) | (?:
615 # path-absolute
616 /
617 (?: [{unreserved}:@]+
618 (?: / [{unreserved}:@]* )* )?
619 ) | (?:
620 # path-rootless
621 [{unreserved}@]
622 [{unreserved}:@]*
623 (?: / [{unreserved}:@]* )*
624 )
625 )
626 (?: # query
627 \?
628 [{unreserved}:@/\?\[\]]*
629 )?
630 (?: # fragment
631 \#
632 [{unreserved}:@/\?]*
633 )?
634 """.format(unreserved="-a-zA-Z0-9._~%!$&'()*+,;=")
635
636 possible_uri_pat = re.compile(possible_uri_re, re.IGNORECASE | re.VERBOSE)
637 uri_trailers_pat = re.compile(r"([,.?:);>]+)$")
638
639
640 def find_uris_in_text(text):
641 """Scan a block of text for URIs, and yield the ones found."""
642 for match in possible_uri_pat.finditer(text):
643 uri_string = match.group()
644 # remove characters from end of URI that are not likely to be
645 # part of the URI.
646 uri_string = uri_trailers_pat.sub("", uri_string)
647 try:
648 uri = URI(uri_string)
649 except InvalidURIError:
650 continue
651 yield uri