Drop intent field from the database.
[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                         char group[32];
296                         sprintf(group, "compacted-%d", object_group);
297                         o->set_group(group);
298                     }
299                     if (status == NULL)
300                         status = "partial";
301                 } else {
302                     o->set_group("data");
303                     status = "new";
304                 }
305
306                 subfile.analyze_new_block(block_buf, bytes);
307                 refs = subfile.create_incremental(tss, o, block_age);
308             } else {
309                 if (flag_rebuild_statcache && ref.is_normal()) {
310                     subfile.analyze_new_block(block_buf, bytes);
311                     subfile.store_analyzed_signatures(ref);
312                 }
313                 refs.push_back(ref);
314             }
315
316             while (!refs.empty()) {
317                 ref = refs.front(); refs.pop_front();
318                 object_list.push_back(ref.to_string());
319                 db->UseObject(ref);
320             }
321             size += bytes;
322
323             if (status == NULL)
324                 status = "old";
325         }
326
327         file_info["checksum"] = hash->digest_str();
328         delete hash;
329     }
330
331     // Sanity check: if we are rebuilding the statcache, but the file looks
332     // like it hasn't changed, then the newly-computed checksum should match
333     // the checksum in the statcache.  If not, we have possible disk corruption
334     // and report a warning.
335     if (flag_rebuild_statcache) {
336         if (found
337             && metawriter->is_unchanged(&stat_buf)
338             && file_info["checksum"] != metawriter->get_checksum()) {
339             fprintf(stderr,
340                     "Warning: Checksum for %s does not match expected value\n"
341                     "    expected: %s\n"
342                     "    actual:   %s\n",
343                     path.c_str(),
344                     metawriter->get_checksum().c_str(),
345                     file_info["checksum"].c_str());
346         }
347     }
348
349     if (verbose && status != NULL)
350         printf("    [%s]\n", status);
351
352     string blocklist = "";
353     for (list<string>::iterator i = object_list.begin();
354          i != object_list.end(); ++i) {
355         if (i != object_list.begin())
356             blocklist += "\n    ";
357         blocklist += *i;
358     }
359     file_info["data"] = blocklist;
360
361     return size;
362 }
363
364 /* Look up a user/group and convert it to string form (either strictly numeric
365  * or numeric plus symbolic).  Caches the results of the call to
366  * getpwuid/getgrgid. */
367 string user_to_string(uid_t uid) {
368     static map<uid_t, string> user_cache;
369     map<uid_t, string>::const_iterator i = user_cache.find(uid);
370     if (i != user_cache.end())
371         return i->second;
372
373     string result = encode_int(uid);
374     struct passwd *pwd = getpwuid(uid);
375     if (pwd != NULL && pwd->pw_name != NULL) {
376         result += " (" + uri_encode(pwd->pw_name) + ")";
377     }
378     user_cache[uid] = result;
379     return result;
380 }
381
382 string group_to_string(gid_t gid) {
383     static map<gid_t, string> group_cache;
384     map<gid_t, string>::const_iterator i = group_cache.find(gid);
385     if (i != group_cache.end())
386         return i->second;
387
388     string result = encode_int(gid);
389     struct group *grp = getgrgid(gid);
390     if (grp != NULL && grp->gr_name != NULL) {
391         result += " (" + uri_encode(grp->gr_name) + ")";
392     }
393     group_cache[gid] = result;
394     return result;
395 }
396
397 /* Dump a specified filesystem object (file, directory, etc.) based on its
398  * inode information.  If the object is a regular file, an open filehandle is
399  * provided. */
400 void dump_inode(const string& path,         // Path within snapshot
401                 const string& fullpath,     // Path to object in filesystem
402                 struct stat& stat_buf,      // Results of stat() call
403                 int fd)                     // Open filehandle if regular file
404 {
405     char *buf;
406     dictionary file_info;
407     int64_t file_size;
408     ssize_t len;
409
410     if (verbose)
411         printf("%s\n", path.c_str());
412     metawriter->find(path);
413
414     file_info["name"] = uri_encode(path);
415     file_info["mode"] = encode_int(stat_buf.st_mode & 07777, 8);
416     file_info["ctime"] = encode_int(stat_buf.st_ctime);
417     file_info["mtime"] = encode_int(stat_buf.st_mtime);
418     file_info["user"] = user_to_string(stat_buf.st_uid);
419     file_info["group"] = group_to_string(stat_buf.st_gid);
420
421     time_t now = time(NULL);
422     if (now - stat_buf.st_ctime < 30 || now - stat_buf.st_mtime < 30)
423         if ((stat_buf.st_mode & S_IFMT) != S_IFDIR)
424             file_info["volatile"] = "1";
425
426     if (stat_buf.st_nlink > 1 && (stat_buf.st_mode & S_IFMT) != S_IFDIR) {
427         file_info["links"] = encode_int(stat_buf.st_nlink);
428     }
429
430     file_info["inode"] = encode_int(major(stat_buf.st_dev))
431         + "/" + encode_int(minor(stat_buf.st_dev))
432         + "/" + encode_int(stat_buf.st_ino);
433
434     char inode_type;
435
436     switch (stat_buf.st_mode & S_IFMT) {
437     case S_IFIFO:
438         inode_type = 'p';
439         break;
440     case S_IFSOCK:
441         inode_type = 's';
442         break;
443     case S_IFBLK:
444     case S_IFCHR:
445         inode_type = ((stat_buf.st_mode & S_IFMT) == S_IFBLK) ? 'b' : 'c';
446         file_info["device"] = encode_int(major(stat_buf.st_rdev))
447             + "/" + encode_int(minor(stat_buf.st_rdev));
448         break;
449     case S_IFLNK:
450         inode_type = 'l';
451
452         /* Use the reported file size to allocate a buffer large enough to read
453          * the symlink.  Allocate slightly more space, so that we ask for more
454          * bytes than we expect and so check for truncation. */
455         buf = new char[stat_buf.st_size + 2];
456         len = readlink(fullpath.c_str(), buf, stat_buf.st_size + 1);
457         if (len < 0) {
458             fprintf(stderr, "error reading symlink: %m\n");
459         } else if (len <= stat_buf.st_size) {
460             buf[len] = '\0';
461             file_info["target"] = uri_encode(buf);
462         } else if (len > stat_buf.st_size) {
463             fprintf(stderr, "error reading symlink: name truncated\n");
464         }
465
466         delete[] buf;
467         break;
468     case S_IFREG:
469         inode_type = 'f';
470
471         file_size = dumpfile(fd, file_info, path, stat_buf);
472         file_info["size"] = encode_int(file_size);
473
474         if (file_size < 0)
475             return;             // error occurred; do not dump file
476
477         if (file_size != stat_buf.st_size) {
478             fprintf(stderr, "Warning: Size of %s changed during reading\n",
479                     path.c_str());
480             file_info["volatile"] = "1";
481         }
482
483         break;
484     case S_IFDIR:
485         inode_type = 'd';
486         break;
487
488     default:
489         fprintf(stderr, "Unknown inode type: mode=%x\n", stat_buf.st_mode);
490         return;
491     }
492
493     file_info["type"] = string(1, inode_type);
494
495     metawriter->add(file_info);
496 }
497
498 /* Converts a path to the normalized form used in the metadata log.  Paths are
499  * written as relative (without any leading slashes).  The root directory is
500  * referred to as ".". */
501 string metafile_path(const string& path)
502 {
503     const char *newpath = path.c_str();
504     if (*newpath == '/')
505         newpath++;
506     if (*newpath == '\0')
507         newpath = ".";
508     return newpath;
509 }
510
511 void try_merge_filter(const string& path, const string& basedir)
512 {
513     struct stat stat_buf;
514     if (lstat(path.c_str(), &stat_buf) < 0)
515         return;
516     if ((stat_buf.st_mode & S_IFMT) != S_IFREG)
517         return;
518     int fd = safe_open(path, NULL);
519     if (fd < 0)
520         return;
521
522     /* As a very crude limit on the complexity of merge rules, only read up to
523      * one block (1 MB) worth of data.  If the file doesn't seems like it might
524      * be larger than that, don't parse the rules in it. */
525     ssize_t bytes = file_read(fd, block_buf, LBS_BLOCK_SIZE);
526     close(fd);
527     if (bytes < 0 || bytes >= static_cast<ssize_t>(LBS_BLOCK_SIZE - 1)) {
528         /* TODO: Add more strict resource limits on merge files? */
529         fprintf(stderr,
530                 "Unable to read filter merge file (possibly size too large\n");
531         return;
532     }
533     filter_rules.merge_patterns(metafile_path(path), basedir,
534                                 string(block_buf, bytes));
535 }
536
537 void scanfile(const string& path)
538 {
539     int fd = -1;
540     struct stat stat_buf;
541     list<string> refs;
542
543     string output_path = metafile_path(path);
544
545     if (lstat(path.c_str(), &stat_buf) < 0) {
546         fprintf(stderr, "lstat(%s): %m\n", path.c_str());
547         return;
548     }
549
550     bool is_directory = ((stat_buf.st_mode & S_IFMT) == S_IFDIR);
551     if (!filter_rules.is_included(output_path, is_directory))
552         return;
553
554     if ((stat_buf.st_mode & S_IFMT) == S_IFREG) {
555         fd = safe_open(path, &stat_buf);
556         if (fd < 0)
557             return;
558     }
559
560     dump_inode(output_path, path, stat_buf, fd);
561
562     if (fd >= 0)
563         close(fd);
564
565     /* If we hit a directory, now that we've written the directory itself,
566      * recursively scan the directory. */
567     if (is_directory) {
568         DIR *dir = opendir(path.c_str());
569
570         if (dir == NULL) {
571             fprintf(stderr, "Error reading directory %s: %m\n",
572                     path.c_str());
573             return;
574         }
575
576         struct dirent *ent;
577         vector<string> contents;
578         while ((ent = readdir(dir)) != NULL) {
579             string filename(ent->d_name);
580             if (filename == "." || filename == "..")
581                 continue;
582             contents.push_back(filename);
583         }
584
585         closedir(dir);
586
587         sort(contents.begin(), contents.end());
588
589         filter_rules.save();
590
591         /* First pass through the directory items: look for any filter rules to
592          * merge and do so. */
593         for (vector<string>::iterator i = contents.begin();
594              i != contents.end(); ++i) {
595             string filename;
596             if (path == ".")
597                 filename = *i;
598             else if (path == "/")
599                 filename = "/" + *i;
600             else
601                 filename = path + "/" + *i;
602             if (filter_rules.is_mergefile(metafile_path(filename))) {
603                 if (verbose) {
604                     printf("Merging directory filter rules %s\n",
605                            filename.c_str());
606                 }
607                 try_merge_filter(filename, output_path);
608             }
609         }
610
611         /* Second pass: recursively scan all items in the directory for backup;
612          * scanfile() will check if the item should be included or not. */
613         for (vector<string>::iterator i = contents.begin();
614              i != contents.end(); ++i) {
615             const string& filename = *i;
616             if (path == ".")
617                 scanfile(filename);
618             else if (path == "/")
619                 scanfile("/" + filename);
620             else
621                 scanfile(path + "/" + filename);
622         }
623
624         filter_rules.restore();
625     }
626 }
627
628 void usage(const char *program)
629 {
630     fprintf(
631         stderr,
632         "Cumulus %s\n\n"
633         "Usage: %s [OPTION]... --dest=DEST PATHS...\n"
634         "Produce backup snapshot of files in SOURCE and store to DEST.\n"
635         "\n"
636         "Options:\n"
637         "  --dest=PATH          path where backup is to be written\n"
638         "  --upload-script=COMMAND\n"
639         "                       program to invoke for each backup file generated\n"
640         "  --exclude=PATTERN    exclude files matching PATTERN from snapshot\n"
641         "  --include=PATTERN    include files matching PATTERN in snapshot\n"
642         "  --dir-merge=PATTERN  parse files matching PATTERN to read additional\n"
643         "                       subtree-specific include/exclude rules during backup\n"
644         "  --localdb=PATH       local backup metadata is stored in PATH\n"
645         "  --tmpdir=PATH        path for temporarily storing backup files\n"
646         "                           (defaults to TMPDIR environment variable or /tmp)\n"
647         "  --filter=COMMAND     program through which to filter segment data\n"
648         "                           (defaults to \"bzip2 -c\")\n"
649         "  --filter-extension=EXT\n"
650         "                       string to append to segment files\n"
651         "                           (defaults to \".bz2\")\n"
652         "  --signature-filter=COMMAND\n"
653         "                       program though which to filter descriptor\n"
654         "  --scheme=NAME        optional name for this snapshot\n"
655         "  --intent=FLOAT       DEPRECATED: ignored, and will be removed soon\n"
656         "  --full-metadata      do not re-use metadata from previous backups\n"
657         "  --rebuild-statcache  re-read all file data to verify statcache\n"
658         "  -v --verbose         list files as they are backed up\n"
659         "\n"
660         "Exactly one of --dest or --upload-script must be specified.\n",
661         cumulus_version, program
662     );
663 }
664
665 int main(int argc, char *argv[])
666 {
667     hash_init();
668
669     string backup_dest = "", backup_script = "";
670     string localdb_dir = "";
671     string backup_scheme = "";
672     string signature_filter = "";
673
674     string tmp_dir = "/tmp";
675     if (getenv("TMPDIR") != NULL)
676         tmp_dir = getenv("TMPDIR");
677
678     while (1) {
679         static struct option long_options[] = {
680             {"localdb", 1, 0, 0},           // 0
681             {"filter", 1, 0, 0},            // 1
682             {"filter-extension", 1, 0, 0},  // 2
683             {"dest", 1, 0, 0},              // 3
684             {"scheme", 1, 0, 0},            // 4
685             {"signature-filter", 1, 0, 0},  // 5
686             {"intent", 1, 0, 0},            // 6, DEPRECATED
687             {"full-metadata", 0, 0, 0},     // 7
688             {"tmpdir", 1, 0, 0},            // 8
689             {"upload-script", 1, 0, 0},     // 9
690             {"rebuild-statcache", 0, 0, 0}, // 10
691             {"include", 1, 0, 0},           // 11
692             {"exclude", 1, 0, 0},           // 12
693             {"dir-merge", 1, 0, 0},         // 13
694             // Aliases for short options
695             {"verbose", 0, 0, 'v'},
696             {NULL, 0, 0, 0},
697         };
698
699         int long_index;
700         int c = getopt_long(argc, argv, "v", long_options, &long_index);
701
702         if (c == -1)
703             break;
704
705         if (c == 0) {
706             switch (long_index) {
707             case 0:     // --localdb
708                 localdb_dir = optarg;
709                 break;
710             case 1:     // --filter
711                 filter_program = optarg;
712                 break;
713             case 2:     // --filter-extension
714                 filter_extension = optarg;
715                 break;
716             case 3:     // --dest
717                 backup_dest = optarg;
718                 break;
719             case 4:     // --scheme
720                 backup_scheme = optarg;
721                 break;
722             case 5:     // --signature-filter
723                 signature_filter = optarg;
724                 break;
725             case 6:     // --intent
726                 fprintf(stderr,
727                         "Warning: The --intent= option is deprecated and will "
728                         "be removed in the future.\n");
729                 break;
730             case 7:     // --full-metadata
731                 flag_full_metadata = true;
732                 break;
733             case 8:     // --tmpdir
734                 tmp_dir = optarg;
735                 break;
736             case 9:     // --upload-script
737                 backup_script = optarg;
738                 break;
739             case 10:    // --rebuild-statcache
740                 flag_rebuild_statcache = true;
741                 break;
742             case 11:    // --include
743                 filter_rules.add_pattern(PathFilterList::INCLUDE, optarg, "");
744                 break;
745             case 12:    // --exclude
746                 filter_rules.add_pattern(PathFilterList::EXCLUDE, optarg, "");
747                 break;
748             case 13:    // --dir-merge
749                 filter_rules.add_pattern(PathFilterList::DIRMERGE, optarg, "");
750                 break;
751             default:
752                 fprintf(stderr, "Unhandled long option!\n");
753                 return 1;
754             }
755         } else {
756             switch (c) {
757             case 'v':
758                 verbose = true;
759                 break;
760             default:
761                 usage(argv[0]);
762                 return 1;
763             }
764         }
765     }
766
767     if (optind == argc) {
768         usage(argv[0]);
769         return 1;
770     }
771
772     if (backup_dest == "" && backup_script == "") {
773         fprintf(stderr,
774                 "Error: Backup destination must be specified using --dest= or --upload-script=\n");
775         usage(argv[0]);
776         return 1;
777     }
778
779     if (backup_dest != "" && backup_script != "") {
780         fprintf(stderr,
781                 "Error: Cannot specify both --dest= and --upload-script=\n");
782         usage(argv[0]);
783         return 1;
784     }
785
786     // Default for --localdb is the same as --dest
787     if (localdb_dir == "") {
788         localdb_dir = backup_dest;
789     }
790     if (localdb_dir == "") {
791         fprintf(stderr,
792                 "Error: Must specify local database path with --localdb=\n");
793         usage(argv[0]);
794         return 1;
795     }
796
797     block_buf = new char[LBS_BLOCK_SIZE];
798
799     /* Initialize the remote storage layer.  If using an upload script, create
800      * a temporary directory for staging files.  Otherwise, write backups
801      * directly to the destination directory. */
802     if (backup_script != "") {
803         tmp_dir = tmp_dir + "/cumulus." + generate_uuid();
804         if (mkdir(tmp_dir.c_str(), 0700) < 0) {
805             fprintf(stderr, "Cannot create temporary directory %s: %m\n",
806                     tmp_dir.c_str());
807             return 1;
808         }
809         remote = new RemoteStore(tmp_dir, backup_script=backup_script);
810     } else {
811         remote = new RemoteStore(backup_dest);
812     }
813
814     /* Store the time when the backup started, so it can be included in the
815      * snapshot name. */
816     time_t now;
817     struct tm time_buf_local, time_buf_utc;
818     char desc_buf[256];
819     time(&now);
820     localtime_r(&now, &time_buf_local);
821     gmtime_r(&now, &time_buf_utc);
822     strftime(desc_buf, sizeof(desc_buf), "%Y%m%dT%H%M%S", &time_buf_utc);
823
824     /* Open the local database which tracks all objects that are stored
825      * remotely, for efficient incrementals.  Provide it with the name of this
826      * snapshot. */
827     string database_path = localdb_dir + "/localdb.sqlite";
828     db = new LocalDb;
829     db->Open(database_path.c_str(), desc_buf, backup_scheme.c_str());
830
831     tss = new TarSegmentStore(remote, db);
832
833     /* Initialize the stat cache, for skipping over unchanged files. */
834     metawriter = new MetadataWriter(tss, localdb_dir.c_str(), desc_buf,
835                                     backup_scheme.c_str());
836
837     for (int i = optind; i < argc; i++) {
838         scanfile(argv[i]);
839     }
840
841     ObjectReference root_ref = metawriter->close();
842     string backup_root = root_ref.to_string();
843
844     delete metawriter;
845
846     tss->sync();
847     tss->dump_stats();
848     delete tss;
849
850     /* Write out a checksums file which lists the checksums for all the
851      * segments included in this snapshot.  The format is designed so that it
852      * may be easily verified using the sha1sums command. */
853     const char csum_type[] = "sha1";
854     string checksum_filename = "snapshot-";
855     if (backup_scheme.size() > 0)
856         checksum_filename += backup_scheme + "-";
857     checksum_filename = checksum_filename + desc_buf + "." + csum_type + "sums";
858     RemoteFile *checksum_file = remote->alloc_file(checksum_filename,
859                                                    "meta");
860     FILE *checksums = fdopen(checksum_file->get_fd(), "w");
861
862     std::set<string> segment_list = db->GetUsedSegments();
863     for (std::set<string>::iterator i = segment_list.begin();
864          i != segment_list.end(); ++i) {
865         string seg_path, seg_csum;
866         if (db->GetSegmentMetadata(*i, &seg_path, &seg_csum)) {
867             const char *raw_checksum = NULL;
868             if (strncmp(seg_csum.c_str(), csum_type,
869                         strlen(csum_type)) == 0) {
870                 raw_checksum = seg_csum.c_str() + strlen(csum_type);
871                 if (*raw_checksum == '=')
872                     raw_checksum++;
873                 else
874                     raw_checksum = NULL;
875             }
876
877             if (raw_checksum != NULL)
878                 fprintf(checksums, "%s *%s\n",
879                         raw_checksum, seg_path.c_str());
880         }
881     }
882     fclose(checksums);
883
884     SHA1Checksum checksum_csum;
885     string csum;
886     checksum_filename = checksum_file->get_local_path();
887     if (checksum_csum.process_file(checksum_filename.c_str())) {
888         csum = checksum_csum.checksum_str();
889     }
890
891     checksum_file->send();
892
893     db->Close();
894
895     /* All other files should be flushed to remote storage before writing the
896      * backup descriptor below, so that it is not possible to have a backup
897      * descriptor written out depending on non-existent (not yet written)
898      * files. */
899     remote->sync();
900
901     /* Write a backup descriptor file, which says which segments are needed and
902      * where to start to restore this snapshot.  The filename is based on the
903      * current time.  If a signature filter program was specified, filter the
904      * data through that to give a chance to sign the descriptor contents. */
905     string desc_filename = "snapshot-";
906     if (backup_scheme.size() > 0)
907         desc_filename += backup_scheme + "-";
908     desc_filename = desc_filename + desc_buf + ".cumulus";
909
910     RemoteFile *descriptor_file = remote->alloc_file(desc_filename,
911                                                      "snapshots");
912     int descriptor_fd = descriptor_file->get_fd();
913     if (descriptor_fd < 0) {
914         fprintf(stderr, "Unable to open descriptor output file: %m\n");
915         return 1;
916     }
917     pid_t signature_pid = 0;
918     if (signature_filter.size() > 0) {
919         int new_fd = spawn_filter(descriptor_fd, signature_filter.c_str(),
920                                   &signature_pid);
921         close(descriptor_fd);
922         descriptor_fd = new_fd;
923     }
924     FILE *descriptor = fdopen(descriptor_fd, "w");
925
926     fprintf(descriptor, "Format: Cumulus Snapshot v0.11\n");
927     fprintf(descriptor, "Producer: Cumulus %s\n", cumulus_version);
928     strftime(desc_buf, sizeof(desc_buf), "%Y-%m-%d %H:%M:%S %z",
929              &time_buf_local);
930     fprintf(descriptor, "Date: %s\n", desc_buf);
931     if (backup_scheme.size() > 0)
932         fprintf(descriptor, "Scheme: %s\n", backup_scheme.c_str());
933     fprintf(descriptor, "Root: %s\n", backup_root.c_str());
934
935     if (csum.size() > 0) {
936         fprintf(descriptor, "Checksums: %s\n", csum.c_str());
937     }
938
939     fprintf(descriptor, "Segments:\n");
940     for (std::set<string>::iterator i = segment_list.begin();
941          i != segment_list.end(); ++i) {
942         fprintf(descriptor, "    %s\n", i->c_str());
943     }
944
945     fclose(descriptor);
946
947     if (signature_pid) {
948         int status;
949         waitpid(signature_pid, &status, 0);
950
951         if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) {
952             fatal("Signature filter process error");
953         }
954     }
955
956     descriptor_file->send();
957
958     remote->sync();
959     delete remote;
960
961     if (backup_script != "") {
962         if (rmdir(tmp_dir.c_str()) < 0) {
963             fprintf(stderr,
964                     "Warning: Cannot delete temporary directory %s: %m\n",
965                     tmp_dir.c_str());
966         }
967     }
968
969     return 0;
970 }