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