-
Notifications
You must be signed in to change notification settings - Fork 41
/
_url.py
2472 lines (2134 loc) · 82.3 KB
/
_url.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- coding: utf-8 -*-
u"""Hyperlink provides Pythonic URL parsing, construction, and rendering.
Usage is straightforward::
>>> import hyperlink
>>> url = hyperlink.parse(u'http://github.com/mahmoud/hyperlink?utm_source=docs')
>>> url.host
u'github.com'
>>> secure_url = url.replace(scheme=u'https')
>>> secure_url.get('utm_source')[0]
u'docs'
Hyperlink's API centers on the :class:`DecodedURL` type, which wraps
the lower-level :class:`URL`, both of which can be returned by the
:func:`parse()` convenience function.
""" # noqa: E501
import re
import sys
import string
import socket
from socket import AF_INET, AF_INET6
try:
from socket import AddressFamily
except ImportError:
AddressFamily = int # type: ignore[assignment,misc]
from typing import (
Any,
Callable,
Dict,
Iterable,
Iterator,
List,
Mapping,
Optional,
Sequence,
Text,
Tuple,
Type,
TypeVar,
Union,
cast,
TYPE_CHECKING,
overload,
)
from unicodedata import normalize
from ._socket import inet_pton
try:
from collections.abc import Mapping as MappingABC
except ImportError: # Python 2
from collections import Mapping as MappingABC
from idna import encode as idna_encode, decode as idna_decode
PY2 = sys.version_info[0] == 2
try:
unichr
except NameError: # Py3
unichr = chr # type: Callable[[int], Text]
NoneType = type(None) # type: Type[None]
QueryPairs = Tuple[Tuple[Text, Optional[Text]], ...] # internal representation
QueryParameters = Union[
Mapping[Text, Optional[Text]],
QueryPairs,
Iterable[Tuple[Text, Optional[Text]]],
]
T = TypeVar("T")
# Literal is not available in all pythons so we only bring it in for mypy.
if TYPE_CHECKING:
from typing import Literal
# from boltons.typeutils
def make_sentinel(name="_MISSING", var_name=""):
# type: (str, str) -> object
"""Creates and returns a new **instance** of a new class, suitable for
usage as a "sentinel", a kind of singleton often used to indicate
a value is missing when ``None`` is a valid input.
Args:
name: Name of the Sentinel
var_name: Set this name to the name of the variable in its respective
module enable pickle-ability.
>>> make_sentinel(var_name='_MISSING')
_MISSING
The most common use cases here in boltons are as default values
for optional function arguments, partly because of its
less-confusing appearance in automatically generated
documentation. Sentinels also function well as placeholders in queues
and linked lists.
.. note::
By design, additional calls to ``make_sentinel`` with the same
values will not produce equivalent objects.
>>> make_sentinel('TEST') == make_sentinel('TEST')
False
>>> type(make_sentinel('TEST')) == type(make_sentinel('TEST'))
False
"""
class Sentinel(object):
def __init__(self):
# type: () -> None
self.name = name
self.var_name = var_name
def __repr__(self):
# type: () -> str
if self.var_name:
return self.var_name
return "%s(%r)" % (self.__class__.__name__, self.name)
if var_name:
# superclass type hints don't allow str return type, but it is
# allowed in the docs, hence the ignore[override] below
def __reduce__(self):
# type: () -> str
return self.var_name
def __nonzero__(self):
# type: () -> bool
return False
__bool__ = __nonzero__
return Sentinel()
_unspecified = _UNSET = make_sentinel("_UNSET") # type: Any
# RFC 3986 Section 2.3, Unreserved URI Characters
# https://tools.ietf.org/html/rfc3986#section-2.3
_UNRESERVED_CHARS = frozenset(
"~-._0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ" "abcdefghijklmnopqrstuvwxyz"
)
# URL parsing regex (based on RFC 3986 Appendix B, with modifications)
_URL_RE = re.compile(
r"^((?P<scheme>[^:/?#]+):)?"
r"((?P<_netloc_sep>//)"
r"(?P<authority>[^/?#]*))?"
r"(?P<path>[^?#]*)"
r"(\?(?P<query>[^#]*))?"
r"(#(?P<fragment>.*))?$"
)
_SCHEME_RE = re.compile(r"^[a-zA-Z0-9+-.]*$")
_AUTHORITY_RE = re.compile(
r"^(?:(?P<userinfo>[^@/?#]*)@)?"
r"(?P<host>"
r"(?:\[(?P<ipv6_host>[^[\]/?#]*)\])"
r"|(?P<plain_host>[^:/?#[\]]*)"
r"|(?P<bad_host>.*?))?"
r"(?::(?P<port>.*))?$"
)
_HEX_CHAR_MAP = dict(
[
((a + b).encode("ascii"), unichr(int(a + b, 16)).encode("charmap"))
for a in string.hexdigits
for b in string.hexdigits
]
)
_ASCII_RE = re.compile("([\x00-\x7f]+)")
# RFC 3986 section 2.2, Reserved Characters
# https://tools.ietf.org/html/rfc3986#section-2.2
_GEN_DELIMS = frozenset(u":/?#[]@")
_SUB_DELIMS = frozenset(u"!$&'()*+,;=")
_ALL_DELIMS = _GEN_DELIMS | _SUB_DELIMS
_USERINFO_SAFE = _UNRESERVED_CHARS | _SUB_DELIMS | set(u"%")
_USERINFO_DELIMS = _ALL_DELIMS - _USERINFO_SAFE
_PATH_SAFE = _USERINFO_SAFE | set(u":@")
_PATH_DELIMS = _ALL_DELIMS - _PATH_SAFE
_SCHEMELESS_PATH_SAFE = _PATH_SAFE - set(":")
_SCHEMELESS_PATH_DELIMS = _ALL_DELIMS - _SCHEMELESS_PATH_SAFE
_FRAGMENT_SAFE = _UNRESERVED_CHARS | _PATH_SAFE | set(u"/?")
_FRAGMENT_DELIMS = _ALL_DELIMS - _FRAGMENT_SAFE
_QUERY_VALUE_SAFE = _UNRESERVED_CHARS | _FRAGMENT_SAFE - set(u"&")
_QUERY_VALUE_DELIMS = _ALL_DELIMS - _QUERY_VALUE_SAFE
_QUERY_KEY_SAFE = _UNRESERVED_CHARS | _QUERY_VALUE_SAFE - set(u"=")
_QUERY_KEY_DELIMS = _ALL_DELIMS - _QUERY_KEY_SAFE
def _make_decode_map(delims, allow_percent=False):
# type: (Iterable[Text], bool) -> Mapping[bytes, bytes]
ret = dict(_HEX_CHAR_MAP)
if not allow_percent:
delims = set(delims) | set([u"%"])
for delim in delims:
_hexord = "{0:02X}".format(ord(delim)).encode("ascii")
_hexord_lower = _hexord.lower()
ret.pop(_hexord)
if _hexord != _hexord_lower:
ret.pop(_hexord_lower)
return ret
def _make_quote_map(safe_chars):
# type: (Iterable[Text]) -> Mapping[Union[int, Text], Text]
ret = {} # type: Dict[Union[int, Text], Text]
# v is included in the dict for py3 mostly, because bytestrings
# are iterables of ints, of course!
for i, v in zip(range(256), range(256)):
c = chr(v)
if c in safe_chars:
ret[c] = ret[v] = c
else:
ret[c] = ret[v] = "%{0:02X}".format(i)
return ret
_USERINFO_PART_QUOTE_MAP = _make_quote_map(_USERINFO_SAFE)
_USERINFO_DECODE_MAP = _make_decode_map(_USERINFO_DELIMS)
_PATH_PART_QUOTE_MAP = _make_quote_map(_PATH_SAFE)
_SCHEMELESS_PATH_PART_QUOTE_MAP = _make_quote_map(_SCHEMELESS_PATH_SAFE)
_PATH_DECODE_MAP = _make_decode_map(_PATH_DELIMS)
_QUERY_KEY_QUOTE_MAP = _make_quote_map(_QUERY_KEY_SAFE)
_QUERY_KEY_DECODE_MAP = _make_decode_map(_QUERY_KEY_DELIMS)
_QUERY_VALUE_QUOTE_MAP = _make_quote_map(_QUERY_VALUE_SAFE)
_QUERY_VALUE_DECODE_MAP = _make_decode_map(_QUERY_VALUE_DELIMS | set("+"))
_FRAGMENT_QUOTE_MAP = _make_quote_map(_FRAGMENT_SAFE)
_FRAGMENT_DECODE_MAP = _make_decode_map(_FRAGMENT_DELIMS)
_UNRESERVED_QUOTE_MAP = _make_quote_map(_UNRESERVED_CHARS)
_UNRESERVED_DECODE_MAP = dict(
[
(k, v)
for k, v in _HEX_CHAR_MAP.items()
if v.decode("ascii", "replace") in _UNRESERVED_CHARS
]
)
_ROOT_PATHS = frozenset(((), (u"",)))
def _encode_reserved(text, maximal=True):
# type: (Text, bool) -> Text
"""A very comprehensive percent encoding for encoding all
delimiters. Used for arguments to DecodedURL, where a % means a
percent sign, and not the character used by URLs for escaping
bytes.
"""
if maximal:
bytestr = normalize("NFC", text).encode("utf8")
return u"".join([_UNRESERVED_QUOTE_MAP[b] for b in bytestr])
return u"".join(
[
_UNRESERVED_QUOTE_MAP[t] if t in _UNRESERVED_CHARS else t
for t in text
]
)
def _encode_path_part(text, maximal=True):
# type: (Text, bool) -> Text
"Percent-encode a single segment of a URL path."
if maximal:
bytestr = normalize("NFC", text).encode("utf8")
return u"".join([_PATH_PART_QUOTE_MAP[b] for b in bytestr])
return u"".join(
[_PATH_PART_QUOTE_MAP[t] if t in _PATH_DELIMS else t for t in text]
)
def _encode_schemeless_path_part(text, maximal=True):
# type: (Text, bool) -> Text
"""Percent-encode the first segment of a URL path for a URL without a
scheme specified.
"""
if maximal:
bytestr = normalize("NFC", text).encode("utf8")
return u"".join([_SCHEMELESS_PATH_PART_QUOTE_MAP[b] for b in bytestr])
return u"".join(
[
_SCHEMELESS_PATH_PART_QUOTE_MAP[t]
if t in _SCHEMELESS_PATH_DELIMS
else t
for t in text
]
)
def _encode_path_parts(
text_parts, # type: Sequence[Text]
rooted=False, # type: bool
has_scheme=True, # type: bool
has_authority=True, # type: bool
maximal=True, # type: bool
):
# type: (...) -> Sequence[Text]
"""
Percent-encode a tuple of path parts into a complete path.
Setting *maximal* to False percent-encodes only the reserved
characters that are syntactically necessary for serialization,
preserving any IRI-style textual data.
Leaving *maximal* set to its default True percent-encodes
everything required to convert a portion of an IRI to a portion of
a URI.
RFC 3986 3.3:
If a URI contains an authority component, then the path component
must either be empty or begin with a slash ("/") character. If a URI
does not contain an authority component, then the path cannot begin
with two slash characters ("//"). In addition, a URI reference
(Section 4.1) may be a relative-path reference, in which case the
first path segment cannot contain a colon (":") character.
"""
if not text_parts:
return ()
if rooted:
text_parts = (u"",) + tuple(text_parts)
# elif has_authority and text_parts:
# raise Exception('see rfc above') # TODO: too late to fail like this?
encoded_parts = [] # type: List[Text]
if has_scheme:
encoded_parts = [
_encode_path_part(part, maximal=maximal) if part else part
for part in text_parts
]
else:
encoded_parts = [_encode_schemeless_path_part(text_parts[0])]
encoded_parts.extend(
[
_encode_path_part(part, maximal=maximal) if part else part
for part in text_parts[1:]
]
)
return tuple(encoded_parts)
def _encode_query_key(text, maximal=True):
# type: (Text, bool) -> Text
"""
Percent-encode a single query string key or value.
"""
if maximal:
bytestr = normalize("NFC", text).encode("utf8")
return u"".join([_QUERY_KEY_QUOTE_MAP[b] for b in bytestr])
return u"".join(
[_QUERY_KEY_QUOTE_MAP[t] if t in _QUERY_KEY_DELIMS else t for t in text]
)
def _encode_query_value(text, maximal=True):
# type: (Text, bool) -> Text
"""
Percent-encode a single query string key or value.
"""
if maximal:
bytestr = normalize("NFC", text).encode("utf8")
return u"".join([_QUERY_VALUE_QUOTE_MAP[b] for b in bytestr])
return u"".join(
[
_QUERY_VALUE_QUOTE_MAP[t] if t in _QUERY_VALUE_DELIMS else t
for t in text
]
)
def _encode_fragment_part(text, maximal=True):
# type: (Text, bool) -> Text
"""Quote the fragment part of the URL. Fragments don't have
subdelimiters, so the whole URL fragment can be passed.
"""
if maximal:
bytestr = normalize("NFC", text).encode("utf8")
return u"".join([_FRAGMENT_QUOTE_MAP[b] for b in bytestr])
return u"".join(
[_FRAGMENT_QUOTE_MAP[t] if t in _FRAGMENT_DELIMS else t for t in text]
)
def _encode_userinfo_part(text, maximal=True):
# type: (Text, bool) -> Text
"""Quote special characters in either the username or password
section of the URL.
"""
if maximal:
bytestr = normalize("NFC", text).encode("utf8")
return u"".join([_USERINFO_PART_QUOTE_MAP[b] for b in bytestr])
return u"".join(
[
_USERINFO_PART_QUOTE_MAP[t] if t in _USERINFO_DELIMS else t
for t in text
]
)
# This port list painstakingly curated by hand searching through
# https://www.iana.org/assignments/uri-schemes/uri-schemes.xhtml
# and
# https://www.iana.org/assignments/service-names-port-numbers/service-names-port-numbers.xhtml
SCHEME_PORT_MAP = {
"acap": 674,
"afp": 548,
"dict": 2628,
"dns": 53,
"file": None,
"ftp": 21,
"git": 9418,
"gopher": 70,
"http": 80,
"https": 443,
"imap": 143,
"ipp": 631,
"ipps": 631,
"irc": 194,
"ircs": 6697,
"ldap": 389,
"ldaps": 636,
"mms": 1755,
"msrp": 2855,
"msrps": None,
"mtqp": 1038,
"nfs": 111,
"nntp": 119,
"nntps": 563,
"pop": 110,
"prospero": 1525,
"redis": 6379,
"rsync": 873,
"rtsp": 554,
"rtsps": 322,
"rtspu": 5005,
"sftp": 22,
"smb": 445,
"snmp": 161,
"ssh": 22,
"steam": None,
"svn": 3690,
"telnet": 23,
"ventrilo": 3784,
"vnc": 5900,
"wais": 210,
"ws": 80,
"wss": 443,
"xmpp": None,
}
# This list of schemes that don't use authorities is also from the link above.
NO_NETLOC_SCHEMES = set(
[
"urn",
"about",
"bitcoin",
"blob",
"data",
"geo",
"magnet",
"mailto",
"news",
"pkcs11",
"sip",
"sips",
"tel",
]
)
# As of Mar 11, 2017, there were 44 netloc schemes, and 13 non-netloc
NO_QUERY_PLUS_SCHEMES = set()
def register_scheme(
text, uses_netloc=True, default_port=None, query_plus_is_space=True
):
# type: (Text, bool, Optional[int], bool) -> None
"""Registers new scheme information, resulting in correct port and
slash behavior from the URL object. There are dozens of standard
schemes preregistered, so this function is mostly meant for
proprietary internal customizations or stopgaps on missing
standards information. If a scheme seems to be missing, please
`file an issue`_!
Args:
text: A string representation of the scheme.
(the 'http' in 'http://hatnote.com')
uses_netloc: Does the scheme support specifying a
network host? For instance, "http" does, "mailto" does
not. Defaults to True.
default_port: The default port, if any, for
netloc-using schemes.
query_plus_is_space: If true, a "+" in the query string should be
decoded as a space by DecodedURL.
.. _file an issue: https://github.com/mahmoud/hyperlink/issues
"""
text = text.lower()
if default_port is not None:
try:
default_port = int(default_port)
except (ValueError, TypeError):
raise ValueError(
"default_port expected integer or None, not %r"
% (default_port,)
)
if uses_netloc is True:
SCHEME_PORT_MAP[text] = default_port
elif uses_netloc is False:
if default_port is not None:
raise ValueError(
"unexpected default port while specifying"
" non-netloc scheme: %r" % default_port
)
NO_NETLOC_SCHEMES.add(text)
else:
raise ValueError("uses_netloc expected bool, not: %r" % uses_netloc)
if not query_plus_is_space:
NO_QUERY_PLUS_SCHEMES.add(text)
return
def scheme_uses_netloc(scheme, default=None):
# type: (Text, Optional[bool]) -> Optional[bool]
"""Whether or not a URL uses :code:`:` or :code:`://` to separate the
scheme from the rest of the URL depends on the scheme's own
standard definition. There is no way to infer this behavior
from other parts of the URL. A scheme either supports network
locations or it does not.
The URL type's approach to this is to check for explicitly
registered schemes, with common schemes like HTTP
preregistered. This is the same approach taken by
:mod:`urlparse`.
URL adds two additional heuristics if the scheme as a whole is
not registered. First, it attempts to check the subpart of the
scheme after the last ``+`` character. This adds intuitive
behavior for schemes like ``git+ssh``. Second, if a URL with
an unrecognized scheme is loaded, it will maintain the
separator it sees.
"""
if not scheme:
return False
scheme = scheme.lower()
if scheme in SCHEME_PORT_MAP:
return True
if scheme in NO_NETLOC_SCHEMES:
return False
if scheme.split("+")[-1] in SCHEME_PORT_MAP:
return True
return default
class URLParseError(ValueError):
"""Exception inheriting from :exc:`ValueError`, raised when failing to
parse a URL. Mostly raised on invalid ports and IPv6 addresses.
"""
pass
def _optional(argument, default):
# type: (Any, Any) -> Any
if argument is _UNSET:
return default
else:
return argument
def _typecheck(name, value, *types):
# type: (Text, T, Type[Any]) -> T
"""
Check that the given *value* is one of the given *types*, or raise an
exception describing the problem using *name*.
"""
if not types:
raise ValueError("expected one or more types, maybe use _textcheck?")
if not isinstance(value, types):
raise TypeError(
"expected %s for %s, got %r"
% (" or ".join([t.__name__ for t in types]), name, value)
)
return value
def _textcheck(name, value, delims=frozenset(), nullable=False):
# type: (Text, T, Iterable[Text], bool) -> T
if not isinstance(value, Text):
if nullable and value is None:
# used by query string values
return value # type: ignore[unreachable]
else:
str_name = "unicode" if PY2 else "str"
exp = str_name + " or NoneType" if nullable else str_name
raise TypeError("expected %s for %s, got %r" % (exp, name, value))
if delims and set(value) & set(delims): # TODO: test caching into regexes
raise ValueError(
"one or more reserved delimiters %s present in %s: %r"
% ("".join(delims), name, value)
)
return value # type: ignore[return-value] # T vs. Text
def iter_pairs(iterable):
# type: (Iterable[Any]) -> Iterator[Any]
"""
Iterate over the (key, value) pairs in ``iterable``.
This handles dictionaries sensibly, and falls back to assuming the
iterable yields (key, value) pairs. This behaviour is similar to
what Python's ``dict()`` constructor does.
"""
if isinstance(iterable, MappingABC):
iterable = iterable.items()
return iter(iterable)
def _decode_unreserved(text, normalize_case=False, encode_stray_percents=False):
# type: (Text, bool, bool) -> Text
return _percent_decode(
text,
normalize_case=normalize_case,
encode_stray_percents=encode_stray_percents,
_decode_map=_UNRESERVED_DECODE_MAP,
)
def _decode_userinfo_part(
text, normalize_case=False, encode_stray_percents=False
):
# type: (Text, bool, bool) -> Text
return _percent_decode(
text,
normalize_case=normalize_case,
encode_stray_percents=encode_stray_percents,
_decode_map=_USERINFO_DECODE_MAP,
)
def _decode_path_part(text, normalize_case=False, encode_stray_percents=False):
# type: (Text, bool, bool) -> Text
"""
>>> _decode_path_part(u'%61%77%2f%7a')
u'aw%2fz'
>>> _decode_path_part(u'%61%77%2f%7a', normalize_case=True)
u'aw%2Fz'
"""
return _percent_decode(
text,
normalize_case=normalize_case,
encode_stray_percents=encode_stray_percents,
_decode_map=_PATH_DECODE_MAP,
)
def _decode_query_key(text, normalize_case=False, encode_stray_percents=False):
# type: (Text, bool, bool) -> Text
return _percent_decode(
text,
normalize_case=normalize_case,
encode_stray_percents=encode_stray_percents,
_decode_map=_QUERY_KEY_DECODE_MAP,
)
def _decode_query_value(
text, normalize_case=False, encode_stray_percents=False
):
# type: (Text, bool, bool) -> Text
return _percent_decode(
text,
normalize_case=normalize_case,
encode_stray_percents=encode_stray_percents,
_decode_map=_QUERY_VALUE_DECODE_MAP,
)
def _decode_fragment_part(
text, normalize_case=False, encode_stray_percents=False
):
# type: (Text, bool, bool) -> Text
return _percent_decode(
text,
normalize_case=normalize_case,
encode_stray_percents=encode_stray_percents,
_decode_map=_FRAGMENT_DECODE_MAP,
)
def _percent_decode(
text, # type: Text
normalize_case=False, # type: bool
subencoding="utf-8", # type: Text
raise_subencoding_exc=False, # type: bool
encode_stray_percents=False, # type: bool
_decode_map=_HEX_CHAR_MAP, # type: Mapping[bytes, bytes]
):
# type: (...) -> Text
"""Convert percent-encoded text characters to their normal,
human-readable equivalents.
All characters in the input text must be encodable by
*subencoding*. All special characters underlying the values in the
percent-encoding must be decodable as *subencoding*. If a
non-*subencoding*-valid string is passed, the original text is
returned with no changes applied.
Only called by field-tailored variants, e.g.,
:func:`_decode_path_part`, as every percent-encodable part of the
URL has characters which should not be percent decoded.
>>> _percent_decode(u'abc%20def')
u'abc def'
Args:
text: Text with percent-encoding present.
normalize_case: Whether undecoded percent segments, such as encoded
delimiters, should be uppercased, per RFC 3986 Section 2.1.
See :func:`_decode_path_part` for an example.
subencoding: The name of the encoding underlying the percent-encoding.
raise_subencoding_exc: Whether an error in decoding the bytes
underlying the percent-decoding should be raised.
Returns:
Text: The percent-decoded version of *text*, decoded by *subencoding*.
"""
try:
quoted_bytes = text.encode(subencoding)
except UnicodeEncodeError:
return text
bits = quoted_bytes.split(b"%")
if len(bits) == 1:
return text
res = [bits[0]]
append = res.append
for item in bits[1:]:
hexpair, rest = item[:2], item[2:]
try:
append(_decode_map[hexpair])
append(rest)
except KeyError:
pair_is_hex = hexpair in _HEX_CHAR_MAP
if pair_is_hex or not encode_stray_percents:
append(b"%")
else:
# if it's undecodable, treat as a real percent sign,
# which is reserved (because it wasn't in the
# context-aware _decode_map passed in), and should
# stay in an encoded state.
append(b"%25")
if normalize_case and pair_is_hex:
append(hexpair.upper())
append(rest)
else:
append(item)
unquoted_bytes = b"".join(res)
try:
return unquoted_bytes.decode(subencoding)
except UnicodeDecodeError:
if raise_subencoding_exc:
raise
return text
def _decode_host(host):
# type: (Text) -> Text
"""Decode a host from ASCII-encodable text to IDNA-decoded text. If
the host text is not ASCII, it is returned unchanged, as it is
presumed that it is already IDNA-decoded.
Some technical details: _decode_host is built on top of the "idna"
package, which has some quirks:
Capital letters are not valid IDNA2008. The idna package will
raise an exception like this on capital letters:
> idna.core.InvalidCodepoint: Codepoint U+004B at position 1 ... not allowed
However, if a segment of a host (i.e., something in
url.host.split('.')) is already ASCII, idna doesn't perform its
usual checks. In fact, for capital letters it automatically
lowercases them.
This check and some other functionality can be bypassed by passing
uts46=True to idna.encode/decode. This allows a more permissive and
convenient interface. So far it seems like the balanced approach.
Example output (from idna==2.6):
>> idna.encode(u'mahmöud.io')
'xn--mahmud-zxa.io'
>> idna.encode(u'Mahmöud.io')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/home/mahmoud/virtualenvs/hyperlink/local/lib/python2.7/site-packages/idna/core.py", line 355, in encode
result.append(alabel(label))
File "/home/mahmoud/virtualenvs/hyperlink/local/lib/python2.7/site-packages/idna/core.py", line 276, in alabel
check_label(label)
File "/home/mahmoud/virtualenvs/hyperlink/local/lib/python2.7/site-packages/idna/core.py", line 253, in check_label
raise InvalidCodepoint('Codepoint {0} at position {1} of {2} not allowed'.format(_unot(cp_value), pos+1, repr(label)))
idna.core.InvalidCodepoint: Codepoint U+004D at position 1 of u'Mahm\xf6ud' not allowed
>> idna.encode(u'Mahmoud.io')
'Mahmoud.io'
# Similar behavior for decodes below
>> idna.decode(u'Mahmoud.io')
u'mahmoud.io
>> idna.decode(u'Méhmoud.io', uts46=True)
u'm\xe9hmoud.io'
""" # noqa: E501
if not host:
return u""
try:
host_bytes = host.encode("ascii")
except UnicodeEncodeError:
host_text = host
else:
try:
host_text = idna_decode(host_bytes, uts46=True)
except ValueError:
# only reached on "narrow" (UCS-2) Python builds <3.4, see #7
# NOTE: not going to raise here, because there's no
# ambiguity in the IDNA, and the host is still
# technically usable
host_text = host
return host_text
def _resolve_dot_segments(path):
# type: (Sequence[Text]) -> Sequence[Text]
"""Normalize the URL path by resolving segments of '.' and '..'. For
more details, see `RFC 3986 section 5.2.4, Remove Dot Segments`_.
Args:
path: sequence of path segments in text form
Returns:
A new sequence of path segments with the '.' and '..' elements removed
and resolved.
.. _RFC 3986 section 5.2.4, Remove Dot Segments: https://tools.ietf.org/html/rfc3986#section-5.2.4
""" # noqa: E501
segs = [] # type: List[Text]
for seg in path:
if seg == u".":
pass
elif seg == u"..":
if segs:
segs.pop()
else:
segs.append(seg)
if list(path[-1:]) in ([u"."], [u".."]):
segs.append(u"")
return segs
def parse_host(host):
# type: (Text) -> Tuple[Optional[AddressFamily], Text]
"""Parse the host into a tuple of ``(family, host)``, where family
is the appropriate :mod:`socket` module constant when the host is
an IP address. Family is ``None`` when the host is not an IP.
Will raise :class:`URLParseError` on invalid IPv6 constants.
Returns:
family (socket constant or None), host (string)
>>> import socket
>>> parse_host('googlewebsite.com') == (None, 'googlewebsite.com')
True
>>> parse_host('::1') == (socket.AF_INET6, '::1')
True
>>> parse_host('192.168.1.1') == (socket.AF_INET, '192.168.1.1')
True
"""
if not host:
return None, u""
if u":" in host:
try:
inet_pton(AF_INET6, host)
except socket.error as se:
raise URLParseError("invalid IPv6 host: %r (%r)" % (host, se))
except UnicodeEncodeError:
pass # TODO: this can't be a real host right?
else:
family = AF_INET6 # type: Optional[AddressFamily]
else:
try:
inet_pton(AF_INET, host)
except (socket.error, UnicodeEncodeError):
family = None # not an IP
else:
family = AF_INET
return family, host
class URL(object):
r"""From blogs to billboards, URLs are so common, that it's easy to
overlook their complexity and power. With hyperlink's
:class:`URL` type, working with URLs doesn't have to be hard.
URLs are made of many parts. Most of these parts are officially
named in `RFC 3986`_ and this diagram may prove handy in identifying
them::
foo://user:pass@example.com:8042/over/there?name=ferret#nose
\_/ \_______/ \_________/ \__/\_________/ \_________/ \__/
| | | | | | |
scheme userinfo host port path query fragment
While :meth:`~URL.from_text` is used for parsing whole URLs, the
:class:`URL` constructor builds a URL from the individual
components, like so::
>>> from hyperlink import URL
>>> url = URL(scheme=u'https', host=u'example.com', path=[u'hello', u'world'])
>>> print(url.to_text())
https://example.com/hello/world
The constructor runs basic type checks. All strings are expected
to be text (:class:`str` in Python 3, :class:`unicode` in Python 2). All
arguments are optional, defaulting to appropriately empty values. A full
list of constructor arguments is below.
Args:
scheme: The text name of the scheme.
host: The host portion of the network location
port: The port part of the network location. If ``None`` or no port is
passed, the port will default to the default port of the scheme, if
it is known. See the ``SCHEME_PORT_MAP`` and
:func:`register_default_port` for more info.
path: A tuple of strings representing the slash-separated parts of the
path, each percent-encoded.
query: The query parameters, as a dictionary or as an sequence of
percent-encoded key-value pairs.
fragment: The fragment part of the URL.
rooted: A rooted URL is one which indicates an absolute path.
This is True on any URL that includes a host, or any relative URL
that starts with a slash.
userinfo: The username or colon-separated username:password pair.
uses_netloc: Indicates whether ``://`` (the "netloc separator") will
appear to separate the scheme from the *path* in cases where no
host is present.
Setting this to ``True`` is a non-spec-compliant affordance for the
common practice of having URIs that are *not* URLs (cannot have a
'host' part) but nevertheless use the common ``://`` idiom that
most people associate with URLs; e.g. ``message:`` URIs like
``message://message-id`` being equivalent to ``message:message-id``.
This may be inferred based on the scheme depending on whether
:func:`register_scheme` has been used to register the scheme and
should not be passed directly unless you know the scheme works like
this and you know it has not been registered.
All of these parts are also exposed as read-only attributes of :class:`URL`
instances, along with several useful methods.
.. _RFC 3986: https://tools.ietf.org/html/rfc3986
.. _RFC 3987: https://tools.ietf.org/html/rfc3987
""" # noqa: E501
def __init__(
self,
scheme=None, # type: Optional[Text]
host=None, # type: Optional[Text]
path=(), # type: Iterable[Text]
query=(), # type: QueryParameters
fragment=u"", # type: Text
port=None, # type: Optional[int]
rooted=None, # type: Optional[bool]
userinfo=u"", # type: Text
uses_netloc=None, # type: Optional[bool]
):
# type: (...) -> None
if host is not None and scheme is None:
scheme = u"http" # TODO: why
if port is None and scheme is not None:
port = SCHEME_PORT_MAP.get(scheme)
if host and query and not path:
# per RFC 3986 6.2.3, "a URI that uses the generic syntax
# for authority with an empty path should be normalized to
# a path of '/'."
path = (u"",)