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