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