1 /* Recursively descend the filesystem and visit each file. */
11 #include <sys/types.h>
34 static TarSegmentStore *tss = NULL;
36 /* Buffer for holding a single block of data read from a file. */
37 static const size_t LBS_BLOCK_SIZE = 1024 * 1024;
38 static char *block_buf;
40 static const size_t LBS_METADATA_BLOCK_SIZE = 65536;
42 /* Local database, which tracks objects written in this and previous
43 * invocations to help in creating incremental snapshots. */
46 /* Contents of the root object. This will contain a set of indirect links to
47 * the metadata objects. */
48 std::ostringstream metadata_root;
50 /* Buffer for building up metadata. */
51 std::ostringstream metadata;
53 /* Keep track of all segments which are needed to reconstruct the snapshot. */
54 std::set<string> segment_list;
56 void scandir(const string& path);
58 /* Ensure contents of metadata are flushed to an object. */
61 string m = metadata.str();
65 /* Write current metadata information to a new object. */
66 LbsObject *meta = new LbsObject;
67 meta->set_group("root");
68 meta->set_data(m.data(), m.size());
72 /* Write a reference to this block in the root. */
73 ObjectReference ref = meta->get_ref();
74 metadata_root << "@" << ref.to_string() << "\n";
75 segment_list.insert(ref.get_segment());
82 /* Read data from a file descriptor and return the amount of data read. A
83 * short read (less than the requested size) will only occur if end-of-file is
85 size_t file_read(int fd, char *buf, size_t maxlen)
87 size_t bytes_read = 0;
90 ssize_t res = read(fd, buf, maxlen);
94 throw IOException("file_read: error reading");
95 } else if (res == 0) {
107 /* Read the contents of a file (specified by an open file descriptor) and copy
108 * the data to the store. Returns the size of the file (number of bytes
109 * dumped), or -1 on error. */
110 int64_t dumpfile(int fd, dictionary &file_info)
112 struct stat stat_buf;
113 fstat(fd, &stat_buf);
115 list<string> object_list;
117 if ((stat_buf.st_mode & S_IFMT) != S_IFREG) {
118 fprintf(stderr, "file is no longer a regular file!\n");
122 /* The index data consists of a sequence of pointers to the data blocks
123 * that actually comprise the file data. This level of indirection is used
124 * so that the same data block can be used in multiple files, or multiple
125 * versions of the same file. */
128 size_t bytes = file_read(fd, block_buf, LBS_BLOCK_SIZE);
132 hash.process(block_buf, bytes);
134 // Either find a copy of this block in an already-existing segment, or
135 // index it so it can be re-used in the future
136 SHA1Checksum block_hash;
137 block_hash.process(block_buf, bytes);
138 string block_csum = block_hash.checksum_str();
139 ObjectReference ref = db->FindObject(block_csum, bytes);
141 // Store a copy of the object if one does not yet exist
142 if (ref.get_segment().size() == 0) {
143 LbsObject *o = new LbsObject;
144 o->set_group("data");
145 o->set_data(block_buf, bytes);
148 db->StoreObject(ref, block_csum, bytes);
151 object_list.push_back(ref.to_string());
152 segment_list.insert(ref.get_segment());
156 file_info["checksum"] = hash.checksum_str();
158 /* For files that only need to be broken apart into a few objects, store
159 * the list of objects directly. For larger files, store the data
160 * out-of-line and provide a pointer to the indrect object. */
161 if (object_list.size() < 8) {
162 string blocklist = "";
163 for (list<string>::iterator i = object_list.begin();
164 i != object_list.end(); ++i) {
165 if (i != object_list.begin())
169 file_info["data"] = blocklist;
171 string blocklist = "";
172 for (list<string>::iterator i = object_list.begin();
173 i != object_list.end(); ++i) {
174 blocklist += *i + "\n";
177 LbsObject *i = new LbsObject;
178 i->set_group("indirect");
179 i->set_data(blocklist.data(), blocklist.size());
181 file_info["data"] = "@" + i->get_name();
182 segment_list.insert(i->get_ref().get_segment());
189 void scanfile(const string& path)
193 struct stat stat_buf;
199 // Set to true if the item is a directory and we should recursively scan
200 bool recurse = false;
202 dictionary file_info;
204 lstat(path.c_str(), &stat_buf);
206 printf("%s\n", path.c_str());
208 metadata << "name: " << uri_encode(path) << "\n";
210 file_info["mode"] = encode_int(stat_buf.st_mode & 07777);
211 file_info["mtime"] = encode_int(stat_buf.st_mtime);
212 file_info["user"] = encode_int(stat_buf.st_uid);
213 file_info["group"] = encode_int(stat_buf.st_gid);
215 struct passwd *pwd = getpwuid(stat_buf.st_uid);
217 file_info["user"] += " (" + uri_encode(pwd->pw_name) + ")";
220 struct group *grp = getgrgid(stat_buf.st_gid);
222 file_info["group"] += " (" + uri_encode(grp->gr_name) + ")";
227 switch (stat_buf.st_mode & S_IFMT) {
243 /* Use the reported file size to allocate a buffer large enough to read
244 * the symlink. Allocate slightly more space, so that we ask for more
245 * bytes than we expect and so check for truncation. */
246 buf = new char[stat_buf.st_size + 2];
247 len = readlink(path.c_str(), buf, stat_buf.st_size + 1);
249 fprintf(stderr, "error reading symlink: %m\n");
250 } else if (len <= stat_buf.st_size) {
252 file_info["contents"] = uri_encode(buf);
253 } else if (len > stat_buf.st_size) {
254 fprintf(stderr, "error reading symlink: name truncated\n");
262 /* Be paranoid when opening the file. We have no guarantee that the
263 * file was not replaced between the stat() call above and the open()
264 * call below, so we might not even be opening a regular file. That
265 * the file descriptor refers to a regular file is checked in
266 * dumpfile(). But we also supply flags to open to to guard against
267 * various conditions before we can perform that verification:
268 * - O_NOFOLLOW: in the event the file was replaced by a symlink
269 * - O_NONBLOCK: prevents open() from blocking if the file was
271 * We also add in O_NOATIME, since this may reduce disk writes (for
273 fd = open(path.c_str(), O_RDONLY|O_NOATIME|O_NOFOLLOW|O_NONBLOCK);
275 /* Drop the use of the O_NONBLOCK flag; we only wanted that for file
277 flags = fcntl(fd, F_GETFL);
278 fcntl(fd, F_SETFL, flags & ~O_NONBLOCK);
280 file_size = dumpfile(fd, file_info);
281 file_info["size"] = encode_int(file_size);
285 return; // error occurred; do not dump file
287 if (file_size != stat_buf.st_size) {
288 fprintf(stderr, "Warning: Size of %s changed during reading\n",
299 fprintf(stderr, "Unknown inode type: mode=%x\n", stat_buf.st_mode);
303 file_info["type"] = string(1, inode_type);
305 dict_output(metadata, file_info);
308 // Break apart metadata listing if it becomes too large.
309 if (metadata.str().size() > LBS_METADATA_BLOCK_SIZE)
312 // If we hit a directory, now that we've written the directory itself,
313 // recursively scan the directory.
318 void scandir(const string& path)
320 DIR *dir = opendir(path.c_str());
323 fprintf(stderr, "Error: %m\n");
328 vector<string> contents;
329 while ((ent = readdir(dir)) != NULL) {
330 string filename(ent->d_name);
331 if (filename == "." || filename == "..")
333 contents.push_back(filename);
336 sort(contents.begin(), contents.end());
338 for (vector<string>::iterator i = contents.begin();
339 i != contents.end(); ++i) {
340 const string& filename = *i;
341 scanfile(path + "/" + filename);
347 int main(int argc, char *argv[])
349 block_buf = new char[LBS_BLOCK_SIZE];
351 string backup_dest = ".";
354 backup_dest = argv[1];
356 tss = new TarSegmentStore(backup_dest);
358 string database_path = backup_dest + "/localdb.sqlite";
360 db->Open(database_path.c_str());
362 /* Write a backup descriptor file, which says which segments are needed and
363 * where to start to restore this snapshot. The filename is based on the
369 localtime_r(&now, &time_buf);
370 strftime(desc_buf, sizeof(desc_buf), "%Y%m%dT%H%M%S", &time_buf);
371 string desc_filename = backup_dest + "/" + desc_buf + ".lbs";
372 std::ofstream descriptor(desc_filename.c_str());
376 } catch (IOException e) {
377 fprintf(stderr, "IOException: %s\n", e.getError().c_str());
381 const string md = metadata_root.str();
383 LbsObject *root = new LbsObject;
384 root->set_group("root");
385 root->set_data(md.data(), md.size());
389 segment_list.insert(root->get_ref().get_segment());
390 descriptor << "Root: " << root->get_ref().to_string() << "\n";
391 strftime(desc_buf, sizeof(desc_buf), "%Y-%m-%d %H:%M:%S %z", &time_buf);
392 descriptor << "Date: " << desc_buf << "\n";
396 descriptor << "Segments:\n";
397 for (std::set<string>::iterator i = segment_list.begin();
398 i != segment_list.end(); ++i) {
399 descriptor << " " << *i << "\n";