Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 1 | #!/usr/bin/env python |
| 2 | # -*- coding: iso-8859-1 -*- |
| 3 | #------------------------------------------------------------------- |
| 4 | # tarfile.py |
| 5 | #------------------------------------------------------------------- |
| 6 | # Copyright (C) 2002 Lars Gustäbel <lars@gustaebel.de> |
| 7 | # All rights reserved. |
| 8 | # |
| 9 | # Permission is hereby granted, free of charge, to any person |
| 10 | # obtaining a copy of this software and associated documentation |
| 11 | # files (the "Software"), to deal in the Software without |
| 12 | # restriction, including without limitation the rights to use, |
| 13 | # copy, modify, merge, publish, distribute, sublicense, and/or sell |
| 14 | # copies of the Software, and to permit persons to whom the |
| 15 | # Software is furnished to do so, subject to the following |
| 16 | # conditions: |
| 17 | # |
| 18 | # The above copyright notice and this permission notice shall be |
| 19 | # included in all copies or substantial portions of the Software. |
| 20 | # |
| 21 | # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, |
| 22 | # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES |
| 23 | # OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND |
| 24 | # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT |
| 25 | # HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, |
| 26 | # WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING |
| 27 | # FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR |
| 28 | # OTHER DEALINGS IN THE SOFTWARE. |
| 29 | # |
| 30 | """Read from and write to tar format archives. |
| 31 | """ |
| 32 | |
| 33 | __version__ = "$Revision$" |
| 34 | # $Source$ |
| 35 | |
Lars Gustäbel | c64e402 | 2007-03-13 10:47:19 +0000 | [diff] [blame] | 36 | version = "0.9.0" |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 37 | __author__ = "Lars Gustäbel (lars@gustaebel.de)" |
| 38 | __date__ = "$Date$" |
| 39 | __cvsid__ = "$Id$" |
| 40 | __credits__ = "Gustavo Niemeyer, Niels Gustäbel, Richard Townsend." |
| 41 | |
| 42 | #--------- |
| 43 | # Imports |
| 44 | #--------- |
| 45 | import sys |
| 46 | import os |
| 47 | import shutil |
| 48 | import stat |
| 49 | import errno |
| 50 | import time |
| 51 | import struct |
Georg Brandl | 3354f28 | 2006-10-29 09:16:12 +0000 | [diff] [blame] | 52 | import copy |
Lars Gustäbel | c64e402 | 2007-03-13 10:47:19 +0000 | [diff] [blame] | 53 | import re |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 54 | |
Jack Jansen | cfc4902 | 2003-03-07 13:37:32 +0000 | [diff] [blame] | 55 | if sys.platform == 'mac': |
| 56 | # This module needs work for MacOS9, especially in the area of pathname |
| 57 | # handling. In many places it is assumed a simple substitution of / by the |
| 58 | # local os.path.sep is good enough to convert pathnames, but this does not |
| 59 | # work with the mac rooted:path:name versus :nonrooted:path:name syntax |
| 60 | raise ImportError, "tarfile does not work for platform==mac" |
| 61 | |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 62 | try: |
| 63 | import grp, pwd |
| 64 | except ImportError: |
| 65 | grp = pwd = None |
| 66 | |
| 67 | # from tarfile import * |
| 68 | __all__ = ["TarFile", "TarInfo", "is_tarfile", "TarError"] |
| 69 | |
| 70 | #--------------------------------------------------------- |
| 71 | # tar constants |
| 72 | #--------------------------------------------------------- |
Lars Gustäbel | c64e402 | 2007-03-13 10:47:19 +0000 | [diff] [blame] | 73 | NUL = "\0" # the null character |
| 74 | BLOCKSIZE = 512 # length of processing blocks |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 75 | RECORDSIZE = BLOCKSIZE * 20 # length of records |
Lars Gustäbel | c64e402 | 2007-03-13 10:47:19 +0000 | [diff] [blame] | 76 | GNU_MAGIC = "ustar \0" # magic gnu tar string |
| 77 | POSIX_MAGIC = "ustar\x0000" # magic posix tar string |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 78 | |
Lars Gustäbel | c64e402 | 2007-03-13 10:47:19 +0000 | [diff] [blame] | 79 | LENGTH_NAME = 100 # maximum length of a filename |
| 80 | LENGTH_LINK = 100 # maximum length of a linkname |
| 81 | LENGTH_PREFIX = 155 # maximum length of the prefix field |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 82 | |
Lars Gustäbel | c64e402 | 2007-03-13 10:47:19 +0000 | [diff] [blame] | 83 | REGTYPE = "0" # regular file |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 84 | AREGTYPE = "\0" # regular file |
Lars Gustäbel | c64e402 | 2007-03-13 10:47:19 +0000 | [diff] [blame] | 85 | LNKTYPE = "1" # link (inside tarfile) |
| 86 | SYMTYPE = "2" # symbolic link |
| 87 | CHRTYPE = "3" # character special device |
| 88 | BLKTYPE = "4" # block special device |
| 89 | DIRTYPE = "5" # directory |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 90 | FIFOTYPE = "6" # fifo special device |
| 91 | CONTTYPE = "7" # contiguous file |
| 92 | |
Lars Gustäbel | c64e402 | 2007-03-13 10:47:19 +0000 | [diff] [blame] | 93 | GNUTYPE_LONGNAME = "L" # GNU tar longname |
| 94 | GNUTYPE_LONGLINK = "K" # GNU tar longlink |
| 95 | GNUTYPE_SPARSE = "S" # GNU tar sparse file |
| 96 | |
| 97 | XHDTYPE = "x" # POSIX.1-2001 extended header |
| 98 | XGLTYPE = "g" # POSIX.1-2001 global header |
| 99 | SOLARIS_XHDTYPE = "X" # Solaris extended header |
| 100 | |
| 101 | USTAR_FORMAT = 0 # POSIX.1-1988 (ustar) format |
| 102 | GNU_FORMAT = 1 # GNU tar format |
| 103 | PAX_FORMAT = 2 # POSIX.1-2001 (pax) format |
| 104 | DEFAULT_FORMAT = GNU_FORMAT |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 105 | |
| 106 | #--------------------------------------------------------- |
| 107 | # tarfile constants |
| 108 | #--------------------------------------------------------- |
Lars Gustäbel | c64e402 | 2007-03-13 10:47:19 +0000 | [diff] [blame] | 109 | # File types that tarfile supports: |
| 110 | SUPPORTED_TYPES = (REGTYPE, AREGTYPE, LNKTYPE, |
| 111 | SYMTYPE, DIRTYPE, FIFOTYPE, |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 112 | CONTTYPE, CHRTYPE, BLKTYPE, |
| 113 | GNUTYPE_LONGNAME, GNUTYPE_LONGLINK, |
| 114 | GNUTYPE_SPARSE) |
| 115 | |
Lars Gustäbel | c64e402 | 2007-03-13 10:47:19 +0000 | [diff] [blame] | 116 | # File types that will be treated as a regular file. |
| 117 | REGULAR_TYPES = (REGTYPE, AREGTYPE, |
| 118 | CONTTYPE, GNUTYPE_SPARSE) |
| 119 | |
| 120 | # File types that are part of the GNU tar format. |
| 121 | GNU_TYPES = (GNUTYPE_LONGNAME, GNUTYPE_LONGLINK, |
| 122 | GNUTYPE_SPARSE) |
| 123 | |
| 124 | # Fields from a pax header that override a TarInfo attribute. |
| 125 | PAX_FIELDS = ("path", "linkpath", "size", "mtime", |
| 126 | "uid", "gid", "uname", "gname") |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 127 | |
Lars Gustäbel | a0fcb93 | 2007-05-27 19:49:30 +0000 | [diff] [blame] | 128 | # Fields in a pax header that are numbers, all other fields |
| 129 | # are treated as strings. |
| 130 | PAX_NUMBER_FIELDS = { |
| 131 | "atime": float, |
| 132 | "ctime": float, |
| 133 | "mtime": float, |
| 134 | "uid": int, |
| 135 | "gid": int, |
| 136 | "size": int |
| 137 | } |
| 138 | |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 139 | #--------------------------------------------------------- |
| 140 | # Bits used in the mode field, values in octal. |
| 141 | #--------------------------------------------------------- |
| 142 | S_IFLNK = 0120000 # symbolic link |
| 143 | S_IFREG = 0100000 # regular file |
| 144 | S_IFBLK = 0060000 # block device |
| 145 | S_IFDIR = 0040000 # directory |
| 146 | S_IFCHR = 0020000 # character device |
| 147 | S_IFIFO = 0010000 # fifo |
| 148 | |
| 149 | TSUID = 04000 # set UID on execution |
| 150 | TSGID = 02000 # set GID on execution |
| 151 | TSVTX = 01000 # reserved |
| 152 | |
| 153 | TUREAD = 0400 # read by owner |
| 154 | TUWRITE = 0200 # write by owner |
| 155 | TUEXEC = 0100 # execute/search by owner |
| 156 | TGREAD = 0040 # read by group |
| 157 | TGWRITE = 0020 # write by group |
| 158 | TGEXEC = 0010 # execute/search by group |
| 159 | TOREAD = 0004 # read by other |
| 160 | TOWRITE = 0002 # write by other |
| 161 | TOEXEC = 0001 # execute/search by other |
| 162 | |
| 163 | #--------------------------------------------------------- |
Lars Gustäbel | c64e402 | 2007-03-13 10:47:19 +0000 | [diff] [blame] | 164 | # initialization |
| 165 | #--------------------------------------------------------- |
| 166 | ENCODING = sys.getfilesystemencoding() |
| 167 | if ENCODING is None: |
Lars Gustäbel | a0fcb93 | 2007-05-27 19:49:30 +0000 | [diff] [blame] | 168 | ENCODING = sys.getdefaultencoding() |
Lars Gustäbel | c64e402 | 2007-03-13 10:47:19 +0000 | [diff] [blame] | 169 | |
| 170 | #--------------------------------------------------------- |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 171 | # Some useful functions |
| 172 | #--------------------------------------------------------- |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 173 | |
Georg Brandl | 38c6a22 | 2006-05-10 16:26:03 +0000 | [diff] [blame] | 174 | def stn(s, length): |
| 175 | """Convert a python string to a null-terminated string buffer. |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 176 | """ |
Georg Brandl | a32e0a0 | 2006-10-24 16:54:16 +0000 | [diff] [blame] | 177 | return s[:length] + (length - len(s)) * NUL |
Georg Brandl | 38c6a22 | 2006-05-10 16:26:03 +0000 | [diff] [blame] | 178 | |
Lars Gustäbel | c64e402 | 2007-03-13 10:47:19 +0000 | [diff] [blame] | 179 | def nts(s): |
| 180 | """Convert a null-terminated string field to a python string. |
| 181 | """ |
| 182 | # Use the string up to the first null char. |
| 183 | p = s.find("\0") |
| 184 | if p == -1: |
| 185 | return s |
| 186 | return s[:p] |
| 187 | |
Georg Brandl | 38c6a22 | 2006-05-10 16:26:03 +0000 | [diff] [blame] | 188 | def nti(s): |
| 189 | """Convert a number field to a python number. |
| 190 | """ |
| 191 | # There are two possible encodings for a number field, see |
| 192 | # itn() below. |
| 193 | if s[0] != chr(0200): |
Georg Brandl | ded1c4d | 2006-12-20 11:55:16 +0000 | [diff] [blame] | 194 | try: |
Lars Gustäbel | c64e402 | 2007-03-13 10:47:19 +0000 | [diff] [blame] | 195 | n = int(nts(s) or "0", 8) |
Georg Brandl | ded1c4d | 2006-12-20 11:55:16 +0000 | [diff] [blame] | 196 | except ValueError: |
| 197 | raise HeaderError("invalid header") |
Georg Brandl | 38c6a22 | 2006-05-10 16:26:03 +0000 | [diff] [blame] | 198 | else: |
| 199 | n = 0L |
| 200 | for i in xrange(len(s) - 1): |
| 201 | n <<= 8 |
| 202 | n += ord(s[i + 1]) |
| 203 | return n |
| 204 | |
Lars Gustäbel | c64e402 | 2007-03-13 10:47:19 +0000 | [diff] [blame] | 205 | def itn(n, digits=8, format=DEFAULT_FORMAT): |
Georg Brandl | 38c6a22 | 2006-05-10 16:26:03 +0000 | [diff] [blame] | 206 | """Convert a python number to a number field. |
| 207 | """ |
| 208 | # POSIX 1003.1-1988 requires numbers to be encoded as a string of |
| 209 | # octal digits followed by a null-byte, this allows values up to |
| 210 | # (8**(digits-1))-1. GNU tar allows storing numbers greater than |
| 211 | # that if necessary. A leading 0200 byte indicates this particular |
| 212 | # encoding, the following digits-1 bytes are a big-endian |
| 213 | # representation. This allows values up to (256**(digits-1))-1. |
| 214 | if 0 <= n < 8 ** (digits - 1): |
| 215 | s = "%0*o" % (digits - 1, n) + NUL |
| 216 | else: |
Lars Gustäbel | c64e402 | 2007-03-13 10:47:19 +0000 | [diff] [blame] | 217 | if format != GNU_FORMAT or n >= 256 ** (digits - 1): |
Georg Brandl | e4751e3 | 2006-05-18 06:11:19 +0000 | [diff] [blame] | 218 | raise ValueError("overflow in number field") |
Georg Brandl | 38c6a22 | 2006-05-10 16:26:03 +0000 | [diff] [blame] | 219 | |
| 220 | if n < 0: |
| 221 | # XXX We mimic GNU tar's behaviour with negative numbers, |
| 222 | # this could raise OverflowError. |
| 223 | n = struct.unpack("L", struct.pack("l", n))[0] |
| 224 | |
| 225 | s = "" |
| 226 | for i in xrange(digits - 1): |
| 227 | s = chr(n & 0377) + s |
| 228 | n >>= 8 |
| 229 | s = chr(0200) + s |
| 230 | return s |
| 231 | |
Lars Gustäbel | a0fcb93 | 2007-05-27 19:49:30 +0000 | [diff] [blame] | 232 | def uts(s, encoding, errors): |
| 233 | """Convert a unicode object to a string. |
| 234 | """ |
| 235 | if errors == "utf-8": |
| 236 | # An extra error handler similar to the -o invalid=UTF-8 option |
| 237 | # in POSIX.1-2001. Replace untranslatable characters with their |
| 238 | # UTF-8 representation. |
| 239 | try: |
| 240 | return s.encode(encoding, "strict") |
| 241 | except UnicodeEncodeError: |
| 242 | x = [] |
| 243 | for c in s: |
| 244 | try: |
| 245 | x.append(c.encode(encoding, "strict")) |
| 246 | except UnicodeEncodeError: |
| 247 | x.append(c.encode("utf8")) |
| 248 | return "".join(x) |
| 249 | else: |
| 250 | return s.encode(encoding, errors) |
| 251 | |
Georg Brandl | 38c6a22 | 2006-05-10 16:26:03 +0000 | [diff] [blame] | 252 | def calc_chksums(buf): |
| 253 | """Calculate the checksum for a member's header by summing up all |
| 254 | characters except for the chksum field which is treated as if |
| 255 | it was filled with spaces. According to the GNU tar sources, |
| 256 | some tars (Sun and NeXT) calculate chksum with signed char, |
| 257 | which will be different if there are chars in the buffer with |
| 258 | the high bit set. So we calculate two checksums, unsigned and |
| 259 | signed. |
| 260 | """ |
| 261 | unsigned_chksum = 256 + sum(struct.unpack("148B", buf[:148]) + struct.unpack("356B", buf[156:512])) |
| 262 | signed_chksum = 256 + sum(struct.unpack("148b", buf[:148]) + struct.unpack("356b", buf[156:512])) |
| 263 | return unsigned_chksum, signed_chksum |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 264 | |
| 265 | def copyfileobj(src, dst, length=None): |
| 266 | """Copy length bytes from fileobj src to fileobj dst. |
| 267 | If length is None, copy the entire content. |
| 268 | """ |
| 269 | if length == 0: |
| 270 | return |
| 271 | if length is None: |
| 272 | shutil.copyfileobj(src, dst) |
| 273 | return |
| 274 | |
| 275 | BUFSIZE = 16 * 1024 |
| 276 | blocks, remainder = divmod(length, BUFSIZE) |
| 277 | for b in xrange(blocks): |
| 278 | buf = src.read(BUFSIZE) |
| 279 | if len(buf) < BUFSIZE: |
Georg Brandl | e4751e3 | 2006-05-18 06:11:19 +0000 | [diff] [blame] | 280 | raise IOError("end of file reached") |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 281 | dst.write(buf) |
| 282 | |
| 283 | if remainder != 0: |
| 284 | buf = src.read(remainder) |
| 285 | if len(buf) < remainder: |
Georg Brandl | e4751e3 | 2006-05-18 06:11:19 +0000 | [diff] [blame] | 286 | raise IOError("end of file reached") |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 287 | dst.write(buf) |
| 288 | return |
| 289 | |
| 290 | filemode_table = ( |
Andrew M. Kuchling | 8bc462f | 2004-10-20 11:48:42 +0000 | [diff] [blame] | 291 | ((S_IFLNK, "l"), |
| 292 | (S_IFREG, "-"), |
| 293 | (S_IFBLK, "b"), |
| 294 | (S_IFDIR, "d"), |
| 295 | (S_IFCHR, "c"), |
| 296 | (S_IFIFO, "p")), |
| 297 | |
| 298 | ((TUREAD, "r"),), |
| 299 | ((TUWRITE, "w"),), |
| 300 | ((TUEXEC|TSUID, "s"), |
| 301 | (TSUID, "S"), |
| 302 | (TUEXEC, "x")), |
| 303 | |
| 304 | ((TGREAD, "r"),), |
| 305 | ((TGWRITE, "w"),), |
| 306 | ((TGEXEC|TSGID, "s"), |
| 307 | (TSGID, "S"), |
| 308 | (TGEXEC, "x")), |
| 309 | |
| 310 | ((TOREAD, "r"),), |
| 311 | ((TOWRITE, "w"),), |
| 312 | ((TOEXEC|TSVTX, "t"), |
| 313 | (TSVTX, "T"), |
| 314 | (TOEXEC, "x")) |
| 315 | ) |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 316 | |
| 317 | def filemode(mode): |
| 318 | """Convert a file's mode to a string of the form |
| 319 | -rwxrwxrwx. |
| 320 | Used by TarFile.list() |
| 321 | """ |
Andrew M. Kuchling | 8bc462f | 2004-10-20 11:48:42 +0000 | [diff] [blame] | 322 | perm = [] |
| 323 | for table in filemode_table: |
| 324 | for bit, char in table: |
| 325 | if mode & bit == bit: |
| 326 | perm.append(char) |
| 327 | break |
| 328 | else: |
| 329 | perm.append("-") |
| 330 | return "".join(perm) |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 331 | |
| 332 | if os.sep != "/": |
| 333 | normpath = lambda path: os.path.normpath(path).replace(os.sep, "/") |
| 334 | else: |
| 335 | normpath = os.path.normpath |
| 336 | |
| 337 | class TarError(Exception): |
| 338 | """Base exception.""" |
| 339 | pass |
| 340 | class ExtractError(TarError): |
| 341 | """General exception for extract errors.""" |
| 342 | pass |
| 343 | class ReadError(TarError): |
| 344 | """Exception for unreadble tar archives.""" |
| 345 | pass |
| 346 | class CompressionError(TarError): |
| 347 | """Exception for unavailable compression methods.""" |
| 348 | pass |
| 349 | class StreamError(TarError): |
| 350 | """Exception for unsupported operations on stream-like TarFiles.""" |
| 351 | pass |
Georg Brandl | ebbeed7 | 2006-12-19 22:06:46 +0000 | [diff] [blame] | 352 | class HeaderError(TarError): |
| 353 | """Exception for invalid headers.""" |
| 354 | pass |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 355 | |
| 356 | #--------------------------- |
| 357 | # internal stream interface |
| 358 | #--------------------------- |
| 359 | class _LowLevelFile: |
| 360 | """Low-level file object. Supports reading and writing. |
| 361 | It is used instead of a regular file object for streaming |
| 362 | access. |
| 363 | """ |
| 364 | |
| 365 | def __init__(self, name, mode): |
| 366 | mode = { |
| 367 | "r": os.O_RDONLY, |
| 368 | "w": os.O_WRONLY | os.O_CREAT | os.O_TRUNC, |
| 369 | }[mode] |
| 370 | if hasattr(os, "O_BINARY"): |
| 371 | mode |= os.O_BINARY |
| 372 | self.fd = os.open(name, mode) |
| 373 | |
| 374 | def close(self): |
| 375 | os.close(self.fd) |
| 376 | |
| 377 | def read(self, size): |
| 378 | return os.read(self.fd, size) |
| 379 | |
| 380 | def write(self, s): |
| 381 | os.write(self.fd, s) |
| 382 | |
| 383 | class _Stream: |
| 384 | """Class that serves as an adapter between TarFile and |
| 385 | a stream-like object. The stream-like object only |
| 386 | needs to have a read() or write() method and is accessed |
| 387 | blockwise. Use of gzip or bzip2 compression is possible. |
| 388 | A stream-like object could be for example: sys.stdin, |
| 389 | sys.stdout, a socket, a tape device etc. |
| 390 | |
| 391 | _Stream is intended to be used only internally. |
| 392 | """ |
| 393 | |
Martin v. Löwis | 78be7df | 2005-03-05 12:47:42 +0000 | [diff] [blame] | 394 | def __init__(self, name, mode, comptype, fileobj, bufsize): |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 395 | """Construct a _Stream object. |
| 396 | """ |
| 397 | self._extfileobj = True |
| 398 | if fileobj is None: |
| 399 | fileobj = _LowLevelFile(name, mode) |
| 400 | self._extfileobj = False |
| 401 | |
Martin v. Löwis | 78be7df | 2005-03-05 12:47:42 +0000 | [diff] [blame] | 402 | if comptype == '*': |
| 403 | # Enable transparent compression detection for the |
| 404 | # stream interface |
| 405 | fileobj = _StreamProxy(fileobj) |
| 406 | comptype = fileobj.getcomptype() |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 407 | |
Martin v. Löwis | 78be7df | 2005-03-05 12:47:42 +0000 | [diff] [blame] | 408 | self.name = name or "" |
| 409 | self.mode = mode |
| 410 | self.comptype = comptype |
| 411 | self.fileobj = fileobj |
| 412 | self.bufsize = bufsize |
| 413 | self.buf = "" |
| 414 | self.pos = 0L |
| 415 | self.closed = False |
| 416 | |
| 417 | if comptype == "gz": |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 418 | try: |
| 419 | import zlib |
| 420 | except ImportError: |
Georg Brandl | e4751e3 | 2006-05-18 06:11:19 +0000 | [diff] [blame] | 421 | raise CompressionError("zlib module is not available") |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 422 | self.zlib = zlib |
Gregory P. Smith | 8844096 | 2008-03-25 06:12:45 +0000 | [diff] [blame] | 423 | self.crc = zlib.crc32("") & 0xffffffffL |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 424 | if mode == "r": |
| 425 | self._init_read_gz() |
| 426 | else: |
| 427 | self._init_write_gz() |
| 428 | |
Martin v. Löwis | 78be7df | 2005-03-05 12:47:42 +0000 | [diff] [blame] | 429 | if comptype == "bz2": |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 430 | try: |
| 431 | import bz2 |
| 432 | except ImportError: |
Georg Brandl | e4751e3 | 2006-05-18 06:11:19 +0000 | [diff] [blame] | 433 | raise CompressionError("bz2 module is not available") |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 434 | if mode == "r": |
| 435 | self.dbuf = "" |
| 436 | self.cmp = bz2.BZ2Decompressor() |
| 437 | else: |
| 438 | self.cmp = bz2.BZ2Compressor() |
| 439 | |
| 440 | def __del__(self): |
Martin v. Löwis | 78be7df | 2005-03-05 12:47:42 +0000 | [diff] [blame] | 441 | if hasattr(self, "closed") and not self.closed: |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 442 | self.close() |
| 443 | |
| 444 | def _init_write_gz(self): |
| 445 | """Initialize for writing with gzip compression. |
| 446 | """ |
| 447 | self.cmp = self.zlib.compressobj(9, self.zlib.DEFLATED, |
| 448 | -self.zlib.MAX_WBITS, |
| 449 | self.zlib.DEF_MEM_LEVEL, |
| 450 | 0) |
| 451 | timestamp = struct.pack("<L", long(time.time())) |
| 452 | self.__write("\037\213\010\010%s\002\377" % timestamp) |
| 453 | if self.name.endswith(".gz"): |
| 454 | self.name = self.name[:-3] |
| 455 | self.__write(self.name + NUL) |
| 456 | |
| 457 | def write(self, s): |
| 458 | """Write string s to the stream. |
| 459 | """ |
Martin v. Löwis | 78be7df | 2005-03-05 12:47:42 +0000 | [diff] [blame] | 460 | if self.comptype == "gz": |
Gregory P. Smith | 8844096 | 2008-03-25 06:12:45 +0000 | [diff] [blame] | 461 | self.crc = self.zlib.crc32(s, self.crc) & 0xffffffffL |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 462 | self.pos += len(s) |
Martin v. Löwis | 78be7df | 2005-03-05 12:47:42 +0000 | [diff] [blame] | 463 | if self.comptype != "tar": |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 464 | s = self.cmp.compress(s) |
| 465 | self.__write(s) |
| 466 | |
| 467 | def __write(self, s): |
| 468 | """Write string s to the stream if a whole new block |
| 469 | is ready to be written. |
| 470 | """ |
| 471 | self.buf += s |
| 472 | while len(self.buf) > self.bufsize: |
| 473 | self.fileobj.write(self.buf[:self.bufsize]) |
| 474 | self.buf = self.buf[self.bufsize:] |
| 475 | |
| 476 | def close(self): |
| 477 | """Close the _Stream object. No operation should be |
| 478 | done on it afterwards. |
| 479 | """ |
| 480 | if self.closed: |
| 481 | return |
| 482 | |
Martin v. Löwis | 78be7df | 2005-03-05 12:47:42 +0000 | [diff] [blame] | 483 | if self.mode == "w" and self.comptype != "tar": |
Martin v. Löwis | c234a52 | 2004-08-22 21:28:33 +0000 | [diff] [blame] | 484 | self.buf += self.cmp.flush() |
Martin v. Löwis | 78be7df | 2005-03-05 12:47:42 +0000 | [diff] [blame] | 485 | |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 486 | if self.mode == "w" and self.buf: |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 487 | self.fileobj.write(self.buf) |
| 488 | self.buf = "" |
Martin v. Löwis | 78be7df | 2005-03-05 12:47:42 +0000 | [diff] [blame] | 489 | if self.comptype == "gz": |
Tim Peters | a05f6e2 | 2006-08-02 05:20:08 +0000 | [diff] [blame] | 490 | # The native zlib crc is an unsigned 32-bit integer, but |
| 491 | # the Python wrapper implicitly casts that to a signed C |
| 492 | # long. So, on a 32-bit box self.crc may "look negative", |
| 493 | # while the same crc on a 64-bit box may "look positive". |
| 494 | # To avoid irksome warnings from the `struct` module, force |
| 495 | # it to look positive on all boxes. |
| 496 | self.fileobj.write(struct.pack("<L", self.crc & 0xffffffffL)) |
Andrew M. Kuchling | 10a4449 | 2003-10-24 17:38:34 +0000 | [diff] [blame] | 497 | self.fileobj.write(struct.pack("<L", self.pos & 0xffffFFFFL)) |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 498 | |
| 499 | if not self._extfileobj: |
| 500 | self.fileobj.close() |
| 501 | |
| 502 | self.closed = True |
| 503 | |
| 504 | def _init_read_gz(self): |
| 505 | """Initialize for reading a gzip compressed fileobj. |
| 506 | """ |
| 507 | self.cmp = self.zlib.decompressobj(-self.zlib.MAX_WBITS) |
| 508 | self.dbuf = "" |
| 509 | |
| 510 | # taken from gzip.GzipFile with some alterations |
| 511 | if self.__read(2) != "\037\213": |
Georg Brandl | e4751e3 | 2006-05-18 06:11:19 +0000 | [diff] [blame] | 512 | raise ReadError("not a gzip file") |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 513 | if self.__read(1) != "\010": |
Georg Brandl | e4751e3 | 2006-05-18 06:11:19 +0000 | [diff] [blame] | 514 | raise CompressionError("unsupported compression method") |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 515 | |
| 516 | flag = ord(self.__read(1)) |
| 517 | self.__read(6) |
| 518 | |
| 519 | if flag & 4: |
| 520 | xlen = ord(self.__read(1)) + 256 * ord(self.__read(1)) |
| 521 | self.read(xlen) |
| 522 | if flag & 8: |
| 523 | while True: |
| 524 | s = self.__read(1) |
| 525 | if not s or s == NUL: |
| 526 | break |
| 527 | if flag & 16: |
| 528 | while True: |
| 529 | s = self.__read(1) |
| 530 | if not s or s == NUL: |
| 531 | break |
| 532 | if flag & 2: |
| 533 | self.__read(2) |
| 534 | |
| 535 | def tell(self): |
| 536 | """Return the stream's file pointer position. |
| 537 | """ |
| 538 | return self.pos |
| 539 | |
| 540 | def seek(self, pos=0): |
| 541 | """Set the stream's file pointer to pos. Negative seeking |
| 542 | is forbidden. |
| 543 | """ |
| 544 | if pos - self.pos >= 0: |
| 545 | blocks, remainder = divmod(pos - self.pos, self.bufsize) |
| 546 | for i in xrange(blocks): |
| 547 | self.read(self.bufsize) |
| 548 | self.read(remainder) |
| 549 | else: |
Georg Brandl | e4751e3 | 2006-05-18 06:11:19 +0000 | [diff] [blame] | 550 | raise StreamError("seeking backwards is not allowed") |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 551 | return self.pos |
| 552 | |
| 553 | def read(self, size=None): |
| 554 | """Return the next size number of bytes from the stream. |
| 555 | If size is not defined, return all bytes of the stream |
| 556 | up to EOF. |
| 557 | """ |
| 558 | if size is None: |
| 559 | t = [] |
| 560 | while True: |
| 561 | buf = self._read(self.bufsize) |
| 562 | if not buf: |
| 563 | break |
| 564 | t.append(buf) |
| 565 | buf = "".join(t) |
| 566 | else: |
| 567 | buf = self._read(size) |
| 568 | self.pos += len(buf) |
| 569 | return buf |
| 570 | |
| 571 | def _read(self, size): |
| 572 | """Return size bytes from the stream. |
| 573 | """ |
Martin v. Löwis | 78be7df | 2005-03-05 12:47:42 +0000 | [diff] [blame] | 574 | if self.comptype == "tar": |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 575 | return self.__read(size) |
| 576 | |
| 577 | c = len(self.dbuf) |
| 578 | t = [self.dbuf] |
| 579 | while c < size: |
| 580 | buf = self.__read(self.bufsize) |
| 581 | if not buf: |
| 582 | break |
Lars Gustäbel | c64e402 | 2007-03-13 10:47:19 +0000 | [diff] [blame] | 583 | try: |
| 584 | buf = self.cmp.decompress(buf) |
| 585 | except IOError: |
| 586 | raise ReadError("invalid compressed data") |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 587 | t.append(buf) |
| 588 | c += len(buf) |
| 589 | t = "".join(t) |
| 590 | self.dbuf = t[size:] |
| 591 | return t[:size] |
| 592 | |
| 593 | def __read(self, size): |
| 594 | """Return size bytes from stream. If internal buffer is empty, |
| 595 | read another block from the stream. |
| 596 | """ |
| 597 | c = len(self.buf) |
| 598 | t = [self.buf] |
| 599 | while c < size: |
| 600 | buf = self.fileobj.read(self.bufsize) |
| 601 | if not buf: |
| 602 | break |
| 603 | t.append(buf) |
| 604 | c += len(buf) |
| 605 | t = "".join(t) |
| 606 | self.buf = t[size:] |
| 607 | return t[:size] |
| 608 | # class _Stream |
| 609 | |
Martin v. Löwis | 78be7df | 2005-03-05 12:47:42 +0000 | [diff] [blame] | 610 | class _StreamProxy(object): |
| 611 | """Small proxy class that enables transparent compression |
| 612 | detection for the Stream interface (mode 'r|*'). |
| 613 | """ |
| 614 | |
| 615 | def __init__(self, fileobj): |
| 616 | self.fileobj = fileobj |
| 617 | self.buf = self.fileobj.read(BLOCKSIZE) |
| 618 | |
| 619 | def read(self, size): |
| 620 | self.read = self.fileobj.read |
| 621 | return self.buf |
| 622 | |
| 623 | def getcomptype(self): |
| 624 | if self.buf.startswith("\037\213\010"): |
| 625 | return "gz" |
| 626 | if self.buf.startswith("BZh91"): |
| 627 | return "bz2" |
| 628 | return "tar" |
| 629 | |
| 630 | def close(self): |
| 631 | self.fileobj.close() |
| 632 | # class StreamProxy |
| 633 | |
Georg Brandl | 49c8f4c | 2006-05-15 19:30:35 +0000 | [diff] [blame] | 634 | class _BZ2Proxy(object): |
| 635 | """Small proxy class that enables external file object |
| 636 | support for "r:bz2" and "w:bz2" modes. This is actually |
| 637 | a workaround for a limitation in bz2 module's BZ2File |
| 638 | class which (unlike gzip.GzipFile) has no support for |
| 639 | a file object argument. |
| 640 | """ |
| 641 | |
| 642 | blocksize = 16 * 1024 |
| 643 | |
| 644 | def __init__(self, fileobj, mode): |
| 645 | self.fileobj = fileobj |
| 646 | self.mode = mode |
Lars Gustäbel | c64e402 | 2007-03-13 10:47:19 +0000 | [diff] [blame] | 647 | self.name = getattr(self.fileobj, "name", None) |
Georg Brandl | 49c8f4c | 2006-05-15 19:30:35 +0000 | [diff] [blame] | 648 | self.init() |
| 649 | |
| 650 | def init(self): |
| 651 | import bz2 |
| 652 | self.pos = 0 |
| 653 | if self.mode == "r": |
| 654 | self.bz2obj = bz2.BZ2Decompressor() |
| 655 | self.fileobj.seek(0) |
| 656 | self.buf = "" |
| 657 | else: |
| 658 | self.bz2obj = bz2.BZ2Compressor() |
| 659 | |
| 660 | def read(self, size): |
| 661 | b = [self.buf] |
| 662 | x = len(self.buf) |
| 663 | while x < size: |
| 664 | try: |
| 665 | raw = self.fileobj.read(self.blocksize) |
| 666 | data = self.bz2obj.decompress(raw) |
| 667 | b.append(data) |
| 668 | except EOFError: |
| 669 | break |
| 670 | x += len(data) |
| 671 | self.buf = "".join(b) |
| 672 | |
| 673 | buf = self.buf[:size] |
| 674 | self.buf = self.buf[size:] |
| 675 | self.pos += len(buf) |
| 676 | return buf |
| 677 | |
| 678 | def seek(self, pos): |
| 679 | if pos < self.pos: |
| 680 | self.init() |
| 681 | self.read(pos - self.pos) |
| 682 | |
| 683 | def tell(self): |
| 684 | return self.pos |
| 685 | |
| 686 | def write(self, data): |
| 687 | self.pos += len(data) |
| 688 | raw = self.bz2obj.compress(data) |
| 689 | self.fileobj.write(raw) |
| 690 | |
| 691 | def close(self): |
| 692 | if self.mode == "w": |
| 693 | raw = self.bz2obj.flush() |
| 694 | self.fileobj.write(raw) |
Georg Brandl | 49c8f4c | 2006-05-15 19:30:35 +0000 | [diff] [blame] | 695 | # class _BZ2Proxy |
| 696 | |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 697 | #------------------------ |
| 698 | # Extraction file object |
| 699 | #------------------------ |
Lars Gustäbel | 6baa502 | 2006-12-23 16:40:13 +0000 | [diff] [blame] | 700 | class _FileInFile(object): |
| 701 | """A thin wrapper around an existing file object that |
| 702 | provides a part of its data as an individual file |
| 703 | object. |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 704 | """ |
| 705 | |
Lars Gustäbel | 6baa502 | 2006-12-23 16:40:13 +0000 | [diff] [blame] | 706 | def __init__(self, fileobj, offset, size, sparse=None): |
| 707 | self.fileobj = fileobj |
| 708 | self.offset = offset |
| 709 | self.size = size |
| 710 | self.sparse = sparse |
| 711 | self.position = 0 |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 712 | |
Lars Gustäbel | 6baa502 | 2006-12-23 16:40:13 +0000 | [diff] [blame] | 713 | def tell(self): |
| 714 | """Return the current file position. |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 715 | """ |
Lars Gustäbel | 6baa502 | 2006-12-23 16:40:13 +0000 | [diff] [blame] | 716 | return self.position |
| 717 | |
| 718 | def seek(self, position): |
| 719 | """Seek to a position in the file. |
| 720 | """ |
| 721 | self.position = position |
| 722 | |
| 723 | def read(self, size=None): |
| 724 | """Read data from the file. |
| 725 | """ |
| 726 | if size is None: |
| 727 | size = self.size - self.position |
| 728 | else: |
| 729 | size = min(size, self.size - self.position) |
| 730 | |
| 731 | if self.sparse is None: |
| 732 | return self.readnormal(size) |
| 733 | else: |
| 734 | return self.readsparse(size) |
| 735 | |
| 736 | def readnormal(self, size): |
| 737 | """Read operation for regular files. |
| 738 | """ |
| 739 | self.fileobj.seek(self.offset + self.position) |
| 740 | self.position += size |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 741 | return self.fileobj.read(size) |
| 742 | |
Lars Gustäbel | 6baa502 | 2006-12-23 16:40:13 +0000 | [diff] [blame] | 743 | def readsparse(self, size): |
| 744 | """Read operation for sparse files. |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 745 | """ |
Lars Gustäbel | 6baa502 | 2006-12-23 16:40:13 +0000 | [diff] [blame] | 746 | data = [] |
| 747 | while size > 0: |
| 748 | buf = self.readsparsesection(size) |
| 749 | if not buf: |
| 750 | break |
| 751 | size -= len(buf) |
| 752 | data.append(buf) |
| 753 | return "".join(data) |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 754 | |
Lars Gustäbel | 6baa502 | 2006-12-23 16:40:13 +0000 | [diff] [blame] | 755 | def readsparsesection(self, size): |
| 756 | """Read a single section of a sparse file. |
| 757 | """ |
| 758 | section = self.sparse.find(self.position) |
| 759 | |
| 760 | if section is None: |
| 761 | return "" |
| 762 | |
| 763 | size = min(size, section.offset + section.size - self.position) |
| 764 | |
| 765 | if isinstance(section, _data): |
| 766 | realpos = section.realpos + self.position - section.offset |
| 767 | self.fileobj.seek(self.offset + realpos) |
| 768 | self.position += size |
| 769 | return self.fileobj.read(size) |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 770 | else: |
Lars Gustäbel | 6baa502 | 2006-12-23 16:40:13 +0000 | [diff] [blame] | 771 | self.position += size |
| 772 | return NUL * size |
| 773 | #class _FileInFile |
| 774 | |
| 775 | |
| 776 | class ExFileObject(object): |
| 777 | """File-like object for reading an archive member. |
| 778 | Is returned by TarFile.extractfile(). |
| 779 | """ |
| 780 | blocksize = 1024 |
| 781 | |
| 782 | def __init__(self, tarfile, tarinfo): |
| 783 | self.fileobj = _FileInFile(tarfile.fileobj, |
| 784 | tarinfo.offset_data, |
| 785 | tarinfo.size, |
| 786 | getattr(tarinfo, "sparse", None)) |
| 787 | self.name = tarinfo.name |
| 788 | self.mode = "r" |
| 789 | self.closed = False |
| 790 | self.size = tarinfo.size |
| 791 | |
| 792 | self.position = 0 |
| 793 | self.buffer = "" |
| 794 | |
| 795 | def read(self, size=None): |
| 796 | """Read at most size bytes from the file. If size is not |
| 797 | present or None, read all data until EOF is reached. |
| 798 | """ |
| 799 | if self.closed: |
| 800 | raise ValueError("I/O operation on closed file") |
| 801 | |
| 802 | buf = "" |
| 803 | if self.buffer: |
| 804 | if size is None: |
| 805 | buf = self.buffer |
| 806 | self.buffer = "" |
| 807 | else: |
| 808 | buf = self.buffer[:size] |
| 809 | self.buffer = self.buffer[size:] |
| 810 | |
| 811 | if size is None: |
| 812 | buf += self.fileobj.read() |
| 813 | else: |
| 814 | buf += self.fileobj.read(size - len(buf)) |
| 815 | |
| 816 | self.position += len(buf) |
| 817 | return buf |
| 818 | |
| 819 | def readline(self, size=-1): |
| 820 | """Read one entire line from the file. If size is present |
| 821 | and non-negative, return a string with at most that |
| 822 | size, which may be an incomplete line. |
| 823 | """ |
| 824 | if self.closed: |
| 825 | raise ValueError("I/O operation on closed file") |
| 826 | |
| 827 | if "\n" in self.buffer: |
| 828 | pos = self.buffer.find("\n") + 1 |
| 829 | else: |
| 830 | buffers = [self.buffer] |
| 831 | while True: |
| 832 | buf = self.fileobj.read(self.blocksize) |
| 833 | buffers.append(buf) |
| 834 | if not buf or "\n" in buf: |
| 835 | self.buffer = "".join(buffers) |
| 836 | pos = self.buffer.find("\n") + 1 |
| 837 | if pos == 0: |
| 838 | # no newline found. |
| 839 | pos = len(self.buffer) |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 840 | break |
Lars Gustäbel | 6baa502 | 2006-12-23 16:40:13 +0000 | [diff] [blame] | 841 | |
| 842 | if size != -1: |
| 843 | pos = min(size, pos) |
| 844 | |
| 845 | buf = self.buffer[:pos] |
| 846 | self.buffer = self.buffer[pos:] |
| 847 | self.position += len(buf) |
| 848 | return buf |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 849 | |
| 850 | def readlines(self): |
Lars Gustäbel | 6baa502 | 2006-12-23 16:40:13 +0000 | [diff] [blame] | 851 | """Return a list with all remaining lines. |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 852 | """ |
| 853 | result = [] |
| 854 | while True: |
| 855 | line = self.readline() |
| 856 | if not line: break |
| 857 | result.append(line) |
| 858 | return result |
| 859 | |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 860 | def tell(self): |
| 861 | """Return the current file position. |
| 862 | """ |
Lars Gustäbel | 6baa502 | 2006-12-23 16:40:13 +0000 | [diff] [blame] | 863 | if self.closed: |
| 864 | raise ValueError("I/O operation on closed file") |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 865 | |
Lars Gustäbel | 6baa502 | 2006-12-23 16:40:13 +0000 | [diff] [blame] | 866 | return self.position |
| 867 | |
| 868 | def seek(self, pos, whence=os.SEEK_SET): |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 869 | """Seek to a position in the file. |
| 870 | """ |
Lars Gustäbel | 6baa502 | 2006-12-23 16:40:13 +0000 | [diff] [blame] | 871 | if self.closed: |
| 872 | raise ValueError("I/O operation on closed file") |
| 873 | |
| 874 | if whence == os.SEEK_SET: |
| 875 | self.position = min(max(pos, 0), self.size) |
| 876 | elif whence == os.SEEK_CUR: |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 877 | if pos < 0: |
Lars Gustäbel | 6baa502 | 2006-12-23 16:40:13 +0000 | [diff] [blame] | 878 | self.position = max(self.position + pos, 0) |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 879 | else: |
Lars Gustäbel | 6baa502 | 2006-12-23 16:40:13 +0000 | [diff] [blame] | 880 | self.position = min(self.position + pos, self.size) |
| 881 | elif whence == os.SEEK_END: |
| 882 | self.position = max(min(self.size + pos, self.size), 0) |
| 883 | else: |
| 884 | raise ValueError("Invalid argument") |
| 885 | |
| 886 | self.buffer = "" |
| 887 | self.fileobj.seek(self.position) |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 888 | |
| 889 | def close(self): |
| 890 | """Close the file object. |
| 891 | """ |
| 892 | self.closed = True |
Martin v. Löwis | df24153 | 2005-03-03 08:17:42 +0000 | [diff] [blame] | 893 | |
| 894 | def __iter__(self): |
Lars Gustäbel | 6baa502 | 2006-12-23 16:40:13 +0000 | [diff] [blame] | 895 | """Get an iterator over the file's lines. |
Martin v. Löwis | df24153 | 2005-03-03 08:17:42 +0000 | [diff] [blame] | 896 | """ |
Lars Gustäbel | 6baa502 | 2006-12-23 16:40:13 +0000 | [diff] [blame] | 897 | while True: |
| 898 | line = self.readline() |
| 899 | if not line: |
| 900 | break |
| 901 | yield line |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 902 | #class ExFileObject |
| 903 | |
| 904 | #------------------ |
| 905 | # Exported Classes |
| 906 | #------------------ |
| 907 | class TarInfo(object): |
| 908 | """Informational class which holds the details about an |
| 909 | archive member given by a tar header block. |
| 910 | TarInfo objects are returned by TarFile.getmember(), |
| 911 | TarFile.getmembers() and TarFile.gettarinfo() and are |
| 912 | usually created internally. |
| 913 | """ |
| 914 | |
| 915 | def __init__(self, name=""): |
| 916 | """Construct a TarInfo object. name is the optional name |
| 917 | of the member. |
| 918 | """ |
Lars Gustäbel | c64e402 | 2007-03-13 10:47:19 +0000 | [diff] [blame] | 919 | self.name = name # member name |
| 920 | self.mode = 0644 # file permissions |
Georg Brandl | 38c6a22 | 2006-05-10 16:26:03 +0000 | [diff] [blame] | 921 | self.uid = 0 # user id |
| 922 | self.gid = 0 # group id |
| 923 | self.size = 0 # file size |
| 924 | self.mtime = 0 # modification time |
| 925 | self.chksum = 0 # header checksum |
| 926 | self.type = REGTYPE # member type |
| 927 | self.linkname = "" # link name |
Lars Gustäbel | c64e402 | 2007-03-13 10:47:19 +0000 | [diff] [blame] | 928 | self.uname = "root" # user name |
| 929 | self.gname = "root" # group name |
Georg Brandl | 38c6a22 | 2006-05-10 16:26:03 +0000 | [diff] [blame] | 930 | self.devmajor = 0 # device major number |
| 931 | self.devminor = 0 # device minor number |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 932 | |
Georg Brandl | 38c6a22 | 2006-05-10 16:26:03 +0000 | [diff] [blame] | 933 | self.offset = 0 # the tar header starts here |
| 934 | self.offset_data = 0 # the file's data starts here |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 935 | |
Lars Gustäbel | c64e402 | 2007-03-13 10:47:19 +0000 | [diff] [blame] | 936 | self.pax_headers = {} # pax header information |
| 937 | |
| 938 | # In pax headers the "name" and "linkname" field are called |
| 939 | # "path" and "linkpath". |
| 940 | def _getpath(self): |
| 941 | return self.name |
| 942 | def _setpath(self, name): |
| 943 | self.name = name |
| 944 | path = property(_getpath, _setpath) |
| 945 | |
| 946 | def _getlinkpath(self): |
| 947 | return self.linkname |
| 948 | def _setlinkpath(self, linkname): |
| 949 | self.linkname = linkname |
| 950 | linkpath = property(_getlinkpath, _setlinkpath) |
| 951 | |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 952 | def __repr__(self): |
| 953 | return "<%s %r at %#x>" % (self.__class__.__name__,self.name,id(self)) |
| 954 | |
Lars Gustäbel | a0fcb93 | 2007-05-27 19:49:30 +0000 | [diff] [blame] | 955 | def get_info(self, encoding, errors): |
Lars Gustäbel | c64e402 | 2007-03-13 10:47:19 +0000 | [diff] [blame] | 956 | """Return the TarInfo's attributes as a dictionary. |
| 957 | """ |
| 958 | info = { |
| 959 | "name": normpath(self.name), |
| 960 | "mode": self.mode & 07777, |
| 961 | "uid": self.uid, |
| 962 | "gid": self.gid, |
| 963 | "size": self.size, |
| 964 | "mtime": self.mtime, |
| 965 | "chksum": self.chksum, |
| 966 | "type": self.type, |
| 967 | "linkname": normpath(self.linkname) if self.linkname else "", |
| 968 | "uname": self.uname, |
| 969 | "gname": self.gname, |
| 970 | "devmajor": self.devmajor, |
| 971 | "devminor": self.devminor |
| 972 | } |
| 973 | |
| 974 | if info["type"] == DIRTYPE and not info["name"].endswith("/"): |
| 975 | info["name"] += "/" |
| 976 | |
Lars Gustäbel | a0fcb93 | 2007-05-27 19:49:30 +0000 | [diff] [blame] | 977 | for key in ("name", "linkname", "uname", "gname"): |
| 978 | if type(info[key]) is unicode: |
| 979 | info[key] = info[key].encode(encoding, errors) |
| 980 | |
Lars Gustäbel | c64e402 | 2007-03-13 10:47:19 +0000 | [diff] [blame] | 981 | return info |
| 982 | |
Lars Gustäbel | a0fcb93 | 2007-05-27 19:49:30 +0000 | [diff] [blame] | 983 | def tobuf(self, format=DEFAULT_FORMAT, encoding=ENCODING, errors="strict"): |
Lars Gustäbel | c64e402 | 2007-03-13 10:47:19 +0000 | [diff] [blame] | 984 | """Return a tar header as a string of 512 byte blocks. |
| 985 | """ |
Lars Gustäbel | a0fcb93 | 2007-05-27 19:49:30 +0000 | [diff] [blame] | 986 | info = self.get_info(encoding, errors) |
| 987 | |
Lars Gustäbel | c64e402 | 2007-03-13 10:47:19 +0000 | [diff] [blame] | 988 | if format == USTAR_FORMAT: |
Lars Gustäbel | a0fcb93 | 2007-05-27 19:49:30 +0000 | [diff] [blame] | 989 | return self.create_ustar_header(info) |
Lars Gustäbel | c64e402 | 2007-03-13 10:47:19 +0000 | [diff] [blame] | 990 | elif format == GNU_FORMAT: |
Lars Gustäbel | a0fcb93 | 2007-05-27 19:49:30 +0000 | [diff] [blame] | 991 | return self.create_gnu_header(info) |
Lars Gustäbel | c64e402 | 2007-03-13 10:47:19 +0000 | [diff] [blame] | 992 | elif format == PAX_FORMAT: |
Lars Gustäbel | a0fcb93 | 2007-05-27 19:49:30 +0000 | [diff] [blame] | 993 | return self.create_pax_header(info, encoding, errors) |
Lars Gustäbel | c64e402 | 2007-03-13 10:47:19 +0000 | [diff] [blame] | 994 | else: |
| 995 | raise ValueError("invalid format") |
| 996 | |
Lars Gustäbel | a0fcb93 | 2007-05-27 19:49:30 +0000 | [diff] [blame] | 997 | def create_ustar_header(self, info): |
Lars Gustäbel | c64e402 | 2007-03-13 10:47:19 +0000 | [diff] [blame] | 998 | """Return the object as a ustar header block. |
| 999 | """ |
Lars Gustäbel | c64e402 | 2007-03-13 10:47:19 +0000 | [diff] [blame] | 1000 | info["magic"] = POSIX_MAGIC |
| 1001 | |
| 1002 | if len(info["linkname"]) > LENGTH_LINK: |
| 1003 | raise ValueError("linkname is too long") |
| 1004 | |
| 1005 | if len(info["name"]) > LENGTH_NAME: |
| 1006 | info["prefix"], info["name"] = self._posix_split_name(info["name"]) |
| 1007 | |
| 1008 | return self._create_header(info, USTAR_FORMAT) |
| 1009 | |
Lars Gustäbel | a0fcb93 | 2007-05-27 19:49:30 +0000 | [diff] [blame] | 1010 | def create_gnu_header(self, info): |
Lars Gustäbel | c64e402 | 2007-03-13 10:47:19 +0000 | [diff] [blame] | 1011 | """Return the object as a GNU header block sequence. |
| 1012 | """ |
Lars Gustäbel | c64e402 | 2007-03-13 10:47:19 +0000 | [diff] [blame] | 1013 | info["magic"] = GNU_MAGIC |
| 1014 | |
| 1015 | buf = "" |
| 1016 | if len(info["linkname"]) > LENGTH_LINK: |
| 1017 | buf += self._create_gnu_long_header(info["linkname"], GNUTYPE_LONGLINK) |
| 1018 | |
| 1019 | if len(info["name"]) > LENGTH_NAME: |
| 1020 | buf += self._create_gnu_long_header(info["name"], GNUTYPE_LONGNAME) |
| 1021 | |
| 1022 | return buf + self._create_header(info, GNU_FORMAT) |
| 1023 | |
Lars Gustäbel | a0fcb93 | 2007-05-27 19:49:30 +0000 | [diff] [blame] | 1024 | def create_pax_header(self, info, encoding, errors): |
Lars Gustäbel | c64e402 | 2007-03-13 10:47:19 +0000 | [diff] [blame] | 1025 | """Return the object as a ustar header block. If it cannot be |
| 1026 | represented this way, prepend a pax extended header sequence |
| 1027 | with supplement information. |
| 1028 | """ |
Lars Gustäbel | c64e402 | 2007-03-13 10:47:19 +0000 | [diff] [blame] | 1029 | info["magic"] = POSIX_MAGIC |
| 1030 | pax_headers = self.pax_headers.copy() |
| 1031 | |
| 1032 | # Test string fields for values that exceed the field length or cannot |
| 1033 | # be represented in ASCII encoding. |
| 1034 | for name, hname, length in ( |
| 1035 | ("name", "path", LENGTH_NAME), ("linkname", "linkpath", LENGTH_LINK), |
| 1036 | ("uname", "uname", 32), ("gname", "gname", 32)): |
| 1037 | |
Lars Gustäbel | a0fcb93 | 2007-05-27 19:49:30 +0000 | [diff] [blame] | 1038 | if hname in pax_headers: |
| 1039 | # The pax header has priority. |
| 1040 | continue |
| 1041 | |
| 1042 | val = info[name].decode(encoding, errors) |
Lars Gustäbel | c64e402 | 2007-03-13 10:47:19 +0000 | [diff] [blame] | 1043 | |
| 1044 | # Try to encode the string as ASCII. |
| 1045 | try: |
| 1046 | val.encode("ascii") |
| 1047 | except UnicodeEncodeError: |
| 1048 | pax_headers[hname] = val |
| 1049 | continue |
| 1050 | |
Lars Gustäbel | a0fcb93 | 2007-05-27 19:49:30 +0000 | [diff] [blame] | 1051 | if len(info[name]) > length: |
| 1052 | pax_headers[hname] = val |
Lars Gustäbel | c64e402 | 2007-03-13 10:47:19 +0000 | [diff] [blame] | 1053 | |
| 1054 | # Test number fields for values that exceed the field limit or values |
| 1055 | # that like to be stored as float. |
| 1056 | for name, digits in (("uid", 8), ("gid", 8), ("size", 12), ("mtime", 12)): |
Lars Gustäbel | a0fcb93 | 2007-05-27 19:49:30 +0000 | [diff] [blame] | 1057 | if name in pax_headers: |
| 1058 | # The pax header has priority. Avoid overflow. |
| 1059 | info[name] = 0 |
| 1060 | continue |
| 1061 | |
Lars Gustäbel | c64e402 | 2007-03-13 10:47:19 +0000 | [diff] [blame] | 1062 | val = info[name] |
| 1063 | if not 0 <= val < 8 ** (digits - 1) or isinstance(val, float): |
| 1064 | pax_headers[name] = unicode(val) |
| 1065 | info[name] = 0 |
| 1066 | |
Lars Gustäbel | a0fcb93 | 2007-05-27 19:49:30 +0000 | [diff] [blame] | 1067 | # Create a pax extended header if necessary. |
Lars Gustäbel | c64e402 | 2007-03-13 10:47:19 +0000 | [diff] [blame] | 1068 | if pax_headers: |
| 1069 | buf = self._create_pax_generic_header(pax_headers) |
| 1070 | else: |
| 1071 | buf = "" |
| 1072 | |
| 1073 | return buf + self._create_header(info, USTAR_FORMAT) |
| 1074 | |
| 1075 | @classmethod |
Lars Gustäbel | a0fcb93 | 2007-05-27 19:49:30 +0000 | [diff] [blame] | 1076 | def create_pax_global_header(cls, pax_headers): |
Lars Gustäbel | c64e402 | 2007-03-13 10:47:19 +0000 | [diff] [blame] | 1077 | """Return the object as a pax global header block sequence. |
| 1078 | """ |
Lars Gustäbel | a0fcb93 | 2007-05-27 19:49:30 +0000 | [diff] [blame] | 1079 | return cls._create_pax_generic_header(pax_headers, type=XGLTYPE) |
Lars Gustäbel | c64e402 | 2007-03-13 10:47:19 +0000 | [diff] [blame] | 1080 | |
| 1081 | def _posix_split_name(self, name): |
| 1082 | """Split a name longer than 100 chars into a prefix |
| 1083 | and a name part. |
| 1084 | """ |
| 1085 | prefix = name[:LENGTH_PREFIX + 1] |
| 1086 | while prefix and prefix[-1] != "/": |
| 1087 | prefix = prefix[:-1] |
| 1088 | |
| 1089 | name = name[len(prefix):] |
| 1090 | prefix = prefix[:-1] |
| 1091 | |
| 1092 | if not prefix or len(name) > LENGTH_NAME: |
| 1093 | raise ValueError("name is too long") |
| 1094 | return prefix, name |
| 1095 | |
| 1096 | @staticmethod |
| 1097 | def _create_header(info, format): |
| 1098 | """Return a header block. info is a dictionary with file |
| 1099 | information, format must be one of the *_FORMAT constants. |
| 1100 | """ |
| 1101 | parts = [ |
| 1102 | stn(info.get("name", ""), 100), |
| 1103 | itn(info.get("mode", 0) & 07777, 8, format), |
| 1104 | itn(info.get("uid", 0), 8, format), |
| 1105 | itn(info.get("gid", 0), 8, format), |
| 1106 | itn(info.get("size", 0), 12, format), |
| 1107 | itn(info.get("mtime", 0), 12, format), |
| 1108 | " ", # checksum field |
| 1109 | info.get("type", REGTYPE), |
| 1110 | stn(info.get("linkname", ""), 100), |
Lars Gustäbel | a0fcb93 | 2007-05-27 19:49:30 +0000 | [diff] [blame] | 1111 | stn(info.get("magic", POSIX_MAGIC), 8), |
| 1112 | stn(info.get("uname", "root"), 32), |
| 1113 | stn(info.get("gname", "root"), 32), |
Lars Gustäbel | c64e402 | 2007-03-13 10:47:19 +0000 | [diff] [blame] | 1114 | itn(info.get("devmajor", 0), 8, format), |
| 1115 | itn(info.get("devminor", 0), 8, format), |
| 1116 | stn(info.get("prefix", ""), 155) |
| 1117 | ] |
| 1118 | |
| 1119 | buf = struct.pack("%ds" % BLOCKSIZE, "".join(parts)) |
| 1120 | chksum = calc_chksums(buf[-BLOCKSIZE:])[0] |
| 1121 | buf = buf[:-364] + "%06o\0" % chksum + buf[-357:] |
| 1122 | return buf |
| 1123 | |
| 1124 | @staticmethod |
| 1125 | def _create_payload(payload): |
| 1126 | """Return the string payload filled with zero bytes |
| 1127 | up to the next 512 byte border. |
| 1128 | """ |
| 1129 | blocks, remainder = divmod(len(payload), BLOCKSIZE) |
| 1130 | if remainder > 0: |
| 1131 | payload += (BLOCKSIZE - remainder) * NUL |
| 1132 | return payload |
| 1133 | |
| 1134 | @classmethod |
| 1135 | def _create_gnu_long_header(cls, name, type): |
| 1136 | """Return a GNUTYPE_LONGNAME or GNUTYPE_LONGLINK sequence |
| 1137 | for name. |
| 1138 | """ |
| 1139 | name += NUL |
| 1140 | |
| 1141 | info = {} |
| 1142 | info["name"] = "././@LongLink" |
| 1143 | info["type"] = type |
| 1144 | info["size"] = len(name) |
| 1145 | info["magic"] = GNU_MAGIC |
| 1146 | |
| 1147 | # create extended header + name blocks. |
| 1148 | return cls._create_header(info, USTAR_FORMAT) + \ |
| 1149 | cls._create_payload(name) |
| 1150 | |
| 1151 | @classmethod |
| 1152 | def _create_pax_generic_header(cls, pax_headers, type=XHDTYPE): |
| 1153 | """Return a POSIX.1-2001 extended or global header sequence |
| 1154 | that contains a list of keyword, value pairs. The values |
| 1155 | must be unicode objects. |
| 1156 | """ |
| 1157 | records = [] |
| 1158 | for keyword, value in pax_headers.iteritems(): |
| 1159 | keyword = keyword.encode("utf8") |
| 1160 | value = value.encode("utf8") |
| 1161 | l = len(keyword) + len(value) + 3 # ' ' + '=' + '\n' |
| 1162 | n = p = 0 |
| 1163 | while True: |
| 1164 | n = l + len(str(p)) |
| 1165 | if n == p: |
| 1166 | break |
| 1167 | p = n |
| 1168 | records.append("%d %s=%s\n" % (p, keyword, value)) |
| 1169 | records = "".join(records) |
| 1170 | |
| 1171 | # We use a hardcoded "././@PaxHeader" name like star does |
| 1172 | # instead of the one that POSIX recommends. |
| 1173 | info = {} |
| 1174 | info["name"] = "././@PaxHeader" |
| 1175 | info["type"] = type |
| 1176 | info["size"] = len(records) |
| 1177 | info["magic"] = POSIX_MAGIC |
| 1178 | |
| 1179 | # Create pax header + record blocks. |
| 1180 | return cls._create_header(info, USTAR_FORMAT) + \ |
| 1181 | cls._create_payload(records) |
| 1182 | |
Guido van Rossum | 75b64e6 | 2005-01-16 00:16:11 +0000 | [diff] [blame] | 1183 | @classmethod |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 1184 | def frombuf(cls, buf): |
| 1185 | """Construct a TarInfo object from a 512 byte string buffer. |
| 1186 | """ |
Georg Brandl | 38c6a22 | 2006-05-10 16:26:03 +0000 | [diff] [blame] | 1187 | if len(buf) != BLOCKSIZE: |
Georg Brandl | ebbeed7 | 2006-12-19 22:06:46 +0000 | [diff] [blame] | 1188 | raise HeaderError("truncated header") |
Georg Brandl | 38c6a22 | 2006-05-10 16:26:03 +0000 | [diff] [blame] | 1189 | if buf.count(NUL) == BLOCKSIZE: |
Georg Brandl | ebbeed7 | 2006-12-19 22:06:46 +0000 | [diff] [blame] | 1190 | raise HeaderError("empty header") |
| 1191 | |
Georg Brandl | ded1c4d | 2006-12-20 11:55:16 +0000 | [diff] [blame] | 1192 | chksum = nti(buf[148:156]) |
Georg Brandl | ebbeed7 | 2006-12-19 22:06:46 +0000 | [diff] [blame] | 1193 | if chksum not in calc_chksums(buf): |
| 1194 | raise HeaderError("bad checksum") |
Georg Brandl | 38c6a22 | 2006-05-10 16:26:03 +0000 | [diff] [blame] | 1195 | |
Lars Gustäbel | c64e402 | 2007-03-13 10:47:19 +0000 | [diff] [blame] | 1196 | obj = cls() |
| 1197 | obj.buf = buf |
| 1198 | obj.name = nts(buf[0:100]) |
| 1199 | obj.mode = nti(buf[100:108]) |
| 1200 | obj.uid = nti(buf[108:116]) |
| 1201 | obj.gid = nti(buf[116:124]) |
| 1202 | obj.size = nti(buf[124:136]) |
| 1203 | obj.mtime = nti(buf[136:148]) |
| 1204 | obj.chksum = chksum |
| 1205 | obj.type = buf[156:157] |
| 1206 | obj.linkname = nts(buf[157:257]) |
| 1207 | obj.uname = nts(buf[265:297]) |
| 1208 | obj.gname = nts(buf[297:329]) |
| 1209 | obj.devmajor = nti(buf[329:337]) |
| 1210 | obj.devminor = nti(buf[337:345]) |
| 1211 | prefix = nts(buf[345:500]) |
Georg Brandl | 3354f28 | 2006-10-29 09:16:12 +0000 | [diff] [blame] | 1212 | |
Lars Gustäbel | c64e402 | 2007-03-13 10:47:19 +0000 | [diff] [blame] | 1213 | # Old V7 tar format represents a directory as a regular |
| 1214 | # file with a trailing slash. |
| 1215 | if obj.type == AREGTYPE and obj.name.endswith("/"): |
| 1216 | obj.type = DIRTYPE |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 1217 | |
Lars Gustäbel | c64e402 | 2007-03-13 10:47:19 +0000 | [diff] [blame] | 1218 | # Remove redundant slashes from directories. |
| 1219 | if obj.isdir(): |
| 1220 | obj.name = obj.name.rstrip("/") |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 1221 | |
Lars Gustäbel | c64e402 | 2007-03-13 10:47:19 +0000 | [diff] [blame] | 1222 | # Reconstruct a ustar longname. |
| 1223 | if prefix and obj.type not in GNU_TYPES: |
| 1224 | obj.name = prefix + "/" + obj.name |
| 1225 | return obj |
| 1226 | |
| 1227 | @classmethod |
| 1228 | def fromtarfile(cls, tarfile): |
| 1229 | """Return the next TarInfo object from TarFile object |
| 1230 | tarfile. |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 1231 | """ |
Lars Gustäbel | c64e402 | 2007-03-13 10:47:19 +0000 | [diff] [blame] | 1232 | buf = tarfile.fileobj.read(BLOCKSIZE) |
| 1233 | if not buf: |
| 1234 | return |
| 1235 | obj = cls.frombuf(buf) |
| 1236 | obj.offset = tarfile.fileobj.tell() - BLOCKSIZE |
| 1237 | return obj._proc_member(tarfile) |
Georg Brandl | 3354f28 | 2006-10-29 09:16:12 +0000 | [diff] [blame] | 1238 | |
Lars Gustäbel | c64e402 | 2007-03-13 10:47:19 +0000 | [diff] [blame] | 1239 | #-------------------------------------------------------------------------- |
| 1240 | # The following are methods that are called depending on the type of a |
| 1241 | # member. The entry point is _proc_member() which can be overridden in a |
| 1242 | # subclass to add custom _proc_*() methods. A _proc_*() method MUST |
| 1243 | # implement the following |
| 1244 | # operations: |
| 1245 | # 1. Set self.offset_data to the position where the data blocks begin, |
| 1246 | # if there is data that follows. |
| 1247 | # 2. Set tarfile.offset to the position where the next member's header will |
| 1248 | # begin. |
| 1249 | # 3. Return self or another valid TarInfo object. |
| 1250 | def _proc_member(self, tarfile): |
| 1251 | """Choose the right processing method depending on |
| 1252 | the type and call it. |
Georg Brandl | 3354f28 | 2006-10-29 09:16:12 +0000 | [diff] [blame] | 1253 | """ |
Lars Gustäbel | c64e402 | 2007-03-13 10:47:19 +0000 | [diff] [blame] | 1254 | if self.type in (GNUTYPE_LONGNAME, GNUTYPE_LONGLINK): |
| 1255 | return self._proc_gnulong(tarfile) |
| 1256 | elif self.type == GNUTYPE_SPARSE: |
| 1257 | return self._proc_sparse(tarfile) |
| 1258 | elif self.type in (XHDTYPE, XGLTYPE, SOLARIS_XHDTYPE): |
| 1259 | return self._proc_pax(tarfile) |
| 1260 | else: |
| 1261 | return self._proc_builtin(tarfile) |
Georg Brandl | 3354f28 | 2006-10-29 09:16:12 +0000 | [diff] [blame] | 1262 | |
Lars Gustäbel | c64e402 | 2007-03-13 10:47:19 +0000 | [diff] [blame] | 1263 | def _proc_builtin(self, tarfile): |
| 1264 | """Process a builtin type or an unknown type which |
| 1265 | will be treated as a regular file. |
| 1266 | """ |
| 1267 | self.offset_data = tarfile.fileobj.tell() |
| 1268 | offset = self.offset_data |
| 1269 | if self.isreg() or self.type not in SUPPORTED_TYPES: |
| 1270 | # Skip the following data blocks. |
| 1271 | offset += self._block(self.size) |
| 1272 | tarfile.offset = offset |
Georg Brandl | 3354f28 | 2006-10-29 09:16:12 +0000 | [diff] [blame] | 1273 | |
Lars Gustäbel | a0fcb93 | 2007-05-27 19:49:30 +0000 | [diff] [blame] | 1274 | # Patch the TarInfo object with saved global |
Lars Gustäbel | c64e402 | 2007-03-13 10:47:19 +0000 | [diff] [blame] | 1275 | # header information. |
Lars Gustäbel | a0fcb93 | 2007-05-27 19:49:30 +0000 | [diff] [blame] | 1276 | self._apply_pax_info(tarfile.pax_headers, tarfile.encoding, tarfile.errors) |
Lars Gustäbel | c64e402 | 2007-03-13 10:47:19 +0000 | [diff] [blame] | 1277 | |
| 1278 | return self |
| 1279 | |
| 1280 | def _proc_gnulong(self, tarfile): |
| 1281 | """Process the blocks that hold a GNU longname |
| 1282 | or longlink member. |
| 1283 | """ |
| 1284 | buf = tarfile.fileobj.read(self._block(self.size)) |
| 1285 | |
| 1286 | # Fetch the next header and process it. |
Lars Gustäbel | a0fcb93 | 2007-05-27 19:49:30 +0000 | [diff] [blame] | 1287 | next = self.fromtarfile(tarfile) |
| 1288 | if next is None: |
| 1289 | raise HeaderError("missing subsequent header") |
Lars Gustäbel | c64e402 | 2007-03-13 10:47:19 +0000 | [diff] [blame] | 1290 | |
| 1291 | # Patch the TarInfo object from the next header with |
| 1292 | # the longname information. |
| 1293 | next.offset = self.offset |
| 1294 | if self.type == GNUTYPE_LONGNAME: |
Lars Gustäbel | a0fcb93 | 2007-05-27 19:49:30 +0000 | [diff] [blame] | 1295 | next.name = nts(buf) |
Lars Gustäbel | c64e402 | 2007-03-13 10:47:19 +0000 | [diff] [blame] | 1296 | elif self.type == GNUTYPE_LONGLINK: |
Lars Gustäbel | a0fcb93 | 2007-05-27 19:49:30 +0000 | [diff] [blame] | 1297 | next.linkname = nts(buf) |
Lars Gustäbel | c64e402 | 2007-03-13 10:47:19 +0000 | [diff] [blame] | 1298 | |
| 1299 | return next |
| 1300 | |
| 1301 | def _proc_sparse(self, tarfile): |
| 1302 | """Process a GNU sparse header plus extra headers. |
| 1303 | """ |
| 1304 | buf = self.buf |
| 1305 | sp = _ringbuffer() |
| 1306 | pos = 386 |
| 1307 | lastpos = 0L |
| 1308 | realpos = 0L |
| 1309 | # There are 4 possible sparse structs in the |
| 1310 | # first header. |
| 1311 | for i in xrange(4): |
| 1312 | try: |
| 1313 | offset = nti(buf[pos:pos + 12]) |
| 1314 | numbytes = nti(buf[pos + 12:pos + 24]) |
| 1315 | except ValueError: |
| 1316 | break |
| 1317 | if offset > lastpos: |
| 1318 | sp.append(_hole(lastpos, offset - lastpos)) |
| 1319 | sp.append(_data(offset, numbytes, realpos)) |
| 1320 | realpos += numbytes |
| 1321 | lastpos = offset + numbytes |
| 1322 | pos += 24 |
| 1323 | |
| 1324 | isextended = ord(buf[482]) |
| 1325 | origsize = nti(buf[483:495]) |
| 1326 | |
| 1327 | # If the isextended flag is given, |
| 1328 | # there are extra headers to process. |
| 1329 | while isextended == 1: |
| 1330 | buf = tarfile.fileobj.read(BLOCKSIZE) |
| 1331 | pos = 0 |
| 1332 | for i in xrange(21): |
| 1333 | try: |
| 1334 | offset = nti(buf[pos:pos + 12]) |
| 1335 | numbytes = nti(buf[pos + 12:pos + 24]) |
| 1336 | except ValueError: |
| 1337 | break |
| 1338 | if offset > lastpos: |
| 1339 | sp.append(_hole(lastpos, offset - lastpos)) |
| 1340 | sp.append(_data(offset, numbytes, realpos)) |
| 1341 | realpos += numbytes |
| 1342 | lastpos = offset + numbytes |
| 1343 | pos += 24 |
| 1344 | isextended = ord(buf[504]) |
| 1345 | |
| 1346 | if lastpos < origsize: |
| 1347 | sp.append(_hole(lastpos, origsize - lastpos)) |
| 1348 | |
| 1349 | self.sparse = sp |
| 1350 | |
| 1351 | self.offset_data = tarfile.fileobj.tell() |
| 1352 | tarfile.offset = self.offset_data + self._block(self.size) |
| 1353 | self.size = origsize |
| 1354 | |
| 1355 | return self |
| 1356 | |
| 1357 | def _proc_pax(self, tarfile): |
| 1358 | """Process an extended or global header as described in |
| 1359 | POSIX.1-2001. |
| 1360 | """ |
| 1361 | # Read the header information. |
| 1362 | buf = tarfile.fileobj.read(self._block(self.size)) |
| 1363 | |
| 1364 | # A pax header stores supplemental information for either |
| 1365 | # the following file (extended) or all following files |
| 1366 | # (global). |
| 1367 | if self.type == XGLTYPE: |
| 1368 | pax_headers = tarfile.pax_headers |
| 1369 | else: |
| 1370 | pax_headers = tarfile.pax_headers.copy() |
| 1371 | |
Lars Gustäbel | c64e402 | 2007-03-13 10:47:19 +0000 | [diff] [blame] | 1372 | # Parse pax header information. A record looks like that: |
| 1373 | # "%d %s=%s\n" % (length, keyword, value). length is the size |
| 1374 | # of the complete record including the length field itself and |
Lars Gustäbel | a0fcb93 | 2007-05-27 19:49:30 +0000 | [diff] [blame] | 1375 | # the newline. keyword and value are both UTF-8 encoded strings. |
Lars Gustäbel | c64e402 | 2007-03-13 10:47:19 +0000 | [diff] [blame] | 1376 | regex = re.compile(r"(\d+) ([^=]+)=", re.U) |
| 1377 | pos = 0 |
| 1378 | while True: |
| 1379 | match = regex.match(buf, pos) |
| 1380 | if not match: |
| 1381 | break |
| 1382 | |
| 1383 | length, keyword = match.groups() |
| 1384 | length = int(length) |
| 1385 | value = buf[match.end(2) + 1:match.start(1) + length - 1] |
| 1386 | |
| 1387 | keyword = keyword.decode("utf8") |
Lars Gustäbel | c64e402 | 2007-03-13 10:47:19 +0000 | [diff] [blame] | 1388 | value = value.decode("utf8") |
Lars Gustäbel | c64e402 | 2007-03-13 10:47:19 +0000 | [diff] [blame] | 1389 | |
| 1390 | pax_headers[keyword] = value |
| 1391 | pos += length |
| 1392 | |
Lars Gustäbel | a0fcb93 | 2007-05-27 19:49:30 +0000 | [diff] [blame] | 1393 | # Fetch the next header. |
| 1394 | next = self.fromtarfile(tarfile) |
Lars Gustäbel | c64e402 | 2007-03-13 10:47:19 +0000 | [diff] [blame] | 1395 | |
Lars Gustäbel | a0fcb93 | 2007-05-27 19:49:30 +0000 | [diff] [blame] | 1396 | if self.type in (XHDTYPE, SOLARIS_XHDTYPE): |
| 1397 | if next is None: |
| 1398 | raise HeaderError("missing subsequent header") |
Lars Gustäbel | c64e402 | 2007-03-13 10:47:19 +0000 | [diff] [blame] | 1399 | |
Lars Gustäbel | a0fcb93 | 2007-05-27 19:49:30 +0000 | [diff] [blame] | 1400 | # Patch the TarInfo object with the extended header info. |
| 1401 | next._apply_pax_info(pax_headers, tarfile.encoding, tarfile.errors) |
| 1402 | next.offset = self.offset |
| 1403 | |
| 1404 | if pax_headers.has_key("size"): |
| 1405 | # If the extended header replaces the size field, |
| 1406 | # we need to recalculate the offset where the next |
| 1407 | # header starts. |
| 1408 | offset = next.offset_data |
| 1409 | if next.isreg() or next.type not in SUPPORTED_TYPES: |
| 1410 | offset += next._block(next.size) |
| 1411 | tarfile.offset = offset |
| 1412 | |
| 1413 | return next |
| 1414 | |
| 1415 | def _apply_pax_info(self, pax_headers, encoding, errors): |
| 1416 | """Replace fields with supplemental information from a previous |
| 1417 | pax extended or global header. |
| 1418 | """ |
| 1419 | for keyword, value in pax_headers.iteritems(): |
| 1420 | if keyword not in PAX_FIELDS: |
| 1421 | continue |
| 1422 | |
| 1423 | if keyword == "path": |
| 1424 | value = value.rstrip("/") |
| 1425 | |
| 1426 | if keyword in PAX_NUMBER_FIELDS: |
| 1427 | try: |
| 1428 | value = PAX_NUMBER_FIELDS[keyword](value) |
| 1429 | except ValueError: |
| 1430 | value = 0 |
| 1431 | else: |
| 1432 | value = uts(value, encoding, errors) |
| 1433 | |
| 1434 | setattr(self, keyword, value) |
| 1435 | |
| 1436 | self.pax_headers = pax_headers.copy() |
Lars Gustäbel | c64e402 | 2007-03-13 10:47:19 +0000 | [diff] [blame] | 1437 | |
| 1438 | def _block(self, count): |
| 1439 | """Round up a byte count by BLOCKSIZE and return it, |
| 1440 | e.g. _block(834) => 1024. |
| 1441 | """ |
| 1442 | blocks, remainder = divmod(count, BLOCKSIZE) |
| 1443 | if remainder: |
| 1444 | blocks += 1 |
| 1445 | return blocks * BLOCKSIZE |
Georg Brandl | 3354f28 | 2006-10-29 09:16:12 +0000 | [diff] [blame] | 1446 | |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 1447 | def isreg(self): |
| 1448 | return self.type in REGULAR_TYPES |
| 1449 | def isfile(self): |
| 1450 | return self.isreg() |
| 1451 | def isdir(self): |
| 1452 | return self.type == DIRTYPE |
| 1453 | def issym(self): |
| 1454 | return self.type == SYMTYPE |
| 1455 | def islnk(self): |
| 1456 | return self.type == LNKTYPE |
| 1457 | def ischr(self): |
| 1458 | return self.type == CHRTYPE |
| 1459 | def isblk(self): |
| 1460 | return self.type == BLKTYPE |
| 1461 | def isfifo(self): |
| 1462 | return self.type == FIFOTYPE |
| 1463 | def issparse(self): |
| 1464 | return self.type == GNUTYPE_SPARSE |
| 1465 | def isdev(self): |
| 1466 | return self.type in (CHRTYPE, BLKTYPE, FIFOTYPE) |
| 1467 | # class TarInfo |
| 1468 | |
| 1469 | class TarFile(object): |
| 1470 | """The TarFile Class provides an interface to tar archives. |
| 1471 | """ |
| 1472 | |
| 1473 | debug = 0 # May be set from 0 (no msgs) to 3 (all msgs) |
| 1474 | |
| 1475 | dereference = False # If true, add content of linked file to the |
| 1476 | # tar file, else the link. |
| 1477 | |
| 1478 | ignore_zeros = False # If true, skips empty or invalid blocks and |
| 1479 | # continues processing. |
| 1480 | |
| 1481 | errorlevel = 0 # If 0, fatal errors only appear in debug |
| 1482 | # messages (if debug >= 0). If > 0, errors |
| 1483 | # are passed to the caller as exceptions. |
| 1484 | |
Lars Gustäbel | c64e402 | 2007-03-13 10:47:19 +0000 | [diff] [blame] | 1485 | format = DEFAULT_FORMAT # The format to use when creating an archive. |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 1486 | |
Lars Gustäbel | a0fcb93 | 2007-05-27 19:49:30 +0000 | [diff] [blame] | 1487 | encoding = ENCODING # Encoding for 8-bit character strings. |
| 1488 | |
| 1489 | errors = None # Error handler for unicode conversion. |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 1490 | |
Lars Gustäbel | c64e402 | 2007-03-13 10:47:19 +0000 | [diff] [blame] | 1491 | tarinfo = TarInfo # The default TarInfo class to use. |
| 1492 | |
| 1493 | fileobject = ExFileObject # The default ExFileObject class to use. |
| 1494 | |
| 1495 | def __init__(self, name=None, mode="r", fileobj=None, format=None, |
| 1496 | tarinfo=None, dereference=None, ignore_zeros=None, encoding=None, |
Lars Gustäbel | a0fcb93 | 2007-05-27 19:49:30 +0000 | [diff] [blame] | 1497 | errors=None, pax_headers=None, debug=None, errorlevel=None): |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 1498 | """Open an (uncompressed) tar archive `name'. `mode' is either 'r' to |
| 1499 | read from an existing archive, 'a' to append data to an existing |
| 1500 | file or 'w' to create a new file overwriting an existing one. `mode' |
| 1501 | defaults to 'r'. |
| 1502 | If `fileobj' is given, it is used for reading or writing data. If it |
| 1503 | can be determined, `mode' is overridden by `fileobj's mode. |
| 1504 | `fileobj' is not closed, when TarFile is closed. |
| 1505 | """ |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 1506 | if len(mode) > 1 or mode not in "raw": |
Georg Brandl | e4751e3 | 2006-05-18 06:11:19 +0000 | [diff] [blame] | 1507 | raise ValueError("mode must be 'r', 'a' or 'w'") |
Lars Gustäbel | c64e402 | 2007-03-13 10:47:19 +0000 | [diff] [blame] | 1508 | self.mode = mode |
| 1509 | self._mode = {"r": "rb", "a": "r+b", "w": "wb"}[mode] |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 1510 | |
| 1511 | if not fileobj: |
Lars Gustäbel | c64e402 | 2007-03-13 10:47:19 +0000 | [diff] [blame] | 1512 | if self.mode == "a" and not os.path.exists(name): |
Lars Gustäbel | 3f8aca1 | 2007-02-06 18:38:13 +0000 | [diff] [blame] | 1513 | # Create nonexistent files in append mode. |
Lars Gustäbel | c64e402 | 2007-03-13 10:47:19 +0000 | [diff] [blame] | 1514 | self.mode = "w" |
| 1515 | self._mode = "wb" |
Brett Cannon | 6cef076 | 2007-05-25 20:17:15 +0000 | [diff] [blame] | 1516 | fileobj = bltn_open(name, self._mode) |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 1517 | self._extfileobj = False |
| 1518 | else: |
Lars Gustäbel | c64e402 | 2007-03-13 10:47:19 +0000 | [diff] [blame] | 1519 | if name is None and hasattr(fileobj, "name"): |
| 1520 | name = fileobj.name |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 1521 | if hasattr(fileobj, "mode"): |
Lars Gustäbel | c64e402 | 2007-03-13 10:47:19 +0000 | [diff] [blame] | 1522 | self._mode = fileobj.mode |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 1523 | self._extfileobj = True |
Lars Gustäbel | 0f4a14b | 2007-08-28 12:31:09 +0000 | [diff] [blame] | 1524 | self.name = os.path.abspath(name) if name else None |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 1525 | self.fileobj = fileobj |
| 1526 | |
Lars Gustäbel | c64e402 | 2007-03-13 10:47:19 +0000 | [diff] [blame] | 1527 | # Init attributes. |
| 1528 | if format is not None: |
| 1529 | self.format = format |
| 1530 | if tarinfo is not None: |
| 1531 | self.tarinfo = tarinfo |
| 1532 | if dereference is not None: |
| 1533 | self.dereference = dereference |
| 1534 | if ignore_zeros is not None: |
| 1535 | self.ignore_zeros = ignore_zeros |
| 1536 | if encoding is not None: |
| 1537 | self.encoding = encoding |
Lars Gustäbel | a0fcb93 | 2007-05-27 19:49:30 +0000 | [diff] [blame] | 1538 | |
| 1539 | if errors is not None: |
| 1540 | self.errors = errors |
| 1541 | elif mode == "r": |
| 1542 | self.errors = "utf-8" |
| 1543 | else: |
| 1544 | self.errors = "strict" |
| 1545 | |
| 1546 | if pax_headers is not None and self.format == PAX_FORMAT: |
| 1547 | self.pax_headers = pax_headers |
| 1548 | else: |
| 1549 | self.pax_headers = {} |
| 1550 | |
Lars Gustäbel | c64e402 | 2007-03-13 10:47:19 +0000 | [diff] [blame] | 1551 | if debug is not None: |
| 1552 | self.debug = debug |
| 1553 | if errorlevel is not None: |
| 1554 | self.errorlevel = errorlevel |
| 1555 | |
| 1556 | # Init datastructures. |
Georg Brandl | 38c6a22 | 2006-05-10 16:26:03 +0000 | [diff] [blame] | 1557 | self.closed = False |
| 1558 | self.members = [] # list of members as TarInfo objects |
| 1559 | self._loaded = False # flag if all members have been read |
Lars Gustäbel | 77b2d63 | 2007-12-01 21:02:12 +0000 | [diff] [blame] | 1560 | self.offset = self.fileobj.tell() |
| 1561 | # current position in the archive file |
Georg Brandl | 38c6a22 | 2006-05-10 16:26:03 +0000 | [diff] [blame] | 1562 | self.inodes = {} # dictionary caching the inodes of |
| 1563 | # archive members already added |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 1564 | |
Lars Gustäbel | c64e402 | 2007-03-13 10:47:19 +0000 | [diff] [blame] | 1565 | if self.mode == "r": |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 1566 | self.firstmember = None |
| 1567 | self.firstmember = self.next() |
| 1568 | |
Lars Gustäbel | c64e402 | 2007-03-13 10:47:19 +0000 | [diff] [blame] | 1569 | if self.mode == "a": |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 1570 | # Move to the end of the archive, |
| 1571 | # before the first empty block. |
| 1572 | self.firstmember = None |
| 1573 | while True: |
Lars Gustäbel | c64e402 | 2007-03-13 10:47:19 +0000 | [diff] [blame] | 1574 | if self.next() is None: |
Lars Gustäbel | 3f8aca1 | 2007-02-06 18:38:13 +0000 | [diff] [blame] | 1575 | if self.offset > 0: |
| 1576 | self.fileobj.seek(- BLOCKSIZE, 1) |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 1577 | break |
| 1578 | |
Lars Gustäbel | c64e402 | 2007-03-13 10:47:19 +0000 | [diff] [blame] | 1579 | if self.mode in "aw": |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 1580 | self._loaded = True |
| 1581 | |
Lars Gustäbel | a0fcb93 | 2007-05-27 19:49:30 +0000 | [diff] [blame] | 1582 | if self.pax_headers: |
| 1583 | buf = self.tarinfo.create_pax_global_header(self.pax_headers.copy()) |
Lars Gustäbel | c64e402 | 2007-03-13 10:47:19 +0000 | [diff] [blame] | 1584 | self.fileobj.write(buf) |
| 1585 | self.offset += len(buf) |
| 1586 | |
| 1587 | def _getposix(self): |
| 1588 | return self.format == USTAR_FORMAT |
| 1589 | def _setposix(self, value): |
| 1590 | import warnings |
| 1591 | warnings.warn("use the format attribute instead", DeprecationWarning) |
| 1592 | if value: |
| 1593 | self.format = USTAR_FORMAT |
| 1594 | else: |
| 1595 | self.format = GNU_FORMAT |
| 1596 | posix = property(_getposix, _setposix) |
| 1597 | |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 1598 | #-------------------------------------------------------------------------- |
| 1599 | # Below are the classmethods which act as alternate constructors to the |
| 1600 | # TarFile class. The open() method is the only one that is needed for |
| 1601 | # public use; it is the "super"-constructor and is able to select an |
| 1602 | # adequate "sub"-constructor for a particular compression using the mapping |
| 1603 | # from OPEN_METH. |
| 1604 | # |
| 1605 | # This concept allows one to subclass TarFile without losing the comfort of |
| 1606 | # the super-constructor. A sub-constructor is registered and made available |
| 1607 | # by adding it to the mapping in OPEN_METH. |
| 1608 | |
Guido van Rossum | 75b64e6 | 2005-01-16 00:16:11 +0000 | [diff] [blame] | 1609 | @classmethod |
Lars Gustäbel | c64e402 | 2007-03-13 10:47:19 +0000 | [diff] [blame] | 1610 | def open(cls, name=None, mode="r", fileobj=None, bufsize=RECORDSIZE, **kwargs): |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 1611 | """Open a tar archive for reading, writing or appending. Return |
| 1612 | an appropriate TarFile class. |
| 1613 | |
| 1614 | mode: |
Martin v. Löwis | 78be7df | 2005-03-05 12:47:42 +0000 | [diff] [blame] | 1615 | 'r' or 'r:*' open for reading with transparent compression |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 1616 | 'r:' open for reading exclusively uncompressed |
| 1617 | 'r:gz' open for reading with gzip compression |
| 1618 | 'r:bz2' open for reading with bzip2 compression |
Lars Gustäbel | 3f8aca1 | 2007-02-06 18:38:13 +0000 | [diff] [blame] | 1619 | 'a' or 'a:' open for appending, creating the file if necessary |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 1620 | 'w' or 'w:' open for writing without compression |
| 1621 | 'w:gz' open for writing with gzip compression |
| 1622 | 'w:bz2' open for writing with bzip2 compression |
Martin v. Löwis | 78be7df | 2005-03-05 12:47:42 +0000 | [diff] [blame] | 1623 | |
| 1624 | 'r|*' open a stream of tar blocks with transparent compression |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 1625 | 'r|' open an uncompressed stream of tar blocks for reading |
| 1626 | 'r|gz' open a gzip compressed stream of tar blocks |
| 1627 | 'r|bz2' open a bzip2 compressed stream of tar blocks |
| 1628 | 'w|' open an uncompressed stream for writing |
| 1629 | 'w|gz' open a gzip compressed stream for writing |
| 1630 | 'w|bz2' open a bzip2 compressed stream for writing |
| 1631 | """ |
| 1632 | |
| 1633 | if not name and not fileobj: |
Georg Brandl | e4751e3 | 2006-05-18 06:11:19 +0000 | [diff] [blame] | 1634 | raise ValueError("nothing to open") |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 1635 | |
Martin v. Löwis | 78be7df | 2005-03-05 12:47:42 +0000 | [diff] [blame] | 1636 | if mode in ("r", "r:*"): |
| 1637 | # Find out which *open() is appropriate for opening the file. |
| 1638 | for comptype in cls.OPEN_METH: |
| 1639 | func = getattr(cls, cls.OPEN_METH[comptype]) |
Lars Gustäbel | a7ba6fc | 2006-12-27 10:30:46 +0000 | [diff] [blame] | 1640 | if fileobj is not None: |
| 1641 | saved_pos = fileobj.tell() |
Martin v. Löwis | 78be7df | 2005-03-05 12:47:42 +0000 | [diff] [blame] | 1642 | try: |
Lars Gustäbel | c64e402 | 2007-03-13 10:47:19 +0000 | [diff] [blame] | 1643 | return func(name, "r", fileobj, **kwargs) |
| 1644 | except (ReadError, CompressionError), e: |
Lars Gustäbel | a7ba6fc | 2006-12-27 10:30:46 +0000 | [diff] [blame] | 1645 | if fileobj is not None: |
| 1646 | fileobj.seek(saved_pos) |
Martin v. Löwis | 78be7df | 2005-03-05 12:47:42 +0000 | [diff] [blame] | 1647 | continue |
Georg Brandl | e4751e3 | 2006-05-18 06:11:19 +0000 | [diff] [blame] | 1648 | raise ReadError("file could not be opened successfully") |
Martin v. Löwis | 78be7df | 2005-03-05 12:47:42 +0000 | [diff] [blame] | 1649 | |
| 1650 | elif ":" in mode: |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 1651 | filemode, comptype = mode.split(":", 1) |
| 1652 | filemode = filemode or "r" |
| 1653 | comptype = comptype or "tar" |
| 1654 | |
| 1655 | # Select the *open() function according to |
| 1656 | # given compression. |
| 1657 | if comptype in cls.OPEN_METH: |
| 1658 | func = getattr(cls, cls.OPEN_METH[comptype]) |
| 1659 | else: |
Georg Brandl | e4751e3 | 2006-05-18 06:11:19 +0000 | [diff] [blame] | 1660 | raise CompressionError("unknown compression type %r" % comptype) |
Lars Gustäbel | c64e402 | 2007-03-13 10:47:19 +0000 | [diff] [blame] | 1661 | return func(name, filemode, fileobj, **kwargs) |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 1662 | |
| 1663 | elif "|" in mode: |
| 1664 | filemode, comptype = mode.split("|", 1) |
| 1665 | filemode = filemode or "r" |
| 1666 | comptype = comptype or "tar" |
| 1667 | |
| 1668 | if filemode not in "rw": |
Georg Brandl | e4751e3 | 2006-05-18 06:11:19 +0000 | [diff] [blame] | 1669 | raise ValueError("mode must be 'r' or 'w'") |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 1670 | |
| 1671 | t = cls(name, filemode, |
Lars Gustäbel | c64e402 | 2007-03-13 10:47:19 +0000 | [diff] [blame] | 1672 | _Stream(name, filemode, comptype, fileobj, bufsize), |
| 1673 | **kwargs) |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 1674 | t._extfileobj = False |
| 1675 | return t |
| 1676 | |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 1677 | elif mode in "aw": |
Lars Gustäbel | c64e402 | 2007-03-13 10:47:19 +0000 | [diff] [blame] | 1678 | return cls.taropen(name, mode, fileobj, **kwargs) |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 1679 | |
Georg Brandl | e4751e3 | 2006-05-18 06:11:19 +0000 | [diff] [blame] | 1680 | raise ValueError("undiscernible mode") |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 1681 | |
Guido van Rossum | 75b64e6 | 2005-01-16 00:16:11 +0000 | [diff] [blame] | 1682 | @classmethod |
Lars Gustäbel | c64e402 | 2007-03-13 10:47:19 +0000 | [diff] [blame] | 1683 | def taropen(cls, name, mode="r", fileobj=None, **kwargs): |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 1684 | """Open uncompressed tar archive name for reading or writing. |
| 1685 | """ |
| 1686 | if len(mode) > 1 or mode not in "raw": |
Georg Brandl | e4751e3 | 2006-05-18 06:11:19 +0000 | [diff] [blame] | 1687 | raise ValueError("mode must be 'r', 'a' or 'w'") |
Lars Gustäbel | c64e402 | 2007-03-13 10:47:19 +0000 | [diff] [blame] | 1688 | return cls(name, mode, fileobj, **kwargs) |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 1689 | |
Guido van Rossum | 75b64e6 | 2005-01-16 00:16:11 +0000 | [diff] [blame] | 1690 | @classmethod |
Lars Gustäbel | c64e402 | 2007-03-13 10:47:19 +0000 | [diff] [blame] | 1691 | def gzopen(cls, name, mode="r", fileobj=None, compresslevel=9, **kwargs): |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 1692 | """Open gzip compressed tar archive name for reading or writing. |
| 1693 | Appending is not allowed. |
| 1694 | """ |
| 1695 | if len(mode) > 1 or mode not in "rw": |
Georg Brandl | e4751e3 | 2006-05-18 06:11:19 +0000 | [diff] [blame] | 1696 | raise ValueError("mode must be 'r' or 'w'") |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 1697 | |
| 1698 | try: |
| 1699 | import gzip |
Neal Norwitz | 4ec6824 | 2003-04-11 03:05:56 +0000 | [diff] [blame] | 1700 | gzip.GzipFile |
| 1701 | except (ImportError, AttributeError): |
Georg Brandl | e4751e3 | 2006-05-18 06:11:19 +0000 | [diff] [blame] | 1702 | raise CompressionError("gzip module is not available") |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 1703 | |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 1704 | if fileobj is None: |
Brett Cannon | 6cef076 | 2007-05-25 20:17:15 +0000 | [diff] [blame] | 1705 | fileobj = bltn_open(name, mode + "b") |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 1706 | |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 1707 | try: |
Lars Gustäbel | a4b2381 | 2006-12-23 17:57:23 +0000 | [diff] [blame] | 1708 | t = cls.taropen(name, mode, |
Lars Gustäbel | c64e402 | 2007-03-13 10:47:19 +0000 | [diff] [blame] | 1709 | gzip.GzipFile(name, mode, compresslevel, fileobj), |
| 1710 | **kwargs) |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 1711 | except IOError: |
Georg Brandl | e4751e3 | 2006-05-18 06:11:19 +0000 | [diff] [blame] | 1712 | raise ReadError("not a gzip file") |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 1713 | t._extfileobj = False |
| 1714 | return t |
| 1715 | |
Guido van Rossum | 75b64e6 | 2005-01-16 00:16:11 +0000 | [diff] [blame] | 1716 | @classmethod |
Lars Gustäbel | c64e402 | 2007-03-13 10:47:19 +0000 | [diff] [blame] | 1717 | def bz2open(cls, name, mode="r", fileobj=None, compresslevel=9, **kwargs): |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 1718 | """Open bzip2 compressed tar archive name for reading or writing. |
| 1719 | Appending is not allowed. |
| 1720 | """ |
| 1721 | if len(mode) > 1 or mode not in "rw": |
Georg Brandl | e4751e3 | 2006-05-18 06:11:19 +0000 | [diff] [blame] | 1722 | raise ValueError("mode must be 'r' or 'w'.") |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 1723 | |
| 1724 | try: |
| 1725 | import bz2 |
| 1726 | except ImportError: |
Georg Brandl | e4751e3 | 2006-05-18 06:11:19 +0000 | [diff] [blame] | 1727 | raise CompressionError("bz2 module is not available") |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 1728 | |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 1729 | if fileobj is not None: |
Georg Brandl | 49c8f4c | 2006-05-15 19:30:35 +0000 | [diff] [blame] | 1730 | fileobj = _BZ2Proxy(fileobj, mode) |
| 1731 | else: |
| 1732 | fileobj = bz2.BZ2File(name, mode, compresslevel=compresslevel) |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 1733 | |
| 1734 | try: |
Lars Gustäbel | c64e402 | 2007-03-13 10:47:19 +0000 | [diff] [blame] | 1735 | t = cls.taropen(name, mode, fileobj, **kwargs) |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 1736 | except IOError: |
Georg Brandl | e4751e3 | 2006-05-18 06:11:19 +0000 | [diff] [blame] | 1737 | raise ReadError("not a bzip2 file") |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 1738 | t._extfileobj = False |
| 1739 | return t |
| 1740 | |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 1741 | # All *open() methods are registered here. |
| 1742 | OPEN_METH = { |
| 1743 | "tar": "taropen", # uncompressed tar |
| 1744 | "gz": "gzopen", # gzip compressed tar |
| 1745 | "bz2": "bz2open" # bzip2 compressed tar |
| 1746 | } |
| 1747 | |
| 1748 | #-------------------------------------------------------------------------- |
| 1749 | # The public methods which TarFile provides: |
| 1750 | |
| 1751 | def close(self): |
| 1752 | """Close the TarFile. In write-mode, two finishing zero blocks are |
| 1753 | appended to the archive. |
| 1754 | """ |
| 1755 | if self.closed: |
| 1756 | return |
| 1757 | |
Lars Gustäbel | c64e402 | 2007-03-13 10:47:19 +0000 | [diff] [blame] | 1758 | if self.mode in "aw": |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 1759 | self.fileobj.write(NUL * (BLOCKSIZE * 2)) |
| 1760 | self.offset += (BLOCKSIZE * 2) |
| 1761 | # fill up the end with zero-blocks |
| 1762 | # (like option -b20 for tar does) |
| 1763 | blocks, remainder = divmod(self.offset, RECORDSIZE) |
| 1764 | if remainder > 0: |
| 1765 | self.fileobj.write(NUL * (RECORDSIZE - remainder)) |
| 1766 | |
| 1767 | if not self._extfileobj: |
| 1768 | self.fileobj.close() |
| 1769 | self.closed = True |
| 1770 | |
| 1771 | def getmember(self, name): |
| 1772 | """Return a TarInfo object for member `name'. If `name' can not be |
| 1773 | found in the archive, KeyError is raised. If a member occurs more |
| 1774 | than once in the archive, its last occurence is assumed to be the |
| 1775 | most up-to-date version. |
| 1776 | """ |
Martin v. Löwis | f3c5611 | 2004-09-18 09:08:52 +0000 | [diff] [blame] | 1777 | tarinfo = self._getmember(name) |
| 1778 | if tarinfo is None: |
Georg Brandl | e4751e3 | 2006-05-18 06:11:19 +0000 | [diff] [blame] | 1779 | raise KeyError("filename %r not found" % name) |
Martin v. Löwis | f3c5611 | 2004-09-18 09:08:52 +0000 | [diff] [blame] | 1780 | return tarinfo |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 1781 | |
| 1782 | def getmembers(self): |
| 1783 | """Return the members of the archive as a list of TarInfo objects. The |
| 1784 | list has the same order as the members in the archive. |
| 1785 | """ |
| 1786 | self._check() |
| 1787 | if not self._loaded: # if we want to obtain a list of |
| 1788 | self._load() # all members, we first have to |
| 1789 | # scan the whole archive. |
| 1790 | return self.members |
| 1791 | |
| 1792 | def getnames(self): |
| 1793 | """Return the members of the archive as a list of their names. It has |
| 1794 | the same order as the list returned by getmembers(). |
| 1795 | """ |
Martin v. Löwis | f3c5611 | 2004-09-18 09:08:52 +0000 | [diff] [blame] | 1796 | return [tarinfo.name for tarinfo in self.getmembers()] |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 1797 | |
| 1798 | def gettarinfo(self, name=None, arcname=None, fileobj=None): |
| 1799 | """Create a TarInfo object for either the file `name' or the file |
| 1800 | object `fileobj' (using os.fstat on its file descriptor). You can |
| 1801 | modify some of the TarInfo's attributes before you add it using |
| 1802 | addfile(). If given, `arcname' specifies an alternative name for the |
| 1803 | file in the archive. |
| 1804 | """ |
| 1805 | self._check("aw") |
| 1806 | |
| 1807 | # When fileobj is given, replace name by |
| 1808 | # fileobj's real name. |
| 1809 | if fileobj is not None: |
| 1810 | name = fileobj.name |
| 1811 | |
| 1812 | # Building the name of the member in the archive. |
| 1813 | # Backward slashes are converted to forward slashes, |
| 1814 | # Absolute paths are turned to relative paths. |
| 1815 | if arcname is None: |
| 1816 | arcname = name |
| 1817 | arcname = normpath(arcname) |
| 1818 | drv, arcname = os.path.splitdrive(arcname) |
| 1819 | while arcname[0:1] == "/": |
| 1820 | arcname = arcname[1:] |
| 1821 | |
| 1822 | # Now, fill the TarInfo object with |
| 1823 | # information specific for the file. |
Lars Gustäbel | c64e402 | 2007-03-13 10:47:19 +0000 | [diff] [blame] | 1824 | tarinfo = self.tarinfo() |
| 1825 | tarinfo.tarfile = self |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 1826 | |
| 1827 | # Use os.stat or os.lstat, depending on platform |
| 1828 | # and if symlinks shall be resolved. |
| 1829 | if fileobj is None: |
| 1830 | if hasattr(os, "lstat") and not self.dereference: |
| 1831 | statres = os.lstat(name) |
| 1832 | else: |
| 1833 | statres = os.stat(name) |
| 1834 | else: |
| 1835 | statres = os.fstat(fileobj.fileno()) |
| 1836 | linkname = "" |
| 1837 | |
| 1838 | stmd = statres.st_mode |
| 1839 | if stat.S_ISREG(stmd): |
| 1840 | inode = (statres.st_ino, statres.st_dev) |
Lars Gustäbel | c64e402 | 2007-03-13 10:47:19 +0000 | [diff] [blame] | 1841 | if not self.dereference and statres.st_nlink > 1 and \ |
| 1842 | inode in self.inodes and arcname != self.inodes[inode]: |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 1843 | # Is it a hardlink to an already |
| 1844 | # archived file? |
| 1845 | type = LNKTYPE |
| 1846 | linkname = self.inodes[inode] |
| 1847 | else: |
| 1848 | # The inode is added only if its valid. |
| 1849 | # For win32 it is always 0. |
| 1850 | type = REGTYPE |
| 1851 | if inode[0]: |
| 1852 | self.inodes[inode] = arcname |
| 1853 | elif stat.S_ISDIR(stmd): |
| 1854 | type = DIRTYPE |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 1855 | elif stat.S_ISFIFO(stmd): |
| 1856 | type = FIFOTYPE |
| 1857 | elif stat.S_ISLNK(stmd): |
| 1858 | type = SYMTYPE |
| 1859 | linkname = os.readlink(name) |
| 1860 | elif stat.S_ISCHR(stmd): |
| 1861 | type = CHRTYPE |
| 1862 | elif stat.S_ISBLK(stmd): |
| 1863 | type = BLKTYPE |
| 1864 | else: |
| 1865 | return None |
| 1866 | |
| 1867 | # Fill the TarInfo object with all |
| 1868 | # information we can get. |
Martin v. Löwis | 5dbdc59 | 2005-08-27 10:07:56 +0000 | [diff] [blame] | 1869 | tarinfo.name = arcname |
| 1870 | tarinfo.mode = stmd |
| 1871 | tarinfo.uid = statres.st_uid |
| 1872 | tarinfo.gid = statres.st_gid |
| 1873 | if stat.S_ISREG(stmd): |
Martin v. Löwis | 61d77e0 | 2004-08-20 06:35:46 +0000 | [diff] [blame] | 1874 | tarinfo.size = statres.st_size |
Martin v. Löwis | 5dbdc59 | 2005-08-27 10:07:56 +0000 | [diff] [blame] | 1875 | else: |
| 1876 | tarinfo.size = 0L |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 1877 | tarinfo.mtime = statres.st_mtime |
Martin v. Löwis | 5dbdc59 | 2005-08-27 10:07:56 +0000 | [diff] [blame] | 1878 | tarinfo.type = type |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 1879 | tarinfo.linkname = linkname |
| 1880 | if pwd: |
| 1881 | try: |
| 1882 | tarinfo.uname = pwd.getpwuid(tarinfo.uid)[0] |
| 1883 | except KeyError: |
| 1884 | pass |
| 1885 | if grp: |
| 1886 | try: |
| 1887 | tarinfo.gname = grp.getgrgid(tarinfo.gid)[0] |
| 1888 | except KeyError: |
| 1889 | pass |
| 1890 | |
| 1891 | if type in (CHRTYPE, BLKTYPE): |
| 1892 | if hasattr(os, "major") and hasattr(os, "minor"): |
| 1893 | tarinfo.devmajor = os.major(statres.st_rdev) |
| 1894 | tarinfo.devminor = os.minor(statres.st_rdev) |
| 1895 | return tarinfo |
| 1896 | |
| 1897 | def list(self, verbose=True): |
| 1898 | """Print a table of contents to sys.stdout. If `verbose' is False, only |
| 1899 | the names of the members are printed. If it is True, an `ls -l'-like |
| 1900 | output is produced. |
| 1901 | """ |
| 1902 | self._check() |
| 1903 | |
| 1904 | for tarinfo in self: |
| 1905 | if verbose: |
| 1906 | print filemode(tarinfo.mode), |
| 1907 | print "%s/%s" % (tarinfo.uname or tarinfo.uid, |
| 1908 | tarinfo.gname or tarinfo.gid), |
| 1909 | if tarinfo.ischr() or tarinfo.isblk(): |
| 1910 | print "%10s" % ("%d,%d" \ |
| 1911 | % (tarinfo.devmajor, tarinfo.devminor)), |
| 1912 | else: |
| 1913 | print "%10d" % tarinfo.size, |
| 1914 | print "%d-%02d-%02d %02d:%02d:%02d" \ |
| 1915 | % time.localtime(tarinfo.mtime)[:6], |
| 1916 | |
Lars Gustäbel | c64e402 | 2007-03-13 10:47:19 +0000 | [diff] [blame] | 1917 | print tarinfo.name + ("/" if tarinfo.isdir() else ""), |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 1918 | |
| 1919 | if verbose: |
| 1920 | if tarinfo.issym(): |
| 1921 | print "->", tarinfo.linkname, |
| 1922 | if tarinfo.islnk(): |
| 1923 | print "link to", tarinfo.linkname, |
| 1924 | print |
| 1925 | |
Lars Gustäbel | 104490e | 2007-06-18 11:42:11 +0000 | [diff] [blame] | 1926 | def add(self, name, arcname=None, recursive=True, exclude=None): |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 1927 | """Add the file `name' to the archive. `name' may be any type of file |
| 1928 | (directory, fifo, symbolic link, etc.). If given, `arcname' |
| 1929 | specifies an alternative name for the file in the archive. |
| 1930 | Directories are added recursively by default. This can be avoided by |
Lars Gustäbel | 104490e | 2007-06-18 11:42:11 +0000 | [diff] [blame] | 1931 | setting `recursive' to False. `exclude' is a function that should |
| 1932 | return True for each filename to be excluded. |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 1933 | """ |
| 1934 | self._check("aw") |
| 1935 | |
| 1936 | if arcname is None: |
| 1937 | arcname = name |
| 1938 | |
Lars Gustäbel | 104490e | 2007-06-18 11:42:11 +0000 | [diff] [blame] | 1939 | # Exclude pathnames. |
| 1940 | if exclude is not None and exclude(name): |
| 1941 | self._dbg(2, "tarfile: Excluded %r" % name) |
| 1942 | return |
| 1943 | |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 1944 | # Skip if somebody tries to archive the archive... |
Lars Gustäbel | a4b2381 | 2006-12-23 17:57:23 +0000 | [diff] [blame] | 1945 | if self.name is not None and os.path.abspath(name) == self.name: |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 1946 | self._dbg(2, "tarfile: Skipped %r" % name) |
| 1947 | return |
| 1948 | |
| 1949 | # Special case: The user wants to add the current |
| 1950 | # working directory. |
| 1951 | if name == ".": |
| 1952 | if recursive: |
| 1953 | if arcname == ".": |
| 1954 | arcname = "" |
Lars Gustäbel | c64e402 | 2007-03-13 10:47:19 +0000 | [diff] [blame] | 1955 | for f in os.listdir(name): |
Lars Gustäbel | 104490e | 2007-06-18 11:42:11 +0000 | [diff] [blame] | 1956 | self.add(f, os.path.join(arcname, f), recursive, exclude) |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 1957 | return |
| 1958 | |
| 1959 | self._dbg(1, name) |
| 1960 | |
| 1961 | # Create a TarInfo object from the file. |
| 1962 | tarinfo = self.gettarinfo(name, arcname) |
| 1963 | |
| 1964 | if tarinfo is None: |
| 1965 | self._dbg(1, "tarfile: Unsupported type %r" % name) |
| 1966 | return |
| 1967 | |
| 1968 | # Append the tar header and data to the archive. |
| 1969 | if tarinfo.isreg(): |
Brett Cannon | 6cef076 | 2007-05-25 20:17:15 +0000 | [diff] [blame] | 1970 | f = bltn_open(name, "rb") |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 1971 | self.addfile(tarinfo, f) |
| 1972 | f.close() |
| 1973 | |
Martin v. Löwis | 5dbdc59 | 2005-08-27 10:07:56 +0000 | [diff] [blame] | 1974 | elif tarinfo.isdir(): |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 1975 | self.addfile(tarinfo) |
| 1976 | if recursive: |
| 1977 | for f in os.listdir(name): |
Lars Gustäbel | 104490e | 2007-06-18 11:42:11 +0000 | [diff] [blame] | 1978 | self.add(os.path.join(name, f), os.path.join(arcname, f), recursive, exclude) |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 1979 | |
Martin v. Löwis | 5dbdc59 | 2005-08-27 10:07:56 +0000 | [diff] [blame] | 1980 | else: |
| 1981 | self.addfile(tarinfo) |
| 1982 | |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 1983 | def addfile(self, tarinfo, fileobj=None): |
| 1984 | """Add the TarInfo object `tarinfo' to the archive. If `fileobj' is |
| 1985 | given, tarinfo.size bytes are read from it and added to the archive. |
| 1986 | You can create TarInfo objects using gettarinfo(). |
| 1987 | On Windows platforms, `fileobj' should always be opened with mode |
| 1988 | 'rb' to avoid irritation about the file size. |
| 1989 | """ |
| 1990 | self._check("aw") |
| 1991 | |
Georg Brandl | 3354f28 | 2006-10-29 09:16:12 +0000 | [diff] [blame] | 1992 | tarinfo = copy.copy(tarinfo) |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 1993 | |
Lars Gustäbel | a0fcb93 | 2007-05-27 19:49:30 +0000 | [diff] [blame] | 1994 | buf = tarinfo.tobuf(self.format, self.encoding, self.errors) |
Georg Brandl | 3354f28 | 2006-10-29 09:16:12 +0000 | [diff] [blame] | 1995 | self.fileobj.write(buf) |
| 1996 | self.offset += len(buf) |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 1997 | |
| 1998 | # If there's data to follow, append it. |
| 1999 | if fileobj is not None: |
| 2000 | copyfileobj(fileobj, self.fileobj, tarinfo.size) |
| 2001 | blocks, remainder = divmod(tarinfo.size, BLOCKSIZE) |
| 2002 | if remainder > 0: |
| 2003 | self.fileobj.write(NUL * (BLOCKSIZE - remainder)) |
| 2004 | blocks += 1 |
| 2005 | self.offset += blocks * BLOCKSIZE |
| 2006 | |
Martin v. Löwis | f3c5611 | 2004-09-18 09:08:52 +0000 | [diff] [blame] | 2007 | self.members.append(tarinfo) |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 2008 | |
Martin v. Löwis | 00a73e7 | 2005-03-04 19:40:34 +0000 | [diff] [blame] | 2009 | def extractall(self, path=".", members=None): |
| 2010 | """Extract all members from the archive to the current working |
| 2011 | directory and set owner, modification time and permissions on |
| 2012 | directories afterwards. `path' specifies a different directory |
| 2013 | to extract to. `members' is optional and must be a subset of the |
| 2014 | list returned by getmembers(). |
| 2015 | """ |
| 2016 | directories = [] |
| 2017 | |
| 2018 | if members is None: |
| 2019 | members = self |
| 2020 | |
| 2021 | for tarinfo in members: |
| 2022 | if tarinfo.isdir(): |
Lars Gustäbel | 0192e43 | 2008-02-05 11:51:40 +0000 | [diff] [blame] | 2023 | # Extract directories with a safe mode. |
Martin v. Löwis | 00a73e7 | 2005-03-04 19:40:34 +0000 | [diff] [blame] | 2024 | directories.append(tarinfo) |
Lars Gustäbel | 0192e43 | 2008-02-05 11:51:40 +0000 | [diff] [blame] | 2025 | tarinfo = copy.copy(tarinfo) |
| 2026 | tarinfo.mode = 0700 |
| 2027 | self.extract(tarinfo, path) |
Martin v. Löwis | 00a73e7 | 2005-03-04 19:40:34 +0000 | [diff] [blame] | 2028 | |
| 2029 | # Reverse sort directories. |
| 2030 | directories.sort(lambda a, b: cmp(a.name, b.name)) |
| 2031 | directories.reverse() |
| 2032 | |
| 2033 | # Set correct owner, mtime and filemode on directories. |
| 2034 | for tarinfo in directories: |
Lars Gustäbel | 2ee1c76 | 2008-01-04 14:00:33 +0000 | [diff] [blame] | 2035 | dirpath = os.path.join(path, tarinfo.name) |
Martin v. Löwis | 00a73e7 | 2005-03-04 19:40:34 +0000 | [diff] [blame] | 2036 | try: |
Lars Gustäbel | 2ee1c76 | 2008-01-04 14:00:33 +0000 | [diff] [blame] | 2037 | self.chown(tarinfo, dirpath) |
| 2038 | self.utime(tarinfo, dirpath) |
| 2039 | self.chmod(tarinfo, dirpath) |
Martin v. Löwis | 00a73e7 | 2005-03-04 19:40:34 +0000 | [diff] [blame] | 2040 | except ExtractError, e: |
| 2041 | if self.errorlevel > 1: |
| 2042 | raise |
| 2043 | else: |
| 2044 | self._dbg(1, "tarfile: %s" % e) |
| 2045 | |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 2046 | def extract(self, member, path=""): |
| 2047 | """Extract a member from the archive to the current working directory, |
| 2048 | using its full name. Its file information is extracted as accurately |
| 2049 | as possible. `member' may be a filename or a TarInfo object. You can |
| 2050 | specify a different directory using `path'. |
| 2051 | """ |
| 2052 | self._check("r") |
| 2053 | |
Lars Gustäbel | c64e402 | 2007-03-13 10:47:19 +0000 | [diff] [blame] | 2054 | if isinstance(member, basestring): |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 2055 | tarinfo = self.getmember(member) |
Lars Gustäbel | c64e402 | 2007-03-13 10:47:19 +0000 | [diff] [blame] | 2056 | else: |
| 2057 | tarinfo = member |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 2058 | |
Neal Norwitz | a4f651a | 2004-07-20 22:07:44 +0000 | [diff] [blame] | 2059 | # Prepare the link target for makelink(). |
| 2060 | if tarinfo.islnk(): |
| 2061 | tarinfo._link_target = os.path.join(path, tarinfo.linkname) |
| 2062 | |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 2063 | try: |
| 2064 | self._extract_member(tarinfo, os.path.join(path, tarinfo.name)) |
| 2065 | except EnvironmentError, e: |
| 2066 | if self.errorlevel > 0: |
| 2067 | raise |
| 2068 | else: |
| 2069 | if e.filename is None: |
| 2070 | self._dbg(1, "tarfile: %s" % e.strerror) |
| 2071 | else: |
| 2072 | self._dbg(1, "tarfile: %s %r" % (e.strerror, e.filename)) |
| 2073 | except ExtractError, e: |
| 2074 | if self.errorlevel > 1: |
| 2075 | raise |
| 2076 | else: |
| 2077 | self._dbg(1, "tarfile: %s" % e) |
| 2078 | |
| 2079 | def extractfile(self, member): |
| 2080 | """Extract a member from the archive as a file object. `member' may be |
| 2081 | a filename or a TarInfo object. If `member' is a regular file, a |
| 2082 | file-like object is returned. If `member' is a link, a file-like |
| 2083 | object is constructed from the link's target. If `member' is none of |
| 2084 | the above, None is returned. |
| 2085 | The file-like object is read-only and provides the following |
| 2086 | methods: read(), readline(), readlines(), seek() and tell() |
| 2087 | """ |
| 2088 | self._check("r") |
| 2089 | |
Lars Gustäbel | c64e402 | 2007-03-13 10:47:19 +0000 | [diff] [blame] | 2090 | if isinstance(member, basestring): |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 2091 | tarinfo = self.getmember(member) |
Lars Gustäbel | c64e402 | 2007-03-13 10:47:19 +0000 | [diff] [blame] | 2092 | else: |
| 2093 | tarinfo = member |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 2094 | |
| 2095 | if tarinfo.isreg(): |
| 2096 | return self.fileobject(self, tarinfo) |
| 2097 | |
| 2098 | elif tarinfo.type not in SUPPORTED_TYPES: |
| 2099 | # If a member's type is unknown, it is treated as a |
| 2100 | # regular file. |
| 2101 | return self.fileobject(self, tarinfo) |
| 2102 | |
| 2103 | elif tarinfo.islnk() or tarinfo.issym(): |
| 2104 | if isinstance(self.fileobj, _Stream): |
| 2105 | # A small but ugly workaround for the case that someone tries |
| 2106 | # to extract a (sym)link as a file-object from a non-seekable |
| 2107 | # stream of tar blocks. |
Georg Brandl | e4751e3 | 2006-05-18 06:11:19 +0000 | [diff] [blame] | 2108 | raise StreamError("cannot extract (sym)link as file object") |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 2109 | else: |
Georg Brandl | 7eb4b7d | 2005-07-22 21:49:32 +0000 | [diff] [blame] | 2110 | # A (sym)link's file object is its target's file object. |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 2111 | return self.extractfile(self._getmember(tarinfo.linkname, |
| 2112 | tarinfo)) |
| 2113 | else: |
| 2114 | # If there's no data associated with the member (directory, chrdev, |
| 2115 | # blkdev, etc.), return None instead of a file object. |
| 2116 | return None |
| 2117 | |
| 2118 | def _extract_member(self, tarinfo, targetpath): |
| 2119 | """Extract the TarInfo object tarinfo to a physical |
| 2120 | file called targetpath. |
| 2121 | """ |
| 2122 | # Fetch the TarInfo object for the given name |
| 2123 | # and build the destination pathname, replacing |
| 2124 | # forward slashes to platform specific separators. |
| 2125 | if targetpath[-1:] == "/": |
| 2126 | targetpath = targetpath[:-1] |
| 2127 | targetpath = os.path.normpath(targetpath) |
| 2128 | |
| 2129 | # Create all upper directories. |
| 2130 | upperdirs = os.path.dirname(targetpath) |
| 2131 | if upperdirs and not os.path.exists(upperdirs): |
Lars Gustäbel | 0192e43 | 2008-02-05 11:51:40 +0000 | [diff] [blame] | 2132 | # Create directories that are not part of the archive with |
| 2133 | # default permissions. |
Lars Gustäbel | d2e2290 | 2007-01-23 11:17:33 +0000 | [diff] [blame] | 2134 | os.makedirs(upperdirs) |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 2135 | |
| 2136 | if tarinfo.islnk() or tarinfo.issym(): |
| 2137 | self._dbg(1, "%s -> %s" % (tarinfo.name, tarinfo.linkname)) |
| 2138 | else: |
| 2139 | self._dbg(1, tarinfo.name) |
| 2140 | |
| 2141 | if tarinfo.isreg(): |
| 2142 | self.makefile(tarinfo, targetpath) |
| 2143 | elif tarinfo.isdir(): |
| 2144 | self.makedir(tarinfo, targetpath) |
| 2145 | elif tarinfo.isfifo(): |
| 2146 | self.makefifo(tarinfo, targetpath) |
| 2147 | elif tarinfo.ischr() or tarinfo.isblk(): |
| 2148 | self.makedev(tarinfo, targetpath) |
| 2149 | elif tarinfo.islnk() or tarinfo.issym(): |
| 2150 | self.makelink(tarinfo, targetpath) |
| 2151 | elif tarinfo.type not in SUPPORTED_TYPES: |
| 2152 | self.makeunknown(tarinfo, targetpath) |
| 2153 | else: |
| 2154 | self.makefile(tarinfo, targetpath) |
| 2155 | |
| 2156 | self.chown(tarinfo, targetpath) |
| 2157 | if not tarinfo.issym(): |
| 2158 | self.chmod(tarinfo, targetpath) |
| 2159 | self.utime(tarinfo, targetpath) |
| 2160 | |
| 2161 | #-------------------------------------------------------------------------- |
| 2162 | # Below are the different file methods. They are called via |
| 2163 | # _extract_member() when extract() is called. They can be replaced in a |
| 2164 | # subclass to implement other functionality. |
| 2165 | |
| 2166 | def makedir(self, tarinfo, targetpath): |
| 2167 | """Make a directory called targetpath. |
| 2168 | """ |
| 2169 | try: |
Lars Gustäbel | 0192e43 | 2008-02-05 11:51:40 +0000 | [diff] [blame] | 2170 | # Use a safe mode for the directory, the real mode is set |
| 2171 | # later in _extract_member(). |
| 2172 | os.mkdir(targetpath, 0700) |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 2173 | except EnvironmentError, e: |
| 2174 | if e.errno != errno.EEXIST: |
| 2175 | raise |
| 2176 | |
| 2177 | def makefile(self, tarinfo, targetpath): |
| 2178 | """Make a file called targetpath. |
| 2179 | """ |
| 2180 | source = self.extractfile(tarinfo) |
Brett Cannon | 6cef076 | 2007-05-25 20:17:15 +0000 | [diff] [blame] | 2181 | target = bltn_open(targetpath, "wb") |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 2182 | copyfileobj(source, target) |
| 2183 | source.close() |
| 2184 | target.close() |
| 2185 | |
| 2186 | def makeunknown(self, tarinfo, targetpath): |
| 2187 | """Make a file from a TarInfo object with an unknown type |
| 2188 | at targetpath. |
| 2189 | """ |
| 2190 | self.makefile(tarinfo, targetpath) |
| 2191 | self._dbg(1, "tarfile: Unknown file type %r, " \ |
| 2192 | "extracted as regular file." % tarinfo.type) |
| 2193 | |
| 2194 | def makefifo(self, tarinfo, targetpath): |
| 2195 | """Make a fifo called targetpath. |
| 2196 | """ |
| 2197 | if hasattr(os, "mkfifo"): |
| 2198 | os.mkfifo(targetpath) |
| 2199 | else: |
Georg Brandl | e4751e3 | 2006-05-18 06:11:19 +0000 | [diff] [blame] | 2200 | raise ExtractError("fifo not supported by system") |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 2201 | |
| 2202 | def makedev(self, tarinfo, targetpath): |
| 2203 | """Make a character or block device called targetpath. |
| 2204 | """ |
| 2205 | if not hasattr(os, "mknod") or not hasattr(os, "makedev"): |
Georg Brandl | e4751e3 | 2006-05-18 06:11:19 +0000 | [diff] [blame] | 2206 | raise ExtractError("special devices not supported by system") |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 2207 | |
| 2208 | mode = tarinfo.mode |
| 2209 | if tarinfo.isblk(): |
| 2210 | mode |= stat.S_IFBLK |
| 2211 | else: |
| 2212 | mode |= stat.S_IFCHR |
| 2213 | |
| 2214 | os.mknod(targetpath, mode, |
| 2215 | os.makedev(tarinfo.devmajor, tarinfo.devminor)) |
| 2216 | |
| 2217 | def makelink(self, tarinfo, targetpath): |
| 2218 | """Make a (symbolic) link called targetpath. If it cannot be created |
| 2219 | (platform limitation), we try to make a copy of the referenced file |
| 2220 | instead of a link. |
| 2221 | """ |
| 2222 | linkpath = tarinfo.linkname |
| 2223 | try: |
| 2224 | if tarinfo.issym(): |
| 2225 | os.symlink(linkpath, targetpath) |
| 2226 | else: |
Neal Norwitz | a4f651a | 2004-07-20 22:07:44 +0000 | [diff] [blame] | 2227 | # See extract(). |
| 2228 | os.link(tarinfo._link_target, targetpath) |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 2229 | except AttributeError: |
| 2230 | if tarinfo.issym(): |
| 2231 | linkpath = os.path.join(os.path.dirname(tarinfo.name), |
| 2232 | linkpath) |
| 2233 | linkpath = normpath(linkpath) |
| 2234 | |
| 2235 | try: |
| 2236 | self._extract_member(self.getmember(linkpath), targetpath) |
| 2237 | except (EnvironmentError, KeyError), e: |
| 2238 | linkpath = os.path.normpath(linkpath) |
| 2239 | try: |
| 2240 | shutil.copy2(linkpath, targetpath) |
| 2241 | except EnvironmentError, e: |
Georg Brandl | e4751e3 | 2006-05-18 06:11:19 +0000 | [diff] [blame] | 2242 | raise IOError("link could not be created") |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 2243 | |
| 2244 | def chown(self, tarinfo, targetpath): |
| 2245 | """Set owner of targetpath according to tarinfo. |
| 2246 | """ |
| 2247 | if pwd and hasattr(os, "geteuid") and os.geteuid() == 0: |
| 2248 | # We have to be root to do so. |
| 2249 | try: |
| 2250 | g = grp.getgrnam(tarinfo.gname)[2] |
| 2251 | except KeyError: |
| 2252 | try: |
| 2253 | g = grp.getgrgid(tarinfo.gid)[2] |
| 2254 | except KeyError: |
| 2255 | g = os.getgid() |
| 2256 | try: |
| 2257 | u = pwd.getpwnam(tarinfo.uname)[2] |
| 2258 | except KeyError: |
| 2259 | try: |
| 2260 | u = pwd.getpwuid(tarinfo.uid)[2] |
| 2261 | except KeyError: |
| 2262 | u = os.getuid() |
| 2263 | try: |
| 2264 | if tarinfo.issym() and hasattr(os, "lchown"): |
| 2265 | os.lchown(targetpath, u, g) |
| 2266 | else: |
Andrew MacIntyre | 7970d20 | 2003-02-19 12:51:34 +0000 | [diff] [blame] | 2267 | if sys.platform != "os2emx": |
| 2268 | os.chown(targetpath, u, g) |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 2269 | except EnvironmentError, e: |
Georg Brandl | e4751e3 | 2006-05-18 06:11:19 +0000 | [diff] [blame] | 2270 | raise ExtractError("could not change owner") |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 2271 | |
| 2272 | def chmod(self, tarinfo, targetpath): |
| 2273 | """Set file permissions of targetpath according to tarinfo. |
| 2274 | """ |
Jack Jansen | 834eff6 | 2003-03-07 12:47:06 +0000 | [diff] [blame] | 2275 | if hasattr(os, 'chmod'): |
| 2276 | try: |
| 2277 | os.chmod(targetpath, tarinfo.mode) |
| 2278 | except EnvironmentError, e: |
Georg Brandl | e4751e3 | 2006-05-18 06:11:19 +0000 | [diff] [blame] | 2279 | raise ExtractError("could not change mode") |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 2280 | |
| 2281 | def utime(self, tarinfo, targetpath): |
| 2282 | """Set modification time of targetpath according to tarinfo. |
| 2283 | """ |
Jack Jansen | 834eff6 | 2003-03-07 12:47:06 +0000 | [diff] [blame] | 2284 | if not hasattr(os, 'utime'): |
Tim Peters | f934778 | 2003-03-07 15:36:41 +0000 | [diff] [blame] | 2285 | return |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 2286 | if sys.platform == "win32" and tarinfo.isdir(): |
| 2287 | # According to msdn.microsoft.com, it is an error (EACCES) |
| 2288 | # to use utime() on directories. |
| 2289 | return |
| 2290 | try: |
| 2291 | os.utime(targetpath, (tarinfo.mtime, tarinfo.mtime)) |
| 2292 | except EnvironmentError, e: |
Georg Brandl | e4751e3 | 2006-05-18 06:11:19 +0000 | [diff] [blame] | 2293 | raise ExtractError("could not change modification time") |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 2294 | |
| 2295 | #-------------------------------------------------------------------------- |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 2296 | def next(self): |
| 2297 | """Return the next member of the archive as a TarInfo object, when |
| 2298 | TarFile is opened for reading. Return None if there is no more |
| 2299 | available. |
| 2300 | """ |
| 2301 | self._check("ra") |
| 2302 | if self.firstmember is not None: |
| 2303 | m = self.firstmember |
| 2304 | self.firstmember = None |
| 2305 | return m |
| 2306 | |
| 2307 | # Read the next block. |
Andrew M. Kuchling | 864bba1 | 2004-07-10 22:02:11 +0000 | [diff] [blame] | 2308 | self.fileobj.seek(self.offset) |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 2309 | while True: |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 2310 | try: |
Lars Gustäbel | c64e402 | 2007-03-13 10:47:19 +0000 | [diff] [blame] | 2311 | tarinfo = self.tarinfo.fromtarfile(self) |
| 2312 | if tarinfo is None: |
| 2313 | return |
| 2314 | self.members.append(tarinfo) |
Georg Brandl | 38c6a22 | 2006-05-10 16:26:03 +0000 | [diff] [blame] | 2315 | |
Georg Brandl | ebbeed7 | 2006-12-19 22:06:46 +0000 | [diff] [blame] | 2316 | except HeaderError, e: |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 2317 | if self.ignore_zeros: |
Georg Brandl | ebbeed7 | 2006-12-19 22:06:46 +0000 | [diff] [blame] | 2318 | self._dbg(2, "0x%X: %s" % (self.offset, e)) |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 2319 | self.offset += BLOCKSIZE |
| 2320 | continue |
| 2321 | else: |
Andrew M. Kuchling | 864bba1 | 2004-07-10 22:02:11 +0000 | [diff] [blame] | 2322 | if self.offset == 0: |
Georg Brandl | ebbeed7 | 2006-12-19 22:06:46 +0000 | [diff] [blame] | 2323 | raise ReadError(str(e)) |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 2324 | return None |
| 2325 | break |
| 2326 | |
Georg Brandl | 38c6a22 | 2006-05-10 16:26:03 +0000 | [diff] [blame] | 2327 | return tarinfo |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 2328 | |
| 2329 | #-------------------------------------------------------------------------- |
| 2330 | # Little helper methods: |
| 2331 | |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 2332 | def _getmember(self, name, tarinfo=None): |
| 2333 | """Find an archive member by name from bottom to top. |
| 2334 | If tarinfo is given, it is used as the starting point. |
| 2335 | """ |
Martin v. Löwis | f3c5611 | 2004-09-18 09:08:52 +0000 | [diff] [blame] | 2336 | # Ensure that all members have been loaded. |
| 2337 | members = self.getmembers() |
| 2338 | |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 2339 | if tarinfo is None: |
Martin v. Löwis | f3c5611 | 2004-09-18 09:08:52 +0000 | [diff] [blame] | 2340 | end = len(members) |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 2341 | else: |
Martin v. Löwis | f3c5611 | 2004-09-18 09:08:52 +0000 | [diff] [blame] | 2342 | end = members.index(tarinfo) |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 2343 | |
| 2344 | for i in xrange(end - 1, -1, -1): |
Martin v. Löwis | f3c5611 | 2004-09-18 09:08:52 +0000 | [diff] [blame] | 2345 | if name == members[i].name: |
| 2346 | return members[i] |
Andrew M. Kuchling | 864bba1 | 2004-07-10 22:02:11 +0000 | [diff] [blame] | 2347 | |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 2348 | def _load(self): |
| 2349 | """Read through the entire archive file and look for readable |
| 2350 | members. |
| 2351 | """ |
| 2352 | while True: |
| 2353 | tarinfo = self.next() |
| 2354 | if tarinfo is None: |
| 2355 | break |
| 2356 | self._loaded = True |
| 2357 | |
| 2358 | def _check(self, mode=None): |
| 2359 | """Check if TarFile is still open, and if the operation's mode |
| 2360 | corresponds to TarFile's mode. |
| 2361 | """ |
| 2362 | if self.closed: |
Georg Brandl | e4751e3 | 2006-05-18 06:11:19 +0000 | [diff] [blame] | 2363 | raise IOError("%s is closed" % self.__class__.__name__) |
Lars Gustäbel | c64e402 | 2007-03-13 10:47:19 +0000 | [diff] [blame] | 2364 | if mode is not None and self.mode not in mode: |
| 2365 | raise IOError("bad operation for mode %r" % self.mode) |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 2366 | |
| 2367 | def __iter__(self): |
| 2368 | """Provide an iterator object. |
| 2369 | """ |
| 2370 | if self._loaded: |
| 2371 | return iter(self.members) |
| 2372 | else: |
| 2373 | return TarIter(self) |
| 2374 | |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 2375 | def _dbg(self, level, msg): |
| 2376 | """Write debugging output to sys.stderr. |
| 2377 | """ |
| 2378 | if level <= self.debug: |
| 2379 | print >> sys.stderr, msg |
| 2380 | # class TarFile |
| 2381 | |
| 2382 | class TarIter: |
| 2383 | """Iterator Class. |
| 2384 | |
| 2385 | for tarinfo in TarFile(...): |
| 2386 | suite... |
| 2387 | """ |
| 2388 | |
| 2389 | def __init__(self, tarfile): |
| 2390 | """Construct a TarIter object. |
| 2391 | """ |
| 2392 | self.tarfile = tarfile |
Martin v. Löwis | 637431b | 2005-03-03 23:12:42 +0000 | [diff] [blame] | 2393 | self.index = 0 |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 2394 | def __iter__(self): |
| 2395 | """Return iterator object. |
| 2396 | """ |
| 2397 | return self |
| 2398 | def next(self): |
| 2399 | """Return the next item using TarFile's next() method. |
| 2400 | When all members have been read, set TarFile as _loaded. |
| 2401 | """ |
Martin v. Löwis | 637431b | 2005-03-03 23:12:42 +0000 | [diff] [blame] | 2402 | # Fix for SF #1100429: Under rare circumstances it can |
| 2403 | # happen that getmembers() is called during iteration, |
| 2404 | # which will cause TarIter to stop prematurely. |
| 2405 | if not self.tarfile._loaded: |
| 2406 | tarinfo = self.tarfile.next() |
| 2407 | if not tarinfo: |
| 2408 | self.tarfile._loaded = True |
| 2409 | raise StopIteration |
| 2410 | else: |
| 2411 | try: |
| 2412 | tarinfo = self.tarfile.members[self.index] |
| 2413 | except IndexError: |
| 2414 | raise StopIteration |
| 2415 | self.index += 1 |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 2416 | return tarinfo |
| 2417 | |
| 2418 | # Helper classes for sparse file support |
| 2419 | class _section: |
| 2420 | """Base class for _data and _hole. |
| 2421 | """ |
| 2422 | def __init__(self, offset, size): |
| 2423 | self.offset = offset |
| 2424 | self.size = size |
| 2425 | def __contains__(self, offset): |
| 2426 | return self.offset <= offset < self.offset + self.size |
| 2427 | |
| 2428 | class _data(_section): |
| 2429 | """Represent a data section in a sparse file. |
| 2430 | """ |
| 2431 | def __init__(self, offset, size, realpos): |
| 2432 | _section.__init__(self, offset, size) |
| 2433 | self.realpos = realpos |
| 2434 | |
| 2435 | class _hole(_section): |
| 2436 | """Represent a hole section in a sparse file. |
| 2437 | """ |
| 2438 | pass |
| 2439 | |
| 2440 | class _ringbuffer(list): |
| 2441 | """Ringbuffer class which increases performance |
| 2442 | over a regular list. |
| 2443 | """ |
| 2444 | def __init__(self): |
| 2445 | self.idx = 0 |
| 2446 | def find(self, offset): |
| 2447 | idx = self.idx |
| 2448 | while True: |
| 2449 | item = self[idx] |
| 2450 | if offset in item: |
| 2451 | break |
| 2452 | idx += 1 |
| 2453 | if idx == len(self): |
| 2454 | idx = 0 |
| 2455 | if idx == self.idx: |
| 2456 | # End of File |
| 2457 | return None |
| 2458 | self.idx = idx |
| 2459 | return item |
| 2460 | |
| 2461 | #--------------------------------------------- |
| 2462 | # zipfile compatible TarFile class |
| 2463 | #--------------------------------------------- |
| 2464 | TAR_PLAIN = 0 # zipfile.ZIP_STORED |
| 2465 | TAR_GZIPPED = 8 # zipfile.ZIP_DEFLATED |
| 2466 | class TarFileCompat: |
| 2467 | """TarFile class compatible with standard module zipfile's |
| 2468 | ZipFile class. |
| 2469 | """ |
| 2470 | def __init__(self, file, mode="r", compression=TAR_PLAIN): |
| 2471 | if compression == TAR_PLAIN: |
| 2472 | self.tarfile = TarFile.taropen(file, mode) |
| 2473 | elif compression == TAR_GZIPPED: |
| 2474 | self.tarfile = TarFile.gzopen(file, mode) |
| 2475 | else: |
Georg Brandl | e4751e3 | 2006-05-18 06:11:19 +0000 | [diff] [blame] | 2476 | raise ValueError("unknown compression constant") |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 2477 | if mode[0:1] == "r": |
| 2478 | members = self.tarfile.getmembers() |
Raymond Hettinger | a1d09e2 | 2005-09-11 16:34:05 +0000 | [diff] [blame] | 2479 | for m in members: |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 2480 | m.filename = m.name |
| 2481 | m.file_size = m.size |
| 2482 | m.date_time = time.gmtime(m.mtime)[:6] |
| 2483 | def namelist(self): |
| 2484 | return map(lambda m: m.name, self.infolist()) |
| 2485 | def infolist(self): |
| 2486 | return filter(lambda m: m.type in REGULAR_TYPES, |
| 2487 | self.tarfile.getmembers()) |
| 2488 | def printdir(self): |
| 2489 | self.tarfile.list() |
| 2490 | def testzip(self): |
| 2491 | return |
| 2492 | def getinfo(self, name): |
| 2493 | return self.tarfile.getmember(name) |
| 2494 | def read(self, name): |
| 2495 | return self.tarfile.extractfile(self.tarfile.getmember(name)).read() |
| 2496 | def write(self, filename, arcname=None, compress_type=None): |
| 2497 | self.tarfile.add(filename, arcname) |
| 2498 | def writestr(self, zinfo, bytes): |
Raymond Hettinger | a617271 | 2004-12-31 19:15:26 +0000 | [diff] [blame] | 2499 | try: |
| 2500 | from cStringIO import StringIO |
| 2501 | except ImportError: |
| 2502 | from StringIO import StringIO |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 2503 | import calendar |
| 2504 | zinfo.name = zinfo.filename |
| 2505 | zinfo.size = zinfo.file_size |
| 2506 | zinfo.mtime = calendar.timegm(zinfo.date_time) |
Raymond Hettinger | a617271 | 2004-12-31 19:15:26 +0000 | [diff] [blame] | 2507 | self.tarfile.addfile(zinfo, StringIO(bytes)) |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 2508 | def close(self): |
| 2509 | self.tarfile.close() |
| 2510 | #class TarFileCompat |
| 2511 | |
| 2512 | #-------------------- |
| 2513 | # exported functions |
| 2514 | #-------------------- |
| 2515 | def is_tarfile(name): |
| 2516 | """Return True if name points to a tar archive that we |
| 2517 | are able to handle, else return False. |
| 2518 | """ |
| 2519 | try: |
| 2520 | t = open(name) |
| 2521 | t.close() |
| 2522 | return True |
| 2523 | except TarError: |
| 2524 | return False |
| 2525 | |
Brett Cannon | 6cef076 | 2007-05-25 20:17:15 +0000 | [diff] [blame] | 2526 | bltn_open = open |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 2527 | open = TarFile.open |