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