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