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