-
Notifications
You must be signed in to change notification settings - Fork 18
Expand file tree
/
Copy pathGatewayConnectionManager.cpp
More file actions
301 lines (238 loc) · 8.79 KB
/
GatewayConnectionManager.cpp
File metadata and controls
301 lines (238 loc) · 8.79 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
#include "GatewayConnectionManager.h"
const char* const TAG = "GatewayConnectionManager";
#include "VisualStateManager.h"
#include "config/Config.h"
#include "Core.h"
#include "GatewayClient.h"
#include "http/JsonAPI.h"
#include "Logging.h"
#include <unordered_map>
//
// ###### ######## ###### ## ## ######## #### ######## ## ## ######## #### ###### ## ##
// ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ##
// ## ## ## ## ## ## ## ## ## #### ## ## ## ## ## ##
// ###### ###### ## ## ## ######## ## ## ## ######## ## ###### #####
// ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ##
// ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ##
// ###### ######## ###### ####### ## ## #### ## ## ## ## #### ###### ## ##
//
// TODO: Fix loading CA Certificate bundles, currently fails with "[esp_crt_bundle.c:161] esp_crt_bundle_init(): Unable to allocate memory for bundle"
// This is probably due to the fact that the bundle is too large for the ESP32's heap or the bundle is incorrectly packedy them
//
#warning SSL certificate verification is currently not implemented, by RFC definition this is a security risk, and allows for MITM attacks, but the realistic risk is low
const char* const AUTH_TOKEN_FILE = "/authToken";
const uint8_t FLAG_NONE = 0;
const uint8_t FLAG_HAS_IP = 1 << 0;
const uint8_t FLAG_LINKED = 1 << 1;
const uint8_t LINK_CODE_LENGTH = 6;
static uint8_t s_flags = 0;
static int64_t s_lastAuthFailure = 0;
static int64_t s_lastConnectionAttempt = 0;
static std::unique_ptr<OpenShock::GatewayClient> s_wsClient = nullptr;
static void evh_gotIP(arduino_event_t* event)
{
(void)event;
s_flags |= FLAG_HAS_IP;
OS_LOGD(TAG, "Got IP address");
}
static void evh_wiFiDisconnected(arduino_event_t* event)
{
(void)event;
s_flags = FLAG_NONE;
s_wsClient = nullptr;
OS_LOGD(TAG, "Lost IP address");
}
static bool checkIsDeAuthRateLimited(int64_t millis)
{
return s_lastAuthFailure != 0 && (millis - s_lastAuthFailure) < 300'000; // 5 Minutes
}
static bool checkIsConnectionRateLimited(int64_t millis)
{
return s_lastConnectionAttempt != 0 && (millis - s_lastConnectionAttempt) < 20'000; // 20 seconds
}
using namespace OpenShock;
namespace JsonAPI = OpenShock::Serialization::JsonAPI;
bool GatewayConnectionManager::Init()
{
WiFi.onEvent(evh_gotIP, ARDUINO_EVENT_WIFI_STA_GOT_IP);
WiFi.onEvent(evh_gotIP, ARDUINO_EVENT_WIFI_STA_GOT_IP6);
WiFi.onEvent(evh_wiFiDisconnected, ARDUINO_EVENT_WIFI_STA_DISCONNECTED);
return true;
}
bool GatewayConnectionManager::IsConnected()
{
if (s_wsClient == nullptr) {
return false;
}
return s_wsClient->state() == GatewayClientState::Connected;
}
bool GatewayConnectionManager::IsLinked()
{
return (s_flags & FLAG_LINKED) != 0;
}
AccountLinkResultCode GatewayConnectionManager::Link(std::string_view linkCode)
{
if ((s_flags & FLAG_HAS_IP) == 0) {
return AccountLinkResultCode::NoInternetConnection;
}
s_wsClient = nullptr;
OS_LOGD(TAG, "Attempting to link to account using code %.*s", linkCode.length(), linkCode.data());
if (linkCode.length() != LINK_CODE_LENGTH) {
OS_LOGE(TAG, "Invalid link code length");
return AccountLinkResultCode::InvalidCode;
}
auto response = HTTP::JsonAPI::LinkAccount(linkCode);
if (response.code == 404) {
return AccountLinkResultCode::InvalidCode;
}
if (response.result == HTTP::RequestResult::RateLimited) {
OS_LOGW(TAG, "Account Link request got ratelimited");
return AccountLinkResultCode::RateLimited;
}
if (response.result != HTTP::RequestResult::Success) {
OS_LOGE(TAG, "Error while getting auth token: %s %d", response.ResultToString(), response.code);
return AccountLinkResultCode::InternalError;
}
if (response.code != 200) {
OS_LOGE(TAG, "Unexpected response code: %d", response.code);
return AccountLinkResultCode::InternalError;
}
if (response.data.authToken.empty()) {
OS_LOGE(TAG, "Received empty auth token");
return AccountLinkResultCode::InternalError;
}
if (!Config::SetBackendAuthToken(std::move(response.data.authToken))) {
OS_LOGE(TAG, "Failed to save auth token");
return AccountLinkResultCode::InternalError;
}
s_flags |= FLAG_LINKED;
OS_LOGD(TAG, "Successfully linked to account");
return AccountLinkResultCode::Success;
}
void GatewayConnectionManager::UnLink()
{
s_flags &= FLAG_HAS_IP;
s_wsClient = nullptr;
Config::ClearBackendAuthToken();
}
bool GatewayConnectionManager::SendMessageTXT(std::string_view data)
{
if (s_wsClient == nullptr) {
return false;
}
return s_wsClient->sendMessageTXT(data);
}
bool GatewayConnectionManager::SendMessageBIN(tcb::span<const uint8_t> data)
{
if (s_wsClient == nullptr) {
return false;
}
return s_wsClient->sendMessageBIN(data);
}
bool FetchHubInfo(std::string authToken)
{
// TODO: this function is very slow, should be optimized!
if ((s_flags & FLAG_HAS_IP) == 0) {
return false;
}
if (checkIsDeAuthRateLimited(OpenShock::millis())) {
return false;
}
auto response = HTTP::JsonAPI::GetHubInfo(std::move(authToken));
if (response.code == 401) {
OS_LOGD(TAG, "Auth token is invalid, waiting 5 minutes before checking again");
s_lastAuthFailure = OpenShock::micros();
return false;
}
if (response.result == HTTP::RequestResult::RateLimited) {
return false; // Just return false, don't spam the console with errors
}
if (response.result != HTTP::RequestResult::Success) {
OS_LOGE(TAG, "Error while fetching hub info: %s %d", response.ResultToString(), response.code);
return false;
}
if (response.code != 200) {
OS_LOGE(TAG, "Unexpected response code: %d", response.code);
return false;
}
OS_LOGI(TAG, "Hub ID: %s", response.data.hubId.c_str());
OS_LOGI(TAG, "Hub Name: %s", response.data.hubName.c_str());
OS_LOGI(TAG, "Shockers:");
for (auto& shocker : response.data.shockers) {
OS_LOGI(TAG, " [%s] rf=%u model=%u", shocker.id.c_str(), shocker.rfId, shocker.model);
}
s_flags |= FLAG_LINKED;
return true;
}
bool StartConnectingToLCG()
{
// TODO: this function is very slow, should be optimized!
if (s_wsClient == nullptr) { // If wsClient is already initialized, we are already paired or connected
OS_LOGD(TAG, "wsClient is null");
return false;
}
if (s_wsClient->state() != GatewayClientState::Disconnected) {
OS_LOGD(TAG, "WebSocketClient is not disconnected, waiting...");
s_wsClient->disconnect();
return false;
}
int64_t msNow = OpenShock::millis();
if (checkIsDeAuthRateLimited(msNow) || checkIsConnectionRateLimited(msNow)) {
return false;
}
s_lastConnectionAttempt = msNow;
if (!Config::HasBackendAuthToken()) {
OS_LOGD(TAG, "No auth token, can't connect to LCG");
return false;
}
std::string authToken;
if (!Config::GetBackendAuthToken(authToken)) {
OS_LOGE(TAG, "Failed to get auth token");
return false;
}
auto response = HTTP::JsonAPI::AssignLcg(std::move(authToken));
if (response.code == 401) {
OS_LOGD(TAG, "Auth token is invalid, waiting 5 minutes before retrying");
s_lastAuthFailure = OpenShock::micros();
return false;
}
if (response.result == HTTP::RequestResult::RateLimited) {
return false; // Just return false, don't spam the console with errors
}
if (response.result != HTTP::RequestResult::Success) {
OS_LOGE(TAG, "Error while fetching LCG endpoint: %s %d", response.ResultToString(), response.code);
return false;
}
if (response.code != 200) {
OS_LOGE(TAG, "Unexpected response code: %d", response.code);
return false;
}
OS_LOGI(TAG, "Connecting to LCG endpoint { host: '%s', port: %hu, path: '%s' } in country %s", response.data.host.c_str(), response.data.port, response.data.path.c_str(), response.data.country.c_str());
s_wsClient->connect(response.data.host, response.data.port, response.data.path);
return true;
}
void GatewayConnectionManager::Update()
{
if (s_wsClient == nullptr) {
// Can't connect to the API without WiFi or an auth token
if ((s_flags & FLAG_HAS_IP) == 0 || !Config::HasBackendAuthToken()) {
return;
}
std::string authToken;
if (!Config::GetBackendAuthToken(authToken)) {
OS_LOGE(TAG, "Failed to get auth token");
return;
}
// Fetch hub info
if (!FetchHubInfo(authToken)) {
return;
}
s_flags |= FLAG_LINKED;
OS_LOGD(TAG, "Successfully verified auth token");
s_wsClient = std::make_unique<GatewayClient>(authToken);
}
if (s_wsClient->loop()) {
return;
}
StartConnectingToLCG();
}