forked from halfgaar/FlashMQ
-
Notifications
You must be signed in to change notification settings - Fork 0
/
retainedmessagesdb.cpp
202 lines (156 loc) · 6.42 KB
/
retainedmessagesdb.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
/*
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.
*/
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <exception>
#include <stdexcept>
#include <stdio.h>
#include <cstring>
#include <inttypes.h>
#include "retainedmessagesdb.h"
#include "utils.h"
#include "logger.h"
#include "mqttpacket.h"
#include "threadglobals.h"
#include "client.h"
#include "logger.h"
RetainedMessagesDB::RetainedMessagesDB(const std::string &filePath) : PersistenceFile(filePath)
{
}
void RetainedMessagesDB::openWrite()
{
PersistenceFile::openWrite(MAGIC_STRING_V4);
}
void RetainedMessagesDB::openRead()
{
PersistenceFile::openRead();
if (detectedVersionString == MAGIC_STRING_V1)
readVersion = ReadVersion::v1;
else if (detectedVersionString == MAGIC_STRING_V2)
readVersion = ReadVersion::v2;
else if (detectedVersionString == MAGIC_STRING_V3)
readVersion = ReadVersion::v3;
else if (detectedVersionString == MAGIC_STRING_V4)
readVersion = ReadVersion::v4;
else
throw std::runtime_error("Unknown file version.");
}
void RetainedMessagesDB::closeFile()
{
PersistenceFile::closeFile();
}
/**
* @brief RetainedMessagesDB::saveData doesn't explicitely name a file version (v1, etc), because we always write the current definition.
* @param messages
*/
void RetainedMessagesDB::saveData(const std::vector<RetainedMessage> &messages)
{
if (!f)
return;
CirBuf cirbuf(1024);
const int64_t now_epoch = std::chrono::duration_cast<std::chrono::seconds>(std::chrono::system_clock::now().time_since_epoch()).count();
logger->log(LOG_DEBUG) << "Saving current time stamp " << now_epoch << " in retained messages DB.";
writeInt64(now_epoch);
writeUint32(messages.size());
char reserved[RESERVED_SPACE_RETAINED_DB_V2];
std::memset(reserved, 0, RESERVED_SPACE_RETAINED_DB_V2);
writeCheck(reserved, 1, RESERVED_SPACE_RETAINED_DB_V2, f);
for (const RetainedMessage &rm : messages)
{
logger->logf(LOG_DEBUG, "Saving retained message for topic '%s' QoS %d, age %d seconds.", rm.publish.topic.c_str(), rm.publish.qos, rm.publish.getAge());
Publish pcopy(rm.publish);
MqttPacket pack(ProtocolVersion::Mqtt5, pcopy);
// Dummy, to please the parser on reading.
if (pcopy.qos > 0)
pack.setPacketId(666);
const uint32_t packSize = pack.getSizeIncludingNonPresentHeader();
const uint32_t pubAge = ageFromTimePoint(pcopy.getCreatedAt());
cirbuf.reset();
cirbuf.ensureFreeSpace(packSize + 32);
pack.readIntoBuf(cirbuf);
writeUint16(pack.getFixedHeaderLength());
writeUint32(pubAge);
writeUint32(packSize);
writeString(pcopy.client_id);
writeString(pcopy.username);
writeCheck(cirbuf.tailPtr(), 1, cirbuf.usedBytes(), f);
}
fflush(f);
}
std::list<RetainedMessage> RetainedMessagesDB::readData()
{
std::list<RetainedMessage> defaultResult;
if (!f)
return defaultResult;
if (readVersion == ReadVersion::v1)
logger->logf(LOG_WARNING, "File '%s' is version 1, an internal development version that was never finalized. Not reading.", getFilePath().c_str());
if (readVersion == ReadVersion::v2)
logger->logf(LOG_WARNING, "File '%s' is version 2, an internal development version that was never finalized. Not reading.", getFilePath().c_str());
if (readVersion == ReadVersion::v3 || readVersion == ReadVersion::v4)
return readDataV3V4();
return defaultResult;
}
std::list<RetainedMessage> RetainedMessagesDB::readDataV3V4()
{
std::list<RetainedMessage> messages;
CirBuf cirbuf(1024);
const Settings &settings = *ThreadGlobals::getSettings();
std::shared_ptr<ThreadData> dummyThreadData;
std::shared_ptr<Client> dummyClient(new Client(0, dummyThreadData, nullptr, false, false, nullptr, settings, false));
dummyClient->setClientProperties(ProtocolVersion::Mqtt5, "Dummyforloadingretained", "nobody", true, 60);
while (!feof(f))
{
bool eofFound = false;
int64_t persistence_state_age = 0;
if (readVersion >= ReadVersion::v4)
{
const int64_t fileSavedAt = readInt64(eofFound);
if (eofFound)
continue;
const int64_t now_epoch = std::chrono::duration_cast<std::chrono::seconds>(std::chrono::system_clock::now().time_since_epoch()).count();
persistence_state_age = fileSavedAt > now_epoch ? 0 : now_epoch - fileSavedAt;
}
const uint32_t numberOfMessages = readUint32(eofFound);
if (eofFound)
continue;
fseek(f, RESERVED_SPACE_RETAINED_DB_V2, SEEK_CUR);
for(uint32_t i = 0; i < numberOfMessages; i++)
{
const uint16_t fixed_header_length = readUint16(eofFound);
uint32_t originalPubAge = 0;
if (readVersion >= ReadVersion::v4)
{
originalPubAge = readUint32(eofFound);
}
const uint32_t newPubAge = persistence_state_age + originalPubAge;
const uint32_t packlen = readUint32(eofFound);
const std::string client_id = readString(eofFound);
const std::string username = readString(eofFound);
if (eofFound)
continue;
cirbuf.reset();
cirbuf.ensureFreeSpace(packlen + 32);
readCheck(cirbuf.headPtr(), 1, packlen, f);
cirbuf.advanceHead(packlen);
MqttPacket pack(cirbuf, packlen, fixed_header_length, dummyClient);
pack.parsePublishData();
Publish pub(pack.getPublishData());
pub.client_id = client_id;
pub.username = username;
// A createdAt only means something when there is expire info (internal boolean is true), so we fake it first.
pub.setExpireAfter(std::numeric_limits<uint32_t>::max());
pub.createdAt = timepointFromAge(newPubAge);
RetainedMessage msg(pub);
logger->logf(LOG_DEBUG, "Loading retained message for topic '%s' QoS %d, age %d seconds.", msg.publish.topic.c_str(), msg.publish.qos, msg.publish.getAge());
messages.push_back(std::move(msg));
}
}
return messages;
}