Clean up error reporting.
[cumulus.git] / scandir.cc
1 /* Recursively descend the filesystem and visit each file. */
2
3 #include <stdio.h>
4 #include <stdlib.h>
5 #include <stdint.h>
6 #include <dirent.h>
7 #include <errno.h>
8 #include <fcntl.h>
9 #include <sys/types.h>
10 #include <sys/stat.h>
11 #include <unistd.h>
12
13 #include <algorithm>
14 #include <string>
15 #include <list>
16 #include <vector>
17 #include <iostream>
18 #include <sstream>
19 #include <set>
20
21 #include "format.h"
22 #include "store.h"
23 #include "sha1.h"
24
25 using std::list;
26 using std::string;
27 using std::vector;
28 using std::ostream;
29
30 static TarSegmentStore *tss = NULL;
31
32 /* Buffer for holding a single block of data read from a file. */
33 static const size_t LBS_BLOCK_SIZE = 1024 * 1024;
34 static char *block_buf;
35
36 static const size_t LBS_METADATA_BLOCK_SIZE = 65536;
37
38 /* Contents of the root object.  This will contain a set of indirect links to
39  * the metadata objects. */
40 std::ostringstream metadata_root;
41
42 /* Buffer for building up metadata. */
43 std::ostringstream metadata;
44
45 /* Keep track of all segments which are needed to reconstruct the snapshot. */
46 std::set<string> segment_list;
47
48 void scandir(const string& path);
49
50 /* Ensure contents of metadata are flushed to an object. */
51 void metadata_flush()
52 {
53     string m = metadata.str();
54     if (m.size() == 0)
55         return;
56
57     /* Write current metadata information to a new object. */
58     LbsObject *meta = new LbsObject;
59     meta->set_group("root");
60     meta->set_data(m.data(), m.size());
61     meta->write(tss);
62     meta->checksum();
63
64     /* Write a reference to this block in the root. */
65     ObjectReference ref = meta->get_ref();
66     metadata_root << "@" << ref.to_string() << "\n";
67     segment_list.insert(ref.get_segment());
68
69     delete meta;
70
71     metadata.str("");
72 }
73
74 /* Read data from a file descriptor and return the amount of data read.  A
75  * short read (less than the requested size) will only occur if end-of-file is
76  * hit. */
77 size_t file_read(int fd, char *buf, size_t maxlen)
78 {
79     size_t bytes_read = 0;
80
81     while (true) {
82         ssize_t res = read(fd, buf, maxlen);
83         if (res < 0) {
84             if (errno == EINTR)
85                 continue;
86             throw IOException("file_read: error reading");
87         } else if (res == 0) {
88             break;
89         } else {
90             bytes_read += res;
91             buf += res;
92             maxlen -= res;
93         }
94     }
95
96     return bytes_read;
97 }
98
99 /* Read the contents of a file (specified by an open file descriptor) and copy
100  * the data to the store. */
101 void dumpfile(int fd, dictionary &file_info)
102 {
103     struct stat stat_buf;
104     fstat(fd, &stat_buf);
105     int64_t size = 0;
106     list<string> object_list;
107
108     if ((stat_buf.st_mode & S_IFMT) != S_IFREG) {
109         fprintf(stderr, "file is no longer a regular file!\n");
110         return;
111     }
112
113     /* The index data consists of a sequence of pointers to the data blocks
114      * that actually comprise the file data.  This level of indirection is used
115      * so that the same data block can be used in multiple files, or multiple
116      * versions of the same file. */
117     SHA1Checksum hash;
118     while (true) {
119         size_t bytes = file_read(fd, block_buf, LBS_BLOCK_SIZE);
120         if (bytes == 0)
121             break;
122
123         hash.process(block_buf, bytes);
124
125         // tarstore processing
126         LbsObject *o = new LbsObject;
127         o->set_group("data");
128         o->set_data(block_buf, bytes);
129         o->write(tss);
130         object_list.push_back(o->get_name());
131         segment_list.insert(o->get_ref().get_segment());
132         delete o;
133
134         size += bytes;
135     }
136
137     file_info["checksum"] = hash.checksum_str();
138
139     /* For files that only need to be broken apart into a few objects, store
140      * the list of objects directly.  For larger files, store the data
141      * out-of-line and provide a pointer to the indrect object. */
142     if (object_list.size() < 8) {
143         string blocklist = "";
144         for (list<string>::iterator i = object_list.begin();
145              i != object_list.end(); ++i) {
146             if (i != object_list.begin())
147                 blocklist += " ";
148             blocklist += *i;
149         }
150         file_info["data"] = blocklist;
151     } else {
152         string blocklist = "";
153         for (list<string>::iterator i = object_list.begin();
154              i != object_list.end(); ++i) {
155             blocklist += *i + "\n";
156         }
157
158         LbsObject *i = new LbsObject;
159         i->set_group("indirect");
160         i->set_data(blocklist.data(), blocklist.size());
161         i->write(tss);
162         file_info["data"] = "@" + i->get_name();
163         segment_list.insert(i->get_ref().get_segment());
164         delete i;
165     }
166 }
167
168 void scanfile(const string& path)
169 {
170     int fd;
171     long flags;
172     struct stat stat_buf;
173     char *buf;
174     ssize_t len;
175     list<string> refs;
176
177     // Set to true if the item is a directory and we should recursively scan
178     bool recurse = false;
179
180     dictionary file_info;
181
182     lstat(path.c_str(), &stat_buf);
183
184     printf("%s\n", path.c_str());
185
186     metadata << "name: " << uri_encode(path) << "\n";
187
188     file_info["mode"] = encode_int(stat_buf.st_mode & 07777);
189     file_info["atime"] = encode_int(stat_buf.st_atime);
190     file_info["ctime"] = encode_int(stat_buf.st_ctime);
191     file_info["mtime"] = encode_int(stat_buf.st_mtime);
192     file_info["user"] = encode_int(stat_buf.st_uid);
193     file_info["group"] = encode_int(stat_buf.st_gid);
194
195     char inode_type;
196
197     switch (stat_buf.st_mode & S_IFMT) {
198     case S_IFIFO:
199         inode_type = 'p';
200         break;
201     case S_IFSOCK:
202         inode_type = 's';
203         break;
204     case S_IFCHR:
205         inode_type = 'c';
206         break;
207     case S_IFBLK:
208         inode_type = 'b';
209         break;
210     case S_IFLNK:
211         inode_type = 'l';
212
213         /* Use the reported file size to allocate a buffer large enough to read
214          * the symlink.  Allocate slightly more space, so that we ask for more
215          * bytes than we expect and so check for truncation. */
216         buf = new char[stat_buf.st_size + 2];
217         len = readlink(path.c_str(), buf, stat_buf.st_size + 1);
218         if (len < 0) {
219             fprintf(stderr, "error reading symlink: %m\n");
220         } else if (len <= stat_buf.st_size) {
221             buf[len] = '\0';
222             file_info["contents"] = uri_encode(buf);
223         } else if (len > stat_buf.st_size) {
224             fprintf(stderr, "error reading symlink: name truncated\n");
225         }
226
227         delete[] buf;
228         break;
229     case S_IFREG:
230         inode_type = '-';
231
232         /* Be paranoid when opening the file.  We have no guarantee that the
233          * file was not replaced between the stat() call above and the open()
234          * call below, so we might not even be opening a regular file.  That
235          * the file descriptor refers to a regular file is checked in
236          * dumpfile().  But we also supply flags to open to to guard against
237          * various conditions before we can perform that verification:
238          *   - O_NOFOLLOW: in the event the file was replaced by a symlink
239          *   - O_NONBLOCK: prevents open() from blocking if the file was
240          *     replaced by a fifo
241          * We also add in O_NOATIME, since this may reduce disk writes (for
242          * inode updates). */
243         fd = open(path.c_str(), O_RDONLY|O_NOATIME|O_NOFOLLOW|O_NONBLOCK);
244
245         /* Drop the use of the O_NONBLOCK flag; we only wanted that for file
246          * open. */
247         flags = fcntl(fd, F_GETFL);
248         fcntl(fd, F_SETFL, flags & ~O_NONBLOCK);
249
250         file_info["size"] = encode_int(stat_buf.st_size);
251         dumpfile(fd, file_info);
252         close(fd);
253
254         break;
255     case S_IFDIR:
256         inode_type = 'd';
257         recurse = true;
258         break;
259
260     default:
261         fprintf(stderr, "Unknown inode type: mode=%x\n", stat_buf.st_mode);
262         return;
263     }
264
265     file_info["type"] = string(1, inode_type);
266
267     dict_output(metadata, file_info);
268     metadata << "\n";
269
270     // Break apart metadata listing if it becomes too large.
271     if (metadata.str().size() > LBS_METADATA_BLOCK_SIZE)
272         metadata_flush();
273
274     // If we hit a directory, now that we've written the directory itself,
275     // recursively scan the directory.
276     if (recurse)
277         scandir(path);
278 }
279
280 void scandir(const string& path)
281 {
282     DIR *dir = opendir(path.c_str());
283
284     if (dir == NULL) {
285         fprintf(stderr, "Error: %m\n");
286         return;
287     }
288
289     struct dirent *ent;
290     vector<string> contents;
291     while ((ent = readdir(dir)) != NULL) {
292         string filename(ent->d_name);
293         if (filename == "." || filename == "..")
294             continue;
295         contents.push_back(filename);
296     }
297
298     sort(contents.begin(), contents.end());
299
300     for (vector<string>::iterator i = contents.begin();
301          i != contents.end(); ++i) {
302         const string& filename = *i;
303         scanfile(path + "/" + filename);
304     }
305
306     closedir(dir);
307 }
308
309 int main(int argc, char *argv[])
310 {
311     block_buf = new char[LBS_BLOCK_SIZE];
312
313     if (argc > 1) {
314         tss = new TarSegmentStore(argv[1]);
315     } else {
316         tss = new TarSegmentStore(".");
317     }
318
319     try {
320         scanfile(".");
321     } catch (IOException e) {
322         fprintf(stderr, "IOException: %s\n", e.getError().c_str());
323     }
324
325     metadata_flush();
326     const string md = metadata_root.str();
327
328     LbsObject *root = new LbsObject;
329     root->set_group("root");
330     root->set_data(md.data(), md.size());
331     root->write(tss);
332     root->checksum();
333
334     segment_list.insert(root->get_ref().get_segment());
335     string r = root->get_ref().to_string();
336     printf("\nroot: %s\n\n", r.c_str());
337     delete root;
338
339     printf("segments:\n");
340     for (std::set<string>::iterator i = segment_list.begin();
341          i != segment_list.end(); ++i) {
342         printf("    %s\n", i->c_str());
343     }
344
345     tss->sync();
346     delete tss;
347
348     return 0;
349 }