-
Notifications
You must be signed in to change notification settings - Fork 33
Expand file tree
/
Copy pathbridgeconfig.cpp
More file actions
417 lines (334 loc) · 12.9 KB
/
bridgeconfig.cpp
File metadata and controls
417 lines (334 loc) · 12.9 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
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
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
#include "bridgeconfig.h"
#include <sstream>
#include <openssl/ssl.h>
#include <openssl/err.h>
#include <cassert>
#include "utils.h"
#include "exceptions.h"
#include "bridgeinfodb.h"
#include "globals.h"
std::string BridgeClientGroupIds::getClientGroupShareName(const std::string &client_id_prefix)
{
std::string &s = this->bridge_share_names[client_id_prefix];
if (s.empty())
s = getSecureRandomString(12);
return s;
}
void BridgeClientGroupIds::setClientGroupShareName(const std::string &client_id_prefix, const std::string &share_name)
{
this->bridge_share_names[client_id_prefix] = share_name;
}
std::string BridgeClientGroupIds::getClientGroupId(const std::string &client_id_prefix)
{
std::string &s = this->bridge_group_ids[client_id_prefix];
if (s.empty())
s = getSecureRandomString(12);
return s;
}
void BridgeClientGroupIds::loadShareNames(const std::string &path, bool real)
{
if (path.empty())
return;
try
{
BridgeInfoDb db(path);
db.openRead();
std::list<BridgeInfoForSerializing> data = db.readInfo();
if (real)
{
for (const BridgeInfoForSerializing &d : data)
{
bridge_share_names[d.prefix] = d.client_group_share_name;
}
}
}
catch (PersistenceFileCantBeOpened &ex) {}
}
void BridgeClientGroupIds::saveShareNames(const std::string &path) const
{
if (path.empty())
return;
std::list<BridgeInfoForSerializing> bridgeInfos;
for (const auto &p : bridge_share_names)
{
BridgeInfoForSerializing ser;
ser.prefix = p.first;
ser.client_group_share_name = p.second;
bridgeInfos.emplace_back(std::move(ser));
}
BridgeInfoDb bridgeInfoDb(path);
bridgeInfoDb.openWrite();
bridgeInfoDb.saveInfo(bridgeInfos);
}
bool BridgeTopicPath::isValidQos() const
{
return qos < 3;
}
bool BridgeTopicPath::operator==(const BridgeTopicPath &other) const
{
return this->topic == other.topic && this->qos == other.qos;
}
BridgeState::BridgeState(const BridgeConfig &config) :
c(config)
{
}
FMQSockaddr BridgeState::popDnsResult()
{
if (dnsResults.empty())
throw std::runtime_error("Trying to get DNS results when there are none");
FMQSockaddr addr = dnsResults.front();
dnsResults.pop_front();
return addr;
}
void BridgeState::initSSL(bool reloadCertificates)
{
if (this->c.tlsMode == BridgeTLSMode::None)
return;
if (reloadCertificates)
this->sslInitialized = false;
if (this->sslInitialized)
return;
sslctx.emplace(TLS_client_method());
sslctx->setMinimumTlsVersion(c.minimumTlsVersion);
SSL_CTX_set_mode(sslctx->get(), SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
const char *privkey = c.sslPrivkey.empty() ? nullptr : c.sslPrivkey.c_str();
const char *fullchain = c.sslFullchain.empty() ? nullptr : c.sslFullchain.c_str();
if (fullchain)
{
if (SSL_CTX_use_certificate_chain_file(sslctx->get(), fullchain) != 1)
{
ERR_print_errors_cb(logSslError, NULL);
throw std::runtime_error("Loading bridge SSL fullchain failed. This was after test loading the certificate, so is very unexpected.");
}
}
if (privkey)
{
if (SSL_CTX_use_PrivateKey_file(sslctx->get(), privkey, SSL_FILETYPE_PEM) != 1)
{
ERR_print_errors_cb(logSslError, NULL);
throw std::runtime_error("Loading bridge SSL privkey failed. This was after test loading the certificate, so is very unexpected.");
}
if (SSL_CTX_check_private_key(sslctx->get()) != 1)
{
ERR_print_errors_cb(logSslError, NULL);
throw std::runtime_error("Verifying bridge SSL privkey failed. This was after test loading the certificate, so is very unexpected.");
}
}
const char *ca_file = c.caFile.empty() ? nullptr : c.caFile.c_str();
const char *ca_dir = c.caDir.empty() ? nullptr : c.caDir.c_str();
if (ca_file || ca_dir)
{
if (SSL_CTX_load_verify_locations(sslctx->get(), ca_file, ca_dir) != 1)
{
ERR_print_errors_cb(logSslError, NULL);
throw std::runtime_error("Loading ca_dir/ca_file failed. This was after test loading the certificate, so is very unexpected.");
}
}
else
{
if (SSL_CTX_set_default_verify_paths(sslctx->get()) != 1)
{
ERR_print_errors_cb(logSslError, NULL);
throw std::runtime_error("Setting default SSL paths failed.");
}
}
this->sslInitialized = true;
}
bool BridgeState::timeForNewReconnectAttempt()
{
/*
* When we are part of a group of connections to a server, don't back off reconnection, because we want to keep all
* of the individual connections on-line, and not have some lag behind.
*/
if (c.getFmqClientGroupId().has_value())
return true;
int next = 1;
if (reconnectCounter > 0)
next = baseReconnectInterval;
if (reconnectCounter > 10)
next = baseReconnectInterval + 300;
if (next > 1 && intervalLogged != next)
{
intervalLogged = next;
Logger *logger = Logger::getInstance();
logger->log(LOG_NOTICE) << "Bridge '" << c.clientidPrefix << "' connection failure count: " << reconnectCounter
<< ". Increasing reconnect interval to " << next << " seconds.";
}
return lastReconnectAttempt + std::chrono::seconds(next) < std::chrono::steady_clock::now();
}
void BridgeState::registerReconnect()
{
lastReconnectAttempt = std::chrono::steady_clock::now();
reconnectCounter++;
}
void BridgeState::resetReconnectCounter()
{
lastReconnectAttempt = std::chrono::time_point<std::chrono::steady_clock>();
reconnectCounter = 0;
intervalLogged = 0;
}
void BridgeState::resetThreadOwners()
{
session.reset_thread();
threadData.reset_thread();
}
/**
* @brief BridgeConfig::setClientId is for setting the client ID on start to the one from a saved state. That's why it only works when the prefix matches.
* @param prefix
* @param id
*/
void BridgeConfig::setClientId(const std::string &prefix, const std::string &id)
{
// This is protection against calling this method too early.
assert(!clientid.empty());
// Should never happen, but just in case; an empty client id can get confusing.
if (id.empty())
return;
if (prefix != this->clientidPrefix)
return;
this->clientid = id;
}
void BridgeConfig::setClientId()
{
if (!clientid.empty())
return;
if (clientidPrefix.length() > this->client_id_max_length)
throw std::runtime_error("clientidPrefix can't be longer than 10");
std::ostringstream oss;
oss << clientidPrefix << "_" << getSecureRandomString(10);
clientid = oss.str();
}
void BridgeConfig::appendConnectionNumber(size_t no)
{
std::string no_s = std::to_string(no);
this->client_id_max_length += no_s.length() + 1;
this->clientidPrefix.append("_").append(std::to_string(no));
}
void BridgeConfig::setSharedSubscriptionName(const std::string &share_name)
{
setSharedSubscriptionName(publishes, share_name);
setSharedSubscriptionName(subscribes, share_name);
}
void BridgeConfig::setSharedSubscriptionName(std::vector<BridgeTopicPath> &topics, const std::string &share_name)
{
for (BridgeTopicPath &t : topics)
{
std::vector<std::string> subtopics = splitTopic(t.topic);
std::string _;
std::string __;
parseSubscriptionShare(subtopics, _, __);
std::string new_topic("$share/");
new_topic.append(share_name);
for (const std::string &s : subtopics)
{
new_topic.append("/");
new_topic.append(s);
}
t.topic = new_topic;
}
}
const std::string &BridgeConfig::getClientid() const
{
return clientid;
}
const std::optional<std::string> &BridgeConfig::getFmqClientGroupId() const
{
return this->fmq_client_group_id;
}
void BridgeConfig::isValid()
{
if (sslPrivkey.empty() != sslFullchain.empty())
throw ConfigFileException("Specify both 'privkey' and 'fullchain' or neither.");
if (tlsMode > BridgeTLSMode::None)
{
if (port == 0)
{
port = 8883;
}
if (sslFullchain.size() || sslPrivkey.size())
{
testSsl(sslFullchain, sslPrivkey);
}
testSslVerifyLocations(caFile, caDir, "Loading bridge ca_file/ca_dir failed.");
}
else
{
if (port == 0)
{
port = 1883;
}
}
if (address.empty())
throw ConfigFileException("No address specified in bridge");
if (publishes.empty() && subscribes.empty())
throw ConfigFileException("No subscribe or publish paths defined in bridge.");
if (!caDir.empty() && !caFile.empty())
throw ConfigFileException("Specify only one 'ca_file' or 'ca_dir'");
if (clientidPrefix.length() > client_id_max_length)
throw ConfigFileException("clientidPrefix can't be longer than 10");
if (protocolVersion <= ProtocolVersion::Mqtt311 && remote_password.has_value() && !remote_username.has_value())
throw ConfigFileException("MQTT 3.1.1 and lower require a username when you set a password.");
if (local_prefix && !endsWith(local_prefix.value(), "/"))
throw ConfigFileException("Option 'local_prefix' must end in a '/'.");
if (remote_prefix && !endsWith(remote_prefix.value(), "/"))
throw ConfigFileException("Option 'remote_prefix' must end in a '/'.");
if (connection_count > 1 && protocolVersion < ProtocolVersion::Mqtt5)
throw ConfigFileException("Using multiple bridge connections needs at least MQTT5");
if (connection_count > 1)
{
auto check = [](const BridgeTopicPath &x)
{
if (startsWith(x.topic, "$share"))
{
throw ConfigFileException("Bridges with multiple connections can't already define share names in the topics.");
}
};
std::for_each(publishes.begin(), publishes.end(), check);
std::for_each(subscribes.begin(), subscribes.end(), check);
}
}
std::vector<BridgeConfig> BridgeConfig::multiply() const
{
std::vector<BridgeConfig> result;
result.reserve(this->connection_count);
const std::string share_name = globals->bridgeClientGroupIds.getClientGroupShareName(this->clientidPrefix);
const std::string group_id = globals->bridgeClientGroupIds.getClientGroupId(this->clientidPrefix);
for (size_t i = 0; i < this->connection_count; i++)
{
result.push_back(*this);
if (this->connection_count > 1)
{
result.back().setSharedSubscriptionName(share_name);
/*
* This means that when people have an existing bridge config with `use_saved_clientid`, it will lose its state when
* they change the amount of connections from 1 to something else. That's good, because otherwise one of the
* connections will get session state that no longer applies to it.
*/
result.back().appendConnectionNumber(i);
result.back().fmq_client_group_id = group_id;
}
result.back().setClientId();
result.back().connection_count = 1;
result.back().isValid();
}
return result;
}
bool BridgeConfig::operator ==(const BridgeConfig &other) const
{
return this->address == other.address && this->port == other.port && this->inet_protocol == other.inet_protocol && this->tlsMode == other.tlsMode
&& this->sslFullchain == other.sslFullchain && this->sslPrivkey == other.sslPrivkey && this->caFile == other.caFile && this->caDir == other.caDir && this->protocolVersion == other.protocolVersion
&& this->bridgeProtocolBit == other.bridgeProtocolBit && this->keepalive == other.keepalive && this->clientidPrefix == other.clientidPrefix
&& this->publishes == other.publishes && this->subscribes == other.subscribes && this->local_username == other.local_username
&& this->remote_username == other.remote_username && this->remote_password == other.remote_password && this->remoteCleanStart == other.remoteCleanStart
&& this->localCleanStart == other.localCleanStart && this->remoteSessionExpiryInterval == other.remoteSessionExpiryInterval
&& this->localSessionExpiryInterval == other.localSessionExpiryInterval && this->remoteRetainAvailable == other.remoteRetainAvailable
&& this->useSavedClientId == other.useSavedClientId && this->maxOutgoingTopicAliases == other.maxOutgoingTopicAliases
&& this->maxIncomingTopicAliases == other.maxIncomingTopicAliases && this->tcpNoDelay == other.tcpNoDelay
&& this->local_prefix == other.local_prefix && this->remote_prefix == other.remote_prefix && this->connection_count == other.connection_count
&& this->maxBufferSize == other.maxBufferSize;
}
bool BridgeConfig::operator !=(const BridgeConfig &other) const
{
bool r = *this == other;
return !r;
}