forked from VILLASframework/node
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvillas-relay.cpp
More file actions
535 lines (421 loc) · 11.5 KB
/
Copy pathvillas-relay.cpp
File metadata and controls
535 lines (421 loc) · 11.5 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
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
/** Simple WebSocket relay facilitating client-to-client connections.
*
* @author Steffen Vogel <post@steffenvogel.de>
* @copyright 2014-2022, Institute for Automation of Complex Power Systems, EONERC
* @license Apache 2.0
*********************************************************************************/
#include <iostream>
#include <map>
#include <queue>
#include <string>
#include <utility>
#include <cstring>
#include <jansson.h>
#include <unistd.h>
#include <villas/node/config.hpp>
#include <villas/compat.hpp>
#include <villas/node/memory.hpp>
#include <villas/tool.hpp>
#include <villas/log.hpp>
#include <villas/uuid.hpp>
#include <villas/web.hpp>
#include "villas-relay.hpp"
typedef char uuid_string_t[37];
using namespace villas;
using namespace villas::node;
namespace villas {
namespace node {
namespace tools {
RelaySession::RelaySession(Relay *r, Identifier sid) :
identifier(sid),
connects(0)
{
auto loggerName = fmt::format("relay:{}", sid);
logger = villas::logging.get(loggerName);
logger->info("Session created: {}", identifier);
sessions[sid] = this;
created = time(nullptr);
uuid::generateFromString(uuid, identifier, r->uuid);
}
RelaySession::~RelaySession()
{
logger->info("Session destroyed: {}", identifier);
sessions.erase(identifier);
}
RelaySession * RelaySession::get(Relay *r, lws *wsi)
{
char uri[64];
/* We use the URI to associate this connection to a session
* Example: ws://example.com/node_1
* Will select the session with the name 'node_1'
*/
/* Get path of incoming request */
lws_hdr_copy(wsi, uri, sizeof(uri), WSI_TOKEN_GET_URI);
if (strlen(uri) <= 1)
throw InvalidUrlException();
Identifier sid = uri + 1;
auto it = sessions.find(sid);
if (it == sessions.end()) {
auto *rs = new RelaySession(r, sid);
if (!rs)
throw MemoryAllocationError();
return rs;
}
else {
auto logger = logging.get("villas-relay");
logger->info("Found existing session: {}", sid);
return it->second;
}
}
json_t * RelaySession::toJson() const
{
json_t *json_connections = json_array();
for (auto it : connections) {
auto conn = it.second;
json_array_append(json_connections, conn->toJson());
}
uuid_string_t uuid_str;
uuid_unparse_lower(uuid, uuid_str);
return json_pack("{ s: s, s: s, s: o, s: I, s: i }",
"identifier", identifier.c_str(),
"uuid", uuid_str,
"connections", json_connections,
"created", created,
"connects", connects
);
}
std::map<std::string, RelaySession *> RelaySession::sessions;
RelayConnection::RelayConnection(Relay *r, lws *w, bool lo) :
wsi(w),
currentFrame(std::make_shared<Frame>()),
outgoingFrames(),
bytes_recv(0),
bytes_sent(0),
frames_recv(0),
frames_sent(0),
loopback(lo)
{
session = RelaySession::get(r, wsi);
session->connections[wsi] = this;
session->connects++;
lws_get_peer_addresses(wsi, lws_get_socket_fd(wsi), name, sizeof(name), ip, sizeof(ip));
created = time(nullptr);
session->logger->info("New connection established: {} ({})", name, ip);
}
RelayConnection::~RelayConnection()
{
session->logger->info("Connection closed: {} ({})", name, ip);
session->connections.erase(wsi);
if (session->connections.empty())
delete session;
}
json_t * RelayConnection::toJson() const
{
return json_pack("{ s: s, s: s, s: I, s: I, s: I, s: I, s: I }",
"name", name,
"ip", ip,
"created", created,
"bytes_recv", bytes_recv,
"bytes_sent", bytes_sent,
"frames_recv", frames_recv,
"frames_sent", frames_sent
);
}
void RelayConnection::write()
{
if (outgoingFrames.empty())
return;
auto fr = outgoingFrames.front();
int ret = lws_write(wsi, fr->data(), fr->size(), LWS_WRITE_BINARY);
if (ret < 0)
return;
bytes_sent += fr->size();
frames_sent++;
outgoingFrames.pop();
if (outgoingFrames.size() > 0)
lws_callback_on_writable(wsi);
}
void RelayConnection::read(void *in, size_t len)
{
currentFrame->insert(currentFrame->end(), (uint8_t *) in, (uint8_t *) in + len);
bytes_recv += len;
if (lws_is_final_fragment(wsi)) {
frames_recv++;
session->logger->debug("Received frame, relaying to {} connections", session->connections.size() - (loopback ? 0 : 1));
for (auto p : session->connections) {
auto c = p.second;
/* We skip the current connection in order
* to avoid receiving our own data */
if (loopback == false && c == this)
continue;
c->outgoingFrames.push(currentFrame);
lws_callback_on_writable(c->wsi);
}
currentFrame = std::make_shared<Frame>();
}
}
Relay::Relay(int argc, char *argv[]) :
Tool(argc, argv, "relay"),
stop(false),
context(nullptr),
vhost(nullptr),
loopback(false),
port(8088),
protocol("live")
{
int ret;
char hname[128];
ret = gethostname(hname, sizeof(hname));
if (ret)
throw SystemError("Failed to get hostname");
hostname = hname;
/* Default UUID is derived from hostname */
uuid::generateFromString(uuid, hname);
ret = memory::init(0);
if (ret)
throw RuntimeError("Failed to initialize memory");
/* Initialize logging */
lws_set_log_level(Web::lwsLogLevel(logging.getLevel()), Web::lwsLogger);
protocols = {
{
.name = "http",
.callback = lws_callback_http_dummy,
.per_session_data_size = 0,
.rx_buffer_size = 1024
},
{
.name = "http-api",
.callback = httpProtocolCallback,
.per_session_data_size = 0,
.rx_buffer_size = 1024
},
{
.name = "live",
.callback = protocolCallback,
.per_session_data_size = sizeof(RelayConnection),
.rx_buffer_size = 0
},
{ nullptr /* terminator */ }
};
}
int Relay::httpProtocolCallback(lws *wsi, enum lws_callback_reasons reason, void *user, void *in, size_t len)
{
int ret;
lws_context *ctx = lws_get_context(wsi);
void *user_ctx = lws_context_user(ctx);
Relay *r = reinterpret_cast<Relay *>(user_ctx);
switch (reason) {
case LWS_CALLBACK_HTTP: {
unsigned char buf[LWS_PRE + 2048], *start = &buf[LWS_PRE], *end = &buf[sizeof(buf) - LWS_PRE - 1], *p = start;
if (lws_add_http_common_headers(wsi, HTTP_STATUS_OK,
"application/json",
LWS_ILLEGAL_HTTP_CONTENT_LEN, /* no content len */
&p, end))
return 1;
if (lws_finalize_write_http_header(wsi, start, &p, end))
return 1;
/* Write the body separately */
lws_callback_on_writable(wsi);
return 0;
}
case LWS_CALLBACK_HTTP_WRITEABLE: {
size_t len;
std::vector<char> buf;
json_t *json_sessions, *json_body;
json_sessions = json_array();
for (auto it : RelaySession::sessions) {
auto &session = it.second;
json_array_append(json_sessions, session->toJson());
}
uuid_string_t uuid_str;
uuid_unparse(r->uuid, uuid_str);
json_body = json_pack("{ s: o, s: s, s: s, s: s, s: { s: b, s: i, s: s } }",
"sessions", json_sessions,
"version", PROJECT_VERSION_STR,
"hostname", r->hostname.c_str(),
"uuid", uuid_str,
"options",
"loopback", r->loopback,
"port", r->port,
"protocol", r->protocol.c_str()
);
if (!json_body)
return -1;
len = 1024;
do {
buf.resize(LWS_PRE + len);
len = json_dumpb(json_body, buf.data() + LWS_PRE, buf.size() - LWS_PRE, JSON_INDENT(4));
if (len == 0)
return -1;
} while (len > buf.size() - LWS_PRE);
ret = lws_write(wsi, (unsigned char *)(buf.data() + LWS_PRE), len, LWS_WRITE_HTTP_FINAL);
if (ret < 0)
return ret;
r->logger->info("Handled API request");
return -1;
}
default:
break;
}
return lws_callback_http_dummy(wsi, reason, user, in, len);
}
int Relay::protocolCallback(lws *wsi, enum lws_callback_reasons reason, void *user, void *in, size_t len)
{
lws_context *ctx = lws_get_context(wsi);
void *user_ctx = lws_context_user(ctx);
Relay *r = reinterpret_cast<Relay *>(user_ctx);
RelayConnection *c = reinterpret_cast<RelayConnection *>(user);
switch (reason) {
case LWS_CALLBACK_ESTABLISHED:
try {
new (c) RelayConnection(r, wsi, r->loopback);
}
catch (const InvalidUrlException &e) {
lws_close_reason(wsi, LWS_CLOSE_STATUS_PROTOCOL_ERR, (unsigned char *) "Invalid URL", strlen("Invalid URL"));
return -1;
}
break;
case LWS_CALLBACK_CLOSED:
c->~RelayConnection();
break;
case LWS_CALLBACK_SERVER_WRITEABLE:
c->write();
break;
case LWS_CALLBACK_RECEIVE:
c->read(in, len);
break;
default:
break;
}
return 0;
}
void Relay::usage()
{
std::cout << "Usage: villas-relay [OPTIONS]" << std::endl
<< " OPTIONS is one or more of the following options:" << std::endl
<< " -d LVL set debug level" << std::endl
<< " -p PORT the port number to listen on" << std::endl
<< " -P PROT the websocket protocol" << std::endl
<< " -l enable loopback of own data" << std::endl
<< " -u UUID unique instance id" << std::endl
<< " -V show version and exit" << std::endl
<< " -h show usage and exit" << std::endl << std::endl;
printCopyright();
}
void Relay::parse()
{
int ret;
char c, *endptr;
while ((c = getopt (argc, argv, "hVp:P:ld:u:")) != -1) {
switch (c) {
case 'd':
logging.setLevel(optarg);
lws_set_log_level(Web::lwsLogLevel(logging.getLevel()), Web::lwsLogger);
break;
case 'p':
port = strtoul(optarg, &endptr, 10);
goto check;
case 'P':
protocol = optarg;
break;
case 'l':
loopback = true;
break;
case 'u':
ret = uuid_parse(optarg, uuid);
if (ret) {
logger->error("Failed to parse UUID: {}", optarg);
exit(EXIT_FAILURE);
}
break;
case 'V':
printVersion();
exit(EXIT_SUCCESS);
case 'h':
case '?':
usage();
exit(c == '?' ? EXIT_FAILURE : EXIT_SUCCESS);
}
continue;
check:
if (optarg == endptr) {
logger->error("Failed to parse parse option argument '-{} {}'", c, optarg);
exit(EXIT_FAILURE);
}
}
if (argc - optind < 0) {
usage();
exit(EXIT_FAILURE);
}
}
int Relay::main() {
/* Start server */
lws_context_creation_info ctx_info = { 0 };
protocols[2].name = protocol.c_str();
ctx_info.options = LWS_SERVER_OPTION_EXPLICIT_VHOSTS | LWS_SERVER_OPTION_DO_SSL_GLOBAL_INIT;
ctx_info.gid = -1;
ctx_info.uid = -1;
ctx_info.protocols = protocols.data();
#ifndef LWS_WITHOUT_EXTENSIONS
ctx_info.extensions = extensions.data();
#endif
ctx_info.port = port;
ctx_info.mounts = &mount;
ctx_info.user = (void *) this;
auto lwsLogger = logging.get("lws");
context = lws_create_context(&ctx_info);
if (context == nullptr) {
lwsLogger->error("Failed to initialize server context");
exit(EXIT_FAILURE);
}
vhost = lws_create_vhost(context, &ctx_info);
if (vhost == nullptr) {
lwsLogger->error("Failed to initialize virtual host");
exit(EXIT_FAILURE);
}
while (!stop)
lws_service(context, 100);
return 0;
}
const std::vector<lws_extension> Relay::extensions = {
#ifdef LWS_DEFLATE_FOUND
{
"permessage-deflate",
lws_extension_callback_pm_deflate,
"permessage-deflate"
},
{
"deflate-frame",
lws_extension_callback_pm_deflate,
"deflate_frame"
},
#endif /* LWS_DEFLATE_FOUND */
{ nullptr /* terminator */ }
};
const lws_http_mount Relay::mount = {
.mount_next = nullptr, /* linked-list "next" */
.mountpoint = "/api/v1", /* mountpoint URL */
.origin = nullptr, /* protocol */
.def = nullptr,
.protocol = "http-api",
.cgienv = nullptr,
.extra_mimetypes = nullptr,
.interpret = nullptr,
.cgi_timeout = 0,
.cache_max_age = 0,
.auth_mask = 0,
.cache_reusable = 0,
.cache_revalidate = 0,
.cache_intermediaries = 0,
.origin_protocol = LWSMPRO_CALLBACK, /* dynamic */
.mountpoint_len = 7, /* char count */
.basic_auth_login_file = nullptr,
};
} /* namespace tools */
} /* namespace node */
} /* namespace villas */
int main(int argc, char *argv[])
{
villas::node::tools::Relay t(argc, argv);
return t.run();
}