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