Put updated copyright statements in all source files.
[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             printf("Including %s\n", path.c_str());
419             include = true;
420         }
421     }
422
423     for (list<string>::iterator i = excludes.begin();
424          i != excludes.end(); ++i) {
425         if (path == *i) {
426             printf("Excluding %s\n", path.c_str());
427             include = false;
428         }
429     }
430
431     for (list<string>::iterator i = searches.begin();
432          i != searches.end(); ++i) {
433         if (path == *i) {
434             printf("Scanning %s\n", path.c_str());
435             scan_only = true;
436         }
437     }
438
439     if (!include && !scan_only)
440         return;
441
442     if (lstat(true_path.c_str(), &stat_buf) < 0) {
443         fprintf(stderr, "lstat(%s): %m\n", path.c_str());
444         return;
445     }
446
447     if ((stat_buf.st_mode & S_IFMT) == S_IFREG) {
448         /* Be paranoid when opening the file.  We have no guarantee that the
449          * file was not replaced between the stat() call above and the open()
450          * call below, so we might not even be opening a regular file.  We
451          * supply flags to open to to guard against various conditions before
452          * we can perform an lstat to check that the file is still a regular
453          * file:
454          *   - O_NOFOLLOW: in the event the file was replaced by a symlink
455          *   - O_NONBLOCK: prevents open() from blocking if the file was
456          *     replaced by a fifo
457          * We also add in O_NOATIME, since this may reduce disk writes (for
458          * inode updates).  However, O_NOATIME may result in EPERM, so if the
459          * initial open fails, try again without O_NOATIME.  */
460         fd = open(true_path.c_str(), O_RDONLY|O_NOATIME|O_NOFOLLOW|O_NONBLOCK);
461         if (fd < 0) {
462             fd = open(true_path.c_str(), O_RDONLY|O_NOFOLLOW|O_NONBLOCK);
463         }
464         if (fd < 0) {
465             fprintf(stderr, "Unable to open file %s: %m\n", path.c_str());
466             return;
467         }
468
469         /* Drop the use of the O_NONBLOCK flag; we only wanted that for file
470          * open. */
471         flags = fcntl(fd, F_GETFL);
472         fcntl(fd, F_SETFL, flags & ~O_NONBLOCK);
473
474         /* Perform the stat call again, and check that we still have a regular
475          * file. */
476         if (fstat(fd, &stat_buf) < 0) {
477             fprintf(stderr, "fstat: %m\n");
478             close(fd);
479             return;
480         }
481
482         if ((stat_buf.st_mode & S_IFMT) != S_IFREG) {
483             fprintf(stderr, "file is no longer a regular file!\n");
484             close(fd);
485             return;
486         }
487     }
488
489     dump_inode(path, true_path, stat_buf, fd);
490
491     if (fd >= 0)
492         close(fd);
493
494     // If we hit a directory, now that we've written the directory itself,
495     // recursively scan the directory.
496     if ((stat_buf.st_mode & S_IFMT) == S_IFDIR) {
497         DIR *dir = opendir(true_path.c_str());
498
499         if (dir == NULL) {
500             fprintf(stderr, "Error: %m\n");
501             return;
502         }
503
504         struct dirent *ent;
505         vector<string> contents;
506         while ((ent = readdir(dir)) != NULL) {
507             string filename(ent->d_name);
508             if (filename == "." || filename == "..")
509                 continue;
510             contents.push_back(filename);
511         }
512
513         closedir(dir);
514
515         sort(contents.begin(), contents.end());
516
517         for (vector<string>::iterator i = contents.begin();
518              i != contents.end(); ++i) {
519             const string& filename = *i;
520             if (path == ".")
521                 scanfile(filename, include);
522             else
523                 scanfile(path + "/" + filename, include);
524         }
525     }
526 }
527
528 /* Include the specified file path in the backups.  Append the path to the
529  * includes list, and to ensure that we actually see the path when scanning the
530  * directory tree, add all the parent directories to the search list, which
531  * means we will scan through the directory listing even if the files
532  * themselves are excluded from being backed up. */
533 void add_include(const char *path)
534 {
535     printf("Add: %s\n", path);
536     /* Was an absolute path specified?  If so, we'll need to start scanning
537      * from the root directory.  Make sure that the user was consistent in
538      * providing either all relative paths or all absolute paths. */
539     if (path[0] == '/') {
540         if (includes.size() > 0 && relative_paths == true) {
541             fprintf(stderr,
542                     "Error: Cannot mix relative and absolute paths!\n");
543             exit(1);
544         }
545
546         relative_paths = false;
547
548         // Skip over leading '/'
549         path++;
550     } else if (relative_paths == false && path[0] != '/') {
551         fprintf(stderr, "Error: Cannot mix relative and absolute paths!\n");
552         exit(1);
553     }
554
555     includes.push_back(path);
556
557     /* Split the specified path into directory components, and ensure that we
558      * descend into all the directories along the path. */
559     const char *slash = path;
560
561     if (path[0] == '\0')
562         return;
563
564     while ((slash = strchr(slash + 1, '/')) != NULL) {
565         string component(path, slash - path);
566         searches.push_back(component);
567     }
568 }
569
570 void usage(const char *program)
571 {
572     fprintf(
573         stderr,
574         "LBS %s\n\n"
575         "Usage: %s [OPTION]... --dest=DEST PATHS...\n"
576         "Produce backup snapshot of files in SOURCE and store to DEST.\n"
577         "\n"
578         "Options:\n"
579         "  --dest=PATH          path where backup is to be written\n"
580         "  --upload-script=COMMAND\n"
581         "                       program to invoke for each backup file generated\n"
582         "  --exclude=PATH       exclude files in PATH from snapshot\n"
583         "  --localdb=PATH       local backup metadata is stored in PATH\n"
584         "  --tmpdir=PATH        path for temporarily storing backup files\n"
585         "                           (defaults to TMPDIR environment variable or /tmp)\n"
586         "  --filter=COMMAND     program through which to filter segment data\n"
587         "                           (defaults to \"bzip2 -c\")\n"
588         "  --filter-extension=EXT\n"
589         "                       string to append to segment files\n"
590         "                           (defaults to \".bz2\")\n"
591         "  --signature-filter=COMMAND\n"
592         "                       program though which to filter descriptor\n"
593         "  --scheme=NAME        optional name for this snapshot\n"
594         "  --intent=FLOAT       intended backup type: 1=daily, 7=weekly, ...\n"
595         "                           (defaults to \"1\")\n"
596         "  --full-metadata      do not re-use metadata from previous backups\n"
597         "\n"
598         "Exactly one of --dest or --upload-script must be specified.\n",
599         lbs_version, program
600     );
601 }
602
603 int main(int argc, char *argv[])
604 {
605     string backup_dest = "", backup_script = "";
606     string localdb_dir = "";
607     string backup_scheme = "";
608     string signature_filter = "";
609
610     string tmp_dir = "/tmp";
611     if (getenv("TMPDIR") != NULL)
612         tmp_dir = getenv("TMPDIR");
613
614     while (1) {
615         static struct option long_options[] = {
616             {"localdb", 1, 0, 0},           // 0
617             {"exclude", 1, 0, 0},           // 1
618             {"filter", 1, 0, 0},            // 2
619             {"filter-extension", 1, 0, 0},  // 3
620             {"dest", 1, 0, 0},              // 4
621             {"scheme", 1, 0, 0},            // 5
622             {"signature-filter", 1, 0, 0},  // 6
623             {"intent", 1, 0, 0},            // 7
624             {"full-metadata", 0, 0, 0},     // 8
625             {"tmpdir", 1, 0, 0},            // 9
626             {"upload-script", 1, 0, 0},     // 10
627             {NULL, 0, 0, 0},
628         };
629
630         int long_index;
631         int c = getopt_long(argc, argv, "", long_options, &long_index);
632
633         if (c == -1)
634             break;
635
636         if (c == 0) {
637             switch (long_index) {
638             case 0:     // --localdb
639                 localdb_dir = optarg;
640                 break;
641             case 1:     // --exclude
642                 if (optarg[0] != '/')
643                     excludes.push_back(optarg);
644                 else
645                     excludes.push_back(optarg + 1);
646                 break;
647             case 2:     // --filter
648                 filter_program = optarg;
649                 break;
650             case 3:     // --filter-extension
651                 filter_extension = optarg;
652                 break;
653             case 4:     // --dest
654                 backup_dest = optarg;
655                 break;
656             case 5:     // --scheme
657                 backup_scheme = optarg;
658                 break;
659             case 6:     // --signature-filter
660                 signature_filter = optarg;
661                 break;
662             case 7:     // --intent
663                 snapshot_intent = atof(optarg);
664                 if (snapshot_intent <= 0)
665                     snapshot_intent = 1;
666                 break;
667             case 8:     // --full-metadata
668                 flag_full_metadata = true;
669                 break;
670             case 9:     // --tmpdir
671                 tmp_dir = optarg;
672                 break;
673             case 10:    // --upload-script
674                 backup_script = optarg;
675                 break;
676             default:
677                 fprintf(stderr, "Unhandled long option!\n");
678                 return 1;
679             }
680         } else {
681             usage(argv[0]);
682             return 1;
683         }
684     }
685
686     if (optind == argc) {
687         usage(argv[0]);
688         return 1;
689     }
690
691     searches.push_back(".");
692     for (int i = optind; i < argc; i++)
693         add_include(argv[i]);
694
695     if (backup_dest == "" && backup_script == "") {
696         fprintf(stderr,
697                 "Error: Backup destination must be specified using --dest= or --upload-script=\n");
698         usage(argv[0]);
699         return 1;
700     }
701
702     if (backup_dest != "" && backup_script != "") {
703         fprintf(stderr,
704                 "Error: Cannot specify both --dest= and --upload-script=\n");
705         usage(argv[0]);
706         return 1;
707     }
708
709     // Default for --localdb is the same as --dest
710     if (localdb_dir == "") {
711         localdb_dir = backup_dest;
712     }
713     if (localdb_dir == "") {
714         fprintf(stderr,
715                 "Error: Must specify local database path with --localdb=\n");
716         usage(argv[0]);
717         return 1;
718     }
719
720     // Dump paths for debugging/informational purposes
721     {
722         list<string>::const_iterator i;
723
724         printf("LBS Version: %s\n", lbs_version);
725
726         printf("--dest=%s\n--localdb=%s\n--upload-script=%s\n",
727                backup_dest.c_str(), localdb_dir.c_str(), backup_script.c_str());
728
729         printf("Includes:\n");
730         for (i = includes.begin(); i != includes.end(); ++i)
731             printf("    %s\n", i->c_str());
732
733         printf("Excludes:\n");
734         for (i = excludes.begin(); i != excludes.end(); ++i)
735             printf("    %s\n", i->c_str());
736
737         printf("Searching:\n");
738         for (i = searches.begin(); i != searches.end(); ++i)
739             printf("    %s\n", i->c_str());
740     }
741
742     block_buf = new char[LBS_BLOCK_SIZE];
743
744     /* Initialize the remote storage layer.  If using an upload script, create
745      * a temporary directory for staging files.  Otherwise, write backups
746      * directly to the destination directory. */
747     if (backup_script != "") {
748         tmp_dir = tmp_dir + "/lbs." + generate_uuid();
749         if (mkdir(tmp_dir.c_str(), 0700) < 0) {
750             fprintf(stderr, "Cannot create temporary directory %s: %m\n",
751                     tmp_dir.c_str());
752             return 1;
753         }
754         remote = new RemoteStore(tmp_dir);
755         remote->set_script(backup_script);
756     } else {
757         remote = new RemoteStore(backup_dest);
758     }
759
760     /* Store the time when the backup started, so it can be included in the
761      * snapshot name. */
762     time_t now;
763     struct tm time_buf;
764     char desc_buf[256];
765     time(&now);
766     localtime_r(&now, &time_buf);
767     strftime(desc_buf, sizeof(desc_buf), "%Y%m%dT%H%M%S", &time_buf);
768
769     /* Open the local database which tracks all objects that are stored
770      * remotely, for efficient incrementals.  Provide it with the name of this
771      * snapshot. */
772     string database_path = localdb_dir + "/localdb.sqlite";
773     db = new LocalDb;
774     db->Open(database_path.c_str(), desc_buf,
775              backup_scheme.size() ? backup_scheme.c_str() : NULL,
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.size()
783                                         ? backup_scheme.c_str()
784                                         : NULL);
785
786     scanfile(".", false);
787
788     ObjectReference root_ref = metawriter->close();
789     add_segment(root_ref.get_segment());
790     string backup_root = root_ref.to_string();
791
792     delete metawriter;
793
794     tss->sync();
795     tss->dump_stats();
796     delete tss;
797
798     /* Write out a checksums file which lists the checksums for all the
799      * segments included in this snapshot.  The format is designed so that it
800      * may be easily verified using the sha1sums command. */
801     const char csum_type[] = "sha1";
802     string checksum_filename = "snapshot-";
803     if (backup_scheme.size() > 0)
804         checksum_filename += backup_scheme + "-";
805     checksum_filename = checksum_filename + desc_buf + "." + csum_type + "sums";
806     RemoteFile *checksum_file = remote->alloc_file(checksum_filename,
807                                                    "checksums");
808     FILE *checksums = fdopen(checksum_file->get_fd(), "w");
809
810     for (std::set<string>::iterator i = segment_list.begin();
811          i != segment_list.end(); ++i) {
812         string seg_path, seg_csum;
813         if (db->GetSegmentChecksum(*i, &seg_path, &seg_csum)) {
814             const char *raw_checksum = NULL;
815             if (strncmp(seg_csum.c_str(), csum_type,
816                         strlen(csum_type)) == 0) {
817                 raw_checksum = seg_csum.c_str() + strlen(csum_type);
818                 if (*raw_checksum == '=')
819                     raw_checksum++;
820                 else
821                     raw_checksum = NULL;
822             }
823
824             if (raw_checksum != NULL)
825                 fprintf(checksums, "%s *%s\n",
826                         raw_checksum, seg_path.c_str());
827         }
828     }
829     fclose(checksums);
830     checksum_file->send();
831
832     db->Close();
833
834     /* All other files should be flushed to remote storage before writing the
835      * backup descriptor below, so that it is not possible to have a backup
836      * descriptor written out depending on non-existent (not yet written)
837      * files. */
838     remote->sync();
839
840     /* Write a backup descriptor file, which says which segments are needed and
841      * where to start to restore this snapshot.  The filename is based on the
842      * current time.  If a signature filter program was specified, filter the
843      * data through that to give a chance to sign the descriptor contents. */
844     string desc_filename = "snapshot-";
845     if (backup_scheme.size() > 0)
846         desc_filename += backup_scheme + "-";
847     desc_filename = desc_filename + desc_buf + ".lbs";
848
849     RemoteFile *descriptor_file = remote->alloc_file(desc_filename,
850                                                      "snapshots");
851     int descriptor_fd = descriptor_file->get_fd();
852     if (descriptor_fd < 0) {
853         fprintf(stderr, "Unable to open descriptor output file: %m\n");
854         return 1;
855     }
856     pid_t signature_pid = 0;
857     if (signature_filter.size() > 0) {
858         int new_fd = spawn_filter(descriptor_fd, signature_filter.c_str(),
859                                   &signature_pid);
860         close(descriptor_fd);
861         descriptor_fd = new_fd;
862     }
863     FILE *descriptor = fdopen(descriptor_fd, "w");
864
865     fprintf(descriptor, "Format: LBS Snapshot v0.6\n");
866     fprintf(descriptor, "Producer: LBS %s\n", lbs_version);
867     strftime(desc_buf, sizeof(desc_buf), "%Y-%m-%d %H:%M:%S %z", &time_buf);
868     fprintf(descriptor, "Date: %s\n", desc_buf);
869     if (backup_scheme.size() > 0)
870         fprintf(descriptor, "Scheme: %s\n", backup_scheme.c_str());
871     fprintf(descriptor, "Backup-Intent: %g\n", snapshot_intent);
872     fprintf(descriptor, "Root: %s\n", backup_root.c_str());
873
874     SHA1Checksum checksum_csum;
875     if (checksum_csum.process_file(checksum_filename.c_str())) {
876         string csum = checksum_csum.checksum_str();
877         fprintf(descriptor, "Checksums: %s\n", csum.c_str());
878     }
879
880     fprintf(descriptor, "Segments:\n");
881     for (std::set<string>::iterator i = segment_list.begin();
882          i != segment_list.end(); ++i) {
883         fprintf(descriptor, "    %s\n", i->c_str());
884     }
885
886     fclose(descriptor);
887
888     if (signature_pid) {
889         int status;
890         waitpid(signature_pid, &status, 0);
891
892         if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) {
893             throw IOException("Signature filter process error");
894         }
895     }
896
897     descriptor_file->send();
898
899     remote->sync();
900     delete remote;
901
902     if (backup_script != "") {
903         if (rmdir(tmp_dir.c_str()) < 0) {
904             fprintf(stderr,
905                     "Warning: Cannot delete temporary directory %s: %m\n",
906                     tmp_dir.c_str());
907         }
908     }
909
910     return 0;
911 }