Remove some debugging output so backup runs are less verbose.
[cumulus.git] / scandir.cc
1 /* Cumulus: Smart Filesystem Backup to Dumb Servers
2  *
3  * Copyright (C) 2006-2008  The Regents of the University of California
4  * Written by Michael Vrable <mvrable@cs.ucsd.edu>
5  *
6  * This program is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License as published by
8  * the Free Software Foundation; either version 2 of the License, or
9  * (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License along
17  * with this program; if not, write to the Free Software Foundation, Inc.,
18  * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
19  */
20
21 /* Main entry point for LBS.  Contains logic for traversing the filesystem and
22  * constructing a backup. */
23
24 #include <dirent.h>
25 #include <errno.h>
26 #include <fcntl.h>
27 #include <getopt.h>
28 #include <grp.h>
29 #include <pwd.h>
30 #include <stdint.h>
31 #include <stdio.h>
32 #include <stdlib.h>
33 #include <sys/stat.h>
34 #include <sys/sysmacros.h>
35 #include <sys/types.h>
36 #include <sys/wait.h>
37 #include <unistd.h>
38
39 #include <algorithm>
40 #include <fstream>
41 #include <iostream>
42 #include <list>
43 #include <set>
44 #include <sstream>
45 #include <string>
46 #include <vector>
47
48 #include "localdb.h"
49 #include "metadata.h"
50 #include "remote.h"
51 #include "store.h"
52 #include "sha1.h"
53 #include "util.h"
54
55 using std::list;
56 using std::string;
57 using std::vector;
58 using std::ostream;
59
60 /* Version information.  This will be filled in by the Makefile. */
61 #ifndef LBS_VERSION
62 #define LBS_VERSION Unknown
63 #endif
64 #define LBS_STRINGIFY(s) LBS_STRINGIFY2(s)
65 #define LBS_STRINGIFY2(s) #s
66 static const char lbs_version[] = LBS_STRINGIFY(LBS_VERSION);
67
68 static RemoteStore *remote = NULL;
69 static TarSegmentStore *tss = NULL;
70 static MetadataWriter *metawriter = NULL;
71
72 /* Buffer for holding a single block of data read from a file. */
73 static const size_t LBS_BLOCK_SIZE = 1024 * 1024;
74 static char *block_buf;
75
76 /* Local database, which tracks objects written in this and previous
77  * invocations to help in creating incremental snapshots. */
78 LocalDb *db;
79
80 /* Keep track of all segments which are needed to reconstruct the snapshot. */
81 std::set<string> segment_list;
82
83 /* Snapshot intent: 1=daily, 7=weekly, etc.  This is not used directly, but is
84  * stored in the local database and can help guide segment cleaning and
85  * snapshot expiration policies. */
86 double snapshot_intent = 1.0;
87
88 /* Selection of files to include/exclude in the snapshot. */
89 std::list<string> includes;         // Paths in which files should be saved
90 std::list<string> excludes;         // Paths which will not be saved
91 std::list<string> searches;         // Directories we don't want to save, but
92                                     //   do want to descend searching for data
93                                     //   in included paths
94
95 bool relative_paths = true;
96
97 /* Ensure that the given segment is listed as a dependency of the current
98  * snapshot. */
99 void add_segment(const string& segment)
100 {
101     segment_list.insert(segment);
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 (metawriter->find(path) && metawriter->is_unchanged(&stat_buf)) {
146         cached = true;
147         list<ObjectReference> blocks = metawriter->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"] = metawriter->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                 if (ref.is_normal())
169                     add_segment(ref.get_segment());
170                 db->UseObject(ref);
171             }
172             size = stat_buf.st_size;
173         }
174     }
175
176     /* If the file is new or changed, we must read in the contents a block at a
177      * time. */
178     if (!cached) {
179         SHA1Checksum hash;
180         while (true) {
181             ssize_t bytes = file_read(fd, block_buf, LBS_BLOCK_SIZE);
182             if (bytes == 0)
183                 break;
184             if (bytes < 0) {
185                 fprintf(stderr, "Backup contents for %s may be incorrect\n",
186                         path.c_str());
187                 break;
188             }
189
190             hash.process(block_buf, bytes);
191
192             // Sparse file processing: if we read a block of all zeroes, encode
193             // that explicitly.
194             bool all_zero = true;
195             for (int i = 0; i < bytes; i++) {
196                 if (block_buf[i] != 0) {
197                     all_zero = false;
198                     break;
199                 }
200             }
201
202             // Either find a copy of this block in an already-existing segment,
203             // or index it so it can be re-used in the future
204             double block_age = 0.0;
205             ObjectReference ref;
206
207             SHA1Checksum block_hash;
208             block_hash.process(block_buf, bytes);
209             string block_csum = block_hash.checksum_str();
210
211             if (all_zero) {
212                 ref = ObjectReference(ObjectReference::REF_ZERO);
213                 ref.set_range(0, bytes);
214             } else {
215                 ref = db->FindObject(block_csum, bytes);
216             }
217
218             // Store a copy of the object if one does not yet exist
219             if (ref.is_null()) {
220                 LbsObject *o = new LbsObject;
221                 int object_group;
222
223                 /* We might still have seen this checksum before, if the object
224                  * was stored at some time in the past, but we have decided to
225                  * clean the segment the object was originally stored in
226                  * (FindObject will not return such objects).  When rewriting
227                  * the object contents, put it in a separate group, so that old
228                  * objects get grouped together.  The hope is that these old
229                  * objects will continue to be used in the future, and we
230                  * obtain segments which will continue to be well-utilized.
231                  * Additionally, keep track of the age of the data by looking
232                  * up the age of the block which was expired and using that
233                  * instead of the current time. */
234                 if (db->IsOldObject(block_csum, bytes,
235                                     &block_age, &object_group)) {
236                     if (object_group == 0) {
237                         o->set_group("data");
238                     } else {
239                         char group[32];
240                         sprintf(group, "compacted-%d", object_group);
241                         o->set_group(group);
242                     }
243                     if (status == NULL)
244                         status = "partial";
245                 } else {
246                     o->set_group("data");
247                     status = "new";
248                 }
249
250                 o->set_data(block_buf, bytes);
251                 o->write(tss);
252                 ref = o->get_ref();
253                 db->StoreObject(ref, block_csum, bytes, block_age);
254                 ref.set_range(0, bytes);
255                 delete o;
256             }
257
258             object_list.push_back(ref.to_string());
259             if (ref.is_normal())
260                 add_segment(ref.get_segment());
261             db->UseObject(ref);
262             size += bytes;
263
264             if (status == NULL)
265                 status = "old";
266         }
267
268         file_info["checksum"] = hash.checksum_str();
269     }
270
271     if (status != NULL)
272         printf("    [%s]\n", status);
273
274     string blocklist = "";
275     for (list<string>::iterator i = object_list.begin();
276          i != object_list.end(); ++i) {
277         if (i != object_list.begin())
278             blocklist += "\n    ";
279         blocklist += *i;
280     }
281     file_info["data"] = blocklist;
282
283     return size;
284 }
285
286 /* Dump a specified filesystem object (file, directory, etc.) based on its
287  * inode information.  If the object is a regular file, an open filehandle is
288  * provided. */
289 void dump_inode(const string& path,         // Path within snapshot
290                 const string& fullpath,     // Path to object in filesystem
291                 struct stat& stat_buf,      // Results of stat() call
292                 int fd)                     // Open filehandle if regular file
293 {
294     char *buf;
295     dictionary file_info;
296     int64_t file_size;
297     ssize_t len;
298
299     printf("%s\n", path.c_str());
300     metawriter->find(path);
301
302     file_info["name"] = uri_encode(path);
303     file_info["mode"] = encode_int(stat_buf.st_mode & 07777, 8);
304     file_info["ctime"] = encode_int(stat_buf.st_ctime);
305     file_info["mtime"] = encode_int(stat_buf.st_mtime);
306     file_info["user"] = encode_int(stat_buf.st_uid);
307     file_info["group"] = encode_int(stat_buf.st_gid);
308
309     time_t now = time(NULL);
310     if (now - stat_buf.st_ctime < 30 || now - stat_buf.st_mtime < 30)
311         if ((stat_buf.st_mode & S_IFMT) != S_IFDIR)
312             file_info["volatile"] = "1";
313
314     struct passwd *pwd = getpwuid(stat_buf.st_uid);
315     if (pwd != NULL) {
316         file_info["user"] += " (" + uri_encode(pwd->pw_name) + ")";
317     }
318
319     struct group *grp = getgrgid(stat_buf.st_gid);
320     if (pwd != NULL) {
321         file_info["group"] += " (" + uri_encode(grp->gr_name) + ")";
322     }
323
324     if (stat_buf.st_nlink > 1 && (stat_buf.st_mode & S_IFMT) != S_IFDIR) {
325         file_info["links"] = encode_int(stat_buf.st_nlink);
326     }
327
328     file_info["inode"] = encode_int(major(stat_buf.st_dev))
329         + "/" + encode_int(minor(stat_buf.st_dev))
330         + "/" + encode_int(stat_buf.st_ino);
331
332     char inode_type;
333
334     switch (stat_buf.st_mode & S_IFMT) {
335     case S_IFIFO:
336         inode_type = 'p';
337         break;
338     case S_IFSOCK:
339         inode_type = 's';
340         break;
341     case S_IFBLK:
342     case S_IFCHR:
343         inode_type = ((stat_buf.st_mode & S_IFMT) == S_IFBLK) ? 'b' : 'c';
344         file_info["device"] = encode_int(major(stat_buf.st_rdev))
345             + "/" + encode_int(minor(stat_buf.st_rdev));
346         break;
347     case S_IFLNK:
348         inode_type = 'l';
349
350         /* Use the reported file size to allocate a buffer large enough to read
351          * the symlink.  Allocate slightly more space, so that we ask for more
352          * bytes than we expect and so check for truncation. */
353         buf = new char[stat_buf.st_size + 2];
354         len = readlink(fullpath.c_str(), buf, stat_buf.st_size + 1);
355         if (len < 0) {
356             fprintf(stderr, "error reading symlink: %m\n");
357         } else if (len <= stat_buf.st_size) {
358             buf[len] = '\0';
359             file_info["target"] = uri_encode(buf);
360         } else if (len > stat_buf.st_size) {
361             fprintf(stderr, "error reading symlink: name truncated\n");
362         }
363
364         delete[] buf;
365         break;
366     case S_IFREG:
367         inode_type = 'f';
368
369         file_size = dumpfile(fd, file_info, path, stat_buf);
370         file_info["size"] = encode_int(file_size);
371
372         if (file_size < 0)
373             return;             // error occurred; do not dump file
374
375         if (file_size != stat_buf.st_size) {
376             fprintf(stderr, "Warning: Size of %s changed during reading\n",
377                     path.c_str());
378             file_info["volatile"] = "1";
379         }
380
381         break;
382     case S_IFDIR:
383         inode_type = 'd';
384         break;
385
386     default:
387         fprintf(stderr, "Unknown inode type: mode=%x\n", stat_buf.st_mode);
388         return;
389     }
390
391     file_info["type"] = string(1, inode_type);
392
393     metawriter->add(file_info);
394 }
395
396 void scanfile(const string& path, bool include)
397 {
398     int fd = -1;
399     long flags;
400     struct stat stat_buf;
401     list<string> refs;
402
403     string true_path;
404     if (relative_paths)
405         true_path = path;
406     else
407         true_path = "/" + path;
408
409     // Set to true if we should scan through the contents of this directory,
410     // but not actually back files up
411     bool scan_only = false;
412
413     // Check this file against the include/exclude list to see if it should be
414     // considered
415     for (list<string>::iterator i = includes.begin();
416          i != includes.end(); ++i) {
417         if (path == *i) {
418             include = true;
419         }
420     }
421
422     for (list<string>::iterator i = excludes.begin();
423          i != excludes.end(); ++i) {
424         if (path == *i) {
425             include = false;
426         }
427     }
428
429     for (list<string>::iterator i = searches.begin();
430          i != searches.end(); ++i) {
431         if (path == *i) {
432             scan_only = true;
433         }
434     }
435
436     if (!include && !scan_only)
437         return;
438
439     if (lstat(true_path.c_str(), &stat_buf) < 0) {
440         fprintf(stderr, "lstat(%s): %m\n", path.c_str());
441         return;
442     }
443
444     if ((stat_buf.st_mode & S_IFMT) == S_IFREG) {
445         /* Be paranoid when opening the file.  We have no guarantee that the
446          * file was not replaced between the stat() call above and the open()
447          * call below, so we might not even be opening a regular file.  We
448          * supply flags to open to to guard against various conditions before
449          * we can perform an lstat to check that the file is still a regular
450          * file:
451          *   - O_NOFOLLOW: in the event the file was replaced by a symlink
452          *   - O_NONBLOCK: prevents open() from blocking if the file was
453          *     replaced by a fifo
454          * We also add in O_NOATIME, since this may reduce disk writes (for
455          * inode updates).  However, O_NOATIME may result in EPERM, so if the
456          * initial open fails, try again without O_NOATIME.  */
457         fd = open(true_path.c_str(), O_RDONLY|O_NOATIME|O_NOFOLLOW|O_NONBLOCK);
458         if (fd < 0) {
459             fd = open(true_path.c_str(), O_RDONLY|O_NOFOLLOW|O_NONBLOCK);
460         }
461         if (fd < 0) {
462             fprintf(stderr, "Unable to open file %s: %m\n", path.c_str());
463             return;
464         }
465
466         /* Drop the use of the O_NONBLOCK flag; we only wanted that for file
467          * open. */
468         flags = fcntl(fd, F_GETFL);
469         fcntl(fd, F_SETFL, flags & ~O_NONBLOCK);
470
471         /* Perform the stat call again, and check that we still have a regular
472          * file. */
473         if (fstat(fd, &stat_buf) < 0) {
474             fprintf(stderr, "fstat: %m\n");
475             close(fd);
476             return;
477         }
478
479         if ((stat_buf.st_mode & S_IFMT) != S_IFREG) {
480             fprintf(stderr, "file is no longer a regular file!\n");
481             close(fd);
482             return;
483         }
484     }
485
486     dump_inode(path, true_path, stat_buf, fd);
487
488     if (fd >= 0)
489         close(fd);
490
491     // If we hit a directory, now that we've written the directory itself,
492     // recursively scan the directory.
493     if ((stat_buf.st_mode & S_IFMT) == S_IFDIR) {
494         DIR *dir = opendir(true_path.c_str());
495
496         if (dir == NULL) {
497             fprintf(stderr, "Error: %m\n");
498             return;
499         }
500
501         struct dirent *ent;
502         vector<string> contents;
503         while ((ent = readdir(dir)) != NULL) {
504             string filename(ent->d_name);
505             if (filename == "." || filename == "..")
506                 continue;
507             contents.push_back(filename);
508         }
509
510         closedir(dir);
511
512         sort(contents.begin(), contents.end());
513
514         for (vector<string>::iterator i = contents.begin();
515              i != contents.end(); ++i) {
516             const string& filename = *i;
517             if (path == ".")
518                 scanfile(filename, include);
519             else
520                 scanfile(path + "/" + filename, include);
521         }
522     }
523 }
524
525 /* Include the specified file path in the backups.  Append the path to the
526  * includes list, and to ensure that we actually see the path when scanning the
527  * directory tree, add all the parent directories to the search list, which
528  * means we will scan through the directory listing even if the files
529  * themselves are excluded from being backed up. */
530 void add_include(const char *path)
531 {
532     /* Was an absolute path specified?  If so, we'll need to start scanning
533      * from the root directory.  Make sure that the user was consistent in
534      * providing either all relative paths or all absolute paths. */
535     if (path[0] == '/') {
536         if (includes.size() > 0 && relative_paths == true) {
537             fprintf(stderr,
538                     "Error: Cannot mix relative and absolute paths!\n");
539             exit(1);
540         }
541
542         relative_paths = false;
543
544         // Skip over leading '/'
545         path++;
546     } else if (relative_paths == false && path[0] != '/') {
547         fprintf(stderr, "Error: Cannot mix relative and absolute paths!\n");
548         exit(1);
549     }
550
551     includes.push_back(path);
552
553     /* Split the specified path into directory components, and ensure that we
554      * descend into all the directories along the path. */
555     const char *slash = path;
556
557     if (path[0] == '\0')
558         return;
559
560     while ((slash = strchr(slash + 1, '/')) != NULL) {
561         string component(path, slash - path);
562         searches.push_back(component);
563     }
564 }
565
566 void usage(const char *program)
567 {
568     fprintf(
569         stderr,
570         "LBS %s\n\n"
571         "Usage: %s [OPTION]... --dest=DEST PATHS...\n"
572         "Produce backup snapshot of files in SOURCE and store to DEST.\n"
573         "\n"
574         "Options:\n"
575         "  --dest=PATH          path where backup is to be written\n"
576         "  --upload-script=COMMAND\n"
577         "                       program to invoke for each backup file generated\n"
578         "  --exclude=PATH       exclude files in PATH from snapshot\n"
579         "  --localdb=PATH       local backup metadata is stored in PATH\n"
580         "  --tmpdir=PATH        path for temporarily storing backup files\n"
581         "                           (defaults to TMPDIR environment variable or /tmp)\n"
582         "  --filter=COMMAND     program through which to filter segment data\n"
583         "                           (defaults to \"bzip2 -c\")\n"
584         "  --filter-extension=EXT\n"
585         "                       string to append to segment files\n"
586         "                           (defaults to \".bz2\")\n"
587         "  --signature-filter=COMMAND\n"
588         "                       program though which to filter descriptor\n"
589         "  --scheme=NAME        optional name for this snapshot\n"
590         "  --intent=FLOAT       intended backup type: 1=daily, 7=weekly, ...\n"
591         "                           (defaults to \"1\")\n"
592         "  --full-metadata      do not re-use metadata from previous backups\n"
593         "\n"
594         "Exactly one of --dest or --upload-script must be specified.\n",
595         lbs_version, program
596     );
597 }
598
599 int main(int argc, char *argv[])
600 {
601     string backup_dest = "", backup_script = "";
602     string localdb_dir = "";
603     string backup_scheme = "";
604     string signature_filter = "";
605
606     string tmp_dir = "/tmp";
607     if (getenv("TMPDIR") != NULL)
608         tmp_dir = getenv("TMPDIR");
609
610     while (1) {
611         static struct option long_options[] = {
612             {"localdb", 1, 0, 0},           // 0
613             {"exclude", 1, 0, 0},           // 1
614             {"filter", 1, 0, 0},            // 2
615             {"filter-extension", 1, 0, 0},  // 3
616             {"dest", 1, 0, 0},              // 4
617             {"scheme", 1, 0, 0},            // 5
618             {"signature-filter", 1, 0, 0},  // 6
619             {"intent", 1, 0, 0},            // 7
620             {"full-metadata", 0, 0, 0},     // 8
621             {"tmpdir", 1, 0, 0},            // 9
622             {"upload-script", 1, 0, 0},     // 10
623             {NULL, 0, 0, 0},
624         };
625
626         int long_index;
627         int c = getopt_long(argc, argv, "", long_options, &long_index);
628
629         if (c == -1)
630             break;
631
632         if (c == 0) {
633             switch (long_index) {
634             case 0:     // --localdb
635                 localdb_dir = optarg;
636                 break;
637             case 1:     // --exclude
638                 if (optarg[0] != '/')
639                     excludes.push_back(optarg);
640                 else
641                     excludes.push_back(optarg + 1);
642                 break;
643             case 2:     // --filter
644                 filter_program = optarg;
645                 break;
646             case 3:     // --filter-extension
647                 filter_extension = optarg;
648                 break;
649             case 4:     // --dest
650                 backup_dest = optarg;
651                 break;
652             case 5:     // --scheme
653                 backup_scheme = optarg;
654                 break;
655             case 6:     // --signature-filter
656                 signature_filter = optarg;
657                 break;
658             case 7:     // --intent
659                 snapshot_intent = atof(optarg);
660                 if (snapshot_intent <= 0)
661                     snapshot_intent = 1;
662                 break;
663             case 8:     // --full-metadata
664                 flag_full_metadata = true;
665                 break;
666             case 9:     // --tmpdir
667                 tmp_dir = optarg;
668                 break;
669             case 10:    // --upload-script
670                 backup_script = optarg;
671                 break;
672             default:
673                 fprintf(stderr, "Unhandled long option!\n");
674                 return 1;
675             }
676         } else {
677             usage(argv[0]);
678             return 1;
679         }
680     }
681
682     if (optind == argc) {
683         usage(argv[0]);
684         return 1;
685     }
686
687     searches.push_back(".");
688     for (int i = optind; i < argc; i++)
689         add_include(argv[i]);
690
691     if (backup_dest == "" && backup_script == "") {
692         fprintf(stderr,
693                 "Error: Backup destination must be specified using --dest= or --upload-script=\n");
694         usage(argv[0]);
695         return 1;
696     }
697
698     if (backup_dest != "" && backup_script != "") {
699         fprintf(stderr,
700                 "Error: Cannot specify both --dest= and --upload-script=\n");
701         usage(argv[0]);
702         return 1;
703     }
704
705     // Default for --localdb is the same as --dest
706     if (localdb_dir == "") {
707         localdb_dir = backup_dest;
708     }
709     if (localdb_dir == "") {
710         fprintf(stderr,
711                 "Error: Must specify local database path with --localdb=\n");
712         usage(argv[0]);
713         return 1;
714     }
715
716     block_buf = new char[LBS_BLOCK_SIZE];
717
718     /* Initialize the remote storage layer.  If using an upload script, create
719      * a temporary directory for staging files.  Otherwise, write backups
720      * directly to the destination directory. */
721     if (backup_script != "") {
722         tmp_dir = tmp_dir + "/lbs." + generate_uuid();
723         if (mkdir(tmp_dir.c_str(), 0700) < 0) {
724             fprintf(stderr, "Cannot create temporary directory %s: %m\n",
725                     tmp_dir.c_str());
726             return 1;
727         }
728         remote = new RemoteStore(tmp_dir);
729         remote->set_script(backup_script);
730     } else {
731         remote = new RemoteStore(backup_dest);
732     }
733
734     /* Store the time when the backup started, so it can be included in the
735      * snapshot name. */
736     time_t now;
737     struct tm time_buf;
738     char desc_buf[256];
739     time(&now);
740     localtime_r(&now, &time_buf);
741     strftime(desc_buf, sizeof(desc_buf), "%Y%m%dT%H%M%S", &time_buf);
742
743     /* Open the local database which tracks all objects that are stored
744      * remotely, for efficient incrementals.  Provide it with the name of this
745      * snapshot. */
746     string database_path = localdb_dir + "/localdb.sqlite";
747     db = new LocalDb;
748     db->Open(database_path.c_str(), desc_buf,
749              backup_scheme.size() ? backup_scheme.c_str() : NULL,
750              snapshot_intent);
751
752     tss = new TarSegmentStore(remote, db);
753
754     /* Initialize the stat cache, for skipping over unchanged files. */
755     metawriter = new MetadataWriter(tss, localdb_dir.c_str(), desc_buf,
756                                     backup_scheme.size()
757                                         ? backup_scheme.c_str()
758                                         : NULL);
759
760     scanfile(".", false);
761
762     ObjectReference root_ref = metawriter->close();
763     add_segment(root_ref.get_segment());
764     string backup_root = root_ref.to_string();
765
766     delete metawriter;
767
768     tss->sync();
769     tss->dump_stats();
770     delete tss;
771
772     /* Write out a checksums file which lists the checksums for all the
773      * segments included in this snapshot.  The format is designed so that it
774      * may be easily verified using the sha1sums command. */
775     const char csum_type[] = "sha1";
776     string checksum_filename = "snapshot-";
777     if (backup_scheme.size() > 0)
778         checksum_filename += backup_scheme + "-";
779     checksum_filename = checksum_filename + desc_buf + "." + csum_type + "sums";
780     RemoteFile *checksum_file = remote->alloc_file(checksum_filename,
781                                                    "checksums");
782     FILE *checksums = fdopen(checksum_file->get_fd(), "w");
783
784     for (std::set<string>::iterator i = segment_list.begin();
785          i != segment_list.end(); ++i) {
786         string seg_path, seg_csum;
787         if (db->GetSegmentChecksum(*i, &seg_path, &seg_csum)) {
788             const char *raw_checksum = NULL;
789             if (strncmp(seg_csum.c_str(), csum_type,
790                         strlen(csum_type)) == 0) {
791                 raw_checksum = seg_csum.c_str() + strlen(csum_type);
792                 if (*raw_checksum == '=')
793                     raw_checksum++;
794                 else
795                     raw_checksum = NULL;
796             }
797
798             if (raw_checksum != NULL)
799                 fprintf(checksums, "%s *%s\n",
800                         raw_checksum, seg_path.c_str());
801         }
802     }
803     fclose(checksums);
804     checksum_file->send();
805
806     db->Close();
807
808     /* All other files should be flushed to remote storage before writing the
809      * backup descriptor below, so that it is not possible to have a backup
810      * descriptor written out depending on non-existent (not yet written)
811      * files. */
812     remote->sync();
813
814     /* Write a backup descriptor file, which says which segments are needed and
815      * where to start to restore this snapshot.  The filename is based on the
816      * current time.  If a signature filter program was specified, filter the
817      * data through that to give a chance to sign the descriptor contents. */
818     string desc_filename = "snapshot-";
819     if (backup_scheme.size() > 0)
820         desc_filename += backup_scheme + "-";
821     desc_filename = desc_filename + desc_buf + ".lbs";
822
823     RemoteFile *descriptor_file = remote->alloc_file(desc_filename,
824                                                      "snapshots");
825     int descriptor_fd = descriptor_file->get_fd();
826     if (descriptor_fd < 0) {
827         fprintf(stderr, "Unable to open descriptor output file: %m\n");
828         return 1;
829     }
830     pid_t signature_pid = 0;
831     if (signature_filter.size() > 0) {
832         int new_fd = spawn_filter(descriptor_fd, signature_filter.c_str(),
833                                   &signature_pid);
834         close(descriptor_fd);
835         descriptor_fd = new_fd;
836     }
837     FILE *descriptor = fdopen(descriptor_fd, "w");
838
839     fprintf(descriptor, "Format: LBS Snapshot v0.6\n");
840     fprintf(descriptor, "Producer: LBS %s\n", lbs_version);
841     strftime(desc_buf, sizeof(desc_buf), "%Y-%m-%d %H:%M:%S %z", &time_buf);
842     fprintf(descriptor, "Date: %s\n", desc_buf);
843     if (backup_scheme.size() > 0)
844         fprintf(descriptor, "Scheme: %s\n", backup_scheme.c_str());
845     fprintf(descriptor, "Backup-Intent: %g\n", snapshot_intent);
846     fprintf(descriptor, "Root: %s\n", backup_root.c_str());
847
848     SHA1Checksum checksum_csum;
849     if (checksum_csum.process_file(checksum_filename.c_str())) {
850         string csum = checksum_csum.checksum_str();
851         fprintf(descriptor, "Checksums: %s\n", csum.c_str());
852     }
853
854     fprintf(descriptor, "Segments:\n");
855     for (std::set<string>::iterator i = segment_list.begin();
856          i != segment_list.end(); ++i) {
857         fprintf(descriptor, "    %s\n", i->c_str());
858     }
859
860     fclose(descriptor);
861
862     if (signature_pid) {
863         int status;
864         waitpid(signature_pid, &status, 0);
865
866         if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) {
867             throw IOException("Signature filter process error");
868         }
869     }
870
871     descriptor_file->send();
872
873     remote->sync();
874     delete remote;
875
876     if (backup_script != "") {
877         if (rmdir(tmp_dir.c_str()) < 0) {
878             fprintf(stderr,
879                     "Warning: Cannot delete temporary directory %s: %m\n",
880                     tmp_dir.c_str());
881         }
882     }
883
884     return 0;
885 }