Compute SHA-1 checksums of regular files to be stored with index data.
[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     dictionary file_info;
75
76     lstat(path.c_str(), &stat_buf);
77
78     printf("%s\n", path.c_str());
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         inode_type = 'p';
92         break;
93     case S_IFSOCK:
94         inode_type = 's';
95         break;
96     case S_IFCHR:
97         inode_type = 'c';
98         break;
99     case S_IFBLK:
100         inode_type = 'b';
101         break;
102     case S_IFLNK:
103         inode_type = 'l';
104
105         /* Use the reported file size to allocate a buffer large enough to read
106          * the symlink.  Allocate slightly more space, so that we ask for more
107          * bytes than we expect and so check for truncation. */
108         buf = new char[stat_buf.st_size + 2];
109         len = readlink(path.c_str(), buf, stat_buf.st_size + 1);
110         if (len < 0) {
111             printf("error reading symlink: %m\n");
112         } else if (len <= stat_buf.st_size) {
113             buf[len] = '\0';
114             printf("    contents=%s\n", buf);
115         } else if (len > stat_buf.st_size) {
116             printf("error reading symlink: name truncated\n");
117         }
118
119         file_info["contents"] = buf;
120
121         delete[] buf;
122         break;
123     case S_IFREG:
124         inode_type = '-';
125
126         /* Be paranoid when opening the file.  We have no guarantee that the
127          * file was not replaced between the stat() call above and the open()
128          * call below, so we might not even be opening a regular file.  That
129          * the file descriptor refers to a regular file is checked in
130          * dumpfile().  But we also supply flags to open to to guard against
131          * various conditions before we can perform that verification:
132          *   - O_NOFOLLOW: in the event the file was replaced by a symlink
133          *   - O_NONBLOCK: prevents open() from blocking if the file was
134          *     replaced by a fifo
135          * We also add in O_NOATIME, since this may reduce disk writes (for
136          * inode updates). */
137         fd = open(path.c_str(), O_RDONLY|O_NOATIME|O_NOFOLLOW|O_NONBLOCK);
138
139         /* Drop the use of the O_NONBLOCK flag; we only wanted that for file
140          * open. */
141         flags = fcntl(fd, F_GETFL);
142         fcntl(fd, F_SETFL, flags & ~O_NONBLOCK);
143
144         file_info["size"] = encode_u64(stat_buf.st_size);
145         dumpfile(fd, file_info);
146         close(fd);
147
148         break;
149     case S_IFDIR:
150         inode_type = 'd';
151         scandir(path);
152         break;
153
154     default:
155         fprintf(stderr, "Unknown inode type: mode=%x\n", stat_buf.st_mode);
156         return;
157     }
158
159     file_info["type"] = string(1, inode_type);
160
161     info_dump->write_string(path);
162     info_dump->write_dictionary(file_info);
163 }
164
165 void scandir(const string& path)
166 {
167     DIR *dir = opendir(path.c_str());
168
169     if (dir == NULL) {
170         printf("Error: %m\n");
171         return;
172     }
173
174     struct dirent *ent;
175     vector<string> contents;
176     while ((ent = readdir(dir)) != NULL) {
177         string filename(ent->d_name);
178         if (filename == "." || filename == "..")
179             continue;
180         contents.push_back(filename);
181     }
182
183     sort(contents.begin(), contents.end());
184
185     for (vector<string>::iterator i = contents.begin();
186          i != contents.end(); ++i) {
187         const string& filename = *i;
188         scanfile(path + "/" + filename);
189     }
190
191     closedir(dir);
192 }
193
194 int main(int argc, char *argv[])
195 {
196     FILE *dump = fopen("fileinfo", "w");
197     if (dump == NULL) {
198         fprintf(stderr, "Cannot open fileinfo: %m\n");
199         return 1;
200     }
201
202     FileOutputStream os(dump);
203     info_dump = &os;
204
205     try {
206         scanfile(".");
207     } catch (IOException e) {
208         fprintf(stderr, "IOException: %s\n", e.getError().c_str());
209     }
210
211     return 0;
212 }