]> arthur.barton.de Git - bup.git/blob - lib/bup/metadata.py
7325355656fd1eb8c38534f689c548c04552c4ab
[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 MetadataAcquisitionError(Exception):
150     # Thrown when unable to extract any given bit of metadata from a path.
151     pass
152
153
154 class MetadataApplicationError(Exception):
155     # Thrown when unable to apply any given bit of metadata to a path.
156     pass
157
158
159 class Metadata:
160     # Metadata is stored as a sequence of tagged binary records.  Each
161     # record will have some subset of add, encode, load, create, and
162     # apply methods, i.e. _add_foo...
163
164     ## Common records
165
166     # Timestamps are (sec, ns), relative to 1970-01-01 00:00:00, ns
167     # must be non-negative and < 10**9.
168
169     def _add_common(self, path, st):
170         self.mode = st.st_mode
171         self.uid = st.st_uid
172         self.gid = st.st_gid
173         self.rdev = st.st_rdev
174         self.atime = st.st_atime
175         self.mtime = st.st_mtime
176         self.ctime = st.st_ctime
177         self.owner = pwd.getpwuid(st.st_uid)[0]
178         self.group = grp.getgrgid(st.st_gid)[0]
179
180     def _encode_common(self):
181         atime = self.atime.to_timespec()
182         mtime = self.mtime.to_timespec()
183         ctime = self.ctime.to_timespec()
184         result = vint.pack('VVsVsVvVvVvV',
185                            self.mode,
186                            self.uid,
187                            self.owner,
188                            self.gid,
189                            self.group,
190                            self.rdev,
191                            atime[0],
192                            atime[1],
193                            mtime[0],
194                            mtime[1],
195                            ctime[0],
196                            ctime[1])
197         return result
198
199     def _load_common_rec(self, port):
200         data = vint.read_bvec(port)
201         (self.mode,
202          self.uid,
203          self.owner,
204          self.gid,
205          self.group,
206          self.rdev,
207          self.atime,
208          atime_ns,
209          self.mtime,
210          mtime_ns,
211          self.ctime,
212          ctime_ns) = vint.unpack('VVsVsVvVvVvV', data)
213         self.atime = FSTime.from_timespec((self.atime, atime_ns))
214         self.mtime = FSTime.from_timespec((self.mtime, mtime_ns))
215         self.ctime = FSTime.from_timespec((self.ctime, ctime_ns))
216
217     def _create_via_common_rec(self, path, create_symlinks=True):
218         # If the path already exists and is a dir, try rmdir.
219         # If the path already exists and is anything else, try unlink.
220         st = None
221         try:
222             st = lstat(path)
223         except IOError, e:
224             if e.errno != errno.ENOENT:
225                 raise
226         if st:
227             if stat.S_ISDIR(st.st_mode):
228                 try:
229                     os.rmdir(path)
230                 except OSError, e:
231                     if e.errno == errno.ENOTEMPTY:
232                         msg = 'refusing to overwrite non-empty dir' + path
233                         raise Exception(msg)
234                     raise
235             else:
236                 os.unlink(path)
237
238         if stat.S_ISREG(self.mode):
239             os.mknod(path, 0600 | stat.S_IFREG)
240         elif stat.S_ISDIR(self.mode):
241             os.mkdir(path, 0700)
242         elif stat.S_ISCHR(self.mode):
243             os.mknod(path, 0600 | stat.S_IFCHR, self.rdev)
244         elif stat.S_ISBLK(self.mode):
245             os.mknod(path, 0600 | stat.S_IFBLK, self.rdev)
246         elif stat.S_ISFIFO(self.mode):
247             os.mknod(path, 0600 | stat.S_IFIFO)
248         elif stat.S_ISLNK(self.mode):
249             if(self.symlink_target and create_symlinks):
250                 os.symlink(self.symlink_target, path)
251         # FIXME: S_ISDOOR, S_IFMPB, S_IFCMP, S_IFNWK, ... see stat(2).
252         # Otherwise, do nothing.
253
254     def _apply_common_rec(self, path, restore_numeric_ids=False):
255         # FIXME: S_ISDOOR, S_IFMPB, S_IFCMP, S_IFNWK, ... see stat(2).
256         if stat.S_ISLNK(self.mode):
257             lutime(path, (self.atime, self.mtime))
258         else:
259             utime(path, (self.atime, self.mtime))
260         if stat.S_ISREG(self.mode) \
261                 | stat.S_ISDIR(self.mode) \
262                 | stat.S_ISCHR(self.mode) \
263                 | stat.S_ISBLK(self.mode) \
264                 | stat.S_ISLNK(self.mode) \
265                 | stat.S_ISFIFO(self.mode):
266             # Be safe.
267             if _have_lchmod:
268                 os.lchmod(path, 0)
269             elif not stat.S_ISLNK(self.mode):
270                 os.chmod(path, 0)
271
272             # Don't try to restore owner unless we're root, and even
273             # if asked, don't try to restore the owner or group if
274             # it doesn't exist in the system db.
275             uid = self.uid
276             gid = self.gid
277             if not restore_numeric_ids:
278                 if os.geteuid() == 0:
279                     try:
280                         uid = pwd.getpwnam(self.owner)[2]
281                     except KeyError:
282                         uid = -1
283                         log('bup: ignoring unknown owner %s for "%s"\n'
284                             % (self.owner, path))
285                 else:
286                     uid = -1 # Not root; assume we can't change owner.
287                 try:
288                     gid = grp.getgrnam(self.group)[2]
289                 except KeyError:
290                     gid = -1
291                     log('bup: ignoring unknown group %s for "%s"\n'
292                         % (self.group, path))
293             os.lchown(path, uid, gid)
294
295             if _have_lchmod:
296                 os.lchmod(path, stat.S_IMODE(self.mode))
297             elif not stat.S_ISLNK(self.mode):
298                 os.chmod(path, stat.S_IMODE(self.mode))
299
300
301     ## Path records
302
303     def _encode_path(self):
304         if self.path:
305             return vint.pack('s', self.path)
306         else:
307             return None
308
309     def _load_path_rec(self, port):
310         self.path = vint.unpack('s', vint.read_bvec(port))[0]
311
312
313     ## Symlink targets
314
315     def _add_symlink_target(self, path, st):
316         if(stat.S_ISLNK(st.st_mode)):
317             self.symlink_target = os.readlink(path)
318
319     def _encode_symlink_target(self):
320         return self.symlink_target
321
322     def _load_symlink_target_rec(self, port):
323         self.symlink_target = vint.read_bvec(port)
324
325
326     ## POSIX1e ACL records
327
328     # Recorded as a list:
329     #   [txt_id_acl, num_id_acl]
330     # or, if a directory:
331     #   [txt_id_acl, num_id_acl, txt_id_default_acl, num_id_default_acl]
332     # The numeric/text distinction only matters when reading/restoring
333     # a stored record.
334     def _add_posix1e_acl(self, path, st):
335         if not stat.S_ISLNK(st.st_mode):
336             try:
337                 if posix1e.has_extended(path):
338                     acl = posix1e.ACL(file=path)
339                     self.posix1e_acl = [acl, acl] # txt and num are the same
340                     if stat.S_ISDIR(st.st_mode):
341                         acl = posix1e.ACL(filedef=path)
342                         self.posix1e_acl.extend([acl, acl])
343             except EnvironmentError, e:
344                 if e.errno != errno.EOPNOTSUPP:
345                     raise
346
347     def _encode_posix1e_acl(self):
348         # Encode as two strings (w/default ACL string possibly empty).
349         if self.posix1e_acl:
350             acls = self.posix1e_acl
351             txt_flags = posix1e.TEXT_ABBREVIATE
352             num_flags = posix1e.TEXT_ABBREVIATE | posix1e.TEXT_NUMERIC_IDS
353             acl_reps = [acls[0].to_any_text('', '\n', txt_flags),
354                         acls[1].to_any_text('', '\n', num_flags)]
355             if(len(acls) < 3):
356                 acl_reps += ['', '']
357             else:
358                 acl_reps.append(acls[2].to_any_text('', '\n', txt_flags))
359                 acl_reps.append(acls[3].to_any_text('', '\n', num_flags))
360             return vint.pack('ssss',
361                              acl_reps[0], acl_reps[1], acl_reps[2], acl_reps[3])
362         else:
363             return None
364
365     def _load_posix1e_acl_rec(self, port):
366         data = vint.read_bvec(port)
367         acl_reps = vint.unpack('ssss', data)
368         if(acl_reps[2] == ''):
369             acl_reps = acl_reps[:2]
370         self.posix1e_acl = [posix1e.ACL(x) for x in acl_reps]
371
372     def _apply_posix1e_acl_rec(self, path, restore_numeric_ids=False):
373         if(self.posix1e_acl):
374             acls = self.posix1e_acl
375             if(len(acls) > 2):
376                 if restore_numeric_ids:
377                     acls[3].applyto(path, posix1e.ACL_TYPE_DEFAULT)
378                 else:
379                     acls[2].applyto(path, posix1e.ACL_TYPE_DEFAULT)
380             if restore_numeric_ids:
381                 acls[1].applyto(path, posix1e.ACL_TYPE_ACCESS)
382             else:
383                 acls[0].applyto(path, posix1e.ACL_TYPE_ACCESS)
384
385
386     ## Linux attributes (lsattr(1), chattr(1))
387
388     def _add_linux_attr(self, path, st):
389         if stat.S_ISREG(st.st_mode) or stat.S_ISDIR(st.st_mode):
390             attr = get_linux_file_attr(path)
391             if(attr != 0):
392                 self.linux_attr = get_linux_file_attr(path)
393
394     def _encode_linux_attr(self):
395         if self.linux_attr:
396             return vint.pack('V', self.linux_attr)
397         else:
398             return None
399
400     def _load_linux_attr_rec(self, port):
401         data = vint.read_bvec(port)
402         self.linux_attr = vint.unpack('V', data)[0]
403
404     def _apply_linux_attr_rec(self, path, restore_numeric_ids=False):
405         if(self.linux_attr):
406             set_linux_file_attr(path, self.linux_attr)
407
408
409     ## Linux extended attributes (getfattr(1), setfattr(1))
410
411     def _add_linux_xattr(self, path, st):
412         try:
413             self.linux_xattr = xattr.get_all(path, nofollow=True)
414         except EnvironmentError, e:
415             if e.errno != errno.EOPNOTSUPP:
416                 raise
417
418     def _encode_linux_xattr(self):
419         if self.linux_xattr:
420             result = vint.pack('V', len(self.linux_xattr))
421             for name, value in self.linux_xattr:
422                 result += vint.pack('ss', name, value)
423             return result
424         else:
425             return None
426
427     def _load_linux_xattr_rec(self, file):
428         data = vint.read_bvec(file)
429         memfile = StringIO(data)
430         result = []
431         for i in range(vint.read_vuint(memfile)):
432             key = vint.read_bvec(memfile)
433             value = vint.read_bvec(memfile)
434             result.append((key, value))
435         self.linux_xattr = result
436
437     def _apply_linux_xattr_rec(self, path, restore_numeric_ids=False):
438         if(self.linux_xattr):
439             for k, v in self.linux_xattr:
440                 xattr.set(path, k, v, nofollow=True)
441
442     def __init__(self):
443         # optional members
444         self.path = None
445         self.symlink_target = None
446         self.linux_attr = None
447         self.linux_xattr = None
448         self.posix1e_acl = None
449         self.posix1e_acl_default = None
450
451     def write(self, port, include_path=True):
452         records = [(_rec_tag_path, self._encode_path())] if include_path else []
453         records.extend([(_rec_tag_common, self._encode_common()),
454                         (_rec_tag_symlink_target, self._encode_symlink_target()),
455                         (_rec_tag_posix1e_acl, self._encode_posix1e_acl()),
456                         (_rec_tag_linux_attr, self._encode_linux_attr()),
457                         (_rec_tag_linux_xattr, self._encode_linux_xattr())])
458         for tag, data in records:
459             if data:
460                 vint.write_vuint(port, tag)
461                 vint.write_bvec(port, data)
462         vint.write_vuint(port, _rec_tag_end)
463
464     @staticmethod
465     def read(port):
466         # This method should either: return a valid Metadata object;
467         # throw EOFError if there was nothing at all to read; throw an
468         # Exception if a valid object could not be read completely.
469         tag = vint.read_vuint(port)
470         try: # From here on, EOF is an error.
471             result = Metadata()
472             while(True): # only exit is error (exception) or _rec_tag_end
473                 if tag == _rec_tag_path:
474                     result._load_path_rec(port)
475                 elif tag == _rec_tag_common:
476                     result._load_common_rec(port)
477                 elif tag == _rec_tag_symlink_target:
478                     result._load_symlink_target_rec(port)
479                 elif tag == _rec_tag_posix1e_acl:
480                     result._load_posix1e_acl(port)
481                 elif tag ==_rec_tag_nfsv4_acl:
482                     result._load_nfsv4_acl_rec(port)
483                 elif tag == _rec_tag_linux_attr:
484                     result._load_linux_attr_rec(port)
485                 elif tag == _rec_tag_linux_xattr:
486                     result._load_linux_xattr_rec(port)
487                 elif tag == _rec_tag_end:
488                     return result
489                 else: # unknown record
490                     vint.skip_bvec(port)
491                 tag = vint.read_vuint(port)
492         except EOFError:
493             raise Exception("EOF while reading Metadata")
494
495     def isdir(self):
496         return stat.S_ISDIR(self.mode)
497
498     def create_path(self, path, create_symlinks=True):
499         self._create_via_common_rec(path, create_symlinks=create_symlinks)
500
501     def apply_to_path(self, path=None, restore_numeric_ids=False):
502         # apply metadata to path -- file must exist
503         if not path:
504             path = self.path
505         if not path:
506             raise Exception('Metadata.apply_to_path() called with no path');
507         num_ids = restore_numeric_ids
508         try: # Later we may want to push this down and make it finer grained.
509             self._apply_common_rec(path, restore_numeric_ids=num_ids)
510             self._apply_posix1e_acl_rec(path, restore_numeric_ids=num_ids)
511             self._apply_linux_attr_rec(path, restore_numeric_ids=num_ids)
512             self._apply_linux_xattr_rec(path, restore_numeric_ids=num_ids)
513         except Exception, e:
514             raise MetadataApplicationError(e)
515
516
517 def from_path(path, archive_path=None, save_symlinks=True):
518     result = Metadata()
519     result.path = archive_path
520     st = lstat(path)
521     try: # Later we may want to push this down and make it finer grained.
522         result._add_common(path, st)
523         if(save_symlinks):
524             result._add_symlink_target(path, st)
525         result._add_posix1e_acl(path, st)
526         result._add_linux_attr(path, st)
527         result._add_linux_xattr(path, st)
528     except Exception, e:
529         raise MetadataAcquisitionError(e)
530     return result
531
532
533 def save_tree(output_file, paths,
534               recurse=False,
535               write_paths=True,
536               save_symlinks=True,
537               xdev=False):
538
539     # Issue top-level rewrite warnings.
540     for path in paths:
541         safe_path = _clean_up_path_for_archive(path)
542         if(safe_path != path):
543             log('bup: archiving "%s" as "%s"\n' % (path, safe_path))
544
545     start_dir = os.getcwd()
546     try:
547         for (p, st) in recursive_dirlist(paths, xdev=xdev):
548             dirlist_dir = os.getcwd()
549             os.chdir(start_dir)
550             safe_path = _clean_up_path_for_archive(p)
551             try:
552                 m = from_path(p, archive_path=safe_path,
553                               save_symlinks=save_symlinks)
554             except MetadataAcquisitionError, e:
555                 add_error(e)
556
557             if verbose:
558                 print >> sys.stderr, m.path
559             m.write(output_file, include_path=write_paths)
560             os.chdir(dirlist_dir)
561     finally:
562         os.chdir(start_dir)
563
564
565 def _set_up_path(meta, create_symlinks=True):
566     # Allow directories to exist as a special case -- might have
567     # been created by an earlier longer path.
568     if meta.isdir():
569         mkdirp(meta.path, 0700)
570     else:
571         parent = os.path.dirname(meta.path)
572         if parent:
573             mkdirp(parent, 0700)
574             meta.create_path(meta.path, create_symlinks=create_symlinks)
575
576
577 class _ArchiveIterator:
578     def next(self):
579         try:
580             return Metadata.read(self._file)
581         except EOFError:
582             raise StopIteration()
583
584     def __iter__(self):
585         return self
586
587     def __init__(self, file):
588         self._file = file
589
590
591 def display_archive(file):
592     for meta in _ArchiveIterator(file):
593         if verbose:
594             print meta.path # FIXME
595         else:
596             print meta.path
597
598
599 def start_extract(file, create_symlinks=True):
600     for meta in _ArchiveIterator(file):
601         if verbose:
602             print >> sys.stderr, meta.path
603         xpath = _clean_up_extract_path(meta.path)
604         if not xpath:
605             add_error(Exception('skipping risky path "%s"' % meta.path))
606         else:
607             meta.path = xpath
608             _set_up_path(meta, create_symlinks=create_symlinks)
609
610
611 def finish_extract(file, restore_numeric_ids=False):
612     all_dirs = []
613     for meta in _ArchiveIterator(file):
614         xpath = _clean_up_extract_path(meta.path)
615         if not xpath:
616             add_error(Exception('skipping risky path "%s"' % dir.path))
617         else:
618             if os.path.isdir(meta.path):
619                 all_dirs.append(meta)
620             else:
621                 if verbose:
622                     print >> sys.stderr, meta.path
623                 try:
624                     meta.apply_to_path(path=xpath,
625                                        restore_numeric_ids=restore_numeric_ids)
626                 except MetadataApplicationError, e:
627                     add_error(e)
628
629     all_dirs.sort(key = lambda x : len(x.path), reverse=True)
630     for dir in all_dirs:
631         # Don't need to check xpath -- won't be in all_dirs if not OK.
632         xpath = _clean_up_extract_path(dir.path)
633         if verbose:
634             print >> sys.stderr, dir.path
635         try:
636             dir.apply_to_path(path=xpath,
637                               restore_numeric_ids=restore_numeric_ids)
638         except MetadataApplicationError, e:
639             add_error(e)
640
641
642 def extract(file, restore_numeric_ids=False, create_symlinks=True):
643     # For now, just store all the directories and handle them last,
644     # longest first.
645     all_dirs = []
646     for meta in _ArchiveIterator(file):
647         xpath = _clean_up_extract_path(meta.path)
648         if not xpath:
649             add_error(Exception('skipping risky path "%s"' % meta.path))
650         else:
651             meta.path = xpath
652             if verbose:
653                 print >> sys.stderr, '+', meta.path
654             _set_up_path(meta, create_symlinks=create_symlinks)
655             if os.path.isdir(meta.path):
656                 all_dirs.append(meta)
657             else:
658                 if verbose:
659                     print >> sys.stderr, '=', meta.path
660                 try:
661                     meta.apply_to_path(restore_numeric_ids=restore_numeric_ids)
662                 except MetadataApplicationError, e:
663                     add_error(e)
664     all_dirs.sort(key = lambda x : len(x.path), reverse=True)
665     for dir in all_dirs:
666         # Don't need to check xpath -- won't be in all_dirs if not OK.
667         xpath = _clean_up_extract_path(meta.path)
668         if verbose:
669             print >> sys.stderr, '=', meta.path
670         # Shouldn't have to check for risky paths here (omitted above).
671         try:
672             dir.apply_to_path(path=dir.path,
673                               restore_numeric_ids=restore_numeric_ids)
674         except MetadataApplicationError, e:
675             add_error(e)