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.
5 Future improvements may include:
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.
12 - Caching of path info that allows for the finding of files to use for
13 moving/linking/copying/alternate-basis-use.
15 - Extend DB support beyond MySQL and SQLite (PostgreSQL?).
17 To use this patch, run these commands for a successful build:
19 patch -p1 <patches/db.diff
24 based-on: 5eda68f11bf6efe782cca60a2415191f4532c3b5
25 diff --git a/.gitignore b/.gitignore
28 @@ -30,6 +30,7 @@ aclocal.m4
36 diff --git a/Makefile.in b/Makefile.in
39 @@ -4,6 +4,7 @@ prefix=@prefix@
40 datarootdir=@datarootdir@
41 exec_prefix=@exec_prefix@
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
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
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)
84 +rsyncdb$(EXEEXT): rsync$(EXEEXT)
85 + ln -s rsync$(EXEEXT) rsyncdb$(EXEEXT)
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
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
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
102 daemon-parm.h: daemon-parm.txt daemon-parm.awk
103 $(AWK) -f $(srcdir)/daemon-parm.awk $(srcdir)/daemon-parm.txt
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
109 -man: rsync.1 rsync-ssl.1 rsyncd.conf.5
110 +man: rsync.1 rsync-ssl.1 rsyncd.conf.5 rsyncdb.1
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
118 +rsyncdb.1: rsyncdb.1.md md2man NEWS.md Makefile
119 + @$(srcdir)/maybe-make-man $(srcdir) rsyncdb.1.md
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
128 diff --git a/checksum.c 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;
136 extern const char *checksum_choice;
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);
142 MD5_Final((uchar *)sum, &m5);
144 + db_set_checksum(5, st_p, sum);
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);
151 mdfour_result(&m, (uchar *)sum);
153 + db_set_checksum(4, st_p, sum);
157 diff --git a/cleanup.c b/cleanup.c
160 @@ -28,6 +28,7 @@ extern int am_daemon;
161 extern int am_receiver;
162 extern int am_sender;
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)
173 + db_disconnect(False);
178 if (cleanup_child_pid != -1) {
180 int pid = wait_process(cleanup_child_pid, &status, WNOHANG);
181 diff --git a/clientserver.c b/clientserver.c
184 @@ -45,12 +45,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;
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 @@ -814,6 +817,11 @@ static int rsync_module(int f_in, int f_out, int i, const char *addr, const char
204 + if (*lp_db_config(i)) {
205 + db_read_config(FLOG, lp_db_config(i));
206 + db_lax = lp_db_lax(i);
210 if ((*lp_early_exec(module_id) || *lp_prexfer_exec(module_id)
211 || *lp_postxfer_exec(module_id) || *lp_name_converter(module_id))
212 @@ -1026,6 +1034,8 @@ static int rsync_module(int f_in, int f_out, int i, const char *addr, const char
214 am_server = 1; /* Don't let someone try to be tricky. */
218 if (lp_ignore_errors(module_id))
221 diff --git a/configure.ac 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"
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]))
241 +if test x"$enable_mysql" = x"no"; then
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)
255 + MYSQL_CFLAGS=`mysql_config --cflags`
256 + MYSQL_LIBS=`mysql_config --libs`
258 + CPPFLAGS="$CPPFLAGS $MYSQL_CFLAGS"
259 + LIBS="$MYSQL_LIBS $LIBS"
261 + AC_CHECK_LIB(mysqlclient, mysql_init)
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]))
271 +if test x"$enable_sqlite" = x"no"; then
274 + AC_CHECK_LIB(sqlite3, sqlite3_open)
275 + AC_CHECK_FUNCS(sqlite3_open_v2 sqlite3_prepare_v2)
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
288 +STRING db_config NULL
289 STRING dont_compress DEFAULT_DONT_COMPRESS
290 STRING early_exec NULL
292 @@ -51,6 +52,7 @@ INTEGER timeout 0
294 ENUM syslog_facility LOG_DAEMON
297 BOOL fake_super False
298 BOOL forward_lookup True
299 BOOL ignore_errors False
300 diff --git a/db.c b/db.c
306 + * Routines to access extended file info via DB.
308 + * Copyright (C) 2008-2013 Wayne Davison
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.
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.
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.
329 +#include "openssl/md4.h"
330 +#include "openssl/md5.h"
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;
343 +#define MOUNT_HELPER_SCRIPT "/usr/sbin/rsyncdb-mountinfo"
345 +#if defined HAVE_MYSQL_MYSQL_H && defined HAVE_LIBMYSQLCLIENT
347 +#include <mysql/mysql.h>
348 +#include <mysql/errmsg.h>
351 +#if defined HAVE_SQLITE3_H && defined HAVE_LIBSQLITE3
353 +#include <sqlite3.h>
354 +#ifndef HAVE_SQLITE3_OPEN_V2
355 +#define sqlite3_open_v2(dbname, dbhptr, flags, vfs) \
356 + sqlite3_open(dbname, dbhptr)
358 +#ifndef HAVE_SQLITE3_PREPARE_V2
359 +#define sqlite3_prepare_v2 sqlite3_prepare
361 +#define MAX_LOCK_FAILURES 10
362 +#define LOCK_FAIL_MSLEEP 100
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)
372 +#define DB_TYPE_NONE 0
373 +#define DB_TYPE_MYSQL 1
374 +#define DB_TYPE_SQLITE 2
376 +int use_db = DB_TYPE_NONE;
377 +int select_many_sums = 0;
380 +#define PREP_MOUNT 1
382 +static const char *dbhost = NULL, *dbuser = NULL, *dbpass = NULL, *dbname = NULL;
383 +static unsigned int dbport = 0;
384 +static int transaction_state = -1;
401 +#define UPD_MOUNT 5 /* SQLite only */
405 +#define INS_PRESENT 9
406 +#define MAX_PREP_CNT 10
408 +#define MAX_BIND_CNT 7
409 +#define MAX_RESULT_BINDS 32
416 + sqlite3_stmt *sqlite;
419 +} statements[MAX_PREP_CNT];
422 +static enum logcode log_code;
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;
433 +static char bind_thishost[128+1];
434 +static unsigned long bind_thishost_len;
435 +static char *mount_helper_script = NULL;
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;
444 +#define PTR_SIZE (sizeof (struct file_struct *))
446 +#if defined USE_MYSQL || defined USE_SQLITE
447 +static void update_mounts(void);
451 + struct name_list *next;
455 +int db_read_config(enum logcode code, const char *config_file)
457 + char buf[2048], *cp;
463 + bind_thishost_len = strlcpy(bind_thishost, "localhost", sizeof bind_thishost);
465 + if (!(fp = fopen(config_file, "r"))) {
466 + rsyserr(log_code, errno, "unable to open %s", config_file);
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)) {
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--;
483 + if (!(cp = strchr(buf, ':')))
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)
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) {
508 + if (strcasecmp(cp, "mysql") == 0) {
509 + use_db = DB_TYPE_MYSQL;
514 + if (strcasecmp(cp, "sqlite") == 0) {
515 + use_db = DB_TYPE_SQLITE;
520 + "Unsupported dbtype on line #%d in %s.\n",
521 + lineno, config_file);
522 + use_db = DB_TYPE_NONE;
526 + rprintf(log_code, "Invalid line #%d in %s\n",
527 + lineno, config_file);
528 + use_db = DB_TYPE_NONE;
534 + if (bind_thishost_len >= (int)sizeof bind_thishost)
535 + bind_thishost_len = sizeof bind_thishost - 1;
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;
543 + md_num = checksum_type == 5 ? 5 : 4;
546 + if (use_db != DB_TYPE_SQLITE)
547 + rprintf(log_code, "Ignoring errlog setting for non-SQLite DB.\n");
548 +#ifndef SQLITE_CONFIG_LOG
550 + rprintf(log_code, "Your sqlite doesn't support SQLITE_CONFIG_LOG.\n");
554 + if (!mount_helper_script)
555 + mount_helper_script = MOUNT_HELPER_SCRIPT;
560 +#if defined USE_SQLITE && defined SQLITE_CONFIG_LOG
561 +static void errorLogCallback(UNUSED(void *pArg), int iErrCode, const char *zMsg)
563 + fprintf(error_log_fp, "[%d] %s (%d)\n", (int)getpid(), zMsg, iErrCode);
567 +static int run_sql(const char *fmt, ...)
574 + qlen = vasprintf(&query, fmt, ap);
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);
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);
592 + case DB_TYPE_SQLITE: {
593 + int rc, lock_failures = 0;
595 + if ((rc = sqlite3_exec(dbh.sqlite, query, NULL, NULL, NULL)) == 0)
597 + if (rc != SQLITE_BUSY && rc != SQLITE_LOCKED)
599 + if (++lock_failures > MAX_LOCK_FAILURES)
601 + msleep(LOCK_FAIL_MSLEEP);
604 + rprintf(FERROR, "[%s] Failed to run sql: %s\n", who_am_i(), sqlite3_errmsg(dbh.sqlite));
605 + rprintf(FERROR, "%s\n", query);
619 +static int prepare_mysql(int ndx, MYSQL_BIND *binds, int bind_cnt, const char *fmt, ...)
623 + int qlen, param_cnt;
624 + MYSQL_STMT *stmt = mysql_stmt_init(dbh.mysql);
627 + out_of_memory("prepare_mysql");
630 + qlen = vasprintf(&query, fmt, ap);
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);
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);
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);
652 + mysql_stmt_bind_param(stmt, binds);
654 + statements[ndx].mysql = stmt;
662 +static int prepare_mysql_queries(int type)
664 + MYSQL_BIND binds[MAX_BIND_CNT];
669 + sql="SELECT disk_id"
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))
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"
689 + " WHERE disk_id = ? AND ino = ?";
690 + if (!prepare_mysql(SEL_SUM, binds, 2, sql))
693 + sql="SELECT checksum"
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;
702 + binds[4].buffer_type = MYSQL_TYPE_LONGLONG;
703 + binds[4].buffer = &bind_ctime;
705 + if (!prepare_mysql(SEL_SUM, binds, 4 + !db_lax, sql, md_num, db_lax ? "" : "AND ctime = ?"))
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))
734 + sql="UPDATE inode_map"
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))
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))
774 + sql="SELECT mount_uniq"
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))
783 + " WHERE host = ? AND last_seen < ? AND devno != 0";
784 + /* Reusing binds from SEL_MOUNT */
785 + if (!prepare_mysql(UN_MOUNT, binds, 2, sql))
795 +static int db_connect_mysql(void)
797 + const char *open_dbname = db_init ? "mysql" : dbname;
799 + if (!(dbh.mysql = mysql_init(NULL)))
800 + out_of_memory("db_read_config");
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);
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));
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);
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);
824 + if (db_output_msgs)
825 + rprintf(FCLIENT, "Creating empty tables ...\n");
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"
836 + exit_cleanup(RERR_IPC);
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"
849 + exit_cleanup(RERR_IPC);
856 + if (!prepare_mysql_queries(PREP_MOUNT))
857 + exit_cleanup(RERR_IPC);
862 + if (!prepare_mysql_queries(PREP_NORM))
870 +static int prepare_sqlite(int ndx, const char *fmt, ...)
874 + int rc, qlen, lock_failures = 0;
877 + qlen = vasprintf(&query, fmt, ap);
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);
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);
889 + if (rc != SQLITE_BUSY && rc != SQLITE_LOCKED)
891 + if (++lock_failures > MAX_LOCK_FAILURES)
893 + msleep(LOCK_FAIL_MSLEEP);
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);
908 +static int prepare_sqlite_queries(int type)
914 + sql="SELECT disk_id"
916 + " WHERE host = ? AND devno = ?";
917 + if (!prepare_sqlite(SEL_DEV, sql))
920 + if (select_many_sums) {
921 + sql="SELECT checksum, sum_type, size, mtime, ctime"
923 + " WHERE disk_id = ? AND ino = ?";
924 + if (!prepare_sqlite(SEL_SUM, sql))
927 + sql="SELECT checksum"
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 = ?"))
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))
941 + sql="UPDATE inode_map"
943 + " WHERE disk_id = ? AND ino = ? AND sum_type = ? AND size = ? AND mtime = ?";
944 + if (!prepare_sqlite(UPD_CTIME, sql))
949 + sql="INSERT OR IGNORE INTO disk"
950 + " (host, last_seen, mount_uniq, devno)"
951 + " VALUES (?, ?, ?, ?)";
952 + if (!prepare_sqlite(INS_MOUNT, sql))
956 + " SET last_seen = ?, devno = ?"
957 + " WHERE host = ? AND mount_uniq = ?";
958 + if (!prepare_sqlite(UPD_MOUNT, sql))
961 + sql="SELECT mount_uniq"
963 + " WHERE host = ? AND last_seen < ? AND devno != 0";
964 + if (!prepare_sqlite(SEL_MOUNT, sql))
969 + " WHERE host = ? AND last_seen < ? AND devno != 0";
970 + if (!prepare_sqlite(UN_MOUNT, sql))
980 +static int db_connect_sqlite(void)
982 + int lock_failures = 0;
985 +#ifdef SQLITE_CONFIG_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);
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));
998 + int open_flags = SQLITE_OPEN_READWRITE;
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) {
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);
1010 + if (rc != SQLITE_BUSY && rc != SQLITE_LOCKED)
1012 + if (++lock_failures > MAX_LOCK_FAILURES)
1014 + msleep(LOCK_FAIL_MSLEEP);
1018 + rprintf(log_code, "Unable to connect to DB: %s (%d)\n", sqlite3_errmsg(dbh.sqlite), rc);
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);
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"
1040 + if (!run_sql(sql))
1041 + exit_cleanup(RERR_IPC);
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"
1053 + if (!run_sql(sql))
1054 + exit_cleanup(RERR_IPC);
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. */
1067 + if (!prepare_sqlite_queries(PREP_MOUNT))
1068 + exit_cleanup(RERR_IPC);
1073 + if (!prepare_sqlite_queries(PREP_NORM)) {
1074 + db_disconnect(False);
1082 +int db_connect(int select_many)
1084 + select_many_sums = select_many;
1088 + case DB_TYPE_MYSQL:
1089 + if (db_connect_mysql())
1094 + case DB_TYPE_SQLITE:
1095 + if (db_connect_sqlite())
1101 + db_disconnect(False);
1106 +void db_disconnect(BOOL commit)
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");
1118 + transaction_state = 0;
1120 + run_sql("COMMIT");
1122 + run_sql("ROLLBACK");
1125 + if (DEBUG_GTE(DB, 1))
1126 + rprintf(FCLIENT, "[%s] Disconnecting from the DB\n", who_am_i());
1128 + for (ndx = 0; ndx < MAX_PREP_CNT; ndx++) {
1129 + if (statements[ndx].all) {
1132 + case DB_TYPE_MYSQL:
1133 + mysql_stmt_close(statements[ndx].mysql);
1137 + case DB_TYPE_SQLITE:
1138 + sqlite3_finalize(statements[ndx].sqlite);
1142 + statements[ndx].all = NULL;
1148 + case DB_TYPE_MYSQL:
1149 + mysql_close(dbh.mysql);
1153 + case DB_TYPE_SQLITE:
1154 + sqlite3_close(dbh.sqlite);
1160 + use_db = DB_TYPE_NONE;
1164 +static MYSQL_STMT *exec_mysql(int ndx)
1166 + MYSQL_STMT *stmt = statements[ndx].mysql;
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);
1178 + rprintf(log_code, "SQL execute failed: %s\n", mysql_stmt_error(stmt));
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)
1199 + int i, rc, rows = 0;
1201 + if (bind_cnt > MAX_RESULT_BINDS) {
1202 + fprintf(stderr, "Internal error: MAX_RESULT_BINDS overflow\n");
1203 + exit_cleanup(RERR_UNSUPPORTED);
1206 + if ((stmt = exec_mysql(ndx)) == NULL)
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];
1214 + mysql_stmt_bind_result(stmt, binds);
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));
1222 + if (++rows >= max_rows)
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;
1230 + case MYSQL_TYPE_LONG:
1231 + binds[i].buffer += sizeof (int);
1233 + case MYSQL_TYPE_LONGLONG:
1234 + binds[i].buffer += sizeof (int64);
1237 + fprintf(stderr, "Unknown MYSQL_TYPE_* in multi-row read: %d.\n", binds[i].buffer_type);
1238 + exit_cleanup(RERR_UNSUPPORTED);
1243 + if (!stmt_ptr || rows < max_rows) {
1244 + mysql_stmt_free_result(stmt);
1254 +#if defined USE_MYSQL || defined USE_SQLITE
1255 +static void update_mounts(void)
1257 + char buf[2048], *argv[2];
1258 + int f_from, f_to, len;
1262 + if (DEBUG_GTE(DB, 2))
1263 + printf("Running %s to grab mount info\n", mount_helper_script);
1264 + argv[0] = mount_helper_script;
1266 + pid = piped_child(argv, &f_from, &f_to);
1269 + bind_mtime = time(NULL); /* abuse mtime slightly to hold our last_seen value */
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;
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;
1280 + fprintf(stderr, "Failed to parse line from %s output\n", mount_helper_script);
1281 + exit_cleanup(RERR_SYNTAX);
1284 + if (lstat(path, &st) < 0) {
1285 + fprintf(stderr, "Failed to lstat(%s): %s\n", path, strerror(errno));
1286 + exit_cleanup(RERR_IPC);
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;
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));
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);
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);
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);
1336 + sqlite3_reset(stmt);
1345 + waitpid(pid, &status, 0);
1349 + case DB_TYPE_MYSQL: {
1350 + if (db_output_msgs) {
1351 + MYSQL_BIND binds[1];
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)) {
1359 + printf("Marking mount \"%s\" as unmounted.\n", bind_mount_uniq);
1360 + if (mysql_stmt_fetch(stmt) != 0)
1363 + mysql_stmt_free_result(stmt);
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);
1376 + case DB_TYPE_SQLITE: {
1377 + sqlite3_stmt *stmt;
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);
1385 + if (sqlite3_step(stmt) != SQLITE_ROW)
1387 + printf("Marking mount \"%s\" as unmounted.\n", sqlite3_column_text(stmt, 0));
1389 + sqlite3_reset(stmt);
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);
1409 +static unsigned int get_disk_id(int64 devno)
1411 + static unsigned int prior_disk_id = 0;
1412 + static int64 prior_devno = 0;
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;
1419 + prior_devno = devno;
1423 + case DB_TYPE_MYSQL: {
1424 + MYSQL_BIND binds[1];
1426 + bind_devno = devno; /* The one changing SEL_DEV input value. */
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;
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);
1444 + prior_disk_id = 0;
1445 + sqlite3_reset(stmt);
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;
1456 +int db_get_checksum(const STRUCT_STAT *st_p, char *sum)
1458 + unsigned int disk_id = get_disk_id(st_p->st_dev);
1466 + case DB_TYPE_MYSQL: {
1467 + MYSQL_BIND binds[1];
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;
1474 + bind_ctime = st_p->st_ctime;
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);
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);
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);
1499 + sqlite3_reset(stmt);
1505 + if (DEBUG_GTE(DB, 2)) {
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));
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);
1520 +int db_get_both_checksums(const STRUCT_STAT *st_p, int *right_sum_cnt, int *wrong_sum_cnt, char **sum4, char **sum5)
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);
1532 + case DB_TYPE_MYSQL: {
1533 + MYSQL_BIND binds[5];
1535 + bind_disk_id = disk_id;
1536 + bind_ino = st_p->st_ino;
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);
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++) {
1560 + if (sqlite3_step(stmt) != SQLITE_ROW)
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);
1571 + sqlite3_reset(stmt);
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));
1592 + if (sum_type[j] == 4) {
1595 + *sum4 = dbsum + MD5_DIGEST_LEN*j;
1599 + *sum5 = dbsum + MD5_DIGEST_LEN*j;
1601 + if (st_p->st_size == dbsize[j] && st_p->st_mtime == dbmtime[j] && (db_lax || st_p->st_ctime == dbctime[j]))
1610 +int db_set_checksum(int mdnum, const STRUCT_STAT *st_p, const char *sum)
1612 + unsigned int disk_id;
1613 + const char *errmsg = NULL;
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
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);
1634 + if ((disk_id = get_disk_id(st_p->st_dev)) == 0)
1639 + case DB_TYPE_MYSQL:
1640 + if (transaction_state == 0) {
1641 + if (!run_sql("BEGIN"))
1643 + transaction_state = 1;
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);
1658 + case DB_TYPE_SQLITE: {
1659 + sqlite3_stmt *stmt = statements[REP_SUM].sqlite;
1660 + int lock_failures = 0;
1662 + if (transaction_state == 0) {
1663 + if (!run_sql("BEGIN"))
1665 + transaction_state = 1;
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);
1676 + rc = sqlite3_step(stmt);
1677 + if (rc != SQLITE_BUSY && rc != SQLITE_LOCKED)
1679 + if (++lock_failures > MAX_LOCK_FAILURES)
1681 + sqlite3_reset(stmt);
1682 + msleep(LOCK_FAIL_MSLEEP);
1684 + if (rc != SQLITE_DONE)
1685 + errmsg = sqlite3_errmsg(dbh.sqlite);
1686 + sqlite3_reset(stmt);
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));
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);
1705 + return errmsg ? 0 : 1;
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)
1713 + unsigned int disk_id = get_disk_id(st_p->st_dev);
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;
1730 + case DB_TYPE_SQLITE: {
1733 + sqlite3_stmt *stmt = statements[UPD_CTIME].sqlite;
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;
1752 +static int db_clean_init(void)
1756 + case DB_TYPE_MYSQL: {
1757 + MYSQL_BIND binds[MAX_BIND_CNT];
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)"
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);
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);
1796 + case DB_TYPE_SQLITE: {
1798 + sql="ATTACH DATABASE '' AS aux1;"; /* Private temp DB, probably in-memory */
1799 + if (!run_sql(sql))
1800 + exit_cleanup(RERR_IPC);
1802 + sql="CREATE TABLE aux1.inode_present ("
1803 + " disk_id integer NOT NULL,"
1804 + " ino bigint NOT NULL,"
1805 + " PRIMARY KEY (disk_id,ino)"
1807 + if (!run_sql(sql))
1808 + exit_cleanup(RERR_IPC);
1810 + sql="INSERT OR IGNORE INTO aux1.inode_present"
1813 + if (!prepare_sqlite(INS_PRESENT, sql))
1814 + exit_cleanup(RERR_IPC);
1816 + sql="DELETE FROM inode_map"
1817 + " WHERE ROWID IN ("
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 < ?"
1824 + if (!prepare_sqlite(DEL_SUMS, sql))
1825 + exit_cleanup(RERR_IPC);
1827 + transaction_state = -1; /* bug work-around -- force transaction off when cleaning XXX */
1837 +static int db_note_present(UNUSED(int disk_id), UNUSED(int64 ino))
1841 + case DB_TYPE_MYSQL:
1842 + bind_disk_id = disk_id;
1844 + return exec_mysql(INS_PRESENT) != NULL;
1847 + case DB_TYPE_SQLITE: {
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;
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))
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. */
1872 + case DB_TYPE_MYSQL: {
1874 + bind_ctime = start_time;
1875 + stmt = exec_mysql(DEL_SUMS);
1877 + del_cnt = mysql_affected_rows(dbh.mysql);
1882 + case DB_TYPE_SQLITE: {
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);
1899 +static int abs_path(char *buf, int bufsiz, const char *curdir, const char *dir)
1902 + strlcpy(buf, dir, bufsiz);
1904 + int len = snprintf(buf, bufsiz, "%s/%s", curdir, dir);
1905 + assert(len > 0); /* silence a compiler warning */
1908 + return clean_fname(buf, CFN_DROP_TRAILING_DOT_DIR | CFN_COLLAPSE_DOT_DOT_DIRS);
1911 +static struct name_list *new_name(const char *basename, const char *filename)
1913 + struct name_list *n;
1914 + int blen = strlen(basename);
1915 + int slen = filename ? (int)strlen(filename) : -1;
1916 + int len = blen + 1 + slen;
1918 + if (len >= MAXPATHLEN) {
1920 + rprintf(FERROR, "Filename too long: %s/%s\n", basename, filename);
1922 + rprintf(FERROR, "Filename too long: %s\n", basename);
1926 + n = (struct name_list *)new_array(char, sizeof (struct name_list) + len);
1928 + memcpy(n->name, basename, blen);
1930 + n->name[blen] = '/';
1931 + memcpy(n->name + 1 + blen, filename, slen);
1933 + n->name[len] = '\0';
1939 +static int name_compare(const void *n1, const void *n2)
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);
1946 +static struct name_list *get_sorted_names(const char *dir)
1948 + struct name_list *add, **sortbuf, *names = NULL, *prior_name = NULL;
1949 + struct dirent *di;
1953 + if (!(d = opendir("."))) {
1954 + rprintf(FERROR, "Unable to opendir %s: %s\n", dir, strerror(errno));
1957 + while ((di = readdir(d)) != NULL) {
1958 + char *dname = d_name(di);
1959 + if (dname[0] == '.' && (dname[1] == '\0' || (dname[1] == '.' && dname[2] == '\0')))
1961 + if (!(add = new_name(dname, NULL)))
1964 + prior_name->next = add;
1975 + sortbuf = new_array(struct name_list *, cnt);
1976 + for (j = 0; j < cnt; j++) {
1977 + sortbuf[j] = names;
1978 + names = names->next;
1981 + qsort(sortbuf, cnt, PTR_SIZE, name_compare);
1983 + names = prior_name = NULL;
1984 + for (j = 0; j < cnt; j++) {
1987 + prior_name->next = add;
1994 + prior_name->next = NULL;
2001 +static inline int sums_ne(const char *sum1, const char *sum2)
2003 + return memcmp(sum1, sum2, MD5_DIGEST_LEN) != 0;
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)
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);
2018 + fputs(md4_str, stdout);
2020 + fputs(md5_str, stdout);
2022 + if (db_output_sum) {
2024 + printf("%s ", sum_as_hex(4, sum4, 0));
2026 + printf("%s ", sum_as_hex(5, sum5, 0));
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);
2042 +NORETURN void run_dbonly(const char **args)
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;
2051 + checksum_type = 5;
2053 + need_sum_cnt = db_do_md4 + db_do_md5;
2055 + if (!db_read_config(FERROR, db_config) || !db_connect(1))
2056 + exit_cleanup(RERR_FILEIO);
2059 + clean_start = time(NULL);
2063 + if (getcwd(start_dir, sizeof start_dir - 1) == NULL) {
2064 + rsyserr(FERROR, errno, "getcwd()");
2065 + exit_cleanup(RERR_FILESELECT);
2067 + start_dir_len = strlen(start_dir);
2072 + struct name_list *add;
2073 + if (abs_path(dirbuf, sizeof dirbuf, start_dir, *args++) <= 0)
2075 + if (!(add = new_name(dirbuf, NULL)))
2078 + prior_dir->next = add;
2084 + dirs_list = new_name(start_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;
2093 + free((void*)prior_dir);
2094 + prior_dir = dirs_list;
2095 + dirs_list = dirs_list->next;
2097 + if (strncmp(reldir, start_dir, start_dir_len) == 0) {
2098 + if (reldir[start_dir_len] == '\0')
2100 + else if (reldir[start_dir_len] == '/')
2101 + reldir += start_dir_len + 1;
2103 + if (db_output_dirs)
2104 + printf("... %s/ ...\n", reldir);
2106 + if (chdir(dir) < 0) {
2107 + rprintf(FERROR, "Unable to chdir to %s: %s\n", dir, strerror(errno));
2110 + if (!(names = get_sorted_names(dir)))
2113 + subdirs = prior_subdir = prior_name = NULL;
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;
2123 + free((void*)prior_name);
2124 + prior_name = names;
2125 + names = names->next;
2127 + dbsum4 = dbsum5 = sum4 = sum5 = NULL;
2129 + if (lstat(name, &st) < 0) {
2130 + rprintf(FERROR, "Failed to lstat(%s): %s\n", name, strerror(errno));
2133 + if (S_ISLNK(st.st_mode))
2135 + if (S_ISDIR(st.st_mode)) {
2136 + /* add optional excluding of things like /^(CVS|\.svn|\.git|\.bzr)$/; */
2138 + struct name_list *add = new_name(dir, name);
2141 + prior_subdir->next = add;
2144 + prior_subdir = add;
2149 + if (!S_ISREG(st.st_mode))
2152 + if (!(disk_id = get_disk_id(st.st_dev)))
2155 + db_note_present(disk_id, st.st_ino);
2156 + if (!db_update && !db_check)
2159 + db_get_both_checksums(&st, &right_sum_cnt, &wrong_sum_cnt,
2160 + db_do_md4 ? &dbsum4 : NULL, db_do_md5 ? &dbsum5 : NULL);
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);
2167 + if (db_update || (db_check && right_sum_cnt) || db_output_sum) {
2172 + struct map_struct *buf;
2173 + OFF_T off, len = st.st_size;
2174 + int fd = do_open(name, O_RDONLY, 0);
2177 + rprintf(FERROR, "ERROR: unable to read %s: %s\n", name, strerror(errno));
2182 + mdfour_begin(&m4);
2186 + buf = map_file(fd, len, MAX_MAP_SIZE, CSUM_CHUNK);
2188 + for (off = 0; off + CSUM_CHUNK <= len; off += CSUM_CHUNK) {
2189 + data = (uchar*)map_ptr(buf, off, CSUM_CHUNK);
2191 + mdfour_update(&m4, data, CSUM_CHUNK);
2193 + MD5_Update(&m5, data, CSUM_CHUNK);
2196 + remainder = (int32)(len - off);
2197 + data = (uchar*)map_ptr(buf, off, remainder);
2199 + mdfour_update(&m4, data, remainder);
2200 + mdfour_result(&m4, (uchar*)(sum4 = sumbuf4));
2203 + MD5_Update(&m5, data, remainder);
2204 + MD5_Final((uchar*)(sum5 = sumbuf5), &m5);
2211 + int chg = mention_file(reldir, name, right_sum_cnt, wrong_sum_cnt, dbsum4, dbsum5, sum4, sum5);
2213 + /* Only db_check should get here... */
2214 + } else if (!db_update) {
2218 + if (db_do_md4 && !db_set_checksum(4, &st, sum4))
2220 + if (db_do_md5 && !db_set_checksum(5, &st, sum5))
2223 + fprintf(stderr, "Failed to set checksum on %s/%s\n", reldir, name);
2224 + exit_cleanup(RERR_FILEIO);
2229 + free((void*)prior_name);
2231 + if (recurse && subdirs) {
2232 + prior_subdir->next = dirs_list;
2233 + dirs_list = subdirs;
2237 + free((void*)prior_dir);
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");
2245 + db_disconnect(True);
2248 diff --git a/flist.c 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;
2256 extern int eol_nulls;
2257 extern int atimes_ndx;
2258 extern int relative_paths;
2259 @@ -1325,11 +1326,8 @@ struct file_struct *make_file(const char *fname, struct file_list *flist,
2260 extra_len += EXTRA_LEN;
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;
2268 + if (sender_keeps_checksum && S_ISREG(st.st_mode))
2269 + extra_len += SUM_EXTRA_CNT * EXTRA_LEN;
2271 #if EXTRA_ROUNDING > 0
2272 if (extra_len & (EXTRA_ROUNDING * EXTRA_LEN))
2273 @@ -1414,8 +1412,12 @@ struct file_struct *make_file(const char *fname, struct file_list *flist,
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);
2287 F_NDX(file) = stats.num_dirs;
2288 @@ -2099,6 +2101,9 @@ void send_extra_file_list(int f, int at_least)
2290 if (io_error != save_io_error && protocol_version == 30 && !ignore_errors)
2291 send_msg_int(MSG_IO_ERROR, io_error);
2293 + if (use_db && flist_eof)
2294 + db_disconnect(True);
2297 struct file_list *send_file_list(int f, int argc, char *argv[])
2298 @@ -2122,6 +2127,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;
2303 + if (always_checksum)
2304 + db_connect(0); /* Will reset use_db on error. */
2309 rprintf(FLOG, "building file list\n");
2310 if (show_filelist_progress)
2311 start_filelist_progress("building file list");
2312 @@ -2465,6 +2477,9 @@ struct file_list *send_file_list(int f, int argc, char *argv[])
2313 rprintf(FINFO, "[%s] flist_eof=1\n", who_am_i());
2316 + if (use_db && (!inc_recurse || flist_eof))
2317 + db_disconnect(True);
2322 diff --git a/generator.c b/generator.c
2325 @@ -61,6 +61,7 @@ extern int ignore_non_existing;
2326 extern int want_xattr_optim;
2327 extern int modify_window;
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;
2343 @@ -2239,6 +2241,13 @@ void generate_files(int f_out, const char *local_name)
2348 + if (always_checksum || (append_mode != 1 && protocol_version >= 30))
2349 + db_connect(0); /* Will reset use_db on error. */
2354 dflt_perms = (ACCESSPERMS & ~orig_umask);
2357 @@ -2364,6 +2373,9 @@ void generate_files(int f_out, const char *local_name)
2358 wait_for_receiver();
2362 + db_disconnect(True);
2364 info_levels[INFO_FLIST] = save_info_flist;
2365 info_levels[INFO_PROGRESS] = save_info_progress;
2367 diff --git a/io.c 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)
2383 maybe_send_keepalive(time(NULL), MSK_ALLOW_FLUSH);
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)
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))
2397 + /* The received data is a set of numbers followed by the checksum. */
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
2407 + iobuf.in_multiplexed = 1;
2408 + db_set_checksum(IVAL(data, MSG_CHECKSUM_LONGS*8), &st, data + MSG_CHECKSUM_LONGS*8 + 4);
2412 if (msg_bytes >= sizeof data)
2414 @@ -1638,6 +1666,7 @@ static void read_a_msg(void)
2415 * with a duplicate exit message. */
2416 _exit_cleanup(val, __FILE__, 0 - __LINE__);
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
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;
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);
2454 + db_read_config(FERROR, db_config);
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[])
2461 env_port = rsync_port;
2464 + db_read_config(FERROR, db_config);
2466 if (daemon_over_rsh < 0)
2467 return start_socket_client(shell_machine, remote_argc, remote_argv, argc, argv);
2469 diff --git a/options.c b/options.c
2472 @@ -86,6 +86,7 @@ int am_root = 0; /* 0 = normal, 1 = root, 2 = --super, -1 = --fake-super */
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;
2486 int protect_args = -1;
2487 int human_readable = 1;
2488 @@ -106,6 +108,9 @@ int recurse = 0;
2489 int allow_inc_recurse = 1;
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)
2510 +#if !defined HAVE_MYSQL_MYSQL_H || !defined HAVE_LIBMYSQLCLIENT
2515 +#if !defined HAVE_SQLITE3_H || !defined HAVE_LIBSQLITE3
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 },
2552 @@ -1069,6 +1093,39 @@ static struct poptOption long_daemon_options[] = {
2556 +static void dbonly_usage(enum logcode F)
2558 + rprintf(F,"Usage: rsyncdb --db=CONFIG_FILE [OPTIONS] [DIRS]\n");
2560 + rprintf(F,"Options:\n");
2561 +#include "help-rsyncdb.h"
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}
2590 static char err_buf[200];
2592 @@ -1194,6 +1251,8 @@ static void set_refuse_options(void)
2593 parse_one_refuse_match(0, "iconv", list_end);
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);
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);
2605 +static NORETURN void parse_dbonly_args(int argc, const char **argv)
2607 + poptContext pc = poptGetContext(RSYNC_NAME, argc, argv, long_dbonly_options, 0);
2614 + while ((opt = poptGetNextOpt(pc)) != -1) {
2618 + for (cp = poptGetOptArg(pc); *cp; cp++) {
2619 + switch (toLower(cp)) {
2621 + db_output_name = 1;
2625 + db_output_sum = db_output_name = 1;
2628 + db_output_info = db_output_name = 1;
2631 + db_output_unchanged = db_output_name = 1;
2634 + db_output_dirs = 1;
2638 + saw_db_output_opt = 1;
2642 + for (cp = poptGetOptArg(pc); *cp; cp++) {
2652 + saw_db_sum_opt = 1;
2656 + dbonly_usage(FINFO);
2660 + arg = poptGetOptArg(pc);
2661 + parse_output_words(info_words, info_levels, arg, USER_PRIORITY);
2665 + arg = poptGetOptArg(pc);
2666 + parse_output_words(debug_words, debug_levels, arg, USER_PRIORITY);
2671 + "rsyncdb: %s: %s\n",
2672 + poptBadOption(pc, POPT_BADOPTION_NOALIAS),
2673 + poptStrerror(opt));
2674 + goto dbonly_usage;
2679 + rprintf(FERROR, "You must specify the --db=FILE option.\n");
2682 + "(Type \"rsyncdb --help\" for assistance.)\n");
2683 + exit_cleanup(RERR_SYNTAX);
2686 + if (!saw_db_output_opt && !quiet) {
2687 + db_output_dirs = db_output_name = 1;
2689 + db_output_info = 1;
2692 + db_output_msgs = 1;
2693 + if (!saw_db_sum_opt)
2696 + am_starting_up = 0;
2697 + run_dbonly(poptGetArgs(pc));
2698 + exit(42); /* NOT REACHED */
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)
2708 + arg = *argv + strlen(*argv);
2709 + if (arg - *argv > 2 && strcmp(arg-2, "db") == 0) {
2710 + parse_dbonly_args(argc, argv);
2714 set_refuse_options();
2717 @@ -1672,6 +1833,12 @@ int parse_arguments(int *argc_p, const char ***argv_p)
2723 + poptFreeContext(pc);
2724 + parse_dbonly_args(argc, argv);
2725 + break; /* NOT REACHED */
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;
2741 diff --git a/pipe.c 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;
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;
2759 * Create a child connected to us via its stdin/stdout.
2761 @@ -141,13 +146,22 @@ pid_t local_child(int argc, char **argv, int *f_in, int *f_out,
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)) {
2770 exit_cleanup(RERR_SYNTAX);
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) {
2778 + db_read_config(FERROR, db_config);
2780 + } else if (use_db)
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
2791 extern int do_xfers;
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);
2801 + if (use_db && !db_lax) {
2803 + if (do_lstat(fname, &st) == 0)
2804 + db_update_ctime(5, &st);
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)
2811 delayed_bits = bitbag_create(cur_flist->used + 1);
2813 + if (use_db && (append_mode == 1 || protocol_version < 30))
2814 + use_db = 0; /* We can't note finished md5 values */
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);
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)) {
2828 @@ -891,6 +903,8 @@ int recv_files(int f_in, int f_out, char *local_name)
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);
2837 diff --git a/rsync.1.md 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
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)
2863 const char *who_am_i(void)
2868 return am_server ? "server" : "client";
2869 return am_sender ? "sender"
2870 diff --git a/rsync.h 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 */
2884 +#define MSG_CHECKSUM_LONGS 5
2885 +#define MSG_CHECKSUM_LEN (MSG_CHECKSUM_LONGS*8 + 4 + MAX_DIGEST_LEN)
2888 #define NDX_FLIST_EOF -2
2889 #define NDX_DEL_STATS -3
2890 @@ -1406,7 +1410,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
2903 +++ b/rsyncdb-mountinfo
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
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).
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
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).
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.
2933 +# The maximum size for MOUNT_UNIQ is 256 characters.
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.
2942 +use Cwd 'abs_path';
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';
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");
2957 + $uuid =~ s{.*/}{};
2958 + $uuid{$lnk} = $uuid;
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/;
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.
2972 + my $mount_uniq = $uuid{$devname} ? $uuid{$devname} : "Mount of $devname";
2973 + if (open UNIQ, '<', "$path/$OVERRIDE_FILE") {
2974 + $mount_uniq = <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.
2979 + print $mount_uniq, "\t", $path, "\n";
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
2994 +rsyncdb - Maintain an rsync checksum DB
2999 +rsyncdb --db=CONFIG [OPTION...] [DIR...]
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
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
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).
3022 +The following command will update checksum information in the database
3023 +described in the /etc/db.conf file:
3025 +> rsyncdb --db=/etc/db.conf -o n --clean /dir1 /dir2
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).
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
3035 +> rsyncdb --db=/etc/db.conf --check --no-r /dir2
3037 +Any errors found are output as well as being fixed in the DB. (See
3038 +`--no-update` for how to check without updating.)
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):
3044 +> rsyncdb --db=/etc/db.conf -rous /dir* >/tmp/md5sums.txt
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.
3050 +The following command initializes a new DB, and is required for any new DB:
3052 +> rsyncdb --db=/etc/db.conf --init --mounts
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).
3060 +Rsyncdb accepts the following options:
3062 +[comment]: # (help-rsyncdb.h)
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
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.
3092 +0. `--db=CONFIG_FILE`
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.
3099 + This option works just like it does in rsync, so refer to that manpage for
3102 +0. `--no-recursive, --no-r`
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.
3108 +0. `--sums=SUMS, -s`
3110 + Only output/update the listed checksum types. By default we deal with just
3111 + the newer md5 checksums (i.e. `--sums=5`).
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`.
3116 +0. `--output=STR, -o`
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".
3122 + The following letters are accepted in the string:
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
3140 + - `?5` indicates an unknown MD5 difference.
3141 + - `u` includes unchanged files in the per-file output lines.
3145 + Check the checksums (forcing the reading of all the files) and fix any
3146 + issues that are found. Makes `--output` default to "dni".
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.
3158 +0. `--no-update, -N`
3160 + Avoids updating/adding info with `--check` and/or `--clean`.
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
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.
3174 +This option cannot be combined with the updating or reporting of checksum
3175 +information, but may be combined with `--mounts`.
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
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
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.
3195 + Specifying the `--mounts` option cannot be combined with updating or
3196 + reporting of checksum information, but may be combined with `--init`.
3200 + Display a summary of the options.
3208 +Rsyncdb was written by Wayne Davison.