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