60
69
return split(url, exclude_trailing_slash=exclude_trailing_slash)[0]
72
# Private copies of quote and unquote, copied from Python's
73
# urllib module because urllib unconditionally imports socket, which imports
76
always_safe = (b'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
77
b'abcdefghijklmnopqrstuvwxyz'
80
for i, c in zip(range(256), bytes(bytearray(range(256)))):
81
_safe_map[c] = c if (i < 128 and c in always_safe) else '%{0:02X}'.format(i).encode('ascii')
85
def quote(s, safe=b'/'):
86
"""quote('abc def') -> 'abc%20def'
88
Each part of a URL, e.g. the path info, the query, etc., has a
89
different set of reserved characters that must be quoted.
91
RFC 2396 Uniform Resource Identifiers (URI): Generic Syntax lists
92
the following reserved characters.
94
reserved = ";" | "/" | "?" | ":" | "@" | "&" | "=" | "+" |
97
Each of these characters is reserved in some component of a URL,
98
but not necessarily in all of them.
100
By default, the quote function is intended for quoting the path
101
section of a URL. Thus, it will not encode '/'. This character
102
is reserved, but in typical usage the quote function is being
103
called on a path where the existing slash characters are used as
109
raise TypeError('None object cannot be quoted')
111
cachekey = (safe, always_safe)
113
(quoter, safe) = _safe_quoters[cachekey]
115
safe_map = _safe_map.copy()
116
safe_map.update([(c, c) for c in safe])
117
quoter = safe_map.__getitem__
118
safe = always_safe + safe
119
_safe_quoters[cachekey] = (quoter, safe)
120
if not s.rstrip(safe):
122
return b''.join(map(quoter, s))
125
_hexdig = '0123456789ABCDEFabcdef'
126
_hextochr = dict((a + b, chr(int(a + b, 16)))
127
for a in _hexdig for b in _hexdig)
130
"""unquote('abc%20def') -> 'abc def'."""
138
s += _hextochr[item[:2]] + item[2:]
141
except UnicodeDecodeError:
142
s += unichr(int(item[:2], 16)) + item[2:]
63
146
def escape(relpath):
64
147
"""Escape relpath to be a valid url."""
65
if isinstance(relpath, unicode):
148
if isinstance(relpath, text_type):
66
149
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='/~'))
150
return quote(relpath, safe=b'/~')
72
153
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.
207
scheme_end, path_start = _find_scheme_and_separator(base)
208
if scheme_end is None and path_start is None:
210
elif path_start is None:
211
path_start = len(base)
212
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.
214
arg_scheme_end, arg_path_start = _find_scheme_and_separator(arg)
215
if arg_scheme_end is None and arg_path_start is None:
217
elif arg_path_start is None:
218
arg_path_start = len(arg)
219
if arg_scheme_end is not None:
221
path = arg[arg_path_start:]
222
scheme_end = arg_scheme_end
223
path_start = arg_path_start
167
path = '/'.join(path)
168
225
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)
226
return base[:path_start] + path
184
229
def joinpath(base, *args):
191
236
We really should try to have exactly one place in the code base responsible
192
237
for combining paths of URLs.
194
path = base.split('/')
195
if len(path) > 1 and path[-1] == '':
239
path = base.split(b'/')
240
if len(path) > 1 and path[-1] == b'':
196
241
#If the path ends in a trailing /, remove it.
199
if arg.startswith('/'):
244
if arg.startswith(b'/'):
201
for chunk in arg.split('/'):
246
for chunk in arg.split(b'/'):
206
251
raise errors.InvalidURLJoin('Cannot go above root',
210
255
path.append(chunk)
214
return '/'.join(path)
259
return b'/'.join(path)
217
262
# jam 20060502 Sorted to 'l' because the final target is 'local_path_from_url'
218
263
def _posix_local_path_from_url(url):
219
264
"""Convert a url like file:///path/to/foo into /path/to/foo"""
220
file_localhost_prefix = 'file://localhost/'
265
url = split_segment_parameters_raw(url)[0]
266
file_localhost_prefix = b'file://localhost/'
221
267
if url.startswith(file_localhost_prefix):
222
268
path = url[len(file_localhost_prefix) - 1:]
223
elif not url.startswith('file:///'):
269
elif not url.startswith(b'file:///'):
224
270
raise errors.InvalidURL(
225
271
url, 'local urls must start with file:/// or file://localhost/')
227
path = url[len('file://'):]
273
path = url[len(b'file://'):]
228
274
# We only strip off 2 slashes
229
275
return unescape(path)
339
386
:param url: Either a hybrid URL or a local path
340
387
:return: A normalized URL which only includes 7-bit ASCII characters.
342
m = _url_scheme_re.match(url)
389
scheme_end, path_start = _find_scheme_and_separator(url)
390
if scheme_end is None:
344
391
return local_path_to_url(url)
345
scheme = m.group('scheme')
346
path = m.group('path')
392
prefix = url[:path_start]
393
path = url[path_start:]
347
394
if not isinstance(url, unicode):
349
396
if c not in _url_safe_characters:
350
397
raise errors.InvalidURL(url, 'URLs can only contain specific'
351
398
' safe characters (not %r)' % c)
352
399
path = _url_hex_escapes_re.sub(_unescape_safe_chars, path)
353
return str(scheme + '://' + ''.join(path))
400
return str(prefix + ''.join(path))
355
402
# We have a unicode (hybrid) url
356
403
path_chars = list(path)
358
for i in xrange(len(path_chars)):
405
for i in range(len(path_chars)):
359
406
if path_chars[i] not in _url_safe_characters:
360
407
chars = path_chars[i].encode('utf-8')
361
408
path_chars[i] = ''.join(
362
409
['%%%02X' % ord(c) for c in path_chars[i].encode('utf-8')])
363
410
path = ''.join(path_chars)
364
411
path = _url_hex_escapes_re.sub(_unescape_safe_chars, path)
365
return str(scheme + '://' + path)
412
return str(prefix + path)
368
415
def relative_url(base, other):
469
516
return url_base + head, tail
519
def split_segment_parameters_raw(url):
520
"""Split the subsegment of the last segment of a URL.
522
:param url: A relative or absolute URL
523
:return: (url, subsegments)
525
# GZ 2011-11-18: Dodgy removing the terminal slash like this, function
526
# operates on urls not url+segments, and Transport classes
527
# should not be blindly adding slashes in the first place.
528
lurl = strip_trailing_slash(url)
529
# Segments begin at first comma after last forward slash, if one exists
530
segment_start = lurl.find(b",", lurl.rfind(b"/")+1)
531
if segment_start == -1:
533
return (lurl[:segment_start], lurl[segment_start+1:].split(b","))
536
def split_segment_parameters(url):
537
"""Split the segment parameters of the last segment of a URL.
539
:param url: A relative or absolute URL
540
:return: (url, segment_parameters)
542
(base_url, subsegments) = split_segment_parameters_raw(url)
544
for subsegment in subsegments:
545
(key, value) = subsegment.split("=", 1)
546
parameters[key] = value
547
return (base_url, parameters)
550
def join_segment_parameters_raw(base, *subsegments):
551
"""Create a new URL by adding subsegments to an existing one.
553
This adds the specified subsegments to the last path in the specified
554
base URL. The subsegments should be bytestrings.
556
:note: You probably want to use join_segment_parameters instead.
560
for subsegment in subsegments:
561
if not isinstance(subsegment, str):
562
raise TypeError("Subsegment %r is not a bytestring" % subsegment)
563
if "," in subsegment:
564
raise errors.InvalidURLJoin(", exists in subsegments",
566
return ",".join((base,) + subsegments)
569
def join_segment_parameters(url, parameters):
570
"""Create a new URL by adding segment parameters to an existing one.
572
The parameters of the last segment in the URL will be updated; if a
573
parameter with the same key already exists it will be overwritten.
575
:param url: A URL, as string
576
:param parameters: Dictionary of parameters, keys and values as bytestrings
578
(base, existing_parameters) = split_segment_parameters(url)
580
new_parameters.update(existing_parameters)
581
for key, value in parameters.items():
582
if not isinstance(key, str):
583
raise TypeError("parameter key %r is not a bytestring" % key)
584
if not isinstance(value, str):
585
raise TypeError("parameter value %r for %s is not a bytestring" %
588
raise errors.InvalidURLJoin("= exists in parameter key", url,
590
new_parameters[key] = value
591
return join_segment_parameters_raw(base,
592
*["%s=%s" % item for item in sorted(new_parameters.items())])
472
595
def _win32_strip_local_trailing_slash(url):
473
596
"""Strip slashes after the drive letter"""
474
597
if len(url) > WIN32_MIN_ABS_FILEURL_LENGTH:
524
647
This returns a Unicode path from a URL
526
649
# jam 20060427 URLs are supposed to be ASCII only strings
527
# If they are passed in as unicode, urllib.unquote
650
# If they are passed in as unicode, unquote
528
651
# will return a UNICODE string, which actually contains
529
652
# utf-8 bytes. So we have to ensure that they are
530
653
# plain ASCII strings, or the final .decode will
531
654
# 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,))
656
if isinstance(url, text_type):
658
url = url.encode("ascii")
659
except UnicodeError as e:
660
raise errors.InvalidURL(url, 'URL was not a plain ASCII url: %s' % (e,))
538
unquoted = urllib.unquote(url)
662
unquoted = unquote(url)
540
664
unicode_path = unquoted.decode('utf-8')
541
except UnicodeError, e:
665
except UnicodeError as e:
542
666
raise errors.InvalidURL(url, 'Unable to encode the URL as utf-8: %s' % (e,))
543
667
return unicode_path
693
817
return osutils.pathjoin(*segments)
823
def __init__(self, scheme, quoted_user, quoted_password, quoted_host,
826
self.quoted_host = quoted_host
827
self.host = unquote(self.quoted_host)
828
self.quoted_user = quoted_user
829
if self.quoted_user is not None:
830
self.user = unquote(self.quoted_user)
833
self.quoted_password = quoted_password
834
if self.quoted_password is not None:
835
self.password = unquote(self.quoted_password)
839
self.quoted_path = _url_hex_escapes_re.sub(_unescape_safe_chars, quoted_path)
840
self.path = unquote(self.quoted_path)
842
def __eq__(self, other):
843
return (isinstance(other, self.__class__) and
844
self.scheme == other.scheme and
845
self.host == other.host and
846
self.user == other.user and
847
self.password == other.password and
848
self.path == other.path)
851
return "<%s(%r, %r, %r, %r, %r, %r)>" % (
852
self.__class__.__name__,
853
self.scheme, self.quoted_user, self.quoted_password,
854
self.quoted_host, self.port, self.quoted_path)
857
def from_string(cls, url):
858
"""Create a URL object from a string.
860
:param url: URL as bytestring
862
if isinstance(url, unicode):
863
raise errors.InvalidURL('should be ascii:\n%r' % url)
864
url = url.encode('utf-8')
865
(scheme, netloc, path, params,
866
query, fragment) = urlparse.urlparse(url, allow_fragments=False)
867
user = password = host = port = None
869
user, host = netloc.rsplit('@', 1)
871
user, password = user.split(':', 1)
875
if ':' in host and not (host[0] == '[' and host[-1] == ']'):
877
host, port = host.rsplit(':',1)
881
raise errors.InvalidURL('invalid port number %s in url:\n%s' %
883
if host != "" and host[0] == '[' and host[-1] == ']': #IPv6
886
return cls(scheme, user, password, host, port, path)
889
netloc = self.quoted_host
891
netloc = "[%s]" % netloc
892
if self.quoted_user is not None:
893
# Note that we don't put the password back even if we
894
# have one so that it doesn't get accidentally
896
netloc = '%s@%s' % (self.quoted_user, netloc)
897
if self.port is not None:
898
netloc = '%s:%d' % (netloc, self.port)
899
return urlparse.urlunparse(
900
(self.scheme, netloc, self.quoted_path, None, None, None))
903
def _combine_paths(base_path, relpath):
904
"""Transform a Transport-relative path to a remote absolute path.
906
This does not handle substitution of ~ but does handle '..' and '.'
911
t._combine_paths('/home/sarah', 'project/foo')
912
=> '/home/sarah/project/foo'
913
t._combine_paths('/home/sarah', '../../etc')
915
t._combine_paths('/home/sarah', '/etc')
918
:param base_path: base path
919
:param relpath: relative url string for relative part of remote path.
920
:return: urlencoded string for final path.
922
if not isinstance(relpath, str):
923
raise errors.InvalidURL(relpath)
924
relpath = _url_hex_escapes_re.sub(_unescape_safe_chars, relpath)
925
if relpath.startswith('/'):
928
base_parts = base_path.split('/')
929
if len(base_parts) > 0 and base_parts[-1] == '':
930
base_parts = base_parts[:-1]
931
for p in relpath.split('/'):
933
if len(base_parts) == 0:
934
# In most filesystems, a request for the parent
935
# of root, just returns root.
942
path = '/'.join(base_parts)
943
if not path.startswith('/'):
947
def clone(self, offset=None):
948
"""Return a new URL for a path relative to this URL.
950
:param offset: A relative path, already urlencoded
951
:return: `URL` instance
953
if offset is not None:
954
relative = unescape(offset).encode('utf-8')
955
path = self._combine_paths(self.path, relative)
956
path = quote(path, safe="/~")
958
path = self.quoted_path
959
return self.__class__(self.scheme, self.quoted_user,
960
self.quoted_password, self.quoted_host, self.port,
697
964
def parse_url(url):
698
965
"""Extract the server address, the credentials and the path from the url.
703
970
:param url: an quoted url
705
971
: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)
974
parsed_url = URL.from_string(url)
975
return (parsed_url.scheme, parsed_url.user, parsed_url.password,
976
parsed_url.host, parsed_url.port, parsed_url.path)