1 """Metadata read/write support for bup."""
3 # Copyright (C) 2010 Rob Browning
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, pwd, grp, struct, re
8 from cStringIO import StringIO
10 from bup.drecurse import recursive_dirlist
11 from bup.helpers import add_error, mkdirp, log
12 from bup.xstat import utime, lutime, lstat, FSTime
13 import bup._helpers as _helpers
18 log('Warning: Linux xattr support missing; install python-pyxattr.\n')
23 except AttributeError:
24 log('Warning: python-xattr module is too old; '
25 'install python-pyxattr instead.\n')
30 log('Warning: POSIX ACL support missing; install python-pylibacl.\n')
32 if _helpers.get_linux_file_attr:
33 from bup._helpers import get_linux_file_attr, set_linux_file_attr
35 # WARNING: the metadata encoding is *not* stable yet. Caveat emptor!
37 # Q: Consider hardlink support?
38 # Q: Is it OK to store raw linux attr (chattr) flags?
39 # Q: Can anything other than S_ISREG(x) or S_ISDIR(x) support posix1e ACLs?
40 # Q: Is the application of posix1e has_extended() correct?
41 # Q: Is one global --numeric-ids argument sufficient?
42 # Q: Do nfsv4 acls trump posix1e acls? (seems likely)
43 # Q: Add support for crtime -- ntfs, and (only internally?) ext*?
45 # FIXME: Fix relative/abs path detection/stripping wrt other platforms.
46 # FIXME: Add nfsv4 acl handling - see nfs4-acl-tools.
47 # FIXME: Consider other entries mentioned in stat(2) (S_IFDOOR, etc.).
48 # FIXME: Consider pack('vvvvsss', ...) optimization.
49 # FIXME: Consider caching users/groups.
53 # osx (varies between hfs and hfs+):
54 # type - regular dir char block fifo socket ...
55 # perms - rwxrwxrwxsgt
56 # times - ctime atime mtime
59 # hard-link-info (hfs+ only)
62 # attributes-osx see chflags
68 # type - regular dir ...
69 # times - creation, modification, posix change, access
72 # attributes - see attrib
74 # forks (alternate data streams)
78 # type - regular dir ...
79 # perms - rwxrwxrwx (maybe - see wikipedia)
80 # times - creation, modification, access
81 # attributes - see attrib
85 _have_lchmod = hasattr(os, 'lchmod')
88 def _clean_up_path_for_archive(p):
89 # Not the most efficient approach.
92 # Take everything after any '/../'.
93 pos = result.rfind('/../')
95 result = result[result.rfind('/../') + 4:]
97 # Take everything after any remaining '../'.
98 if result.startswith("../"):
101 # Remove any '/./' sequences.
102 pos = result.find('/./')
104 result = result[0:pos] + '/' + result[pos + 3:]
105 pos = result.find('/./')
107 # Remove any leading '/'s.
108 result = result.lstrip('/')
110 # Replace '//' with '/' everywhere.
111 pos = result.find('//')
113 result = result[0:pos] + '/' + result[pos + 2:]
114 pos = result.find('//')
116 # Take everything after any remaining './'.
117 if result.startswith('./'):
120 # Take everything before any remaining '/.'.
121 if result.endswith('/.'):
124 if result == '' or result.endswith('/..'):
131 if p.startswith('/'):
133 if p.find('/../') != -1:
135 if p.startswith('../'):
137 if p.endswith('/..'):
142 def _clean_up_extract_path(p):
143 result = p.lstrip('/')
146 elif _risky_path(result):
152 # These tags are currently conceptually private to Metadata, and they
153 # must be unique, and must *never* be changed.
156 _rec_tag_common = 2 # times, owner, group, type, perms, etc.
157 _rec_tag_symlink_target = 3
158 _rec_tag_posix1e_acl = 4 # getfacl(1), setfacl(1), etc.
159 _rec_tag_nfsv4_acl = 5 # intended to supplant posix1e acls?
160 _rec_tag_linux_attr = 6 # lsattr(1) chattr(1)
161 _rec_tag_linux_xattr = 7 # getfattr(1) setfattr(1)
164 class ApplyError(Exception):
165 # Thrown when unable to apply any given bit of metadata to a path.
170 # Metadata is stored as a sequence of tagged binary records. Each
171 # record will have some subset of add, encode, load, create, and
172 # apply methods, i.e. _add_foo...
176 # Timestamps are (sec, ns), relative to 1970-01-01 00:00:00, ns
177 # must be non-negative and < 10**9.
179 def _add_common(self, path, st):
180 self.mode = st.st_mode
183 self.rdev = st.st_rdev
184 self.atime = st.st_atime
185 self.mtime = st.st_mtime
186 self.ctime = st.st_ctime
187 self.owner = self.group = ''
189 self.owner = pwd.getpwuid(st.st_uid)[0]
191 add_error("no user name for id %s '%s'" % (st.st_gid, path))
193 self.group = grp.getgrgid(st.st_gid)[0]
195 add_error("no group name for id %s '%s'" % (st.st_gid, path))
197 def _encode_common(self):
198 atime = self.atime.to_timespec()
199 mtime = self.mtime.to_timespec()
200 ctime = self.ctime.to_timespec()
201 result = vint.pack('VVsVsVvVvVvV',
216 def _load_common_rec(self, port):
217 data = vint.read_bvec(port)
229 ctime_ns) = vint.unpack('VVsVsVvVvVvV', data)
230 self.atime = FSTime.from_timespec((self.atime, atime_ns))
231 self.mtime = FSTime.from_timespec((self.mtime, mtime_ns))
232 self.ctime = FSTime.from_timespec((self.ctime, ctime_ns))
234 def _create_via_common_rec(self, path, create_symlinks=True):
235 # If the path already exists and is a dir, try rmdir.
236 # If the path already exists and is anything else, try unlink.
241 if e.errno != errno.ENOENT:
244 if stat.S_ISDIR(st.st_mode):
248 if e.errno == errno.ENOTEMPTY:
249 msg = 'refusing to overwrite non-empty dir' + path
255 if stat.S_ISREG(self.mode):
256 os.mknod(path, 0600 | stat.S_IFREG)
257 elif stat.S_ISDIR(self.mode):
259 elif stat.S_ISCHR(self.mode):
260 os.mknod(path, 0600 | stat.S_IFCHR, self.rdev)
261 elif stat.S_ISBLK(self.mode):
262 os.mknod(path, 0600 | stat.S_IFBLK, self.rdev)
263 elif stat.S_ISFIFO(self.mode):
264 os.mknod(path, 0600 | stat.S_IFIFO)
265 elif stat.S_ISLNK(self.mode):
266 if self.symlink_target and create_symlinks:
267 os.symlink(self.symlink_target, path)
268 # FIXME: S_ISDOOR, S_IFMPB, S_IFCMP, S_IFNWK, ... see stat(2).
269 # Otherwise, do nothing.
271 def _apply_common_rec(self, path, restore_numeric_ids=False):
272 # FIXME: S_ISDOOR, S_IFMPB, S_IFCMP, S_IFNWK, ... see stat(2).
273 # EACCES errors at this stage are fatal for the current path.
274 if stat.S_ISLNK(self.mode):
276 lutime(path, (self.atime, self.mtime))
278 if e.errno == errno.EACCES:
279 raise ApplyError('lutime: %s' % e)
284 utime(path, (self.atime, self.mtime))
286 if e.errno == errno.EACCES:
287 raise ApplyError('utime: %s' % e)
291 # Don't try to restore owner unless we're root, and even
292 # if asked, don't try to restore the owner or group if
293 # it doesn't exist in the system db.
296 if not restore_numeric_ids:
299 add_error('ignoring missing owner for "%s"\n' % path)
301 if os.geteuid() != 0:
302 uid = -1 # Not root; assume we can't change owner.
305 uid = pwd.getpwnam(self.owner)[2]
308 fmt = 'ignoring unknown owner %s for "%s"\n'
309 add_error(fmt % (self.owner, path))
312 add_error('ignoring missing group for "%s"\n' % path)
315 gid = grp.getgrnam(self.group)[2]
318 add_error('ignoring unknown group %s for "%s"\n'
319 % (self.group, path))
322 os.lchown(path, uid, gid)
324 if e.errno == errno.EPERM:
325 add_error('lchown: %s' % e)
330 os.lchmod(path, stat.S_IMODE(self.mode))
331 elif not stat.S_ISLNK(self.mode):
332 os.chmod(path, stat.S_IMODE(self.mode))
337 def _encode_path(self):
339 return vint.pack('s', self.path)
343 def _load_path_rec(self, port):
344 self.path = vint.unpack('s', vint.read_bvec(port))[0]
349 def _add_symlink_target(self, path, st):
351 if stat.S_ISLNK(st.st_mode):
352 self.symlink_target = os.readlink(path)
354 add_error('readlink: %s', e)
356 def _encode_symlink_target(self):
357 return self.symlink_target
359 def _load_symlink_target_rec(self, port):
360 self.symlink_target = vint.read_bvec(port)
363 ## POSIX1e ACL records
365 # Recorded as a list:
366 # [txt_id_acl, num_id_acl]
367 # or, if a directory:
368 # [txt_id_acl, num_id_acl, txt_id_default_acl, num_id_default_acl]
369 # The numeric/text distinction only matters when reading/restoring
371 def _add_posix1e_acl(self, path, st):
372 if not posix1e: return
373 if not stat.S_ISLNK(st.st_mode):
375 if posix1e.has_extended(path):
376 acl = posix1e.ACL(file=path)
377 self.posix1e_acl = [acl, acl] # txt and num are the same
378 if stat.S_ISDIR(st.st_mode):
379 acl = posix1e.ACL(filedef=path)
380 self.posix1e_acl.extend([acl, acl])
381 except EnvironmentError, e:
382 if e.errno != errno.EOPNOTSUPP:
385 def _encode_posix1e_acl(self):
386 # Encode as two strings (w/default ACL string possibly empty).
388 acls = self.posix1e_acl
389 txt_flags = posix1e.TEXT_ABBREVIATE
390 num_flags = posix1e.TEXT_ABBREVIATE | posix1e.TEXT_NUMERIC_IDS
391 acl_reps = [acls[0].to_any_text('', '\n', txt_flags),
392 acls[1].to_any_text('', '\n', num_flags)]
396 acl_reps.append(acls[2].to_any_text('', '\n', txt_flags))
397 acl_reps.append(acls[3].to_any_text('', '\n', num_flags))
398 return vint.pack('ssss',
399 acl_reps[0], acl_reps[1], acl_reps[2], acl_reps[3])
403 def _load_posix1e_acl_rec(self, port):
404 data = vint.read_bvec(port)
405 acl_reps = vint.unpack('ssss', data)
406 if acl_reps[2] == '':
407 acl_reps = acl_reps[:2]
408 self.posix1e_acl = [posix1e.ACL(text=x) for x in acl_reps]
410 def _apply_posix1e_acl_rec(self, path, restore_numeric_ids=False):
413 add_error("%s: can't restore ACLs; posix1e support missing.\n"
417 acls = self.posix1e_acl
419 if restore_numeric_ids:
420 acls[3].applyto(path, posix1e.ACL_TYPE_DEFAULT)
422 acls[2].applyto(path, posix1e.ACL_TYPE_DEFAULT)
423 if restore_numeric_ids:
424 acls[1].applyto(path, posix1e.ACL_TYPE_ACCESS)
426 acls[0].applyto(path, posix1e.ACL_TYPE_ACCESS)
429 ## Linux attributes (lsattr(1), chattr(1))
431 def _add_linux_attr(self, path, st):
432 if stat.S_ISREG(st.st_mode) or stat.S_ISDIR(st.st_mode):
434 attr = get_linux_file_attr(path)
436 self.linux_attr = attr
438 if e.errno == errno.EACCES:
439 add_error('read Linux attr: %s' % e)
440 elif e.errno == errno.ENOTTY: # Inappropriate ioctl for device.
441 add_error('read Linux attr: %s' % e)
445 def _encode_linux_attr(self):
447 return vint.pack('V', self.linux_attr)
451 def _load_linux_attr_rec(self, port):
452 data = vint.read_bvec(port)
453 self.linux_attr = vint.unpack('V', data)[0]
455 def _apply_linux_attr_rec(self, path, restore_numeric_ids=False):
457 set_linux_file_attr(path, self.linux_attr)
460 ## Linux extended attributes (getfattr(1), setfattr(1))
462 def _add_linux_xattr(self, path, st):
465 self.linux_xattr = xattr.get_all(path, nofollow=True)
466 except EnvironmentError, e:
467 if e.errno != errno.EOPNOTSUPP:
470 def _encode_linux_xattr(self):
472 result = vint.pack('V', len(self.linux_xattr))
473 for name, value in self.linux_xattr:
474 result += vint.pack('ss', name, value)
479 def _load_linux_xattr_rec(self, file):
480 data = vint.read_bvec(file)
481 memfile = StringIO(data)
483 for i in range(vint.read_vuint(memfile)):
484 key = vint.read_bvec(memfile)
485 value = vint.read_bvec(memfile)
486 result.append((key, value))
487 self.linux_xattr = result
489 def _apply_linux_xattr_rec(self, path, restore_numeric_ids=False):
492 add_error("%s: can't restore xattr; xattr support missing.\n"
495 existing_xattrs = set(xattr.list(path, nofollow=True))
497 for k, v in self.linux_xattr:
498 if k not in existing_xattrs \
499 or v != xattr.get(path, k, nofollow=True):
501 xattr.set(path, k, v, nofollow=True)
503 if e.errno == errno.EPERM:
504 raise ApplyError('xattr.set: %s' % e)
507 existing_xattrs -= frozenset([k])
508 for k in existing_xattrs:
510 xattr.remove(path, k, nofollow=True)
512 if e.errno == errno.EPERM:
513 raise ApplyError('xattr.remove: %s' % e)
520 self.symlink_target = None
521 self.linux_attr = None
522 self.linux_xattr = None
523 self.posix1e_acl = None
524 self.posix1e_acl_default = None
526 def write(self, port, include_path=True):
527 records = [(_rec_tag_path, self._encode_path())] if include_path else []
528 records.extend([(_rec_tag_common, self._encode_common()),
529 (_rec_tag_symlink_target, self._encode_symlink_target()),
530 (_rec_tag_posix1e_acl, self._encode_posix1e_acl()),
531 (_rec_tag_linux_attr, self._encode_linux_attr()),
532 (_rec_tag_linux_xattr, self._encode_linux_xattr())])
533 for tag, data in records:
535 vint.write_vuint(port, tag)
536 vint.write_bvec(port, data)
537 vint.write_vuint(port, _rec_tag_end)
541 # This method should either: return a valid Metadata object;
542 # throw EOFError if there was nothing at all to read; throw an
543 # Exception if a valid object could not be read completely.
544 tag = vint.read_vuint(port)
545 try: # From here on, EOF is an error.
547 while True: # only exit is error (exception) or _rec_tag_end
548 if tag == _rec_tag_path:
549 result._load_path_rec(port)
550 elif tag == _rec_tag_common:
551 result._load_common_rec(port)
552 elif tag == _rec_tag_symlink_target:
553 result._load_symlink_target_rec(port)
554 elif tag == _rec_tag_posix1e_acl:
555 result._load_posix1e_acl_rec(port)
556 elif tag ==_rec_tag_nfsv4_acl:
557 result._load_nfsv4_acl_rec(port)
558 elif tag == _rec_tag_linux_attr:
559 result._load_linux_attr_rec(port)
560 elif tag == _rec_tag_linux_xattr:
561 result._load_linux_xattr_rec(port)
562 elif tag == _rec_tag_end:
564 else: # unknown record
566 tag = vint.read_vuint(port)
568 raise Exception("EOF while reading Metadata")
571 return stat.S_ISDIR(self.mode)
573 def create_path(self, path, create_symlinks=True):
574 self._create_via_common_rec(path, create_symlinks=create_symlinks)
576 def apply_to_path(self, path=None, restore_numeric_ids=False):
577 # apply metadata to path -- file must exist
581 raise Exception('Metadata.apply_to_path() called with no path');
582 num_ids = restore_numeric_ids
584 self._apply_common_rec(path, restore_numeric_ids=num_ids)
585 self._apply_posix1e_acl_rec(path, restore_numeric_ids=num_ids)
586 self._apply_linux_attr_rec(path, restore_numeric_ids=num_ids)
587 self._apply_linux_xattr_rec(path, restore_numeric_ids=num_ids)
588 except ApplyError, e:
592 def from_path(path, statinfo=None, archive_path=None, save_symlinks=True):
594 result.path = archive_path
595 st = statinfo if statinfo else lstat(path)
596 result._add_common(path, st)
598 result._add_symlink_target(path, st)
599 result._add_posix1e_acl(path, st)
600 result._add_linux_attr(path, st)
601 result._add_linux_xattr(path, st)
605 def save_tree(output_file, paths,
611 # Issue top-level rewrite warnings.
613 safe_path = _clean_up_path_for_archive(path)
614 if safe_path != path:
615 log('archiving "%s" as "%s"\n' % (path, safe_path))
617 start_dir = os.getcwd()
619 for (p, st) in recursive_dirlist(paths, xdev=xdev):
620 dirlist_dir = os.getcwd()
622 safe_path = _clean_up_path_for_archive(p)
623 m = from_path(p, statinfo=st, archive_path=safe_path,
624 save_symlinks=save_symlinks)
626 print >> sys.stderr, m.path
627 m.write(output_file, include_path=write_paths)
628 os.chdir(dirlist_dir)
633 def _set_up_path(meta, create_symlinks=True):
634 # Allow directories to exist as a special case -- might have
635 # been created by an earlier longer path.
639 parent = os.path.dirname(meta.path)
642 meta.create_path(meta.path, create_symlinks=create_symlinks)
645 class _ArchiveIterator:
648 return Metadata.read(self._file)
650 raise StopIteration()
655 def __init__(self, file):
659 def display_archive(file):
660 for meta in _ArchiveIterator(file):
662 print meta.path # FIXME
667 def start_extract(file, create_symlinks=True):
668 for meta in _ArchiveIterator(file):
670 print >> sys.stderr, meta.path
671 xpath = _clean_up_extract_path(meta.path)
673 add_error(Exception('skipping risky path "%s"' % meta.path))
676 _set_up_path(meta, create_symlinks=create_symlinks)
679 def finish_extract(file, restore_numeric_ids=False):
681 for meta in _ArchiveIterator(file):
682 xpath = _clean_up_extract_path(meta.path)
684 add_error(Exception('skipping risky path "%s"' % dir.path))
686 if os.path.isdir(meta.path):
687 all_dirs.append(meta)
690 print >> sys.stderr, meta.path
691 meta.apply_to_path(path=xpath,
692 restore_numeric_ids=restore_numeric_ids)
693 all_dirs.sort(key = lambda x : len(x.path), reverse=True)
695 # Don't need to check xpath -- won't be in all_dirs if not OK.
696 xpath = _clean_up_extract_path(dir.path)
698 print >> sys.stderr, dir.path
699 dir.apply_to_path(path=xpath, restore_numeric_ids=restore_numeric_ids)
702 def extract(file, restore_numeric_ids=False, create_symlinks=True):
703 # For now, just store all the directories and handle them last,
706 for meta in _ArchiveIterator(file):
707 xpath = _clean_up_extract_path(meta.path)
709 add_error(Exception('skipping risky path "%s"' % meta.path))
713 print >> sys.stderr, '+', meta.path
714 _set_up_path(meta, create_symlinks=create_symlinks)
715 if os.path.isdir(meta.path):
716 all_dirs.append(meta)
719 print >> sys.stderr, '=', meta.path
720 meta.apply_to_path(restore_numeric_ids=restore_numeric_ids)
721 all_dirs.sort(key = lambda x : len(x.path), reverse=True)
723 # Don't need to check xpath -- won't be in all_dirs if not OK.
724 xpath = _clean_up_extract_path(dir.path)
726 print >> sys.stderr, '=', xpath
727 # Shouldn't have to check for risky paths here (omitted above).
728 dir.apply_to_path(path=dir.path,
729 restore_numeric_ids=restore_numeric_ids)