-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathbackup.cpp
More file actions
72 lines (60 loc) · 1.53 KB
/
backup.cpp
File metadata and controls
72 lines (60 loc) · 1.53 KB
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
#include <sys/types.h>
#include <unistd.h>
#include <cerrno>
#include <cstdint>
#include <cstring>
#include <fstream>
#include <memory>
#include "backup.hpp"
#include "errors.hpp"
#include "luks.hpp"
#include "os.hpp"
namespace fluks {
namespace {
void
read_all(int fd, void *buf, size_t count) {
ssize_t remaining = count;
uint8_t *pos = static_cast<uint8_t *>(buf);
while (remaining > 0) {
ssize_t by = ::read(fd, pos, remaining);
if (by < 0)
throw_errno(errno);
if (!by)
throw Disk_error("premature EOF");
remaining -= by;
pos += by;
}
}
}
}
/**
* \throws std::system_error
* \throws Disk_error
* \throws No_header
* \throws Unsupported_version
*/
void
fluks::make_backup(int device, const std::string &backup_path) {
struct phdr1 hdr;
// read the header
if (lseek(device, 0, SEEK_SET) == static_cast<off_t>(-1))
throw_errno(errno);
read_all(device, &hdr, sizeof hdr);
// check the header
endian_switch(&hdr, false);
if (!check_magic(&hdr)) throw No_header();
if (!check_version_1(&hdr)) throw Unsupported_version();
size_t bytes = sector_size(device) * hdr.off_payload - sizeof hdr;
endian_switch(&hdr, false);
// read the remainder
std::unique_ptr<char[]> buf{new char[bytes]};
read_all(device, buf.get(), bytes);
// open dump
std::ofstream dump(backup_path.c_str(),
std::ios_base::binary | std::ios_base::out | std::ios_base::trunc);
if (!dump)
throw Disk_error("failed to open output file");
// dump the header
dump.write(reinterpret_cast<char *>(&hdr), sizeof hdr);
dump.write(buf.get(), bytes);
}