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