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