Skip to content

GH-126367: Fix urllib.request.url2pathname() colon handling in URLs on Windows #127752

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 7 additions & 2 deletions Lib/nturl2path.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,8 +26,13 @@ def url2pathname(url):
# Skip past extra slash before UNC drive in URL path.
url = url[1:]
# Windows itself uses ":" even in URLs.
url = url.replace(':', '|')
if not '|' in url:
url = url.replace(':', '|', 1)
if not '|' in url or ('|' in url and not (
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can this not be simplified? I had a hard time understanding the code:

url = url.replace(':', '|', 1)
if not '|' in url or ('|' in url and not (
    url.startswith('|') # error case
    or '/|' in url      # error case
    or (len(url) > 2 and url[0] == '/' and url[1].isalpha() and url[2] == '|')
)):

url.startswith('|') or
'/|' in url or
(len(url) > 2 and url[0] == '/' and url[2] == '|' and url[1].isalpha()))
):
url = url.replace('|', ':', 1)
# No drive specifier, just convert slashes
# make sure not to convert quoted slashes :-)
return urllib.parse.unquote(url.replace('/', '\\'))
Expand Down
3 changes: 3 additions & 0 deletions Lib/test/test_urllib.py
Original file line number Diff line number Diff line change
Expand Up @@ -1509,6 +1509,9 @@ def test_url2pathname_win(self):
# Percent-encoded forward slashes are preserved for backwards compatibility
self.assertEqual(fn('C:/foo%2fbar'), 'C:\\foo/bar')
self.assertEqual(fn('//server/share/foo%2fbar'), '\\\\server\\share\\foo/bar')
# Colon in filenames, both with drive specifier and without
self.assertEqual(fn('//host/path/spam.foo:bar'), '\\\\host\\path\\spam.foo:bar')
self.assertEqual(fn('///c:/path/spam.foo:bar'), 'c:\\path\\spam.foo:bar')
# Round-tripping
paths = ['C:',
r'\C\test\\',
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Modified the :func:`~urllib.request.url2pathname` function in :mod:`urllib.request` to correctly handle DOS drive paths in URLs on Windows. Previously, the function produced incorrect results for UNC paths and raised OS errors for some paths.
Loading