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