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.
 
 
 
 
 

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