Rework filter process code to make the interface simpler.
[cumulus.git] / main.cc
1 /* Cumulus: Efficient Filesystem Backup to the Cloud
2  * Copyright (C) 2006-2009, 2012 The Cumulus Developers
3  * See the AUTHORS file for a list of contributors.
4  *
5  * This program is free software; you can redistribute it and/or modify
6  * it under the terms of the GNU General Public License as published by
7  * the Free Software Foundation; either version 2 of the License, or
8  * (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License along
16  * with this program; if not, write to the Free Software Foundation, Inc.,
17  * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
18  */
19
20 /* Main entry point for Cumulus.  Contains logic for traversing the filesystem
21  * and constructing a backup. */
22
23 #include <dirent.h>
24 #include <errno.h>
25 #include <fcntl.h>
26 #include <getopt.h>
27 #include <grp.h>
28 #include <pwd.h>
29 #include <stdint.h>
30 #include <stdio.h>
31 #include <stdlib.h>
32 #include <string.h>
33 #include <sys/stat.h>
34 #include <sys/sysmacros.h>
35 #include <sys/types.h>
36 #include <sys/wait.h>
37 #include <unistd.h>
38
39 #include <algorithm>
40 #include <fstream>
41 #include <iostream>
42 #include <list>
43 #include <map>
44 #include <set>
45 #include <sstream>
46 #include <string>
47 #include <vector>
48
49 #include "exclude.h"
50 #include "hash.h"
51 #include "localdb.h"
52 #include "metadata.h"
53 #include "remote.h"
54 #include "store.h"
55 #include "subfile.h"
56 #include "util.h"
57 #include "third_party/sha1.h"
58
59 using std::list;
60 using std::map;
61 using std::string;
62 using std::vector;
63 using std::ostream;
64
65 /* Version information.  This will be filled in by the Makefile. */
66 #ifndef CUMULUS_VERSION
67 #define CUMULUS_VERSION Unknown
68 #endif
69 #define CUMULUS_STRINGIFY(s) CUMULUS_STRINGIFY2(s)
70 #define CUMULUS_STRINGIFY2(s) #s
71 static const char cumulus_version[] = CUMULUS_STRINGIFY(CUMULUS_VERSION);
72
73 static RemoteStore *remote = NULL;
74 static TarSegmentStore *tss = NULL;
75 static MetadataWriter *metawriter = NULL;
76
77 /* Buffer for holding a single block of data read from a file. */
78 static const size_t LBS_BLOCK_SIZE = 1024 * 1024;
79 static char *block_buf;
80
81 /* Local database, which tracks objects written in this and previous
82  * invocations to help in creating incremental snapshots. */
83 LocalDb *db;
84
85 /* Selection of files to include/exclude in the snapshot. */
86 PathFilterList filter_rules;
87
88 bool flag_rebuild_statcache = false;
89
90 /* Whether verbose output is enabled. */
91 bool verbose = false;
92
93 /* Attempts to open a regular file read-only, but with safety checks for files
94  * that might not be fully trusted. */
95 int safe_open(const string& path, struct stat *stat_buf)
96 {
97     int fd;
98
99     /* Be paranoid when opening the file.  We have no guarantee that the
100      * file was not replaced between the stat() call above and the open()
101      * call below, so we might not even be opening a regular file.  We
102      * supply flags to open to to guard against various conditions before
103      * we can perform an lstat to check that the file is still a regular
104      * file:
105      *   - O_NOFOLLOW: in the event the file was replaced by a symlink
106      *   - O_NONBLOCK: prevents open() from blocking if the file was
107      *     replaced by a fifo
108      * We also add in O_NOATIME, since this may reduce disk writes (for
109      * inode updates).  However, O_NOATIME may result in EPERM, so if the
110      * initial open fails, try again without O_NOATIME.  */
111     fd = open(path.c_str(), O_RDONLY|O_NOATIME|O_NOFOLLOW|O_NONBLOCK);
112     if (fd < 0) {
113         fd = open(path.c_str(), O_RDONLY|O_NOFOLLOW|O_NONBLOCK);
114     }
115     if (fd < 0) {
116         fprintf(stderr, "Unable to open file %s: %m\n", path.c_str());
117         return -1;
118     }
119
120     /* Drop the use of the O_NONBLOCK flag; we only wanted that for file
121      * open. */
122     long flags = fcntl(fd, F_GETFL);
123     fcntl(fd, F_SETFL, flags & ~O_NONBLOCK);
124
125     /* Re-check file attributes, storing them into stat_buf if that is
126      * non-NULL. */
127     struct stat internal_stat_buf;
128     if (stat_buf == NULL)
129         stat_buf = &internal_stat_buf;
130
131     /* Perform the stat call again, and check that we still have a regular
132      * file. */
133     if (fstat(fd, stat_buf) < 0) {
134         fprintf(stderr, "fstat: %m\n");
135         close(fd);
136         return -1;
137     }
138
139     if ((stat_buf->st_mode & S_IFMT) != S_IFREG) {
140         fprintf(stderr, "file is no longer a regular file!\n");
141         close(fd);
142         return -1;
143     }
144
145     return fd;
146 }
147
148 /* Read data from a file descriptor and return the amount of data read.  A
149  * short read (less than the requested size) will only occur if end-of-file is
150  * hit. */
151 ssize_t file_read(int fd, char *buf, size_t maxlen)
152 {
153     size_t bytes_read = 0;
154
155     while (true) {
156         ssize_t res = read(fd, buf, maxlen);
157         if (res < 0) {
158             if (errno == EINTR)
159                 continue;
160             fprintf(stderr, "error reading file: %m\n");
161             return -1;
162         } else if (res == 0) {
163             break;
164         } else {
165             bytes_read += res;
166             buf += res;
167             maxlen -= res;
168         }
169     }
170
171     return bytes_read;
172 }
173
174 /* Read the contents of a file (specified by an open file descriptor) and copy
175  * the data to the store.  Returns the size of the file (number of bytes
176  * dumped), or -1 on error. */
177 int64_t dumpfile(int fd, dictionary &file_info, const string &path,
178                  struct stat& stat_buf)
179 {
180     int64_t size = 0;
181     list<string> object_list;
182     const char *status = NULL;          /* Status indicator printed out */
183
184     /* Look up this file in the old stat cache, if we can.  If the stat
185      * information indicates that the file has not changed, do not bother
186      * re-reading the entire contents.  Even if the information has been
187      * changed, we can use the list of old blocks in the search for a sub-block
188      * incremental representation. */
189     bool cached = false;
190     list<ObjectReference> old_blocks;
191
192     bool found = metawriter->find(path);
193     if (found)
194         old_blocks = metawriter->get_blocks();
195
196     if (found
197         && !flag_rebuild_statcache
198         && metawriter->is_unchanged(&stat_buf)) {
199         cached = true;
200
201         /* If any of the blocks in the object have been expired, then we should
202          * fall back to fully reading in the file. */
203         for (list<ObjectReference>::const_iterator i = old_blocks.begin();
204              i != old_blocks.end(); ++i) {
205             const ObjectReference &ref = *i;
206             if (!db->IsAvailable(ref)) {
207                 cached = false;
208                 status = "repack";
209                 break;
210             }
211         }
212
213         /* If everything looks okay, use the cached information */
214         if (cached) {
215             file_info["checksum"] = metawriter->get_checksum();
216             for (list<ObjectReference>::const_iterator i = old_blocks.begin();
217                  i != old_blocks.end(); ++i) {
218                 const ObjectReference &ref = *i;
219                 object_list.push_back(ref.to_string());
220                 db->UseObject(ref);
221             }
222             size = stat_buf.st_size;
223         }
224     }
225
226     /* If the file is new or changed, we must read in the contents a block at a
227      * time. */
228     if (!cached) {
229         Hash *hash = Hash::New();
230         Subfile subfile(db);
231         subfile.load_old_blocks(old_blocks);
232
233         while (true) {
234             ssize_t bytes = file_read(fd, block_buf, LBS_BLOCK_SIZE);
235             if (bytes == 0)
236                 break;
237             if (bytes < 0) {
238                 fprintf(stderr, "Backup contents for %s may be incorrect\n",
239                         path.c_str());
240                 break;
241             }
242
243             hash->update(block_buf, bytes);
244
245             // Sparse file processing: if we read a block of all zeroes, encode
246             // that explicitly.
247             bool all_zero = true;
248             for (int i = 0; i < bytes; i++) {
249                 if (block_buf[i] != 0) {
250                     all_zero = false;
251                     break;
252                 }
253             }
254
255             // Either find a copy of this block in an already-existing segment,
256             // or index it so it can be re-used in the future
257             double block_age = 0.0;
258             ObjectReference ref;
259
260             Hash *hash = Hash::New();
261             hash->update(block_buf, bytes);
262             string block_csum = hash->digest_str();
263             delete hash;
264
265             if (all_zero) {
266                 ref = ObjectReference(ObjectReference::REF_ZERO);
267                 ref.set_range(0, bytes);
268             } else {
269                 ref = db->FindObject(block_csum, bytes);
270             }
271
272             list<ObjectReference> refs;
273
274             // Store a copy of the object if one does not yet exist
275             if (ref.is_null()) {
276                 LbsObject *o = new LbsObject;
277                 int object_group;
278
279                 /* We might still have seen this checksum before, if the object
280                  * was stored at some time in the past, but we have decided to
281                  * clean the segment the object was originally stored in
282                  * (FindObject will not return such objects).  When rewriting
283                  * the object contents, put it in a separate group, so that old
284                  * objects get grouped together.  The hope is that these old
285                  * objects will continue to be used in the future, and we
286                  * obtain segments which will continue to be well-utilized.
287                  * Additionally, keep track of the age of the data by looking
288                  * up the age of the block which was expired and using that
289                  * instead of the current time. */
290                 if (db->IsOldObject(block_csum, bytes,
291                                     &block_age, &object_group)) {
292                     if (object_group == 0) {
293                         o->set_group("data");
294                     } else {
295                         o->set_group(string_printf("compacted-%d",
296                                                    object_group));
297                     }
298                     if (status == NULL)
299                         status = "partial";
300                 } else {
301                     o->set_group("data");
302                     status = "new";
303                 }
304
305                 subfile.analyze_new_block(block_buf, bytes);
306                 refs = subfile.create_incremental(tss, o, block_age);
307             } else {
308                 if (flag_rebuild_statcache && ref.is_normal()) {
309                     subfile.analyze_new_block(block_buf, bytes);
310                     subfile.store_analyzed_signatures(ref);
311                 }
312                 refs.push_back(ref);
313             }
314
315             while (!refs.empty()) {
316                 ref = refs.front(); refs.pop_front();
317                 object_list.push_back(ref.to_string());
318                 db->UseObject(ref);
319             }
320             size += bytes;
321
322             if (status == NULL)
323                 status = "old";
324         }
325
326         file_info["checksum"] = hash->digest_str();
327         delete hash;
328     }
329
330     // Sanity check: if we are rebuilding the statcache, but the file looks
331     // like it hasn't changed, then the newly-computed checksum should match
332     // the checksum in the statcache.  If not, we have possible disk corruption
333     // and report a warning.
334     if (flag_rebuild_statcache) {
335         if (found
336             && metawriter->is_unchanged(&stat_buf)
337             && file_info["checksum"] != metawriter->get_checksum()) {
338             fprintf(stderr,
339                     "Warning: Checksum for %s does not match expected value\n"
340                     "    expected: %s\n"
341                     "    actual:   %s\n",
342                     path.c_str(),
343                     metawriter->get_checksum().c_str(),
344                     file_info["checksum"].c_str());
345         }
346     }
347
348     if (verbose && status != NULL)
349         printf("    [%s]\n", status);
350
351     string blocklist = "";
352     for (list<string>::iterator i = object_list.begin();
353          i != object_list.end(); ++i) {
354         if (i != object_list.begin())
355             blocklist += "\n    ";
356         blocklist += *i;
357     }
358     file_info["data"] = blocklist;
359
360     return size;
361 }
362
363 /* Look up a user/group and convert it to string form (either strictly numeric
364  * or numeric plus symbolic).  Caches the results of the call to
365  * getpwuid/getgrgid. */
366 string user_to_string(uid_t uid) {
367     static map<uid_t, string> user_cache;
368     map<uid_t, string>::const_iterator i = user_cache.find(uid);
369     if (i != user_cache.end())
370         return i->second;
371
372     string result = encode_int(uid);
373     struct passwd *pwd = getpwuid(uid);
374     if (pwd != NULL && pwd->pw_name != NULL) {
375         result += " (" + uri_encode(pwd->pw_name) + ")";
376     }
377     user_cache[uid] = result;
378     return result;
379 }
380
381 string group_to_string(gid_t gid) {
382     static map<gid_t, string> group_cache;
383     map<gid_t, string>::const_iterator i = group_cache.find(gid);
384     if (i != group_cache.end())
385         return i->second;
386
387     string result = encode_int(gid);
388     struct group *grp = getgrgid(gid);
389     if (grp != NULL && grp->gr_name != NULL) {
390         result += " (" + uri_encode(grp->gr_name) + ")";
391     }
392     group_cache[gid] = result;
393     return result;
394 }
395
396 /* Dump a specified filesystem object (file, directory, etc.) based on its
397  * inode information.  If the object is a regular file, an open filehandle is
398  * provided. */
399 void dump_inode(const string& path,         // Path within snapshot
400                 const string& fullpath,     // Path to object in filesystem
401                 struct stat& stat_buf,      // Results of stat() call
402                 int fd)                     // Open filehandle if regular file
403 {
404     char *buf;
405     dictionary file_info;
406     int64_t file_size;
407     ssize_t len;
408
409     if (verbose)
410         printf("%s\n", path.c_str());
411     metawriter->find(path);
412
413     file_info["name"] = uri_encode(path);
414     file_info["mode"] = encode_int(stat_buf.st_mode & 07777, 8);
415     file_info["ctime"] = encode_int(stat_buf.st_ctime);
416     file_info["mtime"] = encode_int(stat_buf.st_mtime);
417     file_info["user"] = user_to_string(stat_buf.st_uid);
418     file_info["group"] = group_to_string(stat_buf.st_gid);
419
420     time_t now = time(NULL);
421     if (now - stat_buf.st_ctime < 30 || now - stat_buf.st_mtime < 30)
422         if ((stat_buf.st_mode & S_IFMT) != S_IFDIR)
423             file_info["volatile"] = "1";
424
425     if (stat_buf.st_nlink > 1 && (stat_buf.st_mode & S_IFMT) != S_IFDIR) {
426         file_info["links"] = encode_int(stat_buf.st_nlink);
427     }
428
429     file_info["inode"] = encode_int(major(stat_buf.st_dev))
430         + "/" + encode_int(minor(stat_buf.st_dev))
431         + "/" + encode_int(stat_buf.st_ino);
432
433     char inode_type;
434
435     switch (stat_buf.st_mode & S_IFMT) {
436     case S_IFIFO:
437         inode_type = 'p';
438         break;
439     case S_IFSOCK:
440         inode_type = 's';
441         break;
442     case S_IFBLK:
443     case S_IFCHR:
444         inode_type = ((stat_buf.st_mode & S_IFMT) == S_IFBLK) ? 'b' : 'c';
445         file_info["device"] = encode_int(major(stat_buf.st_rdev))
446             + "/" + encode_int(minor(stat_buf.st_rdev));
447         break;
448     case S_IFLNK:
449         inode_type = 'l';
450
451         /* Use the reported file size to allocate a buffer large enough to read
452          * the symlink.  Allocate slightly more space, so that we ask for more
453          * bytes than we expect and so check for truncation. */
454         buf = new char[stat_buf.st_size + 2];
455         len = readlink(fullpath.c_str(), buf, stat_buf.st_size + 1);
456         if (len < 0) {
457             fprintf(stderr, "error reading symlink: %m\n");
458         } else if (len <= stat_buf.st_size) {
459             buf[len] = '\0';
460             file_info["target"] = uri_encode(buf);
461         } else if (len > stat_buf.st_size) {
462             fprintf(stderr, "error reading symlink: name truncated\n");
463         }
464
465         delete[] buf;
466         break;
467     case S_IFREG:
468         inode_type = 'f';
469
470         file_size = dumpfile(fd, file_info, path, stat_buf);
471         file_info["size"] = encode_int(file_size);
472
473         if (file_size < 0)
474             return;             // error occurred; do not dump file
475
476         if (file_size != stat_buf.st_size) {
477             fprintf(stderr, "Warning: Size of %s changed during reading\n",
478                     path.c_str());
479             file_info["volatile"] = "1";
480         }
481
482         break;
483     case S_IFDIR:
484         inode_type = 'd';
485         break;
486
487     default:
488         fprintf(stderr, "Unknown inode type: mode=%x\n", stat_buf.st_mode);
489         return;
490     }
491
492     file_info["type"] = string(1, inode_type);
493
494     metawriter->add(file_info);
495 }
496
497 /* Converts a path to the normalized form used in the metadata log.  Paths are
498  * written as relative (without any leading slashes).  The root directory is
499  * referred to as ".". */
500 string metafile_path(const string& path)
501 {
502     const char *newpath = path.c_str();
503     if (*newpath == '/')
504         newpath++;
505     if (*newpath == '\0')
506         newpath = ".";
507     return newpath;
508 }
509
510 void try_merge_filter(const string& path, const string& basedir)
511 {
512     struct stat stat_buf;
513     if (lstat(path.c_str(), &stat_buf) < 0)
514         return;
515     if ((stat_buf.st_mode & S_IFMT) != S_IFREG)
516         return;
517     int fd = safe_open(path, NULL);
518     if (fd < 0)
519         return;
520
521     /* As a very crude limit on the complexity of merge rules, only read up to
522      * one block (1 MB) worth of data.  If the file doesn't seems like it might
523      * be larger than that, don't parse the rules in it. */
524     ssize_t bytes = file_read(fd, block_buf, LBS_BLOCK_SIZE);
525     close(fd);
526     if (bytes < 0 || bytes >= static_cast<ssize_t>(LBS_BLOCK_SIZE - 1)) {
527         /* TODO: Add more strict resource limits on merge files? */
528         fprintf(stderr,
529                 "Unable to read filter merge file (possibly size too large\n");
530         return;
531     }
532     filter_rules.merge_patterns(metafile_path(path), basedir,
533                                 string(block_buf, bytes));
534 }
535
536 void scanfile(const string& path)
537 {
538     int fd = -1;
539     struct stat stat_buf;
540     list<string> refs;
541
542     string output_path = metafile_path(path);
543
544     if (lstat(path.c_str(), &stat_buf) < 0) {
545         fprintf(stderr, "lstat(%s): %m\n", path.c_str());
546         return;
547     }
548
549     bool is_directory = ((stat_buf.st_mode & S_IFMT) == S_IFDIR);
550     if (!filter_rules.is_included(output_path, is_directory))
551         return;
552
553     if ((stat_buf.st_mode & S_IFMT) == S_IFREG) {
554         fd = safe_open(path, &stat_buf);
555         if (fd < 0)
556             return;
557     }
558
559     dump_inode(output_path, path, stat_buf, fd);
560
561     if (fd >= 0)
562         close(fd);
563
564     /* If we hit a directory, now that we've written the directory itself,
565      * recursively scan the directory. */
566     if (is_directory) {
567         DIR *dir = opendir(path.c_str());
568
569         if (dir == NULL) {
570             fprintf(stderr, "Error reading directory %s: %m\n",
571                     path.c_str());
572             return;
573         }
574
575         struct dirent *ent;
576         vector<string> contents;
577         while ((ent = readdir(dir)) != NULL) {
578             string filename(ent->d_name);
579             if (filename == "." || filename == "..")
580                 continue;
581             contents.push_back(filename);
582         }
583
584         closedir(dir);
585
586         sort(contents.begin(), contents.end());
587
588         filter_rules.save();
589
590         /* First pass through the directory items: look for any filter rules to
591          * merge and do so. */
592         for (vector<string>::iterator i = contents.begin();
593              i != contents.end(); ++i) {
594             string filename;
595             if (path == ".")
596                 filename = *i;
597             else if (path == "/")
598                 filename = "/" + *i;
599             else
600                 filename = path + "/" + *i;
601             if (filter_rules.is_mergefile(metafile_path(filename))) {
602                 if (verbose) {
603                     printf("Merging directory filter rules %s\n",
604                            filename.c_str());
605                 }
606                 try_merge_filter(filename, output_path);
607             }
608         }
609
610         /* Second pass: recursively scan all items in the directory for backup;
611          * scanfile() will check if the item should be included or not. */
612         for (vector<string>::iterator i = contents.begin();
613              i != contents.end(); ++i) {
614             const string& filename = *i;
615             if (path == ".")
616                 scanfile(filename);
617             else if (path == "/")
618                 scanfile("/" + filename);
619             else
620                 scanfile(path + "/" + filename);
621         }
622
623         filter_rules.restore();
624     }
625 }
626
627 void usage(const char *program)
628 {
629     fprintf(
630         stderr,
631         "Cumulus %s\n\n"
632         "Usage: %s [OPTION]... --dest=DEST PATHS...\n"
633         "Produce backup snapshot of files in SOURCE and store to DEST.\n"
634         "\n"
635         "Options:\n"
636         "  --dest=PATH          path where backup is to be written\n"
637         "  --upload-script=COMMAND\n"
638         "                       program to invoke for each backup file generated\n"
639         "  --exclude=PATTERN    exclude files matching PATTERN from snapshot\n"
640         "  --include=PATTERN    include files matching PATTERN in snapshot\n"
641         "  --dir-merge=PATTERN  parse files matching PATTERN to read additional\n"
642         "                       subtree-specific include/exclude rules during backup\n"
643         "  --localdb=PATH       local backup metadata is stored in PATH\n"
644         "  --tmpdir=PATH        path for temporarily storing backup files\n"
645         "                           (defaults to TMPDIR environment variable or /tmp)\n"
646         "  --filter=COMMAND     program through which to filter segment data\n"
647         "                           (defaults to \"bzip2 -c\")\n"
648         "  --filter-extension=EXT\n"
649         "                       string to append to segment files\n"
650         "                           (defaults to \".bz2\")\n"
651         "  --signature-filter=COMMAND\n"
652         "                       program though which to filter descriptor\n"
653         "  --scheme=NAME        optional name for this snapshot\n"
654         "  --intent=FLOAT       DEPRECATED: ignored, and will be removed soon\n"
655         "  --full-metadata      do not re-use metadata from previous backups\n"
656         "  --rebuild-statcache  re-read all file data to verify statcache\n"
657         "  -v --verbose         list files as they are backed up\n"
658         "\n"
659         "Exactly one of --dest or --upload-script must be specified.\n",
660         cumulus_version, program
661     );
662 }
663
664 int main(int argc, char *argv[])
665 {
666     hash_init();
667
668     string backup_dest = "", backup_script = "";
669     string localdb_dir = "";
670     string backup_scheme = "";
671     string signature_filter = "";
672
673     string tmp_dir = "/tmp";
674     if (getenv("TMPDIR") != NULL)
675         tmp_dir = getenv("TMPDIR");
676
677     while (1) {
678         static struct option long_options[] = {
679             {"localdb", 1, 0, 0},           // 0
680             {"filter", 1, 0, 0},            // 1
681             {"filter-extension", 1, 0, 0},  // 2
682             {"dest", 1, 0, 0},              // 3
683             {"scheme", 1, 0, 0},            // 4
684             {"signature-filter", 1, 0, 0},  // 5
685             {"intent", 1, 0, 0},            // 6, DEPRECATED
686             {"full-metadata", 0, 0, 0},     // 7
687             {"tmpdir", 1, 0, 0},            // 8
688             {"upload-script", 1, 0, 0},     // 9
689             {"rebuild-statcache", 0, 0, 0}, // 10
690             {"include", 1, 0, 0},           // 11
691             {"exclude", 1, 0, 0},           // 12
692             {"dir-merge", 1, 0, 0},         // 13
693             // Aliases for short options
694             {"verbose", 0, 0, 'v'},
695             {NULL, 0, 0, 0},
696         };
697
698         int long_index;
699         int c = getopt_long(argc, argv, "v", long_options, &long_index);
700
701         if (c == -1)
702             break;
703
704         if (c == 0) {
705             switch (long_index) {
706             case 0:     // --localdb
707                 localdb_dir = optarg;
708                 break;
709             case 1:     // --filter
710                 filter_program = optarg;
711                 break;
712             case 2:     // --filter-extension
713                 filter_extension = optarg;
714                 break;
715             case 3:     // --dest
716                 backup_dest = optarg;
717                 break;
718             case 4:     // --scheme
719                 backup_scheme = optarg;
720                 break;
721             case 5:     // --signature-filter
722                 signature_filter = optarg;
723                 break;
724             case 6:     // --intent
725                 fprintf(stderr,
726                         "Warning: The --intent= option is deprecated and will "
727                         "be removed in the future.\n");
728                 break;
729             case 7:     // --full-metadata
730                 flag_full_metadata = true;
731                 break;
732             case 8:     // --tmpdir
733                 tmp_dir = optarg;
734                 break;
735             case 9:     // --upload-script
736                 backup_script = optarg;
737                 break;
738             case 10:    // --rebuild-statcache
739                 flag_rebuild_statcache = true;
740                 break;
741             case 11:    // --include
742                 filter_rules.add_pattern(PathFilterList::INCLUDE, optarg, "");
743                 break;
744             case 12:    // --exclude
745                 filter_rules.add_pattern(PathFilterList::EXCLUDE, optarg, "");
746                 break;
747             case 13:    // --dir-merge
748                 filter_rules.add_pattern(PathFilterList::DIRMERGE, optarg, "");
749                 break;
750             default:
751                 fprintf(stderr, "Unhandled long option!\n");
752                 return 1;
753             }
754         } else {
755             switch (c) {
756             case 'v':
757                 verbose = true;
758                 break;
759             default:
760                 usage(argv[0]);
761                 return 1;
762             }
763         }
764     }
765
766     if (optind == argc) {
767         usage(argv[0]);
768         return 1;
769     }
770
771     if (backup_dest == "" && backup_script == "") {
772         fprintf(stderr,
773                 "Error: Backup destination must be specified using --dest= or --upload-script=\n");
774         usage(argv[0]);
775         return 1;
776     }
777
778     if (backup_dest != "" && backup_script != "") {
779         fprintf(stderr,
780                 "Error: Cannot specify both --dest= and --upload-script=\n");
781         usage(argv[0]);
782         return 1;
783     }
784
785     // Default for --localdb is the same as --dest
786     if (localdb_dir == "") {
787         localdb_dir = backup_dest;
788     }
789     if (localdb_dir == "") {
790         fprintf(stderr,
791                 "Error: Must specify local database path with --localdb=\n");
792         usage(argv[0]);
793         return 1;
794     }
795
796     block_buf = new char[LBS_BLOCK_SIZE];
797
798     /* Initialize the remote storage layer.  If using an upload script, create
799      * a temporary directory for staging files.  Otherwise, write backups
800      * directly to the destination directory. */
801     if (backup_script != "") {
802         tmp_dir = tmp_dir + "/cumulus." + generate_uuid();
803         if (mkdir(tmp_dir.c_str(), 0700) < 0) {
804             fprintf(stderr, "Cannot create temporary directory %s: %m\n",
805                     tmp_dir.c_str());
806             return 1;
807         }
808         remote = new RemoteStore(tmp_dir, backup_script=backup_script);
809     } else {
810         remote = new RemoteStore(backup_dest);
811     }
812
813     /* Store the time when the backup started, so it can be included in the
814      * snapshot name. */
815     time_t now;
816     time(&now);
817     string timestamp
818         = TimeFormat::format(now, TimeFormat::FORMAT_FILENAME, true);
819
820     /* Open the local database which tracks all objects that are stored
821      * remotely, for efficient incrementals.  Provide it with the name of this
822      * snapshot. */
823     string database_path = localdb_dir + "/localdb.sqlite";
824     db = new LocalDb;
825     db->Open(database_path.c_str(), timestamp.c_str(), backup_scheme.c_str());
826
827     tss = new TarSegmentStore(remote, db);
828
829     /* Initialize the stat cache, for skipping over unchanged files. */
830     metawriter = new MetadataWriter(tss, localdb_dir.c_str(), timestamp.c_str(),
831                                     backup_scheme.c_str());
832
833     for (int i = optind; i < argc; i++) {
834         scanfile(argv[i]);
835     }
836
837     ObjectReference root_ref = metawriter->close();
838     string backup_root = root_ref.to_string();
839
840     delete metawriter;
841
842     tss->sync();
843     tss->dump_stats();
844     delete tss;
845
846     /* Write out a checksums file which lists the checksums for all the
847      * segments included in this snapshot.  The format is designed so that it
848      * may be easily verified using the sha1sums command. */
849     const char csum_type[] = "sha1";
850     string checksum_filename = "snapshot-";
851     if (backup_scheme.size() > 0)
852         checksum_filename += backup_scheme + "-";
853     checksum_filename
854         = checksum_filename + timestamp + "." + csum_type + "sums";
855     RemoteFile *checksum_file = remote->alloc_file(checksum_filename,
856                                                    "meta");
857     FILE *checksums = fdopen(checksum_file->get_fd(), "w");
858
859     std::set<string> segment_list = db->GetUsedSegments();
860     for (std::set<string>::iterator i = segment_list.begin();
861          i != segment_list.end(); ++i) {
862         map<string, string> segment_metadata = db->GetSegmentMetadata(*i);
863         if (segment_metadata.count("path")
864             && segment_metadata.count("checksum"))
865         {
866             string seg_path = segment_metadata["path"];
867             string seg_csum = segment_metadata["checksum"];
868             const char *raw_checksum = NULL;
869             if (strncmp(seg_csum.c_str(), csum_type,
870                         strlen(csum_type)) == 0) {
871                 raw_checksum = seg_csum.c_str() + strlen(csum_type);
872                 if (*raw_checksum == '=')
873                     raw_checksum++;
874                 else
875                     raw_checksum = NULL;
876             }
877
878             if (raw_checksum != NULL)
879                 fprintf(checksums, "%s *%s\n",
880                         raw_checksum, seg_path.c_str());
881         }
882     }
883     fclose(checksums);
884
885     SHA1Checksum checksum_csum;
886     string csum;
887     checksum_filename = checksum_file->get_local_path();
888     if (checksum_csum.process_file(checksum_filename.c_str())) {
889         csum = checksum_csum.checksum_str();
890     }
891
892     checksum_file->send();
893
894     /* Write out a summary file with metadata for all the segments in this
895      * snapshot (can be used to reconstruct database contents if needed). */
896     string dbmeta_filename = "snapshot-";
897     if (backup_scheme.size() > 0)
898         dbmeta_filename += backup_scheme + "-";
899     dbmeta_filename += timestamp + ".meta" + filter_extension;
900     RemoteFile *dbmeta_file = remote->alloc_file(dbmeta_filename, "meta");
901     FileFilter *dbmeta_filter = FileFilter::New(dbmeta_file->get_fd(),
902                                                 filter_program);
903     if (dbmeta_filter == NULL) {
904         fprintf(stderr, "Unable to open descriptor output file: %m\n");
905         return 1;
906     }
907     FILE *dbmeta = fdopen(dbmeta_filter->get_wrapped_fd(), "w");
908
909     for (std::set<string>::iterator i = segment_list.begin();
910          i != segment_list.end(); ++i) {
911         map<string, string> segment_metadata = db->GetSegmentMetadata(*i);
912         if (segment_metadata.size() > 0) {
913             map<string, string>::const_iterator j;
914             for (j = segment_metadata.begin();
915                  j != segment_metadata.end(); ++j)
916             {
917                 fprintf(dbmeta, "%s: %s\n",
918                         j->first.c_str(), j->second.c_str());
919             }
920             fprintf(dbmeta, "\n");
921         }
922     }
923     fclose(dbmeta);
924
925     string dbmeta_csum
926         = Hash::hash_file(dbmeta_file->get_local_path().c_str());
927     dbmeta_file->send();
928
929     db->Close();
930
931     /* All other files should be flushed to remote storage before writing the
932      * backup descriptor below, so that it is not possible to have a backup
933      * descriptor written out depending on non-existent (not yet written)
934      * files. */
935     remote->sync();
936
937     /* Write a backup descriptor file, which says which segments are needed and
938      * where to start to restore this snapshot.  The filename is based on the
939      * current time.  If a signature filter program was specified, filter the
940      * data through that to give a chance to sign the descriptor contents. */
941     string desc_filename = "snapshot-";
942     if (backup_scheme.size() > 0)
943         desc_filename += backup_scheme + "-";
944     desc_filename = desc_filename + timestamp + ".cumulus";
945
946     RemoteFile *descriptor_file = remote->alloc_file(desc_filename,
947                                                      "snapshots");
948     FileFilter *descriptor_filter = FileFilter::New(descriptor_file->get_fd(),
949                                                     signature_filter.c_str());
950     if (descriptor_filter == NULL) {
951         fprintf(stderr, "Unable to open descriptor output file: %m\n");
952         return 1;
953     }
954     FILE *descriptor = fdopen(descriptor_filter->get_wrapped_fd(), "w");
955
956     fprintf(descriptor, "Format: Cumulus Snapshot v0.11\n");
957     fprintf(descriptor, "Producer: Cumulus %s\n", cumulus_version);
958     string timestamp_local
959         = TimeFormat::format(now, TimeFormat::FORMAT_LOCALTIME, false);
960     fprintf(descriptor, "Date: %s\n", timestamp_local.c_str());
961     if (backup_scheme.size() > 0)
962         fprintf(descriptor, "Scheme: %s\n", backup_scheme.c_str());
963     fprintf(descriptor, "Root: %s\n", backup_root.c_str());
964
965     if (dbmeta_csum.size() > 0) {
966         fprintf(descriptor, "Database-state: %s\n", dbmeta_csum.c_str());
967     }
968
969     if (csum.size() > 0) {
970         fprintf(descriptor, "Checksums: %s\n", csum.c_str());
971     }
972
973     fprintf(descriptor, "Segments:\n");
974     for (std::set<string>::iterator i = segment_list.begin();
975          i != segment_list.end(); ++i) {
976         fprintf(descriptor, "    %s\n", i->c_str());
977     }
978
979     fclose(descriptor);
980     if (descriptor_filter->wait() < 0) {
981         fatal("Signature filter process error");
982     }
983
984     descriptor_file->send();
985
986     remote->sync();
987     delete remote;
988
989     if (backup_script != "") {
990         if (rmdir(tmp_dir.c_str()) < 0) {
991             fprintf(stderr,
992                     "Warning: Cannot delete temporary directory %s: %m\n",
993                     tmp_dir.c_str());
994         }
995     }
996
997     return 0;
998 }