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