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
40 ###--------------------------------------------------------------------------
43 def excval(): return exc_info()[1]
45 QUIS = OS.path.basename(argv[0])
48 stderr.write('%s: %s\n' % (QUIS, msg))
60 ###--------------------------------------------------------------------------
61 ### File system enumeration.
63 class FileInfo (object):
64 def __init__(me, file, st = None):
71 me.st = OS.lstat(file)
77 def enum_walk(file, func):
81 return OS.listdir(name)
83 syserr("failed to read directory `%s': %s" % (name, excval().strerror))
91 if fi.st and fi.st.st_dev != dev: pass
92 if fi.st and ST.S_ISDIR(fi.st.st_mode): dd.append(fi)
94 ff.sort(key = lambda fi: fi.name)
95 dd.sort(key = lambda fi: fi.name + '/')
99 if d.st.st_dev == dev:
101 dir([OS.path.join(d.name, e) for e in dirents(d.name)], dev)
103 if file.endswith('/'):
104 cwd = OS.open('.', OS.O_RDONLY)
109 dir(dirents('.'), fi.st.st_dev)
116 if fi.st and ST.S_ISDIR(fi.st.st_mode):
117 dir([OS.path.join(fi.name, e) for e in dirents(fi.name)],
120 def enum_find0(f, func):
125 names = (tail + buf).split('\0')
132 moan("ignored trailing junk after last filename")
134 R_RSYNCESC = RX.compile(r'\\ \# ([0-7]{3})', RX.VERBOSE)
135 def enum_rsync(f, func):
137 ## The format is a little fiddly. Each line consists of PERMS SIZE DATE
138 ## TIME NAME, separated by runs of whitespace, but the NAME starts exactly
139 ## one space character after the TIME and may begin with a space.
140 ## Sequences of the form `\#OOO', where OOO are three octal digits, stand
141 ## for a byte with that value. Newlines, and backslashes which would be
142 ## ambiguous, are converted into this form; all other characters are
145 ## We ignore the stat information and retrieve it ourselves, because it's
146 ## incomplete. Hopefully the dcache is still warm.
149 if line.endswith('\n'): line = line[:-1]
151 ## Extract the escaped name.
152 ff = line.split(None, 3)
154 syserr("ignoring invalid line from rsync: `%s'" % line)
158 spc = tail.index(' ')
160 syserr("ignoring invalid line from rsync: `%s'" % line)
162 name = tail[spc + 1:]
164 ## Now translate escape sequences.
165 name = R_RSYNCESC.sub(lambda m: chr(int(m.group(1), 8)), name)
171 syserr("failed to stat `%s': %s" % (name, excval().strerror))
175 ###--------------------------------------------------------------------------
178 class HashCache (object):
184 """CREATE TABLE meta (
185 version INTEGER NOT NULL,
188 """CREATE TABLE hash (
189 ino INTEGER PRIMARY KEY,
190 mtime INTEGER NOT NULL,
191 ctime INTEGER NOT NULL,
192 size INTEGER NOT NULL,
194 seen BOOLEAN NOT NULL DEFAULT TRUE
196 """PRAGMA journal_mode = WAL;"""
199 def __init__(me, file, hash = None):
203 ## We're going this alone, with no cache.
206 die("no hash specified and no database cache to read from")
209 ## Connect to the database.
210 db = DB.connect(file)
211 db.text_factory = str
213 ## See whether we can understand the cache database.
217 c.execute('SELECT version, hash FROM meta')
219 if c.fetchone() is not None:
220 die("cache database corrupt: meta table has mutliple rows")
221 except (DB.Error, TypeError):
224 ## If that didn't work, we'd better clear the thing and start again.
225 ## But only if we know how to initialize it.
228 ## Explain the situation.
229 moan("cache version %s not understood" % v)
232 die("can't initialize cache: no hash function set")
238 die("unknown hash function `%s'" % hash)
241 c.execute('SELECT type, name FROM sqlite_master')
242 for type, name in c.fetchall():
243 c.execute('DROP %s IF EXISTS %s' % (type, name))
245 ## Now we're ready to go.
248 c.execute('INSERT INTO meta VALUES (?, ?)', [me.VERSION, hash])
251 ## Check the hash function if necessary.
254 elif h is not None and h != hash:
255 die("hash mismatch: cache uses %s but %s requested" % (h, hash))
262 def hashfile(me, fi):
264 ## If this isn't a proper file then don't try to hash it.
265 if fi.err or not ST.S_ISREG(fi.st.st_mode):
268 ## See whether there's a valid entry in the cache.
272 'SELECT mtime, size, hash, seen FROM hash WHERE ino = ?;',
277 if mt == fi.st.st_mtime and \
280 c.execute('UPDATE hash SET seen = 1 WHERE ino = ?',
285 ## Hash the file. Beware raciness: update the file information from the
286 ## open descriptor, but set the size from what we actually read.
289 with open(fi.name, 'rb') as f:
292 buf = f.read(me.BUFSZ)
297 fi.st = OS.fstat(f.fileno())
300 except (OSError, IOError):
304 hash = hash.encode('hex')
306 ## Insert a record into the database.
309 INSERT OR REPLACE INTO hash
310 (ino, mtime, ctime, size, hash, seen)
335 die("no cache database")
340 c.execute('DELETE FROM hash WHERE ino = ?', [ino])
345 c.execute('UPDATE hash SET seen = 0 WHERE seen')
351 c.execute('DELETE FROM hash WHERE NOT seen')
354 ###--------------------------------------------------------------------------
357 class GenericFormatter (object):
358 def __init__(me, fi):
360 def _fmt_time(me, t):
362 return T.strftime('%Y-%m-%dT%H:%M:%SZ', tm)
363 def _enc_name(me, n):
364 return ' \\-> '.join(n.encode('string_escape').split(' -> '))
366 return me._enc_name(me.fi.name)
370 return '%06o' % me.fi.st.st_mode
372 return me.fi.st.st_size
374 return me._fmt_time(me.fi.st.st_mtime)
376 return '%5d:%d' % (me.fi.st.st_uid, me.fi.st.st_gid)
378 class ErrorFormatter (GenericFormatter):
380 return 'E%d %s' % (me.fi.err.errno, me.fi.err.strerror)
381 def error(me): return 'error'
382 mode = size = mtime = owner = error
384 class SocketFormatter (GenericFormatter):
386 class PipeFormatter (GenericFormatter):
389 class LinkFormatter (GenericFormatter):
390 TYPE = 'symbolic-link'
392 n = GenericFormatter.name(me)
394 d = OS.readlink(me.fi.name)
395 return '%s -> %s' % (n, me._enc_name(d))
398 return '%s -> <E%d %s>' % (n, err.errno, err.strerror)
400 class DirectoryFormatter (GenericFormatter):
402 def name(me): return GenericFormatter.name(me) + '/'
403 def size(me): return 'dir'
405 class DeviceFormatter (GenericFormatter):
407 return '%s %d:%d' % (me.TYPE,
408 OS.major(me.fi.st.st_rdev),
409 OS.minor(me.fi.st.st_rdev))
410 class BlockDeviceFormatter (DeviceFormatter):
411 TYPE = 'block-device'
412 class CharDeviceFormatter (DeviceFormatter):
413 TYPE = 'character-device'
415 class FileFormatter (GenericFormatter):
416 TYPE = 'regular-file'
418 class Reporter (object):
421 ST.S_IFSOCK: SocketFormatter,
422 ST.S_IFDIR: DirectoryFormatter,
423 ST.S_IFLNK: LinkFormatter,
424 ST.S_IFREG: FileFormatter,
425 ST.S_IFBLK: BlockDeviceFormatter,
426 ST.S_IFCHR: CharDeviceFormatter,
427 ST.S_IFIFO: PipeFormatter,
430 def __init__(me, db):
434 me._hsz = int(H.new(db.hash).digest_size)
437 h = me._db.hashfile(fi)
439 fmt = ErrorFormatter(fi)
442 fmt = me.TYMAP[ST.S_IFMT(fi.st.st_mode)](fi)
443 inoidx = fi.st.st_dev, fi.st.st_ino
445 vino = me._inomap[inoidx]
450 vino = '%08x' % (Z.crc32(fi.name + suffix) & 0xffffffff)
451 if vino not in me._vinomap: break
452 suffix = '\0%d' % seq
454 me._inomap[inoidx] = vino
455 if OPTS.compat >= 2: me._vinomap[vino] = inoidx
457 else: info = '[%-*s]' % (2*me._hsz - 2, fmt.info())
458 print '%s %8s %6s %-12s %-20s %20s %s' % (
459 info, vino, fmt.mode(), fmt.owner(),
460 fmt.mtime(), fmt.size(), fmt.name())
462 ###--------------------------------------------------------------------------
463 ### Database clearing from diff files.
465 R_HUNK = RX.compile(r'^@@ -\d+,(\d+) \+\d+,(\d+) @@$')
467 def clear_entry(db, lno, line):
471 if line.startswith('['):
474 moan("failed to parse file entry (type field; line %d)" % lno)
476 ty = line[1:pos].strip()
477 rest = line[pos + 1:]
480 ff = line.split(None, 1)
482 moan("failed to parse file entry (field split; line %d)" % lno)
487 ff = rest.split(None, 5)
489 moan("failed to parse file entry (field split; line %d)" % lno)
491 ino, mode, uidgid, mtime, sz, name = ff
493 if ty != 'symbolic-link':
496 nn = name.split(' -> ', 1)
498 moan("failed to parse file entry (name split; line %d)" % lno)
501 target = target.decode('string_escape')
502 name = name.decode('string_escape')
508 moan("failed to stat `%s': %s" % (name, e.strerror))
509 if e.errno != E.ENOENT: good = False
511 print "Clear cache entry for `%s'" % name
518 ## Work through the input diff file one line at a time.
523 if line.endswith('\n'): line = line[:-1]
526 ## We're in a gap between hunks. Find a hunk header and extract the line
528 if diffstate == 'gap':
529 m = R_HUNK.match(line)
531 oldlines = int(m.group(1))
532 newlines = int(m.group(2))
536 ## We're in a hunk. Keep track of whether we've reached the end, and
537 ## discard entries from the cache for mismatching lines.
538 elif diffstate == 'hunk':
540 moan("empty line in diff hunk (line %d)" % lno)
544 oldlines -= 1; newlines -= 1
547 if not clear_entry(db, lno, line[1:]): good = False
550 if not clear_entry(db, lno, line[1:]): good = False
552 moan("incomprehensible line in diff hunk (line %d)" % lno)
554 if oldlines < 0 or newlines < 0:
555 moan("inconsistent lengths in diff hunk header (line %d)" % hdrlno)
557 if oldlines == newlines == 0:
560 if diffstate == 'hunk':
561 moan("truncated diff hunk (started at line %d)" % hdrlno)
566 ###--------------------------------------------------------------------------
570 'rsync': lambda f: enum_rsync(stdin, f),
571 'find0': lambda f: enum_find0(stdin, f)
573 op = OP.OptionParser(
574 usage = '%prog [-au] [-c CACHE] [-f FORMAT] [-H HASH] [FILE ...]',
575 version = '%%prog, version %s' % VERSION,
577 Print a digest of a filesystem (or a collection of specified files) to
578 standard output. The idea is that the digest should be mostly /complete/
579 (i.e., any `interesting\' change to the filesystem results in a different
580 digest) and /canonical/ (i.e., identical filesystem contents result in
584 for short, long, props in [
585 ('-a', '--all', { 'action': 'store_true', 'dest': 'all',
586 'help': 'clear cache of all files not seen' }),
587 ('-c', '--cache', { 'dest': 'cache', 'metavar': 'FILE',
588 'help': 'use FILE as a cache for file hashes' }),
589 ('-f', '--files', { 'dest': 'files', 'metavar': 'FORMAT',
590 'type': 'choice', 'choices': FMTMAP.keys(),
591 'help': 'read files to report in the given FORMAT' }),
592 ('-u', '--udiff', { 'action': 'store_true', 'dest': 'udiff',
593 'help': 'read diff from stdin, clear cache entries' }),
594 ('-C', '--compat', { 'dest': 'compat', 'metavar': 'VERSION',
595 'type': 'int', 'default': 2,
596 'help': 'produce output with given compatibility VERSION' }),
597 ('-H', '--hash', { 'dest': 'hash', 'metavar': 'HASH',
598 ##'type': 'choice', 'choices': H.algorithms,
599 'help': 'use HASH as the hash function' })]:
600 op.add_option(short, long, **props)
601 OPTS, args = op.parse_args(argv)
602 if not 1 <= OPTS.compat <= 2:
603 die("unknown compatibility version %d" % OPTS.compat)
605 if OPTS.cache is None or OPTS.all or OPTS.files or len(args) > 2:
606 die("incompatible options: `-u' requires `-c CACHE', forbids others")
607 db = HashCache(OPTS.cache, OPTS.hash)
608 if len(args) == 2: OS.chdir(args[1])
610 if not clear_cache(db): good = False
614 if not OPTS.files and len(args) <= 1:
615 die("no filename sources: nothing to do")
616 db = HashCache(OPTS.cache, OPTS.hash)
620 print "## fshash report format version %d" % OPTS.compat
623 FMTMAP[OPTS.files](rep.file)
625 enum_walk(dir, rep.file)
630 ###----- That's all, folks --------------------------------------------------