]> arthur.barton.de Git - bup.git/blob - lib/bup/metadata.py
Move stat-related work to bup.xstat; add xstat.stat.
[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
8 import errno, os, sys, stat, pwd, grp, struct, xattr, posix1e, re
9
10 from cStringIO import StringIO
11 from bup import vint
12 from bup.helpers import add_error, mkdirp, log
13 from bup.xstat import utime, lutime, lstat, FSTime
14 import bup._helpers as _helpers
15
16 if _helpers.get_linux_file_attr:
17     from bup._helpers import get_linux_file_attr, set_linux_file_attr
18
19 # WARNING: the metadata encoding is *not* stable yet.  Caveat emptor!
20
21 # Q: Consider hardlink support?
22 # Q: Is it OK to store raw linux attr (chattr) flags?
23 # Q: Can anything other than S_ISREG(x) or S_ISDIR(x) support posix1e ACLs?
24 # Q: Is the application of posix1e has_extended() correct?
25 # Q: Is one global --numeric-ids argument sufficient?
26 # Q: Do nfsv4 acls trump posix1e acls? (seems likely)
27 # Q: Add support for crtime -- ntfs, and (only internally?) ext*?
28
29 # FIXME: Fix relative/abs path detection/stripping wrt other platforms.
30 # FIXME: Add nfsv4 acl handling - see nfs4-acl-tools.
31 # FIXME: Consider other entries mentioned in stat(2) (S_IFDOOR, etc.).
32 # FIXME: Consider pack('vvvvsss', ...) optimization.
33 # FIXME: Consider caching users/groups.
34
35 ## FS notes:
36 #
37 # osx (varies between hfs and hfs+):
38 #   type - regular dir char block fifo socket ...
39 #   perms - rwxrwxrwxsgt
40 #   times - ctime atime mtime
41 #   uid
42 #   gid
43 #   hard-link-info (hfs+ only)
44 #   link-target
45 #   device-major/minor
46 #   attributes-osx see chflags
47 #   content-type
48 #   content-creator
49 #   forks
50 #
51 # ntfs
52 #   type - regular dir ...
53 #   times - creation, modification, posix change, access
54 #   hard-link-info
55 #   link-target
56 #   attributes - see attrib
57 #   ACLs
58 #   forks (alternate data streams)
59 #   crtime?
60 #
61 # fat
62 #   type - regular dir ...
63 #   perms - rwxrwxrwx (maybe - see wikipedia)
64 #   times - creation, modification, access
65 #   attributes - see attrib
66
67 verbose = 0
68
69 _have_lchmod = hasattr(os, 'lchmod')
70
71
72 def _clean_up_path_for_archive(p):
73     # Not the most efficient approach.
74     result = p
75
76     # Take everything after any '/../'.
77     pos = result.rfind('/../')
78     if(pos != -1):
79         result = result[result.rfind('/../') + 4:]
80
81     # Take everything after any remaining '../'.
82     if result.startswith("../"):
83         result = result[3:]
84
85     # Remove any '/./' sequences.
86     pos = result.find('/./')
87     while pos != -1:
88         result = result[0:pos] + '/' + result[pos + 3:]
89         pos = result.find('/./')
90
91     # Remove any leading '/'s.
92     result = result.lstrip('/')
93
94     # Replace '//' with '/' everywhere.
95     pos = result.find('//')
96     while pos != -1:
97         result = result[0:pos] + '/' + result[pos + 2:]
98         pos = result.find('//')
99
100     # Take everything after any remaining './'.
101     if result.startswith('./'):
102         result = result[2:]
103
104     # Take everything before any remaining '/.'.
105     if result.endswith('/.'):
106         result = result[:-2]
107
108     if result == '' or result.endswith('/..'):
109         result = '.'
110
111     return result
112
113
114 def _risky_path(p):
115     if p.startswith('/'):
116         return True
117     if p.find('/../') != -1:
118         return True
119     if p.startswith('../'):
120         return True
121     if p.endswith('/..'):
122         return True
123     return False
124
125
126 def _clean_up_extract_path(p):
127     result = p.lstrip('/')
128     if result == '':
129         return '.'
130     elif _risky_path(result):
131         return None
132     else:
133         return result
134
135
136 # These tags are currently conceptually private to Metadata, and they
137 # must be unique, and must *never* be changed.
138 _rec_tag_end = 0
139 _rec_tag_path = 1
140 _rec_tag_common = 2           # times, owner, group, type, perms, etc.
141 _rec_tag_symlink_target = 3
142 _rec_tag_posix1e_acl = 4      # getfacl(1), setfacl(1), etc.
143 _rec_tag_nfsv4_acl = 5        # intended to supplant posix1e acls?
144 _rec_tag_linux_attr = 6       # lsattr(1) chattr(1)
145 _rec_tag_linux_xattr = 7      # getfattr(1) setfattr(1)
146
147
148 class MetadataAcquisitionError(Exception):
149     # Thrown when unable to extract any given bit of metadata from a path.
150     pass
151
152
153 class MetadataApplicationError(Exception):
154     # Thrown when unable to apply any given bit of metadata to a path.
155     pass
156
157
158 class Metadata:
159     # Metadata is stored as a sequence of tagged binary records.  Each
160     # record will have some subset of add, encode, load, create, and
161     # apply methods, i.e. _add_foo...
162
163     ## Common records
164
165     # Timestamps are (sec, ns), relative to 1970-01-01 00:00:00, ns
166     # must be non-negative and < 10**9.
167
168     def _add_common(self, path, st):
169         self.mode = st.st_mode
170         self.uid = st.st_uid
171         self.gid = st.st_gid
172         self.rdev = st.st_rdev
173         self.atime = st.st_atime
174         self.mtime = st.st_mtime
175         self.ctime = st.st_ctime
176         self.owner = pwd.getpwuid(st.st_uid)[0]
177         self.group = grp.getgrgid(st.st_gid)[0]
178
179     def _encode_common(self):
180         atime = self.atime.to_timespec()
181         mtime = self.mtime.to_timespec()
182         ctime = self.ctime.to_timespec()
183         result = vint.pack('VVsVsVvVvVvV',
184                            self.mode,
185                            self.uid,
186                            self.owner,
187                            self.gid,
188                            self.group,
189                            self.rdev,
190                            atime[0],
191                            atime[1],
192                            mtime[0],
193                            mtime[1],
194                            ctime[0],
195                            ctime[1])
196         return result
197
198     def _load_common_rec(self, port):
199         data = vint.read_bvec(port)
200         (self.mode,
201          self.uid,
202          self.owner,
203          self.gid,
204          self.group,
205          self.rdev,
206          self.atime,
207          atime_ns,
208          self.mtime,
209          mtime_ns,
210          self.ctime,
211          ctime_ns) = vint.unpack('VVsVsVvVvVvV', data)
212         self.atime = FSTime.from_timespec((self.atime, atime_ns))
213         self.mtime = FSTime.from_timespec((self.mtime, mtime_ns))
214         self.ctime = FSTime.from_timespec((self.ctime, ctime_ns))
215
216     def _create_via_common_rec(self, path, create_symlinks=True):
217         # If the path already exists and is a dir, try rmdir.
218         # If the path already exists and is anything else, try unlink.
219         st = None
220         try:
221             st = lstat(path)
222         except IOError, e:
223             if e.errno != errno.ENOENT:
224                 raise
225         if st:
226             if stat.S_ISDIR(st.st_mode):
227                 try:
228                     os.rmdir(path)
229                 except OSError, e:
230                     if e.errno == errno.ENOTEMPTY:
231                         msg = 'refusing to overwrite non-empty dir' + path
232                         raise Exception(msg)
233                     raise
234             else:
235                 os.unlink(path)
236
237         if stat.S_ISREG(self.mode):
238             os.mknod(path, 0600 | stat.S_IFREG)
239         elif stat.S_ISDIR(self.mode):
240             os.mkdir(path, 0700)
241         elif stat.S_ISCHR(self.mode):
242             os.mknod(path, 0600 | stat.S_IFCHR, self.rdev)
243         elif stat.S_ISBLK(self.mode):
244             os.mknod(path, 0600 | stat.S_IFBLK, self.rdev)
245         elif stat.S_ISFIFO(self.mode):
246             os.mknod(path, 0600 | stat.S_IFIFO)
247         elif stat.S_ISLNK(self.mode):
248             if(self.symlink_target and create_symlinks):
249                 os.symlink(self.symlink_target, path)
250         # FIXME: S_ISDOOR, S_IFMPB, S_IFCMP, S_IFNWK, ... see stat(2).
251         # Otherwise, do nothing.
252
253     def _apply_common_rec(self, path, restore_numeric_ids=False):
254         # FIXME: S_ISDOOR, S_IFMPB, S_IFCMP, S_IFNWK, ... see stat(2).
255         if stat.S_ISLNK(self.mode):
256             lutime(path, (self.atime, self.mtime))
257         else:
258             utime(path, (self.atime, self.mtime))
259         if stat.S_ISREG(self.mode) \
260                 | stat.S_ISDIR(self.mode) \
261                 | stat.S_ISCHR(self.mode) \
262                 | stat.S_ISBLK(self.mode) \
263                 | stat.S_ISLNK(self.mode) \
264                 | stat.S_ISFIFO(self.mode):
265             # Be safe.
266             if _have_lchmod:
267                 os.lchmod(path, 0)
268             elif not stat.S_ISLNK(self.mode):
269                 os.chmod(path, 0)
270
271             # Don't try to restore owner unless we're root, and even
272             # if asked, don't try to restore the owner or group if
273             # it doesn't exist in the system db.
274             uid = self.uid
275             gid = self.gid
276             if not restore_numeric_ids:
277                 if os.geteuid() == 0:
278                     try:
279                         uid = pwd.getpwnam(self.owner)[2]
280                     except KeyError:
281                         uid = -1
282                         log('bup: ignoring unknown owner %s for "%s"\n'
283                             % (self.owner, path))
284                 else:
285                     uid = -1 # Not root; assume we can't change owner.
286                 try:
287                     gid = grp.getgrnam(self.group)[2]
288                 except KeyError:
289                     gid = -1
290                     log('bup: ignoring unknown group %s for "%s"\n'
291                         % (self.group, path))
292             os.lchown(path, uid, gid)
293
294             if _have_lchmod:
295                 os.lchmod(path, stat.S_IMODE(self.mode))
296             elif not stat.S_ISLNK(self.mode):
297                 os.chmod(path, stat.S_IMODE(self.mode))
298
299
300     ## Path records
301
302     def _encode_path(self):
303         if self.path:
304             return vint.pack('s', self.path)
305         else:
306             return None
307
308     def _load_path_rec(self, port):
309         self.path = vint.unpack('s', vint.read_bvec(port))[0]
310
311
312     ## Symlink targets
313
314     def _add_symlink_target(self, path, st):
315         if(stat.S_ISLNK(st.st_mode)):
316             self.symlink_target = os.readlink(path)
317
318     def _encode_symlink_target(self):
319         return self.symlink_target
320
321     def _load_symlink_target_rec(self, port):
322         self.symlink_target = vint.read_bvec(port)
323
324
325     ## POSIX1e ACL records
326
327     # Recorded as a list:
328     #   [txt_id_acl, num_id_acl]
329     # or, if a directory:
330     #   [txt_id_acl, num_id_acl, txt_id_default_acl, num_id_default_acl]
331     # The numeric/text distinction only matters when reading/restoring
332     # a stored record.
333     def _add_posix1e_acl(self, path, st):
334         if not stat.S_ISLNK(st.st_mode):
335             try:
336                 if posix1e.has_extended(path):
337                     acl = posix1e.ACL(file=path)
338                     self.posix1e_acl = [acl, acl] # txt and num are the same
339                     if stat.S_ISDIR(st.st_mode):
340                         acl = posix1e.ACL(filedef=path)
341                         self.posix1e_acl.extend([acl, acl])
342             except EnvironmentError, e:
343                 if e.errno != errno.EOPNOTSUPP:
344                     raise
345
346     def _encode_posix1e_acl(self):
347         # Encode as two strings (w/default ACL string possibly empty).
348         if self.posix1e_acl:
349             acls = self.posix1e_acl
350             txt_flags = posix1e.TEXT_ABBREVIATE
351             num_flags = posix1e.TEXT_ABBREVIATE | posix1e.TEXT_NUMERIC_IDS
352             acl_reps = [acls[0].to_any_text('', '\n', txt_flags),
353                         acls[1].to_any_text('', '\n', num_flags)]
354             if(len(acls) < 3):
355                 acl_reps += ['', '']
356             else:
357                 acl_reps.append(acls[2].to_any_text('', '\n', txt_flags))
358                 acl_reps.append(acls[3].to_any_text('', '\n', num_flags))
359             return vint.pack('ssss',
360                              acl_reps[0], acl_reps[1], acl_reps[2], acl_reps[3])
361         else:
362             return None
363
364     def _load_posix1e_acl_rec(self, port):
365         data = vint.read_bvec(port)
366         acl_reps = vint.unpack('ssss', data)
367         if(acl_reps[2] == ''):
368             acl_reps = acl_reps[:2]
369         self.posix1e_acl = [posix1e.ACL(x) for x in acl_reps]
370
371     def _apply_posix1e_acl_rec(self, path, restore_numeric_ids=False):
372         if(self.posix1e_acl):
373             acls = self.posix1e_acl
374             if(len(acls) > 2):
375                 if restore_numeric_ids:
376                     acls[3].applyto(path, posix1e.ACL_TYPE_DEFAULT)
377                 else:
378                     acls[2].applyto(path, posix1e.ACL_TYPE_DEFAULT)
379             if restore_numeric_ids:
380                 acls[1].applyto(path, posix1e.ACL_TYPE_ACCESS)
381             else:
382                 acls[0].applyto(path, posix1e.ACL_TYPE_ACCESS)
383
384
385     ## Linux attributes (lsattr(1), chattr(1))
386
387     def _add_linux_attr(self, path, st):
388         if stat.S_ISREG(st.st_mode) or stat.S_ISDIR(st.st_mode):
389             attr = get_linux_file_attr(path)
390             if(attr != 0):
391                 self.linux_attr = get_linux_file_attr(path)
392
393     def _encode_linux_attr(self):
394         if self.linux_attr:
395             return vint.pack('V', self.linux_attr)
396         else:
397             return None
398
399     def _load_linux_attr_rec(self, port):
400         data = vint.read_bvec(port)
401         self.linux_attr = vint.unpack('V', data)[0]
402
403     def _apply_linux_attr_rec(self, path, restore_numeric_ids=False):
404         if(self.linux_attr):
405             set_linux_file_attr(path, self.linux_attr)
406
407
408     ## Linux extended attributes (getfattr(1), setfattr(1))
409
410     def _add_linux_xattr(self, path, st):
411         try:
412             self.linux_xattr = xattr.get_all(path, nofollow=True)
413         except EnvironmentError, e:
414             if e.errno != errno.EOPNOTSUPP:
415                 raise
416
417     def _encode_linux_xattr(self):
418         if self.linux_xattr:
419             result = vint.pack('V', len(items))
420             for name, value in self.attrs:
421                 result += vint.pack('ss', name, value)
422             return result
423         else:
424             return None
425
426     def _load_linux_xattr_rec(self, file):
427         data = vint.read_bvec(file)
428         memfile = StringIO(data)
429         result = []
430         for i in range(vint.read_vuint(memfile)):
431             key = vint.read_bvec(memfile)
432             value = vint.read_bvec(memfile)
433             result.append((key, value))
434         self.linux_xattr = result
435
436     def _apply_linux_xattr_rec(self, path, restore_numeric_ids=False):
437         if(self.linux_xattr):
438             for k, v in self.linux_xattr:
439                 xattr.set(path, k, v, nofollow=True)
440
441     def __init__(self):
442         # optional members
443         self.path = None
444         self.symlink_target = None
445         self.linux_attr = None
446         self.linux_xattr = None
447         self.posix1e_acl = None
448         self.posix1e_acl_default = None
449
450     def write(self, port, include_path=True):
451         records = [(_rec_tag_path, self._encode_path())] if include_path else []
452         records.extend([(_rec_tag_common, self._encode_common()),
453                         (_rec_tag_symlink_target, self._encode_symlink_target()),
454                         (_rec_tag_posix1e_acl, self._encode_posix1e_acl()),
455                         (_rec_tag_linux_attr, self._encode_linux_attr()),
456                         (_rec_tag_linux_xattr, self._encode_linux_xattr())])
457         for tag, data in records:
458             if data:
459                 vint.write_vuint(port, tag)
460                 vint.write_bvec(port, data)
461         vint.write_vuint(port, _rec_tag_end)
462
463     @staticmethod
464     def read(port):
465         # This method should either: return a valid Metadata object;
466         # throw EOFError if there was nothing at all to read; throw an
467         # Exception if a valid object could not be read completely.
468         tag = vint.read_vuint(port)
469         try: # From here on, EOF is an error.
470             result = Metadata()
471             while(True): # only exit is error (exception) or _rec_tag_end
472                 if tag == _rec_tag_path:
473                     result._load_path_rec(port)
474                 elif tag == _rec_tag_common:
475                     result._load_common_rec(port)
476                 elif tag == _rec_tag_symlink_target:
477                     result._load_symlink_target_rec(port)
478                 elif tag == _rec_tag_posix1e_acl:
479                     result._load_posix1e_acl(port)
480                 elif tag ==_rec_tag_nfsv4_acl:
481                     result._load_nfsv4_acl_rec(port)
482                 elif tag == _rec_tag_linux_attr:
483                     result._load_linux_attr_rec(port)
484                 elif tag == _rec_tag_linux_xattr:
485                     result._load_linux_xattr_rec(port)
486                 elif tag == _rec_tag_end:
487                     return result
488                 else: # unknown record
489                     vint.skip_bvec(port)
490                 tag = vint.read_vuint(port)
491         except EOFError:
492             raise Exception("EOF while reading Metadata")
493
494     def isdir(self):
495         return stat.S_ISDIR(self.mode)
496
497     def create_path(self, path, create_symlinks=True):
498         self._create_via_common_rec(path, create_symlinks=create_symlinks)
499
500     def apply_to_path(self, path=None, restore_numeric_ids=False):
501         # apply metadata to path -- file must exist
502         if not path:
503             path = self.path
504         if not path:
505             raise Exception('Metadata.apply_to_path() called with no path');
506         num_ids = restore_numeric_ids
507         try: # Later we may want to push this down and make it finer grained.
508             self._apply_common_rec(path, restore_numeric_ids=num_ids)
509             self._apply_posix1e_acl_rec(path, restore_numeric_ids=num_ids)
510             self._apply_linux_attr_rec(path, restore_numeric_ids=num_ids)
511             self._apply_linux_xattr_rec(path, restore_numeric_ids=num_ids)
512         except Exception, e:
513             raise MetadataApplicationError(str(e))
514
515
516 def from_path(path, archive_path=None, save_symlinks=True):
517     result = Metadata()
518     result.path = archive_path
519     st = lstat(path)
520     try: # Later we may want to push this down and make it finer grained.
521         result._add_common(path, st)
522         if(save_symlinks):
523             result._add_symlink_target(path, st)
524         result._add_posix1e_acl(path, st)
525         result._add_linux_attr(path, st)
526         result._add_linux_xattr(path, st)
527     except Exception, e:
528         raise MetadataAcquisitionError(str(e))
529     return result
530
531
532 def save_tree(output_file, paths,
533               recurse=False,
534               write_paths=True,
535               save_symlinks=True):
536     for p in paths:
537         safe_path = _clean_up_path_for_archive(p)
538         if(safe_path != p):
539             log('bup: archiving "%s" as "%s"\n' % (p, safe_path))
540
541         # Handle path itself.
542         try:
543             m = from_path(p, archive_path=safe_path,
544                           save_symlinks=save_symlinks)
545         except MetadataAcquisitionError, e:
546             add_error(e)
547
548         if verbose:
549             print >> sys.stderr, m.path
550         m.write(output_file, include_path=write_paths)
551
552         if recurse and os.path.isdir(p):
553             for root, dirs, files in os.walk(p, onerror=add_error):
554                 items = files + dirs
555                 for sub_path in items:
556                     full_path = os.path.join(root, sub_path)
557                     safe_path = _clean_up_path_for_archive(full_path)
558                     try:
559                         m = from_path(full_path,
560                                       archive_path=safe_path,
561                                       save_symlinks=save_symlinks)
562                     except MetadataAcquisitionError, e:
563                         add_error(e)
564                     if verbose:
565                         print >> sys.stderr, m.path
566                     m.write(output_file, include_path=write_paths)
567
568
569 def _set_up_path(meta, create_symlinks=True):
570     # Allow directories to exist as a special case -- might have
571     # been created by an earlier longer path.
572     if meta.isdir():
573         mkdirp(meta.path, 0700)
574     else:
575         parent = os.path.dirname(meta.path)
576         if parent:
577             mkdirp(parent, 0700)
578             meta.create_path(meta.path, create_symlinks=create_symlinks)
579
580
581 class _ArchiveIterator:
582     def next(self):
583         try:
584             return Metadata.read(self._file)
585         except EOFError:
586             raise StopIteration()
587
588     def __iter__(self):
589         return self
590
591     def __init__(self, file):
592         self._file = file
593
594
595 def display_archive(file):
596     for meta in _ArchiveIterator(file):
597         if verbose:
598             print meta.path # FIXME
599         else:
600             print meta.path
601
602
603 def start_extract(file, create_symlinks=True):
604     for meta in _ArchiveIterator(file):
605         if verbose:
606             print >> sys.stderr, meta.path
607         xpath = _clean_up_extract_path(meta.path)
608         if not xpath:
609             add_error(Exception('skipping risky path "%s"' % meta.path))
610         else:
611             meta.path = xpath
612             _set_up_path(meta, create_symlinks=create_symlinks)
613
614
615 def finish_extract(file, restore_numeric_ids=False):
616     all_dirs = []
617     for meta in _ArchiveIterator(file):
618         xpath = _clean_up_extract_path(meta.path)
619         if not xpath:
620             add_error(Exception('skipping risky path "%s"' % dir.path))
621         else:
622             if os.path.isdir(meta.path):
623                 all_dirs.append(meta)
624             else:
625                 if verbose:
626                     print >> sys.stderr, meta.path
627                 try:
628                     meta.apply_to_path(path=xpath,
629                                        restore_numeric_ids=restore_numeric_ids)
630                 except MetadataApplicationError, e:
631                     add_error(e)
632
633     all_dirs.sort(key = lambda x : len(x.path), reverse=True)
634     for dir in all_dirs:
635         # Don't need to check xpath -- won't be in all_dirs if not OK.
636         xpath = _clean_up_extract_path(dir.path)
637         if verbose:
638             print >> sys.stderr, dir.path
639         try:
640             dir.apply_to_path(path=xpath,
641                               restore_numeric_ids=restore_numeric_ids)
642         except MetadataApplicationError, e:
643             add_error(e)
644
645
646 def extract(file, restore_numeric_ids=False, create_symlinks=True):
647     # For now, just store all the directories and handle them last,
648     # longest first.
649     all_dirs = []
650     for meta in _ArchiveIterator(file):
651         xpath = _clean_up_extract_path(meta.path)
652         if not xpath:
653             add_error(Exception('skipping risky path "%s"' % meta.path))
654         else:
655             meta.path = xpath
656             if verbose:
657                 print >> sys.stderr, '+', meta.path
658             _set_up_path(meta, create_symlinks=create_symlinks)
659             if os.path.isdir(meta.path):
660                 all_dirs.append(meta)
661             else:
662                 if verbose:
663                     print >> sys.stderr, '=', meta.path
664                 try:
665                     meta.apply_to_path(restore_numeric_ids=restore_numeric_ids)
666                 except MetadataApplicationError, e:
667                     add_error(e)
668     all_dirs.sort(key = lambda x : len(x.path), reverse=True)
669     for dir in all_dirs:
670         # Don't need to check xpath -- won't be in all_dirs if not OK.
671         xpath = _clean_up_extract_path(meta.path)
672         if verbose:
673             print >> sys.stderr, '=', meta.path
674         # Shouldn't have to check for risky paths here (omitted above).
675         try:
676             dir.apply_to_path(path=dir.path,
677                               restore_numeric_ids=restore_numeric_ids)
678         except MetadataApplicationError, e:
679             add_error(e)