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