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