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