_uri.py 19 KB

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