You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 

701 lines
25 KiB

  1. # Copyright (c) 2011, SmartFile <btimby@smartfile.com>
  2. # All rights reserved.
  3. #
  4. # Redistribution and use in source and binary forms, with or without
  5. # modification, are permitted provided that the following conditions are met:
  6. # * Redistributions of source code must retain the above copyright
  7. # notice, this list of conditions and the following disclaimer.
  8. # * Redistributions in binary form must reproduce the above copyright
  9. # notice, this list of conditions and the following disclaimer in the
  10. # documentation and/or other materials provided with the distribution.
  11. # * Neither the name of the organization nor the
  12. # names of its contributors may be used to endorse or promote products
  13. # derived from this software without specific prior written permission.
  14. #
  15. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
  16. # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  17. # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  18. # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY
  19. # DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  20. # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  21. # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  22. # ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  23. # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  24. # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  25. import os
  26. import stat
  27. import sys
  28. import time
  29. import warnings
  30. #from ctypes import cdll, c_char_p
  31. from libarchive import _libarchive
  32. from io import StringIO
  33. #PY3 = sys.version_info[0] == 3
  34. PY3 = True
  35. # Suggested block size for libarchive. Libarchive may adjust it.
  36. BLOCK_SIZE = 10240
  37. MTIME_FORMAT = ''
  38. # Default encoding scheme.
  39. ENCODING = 'utf-8'
  40. # Functions to initialize read/write for various libarchive supported formats and filters.
  41. FORMATS = {
  42. None: (_libarchive.archive_read_support_format_all, None),
  43. 'tar': (_libarchive.archive_read_support_format_tar, _libarchive.archive_write_set_format_ustar),
  44. 'pax': (_libarchive.archive_read_support_format_tar, _libarchive.archive_write_set_format_pax),
  45. 'gnu': (_libarchive.archive_read_support_format_gnutar, _libarchive.archive_write_set_format_gnutar),
  46. 'zip': (_libarchive.archive_read_support_format_zip, _libarchive.archive_write_set_format_zip),
  47. 'rar': (_libarchive.archive_read_support_format_rar, None),
  48. '7zip': (_libarchive.archive_read_support_format_7zip, None),
  49. 'ar': (_libarchive.archive_read_support_format_ar, None),
  50. 'cab': (_libarchive.archive_read_support_format_cab, None),
  51. 'cpio': (_libarchive.archive_read_support_format_cpio, _libarchive.archive_write_set_format_cpio_newc),
  52. 'iso': (_libarchive.archive_read_support_format_iso9660, _libarchive.archive_write_set_format_iso9660),
  53. 'lha': (_libarchive.archive_read_support_format_lha, None),
  54. 'xar': (_libarchive.archive_read_support_format_xar, _libarchive.archive_write_set_format_xar),
  55. }
  56. FILTERS = {
  57. None: (_libarchive.archive_read_support_filter_all, _libarchive.archive_write_add_filter_none),
  58. 'gz': (_libarchive.archive_read_support_filter_gzip, _libarchive.archive_write_add_filter_gzip),
  59. 'bz2': (_libarchive.archive_read_support_filter_bzip2, _libarchive.archive_write_add_filter_bzip2),
  60. }
  61. # Map file extensions to formats and filters. To support quick detection.
  62. FORMAT_EXTENSIONS = {
  63. '.tar': 'tar',
  64. '.zip': 'zip',
  65. '.rar': 'rar',
  66. '.7z': '7zip',
  67. '.ar': 'ar',
  68. '.cab': 'cab',
  69. '.rpm': 'cpio',
  70. '.cpio': 'cpio',
  71. '.iso': 'iso',
  72. '.lha': 'lha',
  73. '.xar': 'xar',
  74. }
  75. FILTER_EXTENSIONS = {
  76. '.gz': 'gz',
  77. '.bz2': 'bz2',
  78. }
  79. class EOF(Exception):
  80. '''Raised by ArchiveInfo.from_archive() when unable to read the next
  81. archive header.'''
  82. pass
  83. def get_error(archive):
  84. '''Retrieves the last error description for the given archive instance.'''
  85. return _libarchive.archive_error_string(archive)
  86. def call_and_check(func, archive, *args):
  87. '''Executes a libarchive function and raises an exception when appropriate.'''
  88. ret = func(*args)
  89. if ret == _libarchive.ARCHIVE_OK:
  90. return
  91. elif ret == _libarchive.ARCHIVE_WARN:
  92. warnings.warn('Warning executing function: %s.' % get_error(archive), RuntimeWarning)
  93. elif ret == _libarchive.ARCHIVE_EOF:
  94. raise EOF()
  95. else:
  96. raise Exception('Fatal error executing function, message is: %s.' % get_error(archive))
  97. def get_func(name, items, index):
  98. item = items.get(name, None)
  99. if item is None:
  100. return None
  101. return item[index]
  102. def guess_format(filename):
  103. if isinstance(filename, int):
  104. filename = ext = ''
  105. else:
  106. filename, ext = os.path.splitext(filename)
  107. filter = FILTER_EXTENSIONS.get(ext)
  108. if filter:
  109. filename, ext = os.path.splitext(filename)
  110. format = FORMAT_EXTENSIONS.get(ext)
  111. return format, filter
  112. def is_archive_name(filename, formats=None):
  113. '''Quick check to see if the given file has an extension indiciating that it is
  114. an archive. The format parameter can be used to limit what archive format is acceptable.
  115. If omitted, all supported archive formats will be checked.
  116. This function will return the name of the most likely archive format, None if the file is
  117. unlikely to be an archive.'''
  118. if formats is None:
  119. formats = list(FORMAT_EXTENSIONS.values())
  120. format, filter = guess_format(filename)
  121. if format in formats:
  122. return format
  123. def is_archive(f, formats=(None, ), filters=(None, )):
  124. '''Check to see if the given file is actually an archive. The format parameter
  125. can be used to specify which archive format is acceptable. If ommitted, all supported
  126. archive formats will be checked. It opens the file using libarchive. If no error is
  127. received, the file was successfully detected by the libarchive bidding process.
  128. This procedure is quite costly, so you should avoid calling it unless you are reasonably
  129. sure that the given file is an archive. In other words, you may wish to filter large
  130. numbers of file names using is_archive_name() before double-checking the positives with
  131. this function.
  132. This function will return True if the file can be opened as an archive using the given
  133. format(s)/filter(s).'''
  134. if isinstance(f, str):
  135. f = open(f, 'r')
  136. a = _libarchive.archive_read_new()
  137. for format in formats:
  138. format = get_func(format, FORMATS, 0)
  139. if format is None:
  140. return False
  141. format(a)
  142. for filter in filters:
  143. filter = get_func(filter, FILTERS, 0)
  144. if filter is None:
  145. return False
  146. filter(a)
  147. try:
  148. try:
  149. call_and_check(_libarchive.archive_read_open_fd, a, a, f.fileno(), BLOCK_SIZE)
  150. return True
  151. except:
  152. return False
  153. finally:
  154. _libarchive.archive_read_close(a)
  155. _libarchive.archive_read_free(a)
  156. f.close()
  157. class EntryReadStream(object):
  158. '''A file-like object for reading an entry from the archive.'''
  159. def __init__(self, archive, size):
  160. self.archive = archive
  161. self.closed = False
  162. self.size = size
  163. self.bytes = 0
  164. def __enter__(self):
  165. return self
  166. def __exit__(self, *args):
  167. return
  168. def __iter__(self):
  169. if self.closed:
  170. return
  171. while True:
  172. data = self.read(BLOCK_SIZE)
  173. if not data:
  174. break
  175. yield data
  176. def __len__(self):
  177. return self.size
  178. def tell(self):
  179. return self.bytes
  180. def read(self, bytes=-1):
  181. if self.closed:
  182. return
  183. if self.bytes == self.size:
  184. # EOF already reached.
  185. return
  186. if bytes < 0:
  187. bytes = self.size - self.bytes
  188. elif self.bytes + bytes > self.size:
  189. # Limit read to remaining bytes
  190. bytes = self.size - self.bytes
  191. # Read requested bytes
  192. data = _libarchive.archive_read_data_into_str(self.archive._a, bytes)
  193. self.bytes += len(data)
  194. return data
  195. def close(self):
  196. if self.closed:
  197. return
  198. # Call archive.close() with _defer True to let it know we have been
  199. # closed and it is now safe to actually close.
  200. self.archive.close(_defer=True)
  201. self.archive = None
  202. self.closed = True
  203. class EntryWriteStream(object):
  204. '''A file-like object for writing an entry to an archive.
  205. If the size is known ahead of time and provided, then the file contents
  206. are not buffered but flushed directly to the archive. If size is omitted,
  207. then the file contents are buffered and flushed in the close() method.'''
  208. def __init__(self, archive, pathname, size=None):
  209. self.archive = archive
  210. self.entry = Entry(pathname=pathname, mtime=time.time(), mode=stat.S_IFREG)
  211. if size is None:
  212. self.buffer = StringIO()
  213. else:
  214. self.buffer = None
  215. self.entry.size = size
  216. self.entry.to_archive(self.archive)
  217. self.bytes = 0
  218. self.closed = False
  219. def __enter__(self):
  220. return self
  221. def __exit__(self, *args):
  222. self.close()
  223. def __del__(self):
  224. self.close()
  225. def __len__(self):
  226. return self.bytes
  227. def tell(self):
  228. return self.bytes
  229. def write(self, data):
  230. if self.closed:
  231. raise Exception('Cannot write to closed stream.')
  232. if self.buffer:
  233. self.buffer.write(data)
  234. else:
  235. _libarchive.archive_write_data_from_str(self.archive._a, data.encode('utf-8'))
  236. self.bytes += len(data)
  237. def close(self):
  238. if self.closed:
  239. return
  240. if self.buffer:
  241. self.entry.size = self.buffer.tell()
  242. self.entry.to_archive(self.archive)
  243. _libarchive.archive_write_data_from_str(self.archive._a, self.buffer.getvalue().encode('utf-8'))
  244. _libarchive.archive_write_finish_entry(self.archive._a)
  245. # Call archive.close() with _defer True to let it know we have been
  246. # closed and it is now safe to actually close.
  247. self.archive.close(_defer=True)
  248. self.archive = None
  249. self.closed = True
  250. class Entry(object):
  251. '''An entry within an archive. Represents the header data and it's location within the archive.'''
  252. def __init__(self, pathname=None, size=None, mtime=None, mode=None, hpos=None, encoding=ENCODING):
  253. #, symlink=None
  254. self.pathname = pathname
  255. self.size = size
  256. self.mtime = mtime
  257. self.mode = mode
  258. self.hpos = hpos
  259. self.encoding = encoding
  260. self.symlink = ""
  261. #if self.issym() and symlink:
  262. # self.symlink = symlink
  263. #else:
  264. # self.symlink = None
  265. @property
  266. def header_position(self):
  267. return self.hpos
  268. @classmethod
  269. def from_archive(cls, archive, encoding=ENCODING):
  270. '''Instantiates an Entry class and sets all the properties from an archive header.'''
  271. e = _libarchive.archive_entry_new()
  272. try:
  273. call_and_check(_libarchive.archive_read_next_header2, archive._a, archive._a, e)
  274. mode = _libarchive.archive_entry_filetype(e)
  275. mode |= _libarchive.archive_entry_perm(e)
  276. if PY3:
  277. pathname = _libarchive.archive_entry_pathname(e)
  278. else:
  279. pathname = _libarchive.archive_entry_pathname(e).decode(encoding)
  280. entry = cls(
  281. pathname=pathname,
  282. size=_libarchive.archive_entry_size(e),
  283. mtime=_libarchive.archive_entry_mtime(e),
  284. mode=mode,
  285. hpos=archive.header_position,
  286. )
  287. if entry.issym():
  288. print("issym")
  289. symLinkPath = _libarchive.archive_entry_symlink(e)
  290. entry.symlink = symLinkPath
  291. print(symLinkPath)
  292. finally:
  293. _libarchive.archive_entry_free(e)
  294. return entry
  295. @classmethod
  296. def from_file(cls, f, entry=None, encoding=ENCODING):
  297. '''Instantiates an Entry class and sets all the properties from a file on the file system.
  298. f can be a file-like object or a path.'''
  299. if entry is None:
  300. entry = cls(encoding=encoding)
  301. if entry.pathname is None:
  302. if isinstance(f, str):
  303. st = os.stat(f)
  304. entry.pathname = f
  305. entry.size = st.st_size
  306. entry.mtime = st.st_mtime
  307. entry.mode = st.st_mode
  308. elif hasattr(f, 'fileno'):
  309. st = os.fstat(f.fileno())
  310. entry.pathname = getattr(f, 'name', None)
  311. entry.size = st.st_size
  312. entry.mtime = st.st_mtime
  313. entry.mode = st.st_mode
  314. else:
  315. entry.pathname = getattr(f, 'pathname', None)
  316. entry.size = getattr(f, 'size', 0)
  317. entry.mtime = getattr(f, 'mtime', time.time())
  318. entry.mode = stat.S_IFREG
  319. if stat.S_ISLNK(entry.mode):
  320. print("yo")
  321. return entry
  322. def to_archive(self, archive):
  323. '''Creates an archive header and writes it to the given archive.'''
  324. e = _libarchive.archive_entry_new()
  325. try:
  326. if PY3:
  327. _libarchive.archive_entry_set_pathname(e, self.pathname)
  328. else:
  329. _libarchive.archive_entry_set_pathname(e, self.pathname.encode(self.encoding))
  330. _libarchive.archive_entry_set_filetype(e, stat.S_IFMT(self.mode))
  331. _libarchive.archive_entry_set_perm(e, stat.S_IMODE(self.mode))
  332. _libarchive.archive_entry_set_size(e, self.size)
  333. _libarchive.archive_entry_set_mtime(e, self.mtime, 0)
  334. if stat.S_ISLNK(self.mode):
  335. _libarchive.archive_entry_set_symlink(e, self.symlink)
  336. call_and_check(_libarchive.archive_write_header, archive._a, archive._a, e)
  337. #todo
  338. #self.hpos = archive.header_position
  339. finally:
  340. _libarchive.archive_entry_free(e)
  341. def isdir(self):
  342. return stat.S_ISDIR(self.mode)
  343. def isfile(self):
  344. return stat.S_ISREG(self.mode)
  345. def issym(self):
  346. return stat.S_ISLNK(self.mode)
  347. def isfifo(self):
  348. return stat.S_ISFIFO(self.mode)
  349. def ischr(self):
  350. return stat.S_ISCHR(self.mode)
  351. def isblk(self):
  352. return stat.S_ISBLK(self.mode)
  353. class Archive(object):
  354. '''A low-level archive reader which provides forward-only iteration. Consider
  355. this a light-weight pythonic libarchive wrapper.'''
  356. def __init__(self, f, mode='r', format=None, filter=None, entry_class=Entry, encoding=ENCODING, blocksize=BLOCK_SIZE):
  357. assert mode in ('r', 'w', 'wb', 'a'), 'Mode should be "r", "w", "wb", or "a".'
  358. self._stream = None
  359. self.encoding = encoding
  360. self.blocksize = blocksize
  361. if isinstance(f, str):
  362. self.filename = f
  363. f = open(f, mode)
  364. # Only close it if we opened it...
  365. self._defer_close = True
  366. elif hasattr(f, 'fileno'):
  367. self.filename = getattr(f, 'name', None)
  368. # Leave the fd alone, caller should manage it...
  369. self._defer_close = False
  370. else:
  371. raise Exception('Provided file is not path or open file.')
  372. self.f = f
  373. self.mode = mode
  374. # Guess the format/filter from file name (if not provided)
  375. if self.filename:
  376. if format is None:
  377. format = guess_format(self.filename)[0]
  378. if filter is None:
  379. filter = guess_format(self.filename)[1]
  380. self.format = format
  381. self.filter = filter
  382. # The class to use for entries.
  383. self.entry_class = entry_class
  384. # Select filter/format functions.
  385. if self.mode == 'r':
  386. self.format_func = get_func(self.format, FORMATS, 0)
  387. if self.format_func is None:
  388. raise Exception('Unsupported format %s' % format)
  389. self.filter_func = get_func(self.filter, FILTERS, 0)
  390. if self.filter_func is None:
  391. raise Exception('Unsupported filter %s' % filter)
  392. else:
  393. # TODO: how to support appending?
  394. if self.format is None:
  395. raise Exception('You must specify a format for writing.')
  396. self.format_func = get_func(self.format, FORMATS, 1)
  397. if self.format_func is None:
  398. raise Exception('Unsupported format %s' % format)
  399. self.filter_func = get_func(self.filter, FILTERS, 1)
  400. if self.filter_func is None:
  401. raise Exception('Unsupported filter %s' % filter)
  402. # Open the archive, apply filter/format functions.
  403. self.init()
  404. def __iter__(self):
  405. while True:
  406. try:
  407. yield self.entry_class.from_archive(self, encoding=self.encoding)
  408. except EOF:
  409. break
  410. def __enter__(self):
  411. return self
  412. def __exit__(self, type, value, traceback):
  413. self.denit()
  414. def __del__(self):
  415. self.close()
  416. def init(self):
  417. if self.mode == 'r':
  418. self._a = _libarchive.archive_read_new()
  419. else:
  420. self._a = _libarchive.archive_write_new()
  421. self.format_func(self._a)
  422. self.filter_func(self._a)
  423. if self.mode == 'r':
  424. call_and_check(_libarchive.archive_read_open_fd, self._a, self._a, self.f.fileno(), self.blocksize)
  425. else:
  426. call_and_check(_libarchive.archive_write_open_fd, self._a, self._a, self.f.fileno())
  427. def denit(self):
  428. '''Closes and deallocates the archive reader/writer.'''
  429. if getattr(self, '_a', None) is None:
  430. return
  431. try:
  432. if self.mode == 'r':
  433. _libarchive.archive_read_close(self._a)
  434. _libarchive.archive_read_free(self._a)
  435. elif self.mode == 'w':
  436. _libarchive.archive_write_close(self._a)
  437. _libarchive.archive_write_free(self._a)
  438. finally:
  439. # We only want one try at this...
  440. self._a = None
  441. def close(self, _defer=False):
  442. # _defer == True is how a stream can notify Archive that the stream is
  443. # now closed. Calling it directly in not recommended.
  444. if _defer:
  445. # This call came from our open stream.
  446. self._stream = None
  447. if not self._defer_close:
  448. # We are not yet ready to close.
  449. return
  450. if self._stream is not None:
  451. # We have a stream open! don't close, but remember we were asked to.
  452. self._defer_close = True
  453. return
  454. self.denit()
  455. # If there is a file attached...
  456. if hasattr(self, 'f'):
  457. # Make sure it is not already closed...
  458. if getattr(self.f, 'closed', False):
  459. return
  460. # Flush it if not read-only...
  461. if self.f.mode != 'r' and self.f.mode != 'rb':
  462. self.f.flush()
  463. os.fsync(self.f.fileno())
  464. # and then close it, if we opened it...
  465. if getattr(self, '_close', None):
  466. self.f.close()
  467. @property
  468. def header_position(self):
  469. '''The position within the file.'''
  470. return _libarchive.archive_read_header_position(self._a)
  471. def iterpaths(self):
  472. for entry in self:
  473. yield entry.pathname
  474. def read(self, size):
  475. '''Read current archive entry contents into string.'''
  476. return _libarchive.archive_read_data_into_str(self._a, size)
  477. def readpath(self, f):
  478. '''Write current archive entry contents to file. f can be a file-like object or
  479. a path.'''
  480. if isinstance(f, str):
  481. basedir = os.path.basename(f)
  482. if not os.path.exists(basedir):
  483. os.makedirs(basedir)
  484. f = open(f, 'w')
  485. return _libarchive.archive_read_data_into_fd(self._a, f.fileno())
  486. def readstream(self, size):
  487. '''Returns a file-like object for reading current archive entry contents.'''
  488. self._stream = EntryReadStream(self, size)
  489. return self._stream
  490. def write(self, member, data=None):
  491. '''Writes a string buffer to the archive as the given entry.'''
  492. if isinstance(member, str):
  493. member = self.entry_class(pathname=member, encoding=self.encoding)
  494. if data:
  495. member.size = len(data)
  496. member.to_archive(self)
  497. if data:
  498. if PY3:
  499. if isinstance(data, bytes):
  500. result = _libarchive.archive_write_data_from_str(self._a, data)
  501. else:
  502. result = _libarchive.archive_write_data_from_str(self._a, data.encode('utf8'))
  503. else:
  504. result = _libarchive.archive_write_data_from_str(self._a, data)
  505. _libarchive.archive_write_finish_entry(self._a)
  506. def writepath(self, f, pathname=None, folder=False):
  507. '''Writes a file to the archive. f can be a file-like object or a path. Uses
  508. write() to do the actual writing.'''
  509. member = self.entry_class.from_file(f, encoding=self.encoding)
  510. if isinstance(f, str):
  511. if os.path.isfile(f):
  512. f = open(f, 'r')
  513. if pathname:
  514. member.pathname = pathname
  515. if folder and not member.isdir():
  516. member.mode = stat.S_IFDIR
  517. if hasattr(f, 'read'):
  518. # TODO: optimize this to write directly from f to archive.
  519. self.write(member, data=f.read())
  520. else:
  521. self.write(member)
  522. def writestream(self, pathname, size=None):
  523. '''Returns a file-like object for writing a new entry.'''
  524. self._stream = EntryWriteStream(self, pathname, size)
  525. return self._stream
  526. def printlist(self, s=sys.stdout):
  527. for entry in self:
  528. s.write(entry.size)
  529. s.write('\t')
  530. s.write(entry.mtime.strftime(MTIME_FORMAT))
  531. s.write('\t')
  532. s.write(entry.pathname)
  533. s.flush()
  534. def add_passphrase(self, password):
  535. '''Adds a password to the archive.'''
  536. _libarchive.archive_read_add_passphrase(self._a, password)
  537. class SeekableArchive(Archive):
  538. '''A class that provides random-access to archive entries. It does this by using one
  539. or many Archive instances to seek to the correct location. The best performance will
  540. occur when reading archive entries in the order in which they appear in the archive.
  541. Reading out of order will cause the archive to be closed and opened each time a
  542. reverse seek is needed.'''
  543. def __init__(self, f, **kwargs):
  544. self._stream = None
  545. # Convert file to open file. We need this to reopen the archive.
  546. mode = kwargs.setdefault('mode', 'r')
  547. if isinstance(f, str):
  548. f = open(f, mode)
  549. super(SeekableArchive, self).__init__(f, **kwargs)
  550. self.entries = []
  551. self.eof = False
  552. def __iter__(self):
  553. for entry in self.entries:
  554. yield entry
  555. if not self.eof:
  556. try:
  557. for entry in super(SeekableArchive, self).__iter__():
  558. self.entries.append(entry)
  559. yield entry
  560. except StopIteration:
  561. self.eof = True
  562. def reopen(self):
  563. '''Seeks the underlying fd to 0 position, then opens the archive. If the archive
  564. is already open, this will effectively re-open it (rewind to the beginning).'''
  565. self.denit()
  566. self.f.seek(0)
  567. self.init()
  568. def getentry(self, pathname):
  569. '''Take a name or entry object and returns an entry object.'''
  570. for entry in self:
  571. if entry.pathname == pathname:
  572. return entry
  573. raise KeyError(pathname)
  574. def seek(self, entry):
  575. '''Seeks the archive to the requested entry. Will reopen if necessary.'''
  576. move = entry.header_position - self.header_position
  577. if move != 0:
  578. if move < 0:
  579. # can't move back, re-open archive:
  580. self.reopen()
  581. # move to proper position in stream
  582. for curr in super(SeekableArchive, self).__iter__():
  583. if curr.header_position == entry.header_position:
  584. break
  585. def read(self, member):
  586. '''Return the requested archive entry contents as a string.'''
  587. entry = self.getentry(member)
  588. self.seek(entry)
  589. return super(SeekableArchive, self).read(entry.size)
  590. def readpath(self, member, f):
  591. entry = self.getentry(member)
  592. self.seek(entry)
  593. return super(SeekableArchive, self).readpath(f)
  594. def readstream(self, member):
  595. '''Returns a file-like object for reading requested archive entry contents.'''
  596. entry = self.getentry(member)
  597. self.seek(entry)
  598. self._stream = EntryReadStream(self, entry.size)
  599. return self._stream