]> arthur.barton.de Git - bup.git/blob - lib/bup/metadata.py
Replace os.*stat() with xstat.*stat(); use integer ns for all fs times.
[bup.git] / lib / bup / metadata.py
1 """Metadata read/write support for bup."""
2
3 # Copyright (C) 2010 Rob Browning
4 #
5 # This code is covered under the terms of the GNU Library General
6 # Public License as described in the bup LICENSE file.
7 import errno, os, sys, stat, pwd, grp, struct, re
8 from cStringIO import StringIO
9 from bup import vint, xstat
10 from bup.drecurse import recursive_dirlist
11 from bup.helpers import add_error, mkdirp, log
12 from bup.xstat import utime, lutime
13 import bup._helpers as _helpers
14
15 try:
16     import xattr
17 except ImportError:
18     log('Warning: Linux xattr support missing; install python-pyxattr.\n')
19     xattr = None
20 if xattr:
21     try:
22         xattr.get_all
23     except AttributeError:
24         log('Warning: python-xattr module is too old; '
25             'install python-pyxattr instead.\n')
26         xattr = None
27 try:
28     import posix1e
29 except ImportError:
30     log('Warning: POSIX ACL support missing; install python-pylibacl.\n')
31     posix1e = None
32 try:
33     from bup._helpers import get_linux_file_attr, set_linux_file_attr
34 except ImportError:
35     # No need for a warning here; the only reason they won't exist is that we're
36     # not on Linux, in which case files don't have any linux attrs anyway, so
37     # lacking the functions isn't a problem.
38     get_linux_file_attr = set_linux_file_attr = None
39     
40
41 # WARNING: the metadata encoding is *not* stable yet.  Caveat emptor!
42
43 # Q: Consider hardlink support?
44 # Q: Is it OK to store raw linux attr (chattr) flags?
45 # Q: Can anything other than S_ISREG(x) or S_ISDIR(x) support posix1e ACLs?
46 # Q: Is the application of posix1e has_extended() correct?
47 # Q: Is one global --numeric-ids argument sufficient?
48 # Q: Do nfsv4 acls trump posix1e acls? (seems likely)
49 # Q: Add support for crtime -- ntfs, and (only internally?) ext*?
50
51 # FIXME: Fix relative/abs path detection/stripping wrt other platforms.
52 # FIXME: Add nfsv4 acl handling - see nfs4-acl-tools.
53 # FIXME: Consider other entries mentioned in stat(2) (S_IFDOOR, etc.).
54 # FIXME: Consider pack('vvvvsss', ...) optimization.
55 # FIXME: Consider caching users/groups.
56
57 ## FS notes:
58 #
59 # osx (varies between hfs and hfs+):
60 #   type - regular dir char block fifo socket ...
61 #   perms - rwxrwxrwxsgt
62 #   times - ctime atime mtime
63 #   uid
64 #   gid
65 #   hard-link-info (hfs+ only)
66 #   link-target
67 #   device-major/minor
68 #   attributes-osx see chflags
69 #   content-type
70 #   content-creator
71 #   forks
72 #
73 # ntfs
74 #   type - regular dir ...
75 #   times - creation, modification, posix change, access
76 #   hard-link-info
77 #   link-target
78 #   attributes - see attrib
79 #   ACLs
80 #   forks (alternate data streams)
81 #   crtime?
82 #
83 # fat
84 #   type - regular dir ...
85 #   perms - rwxrwxrwx (maybe - see wikipedia)
86 #   times - creation, modification, access
87 #   attributes - see attrib
88
89 verbose = 0
90
91 _have_lchmod = hasattr(os, 'lchmod')
92
93
94 def _clean_up_path_for_archive(p):
95     # Not the most efficient approach.
96     result = p
97
98     # Take everything after any '/../'.
99     pos = result.rfind('/../')
100     if pos != -1:
101         result = result[result.rfind('/../') + 4:]
102
103     # Take everything after any remaining '../'.
104     if result.startswith("../"):
105         result = result[3:]
106
107     # Remove any '/./' sequences.
108     pos = result.find('/./')
109     while pos != -1:
110         result = result[0:pos] + '/' + result[pos + 3:]
111         pos = result.find('/./')
112
113     # Remove any leading '/'s.
114     result = result.lstrip('/')
115
116     # Replace '//' with '/' everywhere.
117     pos = result.find('//')
118     while pos != -1:
119         result = result[0:pos] + '/' + result[pos + 2:]
120         pos = result.find('//')
121
122     # Take everything after any remaining './'.
123     if result.startswith('./'):
124         result = result[2:]
125
126     # Take everything before any remaining '/.'.
127     if result.endswith('/.'):
128         result = result[:-2]
129
130     if result == '' or result.endswith('/..'):
131         result = '.'
132
133     return result
134
135
136 def _risky_path(p):
137     if p.startswith('/'):
138         return True
139     if p.find('/../') != -1:
140         return True
141     if p.startswith('../'):
142         return True
143     if p.endswith('/..'):
144         return True
145     return False
146
147
148 def _clean_up_extract_path(p):
149     result = p.lstrip('/')
150     if result == '':
151         return '.'
152     elif _risky_path(result):
153         return None
154     else:
155         return result
156
157
158 # These tags are currently conceptually private to Metadata, and they
159 # must be unique, and must *never* be changed.
160 _rec_tag_end = 0
161 _rec_tag_path = 1
162 _rec_tag_common = 2           # times, owner, group, type, perms, etc.
163 _rec_tag_symlink_target = 3
164 _rec_tag_posix1e_acl = 4      # getfacl(1), setfacl(1), etc.
165 _rec_tag_nfsv4_acl = 5        # intended to supplant posix1e acls?
166 _rec_tag_linux_attr = 6       # lsattr(1) chattr(1)
167 _rec_tag_linux_xattr = 7      # getfattr(1) setfattr(1)
168
169
170 class ApplyError(Exception):
171     # Thrown when unable to apply any given bit of metadata to a path.
172     pass
173
174
175 class Metadata:
176     # Metadata is stored as a sequence of tagged binary records.  Each
177     # record will have some subset of add, encode, load, create, and
178     # apply methods, i.e. _add_foo...
179
180     ## Common records
181
182     # Timestamps are (sec, ns), relative to 1970-01-01 00:00:00, ns
183     # must be non-negative and < 10**9.
184
185     def _add_common(self, path, st):
186         self.mode = st.st_mode
187         self.uid = st.st_uid
188         self.gid = st.st_gid
189         self.rdev = st.st_rdev
190         self.atime = st.st_atime
191         self.mtime = st.st_mtime
192         self.ctime = st.st_ctime
193         self.owner = self.group = ''
194         try:
195             self.owner = pwd.getpwuid(st.st_uid)[0]
196         except KeyError, e:
197             add_error("no user name for id %s '%s'" % (st.st_gid, path))
198         try:
199             self.group = grp.getgrgid(st.st_gid)[0]
200         except KeyError, e:
201             add_error("no group name for id %s '%s'" % (st.st_gid, path))
202
203     def _encode_common(self):
204         atime = xstat.nsecs_to_timespec(self.atime)
205         mtime = xstat.nsecs_to_timespec(self.mtime)
206         ctime = xstat.nsecs_to_timespec(self.ctime)
207         result = vint.pack('VVsVsVvVvVvV',
208                            self.mode,
209                            self.uid,
210                            self.owner,
211                            self.gid,
212                            self.group,
213                            self.rdev,
214                            atime[0],
215                            atime[1],
216                            mtime[0],
217                            mtime[1],
218                            ctime[0],
219                            ctime[1])
220         return result
221
222     def _load_common_rec(self, port):
223         data = vint.read_bvec(port)
224         (self.mode,
225          self.uid,
226          self.owner,
227          self.gid,
228          self.group,
229          self.rdev,
230          self.atime,
231          atime_ns,
232          self.mtime,
233          mtime_ns,
234          self.ctime,
235          ctime_ns) = vint.unpack('VVsVsVvVvVvV', data)
236         self.atime = xstat.timespec_to_nsecs((self.atime, atime_ns))
237         self.mtime = xstat.timespec_to_nsecs((self.mtime, mtime_ns))
238         self.ctime = xstat.timespec_to_nsecs((self.ctime, ctime_ns))
239
240     def _create_via_common_rec(self, path, create_symlinks=True):
241         # If the path already exists and is a dir, try rmdir.
242         # If the path already exists and is anything else, try unlink.
243         st = None
244         try:
245             st = xstat.lstat(path)
246         except OSError, e:
247             if e.errno != errno.ENOENT:
248                 raise
249         if st:
250             if stat.S_ISDIR(st.st_mode):
251                 try:
252                     os.rmdir(path)
253                 except OSError, e:
254                     if e.errno == errno.ENOTEMPTY:
255                         msg = 'refusing to overwrite non-empty dir' + path
256                         raise Exception(msg)
257                     raise
258             else:
259                 os.unlink(path)
260
261         if stat.S_ISREG(self.mode):
262             fd = os.open(path, os.O_CREAT|os.O_WRONLY|os.O_EXCL, 0600)
263             os.close(fd)
264         elif stat.S_ISDIR(self.mode):
265             os.mkdir(path, 0700)
266         elif stat.S_ISCHR(self.mode):
267             os.mknod(path, 0600 | stat.S_IFCHR, self.rdev)
268         elif stat.S_ISBLK(self.mode):
269             os.mknod(path, 0600 | stat.S_IFBLK, self.rdev)
270         elif stat.S_ISFIFO(self.mode):
271             os.mknod(path, 0600 | stat.S_IFIFO)
272         elif stat.S_ISLNK(self.mode):
273             if self.symlink_target and create_symlinks:
274                 # on MacOS, symlink() permissions depend on umask, and there's no
275                 # way to chown a symlink after creating it, so we have to
276                 # be careful here!
277                 oldumask = os.umask((self.mode & 0777) ^ 0777)
278                 try:
279                     os.symlink(self.symlink_target, path)
280                 finally:
281                     os.umask(oldumask)
282         # FIXME: S_ISDOOR, S_IFMPB, S_IFCMP, S_IFNWK, ... see stat(2).
283         # Otherwise, do nothing.
284
285     def _apply_common_rec(self, path, restore_numeric_ids=False):
286         # FIXME: S_ISDOOR, S_IFMPB, S_IFCMP, S_IFNWK, ... see stat(2).
287         # EACCES errors at this stage are fatal for the current path.
288         if stat.S_ISLNK(self.mode):
289             try:
290                 lutime(path, (self.atime, self.mtime))
291             except OSError, e:
292                 if e.errno == errno.EACCES:
293                     raise ApplyError('lutime: %s' % e)
294                 else:
295                     raise
296         else:
297             try:
298                 utime(path, (self.atime, self.mtime))
299             except OSError, e:
300                 if e.errno == errno.EACCES:
301                     raise ApplyError('utime: %s' % e)
302                 else:
303                     raise
304
305         # Don't try to restore owner unless we're root, and even
306         # if asked, don't try to restore the owner or group if
307         # it doesn't exist in the system db.
308         uid = self.uid
309         gid = self.gid
310         if not restore_numeric_ids:
311             if not self.owner:
312                 uid = -1
313                 add_error('ignoring missing owner for "%s"\n' % path)
314             else:
315                 if os.geteuid() != 0:
316                     uid = -1 # Not root; assume we can't change owner.
317                 else:
318                     try:
319                         uid = pwd.getpwnam(self.owner)[2]
320                     except KeyError:
321                         uid = -1
322                         fmt = 'ignoring unknown owner %s for "%s"\n'
323                         add_error(fmt % (self.owner, path))
324             if not self.group:
325                 gid = -1
326                 add_error('ignoring missing group for "%s"\n' % path)
327             else:
328                 try:
329                     gid = grp.getgrnam(self.group)[2]
330                 except KeyError:
331                     gid = -1
332                     add_error('ignoring unknown group %s for "%s"\n'
333                               % (self.group, path))
334
335         try:
336             os.lchown(path, uid, gid)
337         except OSError, e:
338             if e.errno == errno.EPERM:
339                 add_error('lchown: %s' %  e)
340             else:
341                 raise
342
343         if _have_lchmod:
344             os.lchmod(path, stat.S_IMODE(self.mode))
345         elif not stat.S_ISLNK(self.mode):
346             os.chmod(path, stat.S_IMODE(self.mode))
347
348
349     ## Path records
350
351     def _encode_path(self):
352         if self.path:
353             return vint.pack('s', self.path)
354         else:
355             return None
356
357     def _load_path_rec(self, port):
358         self.path = vint.unpack('s', vint.read_bvec(port))[0]
359
360
361     ## Symlink targets
362
363     def _add_symlink_target(self, path, st):
364         try:
365             if stat.S_ISLNK(st.st_mode):
366                 self.symlink_target = os.readlink(path)
367         except OSError, e:
368             add_error('readlink: %s', e)
369
370     def _encode_symlink_target(self):
371         return self.symlink_target
372
373     def _load_symlink_target_rec(self, port):
374         self.symlink_target = vint.read_bvec(port)
375
376
377     ## POSIX1e ACL records
378
379     # Recorded as a list:
380     #   [txt_id_acl, num_id_acl]
381     # or, if a directory:
382     #   [txt_id_acl, num_id_acl, txt_id_default_acl, num_id_default_acl]
383     # The numeric/text distinction only matters when reading/restoring
384     # a stored record.
385     def _add_posix1e_acl(self, path, st):
386         if not posix1e: return
387         if not stat.S_ISLNK(st.st_mode):
388             try:
389                 if posix1e.has_extended(path):
390                     acl = posix1e.ACL(file=path)
391                     self.posix1e_acl = [acl, acl] # txt and num are the same
392                     if stat.S_ISDIR(st.st_mode):
393                         acl = posix1e.ACL(filedef=path)
394                         self.posix1e_acl.extend([acl, acl])
395             except EnvironmentError, e:
396                 if e.errno != errno.EOPNOTSUPP:
397                     raise
398
399     def _encode_posix1e_acl(self):
400         # Encode as two strings (w/default ACL string possibly empty).
401         if self.posix1e_acl:
402             acls = self.posix1e_acl
403             txt_flags = posix1e.TEXT_ABBREVIATE
404             num_flags = posix1e.TEXT_ABBREVIATE | posix1e.TEXT_NUMERIC_IDS
405             acl_reps = [acls[0].to_any_text('', '\n', txt_flags),
406                         acls[1].to_any_text('', '\n', num_flags)]
407             if len(acls) < 3:
408                 acl_reps += ['', '']
409             else:
410                 acl_reps.append(acls[2].to_any_text('', '\n', txt_flags))
411                 acl_reps.append(acls[3].to_any_text('', '\n', num_flags))
412             return vint.pack('ssss',
413                              acl_reps[0], acl_reps[1], acl_reps[2], acl_reps[3])
414         else:
415             return None
416
417     def _load_posix1e_acl_rec(self, port):
418         data = vint.read_bvec(port)
419         acl_reps = vint.unpack('ssss', data)
420         if acl_reps[2] == '':
421             acl_reps = acl_reps[:2]
422         self.posix1e_acl = [posix1e.ACL(text=x) for x in acl_reps]
423
424     def _apply_posix1e_acl_rec(self, path, restore_numeric_ids=False):
425         if not posix1e:
426             if self.posix1e_acl:
427                 add_error("%s: can't restore ACLs; posix1e support missing.\n"
428                           % path)
429             return
430         if self.posix1e_acl:
431             acls = self.posix1e_acl
432             if len(acls) > 2:
433                 if restore_numeric_ids:
434                     acls[3].applyto(path, posix1e.ACL_TYPE_DEFAULT)
435                 else:
436                     acls[2].applyto(path, posix1e.ACL_TYPE_DEFAULT)
437             if restore_numeric_ids:
438                 acls[1].applyto(path, posix1e.ACL_TYPE_ACCESS)
439             else:
440                 acls[0].applyto(path, posix1e.ACL_TYPE_ACCESS)
441
442
443     ## Linux attributes (lsattr(1), chattr(1))
444
445     def _add_linux_attr(self, path, st):
446         if not get_linux_file_attr: return
447         if stat.S_ISREG(st.st_mode) or stat.S_ISDIR(st.st_mode):
448             try:
449                 attr = get_linux_file_attr(path)
450                 if attr != 0:
451                     self.linux_attr = attr
452             except OSError, e:
453                 if e.errno == errno.EACCES:
454                     add_error('read Linux attr: %s' % e)
455                 elif e.errno == errno.ENOTTY: # Inappropriate ioctl for device.
456                     add_error('read Linux attr: %s' % e)
457                 else:
458                     raise
459
460     def _encode_linux_attr(self):
461         if self.linux_attr:
462             return vint.pack('V', self.linux_attr)
463         else:
464             return None
465
466     def _load_linux_attr_rec(self, port):
467         data = vint.read_bvec(port)
468         self.linux_attr = vint.unpack('V', data)[0]
469
470     def _apply_linux_attr_rec(self, path, restore_numeric_ids=False):
471         if self.linux_attr:
472             if not set_linux_file_attr:
473                 add_error("%s: can't restore linuxattrs: "
474                           "linuxattr support missing.\n" % path)
475                 return
476             set_linux_file_attr(path, self.linux_attr)
477
478
479     ## Linux extended attributes (getfattr(1), setfattr(1))
480
481     def _add_linux_xattr(self, path, st):
482         if not xattr: return
483         try:
484             self.linux_xattr = xattr.get_all(path, nofollow=True)
485         except EnvironmentError, e:
486             if e.errno != errno.EOPNOTSUPP:
487                 raise
488
489     def _encode_linux_xattr(self):
490         if self.linux_xattr:
491             result = vint.pack('V', len(self.linux_xattr))
492             for name, value in self.linux_xattr:
493                 result += vint.pack('ss', name, value)
494             return result
495         else:
496             return None
497
498     def _load_linux_xattr_rec(self, file):
499         data = vint.read_bvec(file)
500         memfile = StringIO(data)
501         result = []
502         for i in range(vint.read_vuint(memfile)):
503             key = vint.read_bvec(memfile)
504             value = vint.read_bvec(memfile)
505             result.append((key, value))
506         self.linux_xattr = result
507
508     def _apply_linux_xattr_rec(self, path, restore_numeric_ids=False):
509         if not xattr:
510             if self.linux_xattr:
511                 add_error("%s: can't restore xattr; xattr support missing.\n"
512                           % path)
513             return
514         existing_xattrs = set(xattr.list(path, nofollow=True))
515         if self.linux_xattr:
516             for k, v in self.linux_xattr:
517                 if k not in existing_xattrs \
518                         or v != xattr.get(path, k, nofollow=True):
519                     try:
520                         xattr.set(path, k, v, nofollow=True)
521                     except IOError, e:
522                         if e.errno == errno.EPERM:
523                             raise ApplyError('xattr.set: %s' % e)
524                         else:
525                             raise
526                 existing_xattrs -= frozenset([k])
527             for k in existing_xattrs:
528                 try:
529                     xattr.remove(path, k, nofollow=True)
530                 except IOError, e:
531                     if e.errno == errno.EPERM:
532                         raise ApplyError('xattr.remove: %s' % e)
533                     else:
534                         raise
535
536     def __init__(self):
537         # optional members
538         self.path = None
539         self.symlink_target = None
540         self.linux_attr = None
541         self.linux_xattr = None
542         self.posix1e_acl = None
543         self.posix1e_acl_default = None
544
545     def write(self, port, include_path=True):
546         records = include_path and [(_rec_tag_path, self._encode_path())] or []
547         records.extend([(_rec_tag_common, self._encode_common()),
548                         (_rec_tag_symlink_target, self._encode_symlink_target()),
549                         (_rec_tag_posix1e_acl, self._encode_posix1e_acl()),
550                         (_rec_tag_linux_attr, self._encode_linux_attr()),
551                         (_rec_tag_linux_xattr, self._encode_linux_xattr())])
552         for tag, data in records:
553             if data:
554                 vint.write_vuint(port, tag)
555                 vint.write_bvec(port, data)
556         vint.write_vuint(port, _rec_tag_end)
557
558     @staticmethod
559     def read(port):
560         # This method should either: return a valid Metadata object;
561         # throw EOFError if there was nothing at all to read; throw an
562         # Exception if a valid object could not be read completely.
563         tag = vint.read_vuint(port)
564         try: # From here on, EOF is an error.
565             result = Metadata()
566             while True: # only exit is error (exception) or _rec_tag_end
567                 if tag == _rec_tag_path:
568                     result._load_path_rec(port)
569                 elif tag == _rec_tag_common:
570                     result._load_common_rec(port)
571                 elif tag == _rec_tag_symlink_target:
572                     result._load_symlink_target_rec(port)
573                 elif tag == _rec_tag_posix1e_acl:
574                     result._load_posix1e_acl_rec(port)
575                 elif tag ==_rec_tag_nfsv4_acl:
576                     result._load_nfsv4_acl_rec(port)
577                 elif tag == _rec_tag_linux_attr:
578                     result._load_linux_attr_rec(port)
579                 elif tag == _rec_tag_linux_xattr:
580                     result._load_linux_xattr_rec(port)
581                 elif tag == _rec_tag_end:
582                     return result
583                 else: # unknown record
584                     vint.skip_bvec(port)
585                 tag = vint.read_vuint(port)
586         except EOFError:
587             raise Exception("EOF while reading Metadata")
588
589     def isdir(self):
590         return stat.S_ISDIR(self.mode)
591
592     def create_path(self, path, create_symlinks=True):
593         self._create_via_common_rec(path, create_symlinks=create_symlinks)
594
595     def apply_to_path(self, path=None, restore_numeric_ids=False):
596         # apply metadata to path -- file must exist
597         if not path:
598             path = self.path
599         if not path:
600             raise Exception('Metadata.apply_to_path() called with no path');
601         num_ids = restore_numeric_ids
602         try:
603             self._apply_common_rec(path, restore_numeric_ids=num_ids)
604             self._apply_posix1e_acl_rec(path, restore_numeric_ids=num_ids)
605             self._apply_linux_attr_rec(path, restore_numeric_ids=num_ids)
606             self._apply_linux_xattr_rec(path, restore_numeric_ids=num_ids)
607         except ApplyError, e:
608             add_error(e)
609
610
611 def from_path(path, statinfo=None, archive_path=None, save_symlinks=True):
612     result = Metadata()
613     result.path = archive_path
614     st = statinfo or xstat.lstat(path)
615     result._add_common(path, st)
616     if save_symlinks:
617         result._add_symlink_target(path, st)
618     result._add_posix1e_acl(path, st)
619     result._add_linux_attr(path, st)
620     result._add_linux_xattr(path, st)
621     return result
622
623
624 def save_tree(output_file, paths,
625               recurse=False,
626               write_paths=True,
627               save_symlinks=True,
628               xdev=False):
629
630     # Issue top-level rewrite warnings.
631     for path in paths:
632         safe_path = _clean_up_path_for_archive(path)
633         if safe_path != path:
634             log('archiving "%s" as "%s"\n' % (path, safe_path))
635
636     start_dir = os.getcwd()
637     try:
638         for (p, st) in recursive_dirlist(paths, xdev=xdev):
639             dirlist_dir = os.getcwd()
640             os.chdir(start_dir)
641             safe_path = _clean_up_path_for_archive(p)
642             m = from_path(p, statinfo=st, archive_path=safe_path,
643                           save_symlinks=save_symlinks)
644             if verbose:
645                 print >> sys.stderr, m.path
646             m.write(output_file, include_path=write_paths)
647             os.chdir(dirlist_dir)
648     finally:
649         os.chdir(start_dir)
650
651
652 def _set_up_path(meta, create_symlinks=True):
653     # Allow directories to exist as a special case -- might have
654     # been created by an earlier longer path.
655     if meta.isdir():
656         mkdirp(meta.path)
657     else:
658         parent = os.path.dirname(meta.path)
659         if parent:
660             mkdirp(parent)
661             meta.create_path(meta.path, create_symlinks=create_symlinks)
662
663
664 class _ArchiveIterator:
665     def next(self):
666         try:
667             return Metadata.read(self._file)
668         except EOFError:
669             raise StopIteration()
670
671     def __iter__(self):
672         return self
673
674     def __init__(self, file):
675         self._file = file
676
677
678 def display_archive(file):
679     for meta in _ArchiveIterator(file):
680         if verbose:
681             print meta.path # FIXME
682         else:
683             print meta.path
684
685
686 def start_extract(file, create_symlinks=True):
687     for meta in _ArchiveIterator(file):
688         if verbose:
689             print >> sys.stderr, meta.path
690         xpath = _clean_up_extract_path(meta.path)
691         if not xpath:
692             add_error(Exception('skipping risky path "%s"' % meta.path))
693         else:
694             meta.path = xpath
695             _set_up_path(meta, create_symlinks=create_symlinks)
696
697
698 def finish_extract(file, restore_numeric_ids=False):
699     all_dirs = []
700     for meta in _ArchiveIterator(file):
701         xpath = _clean_up_extract_path(meta.path)
702         if not xpath:
703             add_error(Exception('skipping risky path "%s"' % dir.path))
704         else:
705             if os.path.isdir(meta.path):
706                 all_dirs.append(meta)
707             else:
708                 if verbose:
709                     print >> sys.stderr, meta.path
710                 meta.apply_to_path(path=xpath,
711                                    restore_numeric_ids=restore_numeric_ids)
712     all_dirs.sort(key = lambda x : len(x.path), reverse=True)
713     for dir in all_dirs:
714         # Don't need to check xpath -- won't be in all_dirs if not OK.
715         xpath = _clean_up_extract_path(dir.path)
716         if verbose:
717             print >> sys.stderr, dir.path
718         dir.apply_to_path(path=xpath, restore_numeric_ids=restore_numeric_ids)
719
720
721 def extract(file, restore_numeric_ids=False, create_symlinks=True):
722     # For now, just store all the directories and handle them last,
723     # longest first.
724     all_dirs = []
725     for meta in _ArchiveIterator(file):
726         xpath = _clean_up_extract_path(meta.path)
727         if not xpath:
728             add_error(Exception('skipping risky path "%s"' % meta.path))
729         else:
730             meta.path = xpath
731             if verbose:
732                 print >> sys.stderr, '+', meta.path
733             _set_up_path(meta, create_symlinks=create_symlinks)
734             if os.path.isdir(meta.path):
735                 all_dirs.append(meta)
736             else:
737                 if verbose:
738                     print >> sys.stderr, '=', meta.path
739                 meta.apply_to_path(restore_numeric_ids=restore_numeric_ids)
740     all_dirs.sort(key = lambda x : len(x.path), reverse=True)
741     for dir in all_dirs:
742         # Don't need to check xpath -- won't be in all_dirs if not OK.
743         xpath = _clean_up_extract_path(dir.path)
744         if verbose:
745             print >> sys.stderr, '=', xpath
746         # Shouldn't have to check for risky paths here (omitted above).
747         dir.apply_to_path(path=dir.path,
748                           restore_numeric_ids=restore_numeric_ids)