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