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