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