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