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