3 ### Efficiently construct canonical digests of filesystems
5 ### (c) 2012 Mark Wooding
8 ###----- Licensing notice ---------------------------------------------------
10 ### This file is part of the `rsync-backup' program.
12 ### rsync-backup is free software; you can redistribute it and/or modify
13 ### it under the terms of the GNU General Public License as published by
14 ### the Free Software Foundation; either version 2 of the License, or
15 ### (at your option) any later version.
17 ### rsync-backup is distributed in the hope that it will be useful,
18 ### but WITHOUT ANY WARRANTY; without even the implied warranty of
19 ### MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 ### GNU General Public License for more details.
22 ### You should have received a copy of the GNU General Public License
23 ### along with rsync-backup; if not, write to the Free Software Foundation,
24 ### Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
26 from sys import argv, exc_info, exit, stdin, stdout, stderr
41 ###--------------------------------------------------------------------------
44 from cStringIO import StringIO; BytesIO = StringIO
47 def bytechr(x): return chr(x)
48 def byteord(x): return ord(x)
49 def excval(): return exc_info()[1]
51 QUIS = OS.path.basename(argv[0])
54 stderr.write('%s: %s\n' % (QUIS, msg))
70 if k == 9: out.write("\\t")
71 elif k == 10: out.write("\\n")
72 elif k == 13: out.write("\\r")
73 elif k == 39: out.write("\\'")
74 elif k == 92: out.write("\\\\")
75 elif 20 <= k <= 126: out.write(chr(k))
76 else: out.write("\\x%02x" % k)
79 R_STRESC = RX.compile(r"\\ (?: x ([0-9A-Fa-f]{2}) | (.))",
85 m = R_STRESC.search(x, i)
86 if m is not None: j = m.start(0)
88 str.write(bin(str[i:j]))
90 k, e = m.group(1), m.group(2)
91 if k is not None: ch = int(k, 16)
92 elif ch == "a": ch = 7
93 elif ch == "b": ch = 8
94 elif ch == "f": ch = 12
95 elif ch == "n": ch = 10
96 elif ch == "r": ch = 13
97 elif ch == "t": ch = 9
98 elif ch == "v": ch = 11
100 str.write(bytechr(ch))
102 return text(out.getvalue())
104 ###--------------------------------------------------------------------------
105 ### File system enumeration.
107 class FileInfo (object):
108 def __init__(me, file, st = None):
115 me.st = OS.lstat(file)
121 def enum_walk(file, func):
125 return OS.listdir(name)
127 syserr("failed to read directory `%s': %s" % (name, excval().strerror))
135 if fi.st and fi.st.st_dev != dev: pass
136 if fi.st and ST.S_ISDIR(fi.st.st_mode): dd.append(fi)
138 ff.sort(key = lambda fi: fi.name)
139 dd.sort(key = lambda fi: fi.name + '/')
143 if d.st.st_dev == dev:
145 dir([OS.path.join(d.name, e) for e in dirents(d.name)], dev)
147 if file.endswith('/'):
148 cwd = OS.open('.', OS.O_RDONLY)
153 dir(dirents('.'), fi.st.st_dev)
160 if fi.st and ST.S_ISDIR(fi.st.st_mode):
161 dir([OS.path.join(fi.name, e) for e in dirents(fi.name)],
164 def enum_find0(f, func):
169 names = (tail + buf).split('\0')
176 moan("ignored trailing junk after last filename")
178 R_RSYNCESC = RX.compile(r'\\ \# ([0-7]{3})', RX.VERBOSE)
179 def enum_rsync(f, func):
181 ## The format is a little fiddly. Each line consists of PERMS SIZE DATE
182 ## TIME NAME, separated by runs of whitespace, but the NAME starts exactly
183 ## one space character after the TIME and may begin with a space.
184 ## Sequences of the form `\#OOO', where OOO are three octal digits, stand
185 ## for a byte with that value. Newlines, and backslashes which would be
186 ## ambiguous, are converted into this form; all other characters are
189 ## We ignore the stat information and retrieve it ourselves, because it's
190 ## incomplete. Hopefully the dcache is still warm.
193 if line.endswith('\n'): line = line[:-1]
195 ## Extract the escaped name.
196 ff = line.split(None, 3)
198 syserr("ignoring invalid line from rsync: `%s'" % line)
202 spc = tail.index(' ')
204 syserr("ignoring invalid line from rsync: `%s'" % line)
206 name = tail[spc + 1:]
208 ## Now translate escape sequences.
209 name = R_RSYNCESC.sub(lambda m: chr(int(m.group(1), 8)), name)
215 syserr("failed to stat `%s': %s" % (name, excval().strerror))
219 ###--------------------------------------------------------------------------
222 class HashCache (object):
228 """CREATE TABLE meta (
229 version INTEGER NOT NULL,
232 """CREATE TABLE hash (
233 ino INTEGER PRIMARY KEY,
234 mtime INTEGER NOT NULL,
235 ctime INTEGER NOT NULL,
236 size INTEGER NOT NULL,
238 seen BOOLEAN NOT NULL DEFAULT TRUE
240 """PRAGMA journal_mode = WAL;"""
243 def __init__(me, file, hash = None):
247 ## We're going this alone, with no cache.
250 die("no hash specified and no database cache to read from")
253 ## Connect to the database.
254 db = DB.connect(file)
255 db.text_factory = str
257 ## See whether we can understand the cache database.
261 c.execute('SELECT version, hash FROM meta')
263 if c.fetchone() is not None:
264 die("cache database corrupt: meta table has mutliple rows")
265 except (DB.Error, TypeError):
268 ## If that didn't work, we'd better clear the thing and start again.
269 ## But only if we know how to initialize it.
272 ## Explain the situation.
273 moan("cache version %s not understood" % v)
276 die("can't initialize cache: no hash function set")
282 die("unknown hash function `%s'" % hash)
285 c.execute('SELECT type, name FROM sqlite_master')
286 for type, name in c.fetchall():
287 c.execute('DROP %s IF EXISTS %s' % (type, name))
289 ## Now we're ready to go.
292 c.execute('INSERT INTO meta VALUES (?, ?)', [me.VERSION, hash])
295 ## Check the hash function if necessary.
298 elif h is not None and h != hash:
299 die("hash mismatch: cache uses %s but %s requested" % (h, hash))
306 def hashfile(me, fi):
308 ## If this isn't a proper file then don't try to hash it.
309 if fi.err or not ST.S_ISREG(fi.st.st_mode):
312 ## See whether there's a valid entry in the cache.
316 'SELECT mtime, size, hash, seen FROM hash WHERE ino = ?;',
321 if mt == fi.st.st_mtime and \
324 c.execute('UPDATE hash SET seen = 1 WHERE ino = ?',
329 ## Hash the file. Beware raciness: update the file information from the
330 ## open descriptor, but set the size from what we actually read.
333 with open(fi.name, 'rb') as f:
336 buf = f.read(me.BUFSZ)
341 fi.st = OS.fstat(f.fileno())
344 except (OSError, IOError):
348 hash = text(B.hexlify(hash))
350 ## Insert a record into the database.
353 INSERT OR REPLACE INTO hash
354 (ino, mtime, ctime, size, hash, seen)
379 die("no cache database")
384 c.execute('DELETE FROM hash WHERE ino = ?', [ino])
389 c.execute('UPDATE hash SET seen = 0 WHERE seen')
395 c.execute('DELETE FROM hash WHERE NOT seen')
398 ###--------------------------------------------------------------------------
401 class GenericFormatter (object):
402 def __init__(me, fi):
404 def _fmt_time(me, t):
406 return T.strftime('%Y-%m-%dT%H:%M:%SZ', tm)
407 def _enc_name(me, n):
408 return ' \\-> '.join(escapify(n).split(' -> '))
410 return me._enc_name(me.fi.name)
414 return '%06o' % me.fi.st.st_mode
416 return me.fi.st.st_size
418 return me._fmt_time(me.fi.st.st_mtime)
420 return '%5d:%d' % (me.fi.st.st_uid, me.fi.st.st_gid)
422 class ErrorFormatter (GenericFormatter):
424 return 'E%d %s' % (me.fi.err.errno, me.fi.err.strerror)
425 def error(me): return 'error'
426 mode = size = mtime = owner = error
428 class SocketFormatter (GenericFormatter):
430 class PipeFormatter (GenericFormatter):
433 class LinkFormatter (GenericFormatter):
434 TYPE = 'symbolic-link'
436 n = GenericFormatter.name(me)
438 d = OS.readlink(me.fi.name)
439 return '%s -> %s' % (n, me._enc_name(d))
442 return '%s -> <E%d %s>' % (n, err.errno, err.strerror)
444 class DirectoryFormatter (GenericFormatter):
446 def name(me): return GenericFormatter.name(me) + '/'
447 def size(me): return 'dir'
449 class DeviceFormatter (GenericFormatter):
451 return '%s %d:%d' % (me.TYPE,
452 OS.major(me.fi.st.st_rdev),
453 OS.minor(me.fi.st.st_rdev))
454 class BlockDeviceFormatter (DeviceFormatter):
455 TYPE = 'block-device'
456 class CharDeviceFormatter (DeviceFormatter):
457 TYPE = 'character-device'
459 class FileFormatter (GenericFormatter):
460 TYPE = 'regular-file'
462 class Reporter (object):
465 ST.S_IFSOCK: SocketFormatter,
466 ST.S_IFDIR: DirectoryFormatter,
467 ST.S_IFLNK: LinkFormatter,
468 ST.S_IFREG: FileFormatter,
469 ST.S_IFBLK: BlockDeviceFormatter,
470 ST.S_IFCHR: CharDeviceFormatter,
471 ST.S_IFIFO: PipeFormatter,
474 def __init__(me, db):
478 me._hsz = int(H.new(db.hash).digest_size)
481 h = me._db.hashfile(fi)
483 fmt = ErrorFormatter(fi)
486 fmt = me.TYMAP[ST.S_IFMT(fi.st.st_mode)](fi)
487 inoidx = fi.st.st_dev, fi.st.st_ino
489 vino = me._inomap[inoidx]
494 vino = '%08x' % (Z.crc32(bin(fi.name + suffix)) & 0xffffffff)
495 if vino not in me._vinomap: break
496 suffix = '\0%d' % seq
498 me._inomap[inoidx] = vino
499 if OPTS.compat >= 2: me._vinomap[vino] = inoidx
501 else: info = '[%-*s]' % (2*me._hsz - 2, fmt.info())
502 print('%s %8s %6s %-12s %-20s %20s %s' %
503 (info, vino, fmt.mode(), fmt.owner(),
504 fmt.mtime(), fmt.size(), fmt.name()))
506 ###--------------------------------------------------------------------------
507 ### Database clearing from diff files.
509 R_HUNK = RX.compile(r'^@@ -\d+,(\d+) \+\d+,(\d+) @@$')
511 def clear_entry(db, lno, line):
515 if line.startswith('['):
518 moan("failed to parse file entry (type field; line %d)" % lno)
520 ty = line[1:pos].strip()
521 rest = line[pos + 1:]
524 ff = line.split(None, 1)
526 moan("failed to parse file entry (field split; line %d)" % lno)
531 ff = rest.split(None, 5)
533 moan("failed to parse file entry (field split; line %d)" % lno)
535 ino, mode, uidgid, mtime, sz, name = ff
537 if ty != 'symbolic-link':
540 nn = name.split(' -> ', 1)
542 moan("failed to parse file entry (name split; line %d)" % lno)
545 target = unescapify(target)
546 name = unescapify(name)
552 moan("failed to stat `%s': %s" % (name, e.strerror))
553 if e.errno != E.ENOENT: good = False
555 print("Clear cache entry for `%s'" % name)
562 ## Work through the input diff file one line at a time.
567 if line.endswith('\n'): line = line[:-1]
570 ## We're in a gap between hunks. Find a hunk header and extract the line
572 if diffstate == 'gap':
573 m = R_HUNK.match(line)
575 oldlines = int(m.group(1))
576 newlines = int(m.group(2))
580 ## We're in a hunk. Keep track of whether we've reached the end, and
581 ## discard entries from the cache for mismatching lines.
582 elif diffstate == 'hunk':
584 moan("empty line in diff hunk (line %d)" % lno)
588 oldlines -= 1; newlines -= 1
591 if not clear_entry(db, lno, line[1:]): good = False
594 if not clear_entry(db, lno, line[1:]): good = False
596 moan("incomprehensible line in diff hunk (line %d)" % lno)
598 if oldlines < 0 or newlines < 0:
599 moan("inconsistent lengths in diff hunk header (line %d)" % hdrlno)
601 if oldlines == newlines == 0:
604 if diffstate == 'hunk':
605 moan("truncated diff hunk (started at line %d)" % hdrlno)
610 ###--------------------------------------------------------------------------
614 'rsync': lambda f: enum_rsync(stdin, f),
615 'find0': lambda f: enum_find0(stdin, f)
617 op = OP.OptionParser(
618 usage = '%prog [-au] [-c CACHE] [-f FORMAT] [-H HASH] [FILE ...]',
619 version = '%%prog, version %s' % VERSION,
621 Print a digest of a filesystem (or a collection of specified files) to
622 standard output. The idea is that the digest should be mostly /complete/
623 (i.e., any `interesting\' change to the filesystem results in a different
624 digest) and /canonical/ (i.e., identical filesystem contents result in
628 for short, long, props in [
629 ('-a', '--all', { 'action': 'store_true', 'dest': 'all',
630 'help': 'clear cache of all files not seen' }),
631 ('-c', '--cache', { 'dest': 'cache', 'metavar': 'FILE',
632 'help': 'use FILE as a cache for file hashes' }),
633 ('-f', '--files', { 'dest': 'files', 'metavar': 'FORMAT',
634 'type': 'choice', 'choices': list(FMTMAP.keys()),
635 'help': 'read files to report in the given FORMAT' }),
636 ('-u', '--udiff', { 'action': 'store_true', 'dest': 'udiff',
637 'help': 'read diff from stdin, clear cache entries' }),
638 ('-C', '--compat', { 'dest': 'compat', 'metavar': 'VERSION',
639 'type': 'int', 'default': 2,
640 'help': 'produce output with given compatibility VERSION' }),
641 ('-H', '--hash', { 'dest': 'hash', 'metavar': 'HASH',
642 ##'type': 'choice', 'choices': H.algorithms,
643 'help': 'use HASH as the hash function' })]:
644 op.add_option(short, long, **props)
645 OPTS, args = op.parse_args(argv)
646 if not 1 <= OPTS.compat <= 2:
647 die("unknown compatibility version %d" % OPTS.compat)
649 if OPTS.cache is None or OPTS.all or OPTS.files or len(args) > 2:
650 die("incompatible options: `-u' requires `-c CACHE', forbids others")
651 db = HashCache(OPTS.cache, OPTS.hash)
652 if len(args) == 2: OS.chdir(args[1])
654 if not clear_cache(db): good = False
658 if not OPTS.files and len(args) <= 1:
659 die("no filename sources: nothing to do")
660 db = HashCache(OPTS.cache, OPTS.hash)
664 print("## fshash report format version %d" % OPTS.compat)
667 FMTMAP[OPTS.files](rep.file)
669 enum_walk(dir, rep.file)
674 ###----- That's all, folks --------------------------------------------------