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