Add rudimentary command-line parsing and support for file exclusions.
[cumulus.git] / scandir.cc
1 /* Recursively descend the filesystem and visit each file. */
2
3 #include <dirent.h>
4 #include <errno.h>
5 #include <fcntl.h>
6 #include <getopt.h>
7 #include <grp.h>
8 #include <pwd.h>
9 #include <stdint.h>
10 #include <stdio.h>
11 #include <stdlib.h>
12 #include <sys/stat.h>
13 #include <sys/types.h>
14 #include <unistd.h>
15
16 #include <algorithm>
17 #include <fstream>
18 #include <iostream>
19 #include <list>
20 #include <set>
21 #include <sstream>
22 #include <string>
23 #include <vector>
24
25 #include "format.h"
26 #include "localdb.h"
27 #include "store.h"
28 #include "sha1.h"
29
30 using std::list;
31 using std::string;
32 using std::vector;
33 using std::ostream;
34
35 static TarSegmentStore *tss = NULL;
36
37 /* Buffer for holding a single block of data read from a file. */
38 static const size_t LBS_BLOCK_SIZE = 1024 * 1024;
39 static char *block_buf;
40
41 static const size_t LBS_METADATA_BLOCK_SIZE = 65536;
42
43 /* Local database, which tracks objects written in this and previous
44  * invocations to help in creating incremental snapshots. */
45 LocalDb *db;
46
47 /* Contents of the root object.  This will contain a set of indirect links to
48  * the metadata objects. */
49 std::ostringstream metadata_root;
50
51 /* Buffer for building up metadata. */
52 std::ostringstream metadata;
53
54 /* Keep track of all segments which are needed to reconstruct the snapshot. */
55 std::set<string> segment_list;
56
57 void scandir(const string& path);
58
59 /* Selection of files to include/exclude in the snapshot. */
60 std::list<string> excludes;
61
62 /* Ensure contents of metadata are flushed to an object. */
63 void metadata_flush()
64 {
65     string m = metadata.str();
66     if (m.size() == 0)
67         return;
68
69     /* Write current metadata information to a new object. */
70     LbsObject *meta = new LbsObject;
71     meta->set_group("root");
72     meta->set_data(m.data(), m.size());
73     meta->write(tss);
74     meta->checksum();
75
76     /* Write a reference to this block in the root. */
77     ObjectReference ref = meta->get_ref();
78     metadata_root << "@" << ref.to_string() << "\n";
79     segment_list.insert(ref.get_segment());
80
81     delete meta;
82
83     metadata.str("");
84 }
85
86 /* Read data from a file descriptor and return the amount of data read.  A
87  * short read (less than the requested size) will only occur if end-of-file is
88  * hit. */
89 size_t file_read(int fd, char *buf, size_t maxlen)
90 {
91     size_t bytes_read = 0;
92
93     while (true) {
94         ssize_t res = read(fd, buf, maxlen);
95         if (res < 0) {
96             if (errno == EINTR)
97                 continue;
98             throw IOException("file_read: error reading");
99         } else if (res == 0) {
100             break;
101         } else {
102             bytes_read += res;
103             buf += res;
104             maxlen -= res;
105         }
106     }
107
108     return bytes_read;
109 }
110
111 /* Read the contents of a file (specified by an open file descriptor) and copy
112  * the data to the store.  Returns the size of the file (number of bytes
113  * dumped), or -1 on error. */
114 int64_t dumpfile(int fd, dictionary &file_info)
115 {
116     struct stat stat_buf;
117     fstat(fd, &stat_buf);
118     int64_t size = 0;
119     list<string> object_list;
120
121     if ((stat_buf.st_mode & S_IFMT) != S_IFREG) {
122         fprintf(stderr, "file is no longer a regular file!\n");
123         return -1;
124     }
125
126     /* The index data consists of a sequence of pointers to the data blocks
127      * that actually comprise the file data.  This level of indirection is used
128      * so that the same data block can be used in multiple files, or multiple
129      * versions of the same file. */
130     SHA1Checksum hash;
131     while (true) {
132         size_t bytes = file_read(fd, block_buf, LBS_BLOCK_SIZE);
133         if (bytes == 0)
134             break;
135
136         hash.process(block_buf, bytes);
137
138         // Either find a copy of this block in an already-existing segment, or
139         // index it so it can be re-used in the future
140         SHA1Checksum block_hash;
141         block_hash.process(block_buf, bytes);
142         string block_csum = block_hash.checksum_str();
143         ObjectReference ref = db->FindObject(block_csum, bytes);
144
145         // Store a copy of the object if one does not yet exist
146         if (ref.get_segment().size() == 0) {
147             LbsObject *o = new LbsObject;
148             o->set_group("data");
149             o->set_data(block_buf, bytes);
150             o->write(tss);
151             ref = o->get_ref();
152             db->StoreObject(ref, block_csum, bytes);
153             delete o;
154         }
155
156         object_list.push_back(ref.to_string());
157         segment_list.insert(ref.get_segment());
158         db->UseObject(ref);
159         size += bytes;
160     }
161
162     file_info["checksum"] = hash.checksum_str();
163
164     /* For files that only need to be broken apart into a few objects, store
165      * the list of objects directly.  For larger files, store the data
166      * out-of-line and provide a pointer to the indrect object. */
167     if (object_list.size() < 8) {
168         string blocklist = "";
169         for (list<string>::iterator i = object_list.begin();
170              i != object_list.end(); ++i) {
171             if (i != object_list.begin())
172                 blocklist += " ";
173             blocklist += *i;
174         }
175         file_info["data"] = blocklist;
176     } else {
177         string blocklist = "";
178         for (list<string>::iterator i = object_list.begin();
179              i != object_list.end(); ++i) {
180             blocklist += *i + "\n";
181         }
182
183         LbsObject *i = new LbsObject;
184         i->set_group("indirect");
185         i->set_data(blocklist.data(), blocklist.size());
186         i->write(tss);
187         file_info["data"] = "@" + i->get_name();
188         segment_list.insert(i->get_ref().get_segment());
189         delete i;
190     }
191
192     return size;
193 }
194
195 void scanfile(const string& path)
196 {
197     int fd;
198     long flags;
199     struct stat stat_buf;
200     char *buf;
201     ssize_t len;
202     int64_t file_size;
203     list<string> refs;
204
205     // Set to true if the item is a directory and we should recursively scan
206     bool recurse = false;
207
208     // Check this file against the include/exclude list to see if it should be
209     // considered
210     for (list<string>::iterator i = excludes.begin();
211          i != excludes.end(); ++i) {
212         if (path == *i) {
213             printf("Excluding %s\n", path.c_str());
214             return;
215         }
216     }
217
218     dictionary file_info;
219
220     lstat(path.c_str(), &stat_buf);
221
222     printf("%s\n", path.c_str());
223
224     metadata << "name: " << uri_encode(path) << "\n";
225
226     file_info["mode"] = encode_int(stat_buf.st_mode & 07777);
227     file_info["mtime"] = encode_int(stat_buf.st_mtime);
228     file_info["user"] = encode_int(stat_buf.st_uid);
229     file_info["group"] = encode_int(stat_buf.st_gid);
230
231     struct passwd *pwd = getpwuid(stat_buf.st_uid);
232     if (pwd != NULL) {
233         file_info["user"] += " (" + uri_encode(pwd->pw_name) + ")";
234     }
235
236     struct group *grp = getgrgid(stat_buf.st_gid);
237     if (pwd != NULL) {
238         file_info["group"] += " (" + uri_encode(grp->gr_name) + ")";
239     }
240
241     char inode_type;
242
243     switch (stat_buf.st_mode & S_IFMT) {
244     case S_IFIFO:
245         inode_type = 'p';
246         break;
247     case S_IFSOCK:
248         inode_type = 's';
249         break;
250     case S_IFCHR:
251         inode_type = 'c';
252         break;
253     case S_IFBLK:
254         inode_type = 'b';
255         break;
256     case S_IFLNK:
257         inode_type = 'l';
258
259         /* Use the reported file size to allocate a buffer large enough to read
260          * the symlink.  Allocate slightly more space, so that we ask for more
261          * bytes than we expect and so check for truncation. */
262         buf = new char[stat_buf.st_size + 2];
263         len = readlink(path.c_str(), buf, stat_buf.st_size + 1);
264         if (len < 0) {
265             fprintf(stderr, "error reading symlink: %m\n");
266         } else if (len <= stat_buf.st_size) {
267             buf[len] = '\0';
268             file_info["contents"] = uri_encode(buf);
269         } else if (len > stat_buf.st_size) {
270             fprintf(stderr, "error reading symlink: name truncated\n");
271         }
272
273         delete[] buf;
274         break;
275     case S_IFREG:
276         inode_type = '-';
277
278         /* Be paranoid when opening the file.  We have no guarantee that the
279          * file was not replaced between the stat() call above and the open()
280          * call below, so we might not even be opening a regular file.  That
281          * the file descriptor refers to a regular file is checked in
282          * dumpfile().  But we also supply flags to open to to guard against
283          * various conditions before we can perform that verification:
284          *   - O_NOFOLLOW: in the event the file was replaced by a symlink
285          *   - O_NONBLOCK: prevents open() from blocking if the file was
286          *     replaced by a fifo
287          * We also add in O_NOATIME, since this may reduce disk writes (for
288          * inode updates). */
289         fd = open(path.c_str(), O_RDONLY|O_NOATIME|O_NOFOLLOW|O_NONBLOCK);
290
291         /* Drop the use of the O_NONBLOCK flag; we only wanted that for file
292          * open. */
293         flags = fcntl(fd, F_GETFL);
294         fcntl(fd, F_SETFL, flags & ~O_NONBLOCK);
295
296         file_size = dumpfile(fd, file_info);
297         file_info["size"] = encode_int(file_size);
298         close(fd);
299
300         if (file_size < 0)
301             return;             // error occurred; do not dump file
302
303         if (file_size != stat_buf.st_size) {
304             fprintf(stderr, "Warning: Size of %s changed during reading\n",
305                     path.c_str());
306         }
307
308         break;
309     case S_IFDIR:
310         inode_type = 'd';
311         recurse = true;
312         break;
313
314     default:
315         fprintf(stderr, "Unknown inode type: mode=%x\n", stat_buf.st_mode);
316         return;
317     }
318
319     file_info["type"] = string(1, inode_type);
320
321     dict_output(metadata, file_info);
322     metadata << "\n";
323
324     // Break apart metadata listing if it becomes too large.
325     if (metadata.str().size() > LBS_METADATA_BLOCK_SIZE)
326         metadata_flush();
327
328     // If we hit a directory, now that we've written the directory itself,
329     // recursively scan the directory.
330     if (recurse)
331         scandir(path);
332 }
333
334 void scandir(const string& path)
335 {
336     DIR *dir = opendir(path.c_str());
337
338     if (dir == NULL) {
339         fprintf(stderr, "Error: %m\n");
340         return;
341     }
342
343     struct dirent *ent;
344     vector<string> contents;
345     while ((ent = readdir(dir)) != NULL) {
346         string filename(ent->d_name);
347         if (filename == "." || filename == "..")
348             continue;
349         contents.push_back(filename);
350     }
351
352     sort(contents.begin(), contents.end());
353
354     for (vector<string>::iterator i = contents.begin();
355          i != contents.end(); ++i) {
356         const string& filename = *i;
357         if (path == ".")
358             scanfile(filename);
359         else
360             scanfile(path + "/" + filename);
361     }
362
363     closedir(dir);
364 }
365
366 void usage(const char *program)
367 {
368     fprintf(stderr,
369             "Usage: %s [OPTION]... SOURCE DEST\n"
370             "Produce backup snapshot of files in SOURCE and store to DEST.\n"
371             "\n"
372             "Options:\n"
373             "  --exclude=PATH       exclude files in PATH from snapshot\n"
374             "  --localdb=PATH       local backup metadata is stored in PATH\n",
375             program);
376 }
377
378 int main(int argc, char *argv[])
379 {
380     string backup_source = ".";
381     string backup_dest = ".";
382     string localdb_dir = "";
383
384     while (1) {
385         static struct option long_options[] = {
386             {"localdb", 1, 0, 0},   // 0
387             {"exclude", 1, 0, 0},   // 1
388             {NULL, 0, 0, 0},
389         };
390
391         int long_index;
392         int c = getopt_long(argc, argv, "", long_options, &long_index);
393
394         if (c == -1)
395             break;
396
397         if (c == 0) {
398             switch (long_index) {
399             case 0:     // --localdb
400                 localdb_dir = optarg;
401                 break;
402             case 1:     // --exclude
403                 excludes.push_back(optarg);
404                 break;
405             default:
406                 fprintf(stderr, "Unhandled long option!\n");
407                 return 1;
408             }
409         } else {
410             usage(argv[0]);
411             return 1;
412         }
413     }
414
415     if (argc < optind + 2) {
416         usage(argv[0]);
417         return 1;
418     }
419
420     backup_source = argv[optind];
421     backup_dest = argv[argc - 1];
422
423     if (localdb_dir == "") {
424         localdb_dir = backup_dest;
425     }
426
427     printf("Source: %s, Dest: %s\n",
428            backup_source.c_str(), backup_dest.c_str());
429
430     tss = new TarSegmentStore(backup_dest);
431     block_buf = new char[LBS_BLOCK_SIZE];
432
433     /* Write a backup descriptor file, which says which segments are needed and
434      * where to start to restore this snapshot.  The filename is based on the
435      * current time. */
436     time_t now;
437     struct tm time_buf;
438     char desc_buf[256];
439     time(&now);
440     localtime_r(&now, &time_buf);
441     strftime(desc_buf, sizeof(desc_buf), "%Y%m%dT%H%M%S", &time_buf);
442     string desc_filename = backup_dest + "/" + desc_buf + ".lbs";
443     std::ofstream descriptor(desc_filename.c_str());
444
445     /* Open the local database which tracks all objects that are stored
446      * remotely, for efficient incrementals.  Provide it with the name of this
447      * snapshot. */
448     string database_path = backup_dest + "/localdb.sqlite";
449     db = new LocalDb;
450     db->Open(database_path.c_str(), desc_buf);
451
452     try {
453         scanfile(".");
454     } catch (IOException e) {
455         fprintf(stderr, "IOException: %s\n", e.getError().c_str());
456     }
457
458     metadata_flush();
459     const string md = metadata_root.str();
460
461     LbsObject *root = new LbsObject;
462     root->set_group("root");
463     root->set_data(md.data(), md.size());
464     root->write(tss);
465     root->checksum();
466
467     segment_list.insert(root->get_ref().get_segment());
468     descriptor << "Root: " << root->get_ref().to_string() << "\n";
469     strftime(desc_buf, sizeof(desc_buf), "%Y-%m-%d %H:%M:%S %z", &time_buf);
470     descriptor << "Date: " << desc_buf << "\n";
471
472     delete root;
473
474     descriptor << "Segments:\n";
475     for (std::set<string>::iterator i = segment_list.begin();
476          i != segment_list.end(); ++i) {
477         descriptor << "    " << *i << "\n";
478     }
479
480     db->Close();
481
482     tss->sync();
483     delete tss;
484
485     return 0;
486 }