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.
 
 
 
 
 

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