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