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.
 
 
 
 
 

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