Skip to content

Commit e92d110

Browse files
bpo-43607: Fix urllib handling of Windows paths with \\?\ prefix (GH-25539)
(cherry picked from commit 3513d55) Co-authored-by: Steve Dower <[email protected]>
1 parent 82b6c09 commit e92d110

File tree

3 files changed

+29
-1
lines changed

3 files changed

+29
-1
lines changed

Lib/nturl2path.py

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,14 @@ def pathname2url(p):
5050
# becomes
5151
# ///C:/foo/bar/spam.foo
5252
import urllib.parse
53+
# First, clean up some special forms. We are going to sacrifice
54+
# the additional information anyway
55+
if p[:4] == '\\\\?\\':
56+
p = p[4:]
57+
if p[:4].upper() == 'UNC\\':
58+
p = '\\' + p[4:]
59+
elif p[1:2] != ':':
60+
raise OSError('Bad path: ' + p)
5361
if not ':' in p:
5462
# No drive specifier, just convert slashes and quote the name
5563
if p[:2] == '\\\\':
@@ -59,7 +67,7 @@ def pathname2url(p):
5967
p = '\\\\' + p
6068
components = p.split('\\')
6169
return urllib.parse.quote('/'.join(components))
62-
comp = p.split(':')
70+
comp = p.split(':', maxsplit=2)
6371
if len(comp) != 2 or len(comp[0]) > 1:
6472
error = 'Bad path: ' + p
6573
raise OSError(error)

Lib/test/test_urllib.py

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1489,6 +1489,24 @@ def test_quoting(self):
14891489
"url2pathname() failed; %s != %s" %
14901490
(expect, result))
14911491

1492+
@unittest.skipUnless(sys.platform == 'win32',
1493+
'test specific to the nturl2path functions.')
1494+
def test_prefixes(self):
1495+
# Test special prefixes are correctly handled in pathname2url()
1496+
given = '\\\\?\\C:\\dir'
1497+
expect = '///C:/dir'
1498+
result = urllib.request.pathname2url(given)
1499+
self.assertEqual(expect, result,
1500+
"pathname2url() failed; %s != %s" %
1501+
(expect, result))
1502+
given = '\\\\?\\unc\\server\\share\\dir'
1503+
expect = '/server/share/dir'
1504+
result = urllib.request.pathname2url(given)
1505+
self.assertEqual(expect, result,
1506+
"pathname2url() failed; %s != %s" %
1507+
(expect, result))
1508+
1509+
14921510
@unittest.skipUnless(sys.platform == 'win32',
14931511
'test specific to the urllib.url2path function.')
14941512
def test_ntpath(self):
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
:mod:`urllib` can now convert Windows paths with ``\\?\`` prefixes into URL
2+
paths.

0 commit comments

Comments
 (0)