Skip to content
This repository was archived by the owner on Jun 25, 2020. It is now read-only.

File download broken for chunked responses from github with Python 3.x - #140

Closed
kartikmohta wants to merge 1 commit into
vcstools:masterfrom
kartikmohta:patch-1
Closed

kartikmohta wants to merge 1 commit into
vcstools:masterfrom
kartikmohta:patch-1

Conversation

@kartikmohta

@kartikmohta kartikmohta commented Sep 8, 2018 •

Copy link
Copy Markdown

Environment: Python 3.7.0 on ArchLinux.

When using wstool to update my workspace, I received the error:

ERROR [vcstools] Tarball download unpack failed: file could not be opened successfully[/vcstools]

I checked the temporary tar file downloaded and it was not a proper tar archive, there were some extra bytes at the start and end of the file compared to the same file manually downloaded. It is odd that this started happening recently, it used to work fine a few weeks ago.

The documentation for both Python 2 and 3 mentions that the response object from urlopen is a file-like object, so I believe we can directly use it in the shutil.copyfileobj function.

Edit: See the following comment #140 (comment) for more details about the issue.

…te to file

Instead of using `resp.fp`, directly use the response object to write data to
file. Using `resp.fp` adds some extra data to the written file in Python 3 which
is obviously undesired.
@tkruse

tkruse commented Sep 9, 2018

Copy link
Copy Markdown
Contributor

Thanks for debugging so far. It would be good to know what happens exactly and why our tests do not catch it. Function urlopen_netrc() first tries urlopen, and if that fails with 401, it tries a netrc call. Is it possible that in your case it's an authenticated call that's being performed?

@kartikmohta

Copy link
Copy Markdown
Author

It's definitely using the urlopen path, not the authenticated call. I used a simple script to test:

import urllib.request
import tempfile
import os
import shutil

resp = urllib.request.urlopen('https://github.com/ros-gbp/qt_gui_core-release/archive/release/melodic/qt_gui/0.3.11-0.tar.gz')
fdesc, fname = tempfile.mkstemp()
print(fname)
fhand = os.fdopen(fdesc, "wb")
shutil.copyfileobj(resp.fp, fhand)

This saves a file which is not a proper gzip compressed file.
Changing the last line to shutil.copyfileobj(resp, fhand) leads a properly formatted gzip file.

@tkruse

tkruse commented Sep 9, 2018

Copy link
Copy Markdown
Contributor

Can you turn that into a unit test that fails for the current version and passes for your fix?

@kartikmohta

Copy link
Copy Markdown
Author

I looked into this a bit more and it looks like the failure happens when receiving a http response with Transfer-Encoding: chunked in the header. If the server sends the full file in a single transfer then there is no issue. This makes it hard to have a consistent unit test since github sometimes provides a response with Transfer-Encoding: chunked while sometimes it returns the file in a single transfer.

Using the following script:

import urllib.request
import tempfile
import os
import shutil
import tarfile

resp = urllib.request.urlopen('https://github.com/ros-gbp/qt_gui_core-release/archive/release/melodic/qt_dotgraph/0.3.11-0.tar.gz')
print(resp.headers)
fdesc, fname = tempfile.mkstemp()
print(fname)
fhand = os.fdopen(fdesc, "wb")
shutil.copyfileobj(resp.fp, fhand)
fhand.close()
temp_tarfile = tarfile.open(fname, 'r:*')

with different URLs resulted in different results (note the difference in the first line of the response headers):

$ python test.py 
Content-Length: 54942
Access-Control-Allow-Origin: https://render.githubusercontent.com
Content-Security-Policy: default-src 'none'; style-src 'unsafe-inline'; sandbox
Strict-Transport-Security: max-age=31536000
Vary: Authorization,Accept-Encoding
X-Content-Type-Options: nosniff
X-Frame-Options: deny
X-XSS-Protection: 1; mode=block
ETag: "a0f9f8d7fe2bbfacb18f0c6eadd43b36349339e2"
Content-Type: application/x-gzip
Content-Disposition: attachment; filename=qt_gui_core-release-release-melodic-qt_gui-0.3.11-0.tar.gz
X-Geo-Block-List: 
Date: Sun, 09 Sep 2018 21:09:32 GMT
X-GitHub-Request-Id: DE02:1705:3342BE:58B50F:5B958C0B
Connection: close


/tmp/tmpuoo52hwj


$ python test.py 
Transfer-Encoding: chunked
Access-Control-Allow-Origin: https://render.githubusercontent.com
Content-Security-Policy: default-src 'none'; style-src 'unsafe-inline'; sandbox
Strict-Transport-Security: max-age=31536000
Vary: Authorization,Accept-Encoding
X-Content-Type-Options: nosniff
X-Frame-Options: deny
X-XSS-Protection: 1; mode=block
ETag: "4016706d2826c5cf8594d02b9009b75b916e4d28"
Content-Type: application/x-gzip
Content-Disposition: attachment; filename=qt_gui_core-release-release-melodic-qt_dotgraph-0.3.11-0.tar.gz
X-Geo-Block-List: 
Date: Sun, 09 Sep 2018 21:12:37 GMT
X-GitHub-Request-Id: DE28:1706:604C24:A40073:5B958CC5
Connection: close


/tmp/tmp9g8l0f_7
Traceback (most recent call last):
  File "test.py", line 18, in <module>
    temp_tarfile = tarfile.open(fname, 'r:*')
  File "/usr/lib/python3.7/tarfile.py", line 1576, in open
    raise ReadError("file could not be opened successfully")
tarfile.ReadError: file could not be opened successfully

The error went away after changing resp.fp to resp in the test script. This is because the returned resp object has special handling for "chunked" transfers while directly reading from the resp.fp doesn't do that (see https://github.com/python/cpython/blob/2.7/Lib/httplib.py#L572 for Python 2.7 and https://github.com/python/cpython/blob/3.4/Lib/http/client.py#L542 for Python 3.4).

As for a new unittest, I changed the URL in the test/test_tar.py and was able to replicate the error (though it was not consistent due to the reason mentioned above), so I don't think a new unittest is required.

Note that, officially, using the response.fp is not recommended since at least Python 3.4 (https://github.com/python/cpython/blob/3.4/Lib/http/client.py#L323).

@tkruse

tkruse commented Sep 9, 2018

Copy link
Copy Markdown
Contributor

Thanks for finding that cause. I still don't know or remember why response.fp has been used in the first place, making me a little worried about removing it. Especially since testing the different code paths and situations is tough. I personally cannot say whether your patch may break other situations or not.

Ideally we would write our own stubbed http endpoint for a unit test (like https://realpython.com/testing-third-party-apis-with-mock-servers/), but that might be too much effort to ask of you.

Also if this is a reproducable bug in urllib, we should report it anyway to the python community.

@kartikmohta

Copy link
Copy Markdown
Author

As far as I see it, the fp field is not mentioned in any official documentation (either Python 2 or 3), so I don't know why it was used in this situation and whether its use is even supported. It's definitely not a bug in urllib, the server is allowed to respond in a slightly different manner to the same request and it is up to the client to handle it.

I'm fairly confident that the patch won't break anything, unless someone was working around this bug in some way, since the old behavior is used in the case when the Transfer-Encoding is not chunked, and the chunked case is handled properly now.

@tkruse

tkruse commented Sep 9, 2018

Copy link
Copy Markdown
Contributor

I don't get how you can be sure that this is not a bug in urllib. If response.fp behaved in one way in previous versions and in a different way in new versions (even if undocumented), this might be an unintended regression hurting other users as well, no?

In any case, @tfoote or @wjwwood should judge whether to merge this. I believe this does need fixing, but I believe there is a small risk of the current patch hurting a few users if our assumptions are wrong about different download situations, in which case an urgent second patch might be required.

@tkruse tkruse changed the title In urlretrieve_netrc, use the response object from urlopen directly as a file object File download broken for chunked responses from github Sep 9, 2018
@tkruse

tkruse commented Sep 9, 2018

Copy link
Copy Markdown
Contributor

Maybe you can edit your initial post (at the top) giving the details you found out since, it will help others get the problem more quickly.

@kartikmohta

Copy link
Copy Markdown
Author

I don't get how you can be sure that this is not a bug in urllib. If response.fp behaved in one way in previous versions and in a different way in new versions (even if undocumented), this might be an unintended regression hurting other users as well, no?

I believe it never supported chunked transfers, so it was already broken. Maybe github changed something on their end which triggers this problem now. Also, you can't expect stable behavior when using undocumented (internal) fields of a class right?

Maybe you can edit your initial post (at the top) giving the details you found out since, it will help others get the problem more quickly.

Yes, that's a good idea. I added a line pointing to the comment with more details.

@tkruse

tkruse commented Sep 11, 2018

Copy link
Copy Markdown
Contributor

I confirm that the given script also fails with Python 3.2 to 3.5, so this is not a python regression, but more likely something that never worked. Since users depend on downloading from github, this looks pretty urgent to me.

@kartikmohta : I created a branch that reproduces the problem (and solution) reliably using a mock-server: https://github.com/tkruse/vcstools/tree/mock_server_tar_test
commit: tkruse@5079395233
Would you like to review, refine and include in your PR? I am a bit short on time, and have not written real Python in years. Ideally the tests from test_tar would:

  • repeatedly run both chunked and unchunked, same with authentication required
  • run on python2 (or else be excluded when using python2)
  • new module mock_server should be refactored a bit to look clean
  • new module mock_server should be more configurable to be reusable for tests of wstool/rosinstall

@wjwwood : Does OSRF share the opinion that this needs urgent fixing?

@tkruse

tkruse commented Sep 11, 2018

Copy link
Copy Markdown
Contributor

Actually, the old variant using shutil.copyfileobj(resp.fp, fhand) does seem to work with Python 2.7, so I guess this formally breaks with Python3.x. I created a bug report for python in any case, though likely it's not a bug, and even if we'd need a fix for vcstools in any case.

@tkruse tkruse changed the title File download broken for chunked responses from github File download broken for chunked responses from github with Python 3.x Sep 11, 2018
tkruse added a commit to tkruse/vcstools that referenced this pull request Sep 13, 2018
@tkruse

tkruse commented Sep 13, 2018

Copy link
Copy Markdown
Contributor

create #141 with enough tests to merge with confidence

@kartikmohta

Copy link
Copy Markdown
Author

Closing this in favor of #141

@kartikmohta
kartikmohta deleted the patch-1 branch October 10, 2018 03:17
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants