-
-
Notifications
You must be signed in to change notification settings - Fork 8
/
backup.cpp
373 lines (281 loc) · 9.74 KB
/
backup.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
#define __STDC_FORMAT_MACROS
#define _POSIX_C_SOURCE 200112L
#define _FILE_OFFSET_BITS 64
#ifdef _WIN32
// lseek
#include <io.h>
#endif
#include "backup.h"
std::vector<int64_t> resolveBlockList(std::vector<int64_t> thisList, std::vector<int64_t> previousList) {
std::vector<int64_t> resultList;
for (int i = 0; i < thisList.size(); ) {
int64_t thisBlock = thisList[i++];
if (thisBlock < 0) {
int runStartIndex = (int) -(thisBlock + 1);
int runLength = (int) thisList[i++];
// Copy a run of block indexes from the previous revision's list of blocks
for (int j = 0; j < runLength; j++) {
resultList.push_back(previousList[runStartIndex + j]);
}
} else {
resultList.push_back(thisBlock);
}
}
return resultList;
}
BackupArchive::BackupArchive(const boost::filesystem::path &path, const std::string &key) : rootPath(path), blockDirectories(path), key(key) {
fileManifestFilename = (path / boost::filesystem::path("cpfmf")).string();
fileHistoryFilename = (path/ boost::filesystem::path("cphdf")).string();
fileManifest = fopen(fileManifestFilename.c_str(), "rb");
fileHistory = fopen(fileHistoryFilename.c_str(), "rb");
if (!fileManifest) {
throw std::runtime_error("Failed to open file manifest file '" + fileManifestFilename + "'");
}
if (!fileHistory) {
throw std::runtime_error("Failed to open file history file '" + fileHistoryFilename + "'");
}
fileHistoryHandle = fileno(fileHistory);
}
BackupArchive::~BackupArchive() {
fclose(fileManifest);
fclose(fileHistory);
}
void BackupArchive::cacheBlockIndex() {
blockDirectories.cacheIndex();
}
void readFileManifestHeader(FILE *file, FileManifestHeader &header) {
readBytes(header.fileId, file, sizeof(header.fileId));
readBytes(header.parentFileId, file, sizeof(header.parentFileId));
header.fileType = readUInt8(file);
header.version.readFrom(file);
header.fileHistoryPosition = readInt64BE(file);
header.fileHistoryLength = readInt32BE(file);
header.encPathLen = readInt16BE(file);
// If we've already slammed into the end of the file then encPathLen is garbage, don't use it
if (!feof(file)) {
header.path.resize(header.encPathLen);
readBytes((uint8_t *) &header.path[0], file, header.encPathLen);
}
}
std::string decryptEncryptedPath(std::string path, const std::string &key) {
const int MODERN_HEADER_LEN = 6;
if (path.length() >= MODERN_HEADER_LEN) {
uint8_t *bytes = (uint8_t *) path.data();
int32_t magic = readInt32BE(bytes);
uint8_t version = readUInt8(bytes);
uint8_t encryption = readUInt8(bytes);
if (magic == -420042000 && version == 1) {
path = path.substr(MODERN_HEADER_LEN);
if (encryption < CIPHER_CODE_MIN || encryption > CIPHER_CODE_MAX) {
throw std::runtime_error("Unsupported filename cipher " + std::to_string(encryption));
} else {
return code42Ciphers[encryption]->decrypt(path, key);
}
}
}
// Assume this the older headerless format that just hard-coded the use of Blowfish-128
return code42Ciphers[CIPHER_CODE_BLOWFISH_128]->decrypt(path, key);
}
BackupArchive::iterator BackupArchive::begin(FilenameMatchMode matchMode, const std::string &search) {
return BackupArchive::iterator(fileManifestFilename, key, matchMode, search);
}
BackupArchive::iterator BackupArchive::end() {
return BackupArchive::iterator(fileManifestFilename);
}
FileHistory BackupArchive::getFileHistory(const FileManifestHeader &manifest) {
FileHistory result;
lseek(fileHistoryHandle, manifest.fileHistoryPosition, SEEK_SET);
// Read the whole compressed history into a buffer:
size_t bytesToRead = manifest.fileHistoryLength;
std::string compressedHistory(bytesToRead, '\0');
while (bytesToRead > 0) {
ssize_t bytesRead = read(fileHistoryHandle, &compressedHistory[0], bytesToRead);
if (bytesRead >= 0) {
bytesToRead -= bytesRead;
if (bytesRead == 0 && bytesToRead > 0) {
throw std::runtime_error("Unexpected end of file when reading file history");
}
}
}
// History may or may not be compressed (gzip/zlib), auto-detect that and decompress it if needed:
std::string historyBuffer = maybeDecompress(compressedHistory);
// Now we can use these cursors to walk the uncompressed history data:
uint8_t *historyCursor = (uint8_t *) historyBuffer.data();
uint8_t *historyEnd = historyCursor + historyBuffer.length();
int16_t magic = readInt16BE(historyCursor);
int16_t dataVersion;
if (magic == 4242) {
dataVersion = readInt16BE(historyCursor);
} else {
historyCursor -= 2; // Unread that magic value.
/* Interestingly it looks like the subsequent MD5 field in version 0 files could be
* occasionally (1/65536) misinterpreted as a magic value
*/
dataVersion = 0;
}
readBytes(result.fileId, historyCursor, sizeof(result.fileId));
if (dataVersion >= 2) {
readBytes(result.manifestChecksum, historyCursor, sizeof(result.manifestChecksum));
}
if (memcmp(result.fileId, manifest.fileId, sizeof(manifest.fileId)) != 0) {
throw std::runtime_error("Bad revision history pointer for file, can't fetch revisions");
}
while (historyCursor < historyEnd) {
ArchivedFileVersion fileVersion;
fileVersion.readFrom(historyCursor, dataVersion);
result.versions.push_back(fileVersion);
}
return result;
}
BackupArchiveFileIterator::BackupArchiveFileIterator(const std::string &manifestFilename) :
fileManifestFilename(manifestFilename),
isEnd(true)
{
}
BackupArchiveFileIterator::BackupArchiveFileIterator(const std::string &manifestFilename,
const std::string &key, FilenameMatchMode matchMode, const std::string &search) :
fileManifestFilename(manifestFilename),
isEnd(false),
key(key),
matchMode(matchMode), search(search) {
openFileManifest();
// Advance to the first file
findNextFile();
}
void BackupArchiveFileIterator::findNextFile() {
if (!isEnd) {
bool found;
do {
off_t start = ftello(manifestFile);
readFileManifestHeader(manifestFile, currentFile);
if (feof(manifestFile)) {
isEnd = true;
fclose(manifestFile);
break;
}
try {
currentFile.path = decryptEncryptedPath(currentFile.path, key);
} catch (const std::exception &e) {
std::cerr << "Failed to decrypt path for file at offset " << std::to_string(start) << std::endl;
throw;
}
// Does this path meet our search conditions?
switch (matchMode) {
case FilenameMatchMode::none:
found = true;
break;
case FilenameMatchMode::prefix:
found = currentFile.path.find(search) == 0;
break;
case FilenameMatchMode::equals:
found = currentFile.path == search;
break;
}
} while (!found);
}
}
FileManifestHeader BackupArchiveFileIterator::operator*() {
return currentFile;
}
bool BackupArchiveFileIterator::operator==(const BackupArchiveFileIterator &that) const {
if (isEnd != that.isEnd) {
return false;
}
if (fileManifestFilename != that.fileManifestFilename) {
return false;
}
if (isEnd && that.isEnd) {
return true;
}
return ftello(manifestFile) == ftello(that.manifestFile);
}
bool BackupArchiveFileIterator::operator!=(const BackupArchiveFileIterator &that) const {
return !(*this == that);
}
BackupArchiveFileIterator &BackupArchiveFileIterator::operator++() {
findNextFile();
return *this;
}
BackupArchiveFileIterator BackupArchiveFileIterator::operator++(int) {
BackupArchiveFileIterator temp(*this);
++*this;
return temp;
}
void BackupArchiveFileIterator::openFileManifest() {
if (!isEnd) {
manifestFile = fopen(fileManifestFilename.c_str(), "rb");
if (!manifestFile) {
throw std::runtime_error(
"Failed to open archive file manifest " + fileManifestFilename);
}
}
}
BackupArchiveFileIterator::BackupArchiveFileIterator(const BackupArchiveFileIterator & that) :
fileManifestFilename(that.fileManifestFilename),
isEnd(that.isEnd),
key(that.key),
matchMode(that.matchMode), search(that.search) {
openFileManifest();
// Doesn't advance the pointer
}
BackupArchiveFileIterator &BackupArchiveFileIterator::operator=(const BackupArchiveFileIterator &that) {
if (!isEnd) {
fclose(manifestFile);
}
fileManifestFilename = that.fileManifestFilename;
isEnd = that.isEnd;
openFileManifest();
currentFile = that.currentFile;
key = that.key;
matchMode = that.matchMode;
search = that.search;
return *this;
}
BackupArchiveFileIterator::~BackupArchiveFileIterator() {
if (!isEnd) {
fclose(manifestFile);
}
}
FileHistoryIterator::FileHistoryIterator(std::vector<ArchivedFileVersion> *versions, bool end) : versions(versions), index(end ? versions->size() : 0) {
if (index == 0 && !versions->empty()) {
snapshot.version = (*versions)[0];
snapshot.blockList = resolveBlockList(snapshot.version.blockInfo, snapshot.version.blockInfo);
}
}
FileHistorySnapshot& FileHistoryIterator::operator*() {
return snapshot;
}
FileHistorySnapshot* FileHistoryIterator::operator->() {
return &snapshot;
}
bool FileHistoryIterator::operator==(const FileHistoryIterator &that) const {
return index == that.index;
}
bool FileHistoryIterator::operator!=(const FileHistoryIterator &that) const {
return index != that.index;
}
FileHistoryIterator &FileHistoryIterator::operator++() {
index++;
if (index < versions->size()) {
snapshot.version = (*versions)[index];
// Resolve backreferences in the list of block numbers using the previous revision we pointed to:
snapshot.blockList = resolveBlockList(snapshot.version.blockInfo, snapshot.blockList);
}
return *this;
}
FileHistoryIterator FileHistoryIterator::operator++(int) {
FileHistoryIterator temp(*this);
++*this;
return temp;
}
FileHistoryIterator::FileHistoryIterator(const FileHistoryIterator & that) :
versions(that.versions),
index(that.index),
snapshot(that.snapshot) {
}
FileHistoryIterator &FileHistoryIterator::operator=(const FileHistoryIterator &that) {
versions = that.versions;
index = that.index;
snapshot = that.snapshot;
return *this;
}