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