forked from n7tae/mrefd
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathm17protocol.cpp
530 lines (476 loc) · 14.6 KB
/
m17protocol.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
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
//
// Created by Jean-Luc Deltombe (LX3JL) on 01/11/2015.
// Copyright © 2015 Jean-Luc Deltombe (LX3JL). All rights reserved.
// Copyright © 2020 Thomas A. Early, N7TAE
//
// ----------------------------------------------------------------------------
// This file is part of mrefd.
//
// mrefd is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// mrefd is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Foobar. If not, see <http://www.gnu.org/licenses/>.
// ----------------------------------------------------------------------------
#include <string.h>
#include "main.h"
#include "m17peer.h"
#include "m17client.h"
#include "m17protocol.h"
#include "reflector.h"
#include "gatekeeper.h"
////////////////////////////////////////////////////////////////////////////////////////
// operation
bool CM17Protocol::Initialize(int ptype, const uint16_t port, const bool has_ipv4, const bool has_ipv6)
{
// base class
if (! CProtocol::Initialize(ptype, port, has_ipv4, has_ipv6))
return false;
// update time
m_LastKeepaliveTime.Now();
m_LastPeersLinkTime.Now();
// done
return true;
}
////////////////////////////////////////////////////////////////////////////////////////
// task
void CM17Protocol::Task(void)
{
uint8_t buf[UDP_BUFFER_LENMAX];
CIp ip;
CCallsign cs;
char mod;
std::unique_ptr<CPacket> pack;
// any incoming packet ?
#ifdef LISTEN_IPV6
#ifdef LISTEN_IPV4
auto len = ReceiveDS(buf, ip, 20);
#else
auto len = Receive6(buf, ip, 20);
#endif
#else
auto len = Receive4(buf, ip, 20);
#endif
//if (len > 0) std::cout << "Received " << len << " bytes from " << ip << std::endl;
switch (len) {
case sizeof(AM17Frame):
if ( IsValidPacket(buf, pack) )
{
if (pack->GetDestCallsign().HasSameCallsign(g_Reflector.GetCallsign()))
{ // only if the packet has the destination set properly!
OnFirstPacketIn(pack, ip); // might open a new stream, if it's the first packet
if (pack) // the packet might have been erased
{ // if it needed to open a new stream, but couldn't
OnPacketIn(pack, ip);
}
}
else
{
CCallsign dest(buf+6);
std::cout << "Packet with wrong destination:" << dest.GetCS() << std::endl;
}
}
break;
case 11:
if ( IsValidConnect(buf, cs, &mod) )
{
std::cout << "Connect packet for module " << mod << " from " << cs << " at " << ip << std::endl;
// callsign authorized?
if ( g_GateKeeper.MayLink(cs, ip, PROTOCOL_M17) )
{
// valid module ?
if ( g_Reflector.IsValidModule(mod) )
{
// is this an ack for a link request?
CPeerCallsignList *list = g_GateKeeper.GetPeerList();
CCallsignListItem *item = list->FindListItem(cs);
if ( item != nullptr && cs.GetModule() == item->GetModules()[1] && mod == item->GetModules()[0] )
{
std::cout << "ACK packet for module " << mod << " from " << cs << " at " << ip << std::endl;
// already connected ?
CPeers *peers = g_Reflector.GetPeers();
if ( nullptr == peers->FindPeer(cs, ip, PROTOCOL_M17) )
{
// create the new peer
// this also create one client per module
// append the peer to reflector peer list
// this also add all new clients to reflector client list
peers->AddPeer(std::make_shared<CM17Peer>(cs, ip, std::string(1, mod).c_str()));
}
g_Reflector.ReleasePeers();
}
else // this is a link request, but from who?
{
// is this a request from another M17 reflector?
if (0 == cs.GetCS(4).compare("M17-")) {
// Yes, then it needs a special acknowledgement
std::cout << "Link request from peer " << cs << "@" << ip << " to module " << mod << std::endl;
char modules[3] = { 0 };
modules[0] = mod;
modules[1] = cs.GetModule();
EncodeConnectPacket(buf, modules);
Send(buf, 11, ip);
} else {
// acknowledge a normal request from a repeater/hot-spot/mvoice
EncodeConnectAckPacket(buf);
Send(buf, 4, ip);
}
// create the client and append
g_Reflector.GetClients()->AddClient(std::make_shared<CM17Client>(cs, ip, mod));
g_Reflector.ReleaseClients();
}
g_GateKeeper.ReleasePeerList();
}
else
{
std::cout << "Node " << cs << " connect attempt on non-existing module '" << mod << "'" << std::endl;
// deny the request
EncodeConnectNackPacket(buf);
Send(buf, 4, ip);
}
}
else
{
// deny the request
EncodeConnectNackPacket(buf);
Send(buf, 4, ip);
}
}
break;
case 10:
if ( IsValidKeepAlive(buf, cs) )
{
// find all clients with that callsign & ip and keep them alive
CClients *clients = g_Reflector.GetClients();
auto it = clients->begin();
std::shared_ptr<CClient>client = nullptr;
while (nullptr != (client = clients->FindNextClient(cs, ip, PROTOCOL_M17, it)))
{
client->Alive();
}
g_Reflector.ReleaseClients();
}
else if ( IsValidDisconnect(buf, cs) )
{
std::cout << "Disconnect packet from " << cs << " at " << ip << std::endl;
// find client & remove it
CClients *clients = g_Reflector.GetClients();
std::shared_ptr<CClient>client = clients->FindClient(ip, PROTOCOL_M17);
if ( client != nullptr )
{
// ack disconnect packet
EncodeDisconnectedPacket(buf);
Send(buf, 4, ip);
// and remove it
clients->RemoveClient(client);
}
g_Reflector.ReleaseClients();
}
break;
default:
break;
}
// handle end of streaming timeout
CheckStreamsTimeout();
// handle queue from reflector
HandleQueue();
// keep alive
if ( m_LastKeepaliveTime.DurationSinceNow() > M17_KEEPALIVE_PERIOD )
{
// handle keep alives
HandleKeepalives();
// update time
m_LastKeepaliveTime.Now();
}
// peer connections
if ( m_LastPeersLinkTime.DurationSinceNow() > M17_RECONNECT_PERIOD )
{
// handle remote peers connections
HandlePeerLinks();
// update time
m_LastPeersLinkTime.Now();
}
}
////////////////////////////////////////////////////////////////////////////////////////
// queue helper
void CM17Protocol::HandleQueue(void)
{
m_Queue.Lock();
while ( !m_Queue.empty() )
{
// get the packet
auto packet = m_Queue.front();
m_Queue.pop();
// push it to all our clients linked to the module and who is not streaming in
CClients *clients = g_Reflector.GetClients();
auto it = clients->begin();
std::shared_ptr<CClient>client = nullptr;
while (nullptr != (client = clients->FindNextClient(PROTOCOL_M17, it)))
{
// is this client busy ?
if ( !client->IsAMaster() && (client->GetReflectorModule() == packet->GetDestModule()) )
{
// packet->GetFrame().lich.addr_dst won't be correct after this.
client->GetCallsign().CodeOut(packet->GetFrame().lich.addr_dst); // set the destination
packet->SetCRC(crc.CalcCRC(packet->GetFrame().magic, sizeof(AM17Frame) - 2)); // recalculate the crc
Send(packet->GetFrame().magic, sizeof(AM17Frame), client->GetIp());
}
}
g_Reflector.ReleaseClients();
}
m_Queue.Unlock();
}
////////////////////////////////////////////////////////////////////////////////////////
// keepalive helpers
void CM17Protocol::HandleKeepalives(void)
{
uint8_t keepalive[10];
EncodeKeepAlivePacket(keepalive);
// iterate on clients
CClients *clients = g_Reflector.GetClients();
auto it = clients->begin();
std::shared_ptr<CClient>client = nullptr;
while ( (client = clients->FindNextClient(PROTOCOL_M17, it)) != nullptr )
{
// send keepalive
Send(keepalive, 10, client->GetIp());
// client busy ?
if ( client->IsAMaster() )
{
// yes, just tickle it
client->Alive();
}
// otherwise check if still with us
else if ( !client->IsAlive() )
{
CPeers *peers = g_Reflector.GetPeers();
std::shared_ptr<CPeer>peer = peers->FindPeer(client->GetCallsign(), client->GetIp(), PROTOCOL_M17);
if ( (peer != nullptr) && (peer->GetReflectorModules()[0] == client->GetReflectorModule()) )
{
// no, but this is a peer client, so it will be handled below
}
else
{
// no, disconnect
uint8_t disconnect[10];
EncodeDisconnectPacket(disconnect, client->GetReflectorModule());
Send(disconnect, 10, client->GetIp());
// remove it
std::cout << "M17 client " << client->GetCallsign() << " keepalive timeout" << std::endl;
clients->RemoveClient(client);
}
g_Reflector.ReleasePeers();
}
}
g_Reflector.ReleaseClients();
// iterate on peers
CPeers *peers = g_Reflector.GetPeers();
auto pit = peers->begin();
std::shared_ptr<CPeer>peer = nullptr;
while ( (peer = peers->FindNextPeer(PROTOCOL_M17, pit)) != nullptr )
{
// keepalives are sent between clients
// some client busy or still with us ?
if ( !peer->IsAMaster() && !peer->IsAlive() )
{
// no, disconnect all clients
uint8_t disconnect[10];
EncodeDisconnectPacket(disconnect, peer->GetReflectorModules()[0]);
CClients *clients = g_Reflector.GetClients();
for ( auto cit=peer->cbegin(); cit!=peer->cend(); cit++ )
{
Send(disconnect, 10, (*cit)->GetIp());
}
g_Reflector.ReleaseClients();
// remove it
std::cout << "Peer " << peer->GetCallsign() << " keepalive timeout" << std::endl;
peers->RemovePeer(peer);
}
}
g_Reflector.ReleasePeers();
}
////////////////////////////////////////////////////////////////////////////////////////
// Peers helpers
void CM17Protocol::HandlePeerLinks(void)
{
uint8_t buf[10];
// get the list of peers
CPeerCallsignList *list = g_GateKeeper.GetPeerList();
CPeers *peers = g_Reflector.GetPeers();
// check if all our connected peers are still listed by gatekeeper
// if not, disconnect
auto pit = peers->begin();
std::shared_ptr<CPeer>peer = nullptr;
while ( (peer = peers->FindNextPeer(PROTOCOL_M17, pit)) != nullptr )
{
if ( list->FindListItem(peer->GetCallsign()) == nullptr )
{
// send disconnect packet
EncodeDisconnectPacket(buf, peer->GetReflectorModules()[0]);
Send(buf, 10, peer->GetIp());
std::cout << "Sending disconnect packet to M17 peer " << peer->GetCallsign() << " at " << peer->GetIp() << std::endl;
// remove client
peers->RemovePeer(peer);
}
}
// check if all ours peers listed by gatekeeper are connected
// if not, connect or reconnect
uint8_t connect[11];
for ( auto it=list->begin(); it!=list->end(); it++ )
{
if ( !(*it).GetCallsign().HasSameCallsignWithWildcard(CCallsign("M17*")) )
continue;
if ( strlen((*it).GetModules()) != 2 )
continue;
if ( nullptr == peers->FindPeer((*it).GetCallsign(), PROTOCOL_M17) )
{
// resolve again peer's IP in case it's a dynamic IP
(*it).ResolveIp();
// send connect packet to re-initiate peer link
EncodeConnectPacket(connect, (*it).GetModules());
Send(connect, 11, (*it).GetIp(), M17_PORT);
std::cout << "Sent connect packet to M17 peer " << (*it).GetCallsign() << " @ " << (*it).GetIp() << " for module " << (*it).GetModules()[1] << " (module " << (*it).GetModules()[0] << ")" << std::endl;
}
}
// done
g_Reflector.ReleasePeers();
g_GateKeeper.ReleasePeerList();
}
////////////////////////////////////////////////////////////////////////////////////////
// streams helpers
void CM17Protocol::OnFirstPacketIn(std::unique_ptr<CPacket> &packet, const CIp &ip)
{
// find the stream
CPacketStream *stream = GetStream(packet->GetStreamId(), ip);
if ( stream )
{
// stream already open
// skip packet, but tickle the stream
stream->Tickle();
}
else
{
// find this client
std::shared_ptr<CClient>client = g_Reflector.GetClients()->FindClient(ip, PROTOCOL_M17);
if ( client )
{
// save the source and destination for Hearing().
// We're going to lose packet on OpenStream();
auto s = packet->GetSourceCallsign();
auto d = packet->GetDestCallsign();
// try to open the stream
stream = g_Reflector.OpenStream(packet, client);
if ( nullptr == stream )
{
std::cerr << "Cant open the stream for " << client->GetCallsign() << std::endl;
packet.release(); // couldn't open the stream, so destroy the packet
}
else
{
// keep the handle
m_Streams.push_back(stream);
// update last heard
g_Reflector.GetUsers()->Hearing(s, d);
g_Reflector.ReleaseUsers();
}
}
// release
g_Reflector.ReleaseClients();
}
}
////////////////////////////////////////////////////////////////////////////////////////
// packet decoding helpers
bool CM17Protocol::IsValidConnect(const uint8_t *buf, CCallsign &cs, char *mod)
{
if (0 == memcmp(buf, "CONN", 4))
{
cs.CodeIn(buf + 4);
if (cs.IsValid())
{
*mod = buf[10];
if (IsLetter(*mod))
return true;
}
}
return false;
}
bool CM17Protocol::IsValidDisconnect(const uint8_t *buf, CCallsign &cs)
{
if (0 == memcmp(buf, "DISC", 4))
{
cs.CodeIn(buf + 4);
if (cs.IsValid())
{
return true;
}
}
return false;
}
bool CM17Protocol::IsValidKeepAlive(const uint8_t *buf, CCallsign &cs)
{
if ('P' == buf[0] && ('I' == buf[1] || 'O' == buf[1]) && 'N' == buf[2] && 'G' == buf[3])
{
cs.CodeIn(buf + 4);
if (cs.IsValid())
{
return true;
}
}
return false;
}
bool CM17Protocol::IsValidPacket(const uint8_t *buf, std::unique_ptr<CPacket> &packet)
{
if (0 == memcmp(buf, "M17 ", 4)) // we tested the size before we got here
{
// create packet
packet = std::unique_ptr<CPacket>(new CPacket(buf));
// check validity of packet
if ( packet->GetSourceCallsign().IsValid() )
{ // looks like a valid source
return true;
}
}
return false;
}
////////////////////////////////////////////////////////////////////////////////////////
// packet encoding helpers
void CM17Protocol::EncodeKeepAlivePacket(uint8_t *buf)
{
memcpy(buf, "PING", 4);
CCallsign cs(GetReflectorCallsign());
cs.CodeOut(buf + 4);
}
void CM17Protocol::EncodeConnectPacket(uint8_t *buf, const char *Modules)
{
memcpy(buf, "CONN", 4);
CCallsign cs(GetReflectorCallsign());
cs.SetModule(Modules[0]);
cs.CodeOut(buf + 4);
buf[10] = Modules[1];
}
void CM17Protocol::EncodeConnectAckPacket(uint8_t *buf)
{
memcpy(buf, "ACKN", 4);
}
void CM17Protocol::EncodeConnectNackPacket(uint8_t *buf)
{
memcpy(buf, "NACK", 4);
}
void CM17Protocol::EncodeDisconnectPacket(uint8_t *buf, char mod)
{
memcpy(buf, "DISC", 4);
CCallsign cs(GetReflectorCallsign());
cs.SetModule(mod);
cs.CodeOut(buf + 4);
}
void CM17Protocol::EncodeDisconnectedPacket(uint8_t *buf)
{
memcpy(buf, "DISC", 4);
}