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