|
|
4fee97 |
diff --git a/pip/download.py b/pip/download.py
|
|
|
4fee97 |
index 54d3131..b55d694 100644
|
|
|
4fee97 |
--- a/pip/download.py
|
|
|
4fee97 |
+++ b/pip/download.py
|
|
|
4fee97 |
@@ -54,7 +54,8 @@ __all__ = ['get_file_content',
|
|
|
4fee97 |
'is_url', 'url_to_path', 'path_to_url',
|
|
|
4fee97 |
'is_archive_file', 'unpack_vcs_link',
|
|
|
4fee97 |
'unpack_file_url', 'is_vcs_url', 'is_file_url',
|
|
|
4fee97 |
- 'unpack_http_url', 'unpack_url']
|
|
|
4fee97 |
+ 'unpack_http_url', 'unpack_url',
|
|
|
4fee97 |
+ 'parse_content_disposition', 'sanitize_content_filename']
|
|
|
4fee97 |
|
|
|
4fee97 |
|
|
|
4fee97 |
logger = logging.getLogger(__name__)
|
|
|
4fee97 |
@@ -823,6 +824,28 @@ def unpack_url(link, location, download_dir=None,
|
|
|
4fee97 |
if only_download:
|
|
|
4fee97 |
write_delete_marker_file(location)
|
|
|
4fee97 |
|
|
|
4fee97 |
+def sanitize_content_filename(filename):
|
|
|
4fee97 |
+ # type: (str) -> str
|
|
|
4fee97 |
+ """
|
|
|
4fee97 |
+ Sanitize the "filename" value from a Content-Disposition header.
|
|
|
4fee97 |
+ """
|
|
|
4fee97 |
+ return os.path.basename(filename)
|
|
|
4fee97 |
+
|
|
|
4fee97 |
+
|
|
|
4fee97 |
+def parse_content_disposition(content_disposition, default_filename):
|
|
|
4fee97 |
+ # type: (str, str) -> str
|
|
|
4fee97 |
+ """
|
|
|
4fee97 |
+ Parse the "filename" value from a Content-Disposition header, and
|
|
|
4fee97 |
+ return the default filename if the result is empty.
|
|
|
4fee97 |
+ """
|
|
|
4fee97 |
+ _type, params = cgi.parse_header(content_disposition)
|
|
|
4fee97 |
+ filename = params.get('filename')
|
|
|
4fee97 |
+ if filename:
|
|
|
4fee97 |
+ # We need to sanitize the filename to prevent directory traversal
|
|
|
4fee97 |
+ # in case the filename contains ".." path parts.
|
|
|
4fee97 |
+ filename = sanitize_content_filename(filename)
|
|
|
4fee97 |
+ return filename or default_filename
|
|
|
4fee97 |
+
|
|
|
4fee97 |
|
|
|
4fee97 |
def _download_http_url(link, session, temp_dir, hashes):
|
|
|
4fee97 |
"""Download link url into temp_dir using provided session"""
|
|
|
4fee97 |
@@ -864,10 +887,7 @@ def _download_http_url(link, session, temp_dir, hashes):
|
|
|
4fee97 |
# Have a look at the Content-Disposition header for a better guess
|
|
|
4fee97 |
content_disposition = resp.headers.get('content-disposition')
|
|
|
4fee97 |
if content_disposition:
|
|
|
4fee97 |
- type, params = cgi.parse_header(content_disposition)
|
|
|
4fee97 |
- # We use ``or`` here because we don't want to use an "empty" value
|
|
|
4fee97 |
- # from the filename param.
|
|
|
4fee97 |
- filename = params.get('filename') or filename
|
|
|
4fee97 |
+ filename = parse_content_disposition(content_disposition, filename)
|
|
|
4fee97 |
ext = splitext(filename)[1]
|
|
|
4fee97 |
if not ext:
|
|
|
4fee97 |
ext = mimetypes.guess_extension(content_type)
|