-
Notifications
You must be signed in to change notification settings - Fork 23
/
persistencefile.h
92 lines (72 loc) · 2.3 KB
/
persistencefile.h
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
/*
This file is part of FlashMQ (https://www.flashmq.org)
Copyright (C) 2021-2023 Wiebe Cazemier
FlashMQ is free software: you can redistribute it and/or modify
it under the terms of The Open Software License 3.0 (OSL-3.0).
See LICENSE for license details.
*/
#ifndef PERSISTENCEFILE_H
#define PERSISTENCEFILE_H
#include <vector>
#include <list>
#include <string>
#include <stdio.h>
#include <openssl/evp.h>
#include <stdexcept>
#include <cstring>
#include "logger.h"
#define MAGIC_STRING_LENGH 32
#define HASH_SIZE 64
#define TOTAL_HEADER_SIZE (MAGIC_STRING_LENGH + HASH_SIZE)
/**
* @brief The PersistenceFileCantBeOpened class should be thrown when a non-fatal file-not-found error happens.
*/
class PersistenceFileCantBeOpened : public std::runtime_error
{
public:
PersistenceFileCantBeOpened(const std::string &msg) : std::runtime_error(msg) {}
};
class PersistenceFile
{
std::string filePath;
std::string filePathTemp;
std::string filePathCorrupt;
std::string dirPath;
EVP_MD_CTX *digestContext = nullptr;
const EVP_MD *sha512 = EVP_sha512();
void hashFile();
void verifyHash();
protected:
enum class FileMode
{
unknown,
read,
write
};
FILE *f = nullptr;
std::vector<char> buf;
FileMode openMode = FileMode::unknown;
std::string detectedVersionString;
Logger *logger = Logger::getInstance();
void makeSureBufSize(size_t n);
void writeCheck(const void *__restrict __ptr, size_t __size, size_t __n, FILE *__restrict __s);
ssize_t readCheck(void *__restrict ptr, size_t size, size_t n, FILE *__restrict stream);
void writeInt64(const int64_t val);
void writeUint32(const uint32_t val);
void writeUint16(const uint16_t val);
void writeUint8(const uint8_t val);
void writeString(const std::string &s);
int64_t readInt64(bool &eofFound);
uint32_t readUint32(bool &eofFound);
uint16_t readUint16(bool &eofFound);
uint8_t readUint8(bool &eofFound);
std::string readString(bool &eofFound);
public:
PersistenceFile(const std::string &filePath);
virtual ~PersistenceFile();
void openWrite(const std::string &versionString);
void openRead(const std::string &expected_version_string);
void closeFile();
const std::string &getFilePath() const;
};
#endif // PERSISTENCEFILE_H