My upload form expects a tar file and I want to check whether the uploaded data is valid. The tarfile module supports is_tarfile()
, but expects a filename - I don't want to waste resources writing the file to disk just to check if it is valid.
Is there a way to check the data is a valid tar file without writing to disk, using standard Python libraries?
The tar file format is here on Wikipedia.
I suspect your best bet would be to check that the header checksum for the first file is valid. You may also want to check the file name for sanity but that may not be reliable, depending on the file names that have been stored in there.
Duplicating the relevant information here:
There is also the UStar format (also detailed in that link) but, since it's an extension to the old tar format, the method detailed above should still work. UStar is generally for just storing extra information about each file.
Alternatively, since Python is open source, you could see how
is_tarfile
works and adapt it to check your stream rather than a file. The source code is available here underPython-3.1.1/Lib/tarfile.py
but it's not for the faint of heart :-)The
open
method oftarfile
takes a file-like object in itsfileObj
argument. This can be aStringIO
instanceThe class TarFile accepts a fileobj object. I guess you can pass any partial download entity you get from your web framework.
Adding to paxdiablo post: tar is a very difficult and complex file format, despite its apparent simplicity. You can check basic constraint, but if you have to support all the possible existing tar dialects you are going to waste a lot of time. Most of its complexity comes from the following issues:
Also, there format has no upfront header, so the only way to check if the whole archive is sane is to scan the file completely, catch each record, and validate each one.
Say your uploaded data is contained in string
data
.There are additional complexities such as handling different tar file formats and compression. More info is available in the tarfile documentation.