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