]> arthur.barton.de Git - bup.git/blob - lib/bup/metadata.py
Save metadata during "bup save".
[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, time, 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, is_superuser
12 from bup.xstat import utime, lutime, lstat
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, user, 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     # We do allow an "empty" object as a special case, i.e. no
181     # records.  One can be created by trying to write Metadata(), and
182     # for such an object, read() will return None.  This is used by
183     # "bup save", for example, as a placeholder in cases where
184     # from_path() fails.
185
186     ## Common records
187
188     # Timestamps are (sec, ns), relative to 1970-01-01 00:00:00, ns
189     # must be non-negative and < 10**9.
190
191     def _add_common(self, path, st):
192         self.uid = st.st_uid
193         self.gid = st.st_gid
194         self.rdev = st.st_rdev
195         self.atime = st.st_atime
196         self.mtime = st.st_mtime
197         self.ctime = st.st_ctime
198         self.user = self.group = ''
199         try:
200             self.user = pwd.getpwuid(st.st_uid)[0]
201         except KeyError, e:
202             add_error("no user name for id %s '%s'" % (st.st_gid, path))
203         try:
204             self.group = grp.getgrgid(st.st_gid)[0]
205         except KeyError, e:
206             add_error("no group name for id %s '%s'" % (st.st_gid, path))
207         self.mode = st.st_mode
208
209     def _encode_common(self):
210         if not self.mode:
211             return None
212         atime = xstat.nsecs_to_timespec(self.atime)
213         mtime = xstat.nsecs_to_timespec(self.mtime)
214         ctime = xstat.nsecs_to_timespec(self.ctime)
215         result = vint.pack('VVsVsVvVvVvV',
216                            self.mode,
217                            self.uid,
218                            self.user,
219                            self.gid,
220                            self.group,
221                            self.rdev,
222                            atime[0],
223                            atime[1],
224                            mtime[0],
225                            mtime[1],
226                            ctime[0],
227                            ctime[1])
228         return result
229
230     def _load_common_rec(self, port):
231         data = vint.read_bvec(port)
232         (self.mode,
233          self.uid,
234          self.user,
235          self.gid,
236          self.group,
237          self.rdev,
238          self.atime,
239          atime_ns,
240          self.mtime,
241          mtime_ns,
242          self.ctime,
243          ctime_ns) = vint.unpack('VVsVsVvVvVvV', data)
244         self.atime = xstat.timespec_to_nsecs((self.atime, atime_ns))
245         self.mtime = xstat.timespec_to_nsecs((self.mtime, mtime_ns))
246         self.ctime = xstat.timespec_to_nsecs((self.ctime, ctime_ns))
247
248     def _recognized_file_type(self):
249         return stat.S_ISREG(self.mode) \
250             or stat.S_ISDIR(self.mode) \
251             or stat.S_ISCHR(self.mode) \
252             or stat.S_ISBLK(self.mode) \
253             or stat.S_ISFIFO(self.mode) \
254             or stat.S_ISSOCK(self.mode) \
255             or stat.S_ISLNK(self.mode)
256
257     def _create_via_common_rec(self, path, create_symlinks=True):
258         if not self.mode:
259             raise ApplyError('no metadata - cannot create path ' + path)
260
261         # If the path already exists and is a dir, try rmdir.
262         # If the path already exists and is anything else, try unlink.
263         st = None
264         try:
265             st = xstat.lstat(path)
266         except OSError, e:
267             if e.errno != errno.ENOENT:
268                 raise
269         if st:
270             if stat.S_ISDIR(st.st_mode):
271                 try:
272                     os.rmdir(path)
273                 except OSError, e:
274                     if e.errno == errno.ENOTEMPTY:
275                         msg = 'refusing to overwrite non-empty dir ' + path
276                         raise Exception(msg)
277                     raise
278             else:
279                 os.unlink(path)
280
281         if stat.S_ISREG(self.mode):
282             assert(self._recognized_file_type())
283             fd = os.open(path, os.O_CREAT|os.O_WRONLY|os.O_EXCL, 0600)
284             os.close(fd)
285         elif stat.S_ISDIR(self.mode):
286             assert(self._recognized_file_type())
287             os.mkdir(path, 0700)
288         elif stat.S_ISCHR(self.mode):
289             assert(self._recognized_file_type())
290             os.mknod(path, 0600 | stat.S_IFCHR, self.rdev)
291         elif stat.S_ISBLK(self.mode):
292             assert(self._recognized_file_type())
293             os.mknod(path, 0600 | stat.S_IFBLK, self.rdev)
294         elif stat.S_ISFIFO(self.mode):
295             assert(self._recognized_file_type())
296             os.mknod(path, 0600 | stat.S_IFIFO)
297         elif stat.S_ISSOCK(self.mode):
298             os.mknod(path, 0600 | stat.S_IFSOCK)
299         elif stat.S_ISLNK(self.mode):
300             assert(self._recognized_file_type())
301             if self.symlink_target and create_symlinks:
302                 # on MacOS, symlink() permissions depend on umask, and there's
303                 # no way to chown a symlink after creating it, so we have to
304                 # be careful here!
305                 oldumask = os.umask((self.mode & 0777) ^ 0777)
306                 try:
307                     os.symlink(self.symlink_target, path)
308                 finally:
309                     os.umask(oldumask)
310         # FIXME: S_ISDOOR, S_IFMPB, S_IFCMP, S_IFNWK, ... see stat(2).
311         else:
312             assert(not self._recognized_file_type())
313             add_error('not creating "%s" with unrecognized mode "0x%x"\n'
314                       % (path, self.mode))
315
316     def _apply_common_rec(self, path, restore_numeric_ids=False):
317         if not self.mode:
318             raise ApplyError('no metadata - cannot apply to ' + path)
319
320         # FIXME: S_ISDOOR, S_IFMPB, S_IFCMP, S_IFNWK, ... see stat(2).
321         # EACCES errors at this stage are fatal for the current path.
322         if lutime and stat.S_ISLNK(self.mode):
323             try:
324                 lutime(path, (self.atime, self.mtime))
325             except OSError, e:
326                 if e.errno == errno.EACCES:
327                     raise ApplyError('lutime: %s' % e)
328                 else:
329                     raise
330         else:
331             try:
332                 utime(path, (self.atime, self.mtime))
333             except OSError, e:
334                 if e.errno == errno.EACCES:
335                     raise ApplyError('utime: %s' % e)
336                 else:
337                     raise
338
339         # Don't try to restore user unless we're root, and even
340         # if asked, don't try to restore the user or group if
341         # it doesn't exist in the system db.
342         uid = self.uid
343         gid = self.gid
344         if not restore_numeric_ids:
345             if not self.user:
346                 uid = -1
347                 add_error('ignoring missing user for "%s"\n' % path)
348             else:
349                 if not is_superuser():
350                     uid = -1 # Not root; assume we can't change user.
351                 else:
352                     try:
353                         uid = pwd.getpwnam(self.user)[2]
354                     except KeyError:
355                         uid = -1
356                         fmt = 'ignoring unknown user %s for "%s"\n'
357                         add_error(fmt % (self.user, path))
358             if not self.group:
359                 gid = -1
360                 add_error('ignoring missing group for "%s"\n' % path)
361             else:
362                 try:
363                     gid = grp.getgrnam(self.group)[2]
364                 except KeyError:
365                     gid = -1
366                     add_error('ignoring unknown group %s for "%s"\n'
367                               % (self.group, path))
368
369         try:
370             os.lchown(path, uid, gid)
371         except OSError, e:
372             if e.errno == errno.EPERM:
373                 add_error('lchown: %s' %  e)
374             else:
375                 raise
376
377         if _have_lchmod:
378             os.lchmod(path, stat.S_IMODE(self.mode))
379         elif not stat.S_ISLNK(self.mode):
380             os.chmod(path, stat.S_IMODE(self.mode))
381
382
383     ## Path records
384
385     def _encode_path(self):
386         if self.path:
387             return vint.pack('s', self.path)
388         else:
389             return None
390
391     def _load_path_rec(self, port):
392         self.path = vint.unpack('s', vint.read_bvec(port))[0]
393
394
395     ## Symlink targets
396
397     def _add_symlink_target(self, path, st):
398         try:
399             if stat.S_ISLNK(st.st_mode):
400                 self.symlink_target = os.readlink(path)
401         except OSError, e:
402             add_error('readlink: %s', e)
403
404     def _encode_symlink_target(self):
405         return self.symlink_target
406
407     def _load_symlink_target_rec(self, port):
408         self.symlink_target = vint.read_bvec(port)
409
410
411     ## POSIX1e ACL records
412
413     # Recorded as a list:
414     #   [txt_id_acl, num_id_acl]
415     # or, if a directory:
416     #   [txt_id_acl, num_id_acl, txt_id_default_acl, num_id_default_acl]
417     # The numeric/text distinction only matters when reading/restoring
418     # a stored record.
419     def _add_posix1e_acl(self, path, st):
420         if not posix1e: return
421         if not stat.S_ISLNK(st.st_mode):
422             try:
423                 if posix1e.has_extended(path):
424                     acl = posix1e.ACL(file=path)
425                     self.posix1e_acl = [acl, acl] # txt and num are the same
426                     if stat.S_ISDIR(st.st_mode):
427                         acl = posix1e.ACL(filedef=path)
428                         self.posix1e_acl.extend([acl, acl])
429             except EnvironmentError, e:
430                 if e.errno != errno.EOPNOTSUPP:
431                     raise
432
433     def _encode_posix1e_acl(self):
434         # Encode as two strings (w/default ACL string possibly empty).
435         if self.posix1e_acl:
436             acls = self.posix1e_acl
437             txt_flags = posix1e.TEXT_ABBREVIATE
438             num_flags = posix1e.TEXT_ABBREVIATE | posix1e.TEXT_NUMERIC_IDS
439             acl_reps = [acls[0].to_any_text('', '\n', txt_flags),
440                         acls[1].to_any_text('', '\n', num_flags)]
441             if len(acls) < 3:
442                 acl_reps += ['', '']
443             else:
444                 acl_reps.append(acls[2].to_any_text('', '\n', txt_flags))
445                 acl_reps.append(acls[3].to_any_text('', '\n', num_flags))
446             return vint.pack('ssss',
447                              acl_reps[0], acl_reps[1], acl_reps[2], acl_reps[3])
448         else:
449             return None
450
451     def _load_posix1e_acl_rec(self, port):
452         data = vint.read_bvec(port)
453         acl_reps = vint.unpack('ssss', data)
454         if acl_reps[2] == '':
455             acl_reps = acl_reps[:2]
456         self.posix1e_acl = [posix1e.ACL(text=x) for x in acl_reps]
457
458     def _apply_posix1e_acl_rec(self, path, restore_numeric_ids=False):
459         if not posix1e:
460             if self.posix1e_acl:
461                 add_error("%s: can't restore ACLs; posix1e support missing.\n"
462                           % path)
463             return
464         if self.posix1e_acl:
465             acls = self.posix1e_acl
466             if len(acls) > 2:
467                 if restore_numeric_ids:
468                     acls[3].applyto(path, posix1e.ACL_TYPE_DEFAULT)
469                 else:
470                     acls[2].applyto(path, posix1e.ACL_TYPE_DEFAULT)
471             if restore_numeric_ids:
472                 acls[1].applyto(path, posix1e.ACL_TYPE_ACCESS)
473             else:
474                 acls[0].applyto(path, posix1e.ACL_TYPE_ACCESS)
475
476
477     ## Linux attributes (lsattr(1), chattr(1))
478
479     def _add_linux_attr(self, path, st):
480         if not get_linux_file_attr: return
481         if stat.S_ISREG(st.st_mode) or stat.S_ISDIR(st.st_mode):
482             try:
483                 attr = get_linux_file_attr(path)
484                 if attr != 0:
485                     self.linux_attr = attr
486             except OSError, e:
487                 if e.errno == errno.EACCES:
488                     add_error('read Linux attr: %s' % e)
489                 elif e.errno == errno.ENOTTY or e.errno == errno.ENOSYS:
490                     # ENOTTY: Function not implemented.
491                     # ENOSYS: Inappropriate ioctl for device.
492                     # Assume filesystem doesn't support attrs.
493                     return
494                 else:
495                     raise
496
497     def _encode_linux_attr(self):
498         if self.linux_attr:
499             return vint.pack('V', self.linux_attr)
500         else:
501             return None
502
503     def _load_linux_attr_rec(self, port):
504         data = vint.read_bvec(port)
505         self.linux_attr = vint.unpack('V', data)[0]
506
507     def _apply_linux_attr_rec(self, path, restore_numeric_ids=False):
508         if self.linux_attr:
509             if not set_linux_file_attr:
510                 add_error("%s: can't restore linuxattrs: "
511                           "linuxattr support missing.\n" % path)
512                 return
513             set_linux_file_attr(path, self.linux_attr)
514
515
516     ## Linux extended attributes (getfattr(1), setfattr(1))
517
518     def _add_linux_xattr(self, path, st):
519         if not xattr: return
520         try:
521             self.linux_xattr = xattr.get_all(path, nofollow=True)
522         except EnvironmentError, e:
523             if e.errno != errno.EOPNOTSUPP:
524                 raise
525
526     def _encode_linux_xattr(self):
527         if self.linux_xattr:
528             result = vint.pack('V', len(self.linux_xattr))
529             for name, value in self.linux_xattr:
530                 result += vint.pack('ss', name, value)
531             return result
532         else:
533             return None
534
535     def _load_linux_xattr_rec(self, file):
536         data = vint.read_bvec(file)
537         memfile = StringIO(data)
538         result = []
539         for i in range(vint.read_vuint(memfile)):
540             key = vint.read_bvec(memfile)
541             value = vint.read_bvec(memfile)
542             result.append((key, value))
543         self.linux_xattr = result
544
545     def _apply_linux_xattr_rec(self, path, restore_numeric_ids=False):
546         if not xattr:
547             if self.linux_xattr:
548                 add_error("%s: can't restore xattr; xattr support missing.\n"
549                           % path)
550             return
551         existing_xattrs = set(xattr.list(path, nofollow=True))
552         if self.linux_xattr:
553             for k, v in self.linux_xattr:
554                 if k not in existing_xattrs \
555                         or v != xattr.get(path, k, nofollow=True):
556                     try:
557                         xattr.set(path, k, v, nofollow=True)
558                     except IOError, e:
559                         if e.errno == errno.EPERM:
560                             raise ApplyError('xattr.set: %s' % e)
561                         else:
562                             raise
563                 existing_xattrs -= frozenset([k])
564             for k in existing_xattrs:
565                 try:
566                     xattr.remove(path, k, nofollow=True)
567                 except IOError, e:
568                     if e.errno == errno.EPERM:
569                         raise ApplyError('xattr.remove: %s' % e)
570                     else:
571                         raise
572
573     def __init__(self):
574         self.mode = None
575         # optional members
576         self.path = None
577         self.size = None
578         self.symlink_target = None
579         self.linux_attr = None
580         self.linux_xattr = None
581         self.posix1e_acl = None
582         self.posix1e_acl_default = None
583
584     def write(self, port, include_path=True):
585         records = include_path and [(_rec_tag_path, self._encode_path())] or []
586         records.extend([(_rec_tag_common, self._encode_common()),
587                         (_rec_tag_symlink_target, self._encode_symlink_target()),
588                         (_rec_tag_posix1e_acl, self._encode_posix1e_acl()),
589                         (_rec_tag_linux_attr, self._encode_linux_attr()),
590                         (_rec_tag_linux_xattr, self._encode_linux_xattr())])
591         for tag, data in records:
592             if data:
593                 vint.write_vuint(port, tag)
594                 vint.write_bvec(port, data)
595         vint.write_vuint(port, _rec_tag_end)
596
597     def encode(self, include_path=True):
598         port = StringIO()
599         self.write(port, include_path)
600         return port.getvalue()
601
602     @staticmethod
603     def read(port):
604         # This method should either return a valid Metadata object,
605         # return None if there was no information at all (just a
606         # _rec_tag_end), throw EOFError if there was nothing at all to
607         # read, or throw an Exception if a valid object could not be
608         # read completely.
609         tag = vint.read_vuint(port)
610         if tag == _rec_tag_end:
611             return None
612         try: # From here on, EOF is an error.
613             result = Metadata()
614             while True: # only exit is error (exception) or _rec_tag_end
615                 if tag == _rec_tag_path:
616                     result._load_path_rec(port)
617                 elif tag == _rec_tag_common:
618                     result._load_common_rec(port)
619                 elif tag == _rec_tag_symlink_target:
620                     result._load_symlink_target_rec(port)
621                 elif tag == _rec_tag_posix1e_acl:
622                     result._load_posix1e_acl_rec(port)
623                 elif tag ==_rec_tag_nfsv4_acl:
624                     result._load_nfsv4_acl_rec(port)
625                 elif tag == _rec_tag_linux_attr:
626                     result._load_linux_attr_rec(port)
627                 elif tag == _rec_tag_linux_xattr:
628                     result._load_linux_xattr_rec(port)
629                 elif tag == _rec_tag_end:
630                     return result
631                 else: # unknown record
632                     vint.skip_bvec(port)
633                 tag = vint.read_vuint(port)
634         except EOFError:
635             raise Exception("EOF while reading Metadata")
636
637     def isdir(self):
638         return stat.S_ISDIR(self.mode)
639
640     def create_path(self, path, create_symlinks=True):
641         self._create_via_common_rec(path, create_symlinks=create_symlinks)
642
643     def apply_to_path(self, path=None, restore_numeric_ids=False):
644         # apply metadata to path -- file must exist
645         if not path:
646             path = self.path
647         if not path:
648             raise Exception('Metadata.apply_to_path() called with no path');
649         if not self._recognized_file_type():
650             add_error('not applying metadata to "%s"' % path
651                       + ' with unrecognized mode "0x%x"\n' % self.mode)
652             return
653         num_ids = restore_numeric_ids
654         try:
655             self._apply_common_rec(path, restore_numeric_ids=num_ids)
656             self._apply_posix1e_acl_rec(path, restore_numeric_ids=num_ids)
657             self._apply_linux_attr_rec(path, restore_numeric_ids=num_ids)
658             self._apply_linux_xattr_rec(path, restore_numeric_ids=num_ids)
659         except ApplyError, e:
660             add_error(e)
661
662
663 def from_path(path, statinfo=None, archive_path=None, save_symlinks=True):
664     result = Metadata()
665     result.path = archive_path
666     st = statinfo or xstat.lstat(path)
667     result.size = st.st_size
668     result._add_common(path, st)
669     if save_symlinks:
670         result._add_symlink_target(path, st)
671     result._add_posix1e_acl(path, st)
672     result._add_linux_attr(path, st)
673     result._add_linux_xattr(path, st)
674     return result
675
676
677 def save_tree(output_file, paths,
678               recurse=False,
679               write_paths=True,
680               save_symlinks=True,
681               xdev=False):
682
683     # Issue top-level rewrite warnings.
684     for path in paths:
685         safe_path = _clean_up_path_for_archive(path)
686         if safe_path != path:
687             log('archiving "%s" as "%s"\n' % (path, safe_path))
688
689     start_dir = os.getcwd()
690     try:
691         for (p, st) in recursive_dirlist(paths, xdev=xdev):
692             dirlist_dir = os.getcwd()
693             os.chdir(start_dir)
694             safe_path = _clean_up_path_for_archive(p)
695             m = from_path(p, statinfo=st, archive_path=safe_path,
696                           save_symlinks=save_symlinks)
697             if verbose:
698                 print >> sys.stderr, m.path
699             m.write(output_file, include_path=write_paths)
700             os.chdir(dirlist_dir)
701     finally:
702         os.chdir(start_dir)
703
704
705 def _set_up_path(meta, create_symlinks=True):
706     # Allow directories to exist as a special case -- might have
707     # been created by an earlier longer path.
708     if meta.isdir():
709         mkdirp(meta.path)
710     else:
711         parent = os.path.dirname(meta.path)
712         if parent:
713             mkdirp(parent)
714         meta.create_path(meta.path, create_symlinks=create_symlinks)
715
716
717 all_fields = frozenset(['path',
718                         'mode',
719                         'link-target',
720                         'rdev',
721                         'size',
722                         'uid',
723                         'gid',
724                         'user',
725                         'group',
726                         'atime',
727                         'mtime',
728                         'ctime',
729                         'linux-attr',
730                         'linux-xattr',
731                         'posix1e-acl'])
732
733
734 def summary_str(meta):
735     mode_val = xstat.mode_str(meta.mode)
736     user_val = meta.user
737     if not user_val:
738         user_val = str(meta.uid)
739     group_val = meta.group
740     if not group_val:
741         group_val = str(meta.gid)
742     size_or_dev_val = '-'
743     if stat.S_ISCHR(meta.mode) or stat.S_ISBLK(meta.mode):
744         size_or_dev_val = '%d,%d' % (os.major(meta.rdev), os.minor(meta.rdev))
745     elif meta.size:
746         size_or_dev_val = meta.size
747     mtime_secs = xstat.fstime_floor_secs(meta.mtime)
748     time_val = time.strftime('%Y-%m-%d %H:%M', time.localtime(mtime_secs))
749     path_val = meta.path or ''
750     if stat.S_ISLNK(meta.mode):
751         path_val += ' -> ' + meta.symlink_target
752     return '%-10s %-11s %11s %16s %s' % (mode_val,
753                                          user_val + "/" + group_val,
754                                          size_or_dev_val,
755                                          time_val,
756                                          path_val)
757
758
759 def detailed_str(meta, fields = None):
760     # FIXME: should optional fields be omitted, or empty i.e. "rdev:
761     # 0", "link-target:", etc.
762     if not fields:
763         fields = all_fields
764
765     result = []
766     if 'path' in fields:
767         path = meta.path or ''
768         result.append('path: ' + path)
769     if 'mode' in fields:
770         result.append('mode: %s (%s)' % (oct(meta.mode),
771                                          xstat.mode_str(meta.mode)))
772     if 'link-target' in fields and stat.S_ISLNK(meta.mode):
773         result.append('link-target: ' + meta.symlink_target)
774     if 'rdev' in fields:
775         if meta.rdev:
776             result.append('rdev: %d,%d' % (os.major(meta.rdev),
777                                            os.minor(meta.rdev)))
778         else:
779             result.append('rdev: 0')
780     if 'size' in fields and meta.size:
781         result.append('size: ' + str(meta.size))
782     if 'uid' in fields:
783         result.append('uid: ' + str(meta.uid))
784     if 'gid' in fields:
785         result.append('gid: ' + str(meta.gid))
786     if 'user' in fields:
787         result.append('user: ' + meta.user)
788     if 'group' in fields:
789         result.append('group: ' + meta.group)
790     if 'atime' in fields:
791         # If we don't have xstat.lutime, that means we have to use
792         # utime(), and utime() has no way to set the mtime/atime of a
793         # symlink.  Thus, the mtime/atime of a symlink is meaningless,
794         # so let's not report it.  (That way scripts comparing
795         # before/after won't trigger.)
796         if xstat.lutime or not stat.S_ISLNK(meta.mode):
797             result.append('atime: ' + xstat.fstime_to_sec_str(meta.atime))
798         else:
799             result.append('atime: 0')
800     if 'mtime' in fields:
801         if xstat.lutime or not stat.S_ISLNK(meta.mode):
802             result.append('mtime: ' + xstat.fstime_to_sec_str(meta.mtime))
803         else:
804             result.append('mtime: 0')
805     if 'ctime' in fields:
806         result.append('ctime: ' + xstat.fstime_to_sec_str(meta.ctime))
807     if 'linux-attr' in fields and meta.linux_attr:
808         result.append('linux-attr: ' + hex(meta.linux_attr))
809     if 'linux-xattr' in fields and meta.linux_xattr:
810         for name, value in meta.linux_xattr:
811             result.append('linux-xattr: %s -> %s' % (name, repr(value)))
812     if 'posix1e-acl' in fields and meta.posix1e_acl and posix1e:
813         flags = posix1e.TEXT_ABBREVIATE
814         if stat.S_ISDIR(meta.mode):
815             acl = meta.posix1e_acl[0]
816             default_acl = meta.posix1e_acl[2]
817             result.append(acl.to_any_text('posix1e-acl: ', '\n', flags))
818             result.append(acl.to_any_text('posix1e-acl-default: ', '\n', flags))
819         else:
820             acl = meta.posix1e_acl[0]
821             result.append(acl.to_any_text('posix1e-acl: ', '\n', flags))
822     return '\n'.join(result)
823
824
825 class _ArchiveIterator:
826     def next(self):
827         try:
828             return Metadata.read(self._file)
829         except EOFError:
830             raise StopIteration()
831
832     def __iter__(self):
833         return self
834
835     def __init__(self, file):
836         self._file = file
837
838
839 def display_archive(file):
840     if verbose > 1:
841         first_item = True
842         for meta in _ArchiveIterator(file):
843             if not first_item:
844                 print
845             print detailed_str(meta)
846             first_item = False
847     elif verbose > 0:
848         for meta in _ArchiveIterator(file):
849             print summary_str(meta)
850     elif verbose == 0:
851         for meta in _ArchiveIterator(file):
852             if not meta.path:
853                 print >> sys.stderr, \
854                     'bup: no metadata path, but asked to only display path (increase verbosity?)'
855                 sys.exit(1)
856             print meta.path
857
858
859 def start_extract(file, create_symlinks=True):
860     for meta in _ArchiveIterator(file):
861         if not meta: # Hit end record.
862             break
863         if verbose:
864             print >> sys.stderr, meta.path
865         xpath = _clean_up_extract_path(meta.path)
866         if not xpath:
867             add_error(Exception('skipping risky path "%s"' % meta.path))
868         else:
869             meta.path = xpath
870             _set_up_path(meta, create_symlinks=create_symlinks)
871
872
873 def finish_extract(file, restore_numeric_ids=False):
874     all_dirs = []
875     for meta in _ArchiveIterator(file):
876         if not meta: # Hit end record.
877             break
878         xpath = _clean_up_extract_path(meta.path)
879         if not xpath:
880             add_error(Exception('skipping risky path "%s"' % dir.path))
881         else:
882             if os.path.isdir(meta.path):
883                 all_dirs.append(meta)
884             else:
885                 if verbose:
886                     print >> sys.stderr, meta.path
887                 meta.apply_to_path(path=xpath,
888                                    restore_numeric_ids=restore_numeric_ids)
889     all_dirs.sort(key = lambda x : len(x.path), reverse=True)
890     for dir in all_dirs:
891         # Don't need to check xpath -- won't be in all_dirs if not OK.
892         xpath = _clean_up_extract_path(dir.path)
893         if verbose:
894             print >> sys.stderr, dir.path
895         dir.apply_to_path(path=xpath, restore_numeric_ids=restore_numeric_ids)
896
897
898 def extract(file, restore_numeric_ids=False, create_symlinks=True):
899     # For now, just store all the directories and handle them last,
900     # longest first.
901     all_dirs = []
902     for meta in _ArchiveIterator(file):
903         if not meta: # Hit end record.
904             break
905         xpath = _clean_up_extract_path(meta.path)
906         if not xpath:
907             add_error(Exception('skipping risky path "%s"' % meta.path))
908         else:
909             meta.path = xpath
910             if verbose:
911                 print >> sys.stderr, '+', meta.path
912             _set_up_path(meta, create_symlinks=create_symlinks)
913             if os.path.isdir(meta.path):
914                 all_dirs.append(meta)
915             else:
916                 if verbose:
917                     print >> sys.stderr, '=', meta.path
918                 meta.apply_to_path(restore_numeric_ids=restore_numeric_ids)
919     all_dirs.sort(key = lambda x : len(x.path), reverse=True)
920     for dir in all_dirs:
921         # Don't need to check xpath -- won't be in all_dirs if not OK.
922         xpath = _clean_up_extract_path(dir.path)
923         if verbose:
924             print >> sys.stderr, '=', xpath
925         # Shouldn't have to check for risky paths here (omitted above).
926         dir.apply_to_path(path=dir.path,
927                           restore_numeric_ids=restore_numeric_ids)