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.
8 import errno, os, sys, stat, pwd, grp, struct, xattr, posix1e, re
10 from cStringIO import StringIO
12 from bup.drecurse import recursive_dirlist
13 from bup.helpers import add_error, mkdirp, log
14 from bup.xstat import utime, lutime, lstat, FSTime
15 import bup._helpers as _helpers
17 if _helpers.get_linux_file_attr:
18 from bup._helpers import get_linux_file_attr, set_linux_file_attr
20 # WARNING: the metadata encoding is *not* stable yet. Caveat emptor!
22 # Q: Consider hardlink support?
23 # Q: Is it OK to store raw linux attr (chattr) flags?
24 # Q: Can anything other than S_ISREG(x) or S_ISDIR(x) support posix1e ACLs?
25 # Q: Is the application of posix1e has_extended() correct?
26 # Q: Is one global --numeric-ids argument sufficient?
27 # Q: Do nfsv4 acls trump posix1e acls? (seems likely)
28 # Q: Add support for crtime -- ntfs, and (only internally?) ext*?
30 # FIXME: Fix relative/abs path detection/stripping wrt other platforms.
31 # FIXME: Add nfsv4 acl handling - see nfs4-acl-tools.
32 # FIXME: Consider other entries mentioned in stat(2) (S_IFDOOR, etc.).
33 # FIXME: Consider pack('vvvvsss', ...) optimization.
34 # FIXME: Consider caching users/groups.
38 # osx (varies between hfs and hfs+):
39 # type - regular dir char block fifo socket ...
40 # perms - rwxrwxrwxsgt
41 # times - ctime atime mtime
44 # hard-link-info (hfs+ only)
47 # attributes-osx see chflags
53 # type - regular dir ...
54 # times - creation, modification, posix change, access
57 # attributes - see attrib
59 # forks (alternate data streams)
63 # type - regular dir ...
64 # perms - rwxrwxrwx (maybe - see wikipedia)
65 # times - creation, modification, access
66 # attributes - see attrib
70 _have_lchmod = hasattr(os, 'lchmod')
73 def _clean_up_path_for_archive(p):
74 # Not the most efficient approach.
77 # Take everything after any '/../'.
78 pos = result.rfind('/../')
80 result = result[result.rfind('/../') + 4:]
82 # Take everything after any remaining '../'.
83 if result.startswith("../"):
86 # Remove any '/./' sequences.
87 pos = result.find('/./')
89 result = result[0:pos] + '/' + result[pos + 3:]
90 pos = result.find('/./')
92 # Remove any leading '/'s.
93 result = result.lstrip('/')
95 # Replace '//' with '/' everywhere.
96 pos = result.find('//')
98 result = result[0:pos] + '/' + result[pos + 2:]
99 pos = result.find('//')
101 # Take everything after any remaining './'.
102 if result.startswith('./'):
105 # Take everything before any remaining '/.'.
106 if result.endswith('/.'):
109 if result == '' or result.endswith('/..'):
116 if p.startswith('/'):
118 if p.find('/../') != -1:
120 if p.startswith('../'):
122 if p.endswith('/..'):
127 def _clean_up_extract_path(p):
128 result = p.lstrip('/')
131 elif _risky_path(result):
137 # These tags are currently conceptually private to Metadata, and they
138 # must be unique, and must *never* be changed.
141 _rec_tag_common = 2 # times, owner, group, type, perms, etc.
142 _rec_tag_symlink_target = 3
143 _rec_tag_posix1e_acl = 4 # getfacl(1), setfacl(1), etc.
144 _rec_tag_nfsv4_acl = 5 # intended to supplant posix1e acls?
145 _rec_tag_linux_attr = 6 # lsattr(1) chattr(1)
146 _rec_tag_linux_xattr = 7 # getfattr(1) setfattr(1)
149 class ApplyError(Exception):
150 # Thrown when unable to apply any given bit of metadata to a path.
155 # Metadata is stored as a sequence of tagged binary records. Each
156 # record will have some subset of add, encode, load, create, and
157 # apply methods, i.e. _add_foo...
161 # Timestamps are (sec, ns), relative to 1970-01-01 00:00:00, ns
162 # must be non-negative and < 10**9.
164 def _add_common(self, path, st):
165 self.mode = st.st_mode
168 self.rdev = st.st_rdev
169 self.atime = st.st_atime
170 self.mtime = st.st_mtime
171 self.ctime = st.st_ctime
172 self.owner = self.group = ''
174 self.owner = pwd.getpwuid(st.st_uid)[0]
178 self.group = grp.getgrgid(st.st_gid)[0]
182 def _encode_common(self):
183 atime = self.atime.to_timespec()
184 mtime = self.mtime.to_timespec()
185 ctime = self.ctime.to_timespec()
186 result = vint.pack('VVsVsVvVvVvV',
201 def _load_common_rec(self, port):
202 data = vint.read_bvec(port)
214 ctime_ns) = vint.unpack('VVsVsVvVvVvV', data)
215 self.atime = FSTime.from_timespec((self.atime, atime_ns))
216 self.mtime = FSTime.from_timespec((self.mtime, mtime_ns))
217 self.ctime = FSTime.from_timespec((self.ctime, ctime_ns))
219 def _create_via_common_rec(self, path, create_symlinks=True):
220 # If the path already exists and is a dir, try rmdir.
221 # If the path already exists and is anything else, try unlink.
226 if e.errno != errno.ENOENT:
229 if stat.S_ISDIR(st.st_mode):
233 if e.errno == errno.ENOTEMPTY:
234 msg = 'refusing to overwrite non-empty dir' + path
240 if stat.S_ISREG(self.mode):
241 os.mknod(path, 0600 | stat.S_IFREG)
242 elif stat.S_ISDIR(self.mode):
244 elif stat.S_ISCHR(self.mode):
245 os.mknod(path, 0600 | stat.S_IFCHR, self.rdev)
246 elif stat.S_ISBLK(self.mode):
247 os.mknod(path, 0600 | stat.S_IFBLK, self.rdev)
248 elif stat.S_ISFIFO(self.mode):
249 os.mknod(path, 0600 | stat.S_IFIFO)
250 elif stat.S_ISLNK(self.mode):
251 if(self.symlink_target and create_symlinks):
252 os.symlink(self.symlink_target, path)
253 # FIXME: S_ISDOOR, S_IFMPB, S_IFCMP, S_IFNWK, ... see stat(2).
254 # Otherwise, do nothing.
256 def _apply_common_rec(self, path, restore_numeric_ids=False):
257 # FIXME: S_ISDOOR, S_IFMPB, S_IFCMP, S_IFNWK, ... see stat(2).
258 # EACCES errors at this stage are fatal for the current path.
259 if stat.S_ISLNK(self.mode):
261 lutime(path, (self.atime, self.mtime))
263 if e.errno == errno.EACCES:
264 raise ApplyError('lutime: %s' % e)
269 utime(path, (self.atime, self.mtime))
271 if e.errno == errno.EACCES:
272 raise ApplyError('utime: %s' % e)
276 # Don't try to restore owner unless we're root, and even
277 # if asked, don't try to restore the owner or group if
278 # it doesn't exist in the system db.
281 if not restore_numeric_ids:
284 add_error('bup: ignoring missing owner for "%s"\n' % path)
286 if os.geteuid() != 0:
287 uid = -1 # Not root; assume we can't change owner.
290 uid = pwd.getpwnam(self.owner)[2]
293 fmt = 'bup: ignoring unknown owner %s for "%s"\n'
294 add_error(fmt % (self.owner, path))
297 add_error('bup: ignoring missing group for "%s"\n' % path)
300 gid = grp.getgrnam(self.group)[2]
303 add_error('bup: ignoring unknown group %s for "%s"\n'
304 % (self.group, path))
307 os.lchown(path, uid, gid)
309 if e.errno == errno.EPERM:
310 add_error('lchown: %s' % e)
315 os.lchmod(path, stat.S_IMODE(self.mode))
316 elif not stat.S_ISLNK(self.mode):
317 os.chmod(path, stat.S_IMODE(self.mode))
322 def _encode_path(self):
324 return vint.pack('s', self.path)
328 def _load_path_rec(self, port):
329 self.path = vint.unpack('s', vint.read_bvec(port))[0]
334 def _add_symlink_target(self, path, st):
336 if(stat.S_ISLNK(st.st_mode)):
337 self.symlink_target = os.readlink(path)
341 def _encode_symlink_target(self):
342 return self.symlink_target
344 def _load_symlink_target_rec(self, port):
345 self.symlink_target = vint.read_bvec(port)
348 ## POSIX1e ACL records
350 # Recorded as a list:
351 # [txt_id_acl, num_id_acl]
352 # or, if a directory:
353 # [txt_id_acl, num_id_acl, txt_id_default_acl, num_id_default_acl]
354 # The numeric/text distinction only matters when reading/restoring
356 def _add_posix1e_acl(self, path, st):
357 if not stat.S_ISLNK(st.st_mode):
359 if posix1e.has_extended(path):
360 acl = posix1e.ACL(file=path)
361 self.posix1e_acl = [acl, acl] # txt and num are the same
362 if stat.S_ISDIR(st.st_mode):
363 acl = posix1e.ACL(filedef=path)
364 self.posix1e_acl.extend([acl, acl])
365 except EnvironmentError, e:
366 if e.errno != errno.EOPNOTSUPP:
369 def _encode_posix1e_acl(self):
370 # Encode as two strings (w/default ACL string possibly empty).
372 acls = self.posix1e_acl
373 txt_flags = posix1e.TEXT_ABBREVIATE
374 num_flags = posix1e.TEXT_ABBREVIATE | posix1e.TEXT_NUMERIC_IDS
375 acl_reps = [acls[0].to_any_text('', '\n', txt_flags),
376 acls[1].to_any_text('', '\n', num_flags)]
380 acl_reps.append(acls[2].to_any_text('', '\n', txt_flags))
381 acl_reps.append(acls[3].to_any_text('', '\n', num_flags))
382 return vint.pack('ssss',
383 acl_reps[0], acl_reps[1], acl_reps[2], acl_reps[3])
387 def _load_posix1e_acl_rec(self, port):
388 data = vint.read_bvec(port)
389 acl_reps = vint.unpack('ssss', data)
390 if(acl_reps[2] == ''):
391 acl_reps = acl_reps[:2]
392 self.posix1e_acl = [posix1e.ACL(x) for x in acl_reps]
394 def _apply_posix1e_acl_rec(self, path, restore_numeric_ids=False):
395 if(self.posix1e_acl):
396 acls = self.posix1e_acl
398 if restore_numeric_ids:
399 acls[3].applyto(path, posix1e.ACL_TYPE_DEFAULT)
401 acls[2].applyto(path, posix1e.ACL_TYPE_DEFAULT)
402 if restore_numeric_ids:
403 acls[1].applyto(path, posix1e.ACL_TYPE_ACCESS)
405 acls[0].applyto(path, posix1e.ACL_TYPE_ACCESS)
408 ## Linux attributes (lsattr(1), chattr(1))
410 def _add_linux_attr(self, path, st):
411 if stat.S_ISREG(st.st_mode) or stat.S_ISDIR(st.st_mode):
413 attr = get_linux_file_attr(path)
415 self.linux_attr = get_linux_file_attr(path)
416 except EnvironmentError, e:
417 if e.errno == errno.EACCES:
418 add_error('bup: unable to read Linux attr for "%s"' % path)
422 def _encode_linux_attr(self):
424 return vint.pack('V', self.linux_attr)
428 def _load_linux_attr_rec(self, port):
429 data = vint.read_bvec(port)
430 self.linux_attr = vint.unpack('V', data)[0]
432 def _apply_linux_attr_rec(self, path, restore_numeric_ids=False):
434 set_linux_file_attr(path, self.linux_attr)
437 ## Linux extended attributes (getfattr(1), setfattr(1))
439 def _add_linux_xattr(self, path, st):
441 self.linux_xattr = xattr.get_all(path, nofollow=True)
442 except EnvironmentError, e:
443 if e.errno != errno.EOPNOTSUPP:
446 def _encode_linux_xattr(self):
448 result = vint.pack('V', len(self.linux_xattr))
449 for name, value in self.linux_xattr:
450 result += vint.pack('ss', name, value)
455 def _load_linux_xattr_rec(self, file):
456 data = vint.read_bvec(file)
457 memfile = StringIO(data)
459 for i in range(vint.read_vuint(memfile)):
460 key = vint.read_bvec(memfile)
461 value = vint.read_bvec(memfile)
462 result.append((key, value))
463 self.linux_xattr = result
465 def _apply_linux_xattr_rec(self, path, restore_numeric_ids=False):
466 if(self.linux_xattr):
467 for k, v in self.linux_xattr:
468 xattr.set(path, k, v, nofollow=True)
473 self.symlink_target = None
474 self.linux_attr = None
475 self.linux_xattr = None
476 self.posix1e_acl = None
477 self.posix1e_acl_default = None
479 def write(self, port, include_path=True):
480 records = [(_rec_tag_path, self._encode_path())] if include_path else []
481 records.extend([(_rec_tag_common, self._encode_common()),
482 (_rec_tag_symlink_target, self._encode_symlink_target()),
483 (_rec_tag_posix1e_acl, self._encode_posix1e_acl()),
484 (_rec_tag_linux_attr, self._encode_linux_attr()),
485 (_rec_tag_linux_xattr, self._encode_linux_xattr())])
486 for tag, data in records:
488 vint.write_vuint(port, tag)
489 vint.write_bvec(port, data)
490 vint.write_vuint(port, _rec_tag_end)
494 # This method should either: return a valid Metadata object;
495 # throw EOFError if there was nothing at all to read; throw an
496 # Exception if a valid object could not be read completely.
497 tag = vint.read_vuint(port)
498 try: # From here on, EOF is an error.
500 while(True): # only exit is error (exception) or _rec_tag_end
501 if tag == _rec_tag_path:
502 result._load_path_rec(port)
503 elif tag == _rec_tag_common:
504 result._load_common_rec(port)
505 elif tag == _rec_tag_symlink_target:
506 result._load_symlink_target_rec(port)
507 elif tag == _rec_tag_posix1e_acl:
508 result._load_posix1e_acl(port)
509 elif tag ==_rec_tag_nfsv4_acl:
510 result._load_nfsv4_acl_rec(port)
511 elif tag == _rec_tag_linux_attr:
512 result._load_linux_attr_rec(port)
513 elif tag == _rec_tag_linux_xattr:
514 result._load_linux_xattr_rec(port)
515 elif tag == _rec_tag_end:
517 else: # unknown record
519 tag = vint.read_vuint(port)
521 raise Exception("EOF while reading Metadata")
524 return stat.S_ISDIR(self.mode)
526 def create_path(self, path, create_symlinks=True):
527 self._create_via_common_rec(path, create_symlinks=create_symlinks)
529 def apply_to_path(self, path=None, restore_numeric_ids=False):
530 # apply metadata to path -- file must exist
534 raise Exception('Metadata.apply_to_path() called with no path');
535 num_ids = restore_numeric_ids
537 self._apply_common_rec(path, restore_numeric_ids=num_ids)
538 self._apply_posix1e_acl_rec(path, restore_numeric_ids=num_ids)
539 self._apply_linux_attr_rec(path, restore_numeric_ids=num_ids)
540 self._apply_linux_xattr_rec(path, restore_numeric_ids=num_ids)
541 except ApplyError, e:
545 def from_path(path, archive_path=None, save_symlinks=True):
547 result.path = archive_path
549 result._add_common(path, st)
551 result._add_symlink_target(path, st)
552 result._add_posix1e_acl(path, st)
553 result._add_linux_attr(path, st)
554 result._add_linux_xattr(path, st)
558 def save_tree(output_file, paths,
564 # Issue top-level rewrite warnings.
566 safe_path = _clean_up_path_for_archive(path)
567 if(safe_path != path):
568 log('bup: archiving "%s" as "%s"\n' % (path, safe_path))
570 start_dir = os.getcwd()
572 for (p, st) in recursive_dirlist(paths, xdev=xdev):
573 dirlist_dir = os.getcwd()
575 safe_path = _clean_up_path_for_archive(p)
576 m = from_path(p, archive_path=safe_path,
577 save_symlinks=save_symlinks)
579 print >> sys.stderr, m.path
580 m.write(output_file, include_path=write_paths)
581 os.chdir(dirlist_dir)
586 def _set_up_path(meta, create_symlinks=True):
587 # Allow directories to exist as a special case -- might have
588 # been created by an earlier longer path.
590 mkdirp(meta.path, 0700)
592 parent = os.path.dirname(meta.path)
595 meta.create_path(meta.path, create_symlinks=create_symlinks)
598 class _ArchiveIterator:
601 return Metadata.read(self._file)
603 raise StopIteration()
608 def __init__(self, file):
612 def display_archive(file):
613 for meta in _ArchiveIterator(file):
615 print meta.path # FIXME
620 def start_extract(file, create_symlinks=True):
621 for meta in _ArchiveIterator(file):
623 print >> sys.stderr, meta.path
624 xpath = _clean_up_extract_path(meta.path)
626 add_error(Exception('skipping risky path "%s"' % meta.path))
629 _set_up_path(meta, create_symlinks=create_symlinks)
632 def finish_extract(file, restore_numeric_ids=False):
634 for meta in _ArchiveIterator(file):
635 xpath = _clean_up_extract_path(meta.path)
637 add_error(Exception('skipping risky path "%s"' % dir.path))
639 if os.path.isdir(meta.path):
640 all_dirs.append(meta)
643 print >> sys.stderr, meta.path
644 meta.apply_to_path(path=xpath,
645 restore_numeric_ids=restore_numeric_ids)
646 all_dirs.sort(key = lambda x : len(x.path), reverse=True)
648 # Don't need to check xpath -- won't be in all_dirs if not OK.
649 xpath = _clean_up_extract_path(dir.path)
651 print >> sys.stderr, dir.path
652 dir.apply_to_path(path=xpath, restore_numeric_ids=restore_numeric_ids)
655 def extract(file, restore_numeric_ids=False, create_symlinks=True):
656 # For now, just store all the directories and handle them last,
659 for meta in _ArchiveIterator(file):
660 xpath = _clean_up_extract_path(meta.path)
662 add_error(Exception('skipping risky path "%s"' % meta.path))
666 print >> sys.stderr, '+', meta.path
667 _set_up_path(meta, create_symlinks=create_symlinks)
668 if os.path.isdir(meta.path):
669 all_dirs.append(meta)
672 print >> sys.stderr, '=', meta.path
673 meta.apply_to_path(restore_numeric_ids=restore_numeric_ids)
674 all_dirs.sort(key = lambda x : len(x.path), reverse=True)
676 # Don't need to check xpath -- won't be in all_dirs if not OK.
677 xpath = _clean_up_extract_path(meta.path)
679 print >> sys.stderr, '=', meta.path
680 # Shouldn't have to check for risky paths here (omitted above).
681 dir.apply_to_path(path=dir.path,
682 restore_numeric_ids=restore_numeric_ids)