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