Skip to content

Commit b4fe824

Browse files
committed
prevent savedata corruption, and exit cleanly when systemd sends SIGTERM
1 parent ecb17a5 commit b4fe824

File tree

1 file changed

+23
-8
lines changed

1 file changed

+23
-8
lines changed

src/main.cpp

Lines changed: 23 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
#include <zmq.h>
88
#endif
99
#include <chrono>
10+
#include <memory>
1011

1112
using namespace std;
1213
using namespace ToxVPN;
@@ -48,15 +49,28 @@ int netmode = MODE_TUN;
4849

4950
bool saveState(Tox* tox) {
5051
size_t size = tox_get_savedata_size(tox);
51-
uint8_t* savedata = new uint8_t[size];
52-
tox_get_savedata(tox, savedata);
53-
int fd = open("savedata", O_TRUNC | O_WRONLY | O_CREAT, 0644);
54-
assert(fd);
55-
ssize_t written = write(fd, savedata, size);
56-
assert(written > 0); // FIXME: check even if NDEBUG is disabled
52+
auto savedata = make_unique<uint8_t[]>(size);
53+
tox_get_savedata(tox, savedata.get());
54+
int fd = open("savedata.new", O_TRUNC | O_WRONLY | O_CREAT, 0644);
55+
if (fd < 0) {
56+
perror("cant open savedata.new");
57+
return false;
58+
}
59+
ssize_t written = write(fd, savedata.get(), size);
60+
if (written != size) {
61+
printf("failed to write to savedata.new, %d bytes written out of %d\n", written, size);
62+
close(fd);
63+
return false;
64+
}
65+
int ret = fdatasync(fd);
66+
if (ret == -1) {
67+
perror("cant fdatasync to savedata.new");
68+
close(fd);
69+
return false;
70+
}
5771
close(fd);
58-
delete[] savedata;
59-
return written > 0;
72+
rename("savedata.new","savedata");
73+
return true;
6074
}
6175

6276
void do_bootstrap(Tox* tox, ToxVPNCore* toxvpn) {
@@ -362,6 +376,7 @@ int main(int argc, char** argv) {
362376
memset(&interupt, 0, sizeof(interupt));
363377
interupt.sa_handler = &handle_int;
364378
sigaction(SIGINT, &interupt, nullptr);
379+
sigaction(SIGTERM, &interupt, nullptr);
365380
#endif
366381

367382
json configRoot;

0 commit comments

Comments
 (0)