1 """Unpacking archives of various formats."""
3 # Copyright (C) 2006, Thomas Leonard
4 # See the README file for details, or visit http://0install.net.
9 from tempfile
import mkdtemp
, mkstemp
12 from logging
import debug
, info
, warn
13 from zeroinstall
import SafeException
14 from zeroinstall
.support
import find_in_path
, ro_rmtree
17 def _get_cpio_version():
19 if _cpio_version
is None:
20 _cpio_version
= os
.popen('cpio --version 2>&1').next()
21 debug("cpio version = %s", _cpio_version
)
25 gnu_cpio
= '(GNU cpio)' in _get_cpio_version()
26 debug("Is GNU cpio = %s", gnu_cpio
)
30 def _get_tar_version():
32 if _tar_version
is None:
33 _tar_version
= os
.popen('tar --version 2>&1').next()
34 debug("tar version = %s", _tar_version
)
38 gnu_tar
= '(GNU tar)' in _get_tar_version()
39 debug("Is GNU tar = %s", gnu_tar
)
43 """@deprecated: should be private"""
44 recent_gnu_tar
= False
46 version
= _get_tar_version()
48 version
= version
.split(')', 1)[1].strip()
50 version
= map(int, version
.split('.'))
51 recent_gnu_tar
= version
> [1, 13, 92]
53 warn("Failed to extract GNU tar version number")
54 debug("Recent GNU tar = %s", recent_gnu_tar
)
57 _pola_run
= find_in_path('pola-run')
59 info('Found pola-run: %s', _pola_run
)
61 info('pola-run not found; archive extraction will not be sandboxed')
63 def type_from_url(url
):
64 """Guess the MIME type for this resource based on its URL. Returns None if we don't know what it is."""
66 if url
.endswith('.rpm'): return 'application/x-rpm'
67 if url
.endswith('.deb'): return 'application/x-deb'
68 if url
.endswith('.tar.bz2'): return 'application/x-bzip-compressed-tar'
69 if url
.endswith('.tar.gz'): return 'application/x-compressed-tar'
70 if url
.endswith('.tar.lzma'): return 'application/x-lzma-compressed-tar' # XXX: No registered MIME type!
71 if url
.endswith('.tgz'): return 'application/x-compressed-tar'
72 if url
.endswith('.tar'): return 'application/x-tar'
73 if url
.endswith('.zip'): return 'application/zip'
74 if url
.endswith('.cab'): return 'application/vnd.ms-cab-compressed'
77 def check_type_ok(mime_type
):
78 """Check we have the needed software to extract from an archive of the given type.
79 @raise SafeException: if the needed software is not available"""
81 if mime_type
== 'application/x-rpm':
82 if not find_in_path('rpm2cpio'):
83 raise SafeException("This package looks like an RPM, but you don't have the rpm2cpio command "
84 "I need to extract it. Install the 'rpm' package first (this works even if "
85 "you're on a non-RPM-based distribution such as Debian).")
86 elif mime_type
== 'application/x-deb':
87 if not find_in_path('ar'):
88 raise SafeException("This package looks like a Debian package, but you don't have the 'ar' command "
89 "I need to extract it. Install the package containing it (sometimes called 'binutils') "
90 "first. This works even if you're on a non-Debian-based distribution such as Red Hat).")
91 elif mime_type
== 'application/x-bzip-compressed-tar':
92 if not find_in_path('bunzip2'):
93 raise SafeException("This package looks like a bzip2-compressed package, but you don't have the 'bunzip2' command "
94 "I need to extract it. Install the package containing it (it's probably called 'bzip2') "
96 elif mime_type
== 'application/zip':
97 if not find_in_path('unzip'):
98 raise SafeException("This package looks like a zip-compressed archive, but you don't have the 'unzip' command "
99 "I need to extract it. Install the package containing it first.")
100 elif mime_type
== 'application/vnd.ms-cab-compressed':
101 if not find_in_path('cabextract'):
102 raise SafeException("This package looks like a Microsoft Cabinet archive, but you don't have the 'cabextract' command "
103 "I need to extract it. Install the package containing it first.")
104 elif mime_type
== 'application/x-lzma-compressed-tar':
105 if not find_in_path('unlzma'):
106 raise SafeException("This package looks like an LZMA archive, but you don't have the 'unlzma' command "
107 "I need to extract it. Install the package containing it (it's probably called 'lzma') first.")
108 elif mime_type
in ('application/x-compressed-tar', 'application/x-tar'):
111 from zeroinstall
import version
112 raise SafeException("Unsupported archive type '%s' (for injector version %s)" % (mime_type
, version
))
114 def _exec_maybe_sandboxed(writable
, prog
, *args
):
115 """execlp prog, with (only) the 'writable' directory writable if sandboxing is available.
116 If no sandbox is available, run without a sandbox."""
117 prog_path
= find_in_path(prog
)
118 if not prog_path
: raise Exception("'%s' not found in $PATH" % prog
)
119 if _pola_run
is None:
120 os
.execlp(prog_path
, prog_path
, *args
)
121 # We have pola-shell :-)
122 pola_args
= ['--prog', prog_path
, '-f', '/']
124 pola_args
+= ['-a', a
]
126 pola_args
+= ['-fw', writable
]
127 os
.execl(_pola_run
, _pola_run
, *pola_args
)
129 def unpack_archive_over(url
, data
, destdir
, extract
= None, type = None, start_offset
= 0):
130 """Like unpack_archive, except that we unpack to a temporary directory first and
131 then move things over, checking that we're not following symlinks at each stage.
132 Use this when you want to unpack an unarchive into a directory which already has
136 tmpdir
= mkdtemp(dir = destdir
)
140 unpack_archive(url
, data
, tmpdir
, extract
, type, start_offset
)
142 stem_len
= len(tmpdir
)
143 for root
, dirs
, files
in os
.walk(tmpdir
):
144 relative_root
= root
[stem_len
+ 1:] or '.'
145 target_root
= os
.path
.join(destdir
, relative_root
)
147 info
= os
.lstat(target_root
)
150 raise # Some odd error.
152 os
.mkdir(target_root
)
154 if stat
.S_ISLNK(info
.st_mode
):
155 raise SafeException('Attempt to unpack dir over symlink "%s"!' % relative_root
)
156 elif not stat
.S_ISDIR(info
.st_mode
):
157 raise SafeException('Attempt to unpack dir over non-directory "%s"!' % relative_root
)
158 mtimes
.append((relative_root
, os
.lstat(os
.path
.join(tmpdir
, root
)).st_mtime
))
160 for s
in dirs
: # Symlinks are counted as directories
161 src
= os
.path
.join(tmpdir
, relative_root
, s
)
162 if os
.path
.islink(src
):
166 src
= os
.path
.join(tmpdir
, relative_root
, f
)
167 dest
= os
.path
.join(destdir
, relative_root
, f
)
168 if os
.path
.islink(dest
):
169 raise SafeException('Attempt to unpack file over symlink "%s"!' %
170 os
.path
.join(relative_root
, f
))
173 for path
, mtime
in mtimes
[1:]:
174 os
.utime(os
.path
.join(destdir
, path
), (mtime
, mtime
))
178 def unpack_archive(url
, data
, destdir
, extract
= None, type = None, start_offset
= 0):
179 """Unpack stream 'data' into directory 'destdir'. If extract is given, extract just
180 that sub-directory from the archive. Works out the format from the name."""
181 if type is None: type = type_from_url(url
)
182 if type is None: raise SafeException("Unknown extension (and no MIME type given) in '%s'" % url
)
183 if type == 'application/x-bzip-compressed-tar':
184 extract_tar(data
, destdir
, extract
, 'bzip2', start_offset
)
185 elif type == 'application/x-deb':
186 extract_deb(data
, destdir
, extract
, start_offset
)
187 elif type == 'application/x-rpm':
188 extract_rpm(data
, destdir
, extract
, start_offset
)
189 elif type == 'application/zip':
190 extract_zip(data
, destdir
, extract
, start_offset
)
191 elif type == 'application/x-tar':
192 extract_tar(data
, destdir
, extract
, None, start_offset
)
193 elif type == 'application/x-lzma-compressed-tar':
194 extract_tar(data
, destdir
, extract
, 'lzma', start_offset
)
195 elif type == 'application/x-compressed-tar':
196 extract_tar(data
, destdir
, extract
, 'gzip', start_offset
)
197 elif type == 'application/vnd.ms-cab-compressed':
198 extract_cab(data
, destdir
, extract
, start_offset
)
200 raise SafeException('Unknown MIME type "%s" for "%s"' % (type, url
))
202 def extract_deb(stream
, destdir
, extract
= None, start_offset
= 0):
204 raise SafeException('Sorry, but the "extract" attribute is not yet supported for Debs')
206 stream
.seek(start_offset
)
207 # ar can't read from stdin, so make a copy...
208 deb_copy_name
= os
.path
.join(destdir
, 'archive.deb')
209 deb_copy
= file(deb_copy_name
, 'w')
210 shutil
.copyfileobj(stream
, deb_copy
)
212 _extract(stream
, destdir
, ('ar', 'x', 'archive.deb', 'data.tar.gz'))
213 os
.unlink(deb_copy_name
)
214 data_name
= os
.path
.join(destdir
, 'data.tar.gz')
215 data_stream
= file(data_name
)
217 extract_tar(data_stream
, destdir
, None, 'gzip')
219 def extract_rpm(stream
, destdir
, extract
= None, start_offset
= 0):
221 raise SafeException('Sorry, but the "extract" attribute is not yet supported for RPMs')
222 fd
, cpiopath
= mkstemp('-rpm-tmp')
228 os
.dup2(stream
.fileno(), 0)
229 os
.lseek(0, start_offset
, 0)
231 _exec_maybe_sandboxed(None, 'rpm2cpio', '-')
233 traceback
.print_exc()
236 id, status
= os
.waitpid(child
, 0)
239 raise SafeException("rpm2cpio failed; can't unpack RPM archive; exit code %d" % status
)
243 args
= ['cpio', '-mid']
245 args
.append('--quiet')
247 _extract(file(cpiopath
), destdir
, args
)
248 # Set the mtime of every directory under 'tmp' to 0, since cpio doesn't
249 # preserve directory mtimes.
250 os
.path
.walk(destdir
, lambda arg
, dirname
, names
: os
.utime(dirname
, (0, 0)), None)
256 def extract_cab(stream
, destdir
, extract
, start_offset
= 0):
259 raise SafeException('Sorry, but the "extract" attribute is not yet supported for Cabinet files')
261 stream
.seek(start_offset
)
262 # cabextract can't read from stdin, so make a copy...
263 cab_copy_name
= os
.path
.join(destdir
, 'archive.cab')
264 cab_copy
= file(cab_copy_name
, 'w')
265 shutil
.copyfileobj(stream
, cab_copy
)
268 _extract(stream
, destdir
, ['cabextract', '-s', '-q', 'archive.cab'])
269 os
.unlink(cab_copy_name
)
271 def extract_zip(stream
, destdir
, extract
, start_offset
= 0):
273 # Limit the characters we accept, to avoid sending dodgy
275 if not re
.match('^[a-zA-Z0-9][- _a-zA-Z0-9.]*$', extract
):
276 raise SafeException('Illegal character in extract attribute')
278 stream
.seek(start_offset
)
279 # unzip can't read from stdin, so make a copy...
280 zip_copy_name
= os
.path
.join(destdir
, 'archive.zip')
281 zip_copy
= file(zip_copy_name
, 'w')
282 shutil
.copyfileobj(stream
, zip_copy
)
285 args
= ['unzip', '-q', '-o']
290 _extract(stream
, destdir
, args
+ ['archive.zip'])
291 os
.unlink(zip_copy_name
)
293 def extract_tar(stream
, destdir
, extract
, decompress
, start_offset
= 0):
295 # Limit the characters we accept, to avoid sending dodgy
297 if not re
.match('^[a-zA-Z0-9][- _a-zA-Z0-9.]*$', extract
):
298 raise SafeException('Illegal character in extract attribute')
300 assert decompress
in [None, 'bzip2', 'gzip', 'lzma']
305 if decompress
== 'bzip2':
306 ext_cmd
.append('--bzip2')
307 elif decompress
== 'gzip':
309 elif decompress
== 'lzma':
310 ext_cmd
.append('--use-compress-program=unlzma')
313 ext_cmd
.extend(('-x', '--no-same-owner', '--no-same-permissions'))
315 ext_cmd
.extend(('xf', '-'))
318 ext_cmd
.append(extract
)
320 _extract(stream
, destdir
, ext_cmd
, start_offset
)
322 # Since we don't have GNU tar, use python's tarfile module. This will probably
323 # be a lot slower and we do not support lzma; however, it is portable.
324 if decompress
is None:
326 elif decompress
== 'bzip2':
328 elif decompress
== 'gzip':
331 raise SafeException('GNU tar unavailable; unsupported compression format: ' + decompress
)
335 stream
.seek(start_offset
)
336 # Python 2.5.1 crashes if name is None; see Python bug #1706850
337 tar
= tarfile
.open(name
= '', mode
= rmode
, fileobj
= stream
)
339 current_umask
= os
.umask(0)
340 os
.umask(current_umask
)
347 debug("Can't get uid/gid")
349 def chmod_extract(tarinfo
):
350 # If any X bit is set, they all must be
351 if tarinfo
.mode
& 0111:
354 # Everyone gets read and write (subject to the umask)
355 # No special bits are allowed.
356 tarinfo
.mode
= ((tarinfo
.mode |
0666) & ~current_umask
) & 0777
358 # Don't change owner, even if run as root
363 tar
.extract(tarinfo
, destdir
)
365 extracted_anything
= False
369 if extract
is None or \
370 tarinfo
.name
.startswith(extract
+ '/') or \
371 tarinfo
.name
== extract
:
373 ext_dirs
.append(tarinfo
)
375 chmod_extract(tarinfo
)
376 extracted_anything
= True
378 # Due to a bug in tarfile (python versions < 2.5), we have to manually
379 # set the mtime of each directory that we extract after extracting everything.
381 for tarinfo
in ext_dirs
:
382 dirname
= os
.path
.join(destdir
, tarinfo
.name
)
383 os
.utime(dirname
, (tarinfo
.mtime
, tarinfo
.mtime
))
387 if extract
and not extracted_anything
:
388 raise SafeException('Unable to find specified file = %s in archive' % extract
)
390 def _extract(stream
, destdir
, command
, start_offset
= 0):
391 """Run execvp('command') inside destdir in a child process, with
392 stream seeked to 'start_offset' as stdin."""
398 stream
.seek(start_offset
)
399 os
.dup2(stream
.fileno(), 0)
400 _exec_maybe_sandboxed(destdir
, *command
)
402 traceback
.print_exc()
405 id, status
= os
.waitpid(child
, 0)
408 raise SafeException('Failed to extract archive; exit code %d' % status
)