17
17
"""A collection of function for handling URL operations."""
19
from __future__ import absolute_import
23
from bzrlib.lazy_import import lazy_import
24
lazy_import(globals(), """
25
from posixpath import split as _posix_split, normpath as _posix_normpath
28
from urllib import parse as urlparse
35
from .lazy_import import lazy_import
36
lazy_import(globals(), """
37
from posixpath import split as _posix_split
47
class InvalidURL(errors.PathError):
49
_fmt = 'Invalid url supplied to transport: "%(path)s"%(extra)s'
52
class InvalidURLJoin(errors.PathError):
54
_fmt = "Invalid URL join request: %(reason)s: %(base)r + %(join_args)r"
56
def __init__(self, reason, base, join_args):
59
self.join_args = join_args
60
errors.PathError.__init__(self, base, reason)
63
class InvalidRebaseURLs(errors.PathError):
65
_fmt = "URLs differ by more than path: %(from_)r and %(to)r"
67
def __init__(self, from_, to):
70
errors.PathError.__init__(self, from_, 'URLs differ by more than path.')
36
73
def basename(url, exclude_trailing_slash=True):
37
74
"""Return the last component of a URL.
60
97
return split(url, exclude_trailing_slash=exclude_trailing_slash)[0]
101
quote_from_bytes = urlparse.quote_from_bytes
102
quote = urlparse.quote
103
unquote_to_bytes = urlparse.unquote_to_bytes
105
# Private copies of quote and unquote, copied from Python's
106
# urllib module because urllib unconditionally imports socket, which imports
109
always_safe = ('ABCDEFGHIJKLMNOPQRSTUVWXYZ'
110
'abcdefghijklmnopqrstuvwxyz'
113
for i, c in zip(range(256), ''.join(map(chr, range(256)))):
114
_safe_map[c] = c if (i < 128 and c in always_safe) else '%{0:02X}'.format(i)
117
def quote_from_bytes(s, safe='/'):
118
"""quote('abc def') -> 'abc%20def'
120
Each part of a URL, e.g. the path info, the query, etc., has a
121
different set of reserved characters that must be quoted.
123
RFC 2396 Uniform Resource Identifiers (URI): Generic Syntax lists
124
the following reserved characters.
126
reserved = ";" | "/" | "?" | ":" | "@" | "&" | "=" | "+" |
129
Each of these characters is reserved in some component of a URL,
130
but not necessarily in all of them.
132
By default, the quote function is intended for quoting the path
133
section of a URL. Thus, it will not encode '/'. This character
134
is reserved, but in typical usage the quote function is being
135
called on a path where the existing slash characters are used as
141
raise TypeError('None object cannot be quoted')
143
cachekey = (safe, always_safe)
145
(quoter, safe) = _safe_quoters[cachekey]
147
safe_map = _safe_map.copy()
148
safe_map.update([(c, c) for c in safe])
149
quoter = safe_map.__getitem__
150
safe = always_safe + safe
151
_safe_quoters[cachekey] = (quoter, safe)
152
if not s.rstrip(safe):
154
return ''.join(map(quoter, s))
156
quote = quote_from_bytes
157
unquote_to_bytes = urlparse.unquote
160
unquote = urlparse.unquote
63
163
def escape(relpath):
64
164
"""Escape relpath to be a valid url."""
65
if isinstance(relpath, unicode):
165
if not isinstance(relpath, str) and sys.version_info[0] == 2:
66
166
relpath = relpath.encode('utf-8')
67
# After quoting and encoding, the path should be perfectly
68
# safe as a plain ASCII string, str() just enforces this
69
return str(urllib.quote(relpath, safe='/~'))
167
return quote(relpath, safe='/~')
72
170
def file_relpath(base, path):
121
match = _url_scheme_re.match(base)
124
scheme = match.group('scheme')
125
path = match.group('path').split('/')
126
if path[-1:] == ['']:
127
# Strip off a trailing slash
128
# This helps both when we are at the root, and when
129
# 'base' has an extra slash at the end
132
path = base.split('/')
134
if scheme is not None and len(path) >= 1:
136
# the path should be represented as an abs path.
137
# we know this must be absolute because of the presence of a URL scheme.
139
path = [''] + path[1:]
141
# create an empty host, but dont alter the path - this might be a
142
# relative url fragment.
224
scheme_end, path_start = _find_scheme_and_separator(base)
225
if scheme_end is None and path_start is None:
227
elif path_start is None:
228
path_start = len(base)
229
path = base[path_start:]
147
match = _url_scheme_re.match(arg)
150
scheme = match.group('scheme')
151
# this skips .. normalisation, making http://host/../../..
153
path = match.group('path').split('/')
154
# set the host and path according to new absolute URL, discarding
155
# any previous values.
156
# XXX: duplicates mess from earlier in this function. This URL
157
# manipulation code needs some cleaning up.
158
if scheme is not None and len(path) >= 1:
161
# url scheme implies absolute path.
164
# no url scheme we take the path as is.
231
arg_scheme_end, arg_path_start = _find_scheme_and_separator(arg)
232
if arg_scheme_end is None and arg_path_start is None:
234
elif arg_path_start is None:
235
arg_path_start = len(arg)
236
if arg_scheme_end is not None:
238
path = arg[arg_path_start:]
239
scheme_end = arg_scheme_end
240
path_start = arg_path_start
167
path = '/'.join(path)
168
242
path = joinpath(path, arg)
169
path = path.split('/')
170
if remove_root and path[0:1] == ['']:
173
# Remove the leading slash from the path, so long as it isn't also the
174
# trailing slash, which we want to keep if present.
175
if path and path[0] == '' and len(path) > 1:
180
return '/'.join(path)
181
return scheme + '://' + '/'.join(path)
243
return base[:path_start] + path
184
246
def joinpath(base, *args):
237
300
# importing directly from posixpath allows us to test this
238
301
# on non-posix platforms
239
return 'file://' + escape(_posix_normpath(
240
osutils._posix_abspath(path)))
302
return 'file://' + escape(osutils._posix_abspath(path))
243
305
def _win32_local_path_from_url(url):
244
306
"""Convert a url like file:///C:/path/to/foo into C:/path/to/foo"""
245
307
if not url.startswith('file://'):
246
raise errors.InvalidURL(url, 'local urls must start with file:///, '
308
raise InvalidURL(url, 'local urls must start with file:///, '
247
309
'UNC path urls must start with file://')
310
url = split_segment_parameters_raw(url)[0]
248
311
# We strip off all 3 slashes
249
312
win32_url = url[len('file:'):]
250
313
# check for UNC path: //HOST/path
251
314
if not win32_url.startswith('///'):
252
315
if (win32_url[2] == '/'
253
316
or win32_url[3] in '|:'):
254
raise errors.InvalidURL(url, 'Win32 UNC path urls'
317
raise InvalidURL(url, 'Win32 UNC path urls'
255
318
' have form file://HOST/path')
256
319
return unescape(win32_url)
339
403
:param url: Either a hybrid URL or a local path
340
404
:return: A normalized URL which only includes 7-bit ASCII characters.
342
m = _url_scheme_re.match(url)
406
scheme_end, path_start = _find_scheme_and_separator(url)
407
if scheme_end is None:
344
408
return local_path_to_url(url)
345
scheme = m.group('scheme')
346
path = m.group('path')
347
if not isinstance(url, unicode):
409
prefix = url[:path_start]
410
path = url[path_start:]
411
if not isinstance(url, text_type):
349
413
if c not in _url_safe_characters:
350
raise errors.InvalidURL(url, 'URLs can only contain specific'
414
raise InvalidURL(url, 'URLs can only contain specific'
351
415
' safe characters (not %r)' % c)
352
416
path = _url_hex_escapes_re.sub(_unescape_safe_chars, path)
353
return str(scheme + '://' + ''.join(path))
417
return str(prefix + ''.join(path))
355
419
# We have a unicode (hybrid) url
356
420
path_chars = list(path)
358
for i in xrange(len(path_chars)):
422
for i in range(len(path_chars)):
359
423
if path_chars[i] not in _url_safe_characters:
360
424
chars = path_chars[i].encode('utf-8')
361
425
path_chars[i] = ''.join(
362
['%%%02X' % ord(c) for c in path_chars[i].encode('utf-8')])
426
['%%%02X' % c for c in bytearray(path_chars[i].encode('utf-8'))])
363
427
path = ''.join(path_chars)
364
428
path = _url_hex_escapes_re.sub(_unescape_safe_chars, path)
365
return str(scheme + '://' + path)
429
return str(prefix + path)
368
432
def relative_url(base, other):
469
533
return url_base + head, tail
536
def split_segment_parameters_raw(url):
537
"""Split the subsegment of the last segment of a URL.
539
:param url: A relative or absolute URL
540
:return: (url, subsegments)
542
# GZ 2011-11-18: Dodgy removing the terminal slash like this, function
543
# operates on urls not url+segments, and Transport classes
544
# should not be blindly adding slashes in the first place.
545
lurl = strip_trailing_slash(url)
546
# Segments begin at first comma after last forward slash, if one exists
547
segment_start = lurl.find(",", lurl.rfind("/")+1)
548
if segment_start == -1:
550
return (lurl[:segment_start], [str(s) for s in lurl[segment_start+1:].split(",")])
553
def split_segment_parameters(url):
554
"""Split the segment parameters of the last segment of a URL.
556
:param url: A relative or absolute URL
557
:return: (url, segment_parameters)
559
(base_url, subsegments) = split_segment_parameters_raw(url)
561
for subsegment in subsegments:
562
(key, value) = subsegment.split("=", 1)
563
if not isinstance(key, str):
565
if not isinstance(value, str):
566
raise TypeError(value)
567
parameters[key] = value
568
return (base_url, parameters)
571
def join_segment_parameters_raw(base, *subsegments):
572
"""Create a new URL by adding subsegments to an existing one.
574
This adds the specified subsegments to the last path in the specified
575
base URL. The subsegments should be bytestrings.
577
:note: You probably want to use join_segment_parameters instead.
581
for subsegment in subsegments:
582
if not isinstance(subsegment, str):
583
raise TypeError("Subsegment %r is not a bytestring" % subsegment)
584
if "," in subsegment:
585
raise InvalidURLJoin(", exists in subsegments",
587
return ",".join((base,) + subsegments)
590
def join_segment_parameters(url, parameters):
591
"""Create a new URL by adding segment parameters to an existing one.
593
The parameters of the last segment in the URL will be updated; if a
594
parameter with the same key already exists it will be overwritten.
596
:param url: A URL, as string
597
:param parameters: Dictionary of parameters, keys and values as bytestrings
599
(base, existing_parameters) = split_segment_parameters(url)
601
new_parameters.update(existing_parameters)
602
for key, value in parameters.items():
603
if not isinstance(key, str):
604
raise TypeError("parameter key %r is not a str" % key)
605
if not isinstance(value, str):
606
raise TypeError("parameter value %r for %r is not a str" %
609
raise InvalidURLJoin("= exists in parameter key", url,
611
new_parameters[key] = value
612
return join_segment_parameters_raw(base,
613
*["%s=%s" % item for item in sorted(new_parameters.items())])
472
616
def _win32_strip_local_trailing_slash(url):
473
617
"""Strip slashes after the drive letter"""
474
618
if len(url) > WIN32_MIN_ABS_FILEURL_LENGTH:
524
668
This returns a Unicode path from a URL
526
670
# jam 20060427 URLs are supposed to be ASCII only strings
527
# If they are passed in as unicode, urllib.unquote
671
# If they are passed in as unicode, unquote
528
672
# will return a UNICODE string, which actually contains
529
673
# utf-8 bytes. So we have to ensure that they are
530
674
# plain ASCII strings, or the final .decode will
531
675
# try to encode the UNICODE => ASCII, and then decode
535
except UnicodeError, e:
536
raise errors.InvalidURL(url, 'URL was not a plain ASCII url: %s' % (e,))
538
unquoted = urllib.unquote(url)
540
unicode_path = unquoted.decode('utf-8')
541
except UnicodeError, e:
542
raise errors.InvalidURL(url, 'Unable to encode the URL as utf-8: %s' % (e,))
679
if isinstance(url, text_type):
682
except UnicodeError as e:
683
raise InvalidURL(url, 'URL was not a plain ASCII url: %s' % (e,))
684
return urlparse.unquote(url)
686
if isinstance(url, text_type):
688
url = url.encode("ascii")
689
except UnicodeError as e:
690
raise InvalidURL(url, 'URL was not a plain ASCII url: %s' % (e,))
691
unquoted = unquote(url)
693
unicode_path = unquoted.decode('utf-8')
694
except UnicodeError as e:
695
raise InvalidURL(url, 'Unable to encode the URL as utf-8: %s' % (e,))
546
699
# These are characters that if escaped, should stay that way
572
725
"%#" # Extra reserved characters
729
def _unescape_segment_for_display(segment, encoding):
730
"""Unescape a segment for display.
732
Helper for unescape_for_display
734
:param url: A 7-bit ASCII URL
735
:param encoding: The final output encoding
737
:return: A unicode string which can be safely encoded into the
740
escaped_chunks = segment.split('%')
741
escaped_chunks[0] = escaped_chunks[0].encode('utf-8')
742
for j in range(1, len(escaped_chunks)):
743
item = escaped_chunks[j]
745
escaped_chunks[j] = _hex_display_map[item[:2]]
747
# Put back the percent symbol
748
escaped_chunks[j] = b'%' + (item[:2].encode('utf-8') if PY3 else item[:2])
749
except UnicodeDecodeError:
750
escaped_chunks[j] = unichr(int(item[:2], 16)).encode('utf-8')
751
escaped_chunks[j] += (item[2:].encode('utf-8') if PY3 else item[2:])
752
unescaped = b''.join(escaped_chunks)
754
decoded = unescaped.decode('utf-8')
755
except UnicodeDecodeError:
756
# If this path segment cannot be properly utf-8 decoded
757
# after doing unescaping we will just leave it alone
761
decoded.encode(encoding)
762
except UnicodeEncodeError:
763
# If this chunk cannot be encoded in the local
764
# encoding, then we should leave it alone
767
# Otherwise take the url decoded one
575
771
def unescape_for_display(url, encoding):
576
772
"""Decode what you can for a URL, so that we get a nice looking path.
600
796
# Split into sections to try to decode utf-8
601
797
res = url.split('/')
602
for i in xrange(1, len(res)):
603
escaped_chunks = res[i].split('%')
604
for j in xrange(1, len(escaped_chunks)):
605
item = escaped_chunks[j]
607
escaped_chunks[j] = _hex_display_map[item[:2]] + item[2:]
609
# Put back the percent symbol
610
escaped_chunks[j] = '%' + item
611
except UnicodeDecodeError:
612
escaped_chunks[j] = unichr(int(item[:2], 16)) + item[2:]
613
unescaped = ''.join(escaped_chunks)
615
decoded = unescaped.decode('utf-8')
616
except UnicodeDecodeError:
617
# If this path segment cannot be properly utf-8 decoded
618
# after doing unescaping we will just leave it alone
622
decoded.encode(encoding)
623
except UnicodeEncodeError:
624
# If this chunk cannot be encoded in the local
625
# encoding, then we should leave it alone
628
# Otherwise take the url decoded one
798
for i in range(1, len(res)):
799
res[i] = _unescape_segment_for_display(res[i], encoding)
630
800
return u'/'.join(res)
693
864
return osutils.pathjoin(*segments)
870
def __init__(self, scheme, quoted_user, quoted_password, quoted_host,
873
self.quoted_host = quoted_host
874
self.host = unquote(self.quoted_host)
875
self.quoted_user = quoted_user
876
if self.quoted_user is not None:
877
self.user = unquote(self.quoted_user)
880
self.quoted_password = quoted_password
881
if self.quoted_password is not None:
882
self.password = unquote(self.quoted_password)
886
self.quoted_path = _url_hex_escapes_re.sub(_unescape_safe_chars, quoted_path)
887
self.path = unquote(self.quoted_path)
889
def __eq__(self, other):
890
return (isinstance(other, self.__class__) and
891
self.scheme == other.scheme and
892
self.host == other.host and
893
self.user == other.user and
894
self.password == other.password and
895
self.path == other.path)
898
return "<%s(%r, %r, %r, %r, %r, %r)>" % (
899
self.__class__.__name__,
900
self.scheme, self.quoted_user, self.quoted_password,
901
self.quoted_host, self.port, self.quoted_path)
904
def from_string(cls, url):
905
"""Create a URL object from a string.
907
:param url: URL as bytestring
909
# GZ 2017-06-09: Actually validate ascii-ness
910
# pad.lv/1696545: For the moment, accept both native strings and unicode.
911
if isinstance(url, str):
913
elif isinstance(url, text_type):
916
except UnicodeEncodeError:
917
raise InvalidURL(url)
919
raise InvalidURL(url)
920
(scheme, netloc, path, params,
921
query, fragment) = urlparse.urlparse(url, allow_fragments=False)
922
user = password = host = port = None
924
user, host = netloc.rsplit('@', 1)
926
user, password = user.split(':', 1)
930
if ':' in host and not (host[0] == '[' and host[-1] == ']'):
932
host, port = host.rsplit(':', 1)
937
raise InvalidURL('invalid port number %s in url:\n%s' %
941
if host != "" and host[0] == '[' and host[-1] == ']': #IPv6
944
return cls(scheme, user, password, host, port, path)
947
netloc = self.quoted_host
949
netloc = "[%s]" % netloc
950
if self.quoted_user is not None:
951
# Note that we don't put the password back even if we
952
# have one so that it doesn't get accidentally
954
netloc = '%s@%s' % (self.quoted_user, netloc)
955
if self.port is not None:
956
netloc = '%s:%d' % (netloc, self.port)
957
return urlparse.urlunparse(
958
(self.scheme, netloc, self.quoted_path, None, None, None))
961
def _combine_paths(base_path, relpath):
962
"""Transform a Transport-relative path to a remote absolute path.
964
This does not handle substitution of ~ but does handle '..' and '.'
969
t._combine_paths('/home/sarah', 'project/foo')
970
=> '/home/sarah/project/foo'
971
t._combine_paths('/home/sarah', '../../etc')
973
t._combine_paths('/home/sarah', '/etc')
976
:param base_path: base path
977
:param relpath: relative url string for relative part of remote path.
978
:return: urlencoded string for final path.
980
# pad.lv/1696545: For the moment, accept both native strings and unicode.
981
if isinstance(relpath, str):
983
elif isinstance(relpath, text_type):
985
relpath = relpath.encode()
986
except UnicodeEncodeError:
987
raise InvalidURL(relpath)
989
raise InvalidURL(relpath)
990
relpath = _url_hex_escapes_re.sub(_unescape_safe_chars, relpath)
991
if relpath.startswith('/'):
994
base_parts = base_path.split('/')
995
if len(base_parts) > 0 and base_parts[-1] == '':
996
base_parts = base_parts[:-1]
997
for p in relpath.split('/'):
999
if len(base_parts) == 0:
1000
# In most filesystems, a request for the parent
1001
# of root, just returns root.
1007
base_parts.append(p)
1008
path = '/'.join(base_parts)
1009
if not path.startswith('/'):
1013
def clone(self, offset=None):
1014
"""Return a new URL for a path relative to this URL.
1016
:param offset: A relative path, already urlencoded
1017
:return: `URL` instance
1019
if offset is not None:
1020
relative = unescape(offset)
1021
if sys.version_info[0] == 2:
1022
relative = relative.encode('utf-8')
1023
path = self._combine_paths(self.path, relative)
1024
path = quote(path, safe="/~")
1026
path = self.quoted_path
1027
return self.__class__(self.scheme, self.quoted_user,
1028
self.quoted_password, self.quoted_host, self.port,
697
1032
def parse_url(url):
698
1033
"""Extract the server address, the credentials and the path from the url.
703
1038
:param url: an quoted url
705
1039
:return: (scheme, user, password, host, port, path) tuple, all fields
708
if isinstance(url, unicode):
709
raise errors.InvalidURL('should be ascii:\n%r' % url)
710
url = url.encode('utf-8')
711
(scheme, netloc, path, params,
712
query, fragment) = urlparse.urlparse(url, allow_fragments=False)
713
user = password = host = port = None
715
user, host = netloc.rsplit('@', 1)
717
user, password = user.split(':', 1)
718
password = urllib.unquote(password)
719
user = urllib.unquote(user)
723
if ':' in host and not (host[0] == '[' and host[-1] == ']'): #there *is* port
724
host, port = host.rsplit(':',1)
728
raise errors.InvalidURL('invalid port number %s in url:\n%s' %
730
if host != "" and host[0] == '[' and host[-1] == ']': #IPv6
733
host = urllib.unquote(host)
734
path = urllib.unquote(path)
736
return (scheme, user, password, host, port, path)
1042
parsed_url = URL.from_string(url)
1043
return (parsed_url.scheme, parsed_url.user, parsed_url.password,
1044
parsed_url.host, parsed_url.port, parsed_url.path)