-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFnePeer.cs
More file actions
1224 lines (1048 loc) · 60.9 KB
/
Copy pathFnePeer.cs
File metadata and controls
1224 lines (1048 loc) · 60.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
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
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// SPDX-License-Identifier: AGPL-3.0-only
/**
* Digital Voice Modem - Fixed Network Equipment Core Library
* AGPLv3 Open Source. Use is subject to license terms.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* @package DVM / Fixed Network Equipment Core Library
* @license AGPLv3 License (https://opensource.org/licenses/AGPL-3.0)
*
* Copyright (C) 2022-2025 Bryan Biedenkapp, N2PLL
* Copyright (C) 2024 Caleb, KO4UYJ
*
*/
using System;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Threading.Tasks;
using System.Text;
using System.Text.Json;
using System.Linq;
using System.Collections.Generic;
using fnecore.DMR;
using fnecore.P25;
using fnecore.NXDN;
using fnecore.Analog;
using fnecore.P25.KMM;
namespace fnecore
{
/// <summary>
/// Callback used to process a raw network frame.
/// </summary>
/// <param name="frame"><see cref="UdpFrame"/></param>
/// <param name="peerId">Peer ID</param>
/// <param name="streamId">Stream ID</param>
/// <returns>True, if the frame was handled, otherwise false.</returns>
public delegate bool RawNetworkFrame(UdpFrame frame, uint peerId, uint streamId);
/// <summary>
/// Callback used to process a raw network frame.
/// </summary>
/// <param name="frame"><see cref="UdpFrame"/></param>
/// <param name="peerId">Peer ID</param>
/// <param name="streamId">Stream ID</param>
/// <param name="rtpHeader">RTP Header</param>
/// <param name="fneHeader">RTP FNE Header</param>
/// <param name="message">Raw packet message</param>
/// <returns>True, if the frame was handled, otherwise false.</returns>
public delegate bool UserPacketHandler(UdpFrame frame, uint peerId, uint streamId,
RtpHeader rtpHeader, RtpFNEHeader fneHeader, byte[] message);
/// <summary>
/// Implements an FNE "peer".
/// </summary>
public class FnePeer : FneBase
{
private const int MAX_MISSED_PEER_PINGS = 5;
private UdpReceiver client = null;
private bool abortListening = false;
private CancellationTokenSource listenCancelToken = new CancellationTokenSource();
private Task listenTask = null;
private CancellationTokenSource maintainenceCancelToken = new CancellationTokenSource();
private Task maintainenceTask = null;
private PeerInformation info;
private IPEndPoint masterEndpoint = null;
private ushort currPktSeq = 0;
private uint streamId = 0;
private List<TalkgroupEntry> announcedTGs = new List<TalkgroupEntry>();
private List<PeerHAIPEntry> haIPs = new List<PeerHAIPEntry>();
private int currentHAIP;
private int retryCount;
private int maxRetryCount = Constants.MAX_RETRY_BEFORE_RECONNECT;
private bool trafficLogging;
/*
** Properties
*/
/// <summary>
/// Gets/sets the peer information.
/// </summary>
public PeerInformation Information
{
get { return info; }
set { info = value; }
}
/// <summary>
/// Gets/sets the password used for connecting to a master.
/// </summary>
public string Passphrase
{
get;
set;
}
/// <summary>
/// Gets the list of talkgroups announced from the master FNE.
/// </summary>
public List<TalkgroupEntry> AnnouncedTGs => announcedTGs;
/// <summary>
/// Gets the number of pings sent.
/// </summary>
public int PingsSent
{
get;
private set;
}
/// <summary>
/// Gets the number of pings acked.
/// </summary>
public int PingsAcked
{
get;
private set;
}
/// <summary>
/// Gets/sets flag indicating whether or not the user packet handler is also handling
/// protocol packets.
/// </summary>
public bool UserProtocolHandler
{
get;
set;
}
/*
** Events/Callbacks
*/
/// <summary>
/// Event action that handles a raw network frame directly.
/// </summary>
public RawNetworkFrame NetworkFrameHandler = null;
/// <summary>
/// Event action that handles a RTP network packet.
/// </summary>
public UserPacketHandler UserPacketHandler = null;
/*
** Methods
*/
/// <summary>
/// Initializes a new instance of the <see cref="FnePeer"/> class.
/// </summary>
/// <param name="systemName"></param>
/// <param name="peerId"></param>
/// <param name="address"></param>
/// <param name="port"></param>
public FnePeer(string systemName, uint peerId, string address, int port, string PresharedKey = null, bool trafficLogging = false) : this(systemName, peerId, new IPEndPoint(IPAddress.Parse(address), port), PresharedKey)
{
this.trafficLogging = trafficLogging;
/* stub */
}
/// <summary>
/// Initializes a new instance of the <see cref="FnePeer"/> class.
/// </summary>
/// <param name="systemName"></param>
/// <param name="peerId"></param>
/// <param name="endpoint"></param>
public FnePeer(string systemName, uint peerId, IPEndPoint endpoint, string PresharedKey = null, bool trafficLogging = false) : base(systemName, peerId)
{
masterEndpoint = endpoint;
client = new UdpReceiver();
if (PresharedKey != null)
client.SetPresharedKey(FneUtils.ConvertHexStringToPresharedKey(PresharedKey));
info = new PeerInformation();
info.PeerID = peerId;
info.State = ConnectionState.WAITING_LOGIN;
UserProtocolHandler = false;
PingsAcked = 0;
this.trafficLogging = trafficLogging;
}
/// <summary>
/// Starts the main execution loop for this <see cref="FnePeer"/>.
/// </summary>
public override void Start()
{
if (isStarted)
throw new InvalidOperationException("Cannot start listening when already started.");
Logger(LogLevel.INFO, $"({systemName}) starting network services, {masterEndpoint}");
// attempt initial connection
try
{
client.Connect(masterEndpoint);
}
catch (SocketException se)
{
Log(LogLevel.FATAL, $"({systemName}) SOCKET ERROR: {se.SocketErrorCode}; {se.Message}");
}
abortListening = false;
listenTask = Task.Factory.StartNew(Listen, listenCancelToken.Token);
maintainenceTask = Task.Factory.StartNew(Maintainence, maintainenceCancelToken.Token);
isStarted = true;
}
/// <summary>
/// Stops the main execution loop for this <see cref="FnePeer"/>.
/// </summary>
public override void Stop()
{
if (!isStarted)
throw new InvalidOperationException("Cannot stop listening when not started.");
Logger(LogLevel.INFO, $"({systemName}) stopping network services, {masterEndpoint}");
// send shutdown opcode to server
SendMaster(CreateOpcode(Constants.NET_FUNC_RPT_CLOSING, Constants.NET_SUBFUNC_NOP), new byte[1], 1, CreateStreamID(), true);
// stop UDP listen task
if (listenTask != null)
{
abortListening = true;
listenCancelToken.Cancel();
try
{
listenTask.GetAwaiter().GetResult();
}
catch (OperationCanceledException) { /* stub */ }
finally
{
listenCancelToken.Dispose();
}
}
// stop maintainence task
if (maintainenceTask != null)
{
maintainenceCancelToken.Cancel();
try
{
maintainenceTask.GetAwaiter().GetResult();
}
catch (OperationCanceledException) { /* stub */ }
finally
{
maintainenceCancelToken.Dispose();
}
}
isStarted = false;
}
/// <summary>
/// Helper to send a raw UDP frame.
/// </summary>
/// <param name="frame">UDP frame to send</param>
public void Send(UdpFrame frame)
{
if (RawPacketTrace)
Log(LogLevel.DEBUG, $"({systemName}) Network Sent (to {frame.Endpoint}) -- {FneUtils.HexDump(frame.Message, 0)}");
client.Send(frame);
}
/// <summary>
/// Helper to send a data message to the master.
/// </summary>
/// <param name="opcode">Opcode</param>
/// <param name="message">Byte array containing message to send</param>
/// <param name="pktSeq">RTP Packet Sequence</param>
/// <param name="streamId"></param>
/// <param name="forceZeroStream"></param>
public void SendMaster(Tuple<byte, byte> opcode, byte[] message, ushort pktSeq, uint streamId = 0, bool forceZeroStream = false)
{
if (streamId == 0 && !forceZeroStream)
streamId = this.streamId;
Send(new UdpFrame()
{
Endpoint = masterEndpoint,
Message = WriteFrame(message, peerId, this.peerId, opcode, pktSeq, streamId)
});
}
/// <summary>
/// Helper to send a data message to the master.
/// </summary>
/// <param name="opcode">Opcode</param>
/// <param name="message">Byte array containing message to send</param>
public void SendMaster(Tuple<byte, byte> opcode, byte[] message)
{
SendMaster(opcode, message, pktSeq());
}
/// <summary>
/// Helper to send group affiliation announcements to the master.
/// </summary>
/// <param name="srcId"></param>
/// <param name="dstId"></param>
public void SendMasterGroupAffiliation(uint srcId, uint dstId)
{
// send message to master
byte[] res = new byte[6];
FneUtils.Write3Bytes(srcId, ref res, 0);
FneUtils.Write3Bytes(dstId, ref res, 3);
SendMaster(CreateOpcode(Constants.NET_FUNC_ANNOUNCE, Constants.NET_ANNC_SUBFUNC_GRP_AFFIL), res, 0, 0, true);
}
/// <summary>
/// Helper to send group affiliation dictionary to the master
/// </summary>
/// <param name="affs"></param>
public void SendMasterAffiliationUpdate(List<Tuple<uint, uint>> affs)
{
int bufferSize = 4 + (affs.Count * 8);
byte[] buffer = new byte[bufferSize];
FneUtils.WriteBytes((uint)affs.Count, ref buffer, 0);
int offset = 4;
foreach (var entry in affs)
{
FneUtils.Write3Bytes(entry.Item1, ref buffer, offset);
FneUtils.Write3Bytes(entry.Item2, ref buffer, offset + 4);
offset += 8;
}
SendMaster(CreateOpcode(Constants.NET_FUNC_ANNOUNCE, Constants.NET_ANNC_SUBFUNC_AFFILS), buffer, 0, 0, true);
}
/// <summary>
/// Helper to send group affiliation removal announcement to the master.
/// </summary>
/// <param name="srcId"></param>
public void SendMasterGroupAffiliationRemoval(uint srcId)
{
// send message to master
byte[] res = new byte[3];
FneUtils.Write3Bytes(srcId, ref res, 0);
SendMaster(CreateOpcode(Constants.NET_FUNC_ANNOUNCE, Constants.NET_ANNC_SUBFUNC_GRP_UNAFFIL), res, 0, 0, true);
}
/// <summary>
/// Helper to send unit registration announcements to the master.
/// </summary>
/// <param name="srcId"></param>
public void SendMasterUnitRegistration(uint srcId)
{
// send message to master
byte[] res = new byte[3];
FneUtils.Write3Bytes(srcId, ref res, 0);
SendMaster(CreateOpcode(Constants.NET_FUNC_ANNOUNCE, Constants.NET_ANNC_SUBFUNC_UNIT_REG), res, 0, 0, true);
}
/// <summary>
/// Helper to send unit deregistration announcements to the master.
/// </summary>
/// <param name="srcId"></param>
public void SendMasterUnitDeRegistration(uint srcId)
{
// send message to master
byte[] res = new byte[3];
FneUtils.Write3Bytes(srcId, ref res, 0);
SendMaster(CreateOpcode(Constants.NET_FUNC_ANNOUNCE, Constants.NET_ANNC_SUBFUNC_UNIT_DEREG), res, 0, 0, true);
}
/// <summary>
/// Helper to send a key request to the master
/// </summary>
/// <param name="algId"></param>
/// <param name="kId"></param>
public void SendMasterKeyRequest(byte algId, ushort kId)
{
byte[] res = new byte[32];
KmmModifyKey modifyKey = new KmmModifyKey
{
AlgId = algId,
KeyId = kId
};
KeysetItem ks = new KeysetItem
{
KeysetId = 0,
AlgId = algId,
KeyLength = 32
};
modifyKey.KeysetItem = ks;
modifyKey.MessageLength = 21;
byte[] payload = new byte[modifyKey.MessageLength];
modifyKey.Encode(payload);
Array.Copy(payload, 0, res, 11, payload.Length);
SendMaster(CreateOpcode(Constants.NET_FUNC_KEY_REQ, Constants.NET_SUBFUNC_NOP), res, Constants.RtpCallEndSeq, 0, true);
}
/// <summary>
/// Helper to update the RTP packet sequence.
/// </summary>
/// <param name="reset"></param>
/// <returns>RTP packet sequence.</returns>
public ushort pktSeq(bool reset = false)
{
if (reset)
{
currPktSeq = 0;
return currPktSeq;
}
ushort curr = currPktSeq;
++currPktSeq;
if (currPktSeq > (Constants.RtpCallEndSeq - 1))
currPktSeq = 0;
return curr;
}
/// <summary>
/// Helper to rotate the master endpoint to the next HA endpoint.
/// </summary>
private void RotateMasterEndpont()
{
// are we rotating IPs for HA reconnect?
if (haIPs.Count() > 0 && retryCount > 0U && maxRetryCount == Constants.MAX_RETRY_HA_RECONNECT)
{
PeerHAIPEntry entry = haIPs[currentHAIP];
currentHAIP++;
if (currentHAIP > haIPs.Count)
{
currentHAIP = 0;
}
Log(LogLevel.ERROR, $"({systemName}) Not connected or lost connection to {masterEndpoint}; trying next HA {entry.EndPoint}...");
masterEndpoint = entry.EndPoint;
}
++retryCount;
}
/// <summary>
/// Internal UDP listen routine.
/// </summary>
private async void Listen()
{
CancellationToken ct = listenCancelToken.Token;
ct.ThrowIfCancellationRequested();
while (!abortListening)
{
try
{
UdpFrame frame = await client.Receive();
if (RawPacketTrace)
Log(LogLevel.DEBUG, $"Network Received (from {frame.Endpoint}) -- {FneUtils.HexDump(frame.Message, 0)}");
// decode RTP frame
if (frame.Message.Length <= 0)
continue;
RtpHeader rtpHeader;
RtpFNEHeader fneHeader;
int messageLength = 0;
byte[] message = ReadFrame(frame, out messageLength, out rtpHeader, out fneHeader);
if (message == null)
{
Log(LogLevel.ERROR, $"({systemName}) Malformed packet (from {frame.Endpoint}); failed to decode RTP frame");
continue;
}
if (message.Length < 1)
{
Log(LogLevel.WARNING, $"({systemName}) Malformed packet (from {frame.Endpoint}) -- {FneUtils.HexDump(message, 0)}");
continue;
}
// validate frame endpoint
if (frame.Endpoint.ToString() == masterEndpoint.ToString())
{
uint peerId = fneHeader.PeerID;
if (streamId != fneHeader.StreamID)
pktSeq(true);
// update current peer stream ID
streamId = fneHeader.StreamID;
// see if the peer is defining its own frame handler, if it is try to handle the frame there
if (NetworkFrameHandler != null)
{
if (NetworkFrameHandler(frame, peerId, streamId))
continue;
}
// process incoming message frame opcodes
switch (fneHeader.Function)
{
case Constants.NET_FUNC_PROTOCOL:
{
// are we handling protocol packets with the user packet handler?
if (UserPacketHandler != null && UserProtocolHandler)
{
UserPacketHandler(frame, peerId, streamId, rtpHeader, fneHeader, message);
break;
}
if (fneHeader.SubFunction == Constants.NET_PROTOCOL_SUBFUNC_DMR) // Encapsulated DMR data frame
{
if (peerId != this.peerId)
{
//Log(LogLevel.WARNING, $"({systemName}) PEER {peerId}; routed traffic, rewriting PEER {this.peerId}");
peerId = this.peerId;
}
// is this for our peer?
if (peerId == this.peerId)
{
// TODO: port the mux validation logic from dvmhost:src/common/network/Network.cpp
byte seqNo = message[4];
uint srcId = FneUtils.Bytes3ToUInt32(message, 5);
uint dstId = FneUtils.Bytes3ToUInt32(message, 8);
byte bits = message[15];
byte slot = (byte)(((bits & 0x80) == 0x80) ? 1 : 0);
CallType callType = ((bits & 0x40) == 0x40) ? CallType.PRIVATE : CallType.GROUP;
FrameType frameType = (FrameType)((bits & 0x30) >> 4);
DMRDataType dataType = DMRDataType.IDLE;
if ((bits & 0x20) == 0x20)
dataType = (DMRDataType)(bits & ~(0x20));
byte n = (byte)(bits & 0xF);
#if DEBUG
if (trafficLogging)
Log(LogLevel.DEBUG, $"{systemName} DMRD: SRC_PEER {peerId} SRC_ID {srcId} DST_ID {dstId} TS {slot} [STREAM ID {streamId}]");
#endif
// perform any userland actions with the data
FireDMRDataReceived(new DMRDataReceivedEvent(peerId, srcId, dstId, slot, callType, frameType, dataType, n, rtpHeader.Sequence, streamId, message));
}
}
else if (fneHeader.SubFunction == Constants.NET_PROTOCOL_SUBFUNC_P25) // Encapsulated P25 data frame
{
if (peerId != this.peerId)
{
//Log(LogLevel.WARNING, $"({systemName}) PEER {peerId}; routed traffic, rewriting PEER {this.peerId}");
peerId = this.peerId;
}
// is this for our peer?
if (peerId == this.peerId)
{
// TODO: port the mux validation logic from dvmhost:src/common/network/Network.cpp
uint srcId = FneUtils.Bytes3ToUInt32(message, 5);
uint dstId = FneUtils.Bytes3ToUInt32(message, 8);
CallType callType = (message[4] == P25Defines.LC_PRIVATE) ? CallType.PRIVATE : CallType.GROUP;
P25DUID duid = (P25DUID)message[22];
FrameType frameType = ((duid != P25DUID.TDU) && (duid != P25DUID.TDULC)) ? FrameType.VOICE : FrameType.TERMINATOR;
#if DEBUG
if (trafficLogging)
Log(LogLevel.DEBUG, $"{systemName} P25D: SRC_PEER {peerId} SRC_ID {srcId} DST_ID {dstId} [STREAM ID {streamId}]");
#endif
// perform any userland actions with the data
FireP25DataReceived(new P25DataReceivedEvent(peerId, srcId, dstId, callType, duid, frameType, rtpHeader.Sequence, streamId, message));
}
}
else if (fneHeader.SubFunction == Constants.NET_PROTOCOL_SUBFUNC_NXDN) // Encapsulated NXDN data frame
{
if (peerId != this.peerId)
{
//Log(LogLevel.WARNING, $"({systemName}) PEER {peerId}; routed traffic, rewriting PEER {this.peerId}");
peerId = this.peerId;
}
// is this for our peer?
if (peerId == this.peerId)
{
// TODO: port the mux validation logic from dvmhost:src/common/network/Network.cpp
NXDNMessageType messageType = (NXDNMessageType)message[4];
uint srcId = FneUtils.Bytes3ToUInt32(message, 5);
uint dstId = FneUtils.Bytes3ToUInt32(message, 8);
byte bits = message[15];
CallType callType = ((bits & 0x40) == 0x40) ? CallType.PRIVATE : CallType.GROUP;
FrameType frameType = (messageType != NXDNMessageType.MESSAGE_TYPE_TX_REL) ? FrameType.VOICE : FrameType.TERMINATOR;
#if DEBUG
if (trafficLogging)
Log(LogLevel.DEBUG, $"{systemName} NXDD: SRC_PEER {peerId} SRC_ID {srcId} DST_ID {dstId} [STREAM ID {streamId}]");
#endif
// perform any userland actions with the data
FireNXDNDataReceived(new NXDNDataReceivedEvent(peerId, srcId, dstId, callType, messageType, frameType, rtpHeader.Sequence, streamId, message));
}
}
else if (fneHeader.SubFunction == Constants.NET_PROTOCOL_SUBFUNC_ANALOG) // Encapsulated Analog data frame
{
if (peerId != this.peerId)
{
//Log(LogLevel.WARNING, $"({systemName}) PEER {peerId}; routed traffic, rewriting PEER {this.peerId}");
peerId = this.peerId;
}
// is this for our peer?
if (peerId == this.peerId)
{
// TODO: port the mux validation logic from dvmhost:src/common/network/Network.cpp
uint srcId = FneUtils.Bytes3ToUInt32(message, 5);
uint dstId = FneUtils.Bytes3ToUInt32(message, 8);
CallType callType = CallType.GROUP; /* analog calls cannot be private calls right now ... */
AudioFrameType audioFrameType = (AudioFrameType)(message[15] & 0x0F);
FrameType frameType = (audioFrameType != AudioFrameType.TERMINATOR) ? FrameType.VOICE : FrameType.TERMINATOR;
#if DEBUG
if (trafficLogging)
Log(LogLevel.DEBUG, $"{systemName} P25D: SRC_PEER {peerId} SRC_ID {srcId} DST_ID {dstId} [STREAM ID {streamId}]");
#endif
// perform any userland actions with the data
FireAnalogDataReceived(new AnalogDataReceivedEvent(peerId, srcId, dstId, callType, audioFrameType, frameType, rtpHeader.Sequence, streamId, message));
}
}
else
{
Log(LogLevel.ERROR, $"({systemName}) Unknown protocol opcode {fneHeader.Function.ToString("X2")} / {fneHeader.SubFunction.ToString("X2")} -- {FneUtils.HexDump(message, 0)}");
}
}
break;
case Constants.NET_FUNC_MASTER: // Master
{
if (this.peerId == peerId)
{
// process incoming message subfunction opcodes
switch (fneHeader.SubFunction)
{
case Constants.NET_MASTER_SUBFUNC_WL_RID: // Whitelisted Radio IDs
case Constants.NET_MASTER_SUBFUNC_BL_RID: // Blacklisted Radio IDs
// ignore these
break;
case Constants.NET_MASTER_SUBFUNC_ACTIVE_TGS: // Talkgroup Active IDs
{
uint len = FneUtils.ToUInt32(message, 6);
int offs = 11;
for (int i = 0; i < len; i++)
{
uint id = FneUtils.Bytes3ToUInt32(message, offs);
byte slot = (byte)(message[offs + 3] & 0x03);
bool affiliated = (message[offs + 3] & 0x40) == 0x40;
bool nonPreferred = (message[offs + 3] & 0x80) == 0x80;
TalkgroupEntry entry = new TalkgroupEntry()
{
ID = id,
Slot = slot,
Affiliated = affiliated,
NonPreferred = nonPreferred,
Invalid = false
};
int idx = announcedTGs.FindIndex(x => x.ID == id && x.Slot == slot);
if (idx != -1)
announcedTGs[idx] = entry;
else
announcedTGs.Add(entry);
offs += 5;
}
Log(LogLevel.INFO, $"Activated {len} TGs; loaded {announcedTGs.Count} entries into talkgroup table");
}
break;
case Constants.NET_MASTER_SUBFUNC_DEACTIVE_TGS: // Talkgroup Deactivated IDs
{
uint len = FneUtils.ToUInt32(message, 6);
int offs = 11;
for (int i = 0; i < len; i++)
{
uint id = FneUtils.Bytes3ToUInt32(message, offs);
byte slot = message[offs + 3];
int idx = announcedTGs.FindIndex(x => x.ID == id && x.Slot == slot);
if (idx != -1)
announcedTGs[idx].Invalid = true;
else
{
TalkgroupEntry entry = new TalkgroupEntry()
{
ID = id,
Slot = slot,
Affiliated = false,
NonPreferred = false,
Invalid = true
};
announcedTGs.Add(entry);
}
offs += 5;
}
Log(LogLevel.INFO, $"Deactivated {len} TGs; loaded {announcedTGs.Count} entries into talkgroup table");
}
break;
case Constants.NET_MASTER_SUBFUNC_HA_PARAMS: // HA Parameters
{
haIPs.Clear();
currentHAIP = 0;
maxRetryCount = Constants.MAX_RETRY_HA_RECONNECT;
// always add the configured address to the HA IP list
haIPs.Add(new PeerHAIPEntry(masterEndpoint.Address.ToString(), masterEndpoint.Port));
uint len = FneUtils.ToUInt32(message, 6);
if (len > 0)
len /= Constants.HAParamsEntryLen;
int offs = 10;
for (int i = 0; i < len; i++, offs += (int)Constants.HAParamsEntryLen)
{
uint ipAddr = FneUtils.ToUInt32(message, offs + 4);
ushort port = FneUtils.ToUInt16(message, offs + 8);
IPAddress address = new IPAddress(ipAddr);
haIPs.Add(new PeerHAIPEntry(address.ToString(), port));
}
if (haIPs.Count > 1)
{
currentHAIP = 1;
Log(LogLevel.INFO, $"Loaded {haIPs.Count} HA IPs from master");
}
}
break;
default:
Log(LogLevel.ERROR, $"({systemName}) Unknown master opcode {fneHeader.Function.ToString("X2")} / {fneHeader.SubFunction.ToString("X2")} -- {FneUtils.HexDump(message, 0)}");
break;
}
}
}
break;
case Constants.NET_FUNC_INCALL_CTRL: // In-Call Control
{
if (this.peerId == peerId)
{
// process incoming message subfunction opcodes
switch (fneHeader.SubFunction)
{
case Constants.NET_PROTOCOL_SUBFUNC_DMR: // DMR In-Call Control
{
byte command = message[10];
uint dstId = FneUtils.Bytes3ToUInt32(message, 11);
byte slot = message[14];
// fire off DMR in-call callback if we have one
FireDMRInCallControl(new DMRInCallControlEvent(peerId, dstId, slot, command));
}
break;
case Constants.NET_PROTOCOL_SUBFUNC_P25: // P25 In-Call Control
{
byte command = message[10];
uint dstId = FneUtils.Bytes3ToUInt32(message, 11);
// fire off P25 in-call callback if we have one
FireP25InCallControl(new P25InCallControlEvent(peerId, dstId, command));
}
break;
case Constants.NET_PROTOCOL_SUBFUNC_NXDN: // NXDN In-Call Control
{
byte command = message[10];
uint dstId = FneUtils.Bytes3ToUInt32(message, 11);
// fire off NXDN in-call callback if we have one
FireNXDNInCallControl(new NXDNInCallControlEvent(peerId, dstId, command));
}
break;
case Constants.NET_PROTOCOL_SUBFUNC_ANALOG: // Analog In-Call Control
{
byte command = message[10];
uint dstId = FneUtils.Bytes3ToUInt32(message, 11);
// fire off analog in-call callback if we have one
FireAnalogInCallControl(new AnalogInCallControlEvent(peerId, dstId, command));
}
break;
default:
Log(LogLevel.ERROR, $"({systemName}) Unknown incall control opcode {fneHeader.Function.ToString("X2")} / {fneHeader.SubFunction.ToString("X2")} -- {FneUtils.HexDump(message, 0)}");
break;
}
}
}
break;
case Constants.NET_FUNC_NAK: // Master NAK
{
if (this.peerId == peerId)
{
// DVM 3.6 adds support to respond with a NAK reason, as such we just check if the NAK response is greater
// then 10 bytes and process the reason value
ConnectionMSTNAK reason = ConnectionMSTNAK.INVALID;
if (message.Length > 10)
{
reason = (ConnectionMSTNAK)FneUtils.ToUInt16(message, 10);
switch (reason)
{
case ConnectionMSTNAK.MODE_NOT_ENABLED:
Log(LogLevel.WARNING, $"({systemName}) PEER {this.peerId} master NAK; digital mode not enabled on FNE");
break;
case ConnectionMSTNAK.ILLEGAL_PACKET:
Log(LogLevel.WARNING, $"({systemName}) PEER {this.peerId} master NAK; illegal/unknown packet");
break;
case ConnectionMSTNAK.FNE_UNAUTHORIZED:
Log(LogLevel.WARNING, $"({systemName}) PEER {this.peerId} master NAK; unauthorized");
break;
case ConnectionMSTNAK.BAD_CONN_STATE:
Log(LogLevel.WARNING, $"({systemName}) PEER {this.peerId} master NAK; bad connection state");
break;
case ConnectionMSTNAK.INVALID_CONFIG_DATA:
Log(LogLevel.WARNING, $"({systemName}) PEER {this.peerId} master NAK; invalid configuration data");
break;
case ConnectionMSTNAK.FNE_MAX_CONN:
Log(LogLevel.WARNING, $"({systemName}) PEER {this.peerId} master NAK; FNE has reached maximum permitted connections");
break;
case ConnectionMSTNAK.PEER_RESET:
Log(LogLevel.WARNING, $"({systemName}) PEER {this.peerId} master NAK; FNE demanded connection reset");
break;
case ConnectionMSTNAK.PEER_ACL:
Log(LogLevel.ERROR, $"({systemName}) PEER {this.peerId} master NAK; ACL rejection, network disabled");
info.State = ConnectionState.WAITING_LOGIN;
Stop();
break;
case ConnectionMSTNAK.GENERAL_FAILURE:
default:
Log(LogLevel.WARNING, $"({systemName}) PEER {this.peerId} master NAK; general failure");
break;
}
}
if (info.State == ConnectionState.RUNNING && (reason == ConnectionMSTNAK.FNE_MAX_CONN))
{
Log(LogLevel.WARNING, $"({systemName}) PEER {this.peerId} master NAK; attemping to relogin");
// reset states
PingsSent = 0;
PingsAcked = 0;
info.State = ConnectionState.WAITING_LOGIN;
}
else
{
Log(LogLevel.ERROR, $"({systemName}) PEER {this.peerId} master NAK; network reconnect");
// reset states
PingsSent = 0;
PingsAcked = 0;
info.State = ConnectionState.WAITING_LOGIN;
break;
}
}
}
break;
case Constants.NET_FUNC_ACK: // Repeater ACK
{
if (info.State == ConnectionState.WAITING_LOGIN) // Repeater Login
{
uint salt = FneUtils.ToUInt32(message, 6);
Log(LogLevel.INFO, $"({systemName}) PEER {this.peerId} login ACK received with ID {salt}");
info.Salt = salt;
// calculate our own hash
byte[] inBuf = new byte[4 + Passphrase.Length];
FneUtils.WriteBytes(info.Salt, ref inBuf, 0);
FneUtils.StringToBytes(Passphrase, inBuf, 4, Passphrase.Length);
byte[] calcHash = FneUtils.sha256_hash(inBuf);
// send message to master
byte[] res = new byte[calcHash.Length + 8];
FneUtils.StringToBytes(Constants.TAG_REPEATER_AUTH, res, 0, 4);
FneUtils.WriteBytes(peerId, ref res, 4);
Buffer.BlockCopy(calcHash, 0, res, 8, calcHash.Length);
SendMaster(CreateOpcode(Constants.NET_FUNC_RPTK), res);
info.State = ConnectionState.WAITING_AUTHORISATION;
}
else if (info.State == ConnectionState.WAITING_AUTHORISATION) // Repeater Authorization
{
if (this.peerId == peerId)
{
string json = string.Empty;
using (MemoryStream stream = new MemoryStream())
{
using (Utf8JsonWriter jsonWriter = new Utf8JsonWriter(stream))
{
jsonWriter.WriteStartObject();
// identity
jsonWriter.WriteString("identity", info.Details.Identity);
jsonWriter.WriteNumber("rxFrequency", info.Details.RxFrequency);
jsonWriter.WriteNumber("txFrequency", info.Details.TxFrequency);
// peer types
jsonWriter.WriteBoolean("externalPeer", info.Details.ExternalPeer);
jsonWriter.WriteBoolean("conventionalPeer", info.Details.ConventionalPeer);
jsonWriter.WriteBoolean("sysView", info.Details.SysView);
// system info
{
jsonWriter.WritePropertyName("info");
jsonWriter.WriteStartObject();
jsonWriter.WriteNumber("latitude", info.Details.Latitude);
jsonWriter.WriteNumber("longitude", info.Details.Longitude);
jsonWriter.WriteNumber("height", info.Details.Height);
jsonWriter.WriteString("location", info.Details.Location);
jsonWriter.WriteEndObject();
}
// channel data
{
jsonWriter.WritePropertyName("channel");
jsonWriter.WriteStartObject();
jsonWriter.WriteNumber("txPower", info.Details.TxPower);
jsonWriter.WriteNumber("txOffsetMhz", (double)info.Details.TxOffsetMhz);
jsonWriter.WriteNumber("chBandwidthKhz", (double)info.Details.ChBandwidthKhz);
jsonWriter.WriteNumber("channelId", info.Details.ChannelID);
jsonWriter.WriteNumber("channelNo", info.Details.ChannelNo);
jsonWriter.WriteEndObject();
}
// RCON
{
jsonWriter.WritePropertyName("rcon");
jsonWriter.WriteStartObject();
jsonWriter.WriteString("password", info.Details.Password);
jsonWriter.WriteNumber("port", info.Details.Port);
jsonWriter.WriteEndObject();
}
jsonWriter.WriteString("software", info.Details.Software);
jsonWriter.WriteEndObject();
}
json = Encoding.UTF8.GetString(stream.ToArray());
}
// send message to master
byte[] res = new byte[json.Length + 8];
FneUtils.StringToBytes(Constants.TAG_REPEATER_CONFIG, res, 0, 4);
FneUtils.WriteBytes(peerId, ref res, 4);
FneUtils.StringToBytes(json, res, 8, json.Length);
SendMaster(CreateOpcode(Constants.NET_FUNC_RPTC), res);
info.State = ConnectionState.WAITING_CONFIG;
}
else
{
info.State = ConnectionState.WAITING_LOGIN;