Add new interface for creating new segments.
[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 OutputStream *info_dump = NULL;
24
25 void scandir(const string& path);
26
27 /* Converts time to microseconds since the epoch. */
28 int64_t encode_time(time_t time)
29 {
30     return (int64_t)time * 1000000;
31 }
32
33 void dumpfile(int fd, dictionary &file_info)
34 {
35     struct stat stat_buf;
36     fstat(fd, &stat_buf);
37     int64_t size = 0;
38
39     char buf[4096];
40
41     if ((stat_buf.st_mode & S_IFMT) != S_IFREG) {
42         printf("file is no longer a regular file!\n");
43         return;
44     }
45
46     SHA1Checksum hash;
47     while (true) {
48         ssize_t res = read(fd, buf, sizeof(buf));
49         if (res < 0) {
50             if (errno == EINTR)
51                 continue;
52             printf("Error while reading: %m\n");
53             return;
54         } else if (res == 0) {
55             break;
56         } else {
57             hash.process(buf, res);
58             size += res;
59         }
60     }
61
62     file_info["sha1"] = string((const char *)hash.checksum(),
63                                hash.checksum_size());
64 }
65
66 void scanfile(const string& path)
67 {
68     int fd;
69     long flags;
70     struct stat stat_buf;
71     char *buf;
72     ssize_t len;
73
74     // Set to true if the item is a directory and we should recursively scan
75     bool recurse = false;
76
77     dictionary file_info;
78
79     lstat(path.c_str(), &stat_buf);
80
81     printf("%s\n", path.c_str());
82
83     file_info["mode"] = encode_u16(stat_buf.st_mode & 07777);
84     file_info["atime"] = encode_u64(encode_time(stat_buf.st_atime));
85     file_info["ctime"] = encode_u64(encode_time(stat_buf.st_ctime));
86     file_info["mtime"] = encode_u64(encode_time(stat_buf.st_mtime));
87     file_info["user"] = encode_u32(stat_buf.st_uid);
88     file_info["group"] = encode_u32(stat_buf.st_gid);
89
90     char inode_type;
91
92     switch (stat_buf.st_mode & S_IFMT) {
93     case S_IFIFO:
94         inode_type = 'p';
95         break;
96     case S_IFSOCK:
97         inode_type = 's';
98         break;
99     case S_IFCHR:
100         inode_type = 'c';
101         break;
102     case S_IFBLK:
103         inode_type = 'b';
104         break;
105     case S_IFLNK:
106         inode_type = 'l';
107
108         /* Use the reported file size to allocate a buffer large enough to read
109          * the symlink.  Allocate slightly more space, so that we ask for more
110          * bytes than we expect and so check for truncation. */
111         buf = new char[stat_buf.st_size + 2];
112         len = readlink(path.c_str(), buf, stat_buf.st_size + 1);
113         if (len < 0) {
114             printf("error reading symlink: %m\n");
115         } else if (len <= stat_buf.st_size) {
116             buf[len] = '\0';
117             printf("    contents=%s\n", buf);
118         } else if (len > stat_buf.st_size) {
119             printf("error reading symlink: name truncated\n");
120         }
121
122         file_info["contents"] = buf;
123
124         delete[] buf;
125         break;
126     case S_IFREG:
127         inode_type = '-';
128
129         /* Be paranoid when opening the file.  We have no guarantee that the
130          * file was not replaced between the stat() call above and the open()
131          * call below, so we might not even be opening a regular file.  That
132          * the file descriptor refers to a regular file is checked in
133          * dumpfile().  But we also supply flags to open to to guard against
134          * various conditions before we can perform that verification:
135          *   - O_NOFOLLOW: in the event the file was replaced by a symlink
136          *   - O_NONBLOCK: prevents open() from blocking if the file was
137          *     replaced by a fifo
138          * We also add in O_NOATIME, since this may reduce disk writes (for
139          * inode updates). */
140         fd = open(path.c_str(), O_RDONLY|O_NOATIME|O_NOFOLLOW|O_NONBLOCK);
141
142         /* Drop the use of the O_NONBLOCK flag; we only wanted that for file
143          * open. */
144         flags = fcntl(fd, F_GETFL);
145         fcntl(fd, F_SETFL, flags & ~O_NONBLOCK);
146
147         file_info["size"] = encode_u64(stat_buf.st_size);
148         dumpfile(fd, file_info);
149         close(fd);
150
151         break;
152     case S_IFDIR:
153         inode_type = 'd';
154         recurse = true;
155         break;
156
157     default:
158         fprintf(stderr, "Unknown inode type: mode=%x\n", stat_buf.st_mode);
159         return;
160     }
161
162     file_info["type"] = string(1, inode_type);
163
164     info_dump->write_string(path);
165     info_dump->write_dictionary(file_info);
166
167     // If we hit a directory, now that we've written the directory itself,
168     // recursively scan the directory.
169     if (recurse)
170         scandir(path);
171 }
172
173 void scandir(const string& path)
174 {
175     DIR *dir = opendir(path.c_str());
176
177     if (dir == NULL) {
178         printf("Error: %m\n");
179         return;
180     }
181
182     struct dirent *ent;
183     vector<string> contents;
184     while ((ent = readdir(dir)) != NULL) {
185         string filename(ent->d_name);
186         if (filename == "." || filename == "..")
187             continue;
188         contents.push_back(filename);
189     }
190
191     sort(contents.begin(), contents.end());
192
193     for (vector<string>::iterator i = contents.begin();
194          i != contents.end(); ++i) {
195         const string& filename = *i;
196         scanfile(path + "/" + filename);
197     }
198
199     closedir(dir);
200 }
201
202 int main(int argc, char *argv[])
203 {
204     SegmentStore ss(".");
205     SegmentWriter *sw = ss.new_segment();
206     info_dump = sw->new_object();
207
208     string uuid = SegmentWriter::format_uuid(sw->get_uuid());
209     printf("Backup UUID: %s\n", uuid.c_str());
210
211     try {
212         scanfile(".");
213     } catch (IOException e) {
214         fprintf(stderr, "IOException: %s\n", e.getError().c_str());
215     }
216
217     delete sw;
218
219     return 0;
220 }