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, exit, stdin, stdout, stderr
40 ###--------------------------------------------------------------------------
43 QUIS = OS.path.basename(argv[0])
46 stderr.write('%s: %s\n' % (QUIS, msg))
58 ###--------------------------------------------------------------------------
59 ### File system enumeration.
61 class FileInfo (object):
62 def __init__(me, file, st = None):
69 me.st = OS.lstat(file)
75 def enum_walk(file, func):
79 return OS.listdir(name)
81 syserr("failed to read directory `%s': %s" % (name, err.strerror))
89 if fi.st and fi.st.st_dev != dev: pass
90 if fi.st and ST.S_ISDIR(fi.st.st_mode): dd.append(fi)
92 ff.sort(key = lambda fi: fi.name)
93 dd.sort(key = lambda fi: fi.name + '/')
97 if d.st.st_dev == dev:
99 dir([OS.path.join(d.name, e) for e in dirents(d.name)], dev)
101 if file.endswith('/'):
102 cwd = OS.open('.', OS.O_RDONLY)
107 dir(dirents('.'), fi.st.st_dev)
114 if fi.st and ST.S_ISDIR(fi.st.st_mode):
115 dir([OS.path.join(fi.name, e) for e in dirents(fi.name)],
118 def enum_find0(f, func):
123 names = (tail + buf).split('\0')
130 moan("ignored trailing junk after last filename")
132 R_RSYNCESC = RX.compile(r'\\ \# ([0-7]{3})', RX.VERBOSE)
133 def enum_rsync(f, func):
135 ## The format is a little fiddly. Each line consists of PERMS SIZE DATE
136 ## TIME NAME, separated by runs of whitespace, but the NAME starts exactly
137 ## one space character after the TIME and may begin with a space.
138 ## Sequences of the form `\#OOO', where OOO are three octal digits, stand
139 ## for a byte with that value. Newlines, and backslashes which would be
140 ## ambiguous, are converted into this form; all other characters are
143 ## We ignore the stat information and retrieve it ourselves, because it's
144 ## incomplete. Hopefully the dcache is still warm.
147 if line.endswith('\n'): line = line[:-1]
149 ## Extract the escaped name.
150 ff = line.split(None, 3)
152 syserr("ignoring invalid line from rsync: `%s'" % line)
156 spc = tail.index(' ')
158 syserr("ignoring invalid line from rsync: `%s'" % line)
160 name = tail[spc + 1:]
162 ## Now translate escape sequences.
163 name = R_RSYNCESC.sub(lambda m: chr(int(m.group(1), 8)), name)
169 syserr("failed to stat `%s': %s" % (name, err.strerror))
173 ###--------------------------------------------------------------------------
176 class HashCache (object):
182 """CREATE TABLE meta (
183 version INTEGER NOT NULL,
186 """CREATE TABLE hash (
187 ino INTEGER PRIMARY KEY,
188 mtime INTEGER NOT NULL,
189 ctime INTEGER NOT NULL,
190 size INTEGER NOT NULL,
192 seen BOOLEAN NOT NULL DEFAULT TRUE
194 """PRAGMA journal_mode = WAL;"""
197 def __init__(me, file, hash = None):
201 ## We're going this alone, with no cache.
204 die("no hash specified and no database cache to read from")
207 ## Connect to the database.
208 db = DB.connect(file)
209 db.text_factory = str
211 ## See whether we can understand the cache database.
215 c.execute('SELECT version, hash FROM meta')
217 if c.fetchone() is not None:
218 die("cache database corrupt: meta table has mutliple rows")
219 except (DB.Error, TypeError):
222 ## If that didn't work, we'd better clear the thing and start again.
223 ## But only if we know how to initialize it.
226 ## Explain the situation.
227 moan("cache version %s not understood" % v)
230 die("can't initialize cache: no hash function set")
236 die("unknown hash function `%s'" % hash)
239 c.execute('SELECT type, name FROM sqlite_master')
240 for type, name in c.fetchall():
241 c.execute('DROP %s IF EXISTS %s' % (type, name))
243 ## Now we're ready to go.
246 c.execute('INSERT INTO meta VALUES (?, ?)', [me.VERSION, hash])
249 ## Check the hash function if necessary.
252 elif h is not None and h != hash:
253 die("hash mismatch: cache uses %s but %s requested" % (h, hash))
260 def hashfile(me, fi):
262 ## If this isn't a proper file then don't try to hash it.
263 if fi.err or not ST.S_ISREG(fi.st.st_mode):
266 ## See whether there's a valid entry in the cache.
270 'SELECT mtime, size, hash, seen FROM hash WHERE ino = ?;',
275 if mt == fi.st.st_mtime and \
278 c.execute('UPDATE hash SET seen = 1 WHERE ino = ?',
283 ## Hash the file. Beware raciness: update the file information from the
284 ## open descriptor, but set the size from what we actually read.
287 with open(fi.name, 'rb') as f:
290 buf = f.read(me.BUFSZ)
295 fi.st = OS.fstat(f.fileno())
298 except (OSError, IOError), err:
302 hash = hash.encode('hex')
304 ## Insert a record into the database.
307 INSERT OR REPLACE INTO hash
308 (ino, mtime, ctime, size, hash, seen)
333 die("no cache database")
338 c.execute('DELETE FROM hash WHERE ino = ?', [ino])
343 c.execute('UPDATE hash SET seen = 0 WHERE seen')
349 c.execute('DELETE FROM hash WHERE NOT seen')
352 ###--------------------------------------------------------------------------
355 class GenericFormatter (object):
356 def __init__(me, fi):
358 def _fmt_time(me, t):
360 return T.strftime('%Y-%m-%dT%H:%M:%SZ', tm)
361 def _enc_name(me, n):
362 return ' \\-> '.join(n.encode('string_escape').split(' -> '))
364 return me._enc_name(me.fi.name)
368 return '%06o' % me.fi.st.st_mode
370 return me.fi.st.st_size
372 return me._fmt_time(me.fi.st.st_mtime)
374 return '%5d:%d' % (me.fi.st.st_uid, me.fi.st.st_gid)
376 class ErrorFormatter (GenericFormatter):
378 return 'E%d %s' % (me.fi.err.errno, me.fi.err.strerror)
379 def error(me): return 'error'
380 mode = size = mtime = owner = error
382 class SocketFormatter (GenericFormatter):
384 class PipeFormatter (GenericFormatter):
387 class LinkFormatter (GenericFormatter):
388 TYPE = 'symbolic-link'
390 n = GenericFormatter.name(me)
392 d = OS.readlink(me.fi.name)
393 return '%s -> %s' % (n, me._enc_name(d))
395 return '%s -> <E%d %s>' % (n, err.errno, err.strerror)
397 class DirectoryFormatter (GenericFormatter):
399 def name(me): return GenericFormatter.name(me) + '/'
400 def size(me): return 'dir'
402 class DeviceFormatter (GenericFormatter):
404 return '%s %d:%d' % (me.TYPE,
405 OS.major(me.fi.st.st_rdev),
406 OS.minor(me.fi.st.st_rdev))
407 class BlockDeviceFormatter (DeviceFormatter):
408 TYPE = 'block-device'
409 class CharDeviceFormatter (DeviceFormatter):
410 TYPE = 'character-device'
412 class FileFormatter (GenericFormatter):
413 TYPE = 'regular-file'
415 class Reporter (object):
418 ST.S_IFSOCK: SocketFormatter,
419 ST.S_IFDIR: DirectoryFormatter,
420 ST.S_IFLNK: LinkFormatter,
421 ST.S_IFREG: FileFormatter,
422 ST.S_IFBLK: BlockDeviceFormatter,
423 ST.S_IFCHR: CharDeviceFormatter,
424 ST.S_IFIFO: PipeFormatter,
427 def __init__(me, db):
431 me._hsz = int(H.new(db.hash).digest_size)
434 h = me._db.hashfile(fi)
436 fmt = ErrorFormatter(fi)
439 fmt = me.TYMAP[ST.S_IFMT(fi.st.st_mode)](fi)
440 inoidx = fi.st.st_dev, fi.st.st_ino
442 vino = me._inomap[inoidx]
447 vino = '%08x' % (Z.crc32(fi.name + suffix) & 0xffffffff)
448 if vino not in me._vinomap: break
449 suffix = '\0%d' % seq
451 me._inomap[inoidx] = vino
452 if OPTS.compat >= 2: me._vinomap[vino] = inoidx
454 else: info = '[%-*s]' % (2*me._hsz - 2, fmt.info())
455 print '%s %8s %6s %-12s %-20s %20s %s' % (
456 info, vino, fmt.mode(), fmt.owner(),
457 fmt.mtime(), fmt.size(), fmt.name())
459 ###--------------------------------------------------------------------------
460 ### Database clearing from diff files.
462 R_HUNK = RX.compile(r'^@@ -\d+,(\d+) \+\d+,(\d+) @@$')
464 def clear_entry(db, lno, line):
468 if line.startswith('['):
471 moan("failed to parse file entry (type field; line %d)" % lno)
473 ty = line[1:pos].strip()
474 rest = line[pos + 1:]
477 ff = line.split(None, 1)
479 moan("failed to parse file entry (field split; line %d)" % lno)
484 ff = rest.split(None, 5)
486 moan("failed to parse file entry (field split; line %d)" % lno)
488 ino, mode, uidgid, mtime, sz, name = ff
490 if ty != 'symbolic-link':
493 nn = name.split(' -> ', 1)
495 moan("failed to parse file entry (name split; line %d)" % lno)
498 target = target.decode('string_escape')
499 name = name.decode('string_escape')
504 moan("failed to stat `%s': %s" % (name, e.strerror))
505 if e.errno != E.ENOENT: good = False
507 print "Clear cache entry for `%s'" % name
514 ## Work through the input diff file one line at a time.
519 if line.endswith('\n'): line = line[:-1]
522 ## We're in a gap between hunks. Find a hunk header and extract the line
524 if diffstate == 'gap':
525 m = R_HUNK.match(line)
527 oldlines = int(m.group(1))
528 newlines = int(m.group(2))
532 ## We're in a hunk. Keep track of whether we've reached the end, and
533 ## discard entries from the cache for mismatching lines.
534 elif diffstate == 'hunk':
536 moan("empty line in diff hunk (line %d)" % lno)
540 oldlines -= 1; newlines -= 1
543 if not clear_entry(db, lno, line[1:]): good = False
546 if not clear_entry(db, lno, line[1:]): good = False
548 moan("incomprehensible line in diff hunk (line %d)" % lno)
550 if oldlines < 0 or newlines < 0:
551 moan("inconsistent lengths in diff hunk header (line %d)" % hdrlno)
553 if oldlines == newlines == 0:
556 if diffstate == 'hunk':
557 moan("truncated diff hunk (started at line %d)" % hdrlno)
562 ###--------------------------------------------------------------------------
566 'rsync': lambda f: enum_rsync(stdin, f),
567 'find0': lambda f: enum_find0(stdin, f)
569 op = OP.OptionParser(
570 usage = '%prog [-au] [-c CACHE] [-f FORMAT] [-H HASH] [FILE ...]',
571 version = '%%prog, version %s' % VERSION,
573 Print a digest of a filesystem (or a collection of specified files) to
574 standard output. The idea is that the digest should be mostly /complete/
575 (i.e., any `interesting\' change to the filesystem results in a different
576 digest) and /canonical/ (i.e., identical filesystem contents result in
580 for short, long, props in [
581 ('-a', '--all', { 'action': 'store_true', 'dest': 'all',
582 'help': 'clear cache of all files not seen' }),
583 ('-c', '--cache', { 'dest': 'cache', 'metavar': 'FILE',
584 'help': 'use FILE as a cache for file hashes' }),
585 ('-f', '--files', { 'dest': 'files', 'metavar': 'FORMAT',
586 'type': 'choice', 'choices': FMTMAP.keys(),
587 'help': 'read files to report in the given FORMAT' }),
588 ('-u', '--udiff', { 'action': 'store_true', 'dest': 'udiff',
589 'help': 'read diff from stdin, clear cache entries' }),
590 ('-C', '--compat', { 'dest': 'compat', 'metavar': 'VERSION',
591 'type': 'int', 'default': 2,
592 'help': 'produce output with given compatibility VERSION' }),
593 ('-H', '--hash', { 'dest': 'hash', 'metavar': 'HASH',
594 ##'type': 'choice', 'choices': H.algorithms,
595 'help': 'use HASH as the hash function' })]:
596 op.add_option(short, long, **props)
597 OPTS, args = op.parse_args(argv)
598 if not 1 <= OPTS.compat <= 2:
599 die("unknown compatibility version %d" % OPTS.compat)
601 if OPTS.cache is None or OPTS.all or OPTS.files or len(args) > 2:
602 die("incompatible options: `-u' requires `-c CACHE', forbids others")
603 db = HashCache(OPTS.cache, OPTS.hash)
604 if len(args) == 2: OS.chdir(args[1])
606 if not clear_cache(db): good = False
610 if not OPTS.files and len(args) <= 1:
611 die("no filename sources: nothing to do")
612 db = HashCache(OPTS.cache, OPTS.hash)
616 print "## fshash report format version %d" % OPTS.compat
619 FMTMAP[OPTS.files](rep.file)
621 enum_walk(dir, rep.file)
626 ###----- That's all, folks --------------------------------------------------