e25352794c1a28c004d073150672170013ee2759
[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 <vector>
16
17 #include "store.h"
18 #include "sha1.h"
19
20 using std::string;
21 using std::vector;
22
23 static SegmentStore *segment_store;
24 static OutputStream *info_dump = NULL;
25
26 static SegmentPartitioner *index_segment, *data_segment;
27
28 /* Buffer for holding a single block of data read from a file. */
29 static const int LBS_BLOCK_SIZE = 1024 * 1024;
30 static char *block_buf;
31
32 void scandir(const string& path);
33
34 /* Converts time to microseconds since the epoch. */
35 int64_t encode_time(time_t time)
36 {
37     return (int64_t)time * 1000000;
38 }
39
40 /* Read data from a file descriptor and return the amount of data read.  A
41  * short read (less than the requested size) will only occur if end-of-file is
42  * hit. */
43 size_t file_read(int fd, char *buf, size_t maxlen)
44 {
45     size_t bytes_read = 0;
46
47     while (true) {
48         ssize_t res = read(fd, buf, maxlen);
49         if (res < 0) {
50             if (errno == EINTR)
51                 continue;
52             throw IOException("file_read: error reading");
53         } else if (res == 0) {
54             break;
55         } else {
56             bytes_read += res;
57             buf += res;
58             maxlen -= res;
59         }
60     }
61
62     return bytes_read;
63 }
64
65 /* Read the contents of a file (specified by an open file descriptor) and copy
66  * the data to the store. */
67 void dumpfile(int fd, dictionary &file_info)
68 {
69     struct stat stat_buf;
70     fstat(fd, &stat_buf);
71     int64_t size = 0;
72
73     if ((stat_buf.st_mode & S_IFMT) != S_IFREG) {
74         printf("file is no longer a regular file!\n");
75         return;
76     }
77
78     /* The index data consists of a sequence of pointers to the data blocks
79      * that actually comprise the file data.  This level of indirection is used
80      * so that the same data block can be used in multiple files, or multiple
81      * versions of the same file. */
82     struct uuid segment_uuid;
83     int object_id;
84     OutputStream *index_data = index_segment->new_object(&segment_uuid,
85                                                          &object_id,
86                                                          "DREF");
87
88     SHA1Checksum hash;
89     while (true) {
90         struct uuid block_segment_uuid;
91         int block_object_id;
92
93         size_t bytes = file_read(fd, block_buf, LBS_BLOCK_SIZE);
94         if (bytes == 0)
95             break;
96
97         hash.process(block_buf, bytes);
98         OutputStream *block = data_segment->new_object(&block_segment_uuid,
99                                                        &block_object_id,
100                                                        "DATA");
101         block->write(block_buf, bytes);
102         index_data->write_uuid(block_segment_uuid);
103         index_data->write_u32(block_object_id);
104
105         size += bytes;
106     }
107
108     file_info["sha1"] = string((const char *)hash.checksum(),
109                                hash.checksum_size());
110     file_info["data"] = encode_objref(segment_uuid, object_id);
111 }
112
113 void scanfile(const string& path)
114 {
115     int fd;
116     long flags;
117     struct stat stat_buf;
118     char *buf;
119     ssize_t len;
120
121     // Set to true if the item is a directory and we should recursively scan
122     bool recurse = false;
123
124     dictionary file_info;
125
126     lstat(path.c_str(), &stat_buf);
127
128     printf("%s\n", path.c_str());
129
130     file_info["mode"] = encode_u16(stat_buf.st_mode & 07777);
131     file_info["atime"] = encode_u64(encode_time(stat_buf.st_atime));
132     file_info["ctime"] = encode_u64(encode_time(stat_buf.st_ctime));
133     file_info["mtime"] = encode_u64(encode_time(stat_buf.st_mtime));
134     file_info["user"] = encode_u32(stat_buf.st_uid);
135     file_info["group"] = encode_u32(stat_buf.st_gid);
136
137     char inode_type;
138
139     switch (stat_buf.st_mode & S_IFMT) {
140     case S_IFIFO:
141         inode_type = 'p';
142         break;
143     case S_IFSOCK:
144         inode_type = 's';
145         break;
146     case S_IFCHR:
147         inode_type = 'c';
148         break;
149     case S_IFBLK:
150         inode_type = 'b';
151         break;
152     case S_IFLNK:
153         inode_type = 'l';
154
155         /* Use the reported file size to allocate a buffer large enough to read
156          * the symlink.  Allocate slightly more space, so that we ask for more
157          * bytes than we expect and so check for truncation. */
158         buf = new char[stat_buf.st_size + 2];
159         len = readlink(path.c_str(), buf, stat_buf.st_size + 1);
160         if (len < 0) {
161             printf("error reading symlink: %m\n");
162         } else if (len <= stat_buf.st_size) {
163             buf[len] = '\0';
164             printf("    contents=%s\n", buf);
165         } else if (len > stat_buf.st_size) {
166             printf("error reading symlink: name truncated\n");
167         }
168
169         file_info["contents"] = buf;
170
171         delete[] buf;
172         break;
173     case S_IFREG:
174         inode_type = '-';
175
176         /* Be paranoid when opening the file.  We have no guarantee that the
177          * file was not replaced between the stat() call above and the open()
178          * call below, so we might not even be opening a regular file.  That
179          * the file descriptor refers to a regular file is checked in
180          * dumpfile().  But we also supply flags to open to to guard against
181          * various conditions before we can perform that verification:
182          *   - O_NOFOLLOW: in the event the file was replaced by a symlink
183          *   - O_NONBLOCK: prevents open() from blocking if the file was
184          *     replaced by a fifo
185          * We also add in O_NOATIME, since this may reduce disk writes (for
186          * inode updates). */
187         fd = open(path.c_str(), O_RDONLY|O_NOATIME|O_NOFOLLOW|O_NONBLOCK);
188
189         /* Drop the use of the O_NONBLOCK flag; we only wanted that for file
190          * open. */
191         flags = fcntl(fd, F_GETFL);
192         fcntl(fd, F_SETFL, flags & ~O_NONBLOCK);
193
194         file_info["size"] = encode_u64(stat_buf.st_size);
195         dumpfile(fd, file_info);
196         close(fd);
197
198         break;
199     case S_IFDIR:
200         inode_type = 'd';
201         recurse = true;
202         break;
203
204     default:
205         fprintf(stderr, "Unknown inode type: mode=%x\n", stat_buf.st_mode);
206         return;
207     }
208
209     file_info["type"] = string(1, inode_type);
210
211     info_dump->write_string(path);
212     info_dump->write_dictionary(file_info);
213
214     // If we hit a directory, now that we've written the directory itself,
215     // recursively scan the directory.
216     if (recurse)
217         scandir(path);
218 }
219
220 void scandir(const string& path)
221 {
222     DIR *dir = opendir(path.c_str());
223
224     if (dir == NULL) {
225         printf("Error: %m\n");
226         return;
227     }
228
229     struct dirent *ent;
230     vector<string> contents;
231     while ((ent = readdir(dir)) != NULL) {
232         string filename(ent->d_name);
233         if (filename == "." || filename == "..")
234             continue;
235         contents.push_back(filename);
236     }
237
238     sort(contents.begin(), contents.end());
239
240     for (vector<string>::iterator i = contents.begin();
241          i != contents.end(); ++i) {
242         const string& filename = *i;
243         scanfile(path + "/" + filename);
244     }
245
246     closedir(dir);
247 }
248
249 int main(int argc, char *argv[])
250 {
251     block_buf = new char[LBS_BLOCK_SIZE];
252
253     segment_store = new SegmentStore(".");
254     SegmentWriter *sw = segment_store->new_segment();
255     info_dump = sw->new_object(NULL, "ROOT");
256
257     index_segment = new SegmentPartitioner(segment_store);
258     data_segment = new SegmentPartitioner(segment_store);
259
260     string uuid = SegmentWriter::format_uuid(sw->get_uuid());
261     printf("Backup UUID: %s\n", uuid.c_str());
262
263     try {
264         scanfile(".");
265     } catch (IOException e) {
266         fprintf(stderr, "IOException: %s\n", e.getError().c_str());
267     }
268
269     delete index_segment;
270     delete data_segment;
271     delete sw;
272
273     return 0;
274 }