-
Notifications
You must be signed in to change notification settings - Fork 22
/
GkClient.cxx
3344 lines (2908 loc) · 105 KB
/
GkClient.cxx
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
//////////////////////////////////////////////////////////////////
//
// GkClient.cxx
//
// Copyright (c) Citron Network Inc. 2001-2003
// Copyright (c) 2002-2023, Jan Willamowius
//
// This work is published under the GNU Public License version 2 (GPLv2)
// see file COPYING for details.
// We also explicitly grant the right to link this code
// with the OpenH323/H323Plus and OpenSSL library.
//
//////////////////////////////////////////////////////////////////
#include "config.h"
#include <ptlib.h>
#include <h323pdu.h>
#include <h235auth.h>
#include "stl_supp.h"
#include "RasPDU.h"
#include "RasSrv.h"
#include "ProxyChannel.h"
#include "h323util.h"
#include "sigmsg.h"
#include "cisco.h"
#include "GkClient.h"
#ifdef HAS_H460
#include <h460/h4601.h>
#endif
#ifdef HAS_H46023
#include <h460/h46024b.h>
#include <ptclib/pstun.h>
#include <ptclib/random.h>
#include <ptclib/cypher.h>
#endif
#if P_DNS
#include <ptclib/pdns.h>
#endif
#include <functional>
using std::vector;
using std::multimap;
using std::make_pair;
using std::for_each;
#if (__cplusplus < 201703L) // before C++17
using std::mem_fun;
using std::bind1st;
#endif
using Routing::Route;
namespace {
const char* const EndpointSection = "Endpoint";
const char* const RewriteE164Section = "Endpoint::RewriteE164";
}
bool IsOIDForAlgo(const PString & oid, const PCaselessString & algo)
{
if (algo == "MD5" && oid == OID_H235_MD5) {
return true;
};
if ( algo == "CAT" && oid == OID_H235_CAT) {
return true;
};
if (algo == "H.235.1"
&& (oid == OID_H235_A_V1 || oid == OID_H235_A_V2 || oid == OID_H235_T_V1 || oid == OID_H235_T_V2 || oid == OID_H235_U_V1 || oid == OID_H235_U_V2)) {
return true;
};
return false;
}
class AlternateGKs {
public:
AlternateGKs(const PIPSocket::Address &, WORD);
void Set(const H225_AlternateGK &);
void Set(const H225_ArrayOf_AlternateGK &);
void Set(const PString &);
bool Get(PIPSocket::Address &, WORD &);
private:
/* No copy constructor allowed */
AlternateGKs(const AlternateGKs &);
/* No operator= allowed */
AlternateGKs & operator=(const AlternateGKs &);
typedef multimap<int, H225_TransportAddress> GKList;
GKList AltGKs;
GKList::iterator index;
PIPSocket::Address pgkaddr;
WORD pgkport;
};
AlternateGKs::AlternateGKs(const PIPSocket::Address & gkaddr, WORD gkport)
: pgkaddr(gkaddr), pgkport(gkport)
{
}
void AlternateGKs::Set(const H225_AlternateGK & agk)
{
AltGKs.clear();
AltGKs.insert(make_pair(int(agk.m_priority), agk.m_rasAddress));
index = AltGKs.begin();
}
void AlternateGKs::Set(const H225_ArrayOf_AlternateGK & agk)
{
AltGKs.clear();
for (PINDEX i = 0; i < agk.GetSize(); ++i) {
const H225_AlternateGK & gk = agk[i];
AltGKs.insert(make_pair(int(gk.m_priority), gk.m_rasAddress));
}
index = AltGKs.begin();
}
void AlternateGKs::Set(const PString & addr)
{
PIPSocket::Address gkaddr;
WORD gkport;
if (GetTransportAddress(addr, GK_DEF_UNICAST_RAS_PORT, gkaddr, gkport)) {
H323TransportAddress taddr(gkaddr, gkport);
H225_TransportAddress haddr;
taddr.SetPDU(haddr);
AltGKs.insert(make_pair(AltGKs.size()+1, haddr));
}
}
bool AlternateGKs::Get(PIPSocket::Address & gkaddr, WORD & gkport)
{
if (!AltGKs.empty()) {
if (index == AltGKs.end()) {
index = AltGKs.begin();
// switch back to original GK
gkaddr = pgkaddr;
gkport = (WORD)pgkport;
return false;
}
const H225_TransportAddress & rasAddress = (index++)->second;
if (GetIPAndPortFromTransportAddr(rasAddress, gkaddr, gkport))
return true;
PTRACE(3, "GKC\tInvalid AlternateGK Address!");
return Get(gkaddr, gkport); // try next
}
return false;
}
class NATClient : public RegularJob {
public:
NATClient(const H225_TransportAddress &, const H225_EndpointIdentifier &);
// override from class RegularJob
virtual void Stop();
private:
// override from class Task
virtual void Exec();
bool DetectIncomingCall();
void SendInfo(int);
PIPSocket::Address gkip;
WORD gkport;
PString endpointId;
CallSignalSocket * socket;
};
NATClient::NATClient(const H225_TransportAddress & addr, const H225_EndpointIdentifier & id)
{
gkport = 0; // make sure port gets initialized, even if addr is invalid
GetIPAndPortFromTransportAddr(addr, gkip, gkport);
endpointId = id.GetValue();
socket = NULL;
SetName("NATClient");
Execute();
}
void NATClient::Stop()
{
PWaitAndSignal lock(m_deletionPreventer);
RegularJob::Stop();
if (socket) {
SendInfo(Q931::CallState_DisconnectRequest);
socket->Close();
}
}
void NATClient::Exec()
{
ReadLock lockConfig(ConfigReloadMutex);
#ifdef HAS_TLS
if (GkConfig()->GetBoolean(EndpointSection, "UseTLS", false)) {
socket = new TLSCallSignalSocket();
} else
#endif
{
socket = new CallSignalSocket();
}
socket->SetPort(gkport);
if (socket->Connect(gkip)) {
PTRACE(2, "GKC\t" << socket->GetName() << " connected, waiting for incoming call");
if (DetectIncomingCall()) {
PTRACE(3, "GKC\tIncoming call detected");
CreateJob(socket, &CallSignalSocket::Dispatch, "NAT call");
socket = NULL;
return;
}
}
PWaitAndSignal lockDeletion(m_deletionPreventer);
delete socket;
socket = NULL;
// If we lose the TCP connection then retry after 60 sec
int retryInterval = GkConfig()->GetInteger(EndpointSection, "NATRetryInterval", 60);
PTRACE(4, "GKC\tNAT Socket connection lost " << gkip << " retry connection in " << retryInterval << " secs.");
ReadUnlock unlockConfig(ConfigReloadMutex);
Wait(retryInterval * 1000);
}
bool NATClient::DetectIncomingCall()
{
while (socket->IsOpen()) {
// keep alive interval must be less than 30 sec (from testing 20 sec seems fine)
long retry = GkConfig()->GetInteger(EndpointSection, "NATKeepaliveInterval", 20);
SendInfo(Q931::CallState_IncomingCallProceeding);
ReadUnlock unlockConfig(ConfigReloadMutex);
while (socket->IsOpen() && --retry > 0)
if (socket->IsReadable(1000)) // one second
return socket->IsOpen();
}
return false;
}
void NATClient::SendInfo(int state)
{
Q931 information;
information.BuildInformation(0, false);
PBYTEArray buf, epid(endpointId, endpointId.GetLength(), false);
information.SetIE(Q931::FacilityIE, epid);
information.SetCallState(Q931::CallStates(state));
information.Encode(buf);
if (socket) {
PrintQ931(5, "Send to ", socket->GetName(), &information, NULL);
socket->TransmitData(buf);
}
}
//////////////////////////////////////////////////////////////////////
#ifdef HAS_H46023
// stuff cut from pstun.cxx
#pragma pack(1)
struct STUNattribute
{
enum Types {
MAPPED_ADDRESS = 0x0001,
RESPONSE_ADDRESS = 0x0002,
CHANGE_REQUEST = 0x0003,
SOURCE_ADDRESS = 0x0004,
CHANGED_ADDRESS = 0x0005,
USERNAME = 0x0006,
PASSWORD = 0x0007,
MESSAGE_INTEGRITY = 0x0008,
ERROR_CODE = 0x0009,
UNKNOWN_ATTRIBUTES = 0x000a,
REFLECTED_FROM = 0x000b,
MaxValidCode
};
PUInt16b type;
PUInt16b length;
STUNattribute * GetNext() const { return (STUNattribute *)(((const BYTE *)this)+length+4); }
};
class STUNaddressAttribute : public STUNattribute
{
public:
BYTE pad;
BYTE family;
PUInt16b port;
BYTE ip[4];
PIPSocket::Address GetIP() const { return PIPSocket::Address(4, ip); }
protected:
enum { SizeofAddressAttribute = sizeof(BYTE)+sizeof(BYTE)+sizeof(WORD)+sizeof(PIPSocket::Address) };
void InitAddrAttr(Types newType)
{
type = (WORD)newType;
length = SizeofAddressAttribute;
pad = 0;
family = 1;
}
bool IsValidAddrAttr(Types checkType) const
{
return type == checkType && length == SizeofAddressAttribute;
}
};
class STUNmappedAddress : public STUNaddressAttribute
{
public:
void Initialise() { InitAddrAttr(MAPPED_ADDRESS); }
bool IsValid() const { return IsValidAddrAttr(MAPPED_ADDRESS); }
};
class STUNchangedAddress : public STUNaddressAttribute
{
public:
void Initialise() { InitAddrAttr(CHANGED_ADDRESS); }
bool IsValid() const { return IsValidAddrAttr(CHANGED_ADDRESS); }
};
class STUNchangeRequest : public STUNattribute
{
public:
BYTE flags[4];
STUNchangeRequest(bool changeIP, bool changePort)
{
Initialise();
SetChangeIP(changeIP);
SetChangePort(changePort);
}
void Initialise()
{
type = CHANGE_REQUEST;
length = sizeof(flags);
memset(flags, 0, sizeof(flags));
}
bool IsValid() const { return type == CHANGE_REQUEST && length == sizeof(flags); }
bool GetChangeIP() const { return (flags[3]&4) != 0; }
void SetChangeIP(bool on) { if (on) flags[3] |= 4; else flags[3] &= ~4; }
bool GetChangePort() const { return (flags[3]&2) != 0; }
void SetChangePort(bool on) { if (on) flags[3] |= 2; else flags[3] &= ~2; }
};
class STUNmessageIntegrity : public STUNattribute
{
public:
BYTE hmac[20];
void Initialise()
{
type = MESSAGE_INTEGRITY;
length = sizeof(hmac);
memset(hmac, 0, sizeof(hmac));
}
bool IsValid() const { return type == MESSAGE_INTEGRITY && length == sizeof(hmac); }
};
struct STUNmessageHeader
{
PUInt16b msgType;
PUInt16b msgLength;
BYTE transactionId[16];
};
#pragma pack()
class STUNmessage : public PBYTEArray
{
public:
enum MsgType {
BindingRequest = 0x0001,
BindingResponse = 0x0101,
BindingError = 0x0111,
SharedSecretRequest = 0x0002,
SharedSecretResponse = 0x0102,
SharedSecretError = 0x0112,
};
STUNmessage() { }
STUNmessage(MsgType newType, const BYTE * id = NULL)
: PBYTEArray(sizeof(STUNmessageHeader))
{
SetType(newType, id);
}
void SetType(MsgType newType, const BYTE * id = NULL)
{
SetMinSize(sizeof(STUNmessageHeader));
STUNmessageHeader * hdr = (STUNmessageHeader *)theArray;
hdr->msgType = (WORD)newType;
for (PINDEX i = 0; i < ((PINDEX)sizeof(hdr->transactionId)); i++)
hdr->transactionId[i] = id != NULL ? id[i] : (BYTE)PRandom::Number();
}
const STUNmessageHeader * operator->() const { return (STUNmessageHeader *)theArray; }
// ignore overflow warning when comparing length
#if (!_WIN32) && (GCC_VERSION >= 40400)
#pragma GCC diagnostic ignored "-Wstrict-overflow"
#endif
STUNattribute * GetFirstAttribute()
{
if (theArray == NULL)
return NULL;
int length = ((STUNmessageHeader *)theArray)->msgLength;
if (length < (int) sizeof(STUNmessageHeader))
return NULL;
STUNattribute * attr = (STUNattribute *)(theArray+sizeof(STUNmessageHeader));
STUNattribute * ptr = attr;
if (attr->length > GetSize() || attr->type >= STUNattribute::MaxValidCode)
return NULL;
while (ptr && (BYTE*) ptr < (BYTE*)(theArray+GetSize()) && length >= (int) ptr->length+4) {
length -= ptr->length + 4;
ptr = ptr->GetNext();
}
if (length != 0)
return NULL;
return attr;
}
bool Validate()
{
int length = ((STUNmessageHeader *)theArray)->msgLength;
STUNattribute * attrib = GetFirstAttribute();
while (attrib && length > 0) {
length -= attrib->length + 4;
attrib = attrib->GetNext();
}
return length == 0; // Exactly correct length
}
void AddAttribute(const STUNattribute & attribute)
{
STUNmessageHeader * hdr = (STUNmessageHeader *)theArray;
int oldLength = hdr->msgLength;
int attrSize = attribute.length + 4;
int newLength = oldLength + attrSize;
hdr->msgLength = (WORD)newLength;
// hdr pointer may be invalidated by next statement
SetMinSize(newLength+sizeof(STUNmessageHeader));
memcpy(theArray+sizeof(STUNmessageHeader)+oldLength, &attribute, attrSize);
}
void SetAttribute(const STUNattribute & attribute)
{
int length = ((STUNmessageHeader *)theArray)->msgLength;
STUNattribute * attrib = GetFirstAttribute();
while (length > 0) {
if (attrib->type == attribute.type) {
if (attrib->length == attribute.length)
*attrib = attribute;
else {
// More here
}
return;
}
length -= attrib->length + 4;
attrib = attrib->GetNext();
}
AddAttribute(attribute);
}
STUNattribute * FindAttribute(STUNattribute::Types type)
{
int length = ((STUNmessageHeader *)theArray)->msgLength;
STUNattribute * attrib = GetFirstAttribute();
while (length > 0) {
if (attrib->type == type)
return attrib;
length -= attrib->length + 4;
attrib = attrib->GetNext();
}
return NULL;
}
bool Read(UDPSocket & socket)
{
if (!socket.Read(GetPointer(1000), 1000))
return false;
SetSize(socket.GetLastReadCount());
return true;
}
bool Write(UDPSocket & socket) const
{
return socket.Write(theArray, ((STUNmessageHeader *)theArray)->msgLength+sizeof(STUNmessageHeader)) != FALSE;
}
bool Poll(UDPSocket & socket, const STUNmessage & request, PINDEX pollRetries)
{
for (PINDEX retry = 0; retry < pollRetries; retry++) {
if (!request.Write(socket))
break;
if (Read(socket) && Validate() &&
memcmp(request->transactionId, (*this)->transactionId, sizeof(request->transactionId)) == 0)
return true;
}
return false;
}
};
//
class STUNsocket : public UDPProxySocket
{
public:
STUNsocket(const char * t, PINDEX callNo);
#ifdef LARGE_FDSET
// the YaSocket based UDPSocket has a const GetLocalAddress()
virtual PBoolean GetLocalAddress(PIPSocket::Address &) const;
virtual PBoolean GetLocalAddress(PIPSocket::Address &, WORD &) const;
#else
// the PTLib based UDPSocket has a non-const GetLocalAddress()
virtual PBoolean GetLocalAddress(PIPSocket::Address &);
virtual PBoolean GetLocalAddress(PIPSocket::Address &, WORD &);
#endif
PIPSocket::Address externalIP;
};
STUNsocket::STUNsocket(const char * t, PINDEX callNo)
: UDPProxySocket(t, callNo), externalIP(0)
{
}
#ifdef LARGE_FDSET
PBoolean STUNsocket::GetLocalAddress(PIPSocket::Address & addr) const
#else
PBoolean STUNsocket::GetLocalAddress(PIPSocket::Address & addr)
#endif
{
if (!externalIP.IsValid())
return UDPSocket::GetLocalAddress(addr);
addr = externalIP;
return true;
}
#ifdef LARGE_FDSET
PBoolean STUNsocket::GetLocalAddress(PIPSocket::Address & addr, WORD & port) const
#else
PBoolean STUNsocket::GetLocalAddress(PIPSocket::Address & addr, WORD & port)
#endif
{
if (!externalIP.IsValid())
return UDPSocket::GetLocalAddress(addr, port);
addr = externalIP;
port = GetPort();
return true;
}
//////
struct STUNportRange
{
STUNportRange() : minport(0), maxport(0) {}
void LoadConfig(const char *, const char *, const char * = "");
WORD minport, maxport;
};
void STUNportRange::LoadConfig(const char *sec, const char *setting, const char *def)
{
PStringArray cfgs = GkConfig()->GetString(sec, setting, def).Tokenise(",.:-/'", FALSE);
if (cfgs.GetSize() >= 2) {
minport = (WORD)cfgs[0].AsUnsigned();
maxport = (WORD)cfgs[1].AsUnsigned();
}
PTRACE(3, "STUN\tPort range set " << ": " << minport << '-' << maxport);
}
//////
class STUNClient : public Job,
public PSTUNClient
{
public:
STUNClient(GkClient * _client, const H323TransportAddress &);
virtual ~STUNClient();
#if PTLIB_VER >= 2130
struct PortInfo {
PortInfo(WORD port = 0)
: basePort(port), maxPort(port), currentPort(port) {}
PMutex mutex;
WORD basePort;
WORD maxPort;
WORD currentPort;
};
#endif
virtual void Stop();
virtual void Run();
virtual bool CreateSocketPair(
PINDEX callNo,
UDPProxySocket * & rtp,
UDPProxySocket * & rtcp,
const PIPSocket::Address & binding = PIPSocket::GetDefaultIpAny()
);
protected:
#if PTLIB_VER >= 2130
PortInfo pairedPortInfo;
#endif
bool OpenSocketA(UDPSocket & socket, PortInfo & portInfo, const PIPSocket::Address & binding);
private:
// override from class Task
virtual void Exec();
// Callback
void OnDetectedNAT(int m_nattype);
GkClient * m_client;
NatTypes m_nattype;
bool m_shutdown;
PMutex m_portCreateMutex;
int m_socketsForPairing;
int m_pollRetries;
};
STUNClient::STUNClient(GkClient * _client, const H323TransportAddress & addr)
: m_client(_client), m_nattype(UnknownNat), m_shutdown(false),
m_socketsForPairing(4), m_pollRetries(3)
{
PIPSocket::Address ip;
WORD port = 0;
addr.GetIpAndPort(ip, port);
#ifdef hasNewSTUN
m_serverAddress = PIPSocketAddressAndPort(ip, port);
#else
SetServer(ip, port);
#endif
STUNportRange ports;
ports.LoadConfig("Proxy", "RTPPortRange", "1024-65535");
SetPortRanges(ports.minport, ports.maxport, ports.minport, ports.maxport);
SetName("STUNClient");
Execute();
}
STUNClient::~STUNClient()
{
Stop();
}
void STUNClient::Stop()
{
Job::Stop();
// disconnect from STUN Server
m_shutdown = true;
}
void STUNClient::Run()
{
Exec();
}
void STUNClient::Exec()
{
ReadLock lockConfig(ConfigReloadMutex);
// Wait 500 ms until the RCF has been processed before running tests
// to prevent blocking.
PThread::Sleep(500);
// Get a valid NAT type....
m_nattype = GetNatType(TRUE);
OnDetectedNAT(m_nattype);
ReadUnlock unlockConfig(ConfigReloadMutex); // make sure the STUN client doesn't permanently hog the mutex
// Keep this job (thread) open so that creating STUN ports does not hold up
// the processing of other calls
while (!m_shutdown) {
PThread::Sleep(100);
}
}
void STUNClient::OnDetectedNAT(int nattype)
{
PTRACE(3, "STUN\tDetected NAT as type " << nattype << " " << GetNatTypeString((NatTypes)nattype));
// Call back to signal the GKClient to do a lightweight reregister
// to notify the gatekeeper
m_client->H46023_TypeDetected(nattype);
}
#ifdef hasNewSTUN
bool STUNClient::OpenSocketA(UDPSocket & socket, PortInfo & portInfo, const PIPSocket::Address & binding)
{
if (!m_serverAddress.IsValid()) {
PTRACE(1, "STUN\tServer port not set.");
return false;
}
if (portInfo.basePort == 0) {
if (!socket.Listen(binding, 1)) {
PTRACE(3, "STUN\tCannot bind port to " << m_interface);
return false;
}
} else {
WORD startPort = portInfo.currentPort;
PTRACE(3, "STUN\tUsing ports " << portInfo.basePort << " through " << portInfo.maxPort << " starting at " << startPort);
for (;;) {
bool status = socket.Listen(binding, 1, portInfo.currentPort);
PWaitAndSignal mutex(portInfo.mutex);
portInfo.currentPort++;
if (portInfo.currentPort > portInfo.maxPort)
portInfo.currentPort = portInfo.basePort;
if (status)
break;
if (portInfo.currentPort == startPort) {
PTRACE(3, "STUN\tListen failed on " << AsString(m_interface, portInfo.currentPort));
SNMP_TRAP(7, SNMPError, Network, "STUN failure");
return false;
}
}
}
socket.SetSendAddress(m_serverAddress.GetAddress(), m_serverAddress.GetPort());
return true;
}
#else
bool STUNClient::OpenSocketA(UDPSocket & socket, PortInfo & portInfo, const PIPSocket::Address & binding)
{
if (serverPort == 0) {
PTRACE(1, "STUN\tServer port not set.");
return false;
}
if (!PIPSocket::GetHostAddress(serverHost, cachedServerAddress) || !cachedServerAddress.IsValid()) {
PTRACE(2, "STUN\tCould not find host \"" << serverHost << "\".");
return false;
}
PWaitAndSignal mutex(portInfo.mutex);
WORD startPort = portInfo.currentPort;
do {
portInfo.currentPort++;
if (portInfo.currentPort > portInfo.maxPort)
portInfo.currentPort = portInfo.basePort;
if (socket.Listen(binding, 1, portInfo.currentPort)) {
socket.SetSendAddress(cachedServerAddress, serverPort);
socket.SetReadTimeout(replyTimeout);
return true;
}
} while (portInfo.currentPort != startPort);
PTRACE(1, "STUN\tFailed to bind to local UDP port in range "
<< portInfo.currentPort << '-' << portInfo.maxPort);
SNMP_TRAP(7, SNMPError, Network, "STUN failure");
return false;
}
#endif
bool STUNClient::CreateSocketPair(PINDEX callNo, UDPProxySocket * & rtp, UDPProxySocket * & rtcp, const PIPSocket::Address & binding)
{
// We only create port pairs, a pair at a time.
PWaitAndSignal m(m_portCreateMutex);
rtp = NULL;
rtcp = NULL;
if (GetNatType(FALSE) != ConeNat) {
PTRACE(1, "STUN\tCannot create socket pair using NAT type " << GetNatTypeName());
return FALSE;
}
PINDEX i;
PList<STUNsocket> stunSocket;
PList<STUNmessage> request;
PList<STUNmessage> response;
for (i = 0; i < m_socketsForPairing; i++)
{
PString t = (i%2 == 0 ? "rtp" : "rtcp");
PINDEX idx = stunSocket.Append(new STUNsocket(t, callNo));
if (!OpenSocketA(stunSocket[idx], pairedPortInfo, binding)) {
PTRACE(1, "STUN\tUnable to open socket to server " << GetServer());
return false;
}
idx = request.Append(new STUNmessage(STUNmessage::BindingRequest));
request[idx].AddAttribute(STUNchangeRequest(false, false));
response.Append(new STUNmessage);
}
for (i = 0; i < m_socketsForPairing; i++)
{
if (!response[i].Poll(stunSocket[i], request[i], m_pollRetries))
{
PTRACE(1, "STUN\tServer unexpectedly went offline." << GetServer());
return false;
}
}
for (i = 0; i < m_socketsForPairing; i++)
{
STUNmappedAddress * mappedAddress = (STUNmappedAddress *)response[i].FindAttribute(STUNattribute::MAPPED_ADDRESS);
if (mappedAddress == NULL)
{
PTRACE(2, "STUN\tExpected mapped address attribute from server " << GetServer());
return false;
}
if (GetNatType(FALSE) != SymmetricNat)
stunSocket[i].SetPort(mappedAddress->port);
stunSocket[i].externalIP = mappedAddress->GetIP();
}
for (i = 0; i < m_socketsForPairing; i++)
{
for (PINDEX j = 0; j < m_socketsForPairing; j++)
{
if ((stunSocket[i].GetPort()&1) == 0 && (stunSocket[i].GetPort()+1) == stunSocket[j].GetPort()) {
stunSocket[i].SetSendAddress(0, 0);
stunSocket[i].SetReadTimeout(PMaxTimeInterval);
stunSocket[j].SetSendAddress(0, 0);
stunSocket[j].SetReadTimeout(PMaxTimeInterval);
rtp = &stunSocket[i];
rtcp = &stunSocket[j];
stunSocket.DisallowDeleteObjects();
stunSocket.Remove(rtp);
stunSocket.Remove(rtcp);
stunSocket.AllowDeleteObjects();
return true;
}
}
}
PTRACE(2, "STUN\tCould not get a pair of adjacent port numbers from NAT");
return false;
}
/////////////////////////////////////////////////////////////////////
class GkClient;
class H46024Socket : public UDPProxySocket
{
public:
H46024Socket(GkClient * client, bool rtp, const H225_CallIdentifier & id, PINDEX callNo, CallRec::NatStrategy strategy, WORD sessionID);
enum probe_state {
e_notRequired, ///< Polling has not started
e_initialising, ///< We are initialising (local set but remote not)
e_idle, ///< Idle (waiting for first packet from remote)
e_probing, ///< Probing for direct route
e_verify_receiver, ///< verified receive connectivity
e_verify_sender, ///< verified send connectivity
e_wait, ///< we are waiting for direct media (to set address)
e_direct ///< we are going direct to detected address
};
struct probe_packet {
PUInt16b Length; // Length
PUInt32b SSRC; // Time Stamp
BYTE name[4]; // Name is limited to 32 (4 Bytes)
BYTE cui[20]; // SHA-1 is always 160 (20 Bytes)
};
virtual bool OnReceiveData(void *, PINDEX, Address &, WORD &);
PBoolean SendRTCPFrame(RTP_ControlFrame & report, const PIPSocket::Address & ip, WORD port, unsigned id);
virtual PBoolean WriteTo(const void * buf, PINDEX len, const Address & addr, WORD port);
virtual PBoolean WriteTo(const void * buf, PINDEX len, const Address & addr, WORD port, unsigned id);
#ifdef HAS_H46019CM
PBoolean WriteSocket(const void * buf, PINDEX len, const Address & addr, WORD port, unsigned altMux = 0);
#endif
void SetAlternateAddresses(const H323TransportAddress & address, const PString & cui, unsigned muxID);
void GetAlternateAddresses(H323TransportAddress & address, PString & cui, unsigned & muxID);
// Annex A
PBoolean ReceivedProbePacket(const RTP_ControlFrame & frame, bool & probe, bool & success);
void BuildProbe(RTP_ControlFrame & report, bool reply);
void StartProbe();
void ProbeReceived(bool probe, const PIPSocket::Address & addr, WORD & port);
void SetProbeState(probe_state newstate);
int GetProbeState() const;
void SignalH46024Adirect();
// Annex B
void H46024Bdirect(const H323TransportAddress & address, unsigned muxID);
void SendRTPPing(const PIPSocket::Address & ip, const WORD & port, unsigned id);
private:
CallRec::NatStrategy m_natStrategy;
WORD m_sessionID;
H225_CallIdentifier m_callIdentifier;
bool m_rtp;
PMutex probeMutex;
probe_state m_state;
// Addresses
PString m_CUIlocal; ///< Local CUI
PString m_CUIremote; ///< Remote CUI
PIPSocket::Address m_locAddr; ///< local Address (address used when starting socket)
PIPSocket::Address m_remAddr; WORD m_remPort; ///< Remote Address (address used when starting socket)
PIPSocket::Address m_detAddr; WORD m_detPort; ///< detected remote Address (as detected from actual packets)
PIPSocket::Address m_pendAddr; WORD m_pendPort; ///< detected pending RTCP Probe Address (as detected from actual packets)
PIPSocket::Address m_altAddr; WORD m_altPort; ///< supplied remote Address (as supplied in Generic Information)
unsigned m_altMuxID;
// Probes
PDECLARE_NOTIFIER(PTimer, H46024Socket, Probe); ///< Thread to probe for direct connection
PTimer m_Probe; ///< Probe Timer
PINDEX m_probes; ///< Probe count
DWORD SSRC; ///< Random number
// Annex B Probes
WORD m_keepseqno; ///< Probe sequence number
PTime m_keepStartTime; ///< Probe start time for TimeStamp.
};
H46024Socket::H46024Socket(GkClient * client, bool rtp, const H225_CallIdentifier & id, PINDEX callNo, CallRec::NatStrategy strategy, WORD sessionID)
:UDPProxySocket((rtp ? "rtp" : "rtcp"), callNo),
m_natStrategy(strategy), m_sessionID(sessionID), m_callIdentifier(id),
m_rtp(rtp), m_state(e_notRequired), m_remPort(0), m_detPort(0), m_pendPort(0), m_altPort(0),
m_altMuxID(0), m_probes(0), SSRC(0), m_keepseqno(100)
{
}
PBoolean H46024Socket::ReceivedProbePacket(const RTP_ControlFrame & frame, bool & probe, bool & success)
{
success = false;
//Inspect the probe packet
if (frame.GetPayloadType() != RTP_ControlFrame::e_ApplDefined)
return false;
int cstate = GetProbeState();
if (cstate == e_notRequired) {
PTRACE(6, "H46024A\ts:" << m_sessionID << " received RTCP probe packet. LOGIC ERROR!");
return false;
}
if (cstate > e_probing) {
PTRACE(6, "H46024A\ts:" << m_sessionID << " received RTCP probe packet. IGNORING! Already authenticated.");
return false;
}
probe = (frame.GetCount() > 0);
PTRACE(4, "H46024A\ts:" << m_sessionID << " RTCP Probe " << (probe ? "Reply" : "Request") << " received.");
#ifdef P_SSL
BYTE * data = frame.GetPayloadPtr();
PBYTEArray bytes(20);
memcpy(bytes.GetPointer(),data+12, 20);
PMessageDigest::Result bin_digest;
PMessageDigestSHA1::Encode(OpalGloballyUniqueID(m_callIdentifier.m_guid).AsString() + m_CUIlocal, bin_digest);
PBYTEArray val(bin_digest.GetPointer(),bin_digest.GetSize());
if (bytes == val) {
if (probe) // We have a reply
SetProbeState(e_verify_sender);
else
SetProbeState(e_verify_receiver);
m_Probe.Stop();
PTRACE(4, "H46024A\ts" << m_sessionID << " RTCP Probe " << (probe ? "Reply" : "Request") << " verified.");