parse.py 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068
  1. """Parse (absolute and relative) URLs.
  2. urlparse module is based upon the following RFC specifications.
  3. RFC 3986 (STD66): "Uniform Resource Identifiers" by T. Berners-Lee, R. Fielding
  4. and L. Masinter, January 2005.
  5. RFC 2732 : "Format for Literal IPv6 Addresses in URL's by R.Hinden, B.Carpenter
  6. and L.Masinter, December 1999.
  7. RFC 2396: "Uniform Resource Identifiers (URI)": Generic Syntax by T.
  8. Berners-Lee, R. Fielding, and L. Masinter, August 1998.
  9. RFC 2368: "The mailto URL scheme", by P.Hoffman , L Masinter, J. Zawinski, July 1998.
  10. RFC 1808: "Relative Uniform Resource Locators", by R. Fielding, UC Irvine, June
  11. 1995.
  12. RFC 1738: "Uniform Resource Locators (URL)" by T. Berners-Lee, L. Masinter, M.
  13. McCahill, December 1994
  14. RFC 3986 is considered the current standard and any future changes to
  15. urlparse module should conform with it. The urlparse module is
  16. currently not entirely compliant with this RFC due to defacto
  17. scenarios for parsing, and for backward compatibility purposes, some
  18. parsing quirks from older RFCs are retained. The testcases in
  19. test_urlparse.py provides a good indicator of parsing behavior.
  20. """
  21. import re
  22. import sys
  23. import collections
  24. __all__ = ["urlparse", "urlunparse", "urljoin", "urldefrag",
  25. "urlsplit", "urlunsplit", "urlencode", "parse_qs",
  26. "parse_qsl", "quote", "quote_plus", "quote_from_bytes",
  27. "unquote", "unquote_plus", "unquote_to_bytes",
  28. "DefragResult", "ParseResult", "SplitResult",
  29. "DefragResultBytes", "ParseResultBytes", "SplitResultBytes"]
  30. # A classification of schemes.
  31. # The empty string classifies URLs with no scheme specified,
  32. # being the default value returned by “urlsplit” and “urlparse”.
  33. uses_relative = ['', 'ftp', 'http', 'gopher', 'nntp', 'imap',
  34. 'wais', 'file', 'https', 'shttp', 'mms',
  35. 'prospero', 'rtsp', 'rtspu', 'sftp',
  36. 'svn', 'svn+ssh', 'ws', 'wss']
  37. uses_netloc = ['', 'ftp', 'http', 'gopher', 'nntp', 'telnet',
  38. 'imap', 'wais', 'file', 'mms', 'https', 'shttp',
  39. 'snews', 'prospero', 'rtsp', 'rtspu', 'rsync',
  40. 'svn', 'svn+ssh', 'sftp', 'nfs', 'git', 'git+ssh',
  41. 'ws', 'wss']
  42. uses_params = ['', 'ftp', 'hdl', 'prospero', 'http', 'imap',
  43. 'https', 'shttp', 'rtsp', 'rtspu', 'sip', 'sips',
  44. 'mms', 'sftp', 'tel']
  45. # These are not actually used anymore, but should stay for backwards
  46. # compatibility. (They are undocumented, but have a public-looking name.)
  47. non_hierarchical = ['gopher', 'hdl', 'mailto', 'news',
  48. 'telnet', 'wais', 'imap', 'snews', 'sip', 'sips']
  49. uses_query = ['', 'http', 'wais', 'imap', 'https', 'shttp', 'mms',
  50. 'gopher', 'rtsp', 'rtspu', 'sip', 'sips']
  51. uses_fragment = ['', 'ftp', 'hdl', 'http', 'gopher', 'news',
  52. 'nntp', 'wais', 'https', 'shttp', 'snews',
  53. 'file', 'prospero']
  54. # Characters valid in scheme names
  55. scheme_chars = ('abcdefghijklmnopqrstuvwxyz'
  56. 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
  57. '0123456789'
  58. '+-.')
  59. # XXX: Consider replacing with functools.lru_cache
  60. MAX_CACHE_SIZE = 20
  61. _parse_cache = {}
  62. def clear_cache():
  63. """Clear the parse cache and the quoters cache."""
  64. _parse_cache.clear()
  65. _safe_quoters.clear()
  66. # Helpers for bytes handling
  67. # For 3.2, we deliberately require applications that
  68. # handle improperly quoted URLs to do their own
  69. # decoding and encoding. If valid use cases are
  70. # presented, we may relax this by using latin-1
  71. # decoding internally for 3.3
  72. _implicit_encoding = 'ascii'
  73. _implicit_errors = 'strict'
  74. def _noop(obj):
  75. return obj
  76. def _encode_result(obj, encoding=_implicit_encoding,
  77. errors=_implicit_errors):
  78. return obj.encode(encoding, errors)
  79. def _decode_args(args, encoding=_implicit_encoding,
  80. errors=_implicit_errors):
  81. return tuple(x.decode(encoding, errors) if x else '' for x in args)
  82. def _coerce_args(*args):
  83. # Invokes decode if necessary to create str args
  84. # and returns the coerced inputs along with
  85. # an appropriate result coercion function
  86. # - noop for str inputs
  87. # - encoding function otherwise
  88. str_input = isinstance(args[0], str)
  89. for arg in args[1:]:
  90. # We special-case the empty string to support the
  91. # "scheme=''" default argument to some functions
  92. if arg and isinstance(arg, str) != str_input:
  93. raise TypeError("Cannot mix str and non-str arguments")
  94. if str_input:
  95. return args + (_noop,)
  96. return _decode_args(args) + (_encode_result,)
  97. # Result objects are more helpful than simple tuples
  98. class _ResultMixinStr(object):
  99. """Standard approach to encoding parsed results from str to bytes"""
  100. __slots__ = ()
  101. def encode(self, encoding='ascii', errors='strict'):
  102. return self._encoded_counterpart(*(x.encode(encoding, errors) for x in self))
  103. class _ResultMixinBytes(object):
  104. """Standard approach to decoding parsed results from bytes to str"""
  105. __slots__ = ()
  106. def decode(self, encoding='ascii', errors='strict'):
  107. return self._decoded_counterpart(*(x.decode(encoding, errors) for x in self))
  108. class _NetlocResultMixinBase(object):
  109. """Shared methods for the parsed result objects containing a netloc element"""
  110. __slots__ = ()
  111. @property
  112. def username(self):
  113. return self._userinfo[0]
  114. @property
  115. def password(self):
  116. return self._userinfo[1]
  117. @property
  118. def hostname(self):
  119. hostname = self._hostinfo[0]
  120. if not hostname:
  121. return None
  122. # Scoped IPv6 address may have zone info, which must not be lowercased
  123. # like http://[fe80::822a:a8ff:fe49:470c%tESt]:1234/keys
  124. separator = '%' if isinstance(hostname, str) else b'%'
  125. hostname, percent, zone = hostname.partition(separator)
  126. return hostname.lower() + percent + zone
  127. @property
  128. def port(self):
  129. port = self._hostinfo[1]
  130. if port is not None:
  131. port = int(port, 10)
  132. if not ( 0 <= port <= 65535):
  133. raise ValueError("Port out of range 0-65535")
  134. return port
  135. class _NetlocResultMixinStr(_NetlocResultMixinBase, _ResultMixinStr):
  136. __slots__ = ()
  137. @property
  138. def _userinfo(self):
  139. netloc = self.netloc
  140. userinfo, have_info, hostinfo = netloc.rpartition('@')
  141. if have_info:
  142. username, have_password, password = userinfo.partition(':')
  143. if not have_password:
  144. password = None
  145. else:
  146. username = password = None
  147. return username, password
  148. @property
  149. def _hostinfo(self):
  150. netloc = self.netloc
  151. _, _, hostinfo = netloc.rpartition('@')
  152. _, have_open_br, bracketed = hostinfo.partition('[')
  153. if have_open_br:
  154. hostname, _, port = bracketed.partition(']')
  155. _, _, port = port.partition(':')
  156. else:
  157. hostname, _, port = hostinfo.partition(':')
  158. if not port:
  159. port = None
  160. return hostname, port
  161. class _NetlocResultMixinBytes(_NetlocResultMixinBase, _ResultMixinBytes):
  162. __slots__ = ()
  163. @property
  164. def _userinfo(self):
  165. netloc = self.netloc
  166. userinfo, have_info, hostinfo = netloc.rpartition(b'@')
  167. if have_info:
  168. username, have_password, password = userinfo.partition(b':')
  169. if not have_password:
  170. password = None
  171. else:
  172. username = password = None
  173. return username, password
  174. @property
  175. def _hostinfo(self):
  176. netloc = self.netloc
  177. _, _, hostinfo = netloc.rpartition(b'@')
  178. _, have_open_br, bracketed = hostinfo.partition(b'[')
  179. if have_open_br:
  180. hostname, _, port = bracketed.partition(b']')
  181. _, _, port = port.partition(b':')
  182. else:
  183. hostname, _, port = hostinfo.partition(b':')
  184. if not port:
  185. port = None
  186. return hostname, port
  187. from collections import namedtuple
  188. _DefragResultBase = namedtuple('DefragResult', 'url fragment')
  189. _SplitResultBase = namedtuple(
  190. 'SplitResult', 'scheme netloc path query fragment')
  191. _ParseResultBase = namedtuple(
  192. 'ParseResult', 'scheme netloc path params query fragment')
  193. _DefragResultBase.__doc__ = """
  194. DefragResult(url, fragment)
  195. A 2-tuple that contains the url without fragment identifier and the fragment
  196. identifier as a separate argument.
  197. """
  198. _DefragResultBase.url.__doc__ = """The URL with no fragment identifier."""
  199. _DefragResultBase.fragment.__doc__ = """
  200. Fragment identifier separated from URL, that allows indirect identification of a
  201. secondary resource by reference to a primary resource and additional identifying
  202. information.
  203. """
  204. _SplitResultBase.__doc__ = """
  205. SplitResult(scheme, netloc, path, query, fragment)
  206. A 5-tuple that contains the different components of a URL. Similar to
  207. ParseResult, but does not split params.
  208. """
  209. _SplitResultBase.scheme.__doc__ = """Specifies URL scheme for the request."""
  210. _SplitResultBase.netloc.__doc__ = """
  211. Network location where the request is made to.
  212. """
  213. _SplitResultBase.path.__doc__ = """
  214. The hierarchical path, such as the path to a file to download.
  215. """
  216. _SplitResultBase.query.__doc__ = """
  217. The query component, that contains non-hierarchical data, that along with data
  218. in path component, identifies a resource in the scope of URI's scheme and
  219. network location.
  220. """
  221. _SplitResultBase.fragment.__doc__ = """
  222. Fragment identifier, that allows indirect identification of a secondary resource
  223. by reference to a primary resource and additional identifying information.
  224. """
  225. _ParseResultBase.__doc__ = """
  226. ParseResult(scheme, netloc, path, params, query, fragment)
  227. A 6-tuple that contains components of a parsed URL.
  228. """
  229. _ParseResultBase.scheme.__doc__ = _SplitResultBase.scheme.__doc__
  230. _ParseResultBase.netloc.__doc__ = _SplitResultBase.netloc.__doc__
  231. _ParseResultBase.path.__doc__ = _SplitResultBase.path.__doc__
  232. _ParseResultBase.params.__doc__ = """
  233. Parameters for last path element used to dereference the URI in order to provide
  234. access to perform some operation on the resource.
  235. """
  236. _ParseResultBase.query.__doc__ = _SplitResultBase.query.__doc__
  237. _ParseResultBase.fragment.__doc__ = _SplitResultBase.fragment.__doc__
  238. # For backwards compatibility, alias _NetlocResultMixinStr
  239. # ResultBase is no longer part of the documented API, but it is
  240. # retained since deprecating it isn't worth the hassle
  241. ResultBase = _NetlocResultMixinStr
  242. # Structured result objects for string data
  243. class DefragResult(_DefragResultBase, _ResultMixinStr):
  244. __slots__ = ()
  245. def geturl(self):
  246. if self.fragment:
  247. return self.url + '#' + self.fragment
  248. else:
  249. return self.url
  250. class SplitResult(_SplitResultBase, _NetlocResultMixinStr):
  251. __slots__ = ()
  252. def geturl(self):
  253. return urlunsplit(self)
  254. class ParseResult(_ParseResultBase, _NetlocResultMixinStr):
  255. __slots__ = ()
  256. def geturl(self):
  257. return urlunparse(self)
  258. # Structured result objects for bytes data
  259. class DefragResultBytes(_DefragResultBase, _ResultMixinBytes):
  260. __slots__ = ()
  261. def geturl(self):
  262. if self.fragment:
  263. return self.url + b'#' + self.fragment
  264. else:
  265. return self.url
  266. class SplitResultBytes(_SplitResultBase, _NetlocResultMixinBytes):
  267. __slots__ = ()
  268. def geturl(self):
  269. return urlunsplit(self)
  270. class ParseResultBytes(_ParseResultBase, _NetlocResultMixinBytes):
  271. __slots__ = ()
  272. def geturl(self):
  273. return urlunparse(self)
  274. # Set up the encode/decode result pairs
  275. def _fix_result_transcoding():
  276. _result_pairs = (
  277. (DefragResult, DefragResultBytes),
  278. (SplitResult, SplitResultBytes),
  279. (ParseResult, ParseResultBytes),
  280. )
  281. for _decoded, _encoded in _result_pairs:
  282. _decoded._encoded_counterpart = _encoded
  283. _encoded._decoded_counterpart = _decoded
  284. _fix_result_transcoding()
  285. del _fix_result_transcoding
  286. def urlparse(url, scheme='', allow_fragments=True):
  287. """Parse a URL into 6 components:
  288. <scheme>://<netloc>/<path>;<params>?<query>#<fragment>
  289. Return a 6-tuple: (scheme, netloc, path, params, query, fragment).
  290. Note that we don't break the components up in smaller bits
  291. (e.g. netloc is a single string) and we don't expand % escapes."""
  292. url, scheme, _coerce_result = _coerce_args(url, scheme)
  293. splitresult = urlsplit(url, scheme, allow_fragments)
  294. scheme, netloc, url, query, fragment = splitresult
  295. if scheme in uses_params and ';' in url:
  296. url, params = _splitparams(url)
  297. else:
  298. params = ''
  299. result = ParseResult(scheme, netloc, url, params, query, fragment)
  300. return _coerce_result(result)
  301. def _splitparams(url):
  302. if '/' in url:
  303. i = url.find(';', url.rfind('/'))
  304. if i < 0:
  305. return url, ''
  306. else:
  307. i = url.find(';')
  308. return url[:i], url[i+1:]
  309. def _splitnetloc(url, start=0):
  310. delim = len(url) # position of end of domain part of url, default is end
  311. for c in '/?#': # look for delimiters; the order is NOT important
  312. wdelim = url.find(c, start) # find first of this delim
  313. if wdelim >= 0: # if found
  314. delim = min(delim, wdelim) # use earliest delim position
  315. return url[start:delim], url[delim:] # return (domain, rest)
  316. def _checknetloc(netloc):
  317. if not netloc or netloc.isascii():
  318. return
  319. # looking for characters like \u2100 that expand to 'a/c'
  320. # IDNA uses NFKC equivalence, so normalize for this check
  321. import unicodedata
  322. n = netloc.replace('@', '') # ignore characters already included
  323. n = n.replace(':', '') # but not the surrounding text
  324. n = n.replace('#', '')
  325. n = n.replace('?', '')
  326. netloc2 = unicodedata.normalize('NFKC', n)
  327. if n == netloc2:
  328. return
  329. for c in '/?#@:':
  330. if c in netloc2:
  331. raise ValueError("netloc '" + netloc + "' contains invalid " +
  332. "characters under NFKC normalization")
  333. def urlsplit(url, scheme='', allow_fragments=True):
  334. """Parse a URL into 5 components:
  335. <scheme>://<netloc>/<path>?<query>#<fragment>
  336. Return a 5-tuple: (scheme, netloc, path, query, fragment).
  337. Note that we don't break the components up in smaller bits
  338. (e.g. netloc is a single string) and we don't expand % escapes."""
  339. url, scheme, _coerce_result = _coerce_args(url, scheme)
  340. allow_fragments = bool(allow_fragments)
  341. key = url, scheme, allow_fragments, type(url), type(scheme)
  342. cached = _parse_cache.get(key, None)
  343. if cached:
  344. return _coerce_result(cached)
  345. if len(_parse_cache) >= MAX_CACHE_SIZE: # avoid runaway growth
  346. clear_cache()
  347. netloc = query = fragment = ''
  348. i = url.find(':')
  349. if i > 0:
  350. if url[:i] == 'http': # optimize the common case
  351. url = url[i+1:]
  352. if url[:2] == '//':
  353. netloc, url = _splitnetloc(url, 2)
  354. if (('[' in netloc and ']' not in netloc) or
  355. (']' in netloc and '[' not in netloc)):
  356. raise ValueError("Invalid IPv6 URL")
  357. if allow_fragments and '#' in url:
  358. url, fragment = url.split('#', 1)
  359. if '?' in url:
  360. url, query = url.split('?', 1)
  361. _checknetloc(netloc)
  362. v = SplitResult('http', netloc, url, query, fragment)
  363. _parse_cache[key] = v
  364. return _coerce_result(v)
  365. for c in url[:i]:
  366. if c not in scheme_chars:
  367. break
  368. else:
  369. # make sure "url" is not actually a port number (in which case
  370. # "scheme" is really part of the path)
  371. rest = url[i+1:]
  372. if not rest or any(c not in '0123456789' for c in rest):
  373. # not a port number
  374. scheme, url = url[:i].lower(), rest
  375. if url[:2] == '//':
  376. netloc, url = _splitnetloc(url, 2)
  377. if (('[' in netloc and ']' not in netloc) or
  378. (']' in netloc and '[' not in netloc)):
  379. raise ValueError("Invalid IPv6 URL")
  380. if allow_fragments and '#' in url:
  381. url, fragment = url.split('#', 1)
  382. if '?' in url:
  383. url, query = url.split('?', 1)
  384. _checknetloc(netloc)
  385. v = SplitResult(scheme, netloc, url, query, fragment)
  386. _parse_cache[key] = v
  387. return _coerce_result(v)
  388. def urlunparse(components):
  389. """Put a parsed URL back together again. This may result in a
  390. slightly different, but equivalent URL, if the URL that was parsed
  391. originally had redundant delimiters, e.g. a ? with an empty query
  392. (the draft states that these are equivalent)."""
  393. scheme, netloc, url, params, query, fragment, _coerce_result = (
  394. _coerce_args(*components))
  395. if params:
  396. url = "%s;%s" % (url, params)
  397. return _coerce_result(urlunsplit((scheme, netloc, url, query, fragment)))
  398. def urlunsplit(components):
  399. """Combine the elements of a tuple as returned by urlsplit() into a
  400. complete URL as a string. The data argument can be any five-item iterable.
  401. This may result in a slightly different, but equivalent URL, if the URL that
  402. was parsed originally had unnecessary delimiters (for example, a ? with an
  403. empty query; the RFC states that these are equivalent)."""
  404. scheme, netloc, url, query, fragment, _coerce_result = (
  405. _coerce_args(*components))
  406. if netloc or (scheme and scheme in uses_netloc and url[:2] != '//'):
  407. if url and url[:1] != '/': url = '/' + url
  408. url = '//' + (netloc or '') + url
  409. if scheme:
  410. url = scheme + ':' + url
  411. if query:
  412. url = url + '?' + query
  413. if fragment:
  414. url = url + '#' + fragment
  415. return _coerce_result(url)
  416. def urljoin(base, url, allow_fragments=True):
  417. """Join a base URL and a possibly relative URL to form an absolute
  418. interpretation of the latter."""
  419. if not base:
  420. return url
  421. if not url:
  422. return base
  423. base, url, _coerce_result = _coerce_args(base, url)
  424. bscheme, bnetloc, bpath, bparams, bquery, bfragment = \
  425. urlparse(base, '', allow_fragments)
  426. scheme, netloc, path, params, query, fragment = \
  427. urlparse(url, bscheme, allow_fragments)
  428. if scheme != bscheme or scheme not in uses_relative:
  429. return _coerce_result(url)
  430. if scheme in uses_netloc:
  431. if netloc:
  432. return _coerce_result(urlunparse((scheme, netloc, path,
  433. params, query, fragment)))
  434. netloc = bnetloc
  435. if not path and not params:
  436. path = bpath
  437. params = bparams
  438. if not query:
  439. query = bquery
  440. return _coerce_result(urlunparse((scheme, netloc, path,
  441. params, query, fragment)))
  442. base_parts = bpath.split('/')
  443. if base_parts[-1] != '':
  444. # the last item is not a directory, so will not be taken into account
  445. # in resolving the relative path
  446. del base_parts[-1]
  447. # for rfc3986, ignore all base path should the first character be root.
  448. if path[:1] == '/':
  449. segments = path.split('/')
  450. else:
  451. segments = base_parts + path.split('/')
  452. # filter out elements that would cause redundant slashes on re-joining
  453. # the resolved_path
  454. segments[1:-1] = filter(None, segments[1:-1])
  455. resolved_path = []
  456. for seg in segments:
  457. if seg == '..':
  458. try:
  459. resolved_path.pop()
  460. except IndexError:
  461. # ignore any .. segments that would otherwise cause an IndexError
  462. # when popped from resolved_path if resolving for rfc3986
  463. pass
  464. elif seg == '.':
  465. continue
  466. else:
  467. resolved_path.append(seg)
  468. if segments[-1] in ('.', '..'):
  469. # do some post-processing here. if the last segment was a relative dir,
  470. # then we need to append the trailing '/'
  471. resolved_path.append('')
  472. return _coerce_result(urlunparse((scheme, netloc, '/'.join(
  473. resolved_path) or '/', params, query, fragment)))
  474. def urldefrag(url):
  475. """Removes any existing fragment from URL.
  476. Returns a tuple of the defragmented URL and the fragment. If
  477. the URL contained no fragments, the second element is the
  478. empty string.
  479. """
  480. url, _coerce_result = _coerce_args(url)
  481. if '#' in url:
  482. s, n, p, a, q, frag = urlparse(url)
  483. defrag = urlunparse((s, n, p, a, q, ''))
  484. else:
  485. frag = ''
  486. defrag = url
  487. return _coerce_result(DefragResult(defrag, frag))
  488. _hexdig = '0123456789ABCDEFabcdef'
  489. _hextobyte = None
  490. def unquote_to_bytes(string):
  491. """unquote_to_bytes('abc%20def') -> b'abc def'."""
  492. # Note: strings are encoded as UTF-8. This is only an issue if it contains
  493. # unescaped non-ASCII characters, which URIs should not.
  494. if not string:
  495. # Is it a string-like object?
  496. string.split
  497. return b''
  498. if isinstance(string, str):
  499. string = string.encode('utf-8')
  500. bits = string.split(b'%')
  501. if len(bits) == 1:
  502. return string
  503. res = [bits[0]]
  504. append = res.append
  505. # Delay the initialization of the table to not waste memory
  506. # if the function is never called
  507. global _hextobyte
  508. if _hextobyte is None:
  509. _hextobyte = {(a + b).encode(): bytes.fromhex(a + b)
  510. for a in _hexdig for b in _hexdig}
  511. for item in bits[1:]:
  512. try:
  513. append(_hextobyte[item[:2]])
  514. append(item[2:])
  515. except KeyError:
  516. append(b'%')
  517. append(item)
  518. return b''.join(res)
  519. _asciire = re.compile('([\x00-\x7f]+)')
  520. def unquote(string, encoding='utf-8', errors='replace'):
  521. """Replace %xx escapes by their single-character equivalent. The optional
  522. encoding and errors parameters specify how to decode percent-encoded
  523. sequences into Unicode characters, as accepted by the bytes.decode()
  524. method.
  525. By default, percent-encoded sequences are decoded with UTF-8, and invalid
  526. sequences are replaced by a placeholder character.
  527. unquote('abc%20def') -> 'abc def'.
  528. """
  529. if '%' not in string:
  530. string.split
  531. return string
  532. if encoding is None:
  533. encoding = 'utf-8'
  534. if errors is None:
  535. errors = 'replace'
  536. bits = _asciire.split(string)
  537. res = [bits[0]]
  538. append = res.append
  539. for i in range(1, len(bits), 2):
  540. append(unquote_to_bytes(bits[i]).decode(encoding, errors))
  541. append(bits[i + 1])
  542. return ''.join(res)
  543. def parse_qs(qs, keep_blank_values=False, strict_parsing=False,
  544. encoding='utf-8', errors='replace', max_num_fields=None):
  545. """Parse a query given as a string argument.
  546. Arguments:
  547. qs: percent-encoded query string to be parsed
  548. keep_blank_values: flag indicating whether blank values in
  549. percent-encoded queries should be treated as blank strings.
  550. A true value indicates that blanks should be retained as
  551. blank strings. The default false value indicates that
  552. blank values are to be ignored and treated as if they were
  553. not included.
  554. strict_parsing: flag indicating what to do with parsing errors.
  555. If false (the default), errors are silently ignored.
  556. If true, errors raise a ValueError exception.
  557. encoding and errors: specify how to decode percent-encoded sequences
  558. into Unicode characters, as accepted by the bytes.decode() method.
  559. max_num_fields: int. If set, then throws a ValueError if there
  560. are more than n fields read by parse_qsl().
  561. Returns a dictionary.
  562. """
  563. parsed_result = {}
  564. pairs = parse_qsl(qs, keep_blank_values, strict_parsing,
  565. encoding=encoding, errors=errors,
  566. max_num_fields=max_num_fields)
  567. for name, value in pairs:
  568. if name in parsed_result:
  569. parsed_result[name].append(value)
  570. else:
  571. parsed_result[name] = [value]
  572. return parsed_result
  573. def parse_qsl(qs, keep_blank_values=False, strict_parsing=False,
  574. encoding='utf-8', errors='replace', max_num_fields=None):
  575. """Parse a query given as a string argument.
  576. Arguments:
  577. qs: percent-encoded query string to be parsed
  578. keep_blank_values: flag indicating whether blank values in
  579. percent-encoded queries should be treated as blank strings.
  580. A true value indicates that blanks should be retained as blank
  581. strings. The default false value indicates that blank values
  582. are to be ignored and treated as if they were not included.
  583. strict_parsing: flag indicating what to do with parsing errors. If
  584. false (the default), errors are silently ignored. If true,
  585. errors raise a ValueError exception.
  586. encoding and errors: specify how to decode percent-encoded sequences
  587. into Unicode characters, as accepted by the bytes.decode() method.
  588. max_num_fields: int. If set, then throws a ValueError
  589. if there are more than n fields read by parse_qsl().
  590. Returns a list, as G-d intended.
  591. """
  592. qs, _coerce_result = _coerce_args(qs)
  593. # If max_num_fields is defined then check that the number of fields
  594. # is less than max_num_fields. This prevents a memory exhaustion DOS
  595. # attack via post bodies with many fields.
  596. if max_num_fields is not None:
  597. num_fields = 1 + qs.count('&') + qs.count(';')
  598. if max_num_fields < num_fields:
  599. raise ValueError('Max number of fields exceeded')
  600. pairs = [s2 for s1 in qs.split('&') for s2 in s1.split(';')]
  601. r = []
  602. for name_value in pairs:
  603. if not name_value and not strict_parsing:
  604. continue
  605. nv = name_value.split('=', 1)
  606. if len(nv) != 2:
  607. if strict_parsing:
  608. raise ValueError("bad query field: %r" % (name_value,))
  609. # Handle case of a control-name with no equal sign
  610. if keep_blank_values:
  611. nv.append('')
  612. else:
  613. continue
  614. if len(nv[1]) or keep_blank_values:
  615. name = nv[0].replace('+', ' ')
  616. name = unquote(name, encoding=encoding, errors=errors)
  617. name = _coerce_result(name)
  618. value = nv[1].replace('+', ' ')
  619. value = unquote(value, encoding=encoding, errors=errors)
  620. value = _coerce_result(value)
  621. r.append((name, value))
  622. return r
  623. def unquote_plus(string, encoding='utf-8', errors='replace'):
  624. """Like unquote(), but also replace plus signs by spaces, as required for
  625. unquoting HTML form values.
  626. unquote_plus('%7e/abc+def') -> '~/abc def'
  627. """
  628. string = string.replace('+', ' ')
  629. return unquote(string, encoding, errors)
  630. _ALWAYS_SAFE = frozenset(b'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
  631. b'abcdefghijklmnopqrstuvwxyz'
  632. b'0123456789'
  633. b'_.-~')
  634. _ALWAYS_SAFE_BYTES = bytes(_ALWAYS_SAFE)
  635. _safe_quoters = {}
  636. class Quoter(collections.defaultdict):
  637. """A mapping from bytes (in range(0,256)) to strings.
  638. String values are percent-encoded byte values, unless the key < 128, and
  639. in the "safe" set (either the specified safe set, or default set).
  640. """
  641. # Keeps a cache internally, using defaultdict, for efficiency (lookups
  642. # of cached keys don't call Python code at all).
  643. def __init__(self, safe):
  644. """safe: bytes object."""
  645. self.safe = _ALWAYS_SAFE.union(safe)
  646. def __repr__(self):
  647. # Without this, will just display as a defaultdict
  648. return "<%s %r>" % (self.__class__.__name__, dict(self))
  649. def __missing__(self, b):
  650. # Handle a cache miss. Store quoted string in cache and return.
  651. res = chr(b) if b in self.safe else '%{:02X}'.format(b)
  652. self[b] = res
  653. return res
  654. def quote(string, safe='/', encoding=None, errors=None):
  655. """quote('abc def') -> 'abc%20def'
  656. Each part of a URL, e.g. the path info, the query, etc., has a
  657. different set of reserved characters that must be quoted. The
  658. quote function offers a cautious (not minimal) way to quote a
  659. string for most of these parts.
  660. RFC 3986 Uniform Resource Identifier (URI): Generic Syntax lists
  661. the following (un)reserved characters.
  662. unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"
  663. reserved = gen-delims / sub-delims
  664. gen-delims = ":" / "/" / "?" / "#" / "[" / "]" / "@"
  665. sub-delims = "!" / "$" / "&" / "'" / "(" / ")"
  666. / "*" / "+" / "," / ";" / "="
  667. Each of the reserved characters is reserved in some component of a URL,
  668. but not necessarily in all of them.
  669. The quote function %-escapes all characters that are neither in the
  670. unreserved chars ("always safe") nor the additional chars set via the
  671. safe arg.
  672. The default for the safe arg is '/'. The character is reserved, but in
  673. typical usage the quote function is being called on a path where the
  674. existing slash characters are to be preserved.
  675. Python 3.7 updates from using RFC 2396 to RFC 3986 to quote URL strings.
  676. Now, "~" is included in the set of unreserved characters.
  677. string and safe may be either str or bytes objects. encoding and errors
  678. must not be specified if string is a bytes object.
  679. The optional encoding and errors parameters specify how to deal with
  680. non-ASCII characters, as accepted by the str.encode method.
  681. By default, encoding='utf-8' (characters are encoded with UTF-8), and
  682. errors='strict' (unsupported characters raise a UnicodeEncodeError).
  683. """
  684. if isinstance(string, str):
  685. if not string:
  686. return string
  687. if encoding is None:
  688. encoding = 'utf-8'
  689. if errors is None:
  690. errors = 'strict'
  691. string = string.encode(encoding, errors)
  692. else:
  693. if encoding is not None:
  694. raise TypeError("quote() doesn't support 'encoding' for bytes")
  695. if errors is not None:
  696. raise TypeError("quote() doesn't support 'errors' for bytes")
  697. return quote_from_bytes(string, safe)
  698. def quote_plus(string, safe='', encoding=None, errors=None):
  699. """Like quote(), but also replace ' ' with '+', as required for quoting
  700. HTML form values. Plus signs in the original string are escaped unless
  701. they are included in safe. It also does not have safe default to '/'.
  702. """
  703. # Check if ' ' in string, where string may either be a str or bytes. If
  704. # there are no spaces, the regular quote will produce the right answer.
  705. if ((isinstance(string, str) and ' ' not in string) or
  706. (isinstance(string, bytes) and b' ' not in string)):
  707. return quote(string, safe, encoding, errors)
  708. if isinstance(safe, str):
  709. space = ' '
  710. else:
  711. space = b' '
  712. string = quote(string, safe + space, encoding, errors)
  713. return string.replace(' ', '+')
  714. def quote_from_bytes(bs, safe='/'):
  715. """Like quote(), but accepts a bytes object rather than a str, and does
  716. not perform string-to-bytes encoding. It always returns an ASCII string.
  717. quote_from_bytes(b'abc def\x3f') -> 'abc%20def%3f'
  718. """
  719. if not isinstance(bs, (bytes, bytearray)):
  720. raise TypeError("quote_from_bytes() expected bytes")
  721. if not bs:
  722. return ''
  723. if isinstance(safe, str):
  724. # Normalize 'safe' by converting to bytes and removing non-ASCII chars
  725. safe = safe.encode('ascii', 'ignore')
  726. else:
  727. safe = bytes([c for c in safe if c < 128])
  728. if not bs.rstrip(_ALWAYS_SAFE_BYTES + safe):
  729. return bs.decode()
  730. try:
  731. quoter = _safe_quoters[safe]
  732. except KeyError:
  733. _safe_quoters[safe] = quoter = Quoter(safe).__getitem__
  734. return ''.join([quoter(char) for char in bs])
  735. def urlencode(query, doseq=False, safe='', encoding=None, errors=None,
  736. quote_via=quote_plus):
  737. """Encode a dict or sequence of two-element tuples into a URL query string.
  738. If any values in the query arg are sequences and doseq is true, each
  739. sequence element is converted to a separate parameter.
  740. If the query arg is a sequence of two-element tuples, the order of the
  741. parameters in the output will match the order of parameters in the
  742. input.
  743. The components of a query arg may each be either a string or a bytes type.
  744. The safe, encoding, and errors parameters are passed down to the function
  745. specified by quote_via (encoding and errors only if a component is a str).
  746. """
  747. if hasattr(query, "items"):
  748. query = query.items()
  749. else:
  750. # It's a bother at times that strings and string-like objects are
  751. # sequences.
  752. try:
  753. # non-sequence items should not work with len()
  754. # non-empty strings will fail this
  755. if len(query) and not isinstance(query[0], tuple):
  756. raise TypeError
  757. # Zero-length sequences of all types will get here and succeed,
  758. # but that's a minor nit. Since the original implementation
  759. # allowed empty dicts that type of behavior probably should be
  760. # preserved for consistency
  761. except TypeError:
  762. ty, va, tb = sys.exc_info()
  763. raise TypeError("not a valid non-string sequence "
  764. "or mapping object").with_traceback(tb)
  765. l = []
  766. if not doseq:
  767. for k, v in query:
  768. if isinstance(k, bytes):
  769. k = quote_via(k, safe)
  770. else:
  771. k = quote_via(str(k), safe, encoding, errors)
  772. if isinstance(v, bytes):
  773. v = quote_via(v, safe)
  774. else:
  775. v = quote_via(str(v), safe, encoding, errors)
  776. l.append(k + '=' + v)
  777. else:
  778. for k, v in query:
  779. if isinstance(k, bytes):
  780. k = quote_via(k, safe)
  781. else:
  782. k = quote_via(str(k), safe, encoding, errors)
  783. if isinstance(v, bytes):
  784. v = quote_via(v, safe)
  785. l.append(k + '=' + v)
  786. elif isinstance(v, str):
  787. v = quote_via(v, safe, encoding, errors)
  788. l.append(k + '=' + v)
  789. else:
  790. try:
  791. # Is this a sufficient test for sequence-ness?
  792. x = len(v)
  793. except TypeError:
  794. # not a sequence
  795. v = quote_via(str(v), safe, encoding, errors)
  796. l.append(k + '=' + v)
  797. else:
  798. # loop over the sequence
  799. for elt in v:
  800. if isinstance(elt, bytes):
  801. elt = quote_via(elt, safe)
  802. else:
  803. elt = quote_via(str(elt), safe, encoding, errors)
  804. l.append(k + '=' + elt)
  805. return '&'.join(l)
  806. def to_bytes(url):
  807. """to_bytes(u"URL") --> 'URL'."""
  808. # Most URL schemes require ASCII. If that changes, the conversion
  809. # can be relaxed.
  810. # XXX get rid of to_bytes()
  811. if isinstance(url, str):
  812. try:
  813. url = url.encode("ASCII").decode()
  814. except UnicodeError:
  815. raise UnicodeError("URL " + repr(url) +
  816. " contains non-ASCII characters")
  817. return url
  818. def unwrap(url):
  819. """unwrap('<URL:type://host/path>') --> 'type://host/path'."""
  820. url = str(url).strip()
  821. if url[:1] == '<' and url[-1:] == '>':
  822. url = url[1:-1].strip()
  823. if url[:4] == 'URL:': url = url[4:].strip()
  824. return url
  825. _typeprog = None
  826. def splittype(url):
  827. """splittype('type:opaquestring') --> 'type', 'opaquestring'."""
  828. global _typeprog
  829. if _typeprog is None:
  830. _typeprog = re.compile('([^/:]+):(.*)', re.DOTALL)
  831. match = _typeprog.match(url)
  832. if match:
  833. scheme, data = match.groups()
  834. return scheme.lower(), data
  835. return None, url
  836. _hostprog = None
  837. def splithost(url):
  838. """splithost('//host[:port]/path') --> 'host[:port]', '/path'."""
  839. global _hostprog
  840. if _hostprog is None:
  841. _hostprog = re.compile('//([^/#?]*)(.*)', re.DOTALL)
  842. match = _hostprog.match(url)
  843. if match:
  844. host_port, path = match.groups()
  845. if path and path[0] != '/':
  846. path = '/' + path
  847. return host_port, path
  848. return None, url
  849. def splituser(host):
  850. """splituser('user[:passwd]@host[:port]') --> 'user[:passwd]', 'host[:port]'."""
  851. user, delim, host = host.rpartition('@')
  852. return (user if delim else None), host
  853. def splitpasswd(user):
  854. """splitpasswd('user:passwd') -> 'user', 'passwd'."""
  855. user, delim, passwd = user.partition(':')
  856. return user, (passwd if delim else None)
  857. # splittag('/path#tag') --> '/path', 'tag'
  858. _portprog = None
  859. def splitport(host):
  860. """splitport('host:port') --> 'host', 'port'."""
  861. global _portprog
  862. if _portprog is None:
  863. _portprog = re.compile('(.*):([0-9]*)', re.DOTALL)
  864. match = _portprog.fullmatch(host)
  865. if match:
  866. host, port = match.groups()
  867. if port:
  868. return host, port
  869. return host, None
  870. def splitnport(host, defport=-1):
  871. """Split host and port, returning numeric port.
  872. Return given default port if no ':' found; defaults to -1.
  873. Return numerical port if a valid number are found after ':'.
  874. Return None if ':' but not a valid number."""
  875. host, delim, port = host.rpartition(':')
  876. if not delim:
  877. host = port
  878. elif port:
  879. try:
  880. nport = int(port)
  881. except ValueError:
  882. nport = None
  883. return host, nport
  884. return host, defport
  885. def splitquery(url):
  886. """splitquery('/path?query') --> '/path', 'query'."""
  887. path, delim, query = url.rpartition('?')
  888. if delim:
  889. return path, query
  890. return url, None
  891. def splittag(url):
  892. """splittag('/path#tag') --> '/path', 'tag'."""
  893. path, delim, tag = url.rpartition('#')
  894. if delim:
  895. return path, tag
  896. return url, None
  897. def splitattr(url):
  898. """splitattr('/path;attr1=value1;attr2=value2;...') ->
  899. '/path', ['attr1=value1', 'attr2=value2', ...]."""
  900. words = url.split(';')
  901. return words[0], words[1:]
  902. def splitvalue(attr):
  903. """splitvalue('attr=value') --> 'attr', 'value'."""
  904. attr, delim, value = attr.partition('=')
  905. return attr, (value if delim else None)