]> arthur.barton.de Git - bup.git/blob - lib/bup/metadata.py
87fd10b84a84383b63c075f0467767bba33ac0c5
[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         if not posix1e:
463             if self.posix1e_acl:
464                 add_error("%s: can't restore ACLs; posix1e support missing.\n"
465                           % path)
466             return
467         if self.posix1e_acl:
468             acls = self.posix1e_acl
469             if len(acls) > 2:
470                 if restore_numeric_ids:
471                     acls[3].applyto(path, posix1e.ACL_TYPE_DEFAULT)
472                 else:
473                     acls[2].applyto(path, posix1e.ACL_TYPE_DEFAULT)
474             if restore_numeric_ids:
475                 acls[1].applyto(path, posix1e.ACL_TYPE_ACCESS)
476             else:
477                 acls[0].applyto(path, posix1e.ACL_TYPE_ACCESS)
478
479
480     ## Linux attributes (lsattr(1), chattr(1))
481
482     def _add_linux_attr(self, path, st):
483         if not get_linux_file_attr: return
484         if stat.S_ISREG(st.st_mode) or stat.S_ISDIR(st.st_mode):
485             try:
486                 attr = get_linux_file_attr(path)
487                 if attr != 0:
488                     self.linux_attr = attr
489             except OSError, e:
490                 if e.errno == errno.EACCES:
491                     add_error('read Linux attr: %s' % e)
492                 elif e.errno == errno.ENOTTY or e.errno == errno.ENOSYS:
493                     # ENOTTY: Function not implemented.
494                     # ENOSYS: Inappropriate ioctl for device.
495                     # Assume filesystem doesn't support attrs.
496                     return
497                 else:
498                     raise
499
500     def _encode_linux_attr(self):
501         if self.linux_attr:
502             return vint.pack('V', self.linux_attr)
503         else:
504             return None
505
506     def _load_linux_attr_rec(self, port):
507         data = vint.read_bvec(port)
508         self.linux_attr = vint.unpack('V', data)[0]
509
510     def _apply_linux_attr_rec(self, path, restore_numeric_ids=False):
511         if self.linux_attr:
512             if not set_linux_file_attr:
513                 add_error("%s: can't restore linuxattrs: "
514                           "linuxattr support missing.\n" % path)
515                 return
516             set_linux_file_attr(path, self.linux_attr)
517
518
519     ## Linux extended attributes (getfattr(1), setfattr(1))
520
521     def _add_linux_xattr(self, path, st):
522         if not xattr: return
523         try:
524             self.linux_xattr = xattr.get_all(path, nofollow=True)
525         except EnvironmentError, e:
526             if e.errno != errno.EOPNOTSUPP:
527                 raise
528
529     def _encode_linux_xattr(self):
530         if self.linux_xattr:
531             result = vint.pack('V', len(self.linux_xattr))
532             for name, value in self.linux_xattr:
533                 result += vint.pack('ss', name, value)
534             return result
535         else:
536             return None
537
538     def _load_linux_xattr_rec(self, file):
539         data = vint.read_bvec(file)
540         memfile = StringIO(data)
541         result = []
542         for i in range(vint.read_vuint(memfile)):
543             key = vint.read_bvec(memfile)
544             value = vint.read_bvec(memfile)
545             result.append((key, value))
546         self.linux_xattr = result
547
548     def _apply_linux_xattr_rec(self, path, restore_numeric_ids=False):
549         if not xattr:
550             if self.linux_xattr:
551                 add_error("%s: can't restore xattr; xattr support missing.\n"
552                           % path)
553             return
554         existing_xattrs = set(xattr.list(path, nofollow=True))
555         if self.linux_xattr:
556             for k, v in self.linux_xattr:
557                 if k not in existing_xattrs \
558                         or v != xattr.get(path, k, nofollow=True):
559                     try:
560                         xattr.set(path, k, v, nofollow=True)
561                     except IOError, e:
562                         if e.errno == errno.EPERM:
563                             raise ApplyError('xattr.set: %s' % e)
564                         else:
565                             raise
566                 existing_xattrs -= frozenset([k])
567             for k in existing_xattrs:
568                 try:
569                     xattr.remove(path, k, nofollow=True)
570                 except IOError, e:
571                     if e.errno == errno.EPERM:
572                         raise ApplyError('xattr.remove: %s' % e)
573                     else:
574                         raise
575
576     def __init__(self):
577         self.mode = None
578         # optional members
579         self.path = None
580         self.size = None
581         self.symlink_target = None
582         self.linux_attr = None
583         self.linux_xattr = None
584         self.posix1e_acl = None
585         self.posix1e_acl_default = None
586
587     def write(self, port, include_path=True):
588         records = include_path and [(_rec_tag_path, self._encode_path())] or []
589         records.extend([(_rec_tag_common, self._encode_common()),
590                         (_rec_tag_symlink_target, self._encode_symlink_target()),
591                         (_rec_tag_posix1e_acl, self._encode_posix1e_acl()),
592                         (_rec_tag_linux_attr, self._encode_linux_attr()),
593                         (_rec_tag_linux_xattr, self._encode_linux_xattr())])
594         for tag, data in records:
595             if data:
596                 vint.write_vuint(port, tag)
597                 vint.write_bvec(port, data)
598         vint.write_vuint(port, _rec_tag_end)
599
600     def encode(self, include_path=True):
601         port = StringIO()
602         self.write(port, include_path)
603         return port.getvalue()
604
605     @staticmethod
606     def read(port):
607         # This method should either return a valid Metadata object,
608         # return None if there was no information at all (just a
609         # _rec_tag_end), throw EOFError if there was nothing at all to
610         # read, or throw an Exception if a valid object could not be
611         # read completely.
612         tag = vint.read_vuint(port)
613         if tag == _rec_tag_end:
614             return None
615         try: # From here on, EOF is an error.
616             result = Metadata()
617             while True: # only exit is error (exception) or _rec_tag_end
618                 if tag == _rec_tag_path:
619                     result._load_path_rec(port)
620                 elif tag == _rec_tag_common:
621                     result._load_common_rec(port)
622                 elif tag == _rec_tag_symlink_target:
623                     result._load_symlink_target_rec(port)
624                 elif tag == _rec_tag_posix1e_acl:
625                     result._load_posix1e_acl_rec(port)
626                 elif tag ==_rec_tag_nfsv4_acl:
627                     result._load_nfsv4_acl_rec(port)
628                 elif tag == _rec_tag_linux_attr:
629                     result._load_linux_attr_rec(port)
630                 elif tag == _rec_tag_linux_xattr:
631                     result._load_linux_xattr_rec(port)
632                 elif tag == _rec_tag_end:
633                     return result
634                 else: # unknown record
635                     vint.skip_bvec(port)
636                 tag = vint.read_vuint(port)
637         except EOFError:
638             raise Exception("EOF while reading Metadata")
639
640     def isdir(self):
641         return stat.S_ISDIR(self.mode)
642
643     def create_path(self, path, create_symlinks=True):
644         self._create_via_common_rec(path, create_symlinks=create_symlinks)
645
646     def apply_to_path(self, path=None, restore_numeric_ids=False):
647         # apply metadata to path -- file must exist
648         if not path:
649             path = self.path
650         if not path:
651             raise Exception('Metadata.apply_to_path() called with no path');
652         if not self._recognized_file_type():
653             add_error('not applying metadata to "%s"' % path
654                       + ' with unrecognized mode "0x%x"\n' % self.mode)
655             return
656         num_ids = restore_numeric_ids
657         try:
658             self._apply_common_rec(path, restore_numeric_ids=num_ids)
659             self._apply_posix1e_acl_rec(path, restore_numeric_ids=num_ids)
660             self._apply_linux_attr_rec(path, restore_numeric_ids=num_ids)
661             self._apply_linux_xattr_rec(path, restore_numeric_ids=num_ids)
662         except ApplyError, e:
663             add_error(e)
664
665
666 def from_path(path, statinfo=None, archive_path=None, save_symlinks=True):
667     result = Metadata()
668     result.path = archive_path
669     st = statinfo or xstat.lstat(path)
670     result.size = st.st_size
671     result._add_common(path, st)
672     if save_symlinks:
673         result._add_symlink_target(path, st)
674     result._add_posix1e_acl(path, st)
675     result._add_linux_attr(path, st)
676     result._add_linux_xattr(path, st)
677     return result
678
679
680 def save_tree(output_file, paths,
681               recurse=False,
682               write_paths=True,
683               save_symlinks=True,
684               xdev=False):
685
686     # Issue top-level rewrite warnings.
687     for path in paths:
688         safe_path = _clean_up_path_for_archive(path)
689         if safe_path != path:
690             log('archiving "%s" as "%s"\n' % (path, safe_path))
691
692     start_dir = os.getcwd()
693     try:
694         for (p, st) in recursive_dirlist(paths, xdev=xdev):
695             dirlist_dir = os.getcwd()
696             os.chdir(start_dir)
697             safe_path = _clean_up_path_for_archive(p)
698             m = from_path(p, statinfo=st, archive_path=safe_path,
699                           save_symlinks=save_symlinks)
700             if verbose:
701                 print >> sys.stderr, m.path
702             m.write(output_file, include_path=write_paths)
703             os.chdir(dirlist_dir)
704     finally:
705         os.chdir(start_dir)
706
707
708 def _set_up_path(meta, create_symlinks=True):
709     # Allow directories to exist as a special case -- might have
710     # been created by an earlier longer path.
711     if meta.isdir():
712         mkdirp(meta.path)
713     else:
714         parent = os.path.dirname(meta.path)
715         if parent:
716             mkdirp(parent)
717         meta.create_path(meta.path, create_symlinks=create_symlinks)
718
719
720 all_fields = frozenset(['path',
721                         'mode',
722                         'link-target',
723                         'rdev',
724                         'size',
725                         'uid',
726                         'gid',
727                         'user',
728                         'group',
729                         'atime',
730                         'mtime',
731                         'ctime',
732                         'linux-attr',
733                         'linux-xattr',
734                         'posix1e-acl'])
735
736
737 def summary_str(meta):
738     mode_val = xstat.mode_str(meta.mode)
739     user_val = meta.user
740     if not user_val:
741         user_val = str(meta.uid)
742     group_val = meta.group
743     if not group_val:
744         group_val = str(meta.gid)
745     size_or_dev_val = '-'
746     if stat.S_ISCHR(meta.mode) or stat.S_ISBLK(meta.mode):
747         size_or_dev_val = '%d,%d' % (os.major(meta.rdev), os.minor(meta.rdev))
748     elif meta.size:
749         size_or_dev_val = meta.size
750     mtime_secs = xstat.fstime_floor_secs(meta.mtime)
751     time_val = time.strftime('%Y-%m-%d %H:%M', time.localtime(mtime_secs))
752     path_val = meta.path or ''
753     if stat.S_ISLNK(meta.mode):
754         path_val += ' -> ' + meta.symlink_target
755     return '%-10s %-11s %11s %16s %s' % (mode_val,
756                                          user_val + "/" + group_val,
757                                          size_or_dev_val,
758                                          time_val,
759                                          path_val)
760
761
762 def detailed_str(meta, fields = None):
763     # FIXME: should optional fields be omitted, or empty i.e. "rdev:
764     # 0", "link-target:", etc.
765     if not fields:
766         fields = all_fields
767
768     result = []
769     if 'path' in fields:
770         path = meta.path or ''
771         result.append('path: ' + path)
772     if 'mode' in fields:
773         result.append('mode: %s (%s)' % (oct(meta.mode),
774                                          xstat.mode_str(meta.mode)))
775     if 'link-target' in fields and stat.S_ISLNK(meta.mode):
776         result.append('link-target: ' + meta.symlink_target)
777     if 'rdev' in fields:
778         if meta.rdev:
779             result.append('rdev: %d,%d' % (os.major(meta.rdev),
780                                            os.minor(meta.rdev)))
781         else:
782             result.append('rdev: 0')
783     if 'size' in fields and meta.size:
784         result.append('size: ' + str(meta.size))
785     if 'uid' in fields:
786         result.append('uid: ' + str(meta.uid))
787     if 'gid' in fields:
788         result.append('gid: ' + str(meta.gid))
789     if 'user' in fields:
790         result.append('user: ' + meta.user)
791     if 'group' in fields:
792         result.append('group: ' + meta.group)
793     if 'atime' in fields:
794         # If we don't have xstat.lutime, that means we have to use
795         # utime(), and utime() has no way to set the mtime/atime of a
796         # symlink.  Thus, the mtime/atime of a symlink is meaningless,
797         # so let's not report it.  (That way scripts comparing
798         # before/after won't trigger.)
799         if xstat.lutime or not stat.S_ISLNK(meta.mode):
800             result.append('atime: ' + xstat.fstime_to_sec_str(meta.atime))
801         else:
802             result.append('atime: 0')
803     if 'mtime' in fields:
804         if xstat.lutime or not stat.S_ISLNK(meta.mode):
805             result.append('mtime: ' + xstat.fstime_to_sec_str(meta.mtime))
806         else:
807             result.append('mtime: 0')
808     if 'ctime' in fields:
809         result.append('ctime: ' + xstat.fstime_to_sec_str(meta.ctime))
810     if 'linux-attr' in fields and meta.linux_attr:
811         result.append('linux-attr: ' + hex(meta.linux_attr))
812     if 'linux-xattr' in fields and meta.linux_xattr:
813         for name, value in meta.linux_xattr:
814             result.append('linux-xattr: %s -> %s' % (name, repr(value)))
815     if 'posix1e-acl' in fields and meta.posix1e_acl and posix1e:
816         flags = posix1e.TEXT_ABBREVIATE
817         if stat.S_ISDIR(meta.mode):
818             acl = meta.posix1e_acl[0]
819             default_acl = meta.posix1e_acl[2]
820             result.append(acl.to_any_text('posix1e-acl: ', '\n', flags))
821             result.append(acl.to_any_text('posix1e-acl-default: ', '\n', flags))
822         else:
823             acl = meta.posix1e_acl[0]
824             result.append(acl.to_any_text('posix1e-acl: ', '\n', flags))
825     return '\n'.join(result)
826
827
828 class _ArchiveIterator:
829     def next(self):
830         try:
831             return Metadata.read(self._file)
832         except EOFError:
833             raise StopIteration()
834
835     def __iter__(self):
836         return self
837
838     def __init__(self, file):
839         self._file = file
840
841
842 def display_archive(file):
843     if verbose > 1:
844         first_item = True
845         for meta in _ArchiveIterator(file):
846             if not first_item:
847                 print
848             print detailed_str(meta)
849             first_item = False
850     elif verbose > 0:
851         for meta in _ArchiveIterator(file):
852             print summary_str(meta)
853     elif verbose == 0:
854         for meta in _ArchiveIterator(file):
855             if not meta.path:
856                 print >> sys.stderr, \
857                     'bup: no metadata path, but asked to only display path (increase verbosity?)'
858                 sys.exit(1)
859             print meta.path
860
861
862 def start_extract(file, create_symlinks=True):
863     for meta in _ArchiveIterator(file):
864         if not meta: # Hit end record.
865             break
866         if verbose:
867             print >> sys.stderr, meta.path
868         xpath = _clean_up_extract_path(meta.path)
869         if not xpath:
870             add_error(Exception('skipping risky path "%s"' % meta.path))
871         else:
872             meta.path = xpath
873             _set_up_path(meta, create_symlinks=create_symlinks)
874
875
876 def finish_extract(file, restore_numeric_ids=False):
877     all_dirs = []
878     for meta in _ArchiveIterator(file):
879         if not meta: # Hit end record.
880             break
881         xpath = _clean_up_extract_path(meta.path)
882         if not xpath:
883             add_error(Exception('skipping risky path "%s"' % dir.path))
884         else:
885             if os.path.isdir(meta.path):
886                 all_dirs.append(meta)
887             else:
888                 if verbose:
889                     print >> sys.stderr, meta.path
890                 meta.apply_to_path(path=xpath,
891                                    restore_numeric_ids=restore_numeric_ids)
892     all_dirs.sort(key = lambda x : len(x.path), reverse=True)
893     for dir in all_dirs:
894         # Don't need to check xpath -- won't be in all_dirs if not OK.
895         xpath = _clean_up_extract_path(dir.path)
896         if verbose:
897             print >> sys.stderr, dir.path
898         dir.apply_to_path(path=xpath, restore_numeric_ids=restore_numeric_ids)
899
900
901 def extract(file, restore_numeric_ids=False, create_symlinks=True):
902     # For now, just store all the directories and handle them last,
903     # longest first.
904     all_dirs = []
905     for meta in _ArchiveIterator(file):
906         if not meta: # Hit end record.
907             break
908         xpath = _clean_up_extract_path(meta.path)
909         if not xpath:
910             add_error(Exception('skipping risky path "%s"' % meta.path))
911         else:
912             meta.path = xpath
913             if verbose:
914                 print >> sys.stderr, '+', meta.path
915             _set_up_path(meta, create_symlinks=create_symlinks)
916             if os.path.isdir(meta.path):
917                 all_dirs.append(meta)
918             else:
919                 if verbose:
920                     print >> sys.stderr, '=', meta.path
921                 meta.apply_to_path(restore_numeric_ids=restore_numeric_ids)
922     all_dirs.sort(key = lambda x : len(x.path), reverse=True)
923     for dir in all_dirs:
924         # Don't need to check xpath -- won't be in all_dirs if not OK.
925         xpath = _clean_up_extract_path(dir.path)
926         if verbose:
927             print >> sys.stderr, '=', xpath
928         # Shouldn't have to check for risky paths here (omitted above).
929         dir.apply_to_path(path=dir.path,
930                           restore_numeric_ids=restore_numeric_ids)