1
# Copyright (C) 2006-2010 Canonical Ltd
3
# This program is free software; you can redistribute it and/or modify
4
# it under the terms of the GNU General Public License as published by
5
# the Free Software Foundation; either version 2 of the License, or
6
# (at your option) any later version.
8
# This program is distributed in the hope that it will be useful,
9
# but WITHOUT ANY WARRANTY; without even the implied warranty of
10
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11
# GNU General Public License for more details.
13
# You should have received a copy of the GNU General Public License
14
# along with this program; if not, write to the Free Software
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
17
"""A collection of function for handling URL operations."""
19
from __future__ import absolute_import
25
from urllib import parse as urlparse
32
from .lazy_import import lazy_import
33
lazy_import(globals(), """
34
from posixpath import split as _posix_split
39
class InvalidURL(errors.PathError):
41
_fmt = 'Invalid url supplied to transport: "%(path)s"%(extra)s'
44
class InvalidURLJoin(errors.PathError):
46
_fmt = "Invalid URL join request: %(reason)s: %(base)r + %(join_args)r"
48
def __init__(self, reason, base, join_args):
51
self.join_args = join_args
52
errors.PathError.__init__(self, base, reason)
55
class InvalidRebaseURLs(errors.PathError):
57
_fmt = "URLs differ by more than path: %(from_)r and %(to)r"
59
def __init__(self, from_, to):
62
errors.PathError.__init__(
63
self, from_, 'URLs differ by more than path.')
66
def basename(url, exclude_trailing_slash=True):
67
"""Return the last component of a URL.
69
:param url: The URL in question
70
:param exclude_trailing_slash: If the url looks like "path/to/foo/"
71
ignore the final slash and return 'foo' rather than ''
72
:return: Just the final component of the URL. This can return ''
73
if you don't exclude_trailing_slash, or if you are at the
76
return split(url, exclude_trailing_slash=exclude_trailing_slash)[1]
79
def dirname(url, exclude_trailing_slash=True):
80
"""Return the parent directory of the given path.
82
:param url: Relative or absolute URL
83
:param exclude_trailing_slash: Remove a final slash
84
(treat http://host/foo/ as http://host/foo, but
85
http://host/ stays http://host/)
86
:return: Everything in the URL except the last path chunk
88
# TODO: jam 20060502 This was named dirname to be consistent
89
# with the os functions, but maybe "parent" would be better
90
return split(url, exclude_trailing_slash=exclude_trailing_slash)[0]
93
quote_from_bytes = urlparse.quote_from_bytes
94
quote = urlparse.quote
95
unquote_to_bytes = urlparse.unquote_to_bytes
96
unquote = urlparse.unquote
99
def escape(relpath, safe='/~'):
100
"""Escape relpath to be a valid url."""
101
return quote(relpath, safe=safe)
104
def file_relpath(base, path):
105
"""Compute just the relative sub-portion of a url
107
This assumes that both paths are already fully specified file:// URLs.
109
if len(base) < MIN_ABS_FILEURL_LENGTH:
110
raise ValueError('Length of base (%r) must equal or'
111
' exceed the platform minimum url length (which is %d)' %
112
(base, MIN_ABS_FILEURL_LENGTH))
113
base = osutils.normpath(local_path_from_url(base))
114
path = osutils.normpath(local_path_from_url(path))
115
return escape(osutils.relpath(base, path))
118
def _find_scheme_and_separator(url):
119
"""Find the scheme separator (://) and the first path separator
121
This is just a helper functions for other path utilities.
122
It could probably be replaced by urlparse
124
m = _url_scheme_re.match(url)
128
scheme = m.group('scheme')
129
path = m.group('path')
131
# Find the path separating slash
132
# (first slash after the ://)
133
first_path_slash = path.find('/')
134
if first_path_slash == -1:
135
return len(scheme), None
136
return len(scheme), first_path_slash + m.start('path')
140
"""Tests whether a URL is in actual fact a URL."""
141
return _url_scheme_re.match(url) is not None
144
def join(base, *args):
145
"""Create a URL by joining sections.
147
This will normalize '..', assuming that paths are absolute
148
(it assumes no symlinks in either path)
150
If any of *args is an absolute URL, it will be treated correctly.
152
join('http://foo', 'http://bar') => 'http://bar'
153
join('http://foo', 'bar') => 'http://foo/bar'
154
join('http://foo', 'bar', '../baz') => 'http://foo/baz'
158
scheme_end, path_start = _find_scheme_and_separator(base)
159
if scheme_end is None and path_start is None:
161
elif path_start is None:
162
path_start = len(base)
163
path = base[path_start:]
165
arg_scheme_end, arg_path_start = _find_scheme_and_separator(arg)
166
if arg_scheme_end is None and arg_path_start is None:
168
elif arg_path_start is None:
169
arg_path_start = len(arg)
170
if arg_scheme_end is not None:
172
path = arg[arg_path_start:]
173
scheme_end = arg_scheme_end
174
path_start = arg_path_start
176
path = joinpath(path, arg)
177
return base[:path_start] + path
180
def joinpath(base, *args):
181
"""Join URL path segments to a URL path segment.
183
This is somewhat like osutils.joinpath, but intended for URLs.
185
XXX: this duplicates some normalisation logic, and also duplicates a lot of
186
path handling logic that already exists in some Transport implementations.
187
We really should try to have exactly one place in the code base responsible
188
for combining paths of URLs.
190
path = base.split('/')
191
if len(path) > 1 and path[-1] == '':
192
# If the path ends in a trailing /, remove it.
195
if arg.startswith('/'):
197
for chunk in arg.split('/'):
202
raise InvalidURLJoin('Cannot go above root',
210
return '/'.join(path)
213
# jam 20060502 Sorted to 'l' because the final target is 'local_path_from_url'
214
def _posix_local_path_from_url(url):
215
"""Convert a url like file:///path/to/foo into /path/to/foo"""
216
url = strip_segment_parameters(url)
217
file_localhost_prefix = 'file://localhost/'
218
if url.startswith(file_localhost_prefix):
219
path = url[len(file_localhost_prefix) - 1:]
220
elif not url.startswith('file:///'):
222
url, 'local urls must start with file:/// or file://localhost/')
224
path = url[len('file://'):]
225
# We only strip off 2 slashes
226
return unescape(path)
229
def _posix_local_path_to_url(path):
230
"""Convert a local path like ./foo into a URL like file:///path/to/foo
232
This also handles transforming escaping unicode characters, etc.
234
# importing directly from posixpath allows us to test this
235
# on non-posix platforms
236
return 'file://' + escape(osutils._posix_abspath(path))
239
def _win32_local_path_from_url(url):
240
"""Convert a url like file:///C:/path/to/foo into C:/path/to/foo"""
241
if not url.startswith('file://'):
242
raise InvalidURL(url, 'local urls must start with file:///, '
243
'UNC path urls must start with file://')
244
url = strip_segment_parameters(url)
245
# We strip off all 3 slashes
246
win32_url = url[len('file:'):]
247
# check for UNC path: //HOST/path
248
if not win32_url.startswith('///'):
249
if (win32_url[2] == '/'
250
or win32_url[3] in '|:'):
251
raise InvalidURL(url, 'Win32 UNC path urls'
252
' have form file://HOST/path')
253
return unescape(win32_url)
255
# allow empty paths so we can serve all roots
256
if win32_url == '///':
259
# usual local path with drive letter
260
if (len(win32_url) < 6
261
or win32_url[3] not in ('abcdefghijklmnopqrstuvwxyz'
262
'ABCDEFGHIJKLMNOPQRSTUVWXYZ') or
263
win32_url[4] not in '|:'
264
or win32_url[5] != '/'):
265
raise InvalidURL(url, 'Win32 file urls start with'
266
' file:///x:/, where x is a valid drive letter')
267
return win32_url[3].upper() + u':' + unescape(win32_url[5:])
270
def _win32_local_path_to_url(path):
271
"""Convert a local path like ./foo into a URL like file:///C:/path/to/foo
273
This also handles transforming escaping unicode characters, etc.
275
# importing directly from ntpath allows us to test this
276
# on non-win32 platform
277
# FIXME: It turns out that on nt, ntpath.abspath uses nt._getfullpathname
278
# which actually strips trailing space characters.
279
# The worst part is that on linux ntpath.abspath has different
280
# semantics, since 'nt' is not an available module.
284
win32_path = osutils._win32_abspath(path)
285
# check for UNC path \\HOST\path
286
if win32_path.startswith('//'):
287
return 'file:' + escape(win32_path)
288
return ('file:///' + str(win32_path[0].upper()) + ':' +
289
escape(win32_path[2:]))
292
local_path_to_url = _posix_local_path_to_url
293
local_path_from_url = _posix_local_path_from_url
294
MIN_ABS_FILEURL_LENGTH = len('file:///')
295
WIN32_MIN_ABS_FILEURL_LENGTH = len('file:///C:/')
297
if sys.platform == 'win32':
298
local_path_to_url = _win32_local_path_to_url
299
local_path_from_url = _win32_local_path_from_url
301
MIN_ABS_FILEURL_LENGTH = WIN32_MIN_ABS_FILEURL_LENGTH
304
_url_scheme_re = re.compile('^(?P<scheme>[^:/]{2,}):(//)?(?P<path>.*)$')
305
_url_hex_escapes_re = re.compile('(%[0-9a-fA-F]{2})')
308
def _unescape_safe_chars(matchobj):
309
"""re.sub callback to convert hex-escapes to plain characters (if safe).
311
e.g. '%7E' will be converted to '~'.
313
hex_digits = matchobj.group(0)[1:]
314
char = chr(int(hex_digits, 16))
315
if char in _url_dont_escape_characters:
318
return matchobj.group(0).upper()
321
def normalize_url(url):
322
"""Make sure that a path string is in fully normalized URL form.
324
This handles URLs which have unicode characters, spaces,
325
special characters, etc.
327
It has two basic modes of operation, depending on whether the
328
supplied string starts with a url specifier (scheme://) or not.
329
If it does not have a specifier it is considered a local path,
330
and will be converted into a file:/// url. Non-ascii characters
331
will be encoded using utf-8.
332
If it does have a url specifier, it will be treated as a "hybrid"
333
URL. Basically, a URL that should have URL special characters already
334
escaped (like +?&# etc), but may have unicode characters, etc
335
which would not be valid in a real URL.
337
:param url: Either a hybrid URL or a local path
338
:return: A normalized URL which only includes 7-bit ASCII characters.
340
scheme_end, path_start = _find_scheme_and_separator(url)
341
if scheme_end is None:
342
return local_path_to_url(url)
343
prefix = url[:path_start]
344
path = url[path_start:]
345
if not isinstance(url, str):
347
if c not in _url_safe_characters:
348
raise InvalidURL(url, 'URLs can only contain specific'
349
' safe characters (not %r)' % c)
350
path = _url_hex_escapes_re.sub(_unescape_safe_chars, path)
351
return str(prefix + ''.join(path))
353
# We have a unicode (hybrid) url
354
path_chars = list(path)
356
for i in range(len(path_chars)):
357
if path_chars[i] not in _url_safe_characters:
358
path_chars[i] = ''.join(
359
['%%%02X' % c for c in bytearray(path_chars[i].encode('utf-8'))])
360
path = ''.join(path_chars)
361
path = _url_hex_escapes_re.sub(_unescape_safe_chars, path)
362
return str(prefix + path)
365
def relative_url(base, other):
366
"""Return a path to other from base.
368
If other is unrelated to base, return other. Else return a relative path.
369
This assumes no symlinks as part of the url.
371
dummy, base_first_slash = _find_scheme_and_separator(base)
372
if base_first_slash is None:
375
dummy, other_first_slash = _find_scheme_and_separator(other)
376
if other_first_slash is None:
379
# this takes care of differing schemes or hosts
380
base_scheme = base[:base_first_slash]
381
other_scheme = other[:other_first_slash]
382
if base_scheme != other_scheme:
384
elif sys.platform == 'win32' and base_scheme == 'file://':
385
base_drive = base[base_first_slash + 1:base_first_slash + 3]
386
other_drive = other[other_first_slash + 1:other_first_slash + 3]
387
if base_drive != other_drive:
390
base_path = base[base_first_slash + 1:]
391
other_path = other[other_first_slash + 1:]
393
if base_path.endswith('/'):
394
base_path = base_path[:-1]
396
base_sections = base_path.split('/')
397
other_sections = other_path.split('/')
399
if base_sections == ['']:
401
if other_sections == ['']:
405
for b, o in zip(base_sections, other_sections):
408
output_sections.append(b)
410
match_len = len(output_sections)
411
output_sections = ['..' for x in base_sections[match_len:]]
412
output_sections.extend(other_sections[match_len:])
414
return "/".join(output_sections) or "."
417
def _win32_extract_drive_letter(url_base, path):
418
"""On win32 the drive letter needs to be added to the url base."""
419
# Strip off the drive letter
420
# path is currently /C:/foo
421
if len(path) < 4 or path[2] not in ':|' or path[3] != '/':
422
raise InvalidURL(url_base + path,
423
'win32 file:/// paths need a drive letter')
424
url_base += path[0:3] # file:// + /C:
425
path = path[3:] # /foo
426
return url_base, path
429
def split(url, exclude_trailing_slash=True):
430
"""Split a URL into its parent directory and a child directory.
432
:param url: A relative or absolute URL
433
:param exclude_trailing_slash: Strip off a final '/' if it is part
434
of the path (but not if it is part of the protocol specification)
436
:return: (parent_url, child_dir). child_dir may be the empty string if
439
scheme_loc, first_path_slash = _find_scheme_and_separator(url)
441
if first_path_slash is None:
442
# We have either a relative path, or no separating slash
443
if scheme_loc is None:
445
if exclude_trailing_slash and url.endswith('/'):
447
return _posix_split(url)
449
# Scheme with no path
452
# We have a fully defined path
453
url_base = url[:first_path_slash] # http://host, file://
454
path = url[first_path_slash:] # /file/foo
456
if sys.platform == 'win32' and url.startswith('file:///'):
457
# Strip off the drive letter
458
# url_base is currently file://
459
# path is currently /C:/foo
460
url_base, path = _win32_extract_drive_letter(url_base, path)
461
# now it should be file:///C: and /foo
463
if exclude_trailing_slash and len(path) > 1 and path.endswith('/'):
465
head, tail = _posix_split(path)
466
return url_base + head, tail
469
def split_segment_parameters_raw(url):
470
"""Split the subsegment of the last segment of a URL.
472
:param url: A relative or absolute URL
473
:return: (url, subsegments)
475
# GZ 2011-11-18: Dodgy removing the terminal slash like this, function
476
# operates on urls not url+segments, and Transport classes
477
# should not be blindly adding slashes in the first place.
478
lurl = strip_trailing_slash(url)
479
# Segments begin at first comma after last forward slash, if one exists
480
segment_start = lurl.find(",", lurl.rfind("/") + 1)
481
if segment_start == -1:
483
return (lurl[:segment_start],
484
[str(s) for s in lurl[segment_start + 1:].split(",")])
487
def split_segment_parameters(url):
488
"""Split the segment parameters of the last segment of a URL.
490
:param url: A relative or absolute URL
491
:return: (url, segment_parameters)
493
(base_url, subsegments) = split_segment_parameters_raw(url)
495
for subsegment in subsegments:
497
(key, value) = subsegment.split("=", 1)
499
raise InvalidURL(url, "missing = in subsegment")
500
if not isinstance(key, str):
502
if not isinstance(value, str):
503
raise TypeError(value)
504
parameters[key] = value
505
return (base_url, parameters)
508
def strip_segment_parameters(url):
509
"""Strip the segment parameters from a URL.
511
:param url: A relative or absolute URL
514
base_url, subsegments = split_segment_parameters_raw(url)
518
def join_segment_parameters_raw(base, *subsegments):
519
"""Create a new URL by adding subsegments to an existing one.
521
This adds the specified subsegments to the last path in the specified
522
base URL. The subsegments should be bytestrings.
524
:note: You probably want to use join_segment_parameters instead.
528
for subsegment in subsegments:
529
if not isinstance(subsegment, str):
530
raise TypeError("Subsegment %r is not a bytestring" % subsegment)
531
if "," in subsegment:
532
raise InvalidURLJoin(", exists in subsegments",
534
return ",".join((base,) + subsegments)
537
def join_segment_parameters(url, parameters):
538
"""Create a new URL by adding segment parameters to an existing one.
540
The parameters of the last segment in the URL will be updated; if a
541
parameter with the same key already exists it will be overwritten.
543
:param url: A URL, as string
544
:param parameters: Dictionary of parameters, keys and values as bytestrings
546
(base, existing_parameters) = split_segment_parameters(url)
548
new_parameters.update(existing_parameters)
549
for key, value in parameters.items():
550
if not isinstance(key, str):
551
raise TypeError("parameter key %r is not a str" % key)
552
if not isinstance(value, str):
553
raise TypeError("parameter value %r for %r is not a str" %
556
raise InvalidURLJoin("= exists in parameter key", url,
558
new_parameters[key] = value
559
return join_segment_parameters_raw(
560
base, *["%s=%s" % item for item in sorted(new_parameters.items())])
563
def _win32_strip_local_trailing_slash(url):
564
"""Strip slashes after the drive letter"""
565
if len(url) > WIN32_MIN_ABS_FILEURL_LENGTH:
571
def strip_trailing_slash(url):
572
"""Strip trailing slash, except for root paths.
574
The definition of 'root path' is platform-dependent.
575
This assumes that all URLs are valid netloc urls, such that they
578
It searches for ://, and then refuses to remove the next '/'.
579
It can also handle relative paths
581
path/to/foo => path/to/foo
582
path/to/foo/ => path/to/foo
583
http://host/path/ => http://host/path
584
http://host/path => http://host/path
585
http://host/ => http://host/
587
file:///foo/ => file:///foo
588
# This is unique on win32 platforms, and is the only URL
589
# format which does it differently.
590
file:///c|/ => file:///c:/
592
if not url.endswith('/'):
595
if sys.platform == 'win32' and url.startswith('file://'):
596
return _win32_strip_local_trailing_slash(url)
598
scheme_loc, first_path_slash = _find_scheme_and_separator(url)
599
if scheme_loc is None:
600
# This is a relative path, as it has no scheme
601
# so just chop off the last character
604
if first_path_slash is None or first_path_slash == len(url) - 1:
605
# Don't chop off anything if the only slash is the path
613
"""Unescape relpath from url format.
615
This returns a Unicode path from a URL
617
# jam 20060427 URLs are supposed to be ASCII only strings
618
# If they are passed in as unicode, unquote
619
# will return a UNICODE string, which actually contains
620
# utf-8 bytes. So we have to ensure that they are
621
# plain ASCII strings, or the final .decode will
622
# try to encode the UNICODE => ASCII, and then decode
625
if isinstance(url, str):
628
except UnicodeError as e:
630
url, 'URL was not a plain ASCII url: %s' % (e,))
631
return urlparse.unquote(url)
634
# These are characters that if escaped, should stay that way
635
_no_decode_chars = ';/?:@&=+$,#'
636
_no_decode_ords = [ord(c) for c in _no_decode_chars]
637
_no_decode_hex = (['%02x' % o for o in _no_decode_ords]
638
+ ['%02X' % o for o in _no_decode_ords])
639
_hex_display_map = dict(([('%02x' % o, bytes([o])) for o in range(256)]
640
+ [('%02X' % o, bytes([o])) for o in range(256)]))
641
# These entries get mapped to themselves
642
_hex_display_map.update((hex, b'%' + hex.encode('ascii'))
643
for hex in _no_decode_hex)
645
# These characters shouldn't be percent-encoded, and it's always safe to
646
# unencode them if they are.
647
_url_dont_escape_characters = set(
648
"abcdefghijklmnopqrstuvwxyz" # Lowercase alpha
649
"ABCDEFGHIJKLMNOPQRSTUVWXYZ" # Uppercase alpha
650
"0123456789" # Numbers
651
"-._~" # Unreserved characters
654
# These characters should not be escaped
655
_url_safe_characters = set(
656
"abcdefghijklmnopqrstuvwxyz" # Lowercase alpha
657
"ABCDEFGHIJKLMNOPQRSTUVWXYZ" # Uppercase alpha
658
"0123456789" # Numbers
659
"_.-!~*'()" # Unreserved characters
660
"/;?:@&=+$," # Reserved characters
661
"%#" # Extra reserved characters
665
def _unescape_segment_for_display(segment, encoding):
666
"""Unescape a segment for display.
668
Helper for unescape_for_display
670
:param url: A 7-bit ASCII URL
671
:param encoding: The final output encoding
673
:return: A unicode string which can be safely encoded into the
676
escaped_chunks = segment.split('%')
677
escaped_chunks[0] = escaped_chunks[0].encode('utf-8')
678
for j in range(1, len(escaped_chunks)):
679
item = escaped_chunks[j]
681
escaped_chunks[j] = _hex_display_map[item[:2]]
683
# Put back the percent symbol
684
escaped_chunks[j] = b'%' + (item[:2].encode('utf-8'))
685
except UnicodeDecodeError:
686
escaped_chunks[j] = chr(int(item[:2], 16)).encode('utf-8')
687
escaped_chunks[j] += (item[2:].encode('utf-8'))
688
unescaped = b''.join(escaped_chunks)
690
decoded = unescaped.decode('utf-8')
691
except UnicodeDecodeError:
692
# If this path segment cannot be properly utf-8 decoded
693
# after doing unescaping we will just leave it alone
697
decoded.encode(encoding)
698
except UnicodeEncodeError:
699
# If this chunk cannot be encoded in the local
700
# encoding, then we should leave it alone
703
# Otherwise take the url decoded one
707
def unescape_for_display(url, encoding):
708
"""Decode what you can for a URL, so that we get a nice looking path.
710
This will turn file:// urls into local paths, and try to decode
711
any portions of a http:// style url that it can.
713
Any sections of the URL which can't be represented in the encoding or
714
need to stay as escapes are left alone.
716
:param url: A 7-bit ASCII URL
717
:param encoding: The final output encoding
719
:return: A unicode string which can be safely encoded into the
723
raise ValueError('you cannot specify None for the display encoding')
724
if url.startswith('file://'):
726
path = local_path_from_url(url)
727
path.encode(encoding)
732
# Split into sections to try to decode utf-8
734
for i in range(1, len(res)):
735
res[i] = _unescape_segment_for_display(res[i], encoding)
736
return u'/'.join(res)
739
def derive_to_location(from_location):
740
"""Derive a TO_LOCATION given a FROM_LOCATION.
742
The normal case is a FROM_LOCATION of http://foo/bar => bar.
743
The Right Thing for some logical destinations may differ though
744
because no / may be present at all. In that case, the result is
745
the full name without the scheme indicator, e.g. lp:foo-bar => foo-bar.
746
This latter case also applies when a Windows drive
747
is used without a path, e.g. c:foo-bar => foo-bar.
748
If no /, path separator or : is found, the from_location is returned.
750
from_location = strip_segment_parameters(from_location)
751
if from_location.find("/") >= 0 or from_location.find(os.sep) >= 0:
752
return os.path.basename(from_location.rstrip("/\\"))
754
sep = from_location.find(":")
756
return from_location[sep + 1:]
761
def _is_absolute(url):
762
return (osutils.pathjoin('/foo', url) == url)
765
def rebase_url(url, old_base, new_base):
766
"""Convert a relative path from an old base URL to a new base URL.
768
The result will be a relative path.
769
Absolute paths and full URLs are returned unaltered.
771
scheme, separator = _find_scheme_and_separator(url)
772
if scheme is not None:
774
if _is_absolute(url):
776
old_parsed = urlparse.urlparse(old_base)
777
new_parsed = urlparse.urlparse(new_base)
778
if (old_parsed[:2]) != (new_parsed[:2]):
779
raise InvalidRebaseURLs(old_base, new_base)
780
return determine_relative_path(new_parsed[2],
781
join(old_parsed[2], url))
784
def determine_relative_path(from_path, to_path):
785
"""Determine a relative path from from_path to to_path."""
786
from_segments = osutils.splitpath(from_path)
787
to_segments = osutils.splitpath(to_path)
789
for count, (from_element, to_element) in enumerate(zip(from_segments,
791
if from_element != to_element:
795
unique_from = from_segments[count:]
796
unique_to = to_segments[count:]
797
segments = (['..'] * len(unique_from) + unique_to)
798
if len(segments) == 0:
800
return osutils.pathjoin(*segments)
806
def __init__(self, scheme, quoted_user, quoted_password, quoted_host,
809
self.quoted_host = quoted_host
810
self.host = unquote(self.quoted_host)
811
self.quoted_user = quoted_user
812
if self.quoted_user is not None:
813
self.user = unquote(self.quoted_user)
816
self.quoted_password = quoted_password
817
if self.quoted_password is not None:
818
self.password = unquote(self.quoted_password)
822
self.quoted_path = _url_hex_escapes_re.sub(
823
_unescape_safe_chars, quoted_path)
824
self.path = unquote(self.quoted_path)
826
def __eq__(self, other):
827
return (isinstance(other, self.__class__) and
828
self.scheme == other.scheme and
829
self.host == other.host and
830
self.user == other.user and
831
self.password == other.password and
832
self.path == other.path)
835
return "<%s(%r, %r, %r, %r, %r, %r)>" % (
836
self.__class__.__name__,
837
self.scheme, self.quoted_user, self.quoted_password,
838
self.quoted_host, self.port, self.quoted_path)
841
def from_string(cls, url):
842
"""Create a URL object from a string.
844
:param url: URL as bytestring
846
# GZ 2017-06-09: Actually validate ascii-ness
847
# pad.lv/1696545: For the moment, accept both native strings and
849
if isinstance(url, str):
851
elif isinstance(url, str):
854
except UnicodeEncodeError:
855
raise InvalidURL(url)
857
raise InvalidURL(url)
858
(scheme, netloc, path, params,
859
query, fragment) = urlparse.urlparse(url, allow_fragments=False)
860
user = password = host = port = None
862
user, host = netloc.rsplit('@', 1)
864
user, password = user.split(':', 1)
868
if ':' in host and not (host[0] == '[' and host[-1] == ']'):
870
host, port = host.rsplit(':', 1)
875
raise InvalidURL('invalid port number %s in url:\n%s' %
879
if host != "" and host[0] == '[' and host[-1] == ']': # IPv6
882
return cls(scheme, user, password, host, port, path)
885
netloc = self.quoted_host
887
netloc = "[%s]" % netloc
888
if self.quoted_user is not None:
889
# Note that we don't put the password back even if we
890
# have one so that it doesn't get accidentally
892
netloc = '%s@%s' % (self.quoted_user, netloc)
893
if self.port is not None:
894
netloc = '%s:%d' % (netloc, self.port)
895
return urlparse.urlunparse(
896
(self.scheme, netloc, self.quoted_path, None, None, None))
899
def _combine_paths(base_path, relpath):
900
"""Transform a Transport-relative path to a remote absolute path.
902
This does not handle substitution of ~ but does handle '..' and '.'
907
t._combine_paths('/home/sarah', 'project/foo')
908
=> '/home/sarah/project/foo'
909
t._combine_paths('/home/sarah', '../../etc')
911
t._combine_paths('/home/sarah', '/etc')
914
:param base_path: base path
915
:param relpath: relative url string for relative part of remote path.
916
:return: urlencoded string for final path.
918
# pad.lv/1696545: For the moment, accept both native strings and
920
if isinstance(relpath, str):
922
elif isinstance(relpath, str):
924
relpath = relpath.encode()
925
except UnicodeEncodeError:
926
raise InvalidURL(relpath)
928
raise InvalidURL(relpath)
929
relpath = _url_hex_escapes_re.sub(_unescape_safe_chars, relpath)
930
if relpath.startswith('/'):
933
base_parts = base_path.split('/')
934
if len(base_parts) > 0 and base_parts[-1] == '':
935
base_parts = base_parts[:-1]
936
for p in relpath.split('/'):
938
if len(base_parts) == 0:
939
# In most filesystems, a request for the parent
940
# of root, just returns root.
947
path = '/'.join(base_parts)
948
if not path.startswith('/'):
952
def clone(self, offset=None):
953
"""Return a new URL for a path relative to this URL.
955
:param offset: A relative path, already urlencoded
956
:return: `URL` instance
958
if offset is not None:
959
relative = unescape(offset)
960
path = self._combine_paths(self.path, relative)
961
path = quote(path, safe="/~")
963
path = self.quoted_path
964
return self.__class__(self.scheme, self.quoted_user,
965
self.quoted_password, self.quoted_host, self.port,
970
"""Extract the server address, the credentials and the path from the url.
972
user, password, host and path should be quoted if they contain reserved
975
:param url: an quoted url
976
:return: (scheme, user, password, host, port, path) tuple, all fields
979
parsed_url = URL.from_string(url)
980
return (parsed_url.scheme, parsed_url.user, parsed_url.password,
981
parsed_url.host, parsed_url.port, parsed_url.path)