Return the names for allocated objects, and link file metaata to data.
[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
87     SHA1Checksum hash;
88     while (true) {
89         struct uuid block_segment_uuid;
90         int block_object_id;
91
92         size_t bytes = file_read(fd, block_buf, LBS_BLOCK_SIZE);
93         if (bytes == 0)
94             break;
95
96         hash.process(block_buf, bytes);
97         OutputStream *block = data_segment->new_object(&block_segment_uuid,
98                                                        &block_object_id);
99         block->write(block_buf, bytes);
100         index_data->write_uuid(block_segment_uuid);
101         index_data->write_u32(block_object_id);
102
103         size += bytes;
104     }
105
106     file_info["sha1"] = string((const char *)hash.checksum(),
107                                hash.checksum_size());
108     file_info["data"] = encode_objref(segment_uuid, object_id);
109 }
110
111 void scanfile(const string& path)
112 {
113     int fd;
114     long flags;
115     struct stat stat_buf;
116     char *buf;
117     ssize_t len;
118
119     // Set to true if the item is a directory and we should recursively scan
120     bool recurse = false;
121
122     dictionary file_info;
123
124     lstat(path.c_str(), &stat_buf);
125
126     printf("%s\n", path.c_str());
127
128     file_info["mode"] = encode_u16(stat_buf.st_mode & 07777);
129     file_info["atime"] = encode_u64(encode_time(stat_buf.st_atime));
130     file_info["ctime"] = encode_u64(encode_time(stat_buf.st_ctime));
131     file_info["mtime"] = encode_u64(encode_time(stat_buf.st_mtime));
132     file_info["user"] = encode_u32(stat_buf.st_uid);
133     file_info["group"] = encode_u32(stat_buf.st_gid);
134
135     char inode_type;
136
137     switch (stat_buf.st_mode & S_IFMT) {
138     case S_IFIFO:
139         inode_type = 'p';
140         break;
141     case S_IFSOCK:
142         inode_type = 's';
143         break;
144     case S_IFCHR:
145         inode_type = 'c';
146         break;
147     case S_IFBLK:
148         inode_type = 'b';
149         break;
150     case S_IFLNK:
151         inode_type = 'l';
152
153         /* Use the reported file size to allocate a buffer large enough to read
154          * the symlink.  Allocate slightly more space, so that we ask for more
155          * bytes than we expect and so check for truncation. */
156         buf = new char[stat_buf.st_size + 2];
157         len = readlink(path.c_str(), buf, stat_buf.st_size + 1);
158         if (len < 0) {
159             printf("error reading symlink: %m\n");
160         } else if (len <= stat_buf.st_size) {
161             buf[len] = '\0';
162             printf("    contents=%s\n", buf);
163         } else if (len > stat_buf.st_size) {
164             printf("error reading symlink: name truncated\n");
165         }
166
167         file_info["contents"] = buf;
168
169         delete[] buf;
170         break;
171     case S_IFREG:
172         inode_type = '-';
173
174         /* Be paranoid when opening the file.  We have no guarantee that the
175          * file was not replaced between the stat() call above and the open()
176          * call below, so we might not even be opening a regular file.  That
177          * the file descriptor refers to a regular file is checked in
178          * dumpfile().  But we also supply flags to open to to guard against
179          * various conditions before we can perform that verification:
180          *   - O_NOFOLLOW: in the event the file was replaced by a symlink
181          *   - O_NONBLOCK: prevents open() from blocking if the file was
182          *     replaced by a fifo
183          * We also add in O_NOATIME, since this may reduce disk writes (for
184          * inode updates). */
185         fd = open(path.c_str(), O_RDONLY|O_NOATIME|O_NOFOLLOW|O_NONBLOCK);
186
187         /* Drop the use of the O_NONBLOCK flag; we only wanted that for file
188          * open. */
189         flags = fcntl(fd, F_GETFL);
190         fcntl(fd, F_SETFL, flags & ~O_NONBLOCK);
191
192         file_info["size"] = encode_u64(stat_buf.st_size);
193         dumpfile(fd, file_info);
194         close(fd);
195
196         break;
197     case S_IFDIR:
198         inode_type = 'd';
199         recurse = true;
200         break;
201
202     default:
203         fprintf(stderr, "Unknown inode type: mode=%x\n", stat_buf.st_mode);
204         return;
205     }
206
207     file_info["type"] = string(1, inode_type);
208
209     info_dump->write_string(path);
210     info_dump->write_dictionary(file_info);
211
212     // If we hit a directory, now that we've written the directory itself,
213     // recursively scan the directory.
214     if (recurse)
215         scandir(path);
216 }
217
218 void scandir(const string& path)
219 {
220     DIR *dir = opendir(path.c_str());
221
222     if (dir == NULL) {
223         printf("Error: %m\n");
224         return;
225     }
226
227     struct dirent *ent;
228     vector<string> contents;
229     while ((ent = readdir(dir)) != NULL) {
230         string filename(ent->d_name);
231         if (filename == "." || filename == "..")
232             continue;
233         contents.push_back(filename);
234     }
235
236     sort(contents.begin(), contents.end());
237
238     for (vector<string>::iterator i = contents.begin();
239          i != contents.end(); ++i) {
240         const string& filename = *i;
241         scanfile(path + "/" + filename);
242     }
243
244     closedir(dir);
245 }
246
247 int main(int argc, char *argv[])
248 {
249     block_buf = new char[LBS_BLOCK_SIZE];
250
251     segment_store = new SegmentStore(".");
252     SegmentWriter *sw = segment_store->new_segment();
253     info_dump = sw->new_object(NULL);
254
255     index_segment = new SegmentPartitioner(segment_store);
256     data_segment = new SegmentPartitioner(segment_store);
257
258     string uuid = SegmentWriter::format_uuid(sw->get_uuid());
259     printf("Backup UUID: %s\n", uuid.c_str());
260
261     try {
262         scanfile(".");
263     } catch (IOException e) {
264         fprintf(stderr, "IOException: %s\n", e.getError().c_str());
265     }
266
267     delete index_segment;
268     delete data_segment;
269     delete sw;
270
271     return 0;
272 }