Fix merge conflicts.
[rsync-patches.git] / db.diff
1 Added some DB-access routines to help rsync keep extra filesystem info
2 about the files it is dealing with.  This adds both the --db=CONFIG_FILE
3 option and the "db config" daemon parameter.
4
5 Future improvements may include:
6
7  - Updating of MD4 checksums when transferring any file, even w/o -c.
8    To make that work we'd need to make the sender force checksum_seed to
9    0 when using a DB and having the receiving side check to see if it
10    got a 0 checksum_seed.
11
12  - Caching of path info that allows for the finding of files to use for
13    moving/linking/copying/alternate-basis-use.
14
15  - Extend DB support beyond MySQL and SQLite (PostgreSQL?).
16
17 To use this patch, run these commands for a successful build:
18
19     patch -p1 <patches/db.diff
20     ./prepare-source
21     ./configure
22     make
23
24 based-on: af531cf787995f6a3bc381cd1da1988192e7ef59
25 diff --git a/.gitignore b/.gitignore
26 --- a/.gitignore
27 +++ b/.gitignore
28 @@ -30,6 +30,7 @@ aclocal.m4
29  /getgroups
30  /gmon.out
31  /rsync
32 +/rsyncdb
33  /stunnel-rsyncd.conf
34  /shconfig
35  /testdir
36 diff --git a/Makefile.in b/Makefile.in
37 --- a/Makefile.in
38 +++ b/Makefile.in
39 @@ -4,6 +4,7 @@ prefix=@prefix@
40  datarootdir=@datarootdir@
41  exec_prefix=@exec_prefix@
42  bindir=@bindir@
43 +sbindir=@sbindir@
44  libdir=@libdir@/rsync
45  mandir=@mandir@
46  
47 @@ -32,8 +33,9 @@ SHELL=/bin/sh
48  SIMD_x86_64=simd-checksum-x86_64.o
49  ASM_x86_64=lib/md5-asm-x86_64.o
50  
51 +GENFILES=configure.sh aclocal.m4 config.h.in proto.h proto.h-tstamp rsync.1 rsync-ssl.1
52  GENFILES=configure.sh aclocal.m4 config.h.in proto.h proto.h-tstamp rsync.1 rsync.1.html \
53 -        rsync-ssl.1 rsync-ssl.1.html rsyncd.conf.5 rsyncd.conf.5.html
54 +        rsync-ssl.1 rsync-ssl.1.html rsyncd.conf.5 rsyncd.conf.5.html rsyncdb.1 rsyncdb.1.html
55  HEADERS=byteorder.h config.h errcode.h proto.h rsync.h ifuncs.h itypes.h inums.h \
56         lib/pool_alloc.h lib/mdigest.h lib/md-defines.h version.h
57  LIBOBJ=lib/wildmatch.o lib/compat.o lib/snprintf.o lib/mdfour.o lib/md5.o \
58 @@ -43,7 +45,7 @@ zlib_OBJS=zlib/deflate.o zlib/inffast.o zlib/inflate.o zlib/inftrees.o \
59  OBJS1=flist.o rsync.o generator.o receiver.o cleanup.o sender.o exclude.o \
60         util.o util2.o main.o checksum.o match.o syscall.o log.o backup.o delete.o
61  OBJS2=options.o io.o compat.o hlink.o token.o uidlist.o socket.o hashtable.o \
62 -       fileio.o batch.o clientname.o chmod.o acls.o xattrs.o
63 +       fileio.o batch.o clientname.o chmod.o db.o acls.o xattrs.o
64  OBJS3=progress.o pipe.o @ASM@
65  DAEMON_OBJ = params.o loadparm.o clientserver.o access.o connection.o authenticate.o
66  popt_OBJS=popt/findme.o  popt/popt.o  popt/poptconfig.o \
67 @@ -75,10 +77,12 @@ install: all
68         -${MKDIR_P} ${DESTDIR}${bindir}
69         ${INSTALLCMD} ${INSTALL_STRIP} -m 755 rsync$(EXEEXT) ${DESTDIR}${bindir}
70         ${INSTALLCMD} -m 755 $(srcdir)/rsync-ssl ${DESTDIR}${bindir}
71 +       rsync -ilt rsyncdb$(EXEEXT) ${DESTDIR}${bindir}/
72         -${MKDIR_P} ${DESTDIR}${mandir}/man1
73         -${MKDIR_P} ${DESTDIR}${mandir}/man5
74         if test -f rsync.1; then ${INSTALLMAN} -m 644 rsync.1 ${DESTDIR}${mandir}/man1; fi
75         if test -f rsync-ssl.1; then ${INSTALLMAN} -m 644 rsync-ssl.1 ${DESTDIR}${mandir}/man1; fi
76 +       if test -f rsyncdb.1; then ${INSTALLMAN} -m 644 rsyncdb.1 ${DESTDIR}${mandir}/man1; fi
77         if test -f rsyncd.conf.5; then ${INSTALLMAN} -m 644 rsyncd.conf.5 ${DESTDIR}${mandir}/man5; fi
78  
79  install-ssl-daemon: stunnel-rsyncd.conf
80 @@ -96,10 +100,13 @@ install-strip:
81  rsync$(EXEEXT): $(OBJS)
82         $(CC) $(CFLAGS) $(LDFLAGS) -o $@ $(OBJS) $(LIBS)
83  
84 +rsyncdb$(EXEEXT): rsync$(EXEEXT)
85 +       ln -s rsync$(EXEEXT) rsyncdb$(EXEEXT)
86 +
87  $(OBJS): $(HEADERS)
88  $(CHECK_OBJS): $(HEADERS)
89  tls.o xattrs.o: lib/sysxattrs.h
90 -options.o: latest-year.h help-rsync.h help-rsyncd.h
91 +options.o: latest-year.h help-rsync.h help-rsyncd.h help-rsyncdb.h
92  exclude.o: default-cvsignore.h
93  loadparm.o: default-dont-compress.h daemon-parm.h
94  
95 @@ -111,6 +118,9 @@ default-cvsignore.h default-dont-compress.h: rsync.1.md define-from-md.awk
96  help-rsync.h help-rsyncd.h: rsync.1.md help-from-md.awk
97         $(AWK) -f $(srcdir)/help-from-md.awk -v hfile=$@ $(srcdir)/rsync.1.md
98  
99 +help-rsyncdb.h: rsyncdb.1.md help-from-md.awk
100 +       awk -f $(srcdir)/help-from-md.awk -v hfile=$@ $(srcdir)/rsyncdb.1.md
101 +
102  daemon-parm.h: daemon-parm.txt daemon-parm.awk
103         $(AWK) -f $(srcdir)/daemon-parm.awk $(srcdir)/daemon-parm.txt
104  
105 @@ -235,7 +245,7 @@ proto.h-tstamp: $(srcdir)/*.c $(srcdir)/lib/compat.c config.h daemon-parm.h
106         $(AWK) -f $(srcdir)/mkproto.awk $(srcdir)/*.c $(srcdir)/lib/compat.c daemon-parm.h
107  
108  .PHONY: man
109 -man: rsync.1 rsync-ssl.1 rsyncd.conf.5
110 +man: rsync.1 rsync-ssl.1 rsyncd.conf.5 rsyncdb.1
111  
112  rsync.1: rsync.1.md md2man version.h Makefile
113         @$(srcdir)/maybe-make-man $(srcdir) rsync.1.md
114 @@ -246,9 +256,12 @@ rsync-ssl.1: rsync-ssl.1.md md2man version.h Makefile
115  rsyncd.conf.5: rsyncd.conf.5.md md2man version.h Makefile
116         @$(srcdir)/maybe-make-man $(srcdir) rsyncd.conf.5.md
117  
118 +rsyncdb.1: rsyncdb.1.md md2man NEWS.md Makefile
119 +       @$(srcdir)/maybe-make-man $(srcdir) rsyncdb.1.md
120 +
121  .PHONY: clean
122  clean: cleantests
123 -       rm -f *~ $(OBJS) $(CHECK_PROGS) $(CHECK_OBJS) $(CHECK_SYMLINKS) \
124 +       rm -f *~ $(OBJS) $(CHECK_PROGS) $(CHECK_OBJS) $(CHECK_SYMLINKS) rsyncdb$(EXEEXT) \
125                 rounding rounding.h *.old rsync*.1 rsync*.5 rsync*.html \
126                 daemon-parm.h help-*.h default-*.h
127  
128 diff --git a/checksum.c b/checksum.c
129 --- a/checksum.c
130 +++ b/checksum.c
131 @@ -40,6 +40,7 @@ extern int whole_file;
132  extern int checksum_seed;
133  extern int protocol_version;
134  extern int proper_seed_order;
135 +extern int use_db;
136  extern const char *checksum_choice;
137  
138  struct name_num_obj valid_checksums = {
139 @@ -386,6 +387,8 @@ void file_checksum(const char *fname, const STRUCT_STAT *st_p, char *sum)
140                         MD5_Update(&m5, (uchar *)map_ptr(buf, i, remainder), remainder);
141  
142                 MD5_Final((uchar *)sum, &m5);
143 +               if (use_db)
144 +                       db_set_checksum(5, st_p, sum);
145                 break;
146           }
147           case CSUM_MD4:
148 @@ -425,6 +428,8 @@ void file_checksum(const char *fname, const STRUCT_STAT *st_p, char *sum)
149                         mdfour_update(&m, (uchar *)map_ptr(buf, i, remainder), remainder);
150  
151                 mdfour_result(&m, (uchar *)sum);
152 +               if (use_db)
153 +                       db_set_checksum(4, st_p, sum);
154                 break;
155           }
156           default:
157 diff --git a/cleanup.c b/cleanup.c
158 --- a/cleanup.c
159 +++ b/cleanup.c
160 @@ -28,6 +28,7 @@ extern int am_daemon;
161  extern int am_receiver;
162  extern int am_sender;
163  extern int io_error;
164 +extern int use_db;
165  extern int keep_partial;
166  extern int got_xfer_error;
167  extern int protocol_version;
168 @@ -143,6 +144,12 @@ NORETURN void _exit_cleanup(int code, const char *file, int line)
169  #include "case_N.h"
170                 switch_step++;
171  
172 +               if (use_db)
173 +                       db_disconnect(False);
174 +
175 +               /* FALLTHROUGH */
176 +#include "case_N.h"
177 +
178                 if (cleanup_child_pid != -1) {
179                         int status;
180                         int pid = wait_process(cleanup_child_pid, &status, WNOHANG);
181 diff --git a/clientserver.c b/clientserver.c
182 --- a/clientserver.c
183 +++ b/clientserver.c
184 @@ -44,12 +44,15 @@ extern int numeric_ids;
185  extern int filesfrom_fd;
186  extern int remote_protocol;
187  extern int protocol_version;
188 +extern int always_checksum;
189 +extern int db_lax;
190  extern int io_timeout;
191  extern int no_detach;
192  extern int write_batch;
193  extern int default_af_hint;
194  extern int logfile_format_has_i;
195  extern int logfile_format_has_o_or_i;
196 +extern char *db_config;
197  extern char *bind_address;
198  extern char *config_file;
199  extern char *logfile_format;
200 @@ -810,6 +813,11 @@ static int rsync_module(int f_in, int f_out, int i, const char *addr, const char
201  
202         log_init(1);
203  
204 +       if (*lp_db_config(i)) {
205 +               db_read_config(FLOG, lp_db_config(i));
206 +               db_lax = lp_db_lax(i);
207 +       }
208 +
209  #ifdef HAVE_PUTENV
210         if ((*lp_early_exec(module_id) || *lp_prexfer_exec(module_id) || *lp_postxfer_exec(module_id))
211          && !getenv("RSYNC_NO_XFER_EXEC")) {
212 @@ -1009,6 +1017,8 @@ static int rsync_module(int f_in, int f_out, int i, const char *addr, const char
213  
214         am_server = 1; /* Don't let someone try to be tricky. */
215         quiet = 0;
216 +       db_config = NULL;
217 +
218         if (lp_ignore_errors(module_id))
219                 ignore_errors = 1;
220         if (write_batch < 0)
221 diff --git a/configure.ac b/configure.ac
222 --- a/configure.ac
223 +++ b/configure.ac
224 @@ -487,6 +487,7 @@ AC_CHECK_HEADERS(sys/fcntl.h sys/select.h fcntl.h sys/time.h sys/unistd.h \
225      unistd.h utime.h grp.h compat.h sys/param.h ctype.h sys/wait.h \
226      sys/ioctl.h sys/filio.h string.h stdlib.h sys/socket.h sys/mode.h \
227      sys/un.h sys/attr.h mcheck.h arpa/inet.h arpa/nameser.h locale.h \
228 +    mysql/mysql.h sqlite3.h \
229      netdb.h malloc.h float.h limits.h iconv.h libcharset.h langinfo.h \
230      sys/acl.h acl/libacl.h attr/xattr.h sys/xattr.h sys/extattr.h dl.h \
231      popt.h popt/popt.h linux/falloc.h netinet/in_systm.h netinet/ip.h \
232 @@ -1336,6 +1337,48 @@ if test x"$enable_acl_support" = x"no" -o x"$enable_xattr_support" = x"no" -o x"
233      fi
234  fi
235  
236 +AC_MSG_CHECKING([whether to include mysql DB support])
237 +AC_ARG_ENABLE(mysql,
238 +       AC_HELP_STRING([--disable-mysql],
239 +               [disable mysql DB support]))
240 +
241 +if test x"$enable_mysql" = x"no"; then
242 +    AC_MSG_RESULT(no)
243 +else
244 +    AC_MSG_RESULT([yes])
245 +    AC_CHECK_PROG(MYSQL_CONFIG, mysql_config, 1, 0)
246 +    if test x$MYSQL_CONFIG = x1; then
247 +       AC_MSG_CHECKING(for mysql version >= 4)
248 +       mysql_version=`mysql_config --version`
249 +       mysql_major_version=`echo $mysql_version | sed 's/\..*//'`
250 +       if test $mysql_major_version -lt 4; then
251 +           AC_MSG_RESULT(no.. skipping MySQL)
252 +       else
253 +           AC_MSG_RESULT(yes)
254 +
255 +           MYSQL_CFLAGS=`mysql_config --cflags`
256 +           MYSQL_LIBS=`mysql_config --libs`
257 +
258 +           CPPFLAGS="$CPPFLAGS $MYSQL_CFLAGS"
259 +           LIBS="$MYSQL_LIBS $LIBS"
260 +
261 +           AC_CHECK_LIB(mysqlclient, mysql_init)
262 +       fi
263 +    fi
264 +fi
265 +
266 +AC_MSG_CHECKING([whether to include sqlite DB support])
267 +AC_ARG_ENABLE(sqlite,
268 +       AC_HELP_STRING([--disable-sqlite],
269 +               [disable sqlite DB support]))
270 +
271 +if test x"$enable_sqlite" = x"no"; then
272 +    AC_MSG_RESULT(no)
273 +else
274 +    AC_CHECK_LIB(sqlite3, sqlite3_open)
275 +    AC_CHECK_FUNCS(sqlite3_open_v2 sqlite3_prepare_v2)
276 +fi
277 +
278  case "$CC" in
279  ' checker'*|checker*)
280      AC_DEFINE(FORCE_FD_ZERO_MEMSET, 1, [Used to make "checker" understand that FD_ZERO() clears memory.])
281 diff --git a/daemon-parm.txt b/daemon-parm.txt
282 --- a/daemon-parm.txt
283 +++ b/daemon-parm.txt
284 @@ -18,6 +18,7 @@ Locals: =================================================================
285  STRING auth_users              NULL
286  STRING charset                 NULL
287  STRING comment                 NULL
288 +STRING db_config               NULL
289  STRING dont_compress           DEFAULT_DONT_COMPRESS
290  STRING early_exec              NULL
291  STRING exclude                 NULL
292 @@ -50,6 +51,7 @@ INTEGER       timeout                 0
293  
294  ENUM   syslog_facility         LOG_DAEMON
295  
296 +BOOL   db_lax                  False
297  BOOL   fake_super              False
298  BOOL   forward_lookup          True
299  BOOL   ignore_errors           False
300 diff --git a/db.c b/db.c
301 new file mode 100644
302 --- /dev/null
303 +++ b/db.c
304 @@ -0,0 +1,1943 @@
305 +/*
306 + * Routines to access extended file info via DB.
307 + *
308 + * Copyright (C) 2008-2013 Wayne Davison
309 + *
310 + * This program is free software; you can redistribute it and/or modify
311 + * it under the terms of the GNU General Public License as published by
312 + * the Free Software Foundation; either version 3 of the License, or
313 + * (at your option) any later version.
314 + *
315 + * This program is distributed in the hope that it will be useful,
316 + * but WITHOUT ANY WARRANTY; without even the implied warranty of
317 + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
318 + * GNU General Public License for more details.
319 + *
320 + * You should have received a copy of the GNU General Public License along
321 + * with this program; if not, visit the http://fsf.org website.
322 + */
323 +
324 +#include "rsync.h"
325 +#include "ifuncs.h"
326 +#include "itypes.h"
327 +#include "inums.h"
328 +#ifdef USE_OPENSSL
329 +#include "openssl/md4.h"
330 +#include "openssl/md5.h"
331 +#endif
332 +
333 +extern int recurse;
334 +extern int same_db;
335 +extern int am_receiver;
336 +extern int am_generator;
337 +extern int checksum_type;
338 +extern int db_clean, db_check, db_do_md4, db_do_md5, db_update, db_lax, db_init, db_mounts;
339 +extern int db_output_name, db_output_sum, db_output_info, db_output_unchanged, db_output_dirs, db_output_msgs;
340 +extern int saw_db_output_opt, saw_db_sum_opt;
341 +extern char *db_config;
342 +
343 +#define MOUNT_HELPER_SCRIPT "/usr/sbin/rsyncdb-mountinfo"
344 +
345 +#if defined HAVE_MYSQL_MYSQL_H && defined HAVE_LIBMYSQLCLIENT
346 +#define USE_MYSQL
347 +#include <mysql/mysql.h>
348 +#include <mysql/errmsg.h>
349 +#endif
350 +
351 +#if defined HAVE_SQLITE3_H && defined HAVE_LIBSQLITE3
352 +#define USE_SQLITE
353 +#include <sqlite3.h>
354 +#ifndef HAVE_SQLITE3_OPEN_V2
355 +#define sqlite3_open_v2(dbname, dbhptr, flags, vfs) \
356 +       sqlite3_open(dbname, dbhptr)
357 +#endif
358 +#ifndef HAVE_SQLITE3_PREPARE_V2
359 +#define sqlite3_prepare_v2 sqlite3_prepare
360 +#endif
361 +#define MAX_LOCK_FAILURES 10
362 +#define LOCK_FAIL_MSLEEP 100
363 +#endif
364 +
365 +#ifndef USE_OPENSSL
366 +#define MD5_CTX md_context
367 +#define MD5_Init md5_begin
368 +#define MD5_Update md5_update
369 +#define MD5_Final(digest, cptr) md5_result(cptr, digest)
370 +#endif
371 +
372 +#define DB_TYPE_NONE 0
373 +#define DB_TYPE_MYSQL 1
374 +#define DB_TYPE_SQLITE 2
375 +
376 +int use_db = DB_TYPE_NONE;
377 +int select_many_sums = 0;
378 +
379 +#define PREP_NORM 0
380 +#define PREP_MOUNT 1
381 +
382 +static const char *dbhost = NULL, *dbuser = NULL, *dbpass = NULL, *dbname = NULL;
383 +static unsigned int dbport = 0;
384 +static int transaction_state = -1;
385 +
386 +static union {
387 +#ifdef USE_MYSQL
388 +    MYSQL *mysql;
389 +#endif
390 +#ifdef USE_SQLITE
391 +    sqlite3 *sqlite;
392 +#endif
393 +    void *all;
394 +} dbh;
395 +
396 +#define SEL_DEV 0
397 +#define SEL_SUM 1
398 +#define REP_SUM 2
399 +#define UPD_CTIME 3
400 +#define INS_MOUNT 4
401 +#define UPD_MOUNT 5 /* SQLite only */
402 +#define SEL_MOUNT 6
403 +#define UN_MOUNT 7
404 +#define DEL_SUMS 8
405 +#define INS_PRESENT 9
406 +#define MAX_PREP_CNT 10
407 +
408 +#define MAX_BIND_CNT 7
409 +#define MAX_RESULT_BINDS 32
410 +
411 +static union {
412 +#ifdef USE_MYSQL
413 +    MYSQL_STMT *mysql;
414 +#endif
415 +#ifdef USE_SQLITE
416 +    sqlite3_stmt *sqlite;
417 +#endif
418 +    void *all;
419 +} statements[MAX_PREP_CNT];
420 +
421 +static int md_num;
422 +static enum logcode log_code;
423 +
424 +#ifdef USE_MYSQL
425 +static unsigned int bind_disk_id, bind_mdnum;
426 +static int64 bind_devno, bind_ino, bind_size, bind_mtime, bind_ctime;
427 +static char bind_sum[MAX_DIGEST_LEN];
428 +static unsigned long result_length[MAX_RESULT_BINDS];
429 +static bool result_is_null[MAX_RESULT_BINDS], result_error[MAX_RESULT_BINDS];
430 +#elif defined USE_SQLITE
431 +static int64 bind_mtime;
432 +#endif
433 +static char bind_thishost[128+1];
434 +static unsigned long bind_thishost_len;
435 +static char *mount_helper_script = NULL;
436 +
437 +static char *error_log;
438 +#if defined USE_SQLITE && defined SQLITE_CONFIG_LOG
439 +static char bind_mount_uniq[128+1];
440 +static unsigned long bind_mount_uniq_len;
441 +static FILE *error_log_fp;
442 +#endif
443 +
444 +#define PTR_SIZE (sizeof (struct file_struct *))
445 +
446 +#if defined USE_MYSQL || defined USE_SQLITE
447 +static void update_mounts(void);
448 +#endif
449 +
450 +struct name_list {
451 +       struct name_list *next;
452 +       char name[1];
453 +} *dirs_list;
454 +
455 +int db_read_config(enum logcode code, const char *config_file)
456 +{
457 +       char buf[2048], *cp;
458 +       FILE *fp;
459 +       int lineno = 0;
460 +
461 +       log_code = code;
462 +
463 +       bind_thishost_len = strlcpy(bind_thishost, "localhost", sizeof bind_thishost);
464 +
465 +       if (!(fp = fopen(config_file, "r"))) {
466 +               rsyserr(log_code, errno, "unable to open %s", config_file);
467 +               return 0;
468 +       }
469 +       if (DEBUG_GTE(DB, 1))
470 +               rprintf(FCLIENT, "[%s] Reading DB config from %s\n", who_am_i(), config_file);
471 +       while (fgets(buf, sizeof buf, fp)) {
472 +               lineno++;
473 +               if ((cp = strchr(buf, '#')) == NULL
474 +                && (cp = strchr(buf, '\r')) == NULL
475 +                && (cp = strchr(buf, '\n')) == NULL)
476 +                       cp = buf + strlen(buf);
477 +               while (cp != buf && isSpace(cp-1)) cp--;
478 +               *cp = '\0';
479 +
480 +               if (!*buf)
481 +                       continue;
482 +
483 +               if (!(cp = strchr(buf, ':')))
484 +                       goto invalid_line;
485 +               *cp++ = '\0';
486 +
487 +               while (isSpace(cp)) cp++;
488 +               if (strcasecmp(buf, "dbhost") == 0)
489 +                       dbhost = strdup(cp);
490 +               else if (strcasecmp(buf, "dbuser") == 0)
491 +                       dbuser = strdup(cp);
492 +               else if (strcasecmp(buf, "dbpass") == 0)
493 +                       dbpass = strdup(cp);
494 +               else if (strcasecmp(buf, "dbname") == 0)
495 +                       dbname = strdup(cp);
496 +               else if (strcasecmp(buf, "dbport") == 0)
497 +                       dbport = atoi(cp);
498 +               else if (strcasecmp(buf, "transaction") == 0)
499 +                       transaction_state = atoi(cp) ? 0 : -1;
500 +               else if (strcasecmp(buf, "mountHelper") == 0)
501 +                       mount_helper_script = strdup(cp);
502 +               else if (strcasecmp(buf, "errlog") == 0)
503 +                       error_log = strdup(cp);
504 +               else if (strcasecmp(buf, "thishost") == 0)
505 +                       bind_thishost_len = strlcpy(bind_thishost, cp, sizeof bind_thishost);
506 +               else if (strcasecmp(buf, "dbtype") == 0) {
507 +#ifdef USE_MYSQL
508 +                       if (strcasecmp(cp, "mysql") == 0) {
509 +                               use_db = DB_TYPE_MYSQL;
510 +                               continue;
511 +                       }
512 +#endif
513 +#ifdef USE_SQLITE
514 +                       if (strcasecmp(cp, "sqlite") == 0) {
515 +                               use_db = DB_TYPE_SQLITE;
516 +                               continue;
517 +                       }
518 +#endif
519 +                       rprintf(log_code,
520 +                           "Unsupported dbtype on line #%d in %s.\n",
521 +                           lineno, config_file);
522 +                       use_db = DB_TYPE_NONE;
523 +                       return 0;
524 +               } else {
525 +                 invalid_line:
526 +                       rprintf(log_code, "Invalid line #%d in %s\n",
527 +                               lineno, config_file);
528 +                       use_db = DB_TYPE_NONE;
529 +                       return 0;
530 +               }
531 +       }
532 +       fclose(fp);
533 +
534 +       if (bind_thishost_len >= (int)sizeof bind_thishost)
535 +               bind_thishost_len = sizeof bind_thishost - 1;
536 +
537 +       if (!use_db || !dbname) {
538 +               rprintf(log_code, "Please specify at least dbtype and dbname in %s.\n", config_file);
539 +               use_db = DB_TYPE_NONE;
540 +               return 0;
541 +       }
542 +
543 +       md_num = checksum_type == 5 ? 5 : 4;
544 +
545 +       if (error_log) {
546 +               if (use_db != DB_TYPE_SQLITE)
547 +                       rprintf(log_code, "Ignoring errlog setting for non-SQLite DB.\n");
548 +#ifndef SQLITE_CONFIG_LOG
549 +               else
550 +                       rprintf(log_code, "Your sqlite doesn't support SQLITE_CONFIG_LOG.\n");
551 +#endif
552 +       }
553 +
554 +       if (!mount_helper_script)
555 +               mount_helper_script = MOUNT_HELPER_SCRIPT;
556 +
557 +       return 1;
558 +}
559 +
560 +#if defined USE_SQLITE && defined SQLITE_CONFIG_LOG
561 +static void errorLogCallback(UNUSED(void *pArg), int iErrCode, const char *zMsg)
562 +{
563 +       fprintf(error_log_fp, "[%d] %s (%d)\n", (int)getpid(), zMsg, iErrCode);
564 +}
565 +#endif
566 +
567 +static int run_sql(const char *fmt, ...)
568 +{
569 +       va_list ap;
570 +       char *query;
571 +       int ok = 0, qlen;
572 +
573 +       va_start(ap, fmt);
574 +       qlen = vasprintf(&query, fmt, ap);
575 +       va_end(ap);
576 +       if (qlen < 0)
577 +               out_of_memory("run_sql");
578 +       if (DEBUG_GTE(DB, 3))
579 +               rprintf(FCLIENT, "[%s] SQL being run: %s\n", who_am_i(), query);
580 +
581 +       switch (use_db) {
582 +#ifdef USE_MYSQL
583 +       case DB_TYPE_MYSQL:
584 +               if (mysql_query(dbh.mysql, query) < 0) {
585 +                       rprintf(FERROR, "Failed to run sql: %s\n", mysql_error(dbh.mysql));
586 +                       rprintf(FERROR, "%s\n", query);
587 +               } else
588 +                       ok = 1;
589 +               break;
590 +#endif
591 +#ifdef USE_SQLITE
592 +       case DB_TYPE_SQLITE: {
593 +               int rc, lock_failures = 0;
594 +               while (1) {
595 +                       if ((rc = sqlite3_exec(dbh.sqlite, query, NULL, NULL, NULL)) == 0)
596 +                               break;
597 +                       if (rc != SQLITE_BUSY && rc != SQLITE_LOCKED)
598 +                               break;
599 +                       if (++lock_failures > MAX_LOCK_FAILURES)
600 +                               break;
601 +                       msleep(LOCK_FAIL_MSLEEP);
602 +               }
603 +               if (rc) {
604 +                       rprintf(FERROR, "[%s] Failed to run sql: %s\n", who_am_i(), sqlite3_errmsg(dbh.sqlite));
605 +                       rprintf(FERROR, "%s\n", query);
606 +               } else
607 +                       ok = 1;
608 +               break;
609 +           }
610 +#endif
611 +       }
612 +
613 +       free(query);
614 +
615 +       return ok;
616 +}
617 +
618 +#ifdef USE_MYSQL
619 +static int prepare_mysql(int ndx, MYSQL_BIND *binds, int bind_cnt, const char *fmt, ...)
620 +{
621 +       va_list ap;
622 +       char *query;
623 +       int qlen, param_cnt;
624 +       MYSQL_STMT *stmt = mysql_stmt_init(dbh.mysql);
625 +
626 +       if (stmt == NULL)
627 +               out_of_memory("prepare_mysql");
628 +
629 +       va_start(ap, fmt);
630 +       qlen = vasprintf(&query, fmt, ap);
631 +       va_end(ap);
632 +       if (qlen < 0)
633 +               out_of_memory("prepare_mysql");
634 +       if (DEBUG_GTE(DB, 3))
635 +               rprintf(FCLIENT, "[%s] SQL being prepared: %s\n", who_am_i(), query);
636 +
637 +       if (mysql_stmt_prepare(stmt, query, qlen) != 0) {
638 +               rprintf(log_code, "[%s] Prepare failed: %s\n", who_am_i(), mysql_stmt_error(stmt));
639 +               rprintf(log_code, "%s\n", query);
640 +               free(query);
641 +               return 0;
642 +       }
643 +
644 +       if ((param_cnt = mysql_stmt_param_count(stmt)) != bind_cnt) {
645 +               rprintf(log_code, "[%s] Parameters in statement = %d, bind vars = %d\n",
646 +                       who_am_i(), param_cnt, bind_cnt);
647 +               rprintf(log_code, "%s\n", query);
648 +               free(query);
649 +               return 0;
650 +       }
651 +       if (bind_cnt)
652 +               mysql_stmt_bind_param(stmt, binds);
653 +
654 +       statements[ndx].mysql = stmt;
655 +       free(query);
656 +
657 +       return 1;
658 +}
659 +#endif
660 +
661 +#ifdef USE_MYSQL
662 +static int prepare_mysql_queries(int type)
663 +{
664 +       MYSQL_BIND binds[MAX_BIND_CNT];
665 +       char *sql;
666 +
667 +       switch (type) {
668 +       case PREP_NORM:
669 +               sql="SELECT disk_id"
670 +                   " FROM disk"
671 +                   " WHERE host = ? AND devno = ?";
672 +               memset(binds, 0, sizeof binds);
673 +               binds[0].buffer_type = MYSQL_TYPE_STRING;
674 +               binds[0].buffer = &bind_thishost;
675 +               binds[0].buffer_length = bind_thishost_len;
676 +               binds[1].buffer_type = MYSQL_TYPE_LONGLONG;
677 +               binds[1].buffer = &bind_devno;
678 +               if (!prepare_mysql(SEL_DEV, binds, 2, sql))
679 +                       return 0;
680 +
681 +               memset(binds, 0, sizeof binds);
682 +               binds[0].buffer_type = MYSQL_TYPE_LONG;
683 +               binds[0].buffer = &bind_disk_id;
684 +               binds[1].buffer_type = MYSQL_TYPE_LONGLONG;
685 +               binds[1].buffer = &bind_ino;
686 +               if (select_many_sums) {
687 +                       sql="SELECT checksum, sum_type, size, mtime, ctime"
688 +                           " FROM inode_map"
689 +                           " WHERE disk_id = ? AND ino = ?";
690 +                       if (!prepare_mysql(SEL_SUM, binds, 2, sql))
691 +                               return 0;
692 +               } else {
693 +                       sql="SELECT checksum"
694 +                           " FROM inode_map"
695 +                           " WHERE disk_id = ? AND ino = ? AND sum_type = %d"
696 +                           "   AND size = ? AND mtime = ? %s"; /* optional: AND ctime = ? */
697 +                       binds[2].buffer_type = MYSQL_TYPE_LONGLONG;
698 +                       binds[2].buffer = &bind_size;
699 +                       binds[3].buffer_type = MYSQL_TYPE_LONGLONG;
700 +                       binds[3].buffer = &bind_mtime;
701 +                       if (!db_lax) {
702 +                               binds[4].buffer_type = MYSQL_TYPE_LONGLONG;
703 +                               binds[4].buffer = &bind_ctime;
704 +                       }
705 +                       if (!prepare_mysql(SEL_SUM, binds, 4 + !db_lax, sql, md_num, db_lax ? "" : "AND ctime = ?"))
706 +                               return 0;
707 +               }
708 +
709 +               sql="INSERT INTO inode_map"
710 +                   " SET disk_id = ?, ino = ?, sum_type = ?,"
711 +                   "     size = ?, mtime = ?, ctime = ?, checksum = ?"
712 +                   " ON DUPLICATE KEY"
713 +                   " UPDATE size = VALUES(size), mtime = VALUES(mtime),"
714 +                   "        ctime = VALUES(ctime), checksum = VALUES(checksum)";
715 +               memset(binds, 0, sizeof binds);
716 +               binds[0].buffer_type = MYSQL_TYPE_LONG;
717 +               binds[0].buffer = &bind_disk_id;
718 +               binds[1].buffer_type = MYSQL_TYPE_LONGLONG;
719 +               binds[1].buffer = &bind_ino;
720 +               binds[2].buffer_type = MYSQL_TYPE_LONG;
721 +               binds[2].buffer = &bind_mdnum;
722 +               binds[3].buffer_type = MYSQL_TYPE_LONGLONG;
723 +               binds[3].buffer = &bind_size;
724 +               binds[4].buffer_type = MYSQL_TYPE_LONGLONG;
725 +               binds[4].buffer = &bind_mtime;
726 +               binds[5].buffer_type = MYSQL_TYPE_LONGLONG;
727 +               binds[5].buffer = &bind_ctime;
728 +               binds[6].buffer_type = MYSQL_TYPE_BLOB;
729 +               binds[6].buffer = &bind_sum;
730 +               binds[6].buffer_length = MD5_DIGEST_LEN; /* Same as MD4_DIGEST_LEN */
731 +               if (!prepare_mysql(REP_SUM, binds, 7, sql))
732 +                       return 0;
733 +
734 +               sql="UPDATE inode_map"
735 +                   " SET ctime = ?"
736 +                   " WHERE disk_id = ? AND ino = ? AND sum_type = ? AND size = ? AND mtime = ?";
737 +               memset(binds, 0, sizeof binds);
738 +               binds[0].buffer_type = MYSQL_TYPE_LONGLONG;
739 +               binds[0].buffer = &bind_ctime;
740 +               binds[1].buffer_type = MYSQL_TYPE_LONG;
741 +               binds[1].buffer = &bind_disk_id;
742 +               binds[2].buffer_type = MYSQL_TYPE_LONGLONG;
743 +               binds[2].buffer = &bind_ino;
744 +               binds[3].buffer_type = MYSQL_TYPE_LONG;
745 +               binds[3].buffer = &bind_mdnum;
746 +               binds[4].buffer_type = MYSQL_TYPE_LONGLONG;
747 +               binds[4].buffer = &bind_size;
748 +               binds[5].buffer_type = MYSQL_TYPE_LONGLONG;
749 +               binds[5].buffer = &bind_mtime;
750 +               if (!prepare_mysql(UPD_CTIME, binds, 6, sql))
751 +                       return 0;
752 +               break;
753 +
754 +       case PREP_MOUNT:
755 +               sql="INSERT INTO disk"
756 +                   " SET host = ?, last_seen = ?, mount_uniq = ?, devno = ?"
757 +                   " ON DUPLICATE KEY"
758 +                   " UPDATE last_seen = VALUES(last_seen), devno = VALUES(devno)";
759 +               memset(binds, 0, sizeof binds);
760 +               binds[0].buffer_type = MYSQL_TYPE_STRING;
761 +               binds[0].buffer = &bind_thishost;
762 +               binds[0].buffer_length = bind_thishost_len;
763 +               binds[1].buffer_type = MYSQL_TYPE_LONGLONG;
764 +               binds[1].buffer = &bind_mtime; /* we abuse mtime to hold the last_seen value */
765 +               binds[2].buffer_type = MYSQL_TYPE_STRING;
766 +               binds[2].buffer = &bind_mount_uniq;
767 +               binds[2].buffer_length = sizeof bind_mount_uniq;
768 +               binds[2].length = &bind_mount_uniq_len;
769 +               binds[3].buffer_type = MYSQL_TYPE_LONGLONG;
770 +               binds[3].buffer = &bind_devno;
771 +               if (!prepare_mysql(INS_MOUNT, binds, 4, sql))
772 +                       return 0;
773 +
774 +               sql="SELECT mount_uniq"
775 +                   " FROM disk"
776 +                   " WHERE host = ? AND last_seen < ? AND devno != 0";
777 +               /* Reusing first 2 binds from INS_MOUNT */
778 +               if (!prepare_mysql(SEL_MOUNT, binds, 2, sql))
779 +                       return 0;
780 +
781 +               sql="UPDATE disk"
782 +                   " SET devno = 0"
783 +                   " WHERE host = ? AND last_seen < ? AND devno != 0";
784 +               /* Reusing binds from SEL_MOUNT */
785 +               if (!prepare_mysql(UN_MOUNT, binds, 2, sql))
786 +                       return 0;
787 +               break;
788 +       }
789 +
790 +       return 1;
791 +}
792 +#endif
793 +
794 +#ifdef USE_MYSQL
795 +static int db_connect_mysql(void)
796 +{
797 +       const char *open_dbname = db_init ? "mysql" : dbname;
798 +
799 +       if (!(dbh.mysql = mysql_init(NULL)))
800 +               out_of_memory("db_read_config");
801 +
802 +       if (DEBUG_GTE(DB, 1)) {
803 +               rprintf(FCLIENT, "[%s] connecting: host=%s user=%s db=%s port=%d\n",
804 +                       who_am_i(), dbhost, dbuser, open_dbname, dbport);
805 +       }
806 +       if (!mysql_real_connect(dbh.mysql, dbhost, dbuser, dbpass, open_dbname, dbport, NULL, 0)) {
807 +               rprintf(log_code, "[%s] Unable to connect to DB: %s\n", who_am_i(), mysql_error(dbh.mysql));
808 +               return 0;
809 +       }
810 +
811 +       if (db_init) {
812 +               if (db_output_msgs)
813 +                       rprintf(FCLIENT, "Creating DB %s (if it does not exist)\n", dbname);
814 +               if (!run_sql("CREATE DATABASE IF NOT EXISTS `%s`", dbname)
815 +                || !run_sql("USE `%s`", dbname))
816 +                       exit_cleanup(RERR_IPC);
817 +
818 +               if (db_output_msgs)
819 +                       rprintf(FCLIENT, "Dropping old tables (if they exist))\n");
820 +               if (!run_sql("DROP TABLE IF EXISTS disk")
821 +                || !run_sql("DROP TABLE IF EXISTS inode_map"))
822 +                       exit_cleanup(RERR_IPC);
823 +
824 +               if (db_output_msgs)
825 +                       rprintf(FCLIENT, "Creating empty tables ...\n");
826 +               if (!run_sql(
827 +                   "CREATE TABLE disk (\n"
828 +                   "  disk_id integer unsigned NOT NULL PRIMARY KEY AUTO_INCREMENT,\n"
829 +                   "  host varchar(128) NOT NULL default 'localhost',\n"
830 +                   "  mount_uniq varchar(128) default NULL,\n"
831 +                   "  devno bigint unsigned NOT NULL,\n" /* This is 0 when not mounted */
832 +                   "  last_seen bigint NOT NULL,\n"
833 +                   "  UNIQUE KEY mount_lookup (host, mount_uniq),\n"
834 +                   "  KEY dev_lookup (devno, host)\n"
835 +                   ")"))
836 +                       exit_cleanup(RERR_IPC);
837 +
838 +               if (!run_sql(
839 +                   "CREATE TABLE inode_map (\n"
840 +                   "  disk_id integer unsigned NOT NULL,\n"
841 +                   "  ino bigint unsigned NOT NULL,\n"
842 +                   "  sum_type tinyint NOT NULL default '0',\n"
843 +                   "  size bigint unsigned NOT NULL,\n"
844 +                   "  mtime bigint NOT NULL,\n"
845 +                   "  ctime bigint NOT NULL,\n"
846 +                   "  checksum binary(16) NOT NULL,\n"
847 +                   "  PRIMARY KEY (disk_id,ino,sum_type)\n"
848 +                   ")"))
849 +                       exit_cleanup(RERR_IPC);
850 +
851 +               if (!db_mounts)
852 +                       exit_cleanup(0);
853 +       }
854 +
855 +       if (db_mounts) {
856 +               if (!prepare_mysql_queries(PREP_MOUNT))
857 +                       exit_cleanup(RERR_IPC);
858 +               update_mounts();
859 +               exit_cleanup(0);
860 +       }
861 +
862 +       if (!prepare_mysql_queries(PREP_NORM))
863 +               return 0;
864 +
865 +       return 1;
866 +}
867 +#endif
868 +
869 +#ifdef USE_SQLITE
870 +static int prepare_sqlite(int ndx, const char *fmt, ...)
871 +{
872 +       va_list ap;
873 +       char *query;
874 +       int rc, qlen, lock_failures = 0;
875 +
876 +       va_start(ap, fmt);
877 +       qlen = vasprintf(&query, fmt, ap);
878 +       va_end(ap);
879 +       if (qlen < 0)
880 +               out_of_memory("prepare_sqlite");
881 +       if (DEBUG_GTE(DB, 3))
882 +               rprintf(FCLIENT, "[%s] SQL being prepared: %s\n", who_am_i(), query);
883 +
884 +       while ((rc = sqlite3_prepare_v2(dbh.sqlite, query, -1, &statements[ndx].sqlite, NULL)) != 0) {
885 +               if (DEBUG_GTE(DB, 4)) {
886 +                       rprintf(FCLIENT, "[%s] sqlite3_prepare_v2(,%s,,) returned %d\n",
887 +                               who_am_i(), query, rc);
888 +               }
889 +               if (rc != SQLITE_BUSY && rc != SQLITE_LOCKED)
890 +                       break;
891 +               if (++lock_failures > MAX_LOCK_FAILURES)
892 +                       break;
893 +               msleep(LOCK_FAIL_MSLEEP);
894 +       }
895 +       if (rc) {
896 +               rprintf(log_code, "[%s] Failed to prepare SQL: %s (%d)\n", who_am_i(), sqlite3_errmsg(dbh.sqlite), rc);
897 +               rprintf(log_code, "%s\n", query);
898 +               free(query);
899 +               return 0;
900 +       }
901 +       free(query);
902 +
903 +       return 1;
904 +}
905 +#endif
906 +
907 +#ifdef USE_SQLITE
908 +static int prepare_sqlite_queries(int type)
909 +{
910 +       char *sql;
911 +
912 +       switch (type) {
913 +       case PREP_NORM:
914 +               sql="SELECT disk_id"
915 +                   " FROM disk"
916 +                   " WHERE host = ? AND devno = ?";
917 +               if (!prepare_sqlite(SEL_DEV, sql))
918 +                       return 0;
919 +
920 +               if (select_many_sums) {
921 +                       sql="SELECT checksum, sum_type, size, mtime, ctime"
922 +                           " FROM inode_map"
923 +                           " WHERE disk_id = ? AND ino = ?";
924 +                       if (!prepare_sqlite(SEL_SUM, sql))
925 +                               return 0;
926 +               } else {
927 +                       sql="SELECT checksum"
928 +                           " FROM inode_map"
929 +                           " WHERE disk_id = ? AND ino = ? AND sum_type = %d"
930 +                           "   AND size = ? AND mtime = ? %s";
931 +                       if (!prepare_sqlite(SEL_SUM, sql, md_num, db_lax ? "" : "AND ctime = ?"))
932 +                               return 0;
933 +               }
934 +
935 +               sql="INSERT OR REPLACE INTO inode_map"
936 +                   " (disk_id, ino, sum_type, size, mtime, ctime, checksum)"
937 +                   " VALUES (?, ?, ?, ?, ?, ?, ?)";
938 +               if (!prepare_sqlite(REP_SUM, sql))
939 +                       return 0;
940 +
941 +               sql="UPDATE inode_map"
942 +                   " SET ctime = ?"
943 +                   " WHERE disk_id = ? AND ino = ? AND sum_type = ? AND size = ? AND mtime = ?";
944 +               if (!prepare_sqlite(UPD_CTIME, sql))
945 +                       return 0;
946 +               break;
947 +
948 +       case PREP_MOUNT:
949 +               sql="INSERT OR IGNORE INTO disk"
950 +                   " (host, last_seen, mount_uniq, devno)"
951 +                   " VALUES (?, ?, ?, ?)";
952 +               if (!prepare_sqlite(INS_MOUNT, sql))
953 +                       return 0;
954 +
955 +               sql="UPDATE disk"
956 +                   " SET last_seen = ?, devno = ?"
957 +                   " WHERE host = ? AND mount_uniq = ?";
958 +               if (!prepare_sqlite(UPD_MOUNT, sql))
959 +                       return 0;
960 +
961 +               sql="SELECT mount_uniq"
962 +                   " FROM disk"
963 +                   " WHERE host = ? AND last_seen < ? AND devno != 0";
964 +               if (!prepare_sqlite(SEL_MOUNT, sql))
965 +                       return 0;
966 +
967 +               sql="UPDATE disk"
968 +                   " SET devno = 0"
969 +                   " WHERE host = ? AND last_seen < ? AND devno != 0";
970 +               if (!prepare_sqlite(UN_MOUNT, sql))
971 +                       return 0;
972 +               break;
973 +       }
974 +
975 +       return 1;
976 +}
977 +#endif
978 +
979 +#ifdef USE_SQLITE
980 +static int db_connect_sqlite(void)
981 +{
982 +       int lock_failures = 0;
983 +       int rc;
984 +
985 +#ifdef SQLITE_CONFIG_LOG
986 +       if (error_log) {
987 +               if (DEBUG_GTE(DB, 1))
988 +                       rprintf(FCLIENT, "[%s] Setting sqlite errlog to %s\n", who_am_i(), error_log);
989 +               if (!(error_log_fp = fopen(error_log, "a"))) {
990 +                       rsyserr(log_code, errno, "unable to append to logfile %s", error_log);
991 +                       error_log = NULL;
992 +               } else if (sqlite3_config(SQLITE_CONFIG_LOG, errorLogCallback, NULL) != 0)
993 +                       rprintf(log_code, "Failed to set errorLogCallback: %s\n", sqlite3_errmsg(dbh.sqlite));
994 +       }
995 +#endif
996 +
997 +       while (1) {
998 +               int open_flags = SQLITE_OPEN_READWRITE;
999 +               if (db_init)
1000 +                       open_flags |= SQLITE_OPEN_CREATE;
1001 +               if (DEBUG_GTE(DB, 1))
1002 +                       rprintf(FCLIENT, "[%s] opening %s (%d)\n", who_am_i(), dbname, open_flags);
1003 +               if ((rc = sqlite3_open_v2(dbname, &dbh.sqlite, open_flags, NULL)) == 0) {
1004 +                       break;
1005 +               }
1006 +               if (DEBUG_GTE(DB, 4)) {
1007 +                       rprintf(FCLIENT, "[%s] sqlite3_open_v2(%s,,%d,NULL) returned %d\n",
1008 +                               who_am_i(), dbname, open_flags, rc);
1009 +               }
1010 +               if (rc != SQLITE_BUSY && rc != SQLITE_LOCKED)
1011 +                       break;
1012 +               if (++lock_failures > MAX_LOCK_FAILURES)
1013 +                       break;
1014 +               msleep(LOCK_FAIL_MSLEEP);
1015 +       }
1016 +
1017 +       if (rc) {
1018 +               rprintf(log_code, "Unable to connect to DB: %s (%d)\n", sqlite3_errmsg(dbh.sqlite), rc);
1019 +               return 0;
1020 +       }
1021 +
1022 +       if (db_init) {
1023 +               char *sql;
1024 +               if (db_output_msgs)
1025 +                       rprintf(FCLIENT, "Dropping old tables (if they exist) ...\n");
1026 +               if (!run_sql("DROP TABLE IF EXISTS disk")
1027 +                || !run_sql("DROP TABLE IF EXISTS inode_map"))
1028 +                       exit_cleanup(RERR_IPC);
1029 +
1030 +               if (db_output_msgs)
1031 +                       rprintf(FCLIENT, "Creating empty tables ...\n");
1032 +               sql="CREATE TABLE disk (\n"
1033 +                   "  disk_id integer NOT NULL PRIMARY KEY AUTOINCREMENT,\n"
1034 +                   "  host varchar(128) NOT NULL default 'localhost',\n"
1035 +                   "  mount_uniq varchar(128) default NULL,\n"
1036 +                   "  devno bigint NOT NULL,\n" /* This is 0 when not mounted */
1037 +                   "  last_seen bigint NOT NULL,\n"
1038 +                   "  UNIQUE (host, mount_uniq)\n"
1039 +                   ")";
1040 +               if (!run_sql(sql))
1041 +                       exit_cleanup(RERR_IPC);
1042 +
1043 +               sql="CREATE TABLE inode_map (\n"
1044 +                   "  disk_id integer NOT NULL,\n"
1045 +                   "  ino bigint NOT NULL,\n"
1046 +                   "  size bigint NOT NULL,\n"
1047 +                   "  mtime bigint NOT NULL,\n"
1048 +                   "  ctime bigint NOT NULL,\n"
1049 +                   "  sum_type tinyint NOT NULL default '0',\n"
1050 +                   "  checksum binary(16) NOT NULL,\n"
1051 +                   "  PRIMARY KEY (disk_id,ino,sum_type)\n"
1052 +                   ")";
1053 +               if (!run_sql(sql))
1054 +                       exit_cleanup(RERR_IPC);
1055 +
1056 +#if SQLITE_VERSION_NUMBER >= 3007000
1057 +               /* Using WAL locking makes concurrency much better (requires sqlite 3.7.0). */
1058 +               sql="PRAGMA journal_mode = wal";
1059 +               run_sql(sql); /* We don't check this for success. */
1060 +#endif
1061 +
1062 +               if (!db_mounts)
1063 +                       exit_cleanup(0);
1064 +       }
1065 +
1066 +       if (db_mounts) {
1067 +               if (!prepare_sqlite_queries(PREP_MOUNT))
1068 +                       exit_cleanup(RERR_IPC);
1069 +               update_mounts();
1070 +               exit_cleanup(0);
1071 +       }
1072 +
1073 +       if (!prepare_sqlite_queries(PREP_NORM)) {
1074 +               db_disconnect(False);
1075 +               return 0;
1076 +       }
1077 +
1078 +       return 1;
1079 +}
1080 +#endif
1081 +
1082 +int db_connect(int select_many)
1083 +{
1084 +       select_many_sums = select_many;
1085 +
1086 +       switch (use_db) {
1087 +#ifdef USE_MYSQL
1088 +       case DB_TYPE_MYSQL:
1089 +               if (db_connect_mysql())
1090 +                       return 1;
1091 +               break;
1092 +#endif
1093 +#ifdef USE_SQLITE
1094 +       case DB_TYPE_SQLITE:
1095 +               if (db_connect_sqlite())
1096 +                       return 1;
1097 +               break;
1098 +#endif
1099 +       }
1100 +
1101 +       db_disconnect(False);
1102 +
1103 +       return 0;
1104 +}
1105 +
1106 +void db_disconnect(BOOL commit)
1107 +{
1108 +       int ndx;
1109 +
1110 +       if (!dbh.all)
1111 +               return;
1112 +
1113 +       if (transaction_state > 0) {
1114 +               if (DEBUG_GTE(DB, 1)) {
1115 +                       rprintf(FCLIENT, "[%s] %s our DB transaction\n",
1116 +                               who_am_i(), commit ? "Committing" : "Rolling back");
1117 +               }
1118 +               transaction_state = 0;
1119 +               if (commit)
1120 +                       run_sql("COMMIT");
1121 +               else
1122 +                       run_sql("ROLLBACK");
1123 +       }
1124 +
1125 +       if (DEBUG_GTE(DB, 1))
1126 +               rprintf(FCLIENT, "[%s] Disconnecting from the DB\n", who_am_i());
1127 +
1128 +       for (ndx = 0; ndx < MAX_PREP_CNT; ndx++) {
1129 +               if (statements[ndx].all) {
1130 +                       switch (use_db) {
1131 +#ifdef USE_MYSQL
1132 +                       case DB_TYPE_MYSQL:
1133 +                               mysql_stmt_close(statements[ndx].mysql);
1134 +                               break;
1135 +#endif
1136 +#ifdef USE_SQLITE
1137 +                       case DB_TYPE_SQLITE:
1138 +                               sqlite3_finalize(statements[ndx].sqlite);
1139 +                               break;
1140 +#endif
1141 +                       }
1142 +                       statements[ndx].all = NULL;
1143 +               }
1144 +       }
1145 +
1146 +       switch (use_db) {
1147 +#ifdef USE_MYSQL
1148 +       case DB_TYPE_MYSQL:
1149 +               mysql_close(dbh.mysql);
1150 +               break;
1151 +#endif
1152 +#ifdef USE_SQLITE
1153 +       case DB_TYPE_SQLITE:
1154 +               sqlite3_close(dbh.sqlite);
1155 +               break;
1156 +#endif
1157 +       }
1158 +
1159 +       dbh.all = NULL;
1160 +       use_db = DB_TYPE_NONE;
1161 +}
1162 +
1163 +#ifdef USE_MYSQL
1164 +static MYSQL_STMT *exec_mysql(int ndx)
1165 +{
1166 +       MYSQL_STMT *stmt = statements[ndx].mysql;
1167 +       int rc;
1168 +
1169 +       if ((rc = mysql_stmt_execute(stmt)) == CR_SERVER_LOST) {
1170 +               db_disconnect(False);
1171 +               use_db = DB_TYPE_MYSQL;
1172 +               if (db_connect(select_many_sums)) {
1173 +                       stmt = statements[ndx].mysql;
1174 +                       rc = mysql_stmt_execute(stmt);
1175 +               }
1176 +       }
1177 +       if (rc != 0) {
1178 +               rprintf(log_code, "SQL execute failed: %s\n", mysql_stmt_error(stmt));
1179 +               return NULL;
1180 +       }
1181 +
1182 +       return stmt;
1183 +}
1184 +#endif
1185 +
1186 +#ifdef USE_MYSQL
1187 +/* This stores up to max_rows into the values pointed to by the bind data arrays.
1188 + * If max_rows is > 1, then all the buffer pointers MUST be set to an array long
1189 + * enough to hold the max count of rows.  The buffer pointer will be incremented
1190 + * to read additional rows (but never past the end).  If stmt_ptr is non-NULL, it
1191 + * will be set to the "stmt" pointer IFF we didn't run out of rows before hitting
1192 + * the max.  In this case, the caller should call mysql_stmt_fetch() to read any
1193 + * remaining rows (the buffer pointers will point at the final array element) and
1194 + * then call mysql_stmt_free_result().  If *stmt_ptr is a NULL value, there were
1195 + * not enough rows to fill the max_rows arrays, and the stmt was already freed. */
1196 +static int fetch_mysql(MYSQL_BIND *binds, int bind_cnt, int ndx, int max_rows, MYSQL_STMT **stmt_ptr)
1197 +{
1198 +       MYSQL_STMT *stmt;
1199 +       int i, rc, rows = 0;
1200 +
1201 +       if (bind_cnt > MAX_RESULT_BINDS) {
1202 +               fprintf(stderr, "Internal error: MAX_RESULT_BINDS overflow\n");
1203 +               exit_cleanup(RERR_UNSUPPORTED);
1204 +       }
1205 +
1206 +       if ((stmt = exec_mysql(ndx)) == NULL)
1207 +               return 0;
1208 +
1209 +       for (i = 0; i < bind_cnt; i++) {
1210 +               binds[i].is_null = &result_is_null[i];
1211 +               binds[i].length = &result_length[i];
1212 +               binds[i].error = &result_error[i];
1213 +       }
1214 +       mysql_stmt_bind_result(stmt, binds);
1215 +
1216 +       while (rows < max_rows) {
1217 +               if ((rc = mysql_stmt_fetch(stmt)) != 0) {
1218 +                       if (rc != MYSQL_NO_DATA)
1219 +                               rprintf(log_code, "SELECT fetch failed: %s\n", mysql_stmt_error(stmt));
1220 +                       break;
1221 +               }
1222 +               if (++rows >= max_rows)
1223 +                       break;
1224 +               for (i = 0; i < bind_cnt; i++) {
1225 +                       switch (binds[i].buffer_type) {
1226 +                       case MYSQL_TYPE_BLOB:
1227 +                       case MYSQL_TYPE_STRING:
1228 +                           binds[i].buffer += binds[i].buffer_length;
1229 +                           break;
1230 +                       case MYSQL_TYPE_LONG:
1231 +                           binds[i].buffer += sizeof (int);
1232 +                           break;
1233 +                       case MYSQL_TYPE_LONGLONG:
1234 +                           binds[i].buffer += sizeof (int64);
1235 +                           break;
1236 +                       default:
1237 +                           fprintf(stderr, "Unknown MYSQL_TYPE_* in multi-row read: %d.\n", binds[i].buffer_type);
1238 +                           exit_cleanup(RERR_UNSUPPORTED);
1239 +                       }
1240 +               }
1241 +       }
1242 +
1243 +       if (!stmt_ptr || rows < max_rows) {
1244 +               mysql_stmt_free_result(stmt);
1245 +               stmt = NULL;
1246 +       }
1247 +       if (stmt_ptr)
1248 +               *stmt_ptr = stmt;
1249 +
1250 +       return rows;
1251 +}
1252 +#endif
1253 +
1254 +#if defined USE_MYSQL || defined USE_SQLITE
1255 +static void update_mounts(void)
1256 +{
1257 +       char buf[2048], *argv[2];
1258 +       int f_from, f_to, len;
1259 +       STRUCT_STAT st;
1260 +       int pid, status;
1261 +
1262 +       if (DEBUG_GTE(DB, 2))
1263 +               printf("Running %s to grab mount info\n", mount_helper_script);
1264 +       argv[0] = mount_helper_script;
1265 +       argv[1] = NULL;
1266 +       pid = piped_child(argv, &f_from, &f_to);
1267 +       close(f_to);
1268 +
1269 +       bind_mtime = time(NULL); /* abuse mtime slightly to hold our last_seen value */
1270 +
1271 +       /* Strict format has 2 items with one tab as separator: MOUNT_UNIQ\tPATH */
1272 +       while ((len = read_line(f_from, buf, sizeof buf, 0)) > 0) {
1273 +               char *mount_uniq, *path;
1274 +
1275 +               if (DEBUG_GTE(DB, 3))
1276 +                       printf("Parsing mount info: %s\n", buf);
1277 +               mount_uniq = strtok(buf, "\t");
1278 +               path = mount_uniq ? strtok(NULL, "\r\n") : NULL;
1279 +               if (!path) {
1280 +                       fprintf(stderr, "Failed to parse line from %s output\n", mount_helper_script);
1281 +                       exit_cleanup(RERR_SYNTAX);
1282 +               }
1283 +
1284 +               if (lstat(path, &st) < 0) {
1285 +                       fprintf(stderr, "Failed to lstat(%s): %s\n", path, strerror(errno));
1286 +                       exit_cleanup(RERR_IPC);
1287 +               }
1288 +
1289 +               bind_mount_uniq_len = strlcpy(bind_mount_uniq, mount_uniq, sizeof bind_mount_uniq);
1290 +               if (bind_mount_uniq_len >= (int)sizeof bind_mount_uniq)
1291 +                       bind_mount_uniq_len = sizeof bind_mount_uniq - 1;
1292 +
1293 +               if (db_output_msgs) {
1294 +                       printf("Marking mount \"%s\" (%s) as a recent mount\n",
1295 +                               bind_mount_uniq, big_num(st.st_dev));
1296 +               }
1297 +               switch (use_db) {
1298 +#ifdef USE_MYSQL
1299 +               case DB_TYPE_MYSQL:
1300 +                       bind_devno = st.st_dev;
1301 +                       if (exec_mysql(INS_MOUNT) == NULL) {
1302 +                               fprintf(stderr, "Failed to update mount info for \"%s\" - %s\n",
1303 +                                       bind_mount_uniq, mysql_error(dbh.mysql));
1304 +                               exit_cleanup(RERR_IPC);
1305 +                       }
1306 +                       break;
1307 +#endif
1308 +#ifdef USE_SQLITE
1309 +               case DB_TYPE_SQLITE: {
1310 +                       int rc, change_cnt;
1311 +                       sqlite3_stmt *stmt = statements[INS_MOUNT].sqlite;
1312 +                       sqlite3_bind_text(stmt, 1, bind_thishost, bind_thishost_len, SQLITE_STATIC);
1313 +                       sqlite3_bind_int64(stmt, 2, bind_mtime);
1314 +                       sqlite3_bind_text(stmt, 3, bind_mount_uniq, bind_mount_uniq_len, SQLITE_STATIC);
1315 +                       sqlite3_bind_int64(stmt, 4, st.st_dev);
1316 +                       rc = sqlite3_step(stmt);
1317 +                       if (rc != SQLITE_DONE) {
1318 +                               fprintf(stderr, "Failed to insert mount info for \"%s\" - %s (%d)\n",
1319 +                                       bind_mount_uniq, sqlite3_errmsg(dbh.sqlite), rc);
1320 +                               exit_cleanup(RERR_IPC);
1321 +                       }
1322 +                       change_cnt = sqlite3_changes(dbh.sqlite);
1323 +                       sqlite3_reset(stmt);
1324 +                       if (change_cnt == 0) {
1325 +                               stmt = statements[UPD_MOUNT].sqlite;
1326 +                               sqlite3_bind_int64(stmt, 1, bind_mtime);
1327 +                               sqlite3_bind_int64(stmt, 2, st.st_dev);
1328 +                               sqlite3_bind_text(stmt, 3, bind_thishost, bind_thishost_len, SQLITE_STATIC);
1329 +                               sqlite3_bind_text(stmt, 4, bind_mount_uniq, bind_mount_uniq_len, SQLITE_STATIC);
1330 +                               rc = sqlite3_step(stmt);
1331 +                               if (rc != SQLITE_DONE) {
1332 +                                       fprintf(stderr, "Failed to update mount info for \"%s\" - %s (%d)\n",
1333 +                                               bind_mount_uniq, sqlite3_errmsg(dbh.sqlite), rc);
1334 +                                       exit_cleanup(RERR_IPC);
1335 +                               }
1336 +                               sqlite3_reset(stmt);
1337 +                       }
1338 +                       break;
1339 +                   }
1340 +#endif
1341 +               }
1342 +       }
1343 +       close(f_from);
1344 +
1345 +       waitpid(pid, &status, 0);
1346 +
1347 +       switch (use_db) {
1348 +#ifdef USE_MYSQL
1349 +       case DB_TYPE_MYSQL: {
1350 +               if (db_output_msgs) {
1351 +                       MYSQL_BIND binds[1];
1352 +                       MYSQL_STMT *stmt;
1353 +
1354 +                       binds[0].buffer_type = MYSQL_TYPE_BLOB;
1355 +                       binds[0].buffer = bind_mount_uniq;
1356 +                       binds[0].buffer_length = sizeof bind_mount_uniq;
1357 +                       if (fetch_mysql(binds, 1, SEL_MOUNT, 1, &stmt)) {
1358 +                               while (1) {
1359 +                                       printf("Marking mount \"%s\" as unmounted.\n", bind_mount_uniq);
1360 +                                       if (mysql_stmt_fetch(stmt) != 0)
1361 +                                               break;
1362 +                               }
1363 +                               mysql_stmt_free_result(stmt);
1364 +                       }
1365 +               }
1366 +
1367 +               if (exec_mysql(UN_MOUNT) == NULL) {
1368 +                       fprintf(stderr, "Failed to update old mount info - %s\n",
1369 +                               mysql_error(dbh.mysql));
1370 +                       exit_cleanup(RERR_IPC);
1371 +               }
1372 +               break;
1373 +           }
1374 +#endif
1375 +#ifdef USE_SQLITE
1376 +       case DB_TYPE_SQLITE: {
1377 +               sqlite3_stmt *stmt;
1378 +               int rc;
1379 +
1380 +               if (db_output_msgs) {
1381 +                       stmt = statements[SEL_MOUNT].sqlite;
1382 +                       sqlite3_bind_text(stmt, 1, bind_thishost, bind_thishost_len, SQLITE_STATIC);
1383 +                       sqlite3_bind_int64(stmt, 2, bind_mtime);
1384 +                       while (1) {
1385 +                               if (sqlite3_step(stmt) != SQLITE_ROW)
1386 +                                       break;
1387 +                               printf("Marking mount \"%s\" as unmounted.\n", sqlite3_column_text(stmt, 0));
1388 +                       }
1389 +                       sqlite3_reset(stmt);
1390 +               }
1391 +
1392 +               stmt = statements[UN_MOUNT].sqlite;
1393 +               sqlite3_bind_text(stmt, 1, bind_thishost, bind_thishost_len, SQLITE_STATIC);
1394 +               sqlite3_bind_int64(stmt, 2, bind_mtime);
1395 +               rc = sqlite3_step(stmt);
1396 +               sqlite3_reset(stmt);
1397 +               if (rc != SQLITE_DONE) {
1398 +                       fprintf(stderr, "Failed to update old mount info - %s (%d)\n",
1399 +                               sqlite3_errmsg(dbh.sqlite), rc);
1400 +                       exit_cleanup(RERR_IPC);
1401 +               }
1402 +               break;
1403 +           }
1404 +#endif
1405 +       }
1406 +}
1407 +#endif
1408 +
1409 +static unsigned int get_disk_id(int64 devno)
1410 +{
1411 +       static unsigned int prior_disk_id = 0;
1412 +       static int64 prior_devno = 0;
1413 +
1414 +       if (prior_devno == devno && prior_disk_id) {
1415 +               if (DEBUG_GTE(DB, 5))
1416 +                       rprintf(FCLIENT, "get_disk_id(%s,%s) = %d (cached)\n", bind_thishost, big_num(devno), prior_disk_id);
1417 +               return prior_disk_id;
1418 +       }
1419 +       prior_devno = devno;
1420 +
1421 +       switch (use_db) {
1422 +#ifdef USE_MYSQL
1423 +       case DB_TYPE_MYSQL: {
1424 +               MYSQL_BIND binds[1];
1425 +
1426 +               bind_devno = devno; /* The one changing SEL_DEV input value. */
1427 +
1428 +               /* Bind where to put the output. */
1429 +               binds[0].buffer_type = MYSQL_TYPE_LONG;
1430 +               binds[0].buffer = &prior_disk_id;
1431 +               if (!fetch_mysql(binds, 1, SEL_DEV, 1, NULL))
1432 +                       prior_disk_id = 0;
1433 +               break;
1434 +           }
1435 +#endif
1436 +#ifdef USE_SQLITE
1437 +       case DB_TYPE_SQLITE: {
1438 +               sqlite3_stmt *stmt = statements[SEL_DEV].sqlite;
1439 +               sqlite3_bind_text(stmt, 1, bind_thishost, bind_thishost_len, SQLITE_STATIC);
1440 +               sqlite3_bind_int64(stmt, 2, devno);
1441 +               if (sqlite3_step(stmt) == SQLITE_ROW)
1442 +                       prior_disk_id = sqlite3_column_int(stmt, 0);
1443 +               else
1444 +                       prior_disk_id = 0;
1445 +               sqlite3_reset(stmt);
1446 +               break;
1447 +           }
1448 +#endif
1449 +       }
1450 +
1451 +       if (DEBUG_GTE(DB, 2))
1452 +               rprintf(FCLIENT, "get_disk_id(%s,%s) = %d\n", bind_thishost, big_num(devno), prior_disk_id);
1453 +       return prior_disk_id;
1454 +}
1455 +
1456 +int db_get_checksum(const STRUCT_STAT *st_p, char *sum)
1457 +{
1458 +       unsigned int disk_id = get_disk_id(st_p->st_dev);
1459 +       int ok = 0;
1460 +
1461 +       if (disk_id == 0)
1462 +               return 0;
1463 +
1464 +       switch (use_db) {
1465 +#ifdef USE_MYSQL
1466 +       case DB_TYPE_MYSQL: {
1467 +               MYSQL_BIND binds[1];
1468 +
1469 +               bind_disk_id = disk_id;
1470 +               bind_ino = st_p->st_ino;
1471 +               bind_size = st_p->st_size;
1472 +               bind_mtime = st_p->st_mtime;
1473 +               if (!db_lax)
1474 +                       bind_ctime = st_p->st_ctime;
1475 +
1476 +               binds[0].buffer_type = MYSQL_TYPE_BLOB;
1477 +               binds[0].buffer = sum;
1478 +               binds[0].buffer_length = MD5_DIGEST_LEN;
1479 +               ok = fetch_mysql(binds, 1, SEL_SUM, 1, NULL);
1480 +               break;
1481 +           }
1482 +#endif
1483 +#ifdef USE_SQLITE
1484 +       case DB_TYPE_SQLITE: {
1485 +               sqlite3_stmt *stmt = statements[SEL_SUM].sqlite;
1486 +               sqlite3_bind_int(stmt, 1, disk_id);
1487 +               sqlite3_bind_int64(stmt, 2, st_p->st_ino);
1488 +               sqlite3_bind_int64(stmt, 3, st_p->st_size);
1489 +               sqlite3_bind_int64(stmt, 4, st_p->st_mtime);
1490 +               if (!db_lax)
1491 +                       sqlite3_bind_int64(stmt, 5, st_p->st_ctime);
1492 +               if (sqlite3_step(stmt) == SQLITE_ROW) {
1493 +                       int len = sqlite3_column_bytes(stmt, 0);
1494 +                       if (len > MAX_DIGEST_LEN)
1495 +                               len = MAX_DIGEST_LEN;
1496 +                       memcpy(sum, sqlite3_column_blob(stmt, 0), len);
1497 +                       ok = 1;
1498 +               }
1499 +               sqlite3_reset(stmt);
1500 +               break;
1501 +           }
1502 +#endif
1503 +       }
1504 +
1505 +       if (DEBUG_GTE(DB, 2)) {
1506 +               if (ok) {
1507 +                       rprintf(FCLIENT, "[%s] Found DB checksum for %s,%s,%d: %s\n",
1508 +                               who_am_i(), big_num(st_p->st_dev),
1509 +                               big_num(st_p->st_ino), md_num, sum_as_hex(md_num, sum, 0));
1510 +               } else {
1511 +                       rprintf(FCLIENT, "[%s] No DB checksum for %s,%s,%d\n",
1512 +                               who_am_i(), big_num(st_p->st_dev),
1513 +                               big_num(st_p->st_ino), md_num);
1514 +               }
1515 +       }
1516 +
1517 +       return ok;
1518 +}
1519 +
1520 +int db_get_both_checksums(const STRUCT_STAT *st_p, int *right_sum_cnt, int *wrong_sum_cnt, char **sum4, char **sum5)
1521 +{
1522 +       static char dbsum[MD5_DIGEST_LEN*2];
1523 +       int rows, j, sum_type[2];
1524 +       int64 dbsize[2], dbmtime[2], dbctime[2];
1525 +       unsigned int disk_id = get_disk_id(st_p->st_dev);
1526 +
1527 +       if (disk_id == 0)
1528 +               return 0;
1529 +
1530 +       switch (use_db) {
1531 +#ifdef USE_MYSQL
1532 +       case DB_TYPE_MYSQL: {
1533 +               MYSQL_BIND binds[5];
1534 +
1535 +               bind_disk_id = disk_id;
1536 +               bind_ino = st_p->st_ino;
1537 +
1538 +               binds[0].buffer_type = MYSQL_TYPE_BLOB;
1539 +               binds[0].buffer = dbsum;
1540 +               binds[0].buffer_length = MD5_DIGEST_LEN;
1541 +               binds[1].buffer_type = MYSQL_TYPE_LONG;
1542 +               binds[1].buffer = (char*)sum_type;
1543 +               binds[2].buffer_type = MYSQL_TYPE_LONGLONG;
1544 +               binds[2].buffer = (char*)dbsize;
1545 +               binds[3].buffer_type = MYSQL_TYPE_LONGLONG;
1546 +               binds[3].buffer = (char*)dbmtime;
1547 +               binds[4].buffer_type = MYSQL_TYPE_LONGLONG;
1548 +               binds[4].buffer = (char*)dbctime;
1549 +               rows = fetch_mysql(binds, 5, SEL_SUM, 2, NULL);
1550 +               break;
1551 +           }
1552 +#endif
1553 +#ifdef USE_SQLITE
1554 +       case DB_TYPE_SQLITE: {
1555 +               sqlite3_stmt *stmt = statements[SEL_SUM].sqlite;
1556 +               sqlite3_bind_int(stmt, 1, disk_id);
1557 +               sqlite3_bind_int64(stmt, 2, st_p->st_ino);
1558 +               for (j = 0; j < 2; j++) {
1559 +                       int len;
1560 +                       if (sqlite3_step(stmt) != SQLITE_ROW)
1561 +                               break;
1562 +                       len = sqlite3_column_bytes(stmt, 0);
1563 +                       if (len > MD5_DIGEST_LEN)
1564 +                               len = MD5_DIGEST_LEN;
1565 +                       memcpy(dbsum + MD5_DIGEST_LEN*j, sqlite3_column_blob(stmt, 0), len);
1566 +                       sum_type[j] = sqlite3_column_int(stmt, 1);
1567 +                       dbsize[j] = sqlite3_column_int(stmt, 2);
1568 +                       dbmtime[j] = sqlite3_column_int64(stmt, 3);
1569 +                       dbctime[j] = sqlite3_column_int64(stmt, 4);
1570 +               }
1571 +               sqlite3_reset(stmt);
1572 +               rows = j;
1573 +               break;
1574 +           }
1575 +#endif
1576 +       default:
1577 +               return 0;
1578 +       }
1579 +
1580 +       if (sum4)
1581 +               *sum4 = NULL;
1582 +       if (sum5)
1583 +               *sum5 = NULL;
1584 +       *right_sum_cnt = *wrong_sum_cnt = 0;
1585 +       for (j = 0; j < rows; j++) {
1586 +               if (DEBUG_GTE(DB, 3)) {
1587 +                       rprintf(FCLIENT, "DB checksum for %s,%s,%d: %s\n",
1588 +                               big_num(st_p->st_dev), big_num(st_p->st_ino), sum_type[j],
1589 +                               sum_as_hex(sum_type[j], dbsum + MD5_DIGEST_LEN*j, 0));
1590 +               }
1591 +
1592 +               if (sum_type[j] == 4) {
1593 +                       if (!sum4)
1594 +                               continue;
1595 +                       *sum4 = dbsum + MD5_DIGEST_LEN*j;
1596 +               } else {
1597 +                       if (!sum5)
1598 +                               continue;
1599 +                       *sum5 = dbsum + MD5_DIGEST_LEN*j;
1600 +               }
1601 +               if (st_p->st_size == dbsize[j] && st_p->st_mtime == dbmtime[j] && (db_lax || st_p->st_ctime == dbctime[j]))
1602 +                       ++*right_sum_cnt;
1603 +               else
1604 +                       ++*wrong_sum_cnt;
1605 +       }
1606 +
1607 +       return rows;
1608 +}
1609 +
1610 +int db_set_checksum(int mdnum, const STRUCT_STAT *st_p, const char *sum)
1611 +{
1612 +       unsigned int disk_id;
1613 +       const char *errmsg = NULL;
1614 +       int rc = 0;
1615 +
1616 +       if (am_receiver || (am_generator && same_db)) {
1617 +               /* Forward the setting to a single process.  The receiver always
1618 +                * forwards to the generator, and the generator will forward to
1619 +                * the sender ONLY if this is a local transfer. */
1620 +               char data[MSG_CHECKSUM_LEN];
1621 +               SIVAL64(data, 0, st_p->st_dev);
1622 +               SIVAL64(data, 8, st_p->st_ino);
1623 +               SIVAL64(data, 16, st_p->st_size);
1624 +               SIVAL64(data, 24, st_p->st_mtime);
1625 +               SIVAL64(data, 32, st_p->st_ctime);
1626 +#if MSG_CHECKSUM_LONGS != 5
1627 +#error Fix the setting of checksum long values
1628 +#endif
1629 +               SIVAL(data, MSG_CHECKSUM_LONGS*8, mdnum);
1630 +               memcpy(data + MSG_CHECKSUM_LONGS*8 + 4, sum, MAX_DIGEST_LEN);
1631 +               return send_msg(MSG_CHECKSUM, data, sizeof data, 0);
1632 +       }
1633 +
1634 +       if ((disk_id = get_disk_id(st_p->st_dev)) == 0)
1635 +               return 0;
1636 +
1637 +       switch (use_db) {
1638 +#ifdef USE_MYSQL
1639 +       case DB_TYPE_MYSQL:
1640 +               if (transaction_state == 0) {
1641 +                       if (!run_sql("BEGIN"))
1642 +                               return 0;
1643 +                       transaction_state = 1;
1644 +               }
1645 +
1646 +               bind_disk_id = disk_id;
1647 +               bind_ino = st_p->st_ino;
1648 +               bind_mdnum = mdnum;
1649 +               bind_size = st_p->st_size;
1650 +               bind_mtime = st_p->st_mtime;
1651 +               bind_ctime = st_p->st_ctime;
1652 +               memcpy(bind_sum, sum, MD5_DIGEST_LEN);
1653 +               if (exec_mysql(REP_SUM) == NULL)
1654 +                       errmsg = mysql_error(dbh.mysql);
1655 +               break;
1656 +#endif
1657 +#ifdef USE_SQLITE
1658 +       case DB_TYPE_SQLITE: {
1659 +               sqlite3_stmt *stmt = statements[REP_SUM].sqlite;
1660 +               int lock_failures = 0;
1661 +
1662 +               if (transaction_state == 0) {
1663 +                       if (!run_sql("BEGIN"))
1664 +                               return 0;
1665 +                       transaction_state = 1;
1666 +               }
1667 +
1668 +               sqlite3_bind_int(stmt, 1, disk_id);
1669 +               sqlite3_bind_int64(stmt, 2, st_p->st_ino);
1670 +               sqlite3_bind_int(stmt, 3, mdnum);
1671 +               sqlite3_bind_int64(stmt, 4, st_p->st_size);
1672 +               sqlite3_bind_int64(stmt, 5, st_p->st_mtime);
1673 +               sqlite3_bind_int64(stmt, 6, st_p->st_ctime);
1674 +               sqlite3_bind_blob(stmt, 7, sum, MD5_DIGEST_LEN, SQLITE_TRANSIENT);
1675 +               while (1) {
1676 +                       rc = sqlite3_step(stmt);
1677 +                       if (rc != SQLITE_BUSY && rc != SQLITE_LOCKED)
1678 +                               break;
1679 +                       if (++lock_failures > MAX_LOCK_FAILURES)
1680 +                               break;
1681 +                       sqlite3_reset(stmt);
1682 +                       msleep(LOCK_FAIL_MSLEEP);
1683 +               }
1684 +               if (rc != SQLITE_DONE)
1685 +                       errmsg = sqlite3_errmsg(dbh.sqlite);
1686 +               sqlite3_reset(stmt);
1687 +               break;
1688 +           }
1689 +#endif
1690 +       }
1691 +
1692 +       if (!errmsg) {
1693 +               if (DEBUG_GTE(DB, 2)) {
1694 +                       rprintf(FCLIENT, "[%s] Set DB checksum for %s,%s,%d: %s\n",
1695 +                               who_am_i(), big_num(st_p->st_dev), big_num(st_p->st_ino),
1696 +                               md_num, sum_as_hex(md_num, sum, 0));
1697 +               }
1698 +       } else {
1699 +               rprintf(log_code, "[%s] Failed to set checksum for %s,%s,%d: %s (%d) -- closing DB\n",
1700 +                       who_am_i(), big_num(st_p->st_dev), big_num(st_p->st_ino),
1701 +                       md_num, errmsg, rc);
1702 +               db_disconnect(False);
1703 +       }
1704 +
1705 +       return errmsg ? 0 : 1;
1706 +}
1707 +
1708 +/* For a delayed-update copy, we set the checksum on the file when it was
1709 + * inside the partial-dir.  Since renaming the file changes its ctime, we need
1710 + * to update the ctime to its new value (we can skip this in db_lax mode). */
1711 +int db_update_ctime(UNUSED(int mdnum), const STRUCT_STAT *st_p)
1712 +{
1713 +       unsigned int disk_id = get_disk_id(st_p->st_dev);
1714 +
1715 +       if (disk_id == 0)
1716 +               return 0;
1717 +
1718 +       switch (use_db) {
1719 +#ifdef USE_MYSQL
1720 +       case DB_TYPE_MYSQL:
1721 +               bind_ctime = st_p->st_ctime;
1722 +               bind_disk_id = disk_id;
1723 +               bind_ino = st_p->st_ino;
1724 +               bind_mdnum = mdnum;
1725 +               bind_size = st_p->st_size;
1726 +               bind_mtime = st_p->st_mtime;
1727 +               return exec_mysql(UPD_CTIME) != NULL;
1728 +#endif
1729 +#ifdef USE_SQLITE
1730 +       case DB_TYPE_SQLITE: {
1731 +               int rc;
1732 +
1733 +               sqlite3_stmt *stmt = statements[UPD_CTIME].sqlite;
1734 +               if (stmt == NULL)
1735 +                       return 0;
1736 +               sqlite3_bind_int64(stmt, 1, st_p->st_ctime);
1737 +               sqlite3_bind_int(stmt, 2, disk_id);
1738 +               sqlite3_bind_int64(stmt, 3, st_p->st_ino);
1739 +               sqlite3_bind_int(stmt, 4, mdnum);
1740 +               sqlite3_bind_int64(stmt, 5, st_p->st_size);
1741 +               sqlite3_bind_int64(stmt, 6, st_p->st_mtime);
1742 +               rc = sqlite3_step(stmt);
1743 +               sqlite3_reset(stmt);
1744 +               return rc == SQLITE_DONE;
1745 +           }
1746 +#endif
1747 +       }
1748 +
1749 +       return 0;
1750 +}
1751 +
1752 +static int db_clean_init(void)
1753 +{
1754 +       switch (use_db) {
1755 +#ifdef USE_MYSQL
1756 +       case DB_TYPE_MYSQL: {
1757 +               MYSQL_BIND binds[MAX_BIND_CNT];
1758 +               char *sql;
1759 +
1760 +               mysql_query(dbh.mysql,
1761 +                       "CREATE TEMPORARY TABLE inode_present ("
1762 +                       " disk_id integer unsigned NOT NULL,"
1763 +                       " ino bigint unsigned NOT NULL,"
1764 +                       " PRIMARY KEY (disk_id,ino)"
1765 +                       ") ENGINE=MEMORY"
1766 +                       );
1767 +
1768 +               sql="INSERT IGNORE INTO inode_present"
1769 +                   " SET disk_id = ?, ino = ?";
1770 +               memset(binds, 0, sizeof binds);
1771 +               binds[0].buffer_type = MYSQL_TYPE_LONG;
1772 +               binds[0].buffer = &bind_disk_id;
1773 +               binds[1].buffer_type = MYSQL_TYPE_LONGLONG;
1774 +               binds[1].buffer = &bind_ino;
1775 +               if (!prepare_mysql(INS_PRESENT, binds, 2, sql))
1776 +                       exit_cleanup(RERR_SYNTAX);
1777 +
1778 +               sql="DELETE m.*"
1779 +                   " FROM inode_map AS m"
1780 +                   " LEFT JOIN inode_present AS p USING(disk_id, ino)"
1781 +                   " JOIN disk AS d ON(m.disk_id = d.disk_id)"
1782 +                   " WHERE host = ? AND devno != 0 AND p.disk_id IS NULL AND ctime < ?";
1783 +               memset(binds, 0, sizeof binds);
1784 +               binds[0].buffer_type = MYSQL_TYPE_STRING;
1785 +               binds[0].buffer = &bind_thishost;
1786 +               binds[0].buffer_length = bind_thishost_len;
1787 +               binds[1].buffer_type = MYSQL_TYPE_LONGLONG;
1788 +               binds[1].buffer = &bind_ctime;
1789 +               if (!prepare_mysql(DEL_SUMS, binds, 2, sql))
1790 +                       exit_cleanup(RERR_SYNTAX);
1791 +
1792 +               return 1;
1793 +           }
1794 +#endif
1795 +#ifdef USE_SQLITE
1796 +       case DB_TYPE_SQLITE: {
1797 +               char *sql;
1798 +               sql="ATTACH DATABASE '' AS aux1;"; /* Private temp DB, probably in-memory */
1799 +               if (!run_sql(sql))
1800 +                       exit_cleanup(RERR_IPC);
1801 +
1802 +               sql="CREATE TABLE aux1.inode_present ("
1803 +                   " disk_id integer NOT NULL,"
1804 +                   " ino bigint NOT NULL,"
1805 +                   " PRIMARY KEY (disk_id,ino)"
1806 +                   ")";
1807 +               if (!run_sql(sql))
1808 +                       exit_cleanup(RERR_IPC);
1809 +
1810 +               sql="INSERT OR IGNORE INTO aux1.inode_present"
1811 +                   " (disk_id, ino)"
1812 +                   " VALUES (?, ?)";
1813 +               if (!prepare_sqlite(INS_PRESENT, sql))
1814 +                       exit_cleanup(RERR_IPC);
1815 +
1816 +               sql="DELETE FROM inode_map"
1817 +                   " WHERE ROWID IN ("
1818 +                   "  SELECT m.ROWID"
1819 +                   "  FROM inode_map AS m"
1820 +                   "  LEFT JOIN aux1.inode_present AS p USING(disk_id, ino)"
1821 +                   "  JOIN disk AS d ON(m.disk_id = d.disk_id)"
1822 +                   "  WHERE host = ? AND devno != 0 AND p.disk_id IS NULL AND ctime < ?"
1823 +                   " )";
1824 +               if (!prepare_sqlite(DEL_SUMS, sql))
1825 +                       exit_cleanup(RERR_IPC);
1826 +
1827 +               transaction_state = -1; /* bug work-around -- force transaction off when cleaning XXX */
1828 +
1829 +               return 1;
1830 +           }
1831 +#endif
1832 +       }
1833 +
1834 +       return 0;
1835 +}
1836 +
1837 +static int db_note_present(UNUSED(int disk_id), UNUSED(int64 ino))
1838 +{
1839 +       switch (use_db) {
1840 +#ifdef USE_MYSQL
1841 +       case DB_TYPE_MYSQL:
1842 +               bind_disk_id = disk_id;
1843 +               bind_ino = ino;
1844 +               return exec_mysql(INS_PRESENT) != NULL;
1845 +#endif
1846 +#ifdef USE_SQLITE
1847 +       case DB_TYPE_SQLITE: {
1848 +               int rc;
1849 +               sqlite3_stmt *stmt = statements[INS_PRESENT].sqlite;
1850 +               sqlite3_bind_int(stmt, 1, disk_id);
1851 +               sqlite3_bind_int64(stmt, 2, ino);
1852 +               rc = sqlite3_step(stmt);
1853 +               sqlite3_reset(stmt);
1854 +               return rc == SQLITE_DONE;
1855 +           }
1856 +#endif
1857 +       }
1858 +
1859 +       return 0;
1860 +}
1861 +
1862 +/* This function requires the user to have populated all disk_id+inode pairs
1863 + * into the inode_present table. */
1864 +static int db_clean_inodes(UNUSED(time_t start_time))
1865 +{
1866 +       int del_cnt = 0;
1867 +
1868 +       /* The extra ctime < start_time check ensures that brand-new checksums that
1869 +        * were added after the start of our cleaning run are not removed. */
1870 +       switch (use_db) {
1871 +#ifdef USE_MYSQL
1872 +       case DB_TYPE_MYSQL: {
1873 +               MYSQL_STMT *stmt;
1874 +               bind_ctime = start_time;
1875 +               stmt = exec_mysql(DEL_SUMS);
1876 +               if (stmt != NULL)
1877 +                       del_cnt = mysql_affected_rows(dbh.mysql);
1878 +               break;
1879 +           }
1880 +#endif
1881 +#ifdef USE_SQLITE
1882 +       case DB_TYPE_SQLITE: {
1883 +               int rc;
1884 +               sqlite3_stmt *stmt = statements[DEL_SUMS].sqlite;
1885 +               sqlite3_bind_text(stmt, 1, bind_thishost, bind_thishost_len, SQLITE_STATIC);
1886 +               sqlite3_bind_int64(stmt, 2, start_time);
1887 +               rc = sqlite3_step(stmt);
1888 +               if (rc == SQLITE_DONE)
1889 +                       del_cnt = sqlite3_changes(dbh.sqlite);
1890 +               sqlite3_reset(stmt);
1891 +               break;
1892 +           }
1893 +#endif
1894 +       }
1895 +
1896 +       return del_cnt;
1897 +}
1898 +
1899 +static int abs_path(char *buf, int bufsiz, const char *curdir, const char *dir)
1900 +{
1901 +       if (*dir == '/')
1902 +               strlcpy(buf, dir, bufsiz);
1903 +       else {
1904 +               int len = snprintf(buf, bufsiz, "%s/%s", curdir, dir);
1905 +               assert(len > 0); /* silence a compiler warning */
1906 +       }
1907 +
1908 +       return clean_fname(buf, CFN_DROP_TRAILING_DOT_DIR | CFN_COLLAPSE_DOT_DOT_DIRS);
1909 +}
1910 +
1911 +static struct name_list *new_name(const char *basename, const char *filename)
1912 +{
1913 +       struct name_list *n;
1914 +       int blen = strlen(basename);
1915 +       int slen = filename ? (int)strlen(filename) : -1;
1916 +       int len = blen + 1 + slen;
1917 +
1918 +       if (len >= MAXPATHLEN) {
1919 +               if (filename)
1920 +                       rprintf(FERROR, "Filename too long: %s/%s\n", basename, filename);
1921 +               else
1922 +                       rprintf(FERROR, "Filename too long: %s\n", basename);
1923 +               return NULL;
1924 +       }
1925 +
1926 +       n = (struct name_list *)new_array(char, sizeof (struct name_list) + len);
1927 +
1928 +       memcpy(n->name, basename, blen);
1929 +       if (filename) {
1930 +               n->name[blen] = '/';
1931 +               memcpy(n->name + 1 + blen, filename, slen);
1932 +       }
1933 +       n->name[len] = '\0';
1934 +       n->next = NULL;
1935 +
1936 +       return n;
1937 +}
1938 +
1939 +static int name_compare(const void *n1, const void *n2)
1940 +{
1941 +       struct name_list *p1 = *(struct name_list **)n1;
1942 +       struct name_list *p2 = *(struct name_list **)n2;
1943 +       return strcmp(p1->name, p2->name);
1944 +}
1945 +
1946 +static struct name_list *get_sorted_names(const char *dir)
1947 +{
1948 +       struct name_list *add, **sortbuf, *names = NULL, *prior_name = NULL;
1949 +       struct dirent *di;
1950 +       int cnt = 0;
1951 +       DIR *d;
1952 +
1953 +       if (!(d = opendir("."))) {
1954 +               rprintf(FERROR, "Unable to opendir %s: %s\n", dir, strerror(errno));
1955 +               return NULL;
1956 +       }
1957 +       while ((di = readdir(d)) != NULL) {
1958 +               char *dname = d_name(di);
1959 +               if (dname[0] == '.' && (dname[1] == '\0' || (dname[1] == '.' && dname[2] == '\0')))
1960 +                       continue;
1961 +               if (!(add = new_name(dname, NULL)))
1962 +                       continue;
1963 +               if (prior_name)
1964 +                       prior_name->next = add;
1965 +               else
1966 +                       names = add;
1967 +               prior_name = add;
1968 +               cnt++;
1969 +       }
1970 +       closedir(d);
1971 +
1972 +       if (cnt) {
1973 +               int j;
1974 +
1975 +               sortbuf = new_array(struct name_list *, cnt);
1976 +               for (j = 0; j < cnt; j++) {
1977 +                       sortbuf[j] = names;
1978 +                       names = names->next;
1979 +               }
1980 +
1981 +               qsort(sortbuf, cnt, PTR_SIZE, name_compare);
1982 +
1983 +               names = prior_name = NULL;
1984 +               for (j = 0; j < cnt; j++) {
1985 +                       add = sortbuf[j];
1986 +                       if (prior_name)
1987 +                               prior_name->next = add;
1988 +                       else
1989 +                               names = add;
1990 +                       prior_name = add;
1991 +               }
1992 +
1993 +               if (prior_name)
1994 +                       prior_name->next = NULL;
1995 +               free(sortbuf);
1996 +       }
1997 +
1998 +       return names;
1999 +}
2000 +
2001 +static inline int sums_ne(const char *sum1, const char *sum2)
2002 +{
2003 +       return memcmp(sum1, sum2, MD5_DIGEST_LEN) != 0;
2004 +}
2005 +
2006 +/* Returns 1 if there is a checksum change, else 0. */
2007 +static int mention_file(const char *dir, const char *name, int right_cnt, int wrong_cnt,
2008 +                       const char *dbsum4, const char *dbsum5, const char *sum4, const char *sum5)
2009 +{
2010 +       char *info_str = wrong_cnt && !right_cnt ? "!i " : "   ";
2011 +       char *md4_str = !db_do_md4 ? NULL : !dbsum4 ? "+4 " : !sum4 ? "?4 " : sums_ne(sum4, dbsum4) ? "!4 " : "   ";
2012 +       char *md5_str = !db_do_md5 ? NULL : !dbsum5 ? "+5 " : !sum5 ? "?5 " : sums_ne(sum5, dbsum5) ? "!5 " : "   ";
2013 +       int chg = *info_str != ' ' || (md4_str && *md4_str != ' ') || (md5_str && *md5_str != ' ');
2014 +       if (chg || db_output_unchanged) {
2015 +               if (db_output_info) {
2016 +                       fputs(info_str, stdout);
2017 +                       if (md4_str)
2018 +                               fputs(md4_str, stdout);
2019 +                       if (md5_str)
2020 +                               fputs(md5_str, stdout);
2021 +               }
2022 +               if (db_output_sum) {
2023 +                       if (db_do_md4)
2024 +                               printf("%s ", sum_as_hex(4, sum4, 0));
2025 +                       if (db_do_md5)
2026 +                               printf("%s ", sum_as_hex(5, sum5, 0));
2027 +               }
2028 +               if (db_output_name) {
2029 +                       if (db_output_sum)
2030 +                               putchar(' '); /* We want 2 spaces, like md5sum. */
2031 +                       if (*dir != '.' || dir[1]) {
2032 +                               fputs(dir, stdout);
2033 +                               putchar('/');
2034 +                       }
2035 +                       puts(name);
2036 +               }
2037 +       }
2038 +
2039 +       return chg;
2040 +}
2041 +
2042 +NORETURN void run_dbonly(const char **args)
2043 +{
2044 +       char start_dir[MAXPATHLEN], dirbuf[MAXPATHLEN];
2045 +       int need_sum_cnt, start_dir_len;
2046 +       struct name_list *prior_dir;
2047 +       struct name_list *names;
2048 +       time_t clean_start = 0;
2049 +       int exit_code = 0;
2050 +
2051 +       checksum_type = 5;
2052 +
2053 +       need_sum_cnt = db_do_md4 + db_do_md5;
2054 +
2055 +       if (!db_read_config(FERROR, db_config) || !db_connect(1))
2056 +               exit_cleanup(RERR_FILEIO);
2057 +
2058 +       if (db_clean) {
2059 +               clean_start = time(NULL);
2060 +               db_clean_init();
2061 +       }
2062 +
2063 +       if (getcwd(start_dir, sizeof start_dir - 1) == NULL) {
2064 +               rsyserr(FERROR, errno, "getcwd()");
2065 +               exit_cleanup(RERR_FILESELECT);
2066 +       }
2067 +       start_dir_len = strlen(start_dir);
2068 +
2069 +       if (args) {
2070 +               prior_dir = NULL;
2071 +               while (*args) {
2072 +                       struct name_list *add;
2073 +                       if (abs_path(dirbuf, sizeof dirbuf, start_dir, *args++) <= 0)
2074 +                               continue;
2075 +                       if (!(add = new_name(dirbuf, NULL)))
2076 +                               continue;
2077 +                       if (prior_dir)
2078 +                               prior_dir->next = add;
2079 +                       else
2080 +                               dirs_list = add;
2081 +                       prior_dir = add;
2082 +               }
2083 +       } else
2084 +               dirs_list = new_name(start_dir, NULL);
2085 +
2086 +       prior_dir = NULL;
2087 +       while (dirs_list) {
2088 +               struct name_list *subdirs, *prior_subdir, *prior_name;
2089 +               const char *dir = dirs_list->name;
2090 +               const char *reldir = dir;
2091 +
2092 +               if (prior_dir)
2093 +                       free((void*)prior_dir);
2094 +               prior_dir = dirs_list;
2095 +               dirs_list = dirs_list->next;
2096 +
2097 +               if (strncmp(reldir, start_dir, start_dir_len) == 0) {
2098 +                       if (reldir[start_dir_len] == '\0')
2099 +                               reldir = ".";
2100 +                       else if (reldir[start_dir_len] == '/')
2101 +                               reldir += start_dir_len + 1;
2102 +               }
2103 +               if (db_output_dirs)
2104 +                       printf("... %s/ ...\n", reldir);
2105 +
2106 +               if (chdir(dir) < 0) {
2107 +                       rprintf(FERROR, "Unable to chdir to %s: %s\n", dir, strerror(errno));
2108 +                       continue;
2109 +               }
2110 +               if (!(names = get_sorted_names(dir)))
2111 +                       continue;
2112 +
2113 +               subdirs = prior_subdir = prior_name = NULL;
2114 +               while (names) {
2115 +                       STRUCT_STAT st;
2116 +                       char *dbsum4, *sum4, sumbuf4[MD5_DIGEST_LEN];
2117 +                       char *dbsum5, *sum5, sumbuf5[MD5_DIGEST_LEN];
2118 +                       int right_sum_cnt, wrong_sum_cnt;
2119 +                       const char *name = names->name;
2120 +                       unsigned int disk_id;
2121 +
2122 +                       if (prior_name)
2123 +                               free((void*)prior_name);
2124 +                       prior_name = names;
2125 +                       names = names->next;
2126 +
2127 +                       dbsum4 = dbsum5 = sum4 = sum5 = NULL;
2128 +
2129 +                       if (lstat(name, &st) < 0) {
2130 +                               rprintf(FERROR, "Failed to lstat(%s): %s\n", name, strerror(errno));
2131 +                               continue;
2132 +                       }
2133 +                       if (S_ISLNK(st.st_mode))
2134 +                               continue;
2135 +                       if (S_ISDIR(st.st_mode)) {
2136 +                               /* add optional excluding of things like /^(CVS|\.svn|\.git|\.bzr)$/; */
2137 +                               if (recurse) {
2138 +                                       struct name_list *add = new_name(dir, name);
2139 +                                       if (add) {
2140 +                                               if (prior_subdir)
2141 +                                                       prior_subdir->next = add;
2142 +                                               else
2143 +                                                       subdirs = add;
2144 +                                               prior_subdir = add;
2145 +                                       }
2146 +                               }
2147 +                               continue;
2148 +                       }
2149 +                       if (!S_ISREG(st.st_mode))
2150 +                               continue;
2151 +
2152 +                       if (!(disk_id = get_disk_id(st.st_dev)))
2153 +                               continue;
2154 +                       if (db_clean) {
2155 +                               db_note_present(disk_id, st.st_ino);
2156 +                               if (!db_update && !db_check)
2157 +                                       continue;
2158 +                       }
2159 +                       db_get_both_checksums(&st, &right_sum_cnt, &wrong_sum_cnt,
2160 +                                             db_do_md4 ? &dbsum4 : NULL, db_do_md5 ? &dbsum5 : NULL);
2161 +
2162 +                       if (!db_check && right_sum_cnt == need_sum_cnt) {
2163 +                               mention_file(reldir, name, right_sum_cnt, wrong_sum_cnt, dbsum4, dbsum5, dbsum4, dbsum5);
2164 +                               continue;
2165 +                       }
2166 +
2167 +                       if (db_update || (db_check && right_sum_cnt) || db_output_sum) {
2168 +                               uchar *data;
2169 +                               int32 remainder;
2170 +                               md_context m4;
2171 +                               MD5_CTX m5;
2172 +                               struct map_struct *buf;
2173 +                               OFF_T off, len = st.st_size;
2174 +                               int fd = do_open(name, O_RDONLY, 0);
2175 +
2176 +                               if (fd < 0) {
2177 +                                       rprintf(FERROR, "ERROR: unable to read %s: %s\n", name, strerror(errno));
2178 +                                       continue;
2179 +                               }
2180 +
2181 +                               if (db_do_md4)
2182 +                                       mdfour_begin(&m4);
2183 +                               if (db_do_md5)
2184 +                                       MD5_Init(&m5);
2185 +
2186 +                               buf = map_file(fd, len, MAX_MAP_SIZE, CSUM_CHUNK);
2187 +
2188 +                               for (off = 0; off + CSUM_CHUNK <= len; off += CSUM_CHUNK) {
2189 +                                       data = (uchar*)map_ptr(buf, off, CSUM_CHUNK);
2190 +                                       if (db_do_md4)
2191 +                                               mdfour_update(&m4, data, CSUM_CHUNK);
2192 +                                       if (db_do_md5)
2193 +                                               MD5_Update(&m5, data, CSUM_CHUNK);
2194 +                               }
2195 +
2196 +                               remainder = (int32)(len - off);
2197 +                               data = (uchar*)map_ptr(buf, off, remainder);
2198 +                               if (db_do_md4) {
2199 +                                       mdfour_update(&m4, data, remainder);
2200 +                                       mdfour_result(&m4, (uchar*)(sum4 = sumbuf4));
2201 +                               }
2202 +                               if (db_do_md5) {
2203 +                                       MD5_Update(&m5, data, remainder);
2204 +                                       MD5_Final((uchar*)(sum5 = sumbuf5), &m5);
2205 +                               }
2206 +
2207 +                               close(fd);
2208 +                               unmap_file(buf);
2209 +                       }
2210 +
2211 +                       int chg = mention_file(reldir, name, right_sum_cnt, wrong_sum_cnt, dbsum4, dbsum5, sum4, sum5);
2212 +                       if (!chg) {
2213 +                               /* Only db_check should get here... */
2214 +                       } else if (!db_update) {
2215 +                               exit_code = 1;
2216 +                       } else {
2217 +                               int fail = 0;
2218 +                               if (db_do_md4 && !db_set_checksum(4, &st, sum4))
2219 +                                       fail = 1;
2220 +                               if (db_do_md5 && !db_set_checksum(5, &st, sum5))
2221 +                                       fail = 1;
2222 +                               if (fail) {
2223 +                                       fprintf(stderr, "Failed to set checksum on %s/%s\n", reldir, name);
2224 +                                       exit_cleanup(RERR_FILEIO);
2225 +                               }
2226 +                       }
2227 +               }
2228 +               if (prior_name)
2229 +                       free((void*)prior_name);
2230 +
2231 +               if (recurse && subdirs) {
2232 +                       prior_subdir->next = dirs_list;
2233 +                       dirs_list = subdirs;
2234 +               }
2235 +       }
2236 +       if (prior_dir)
2237 +               free((void*)prior_dir);
2238 +
2239 +       if (db_clean) {
2240 +               int rows = db_clean_inodes(clean_start);
2241 +               if (db_output_msgs)
2242 +                       printf("Cleaned out %d old inode%s.\n", rows, rows == 1 ? "" : "s");
2243 +       }
2244 +
2245 +       db_disconnect(True);
2246 +       exit(exit_code);
2247 +}
2248 diff --git a/flist.c b/flist.c
2249 --- a/flist.c
2250 +++ b/flist.c
2251 @@ -54,6 +54,7 @@ extern int preserve_devices;
2252  extern int preserve_specials;
2253  extern int delete_during;
2254  extern int missing_args;
2255 +extern int use_db;
2256  extern int eol_nulls;
2257  extern int atimes_ndx;
2258  extern int relative_paths;
2259 @@ -1324,11 +1325,8 @@ struct file_struct *make_file(const char *fname, struct file_list *flist,
2260                 extra_len += EXTRA_LEN;
2261  #endif
2262  
2263 -       if (always_checksum && am_sender && S_ISREG(st.st_mode)) {
2264 -               file_checksum(thisname, &st, tmp_sum);
2265 -               if (sender_keeps_checksum)
2266 -                       extra_len += SUM_EXTRA_CNT * EXTRA_LEN;
2267 -       }
2268 +       if (sender_keeps_checksum && S_ISREG(st.st_mode))
2269 +               extra_len += SUM_EXTRA_CNT * EXTRA_LEN;
2270  
2271  #if EXTRA_ROUNDING > 0
2272         if (extra_len & (EXTRA_ROUNDING * EXTRA_LEN))
2273 @@ -1413,8 +1411,12 @@ struct file_struct *make_file(const char *fname, struct file_list *flist,
2274                 return NULL;
2275         }
2276  
2277 -       if (sender_keeps_checksum && S_ISREG(st.st_mode))
2278 -               memcpy(F_SUM(file), tmp_sum, flist_csum_len);
2279 +       if (always_checksum && am_sender && S_ISREG(st.st_mode)) {
2280 +               if (!use_db || !db_get_checksum(&st, tmp_sum))
2281 +                       file_checksum(thisname, &st, tmp_sum);
2282 +               if (sender_keeps_checksum)
2283 +                       memcpy(F_SUM(file), tmp_sum, flist_csum_len);
2284 +       }
2285  
2286         if (unsort_ndx)
2287                 F_NDX(file) = stats.num_dirs;
2288 @@ -2098,6 +2100,9 @@ void send_extra_file_list(int f, int at_least)
2289    finish:
2290         if (io_error != save_io_error && protocol_version == 30 && !ignore_errors)
2291                 send_msg_int(MSG_IO_ERROR, io_error);
2292 +
2293 +       if (use_db && flist_eof)
2294 +               db_disconnect(True);
2295  }
2296  
2297  struct file_list *send_file_list(int f, int argc, char *argv[])
2298 @@ -2121,6 +2126,13 @@ struct file_list *send_file_list(int f, int argc, char *argv[])
2299                      | (eol_nulls || reading_remotely ? RL_EOL_NULLS : 0);
2300         int implied_dot_dir = 0;
2301  
2302 +       if (use_db) {
2303 +               if (always_checksum)
2304 +                       db_connect(0); /* Will reset use_db on error. */
2305 +               else
2306 +                       use_db = 0;
2307 +       }
2308 +
2309         rprintf(FLOG, "building file list\n");
2310         if (show_filelist_progress)
2311                 start_filelist_progress("building file list");
2312 @@ -2464,6 +2476,9 @@ struct file_list *send_file_list(int f, int argc, char *argv[])
2313                         rprintf(FINFO, "[%s] flist_eof=1\n", who_am_i());
2314         }
2315  
2316 +       if (use_db && (!inc_recurse || flist_eof))
2317 +               db_disconnect(True);
2318 +
2319         return flist;
2320  }
2321  
2322 diff --git a/generator.c b/generator.c
2323 --- a/generator.c
2324 +++ b/generator.c
2325 @@ -61,6 +61,7 @@ extern int ignore_non_existing;
2326  extern int want_xattr_optim;
2327  extern int modify_window;
2328  extern int inplace;
2329 +extern int use_db;
2330  extern int append_mode;
2331  extern int make_backups;
2332  extern int csum_length;
2333 @@ -589,7 +590,8 @@ int unchanged_file(char *fn, struct file_struct *file, STRUCT_STAT *st)
2334            of the file time to determine whether to sync */
2335         if (always_checksum > 0 && S_ISREG(st->st_mode)) {
2336                 char sum[MAX_DIGEST_LEN];
2337 -               file_checksum(fn, st, sum);
2338 +               if (!use_db || !db_get_checksum(st, sum))
2339 +                       file_checksum(fn, st, sum);
2340                 return memcmp(sum, F_SUM(file), flist_csum_len) == 0;
2341         }
2342  
2343 @@ -2239,6 +2241,13 @@ void generate_files(int f_out, const char *local_name)
2344                         : "enabled");
2345         }
2346  
2347 +       if (use_db) {
2348 +               if (always_checksum || (append_mode != 1 && protocol_version >= 30))
2349 +                       db_connect(0); /* Will reset use_db on error. */
2350 +               else
2351 +                       use_db = 0;
2352 +       }
2353 +
2354         dflt_perms = (ACCESSPERMS & ~orig_umask);
2355  
2356         do {
2357 @@ -2364,6 +2373,9 @@ void generate_files(int f_out, const char *local_name)
2358                         wait_for_receiver();
2359         }
2360  
2361 +       if (use_db)
2362 +               db_disconnect(True);
2363 +
2364         info_levels[INFO_FLIST] = save_info_flist;
2365         info_levels[INFO_PROGRESS] = save_info_progress;
2366  
2367 diff --git a/io.c b/io.c
2368 --- a/io.c
2369 +++ b/io.c
2370 @@ -41,8 +41,10 @@ extern int am_server;
2371  extern int am_sender;
2372  extern int am_receiver;
2373  extern int am_generator;
2374 +extern int local_server;
2375  extern int msgs2stderr;
2376  extern int inc_recurse;
2377 +extern int same_db;
2378  extern int io_error;
2379  extern int batch_fd;
2380  extern int eol_nulls;
2381 @@ -1487,6 +1489,32 @@ static void read_a_msg(void)
2382                 if (am_sender)
2383                         maybe_send_keepalive(time(NULL), MSK_ALLOW_FLUSH);
2384                 break;
2385 +       case MSG_CHECKSUM:
2386 +               /* This receives some checksum info that we want to make a note of
2387 +                * (which allows a single process to do all the writing to the db). */
2388 +               if (msg_bytes != MSG_CHECKSUM_LEN)
2389 +                       goto overflow;
2390 +               raw_read_buf(data, MSG_CHECKSUM_LEN);
2391 +               if (am_generator && same_db) {
2392 +                       iobuf.in_multiplexed = 1;
2393 +                       send_msg(MSG_CHECKSUM, data, MSG_CHECKSUM_LEN, 0);
2394 +               } if (am_receiver || (am_sender && !local_server))
2395 +                       goto unexpected;
2396 +               else {
2397 +                       /* The received data is a set of numbers followed by the checksum. */
2398 +                       STRUCT_STAT st;
2399 +                       st.st_dev = IVAL64(data, 0);
2400 +                       st.st_ino = IVAL64(data, 8);
2401 +                       st.st_size = IVAL64(data, 16);
2402 +                       st.st_mtime = IVAL64(data, 24);
2403 +                       st.st_ctime = IVAL64(data, 32);
2404 +#if MSG_CHECKSUM_LONGS != 5
2405 +#error Fix the parsing of checksum long values
2406 +#endif
2407 +                       iobuf.in_multiplexed = 1;
2408 +                       db_set_checksum(IVAL(data, MSG_CHECKSUM_LONGS*8), &st, data + MSG_CHECKSUM_LONGS*8 + 4);
2409 +               }
2410 +               break;
2411         case MSG_DELETED:
2412                 if (msg_bytes >= sizeof data)
2413                         goto overflow;
2414 @@ -1638,6 +1666,7 @@ static void read_a_msg(void)
2415                  * with a duplicate exit message. */
2416                 _exit_cleanup(val, __FILE__, 0 - __LINE__);
2417         default:
2418 +       unexpected:
2419                 rprintf(FERROR, "unexpected tag %d [%s%s]\n",
2420                         tag, who_am_i(), inc_recurse ? "/inc" : "");
2421                 exit_cleanup(RERR_STREAMIO);
2422 diff --git a/main.c b/main.c
2423 --- a/main.c
2424 +++ b/main.c
2425 @@ -39,6 +39,7 @@ extern int am_root;
2426  extern int am_server;
2427  extern int am_sender;
2428  extern int am_daemon;
2429 +extern int am_dbadmin;
2430  extern int inc_recurse;
2431  extern int blocking_io;
2432  extern int always_checksum;
2433 @@ -57,6 +58,7 @@ extern int copy_unsafe_links;
2434  extern int keep_dirlinks;
2435  extern int preserve_hard_links;
2436  extern int protocol_version;
2437 +extern int always_checksum;
2438  extern int file_total;
2439  extern int recurse;
2440  extern int xfer_dirs;
2441 @@ -92,6 +94,7 @@ extern char *logfile_format;
2442  extern char *filesfrom_host;
2443  extern char *partial_dir;
2444  extern char *rsync_path;
2445 +extern char *db_config;
2446  extern char *shell_cmd;
2447  extern char *password_file;
2448  extern char *backup_dir;
2449 @@ -1201,6 +1204,9 @@ void start_server(int f_in, int f_out, int argc, char *argv[])
2450         if (am_daemon && io_timeout && protocol_version >= 31)
2451                 send_msg_int(MSG_IO_TIMEOUT, io_timeout);
2452  
2453 +       if (db_config)
2454 +               db_read_config(FERROR, db_config);
2455 +
2456         if (am_sender) {
2457                 keep_dirlinks = 0; /* Must be disabled on the sender. */
2458                 if (need_messages_from_generator)
2459 @@ -1484,6 +1490,9 @@ static int start_client(int argc, char *argv[])
2460         else
2461                 env_port = rsync_port;
2462  
2463 +       if (db_config)
2464 +               db_read_config(FERROR, db_config);
2465 +
2466         if (daemon_over_rsh < 0)
2467                 return start_socket_client(shell_machine, remote_argc, remote_argv, argc, argv);
2468  
2469 diff --git a/options.c b/options.c
2470 --- a/options.c
2471 +++ b/options.c
2472 @@ -86,6 +86,7 @@ int am_root = 0; /* 0 = normal, 1 = root, 2 = --super, -1 = --fake-super */
2473  int am_server = 0;
2474  int am_sender = 0;
2475  int am_starting_up = 1;
2476 +int am_dbadmin = 0;
2477  int relative_paths = -1;
2478  int implied_dirs = 1;
2479  int missing_args = 0; /* 0 = FERROR_XFER, 1 = ignore, 2 = delete */
2480 @@ -99,6 +100,7 @@ int use_qsort = 0;
2481  char *files_from = NULL;
2482  int filesfrom_fd = -1;
2483  char *filesfrom_host = NULL;
2484 +char *db_config = NULL;
2485  int eol_nulls = 0;
2486  int protect_args = -1;
2487  int human_readable = 1;
2488 @@ -106,6 +108,9 @@ int recurse = 0;
2489  int allow_inc_recurse = 1;
2490  int xfer_dirs = -1;
2491  int am_daemon = 0;
2492 +int db_clean, db_check, db_do_md4, db_do_md5, db_update = 1, db_lax, db_init, db_mounts;
2493 +int db_output_name, db_output_sum, db_output_info, db_output_unchanged, db_output_dirs, db_output_msgs;
2494 +int saw_db_output_opt, saw_db_sum_opt;
2495  int connect_timeout = 0;
2496  int keep_partial = 0;
2497  int safe_symlinks = 0;
2498 @@ -288,6 +293,7 @@ static struct output_struct debug_words[COUNT_DEBUG+1] = {
2499         DEBUG_WORD(CHDIR, W_CLI|W_SRV, "Debug when the current directory changes"),
2500         DEBUG_WORD(CONNECT, W_CLI, "Debug connection events (levels 1-2)"),
2501         DEBUG_WORD(CMD, W_CLI, "Debug commands+options that are issued (levels 1-2)"),
2502 +       DEBUG_WORD(DB, W_SND|W_REC, "Debug DB operations (levels 1-5)"),
2503         DEBUG_WORD(DEL, W_REC, "Debug delete actions (levels 1-3)"),
2504         DEBUG_WORD(DELTASUM, W_SND|W_REC, "Debug delta-transfer checksumming (levels 1-4)"),
2505         DEBUG_WORD(DUP, W_REC, "Debug weeding of duplicate names"),
2506 @@ -670,6 +676,16 @@ static void print_info_flags(enum logcode f)
2507  #endif
2508                         "stop-at",
2509  
2510 +#if !defined HAVE_MYSQL_MYSQL_H || !defined HAVE_LIBMYSQLCLIENT
2511 +               "no "
2512 +#endif
2513 +                       "MySQL",
2514 +
2515 +#if !defined HAVE_SQLITE3_H || !defined HAVE_LIBSQLITE3
2516 +               "no "
2517 +#endif
2518 +                       "SQLite",
2519 +
2520         "*Optimizations",
2521  
2522  #ifndef HAVE_SIMD
2523 @@ -783,6 +799,7 @@ enum {OPT_SERVER = 1000, OPT_DAEMON, OPT_SENDER, OPT_EXCLUDE, OPT_EXCLUDE_FROM,
2524        OPT_INCLUDE, OPT_INCLUDE_FROM, OPT_MODIFY_WINDOW, OPT_MIN_SIZE, OPT_CHMOD,
2525        OPT_READ_BATCH, OPT_WRITE_BATCH, OPT_ONLY_WRITE_BATCH, OPT_MAX_SIZE,
2526        OPT_NO_D, OPT_APPEND, OPT_NO_ICONV, OPT_INFO, OPT_DEBUG, OPT_BLOCK_SIZE,
2527 +      OPT_NO_DB, OPT_DBONLY,
2528        OPT_USERMAP, OPT_GROUPMAP, OPT_CHOWN, OPT_BWLIMIT,
2529        OPT_OLD_COMPRESS, OPT_NEW_COMPRESS, OPT_NO_COMPRESS,
2530        OPT_STOP_AFTER, OPT_STOP_AT,
2531 @@ -935,6 +952,10 @@ static struct poptOption long_options[] = {
2532    {"no-c",             0,  POPT_ARG_VAL,    &always_checksum, 0, 0, 0 },
2533    {"checksum-choice",  0,  POPT_ARG_STRING, &checksum_choice, 0, 0, 0 },
2534    {"cc",               0,  POPT_ARG_STRING, &checksum_choice, 0, 0, 0 },
2535 +  {"db",               0,  POPT_ARG_STRING, &db_config, 0, 0, 0 },
2536 +  {"no-db",            0,  POPT_ARG_NONE,   0, OPT_NO_DB, 0, 0 },
2537 +  {"db-lax",           0,  POPT_ARG_VAL,    &db_lax, 1, 0, 0 },
2538 +  {"no-db-lax",        0,  POPT_ARG_VAL,    &db_lax, 0, 0, 0 },
2539    {"block-size",      'B', POPT_ARG_STRING, 0, OPT_BLOCK_SIZE, 0, 0 },
2540    {"compare-dest",     0,  POPT_ARG_STRING, 0, OPT_COMPARE_DEST, 0, 0 },
2541    {"copy-dest",        0,  POPT_ARG_STRING, 0, OPT_COPY_DEST, 0, 0 },
2542 @@ -1029,6 +1050,9 @@ static struct poptOption long_options[] = {
2543    {"dparam",           0,  POPT_ARG_STRING, 0, OPT_DAEMON, 0, 0 },
2544    {"detach",           0,  POPT_ARG_NONE,   0, OPT_DAEMON, 0, 0 },
2545    {"no-detach",        0,  POPT_ARG_NONE,   0, OPT_DAEMON, 0, 0 },
2546 +  /* All the following options switch us into DB-admin option-parsing. */
2547 +  {"db-help",          0,  POPT_ARG_NONE,   0, OPT_DBONLY, 0, 0 },
2548 +  {"db-only",          0,  POPT_ARG_STRING, 0, OPT_DBONLY, 0, 0 },
2549    {0,0,0,0, 0, 0, 0}
2550  };
2551  
2552 @@ -1069,6 +1093,39 @@ static struct poptOption long_daemon_options[] = {
2553    {0,0,0,0, 0, 0, 0}
2554  };
2555  
2556 +static void dbonly_usage(enum logcode F)
2557 +{
2558 +  rprintf(F,"Usage: rsyncdb --db=CONFIG_FILE [OPTIONS] [DIRS]\n");
2559 +  rprintf(F,"\n");
2560 +  rprintf(F,"Options:\n");
2561 +#include "help-rsyncdb.h"
2562 +}
2563 +
2564 +static struct poptOption long_dbonly_options[] = {
2565 +  /* longName, shortName, argInfo, argPtr, value, descrip, argDesc */
2566 +  {"check",           'c', POPT_ARG_NONE,   &db_check, 0, 0, 0},
2567 +  {"clean",            0,  POPT_ARG_NONE,   &db_clean, 0, 0, 0},
2568 +  {"db",               0,  POPT_ARG_STRING, &db_config, 0, 0, 0 },
2569 +  {"db-only",          0,  POPT_ARG_STRING, &db_config, 0, 0, 0 },
2570 +  {"db-lax",           0,  POPT_ARG_VAL,    &db_lax, 1, 0, 0 },
2571 +  {"no-db-lax",        0,  POPT_ARG_VAL,    &db_lax, 0, 0, 0 },
2572 +  {"info",             0,  POPT_ARG_STRING, 0, OPT_INFO, 0, 0 },
2573 +  {"debug",            0,  POPT_ARG_STRING, 0, OPT_DEBUG, 0, 0 },
2574 +  {"update",          'u', POPT_ARG_VAL,    &db_update, 1, 0, 0 },
2575 +  {"no-update",       'N', POPT_ARG_VAL,    &db_update, 0, 0, 0 },
2576 +  {"no-u",             0,  POPT_ARG_VAL,    &db_update, 0, 0, 0 },
2577 +  {"output",          'o', POPT_ARG_STRING, 0, 'o', 0, 0 },
2578 +  {"recursive",       'r', POPT_ARG_VAL,    &recurse, 1, 0, 0 },
2579 +  {"no-recursive",     0,  POPT_ARG_VAL,    &recurse, 0, 0, 0 },
2580 +  {"no-r",             0,  POPT_ARG_VAL,    &recurse, 0, 0, 0 },
2581 +  {"sums",            's', POPT_ARG_STRING, 0, 's', 0, 0 },
2582 +  {"init",             0,  POPT_ARG_NONE,   &db_init, 0, 0, 0 },
2583 +  {"mounts",           0,  POPT_ARG_NONE,   &db_mounts, 0, 0, 0 },
2584 +  {"quiet",           'q', POPT_ARG_NONE,   &quiet, 0, 0, 0 },
2585 +  {"help",            'h', POPT_ARG_NONE,   0, 'h', 0, 0 },
2586 +  {"db-help",          0,  POPT_ARG_NONE,   0, 'h', 0, 0 },
2587 +  {0,0,0,0, 0, 0, 0}
2588 +};
2589  
2590  static char err_buf[200];
2591  
2592 @@ -1194,6 +1251,8 @@ static void set_refuse_options(void)
2593                         parse_one_refuse_match(0, "iconv", list_end);
2594  #endif
2595                 parse_one_refuse_match(0, "log-file*", list_end);
2596 +               parse_one_refuse_match(0, "db", list_end);
2597 +               parse_one_refuse_match(0, "db-lax", list_end);
2598         }
2599  
2600  #ifndef SUPPORT_ATIMES
2601 @@ -1498,6 +1557,102 @@ static void create_refuse_error(int which)
2602                 snprintf(err_buf + n, sizeof err_buf - n, " (-%c)\n", op->shortName);
2603  }
2604  
2605 +static NORETURN void parse_dbonly_args(int argc, const char **argv)
2606 +{
2607 +       poptContext pc = poptGetContext(RSYNC_NAME, argc, argv, long_dbonly_options, 0);
2608 +       const char *arg;
2609 +       int opt;
2610 +
2611 +       recurse = 1;
2612 +       am_dbadmin = 1;
2613 +
2614 +       while ((opt = poptGetNextOpt(pc)) != -1) {
2615 +               const char *cp;
2616 +               switch (opt) {
2617 +               case 'o':
2618 +                       for (cp = poptGetOptArg(pc); *cp; cp++) {
2619 +                               switch (toLower(cp)) {
2620 +                               case 'n':
2621 +                                       db_output_name = 1;
2622 +                                       break;
2623 +                               case 's':
2624 +                               case 'c':
2625 +                                       db_output_sum = db_output_name = 1;
2626 +                                       break;
2627 +                               case 'i':
2628 +                                       db_output_info = db_output_name = 1;
2629 +                                       break;
2630 +                               case 'u':
2631 +                                       db_output_unchanged = db_output_name = 1;
2632 +                                       break;
2633 +                               case 'd':
2634 +                                       db_output_dirs = 1;
2635 +                                       break;
2636 +                               }
2637 +                       }
2638 +                       saw_db_output_opt = 1;
2639 +                       break;
2640 +
2641 +               case 's':
2642 +                       for (cp = poptGetOptArg(pc); *cp; cp++) {
2643 +                               switch (*cp) {
2644 +                               case '4':
2645 +                                       db_do_md4 = 1;
2646 +                                       break;
2647 +                               case '5':
2648 +                                       db_do_md5 = 1;
2649 +                                       break;
2650 +                               }
2651 +                       }
2652 +                       saw_db_sum_opt = 1;
2653 +                       break;
2654 +
2655 +               case 'h':
2656 +                       dbonly_usage(FINFO);
2657 +                       exit_cleanup(0);
2658 +
2659 +               case OPT_INFO:
2660 +                       arg = poptGetOptArg(pc);
2661 +                       parse_output_words(info_words, info_levels, arg, USER_PRIORITY);
2662 +                       break;
2663 +
2664 +               case OPT_DEBUG:
2665 +                       arg = poptGetOptArg(pc);
2666 +                       parse_output_words(debug_words, debug_levels, arg, USER_PRIORITY);
2667 +                       break;
2668 +
2669 +               default:
2670 +                       rprintf(FERROR,
2671 +                               "rsyncdb: %s: %s\n",
2672 +                               poptBadOption(pc, POPT_BADOPTION_NOALIAS),
2673 +                               poptStrerror(opt));
2674 +                       goto dbonly_usage;
2675 +               }
2676 +       }
2677 +
2678 +       if (!db_config) {
2679 +               rprintf(FERROR, "You must specify the --db=FILE option.\n");
2680 +         dbonly_usage:
2681 +               rprintf(FERROR,
2682 +                       "(Type \"rsyncdb --help\" for assistance.)\n");
2683 +               exit_cleanup(RERR_SYNTAX);
2684 +       }
2685 +
2686 +       if (!saw_db_output_opt && !quiet) {
2687 +               db_output_dirs = db_output_name = 1;
2688 +               if (db_check)
2689 +                       db_output_info = 1;
2690 +       }
2691 +       if (!quiet)
2692 +               db_output_msgs = 1;
2693 +       if (!saw_db_sum_opt)
2694 +               db_do_md5 = 1;
2695 +
2696 +       am_starting_up = 0;
2697 +       run_dbonly(poptGetArgs(pc));
2698 +       exit(42); /* NOT REACHED */
2699 +}
2700 +
2701  /* This is used to make sure that --daemon & --server cannot be aliased to
2702   * something else. These options have always disabled popt aliases for the
2703   * parsing of a daemon or server command-line, but we have to make sure that
2704 @@ -1554,6 +1709,12 @@ int parse_arguments(int *argc_p, const char ***argv_p)
2705                 return 0;
2706         }
2707  
2708 +       arg = *argv + strlen(*argv);
2709 +       if (arg - *argv > 2 && strcmp(arg-2, "db") == 0) {
2710 +               parse_dbonly_args(argc, argv);
2711 +               /* NOT REACHED */
2712 +       }
2713 +
2714         set_refuse_options();
2715  
2716  #ifdef ICONV_OPTION
2717 @@ -1672,6 +1833,12 @@ int parse_arguments(int *argc_p, const char ***argv_p)
2718                         am_daemon = 1;
2719                         return 1;
2720  
2721 +               case OPT_DBONLY:
2722 +                       protect_args = 0;
2723 +                       poptFreeContext(pc);
2724 +                       parse_dbonly_args(argc, argv);
2725 +                       break; /* NOT REACHED */
2726 +
2727                 case OPT_MODIFY_WINDOW:
2728                         /* The value has already been set by popt, but
2729                          * we need to remember that we're using a
2730 @@ -1744,6 +1911,10 @@ int parse_arguments(int *argc_p, const char ***argv_p)
2731                         preserve_devices = preserve_specials = 0;
2732                         break;
2733  
2734 +               case OPT_NO_DB:
2735 +                       db_config = NULL;
2736 +                       break;
2737 +
2738                 case 'h':
2739                         human_readable++;
2740                         break;
2741 diff --git a/pipe.c b/pipe.c
2742 --- a/pipe.c
2743 +++ b/pipe.c
2744 @@ -27,11 +27,16 @@ extern int am_server;
2745  extern int blocking_io;
2746  extern int filesfrom_fd;
2747  extern int munge_symlinks;
2748 +extern int always_checksum;
2749 +extern int use_db;
2750 +extern char *db_config;
2751  extern char *logfile_name;
2752  extern int remote_option_cnt;
2753  extern const char **remote_options;
2754  extern struct chmod_mode_struct *chmod_modes;
2755  
2756 +int same_db = 0;
2757 +
2758  /**
2759   * Create a child connected to us via its stdin/stdout.
2760   *
2761 @@ -141,13 +146,22 @@ pid_t local_child(int argc, char **argv, int *f_in, int *f_out,
2762                 }
2763  
2764                 if (remote_option_cnt) {
2765 +                       const char *db_config_save = db_config;
2766                         int rc = remote_option_cnt + 1;
2767                         const char **rv = remote_options;
2768                         if (!parse_arguments(&rc, &rv)) {
2769                                 option_error();
2770                                 exit_cleanup(RERR_SYNTAX);
2771                         }
2772 -               }
2773 +                       if (db_config == db_config_save)
2774 +                               same_db = db_config != NULL;
2775 +                       else if (!db_config || !db_config_save || strcmp(db_config, db_config_save) != 0) {
2776 +                               use_db = 0;
2777 +                               if (db_config)
2778 +                                       db_read_config(FERROR, db_config);
2779 +                       }
2780 +               } else if (use_db)
2781 +                       same_db = 1;
2782  
2783                 if (dup2(to_child_pipe[0], STDIN_FILENO) < 0
2784                  || close(to_child_pipe[1]) < 0
2785 diff --git a/receiver.c b/receiver.c
2786 --- a/receiver.c
2787 +++ b/receiver.c
2788 @@ -24,6 +24,8 @@
2789  
2790  extern int dry_run;
2791  extern int do_xfers;
2792 +extern int use_db;
2793 +extern int db_lax;
2794  extern int am_root;
2795  extern int am_server;
2796  extern int inc_recurse;
2797 @@ -433,6 +435,11 @@ static void handle_delayed_updates(char *local_name)
2798                                         "rename failed for %s (from %s)",
2799                                         full_fname(fname), partialptr);
2800                         } else {
2801 +                               if (use_db && !db_lax) {
2802 +                                       STRUCT_STAT st;
2803 +                                       if (do_lstat(fname, &st) == 0)
2804 +                                               db_update_ctime(5, &st);
2805 +                               }
2806                                 if (remove_source_files
2807                                  || (preserve_hard_links && F_IS_HLINKED(file)))
2808                                         send_msg_int(MSG_SUCCESS, ndx);
2809 @@ -539,6 +546,9 @@ int recv_files(int f_in, int f_out, char *local_name)
2810         if (delay_updates)
2811                 delayed_bits = bitbag_create(cur_flist->used + 1);
2812  
2813 +       if (use_db && (append_mode == 1 || protocol_version < 30))
2814 +               use_db = 0; /* We can't note finished md5 values */
2815 +
2816         progress_init();
2817  
2818         while (1) {
2819 @@ -878,6 +888,8 @@ int recv_files(int f_in, int f_out, char *local_name)
2820                                         do_unlink(partialptr);
2821                                 handle_partial_dir(partialptr, PDIR_DELETE);
2822                         }
2823 +                       if (use_db && do_lstat(fname, &st) == 0)
2824 +                               db_set_checksum(5, &st, sender_file_sum);
2825                 } else if (keep_partial && partialptr && !one_inplace) {
2826                         if (!handle_partial_dir(partialptr, PDIR_CREATE)) {
2827                                 rprintf(FERROR,
2828 @@ -891,6 +903,8 @@ int recv_files(int f_in, int f_out, char *local_name)
2829                                 recv_ok = -1;
2830                         else if (delay_updates && recv_ok) {
2831                                 bitbag_set_bit(delayed_bits, ndx);
2832 +                               if (use_db && do_lstat(partialptr, &st) == 0)
2833 +                                       db_set_checksum(5, &st, sender_file_sum);
2834                                 recv_ok = 2;
2835                         } else
2836                                 partialptr = NULL;
2837 diff --git a/rsync.1.md b/rsync.1.md
2838 --- a/rsync.1.md
2839 +++ b/rsync.1.md
2840 @@ -382,6 +382,9 @@ detailed description below for a complete description.
2841  --dry-run, -n            perform a trial run with no changes made
2842  --whole-file, -W         copy files whole (w/o delta-xfer algorithm)
2843  --checksum-choice=STR    choose the checksum algorithm (aka --cc)
2844 +--db=CONFIG_FILE         specify a CONFIG_FILE for DB checksums
2845 +--db-only=CONFIG_FILE    behave like rsyncdb
2846 +--db-lax                 ignore ctime changes (use with CAUTION)
2847  --one-file-system, -x    don't cross filesystem boundaries
2848  --block-size=SIZE, -B    force a fixed checksum block-size
2849  --rsh=COMMAND, -e        specify the remote shell to use
2850 diff --git a/rsync.c b/rsync.c
2851 --- a/rsync.c
2852 +++ b/rsync.c
2853 @@ -39,6 +39,7 @@ extern int am_daemon;
2854  extern int am_sender;
2855  extern int am_receiver;
2856  extern int am_generator;
2857 +extern int am_dbadmin;
2858  extern int am_starting_up;
2859  extern int allow_8bit_chars;
2860  extern int protocol_version;
2861 @@ -794,6 +795,8 @@ struct file_list *flist_for_ndx(int ndx, const char *fatal_error_loc)
2862  
2863  const char *who_am_i(void)
2864  {
2865 +       if (am_dbadmin)
2866 +               return "rsyncdb";
2867         if (am_starting_up)
2868                 return am_server ? "server" : "client";
2869         return am_sender ? "sender"
2870 diff --git a/rsync.h b/rsync.h
2871 --- a/rsync.h
2872 +++ b/rsync.h
2873 @@ -259,12 +259,16 @@ enum msgcode {
2874         MSG_IO_ERROR=22,/* the sending side had an I/O error */
2875         MSG_IO_TIMEOUT=33,/* tell client about a daemon's timeout value */
2876         MSG_NOOP=42,    /* a do-nothing message (legacy protocol-30 only) */
2877 +       MSG_CHECKSUM=55,/* sent via rcvr -> gen pipe and local-host-only gen -> sender */
2878         MSG_ERROR_EXIT=86, /* synchronize an error exit (siblings and protocol >= 31) */
2879         MSG_SUCCESS=100,/* successfully updated indicated flist index */
2880         MSG_DELETED=101,/* successfully deleted a file on receiving side */
2881         MSG_NO_SEND=102,/* sender failed to open a file we wanted */
2882  };
2883  
2884 +#define MSG_CHECKSUM_LONGS 5
2885 +#define MSG_CHECKSUM_LEN (MSG_CHECKSUM_LONGS*8 + 4 + MAX_DIGEST_LEN)
2886 +
2887  #define NDX_DONE -1
2888  #define NDX_FLIST_EOF -2
2889  #define NDX_DEL_STATS -3
2890 @@ -1399,7 +1403,8 @@ extern short info_levels[], debug_levels[];
2891  #define DEBUG_CHDIR (DEBUG_BIND+1)
2892  #define DEBUG_CONNECT (DEBUG_CHDIR+1)
2893  #define DEBUG_CMD (DEBUG_CONNECT+1)
2894 -#define DEBUG_DEL (DEBUG_CMD+1)
2895 +#define DEBUG_DB (DEBUG_CMD+1)
2896 +#define DEBUG_DEL (DEBUG_DB+1)
2897  #define DEBUG_DELTASUM (DEBUG_DEL+1)
2898  #define DEBUG_DUP (DEBUG_DELTASUM+1)
2899  #define DEBUG_EXIT (DEBUG_DUP+1)
2900 diff --git a/rsyncdb-mountinfo b/rsyncdb-mountinfo
2901 new file mode 100755
2902 --- /dev/null
2903 +++ b/rsyncdb-mountinfo
2904 @@ -0,0 +1,82 @@
2905 +#!/usr/bin/perl
2906 +
2907 +# This script outputs data for rsyncdb --mounts.  It must output a complete
2908 +# list of the mounts for the current host in a strict format -- 2 fields
2909 +# with a Tab between:  $MOUNT_UNIQ\t$PATH
2910 +#
2911 +# The list of mounts MUST NOT contain any entry that has the same devnum
2912 +# (st_dev) as any other entry in the list (as checked via its PATH).
2913 +#
2914 +# MOUNT_UNIQ is a unique string that identifies the mount on this host.
2915 +# This cannot be the devnum (st_dev) because that can vary depending on the
2916 +# mount order or be reused for different mounts if they are not mounted at
2917 +# the same time.  Ideally this would be its UUID value, if that is available
2918 +# on this OS.  This script looks in /dev/disk/by-uuid for the current UUID
2919 +# mappings).  If the UUID is not found, the fallback default is the string
2920 +# "Mount of $devname", which should be adequate for situations that don't
2921 +# use removable media (though you may need to take steps to weed-out removable
2922 +# mounts).
2923 +#
2924 +# You can override the MOUNT_UNIQ value by putting a .rsyncdb_mount_uniq
2925 +# file in the root directory of any mount, at which point it is up to you
2926 +# to make sure that the value stays unique (note that all sequences of
2927 +# whitespace are transformed into a single space, and leading/trailing
2928 +# whitespace is removed).
2929 +#
2930 +# MOUNT_UNIQ may never contain a Tab but it would be legal for PATH to have
2931 +# a Tab (just really weird).  Neither may have a CR or LF in it.
2932 +#
2933 +# The maximum size for MOUNT_UNIQ is 256 characters.
2934 +#
2935 +# If this script doesn't meet your needs, feel free to edit/replace it and
2936 +# choose some other method of finding a unique value for each mount.  If you
2937 +# come up with a good idiom that might be useful to others, please share it
2938 +# with the rsync mailing list.
2939 +
2940 +use strict;
2941 +use warnings;
2942 +use Cwd 'abs_path';
2943 +
2944 +my @MOUNT_FILES = qw( /proc/mounts /etc/mtab );
2945 +my $VALID_DEVICE_REGEX = qr{^/dev|^rootfs$};
2946 +my $UUID_DIR = '/dev/disk/by-uuid';
2947 +my $OVERRIDE_FILE = '.rsyncdb_mount_uniq';
2948 +
2949 +my (%hash, %uuid);
2950 +
2951 +if (-d $UUID_DIR) {
2952 +    foreach my $uuid (glob "$UUID_DIR/*") {
2953 +       my $lnk = readlink($uuid);
2954 +       if ($lnk !~ m{^/}) {
2955 +           $lnk = abs_path("$UUID_DIR/$lnk");
2956 +       }
2957 +       $uuid =~ s{.*/}{};
2958 +       $uuid{$lnk} = $uuid;
2959 +    }
2960 +}
2961 +
2962 +foreach my $mount_file (@MOUNT_FILES) {
2963 +    if (open MOUNTS, $mount_file) {
2964 +       while (<MOUNTS>) {
2965 +           my ($devname, $path) = (split)[0,1];
2966 +           next unless $devname =~ /$VALID_DEVICE_REGEX/;
2967 +
2968 +           my ($devno) = (stat($path))[0];
2969 +           next unless defined $devno; # Skip if mount is invalid.
2970 +           next if $hash{$devno}++; # SKip if we've seen this devno earlier.
2971 +
2972 +           my $mount_uniq = $uuid{$devname} ? $uuid{$devname} : "Mount of $devname";
2973 +           if (open UNIQ, '<', "$path/$OVERRIDE_FILE") {
2974 +               $mount_uniq = <UNIQ>;
2975 +               close UNIQ;
2976 +               $mount_uniq =~ s/\s+/ /g; # This ensures no tab, CR, nor LF.
2977 +               $mount_uniq =~ s/^ | $//g; # .. and no leading or trailing whitespace.
2978 +           }
2979 +           print $mount_uniq, "\t", $path, "\n";
2980 +       }
2981 +       close MOUNTS;
2982 +       exit;
2983 +    }
2984 +}
2985 +
2986 +die "Failed to to open any mount files: @MOUNT_FILES\n";
2987 diff --git a/rsyncdb.1.md b/rsyncdb.1.md
2988 new file mode 100644
2989 --- /dev/null
2990 +++ b/rsyncdb.1.md
2991 @@ -0,0 +1,217 @@
2992 +# NAME
2993 +
2994 +rsyncdb - Maintain an rsync checksum DB
2995 +
2996 +# SYNOPSIS
2997 +
2998 +```
2999 +rsyncdb --db=CONFIG [OPTION...] [DIR...]
3000 +```
3001 +
3002 +# DESCRIPTION
3003 +
3004 +Rsyncdb can maintain a checksum-caching DB that rsync can use to make its
3005 +`--checksum` option more optimal.  You must specify a config file via
3006 +the `--db=CONFIG_FILE` option in order for rsyncdb to know what DB to
3007 +manipulate.  See the rsync manpage's `--db` option for full details on
3008 +the file's format.
3009 +
3010 +You can specify one or more directory args for rsyncdb to scan.  If no
3011 +DIR args are specified, the current directory is assumed to be the spot
3012 +to start scanning.
3013 +
3014 +Note that the rsyncdb program is usually just a symlink to the rsync program.
3015 +You can force rsync to behave as rsyncdb either by having a symlink (or
3016 +hardlink) name that ends with "db" or by `starting` the rsync args with
3017 +`--db-only=CONFIG` (and that option works just like `--db=CONFIG` to
3018 +a program named rsyncdb).
3019 +
3020 +# EXAMPLES
3021 +
3022 +The following command will update checksum information in the database
3023 +described in the /etc/db.conf file:
3024 +
3025 +>     rsyncdb --db=/etc/db.conf -o n --clean /dir1 /dir2
3026 +
3027 +It scans 2 directory hierarchies (/dir1 & /dir2) and cleans out any
3028 +checksums whose inodes are no longer found in those directories (so that
3029 +directory args are presumed to be complete for this host's DB contents).
3030 +
3031 +The following command will scan all the files in the /dir2 directory (without
3032 +recursive scanning, due to the `--no-r` option) and check them against
3033 +the DB:
3034 +
3035 +>     rsyncdb --db=/etc/db.conf --check --no-r /dir2
3036 +
3037 +Any errors found are output as well as being fixed in the DB.  (See
3038 +`--no-update` for how to check without updating.)
3039 +
3040 +The following command will output MD5 sums for all the files found in the
3041 +directories mentioned, even if they are unchanged (due to the
3042 +`--output=us` option):
3043 +
3044 +>     rsyncdb --db=/etc/db.conf -rous /dir* >/tmp/md5sums.txt
3045 +
3046 +This is just like running md5sum, only faster.  Unlike md5sum, you can't
3047 +specify a single file, so use `--no-r` and grep the output if you just
3048 +want to see a single file's value.
3049 +
3050 +The following command initializes a new DB, and is required for any new DB:
3051 +
3052 +>     rsyncdb --db=/etc/db.conf --init --mounts
3053 +
3054 +The `--init` option should only be used once (unless you want to
3055 +destroy existing data).  The `--mounts` option may need to be used
3056 +periodically, and makes use of a helper script (see below).
3057 +
3058 +# OPTIONS SUMMARY
3059 +
3060 +Rsyncdb accepts the following options:
3061 +
3062 +[comment]: # (help-rsyncdb.h)
3063 +
3064 +```
3065 +--db=CONFIG       Specify the CONFIG file to read for the DB info
3066 +--db-lax          Ignore ctime changes (use with CAUTION)
3067 +--recursive, -r   Scan files in subdirs (the default w/o --no-recursive)
3068 +--sums=SUMS, -s   List which checksums to update (default: 4,5)
3069 +--output=STR, -o  One or more letters of what to output (default: "")
3070 +--check, -c       Check checksums (by reading the files) and fix any
3071 +                  issues.  Makes --output default to "dni".
3072 +--clean           Note all inodes in the DIRS and remove DB extras
3073 +--no-update, -N   Avoids updating/adding info w/--check and/or --clean
3074 +--init            Initialize a DB by (re-)creating its tables
3075 +--mounts          Scan for mounted filesystems and update the DB
3076 +--quiet, -q       Disable the default non-error output
3077 +--help, -h        Display this help message
3078 +```
3079 +
3080 +# OPTIONS
3081 +
3082 +Rsyncdb accepts both long (double-dash + word) and short (single-dash + letter)
3083 +options.  The full list of the available options are described below.  If an
3084 +option can be specified in more than one way, the choices are comma-separated.
3085 +Some options only have a long variant, not a short.  If the option takes a
3086 +parameter, the parameter is only listed after the long variant, even though it
3087 +must also be specified for the short.  When specifying a parameter, you can
3088 +either use the form --option=param or replace the '=' with whitespace.  The
3089 +parameter may need to be quoted in some manner for it to survive the shell's
3090 +command-line parsing.
3091 +
3092 +0.  `--db=CONFIG_FILE`
3093 +
3094 +    This tells rsyncdb what DB-config file to read for the DB setup.  This is
3095 +    the same as the option in rsync, so refer to that manpage for full details.
3096 +
3097 +0.  `--db-lax`
3098 +
3099 +    This option works just like it does in rsync, so refer to that manpage for
3100 +    full details.
3101 +
3102 +0.  `--no-recursive, --no-r`
3103 +
3104 +    This disables the default recursive directory scan that is performed on the
3105 +    listed directory args.  The options `--recursive` and `-r` are also
3106 +    accepted, if someone wants to override an earlier `--no-r` override.
3107 +
3108 +0.  `--sums=SUMS, -s`
3109 +
3110 +    Only output/update the listed checksum types. By default we deal with just
3111 +    the newer md5 checksums (i.e.  `--sums=5`).
3112 +
3113 +    Note that this option does NOT affect the order that checksums are output
3114 +    if "-o s" is enabled, so `-s5,4` is the same as `-s4,5`.
3115 +
3116 +0.  `--output=STR, -o`
3117 +
3118 +    The output option lets you specify one or more letters indicating what
3119 +    information should be output.  If `--output` is not specified, the default
3120 +    is either "dn" or (with `--check`) "dni".
3121 +
3122 +    The following letters are accepted in the string:
3123 +
3124 +    - `d` outputs "... dir_name ..." lines for each directory in our scan.  if
3125 +      "d" is omitted, then this progress indictor is not output.
3126 +    - `n` includes the file's name in the per-file output. These lines are only
3127 +      output for changed files unless "u" is given.  The "n" option is implied
3128 +      by every other output option letter except "d".
3129 +    - `s` includes the checksum info in the per-file output.
3130 +    - `c` is a synonym for 's'.
3131 +    - `i` includes itemized change info in the per-file output.
3132 +      - `!i` indicates that the time and/or size is wrong.
3133 +      - `+4` indicates the MD4 sum is missing.
3134 +      - `+5` indicates the MD5 sum is missing.
3135 +      - `!4` indicates the MD4 sum is wrong.
3136 +      - `!5` indicates the MD5 sum is wrong.
3137 +      - `?4` indicates an unknown MD4 difference.  This can happen if we didn't
3138 +       need to read the file; i.e. if the time/size is wrong and no sum info
3139 +       was requested.
3140 +      - `?5` indicates an unknown MD5 difference.
3141 +    - `u` includes unchanged files in the per-file output lines.
3142 +
3143 +0.  `--check, -c`
3144 +
3145 +    Check the checksums (forcing the reading of all the files) and fix any
3146 +    issues that are found.  Makes `--output` default to "dni".
3147 +
3148 +0.  `--clean`
3149 +
3150 +    Makes a temp-DB of all the inodes that we find in all the listed
3151 +    directories and removes any extraneous checksums from the DB.  You will
3152 +    need to specify all the mounted directories that are present (and listed as
3153 +    mounted) in the DB on this host or else the checksums from the unvisited
3154 +    directories will be discarded from the DB.  If you want to just --clean
3155 +    without adding or updating the info of new or changed files, specify
3156 +    `--no-update` as well.
3157 +
3158 +0.  `--no-update, -N`
3159 +
3160 +    Avoids updating/adding info with `--check` and/or `--clean`.
3161 +
3162 +0.  `--quiet, -q`
3163 +
3164 +    Disable the default (non-error) output settings.  This turns off the
3165 +    messages that `--init`, `--mount`, and `--clean` output, and makes the
3166 +    default for `--output` be nothing (though an explicit `--output` option is
3167 +    not affected).
3168 +
3169 +0.  `--init`
3170 +
3171 +    Create the tables in the DB.  If it is used on an existing DB, all the
3172 +    existing tables are dropped and re-created.
3173 +
3174 +This option cannot be combined with the updating or reporting of checksum
3175 +information, but may be combined with `--mounts`.
3176 +
3177 +0.  `--mounts`
3178 +
3179 +    Populate the "disk" DB with the available device numbers and change any
3180 +    mounted/unmount information for devices.  This should be run every time a
3181 +    mount-change happens that may affect a directory hierarchy in the DB.
3182 +    Rsyncdb will not save any checksums for a device that is not listed in the
3183 +    "disk" table.
3184 +
3185 +    The helper script "rsyncdb-mountinfo" is used as the source of the mount
3186 +    information on the host, which it derives from various system files and
3187 +    UUID directories (if available).  That script supports the use of an
3188 +    override file named ".rsyncdb_mount_uniq" in the root of the mount as one
3189 +    way to manually assign unique values to a shared (mountable) device's
3190 +    various disks.
3191 +
3192 +    Some advanced users may want to maintain the disk table themselves in order
3193 +    to support mounting a drive in different (or multiple) locations, etc.
3194 +
3195 +    Specifying the `--mounts` option cannot be combined with updating or
3196 +    reporting of checksum information, but may be combined with `--init`.
3197 +
3198 +0.  `--help, -h`
3199 +
3200 +    Display a summary of the options.
3201 +
3202 +# SEE ALSO
3203 +
3204 +**rsync**(1)
3205 +
3206 +# AUTHOR
3207 +
3208 +Rsyncdb was written by Wayne Davison.