forked from willamowius/gnugk
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Neighbor.cxx
2825 lines (2514 loc) · 95.6 KB
/
Neighbor.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
//////////////////////////////////////////////////////////////////
//
// Neighboring System for GNU Gatekeeper
//
// Copyright (c) Citron Network Inc. 2002-2003
// Copyright (c) 2004-2020, 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 <ptclib/pdns.h>
#include <ptclib/enum.h>
#include <h323pdu.h>
#include <ptclib/cypher.h>
#include "gk_const.h"
#include "stl_supp.h"
#include "GkClient.h"
#include "RasPDU.h"
#include "RasSrv.h"
#include "RasTbl.h"
#include "sigmsg.h"
#include "cisco.h"
#include "h323util.h"
#include "Neighbor.h"
#ifdef HAS_H460
#include <h460/h4601.h>
#endif
#ifdef P_SSL
#include <openssl/rand.h>
#endif // P_SSL
using std::multimap;
using std::make_pair;
using std::find_if;
using std::bind2nd;
using std::equal_to;
using std::mem_fun;
using Routing::Route;
namespace Neighbors {
const char *NeighborSection = "RasSrv::Neighbors";
const char *LRQFeaturesSection = "RasSrv::LRQFeatures";
const char *RoutedSec = "RoutedMode";
static const char OID_MD5[] = "1.2.840.113549.2.5";
void SetCryptoGkTokens(H225_ArrayOf_CryptoH323Token & cryptoTokens, const PString & id, const PString & password)
{
cryptoTokens.SetSize(0);
H235AuthSimpleMD5 auth;
// avoid copying for thread-safety
auth.SetLocalId((const char *)id);
auth.SetPassword((const char *)password);
H225_ArrayOf_ClearToken dumbTokens;
H225_ArrayOf_CryptoH323Token newCryptoTokens;
auth.PrepareTokens(dumbTokens, newCryptoTokens);
H225_CryptoH323Token_cryptoEPPwdHash & cryptoEPPwdHash = newCryptoTokens[0];
// Create the H.225 GK crypto token with the hash calculated for the EP token
H225_CryptoH323Token * finalCryptoToken = new H225_CryptoH323Token;
finalCryptoToken->SetTag(H225_CryptoH323Token::e_cryptoGKPwdHash);
H225_CryptoH323Token_cryptoGKPwdHash & cryptoGKPwdHash = *finalCryptoToken;
// Set the token data that actually goes over the wire
cryptoGKPwdHash.m_gatekeeperId = id;
cryptoGKPwdHash.m_timeStamp = cryptoEPPwdHash.m_timeStamp;
cryptoGKPwdHash.m_token.m_algorithmOID = OID_MD5;
cryptoGKPwdHash.m_token.m_hash = cryptoEPPwdHash.m_token.m_hash;
cryptoTokens.Append(finalCryptoToken);
}
class OldGK : public Neighbor {
// override from class Neighbor
virtual bool SetProfile(const PString &, const PString &);
};
class GnuGK : public Neighbor {
// override from class Neighbor
virtual bool OnSendingLRQ(H225_LocationRequest &, const AdmissionRequest &);
virtual bool OnSendingLRQ(H225_LocationRequest &, const SetupRequest &);
virtual bool OnSendingLRQ(H225_LocationRequest &, const FacilityRequest &);
virtual bool IsAcceptable(RasMsg *ras) const;
};
class CiscoGK : public Neighbor {
public:
// override from class Neighbor
virtual bool OnSendingLRQ(H225_LocationRequest &, const AdmissionRequest &);
virtual bool OnSendingLRQ(H225_LocationRequest &, const LocationRequest &);
virtual bool OnSendingLRQ(H225_LocationRequest &, const SetupRequest &);
virtual bool CheckReply(RasMsg *msg) const;
};
// stupid Clarent gatekeeper
class ClarentGK : public Neighbor {
// override from class Neighbor
virtual bool OnSendingLRQ(H225_LocationRequest &);
};
// a gatekeeper from a Korean vendor
class GlonetGK : public Neighbor {
// override from class Neighbor
virtual bool OnSendingLRQ(H225_LocationRequest &, const AdmissionRequest &);
virtual bool OnSendingLRQ(H225_LocationRequest &, const LocationRequest &);
virtual bool OnSendingLRQ(H225_LocationRequest &, const SetupRequest &);
virtual bool OnSendingLRQ(H225_LocationRequest &, const FacilityRequest &);
bool BuildLRQ(H225_LocationRequest &, WORD);
};
namespace { // anonymous namespace
SimpleCreator<OldGK> OldGKCreator("OldGK");
SimpleCreator<GnuGK> GnuGKCreator("GnuGK");
SimpleCreator<CiscoGK> CiscoGKCreator("CiscoGK");
SimpleCreator<ClarentGK> ClarentGKCreator("ClarentGK");
SimpleCreator<GlonetGK> GlonetGKCreator("GlonetGK");
int challenge;
const char * const OID_T = "0.0.8.235.0.2.5";
}
// if we put nomatch into anonymous namespace,
// stupid VC can't find it, why??
static const PrefixInfo nomatch(-1, 0);
// template class LRQSender
typedef Functor2<PrefixInfo, Neighbor *, WORD> LRQFunctor;
template<class R>
class LRQSender : public LRQFunctor {
public:
LRQSender(const R & r) : m_r(r) { }
virtual PrefixInfo operator()(Neighbor *, WORD seqnum) const;
private:
const R & m_r;
};
template<class R>
PrefixInfo LRQSender<R>::operator()(Neighbor *nb, WORD seqnum) const
{
// select neighbor based on dialed alias
if (const H225_ArrayOf_AliasAddress *dest = m_r.GetAliases()) {
H225_ArrayOf_AliasAddress aliases;
if (PrefixInfo info = nb->GetPrefixInfo(*dest, aliases)) {
H225_RasMessage lrq_ras;
H225_LocationRequest & lrq = nb->BuildLRQ(lrq_ras, seqnum, aliases);
if (nb->OnSendingLRQ(lrq, m_r) && nb->SendLRQ(lrq_ras))
return info;
}
}
// select neighbor based on dialed IP
if (const H225_TransportAddress *dest = m_r.GetDestIP()) {
H225_ArrayOf_AliasAddress aliases;
if (nb->GetIPInfo(*dest, aliases)) {
H225_RasMessage lrq_ras;
H225_LocationRequest & lrq = nb->BuildLRQ(lrq_ras, seqnum, aliases);
if (nb->OnSendingLRQ(lrq, m_r) && nb->SendLRQ(lrq_ras))
return PrefixInfo(100, 1);
}
}
return nomatch;
}
class LRQForwarder : public LRQFunctor {
public:
LRQForwarder(const LocationRequest & l) : m_lrq(l) { }
virtual PrefixInfo operator()(Neighbor *, WORD) const;
private:
const LocationRequest & m_lrq;
};
PrefixInfo LRQForwarder::operator()(Neighbor *nb, WORD /*seqnum*/) const
{
H225_ArrayOf_AliasAddress aliases;
if (PrefixInfo info = nb->GetPrefixInfo(m_lrq.GetRequest().m_destinationInfo, aliases)) {
H225_RasMessage lrq_ras;
lrq_ras.SetTag(H225_RasMessage::e_locationRequest);
H225_LocationRequest & lrq = lrq_ras;
// copy and forward
lrq = m_lrq.GetRequest();
lrq.m_destinationInfo = aliases;
// do the GW OUT rewrites
PString neighbor_id = nb->GetId();
PString neighbor_gkid = nb->GetGkId();
if (!neighbor_id.IsEmpty() && lrq.m_destinationInfo.GetSize() > 0) {
Toolkit::Instance()->GWRewriteE164(neighbor_id, GW_REWRITE_OUT, lrq.m_destinationInfo[0]);
}
if (!neighbor_gkid.IsEmpty() && (neighbor_gkid != neighbor_id) && lrq.m_destinationInfo.GetSize() > 0) {
Toolkit::Instance()->GWRewriteE164(neighbor_gkid, GW_REWRITE_OUT, lrq.m_destinationInfo[0]);
}
// include hopCount if configured and not already included
if (nb->GetDefaultHopCount() >= 1
&& !lrq.HasOptionalField(H225_LocationRequest::e_hopCount)) {
lrq.IncludeOptionalField(H225_LocationRequest::e_hopCount);
lrq.m_hopCount = nb->GetDefaultHopCount();
}
if (nb->OnSendingLRQ(lrq, m_lrq) && nb->SendLRQ(lrq_ras))
return info;
}
return nomatch;
}
// class LRQRequester
class LRQRequester : public RasRequester {
public:
LRQRequester(const LRQFunctor &);
virtual ~LRQRequester();
bool Send(NeighborList::List &, Neighbor * requester = NULL);
bool Send(Neighbor * nb);
int GetReqNumber() const { return m_requests.size(); }
H225_LocationConfirm * WaitForDestination(int timeout);
PString GetNeighborUsed() const { return m_neighbor_used; }
bool IsTraversalClient() const { return m_h46018_client; }
bool IsTraversalServer() const { return m_h46018_server; }
bool IsTraversalZone() const { return m_h46018_client || m_h46018_server; }
bool IsH46024Supported() const;
bool IsTLSNegotiated();
bool UseTLS() const { return m_useTLS; }
bool HasVendorInfo() const;
bool SupportLanguages() const;
PStringList GetLanguages() const;
// override from class RasRequester
virtual bool IsExpected(const RasMsg *) const;
virtual void Process(RasMsg *);
virtual bool OnTimeout();
private:
struct Request {
Request(Neighbor *n) : m_neighbor(n), m_reply(NULL), m_count(1) { }
Neighbor * m_neighbor;
RasMsg * m_reply;
int m_count;
};
typedef multimap<PrefixInfo, Request> Queue;
Queue m_requests;
PMutex m_rmutex;
const LRQFunctor & m_sendto;
RasMsg * m_result;
PString m_neighbor_used;
bool m_h46018_client, m_h46018_server;
bool m_useTLS;
};
class NeighborPingThread : public PThread, public RasRequester {
public:
NeighborPingThread(Neighbor * nb) : PThread(5000, AutoDeleteThread, NormalPriority, "NeighborPingThread"), m_nb(nb), m_stopThread(false) { }
virtual ~NeighborPingThread() { }
virtual void Main();
virtual void Process(RasMsg * ras);
virtual void StopThread() { m_stopThread = true; }
bool SendRequest(const Address & addr, WORD pt, int r);
protected:
Neighbor * m_nb;
bool m_stopThread;
};
void NeighborPingThread::Main()
{
int timeout = GkConfig()->GetInteger(LRQFeaturesSection, "NeighborTimeout", 5) * 1000;
PString pingAlias = GkConfig()->GetString(LRQFeaturesSection, "PingAlias", "gatekeeper-monitoring-check");
H225_ArrayOf_AliasAddress aliases;
aliases.SetSize(1);
H323SetAliasAddress(pingAlias, aliases[0]);
while (!m_stopThread) {
AddFilter(H225_RasMessage::e_locationConfirm);
AddFilter(H225_RasMessage::e_locationReject);
m_rasSrv->RegisterHandler(this);
m_request = new H225_RasMessage();
m_nb->BuildLRQ(*m_request, m_seqNum, aliases);
SendRequest(m_nb->GetIP(), m_nb->GetPort(), 0); // no retries
bool signaled = m_sync.Wait(timeout);
if (!signaled) {
if (!m_nb->IsDisabled()) {
PTRACE(3, "NB\tPing timeout: Disabling neighbor " << m_nb->GetId());
m_nb->SetDisabled(true);
}
}
m_rasSrv->UnregisterHandler(this);
delete m_request;
m_request = NULL;
Suspend();
}
Terminate(); // stop thread and auto delete
}
void NeighborPingThread::Process(RasMsg * ras)
{
switch (ras->GetTag()) {
case H225_RasMessage::e_requestInProgress:
break;
case H225_RasMessage::e_locationConfirm:
case H225_RasMessage::e_locationReject:
if (m_nb->IsDisabled()) {
PTRACE(3, "NB\tPing successful: Activating neighbor " << m_nb->GetId());
m_nb->SetDisabled(false);
}
m_sync.Signal();
break;
default:
PTRACE(1, "RAS\tUnknown reply " << ras->GetTagName());
break;
}
delete ras;
}
bool NeighborPingThread::SendRequest(const Address & addr, WORD pt, int r)
{
m_txAddr = addr, m_txPort = pt, m_retry = r;
vector<Address> GKHome;
Toolkit::Instance()->GetGKHome(GKHome);
for (std::vector<Address>::iterator i = GKHome.begin(); i != GKHome.end(); ++i) {
if ((IsLoopback(addr) || IsLoopback(*i)) && addr != *i)
continue;
if (addr.GetVersion() != i->GetVersion())
continue;
GkInterface * inter = m_rasSrv->SelectInterface(*i);
if (inter == NULL)
return false;
RasListener *socket = inter->GetRasListener();
socket->SendRas(*m_request, addr, pt, NULL);
}
m_sentTime = PTime();
return true;
}
// class Neighbor
Neighbor::Neighbor()
{
m_rasSrv = RasServer::Instance();
m_port = 0;
m_forwardHopCount = 0;
m_dynamic = false;
m_acceptForwarded = true;
m_forwardResponse = false;
m_forwardto = 0;
m_externalGK = false;
m_keepAliveTimer = GkTimerManager::INVALID_HANDLE;
m_keepAliveTimerInterval = 0;
m_lrqPingTimer = GkTimerManager::INVALID_HANDLE;
m_lrqPingInterval = 0;
m_pingThread = NULL;
m_H46018Server = false;
m_H46018Client = false;
m_useTLS = false;
m_disabled = false;
m_loopDetection = false;
}
Neighbor::~Neighbor()
{
if (m_keepAliveTimer != GkTimerManager::INVALID_HANDLE)
Toolkit::Instance()->GetTimerManager()->UnregisterTimer(m_keepAliveTimer);
if (m_lrqPingTimer != GkTimerManager::INVALID_HANDLE)
Toolkit::Instance()->GetTimerManager()->UnregisterTimer(m_lrqPingTimer);
if (m_pingThread != NULL) {
m_pingThread->StopThread();
m_pingThread = NULL; // auto delete thread will delete itself
}
PTRACE(1, "NB\tDelete neighbor " << m_id);
}
bool Neighbor::SendLRQ(H225_RasMessage & lrq_ras)
{
if (!m_sendPassword.IsEmpty()) {
H225_LocationRequest & lrq = lrq_ras;
lrq.IncludeOptionalField(H225_LocationRequest::e_cryptoTokens);
lrq.m_cryptoTokens.SetSize(1);
SetCryptoGkTokens(lrq.m_cryptoTokens, m_sendAuthUser, m_sendPassword);
}
return m_rasSrv->SendRas(lrq_ras, GetIP(), m_port);
}
PIPSocket::Address Neighbor::GetIP() const
{
if (m_dynamic) {
PIPSocket::ClearNameCache();
// Retrieve the ip address at this time
if (!GetTransportAddress(m_name, GK_DEF_UNICAST_RAS_PORT, m_ip, m_port)) {
PTRACE(1, "NB\tCan't get neighbor ip for " << m_name);
}
}
return m_ip;
}
WORD Neighbor::GetPort() const
{
if (m_dynamic) {
PIPSocket::ClearNameCache();
// Retrieve the ip address at this time
if (!GetTransportAddress(m_name, GK_DEF_UNICAST_RAS_PORT, m_ip, m_port)) {
PTRACE(1, "NB\tCan't get neighbor port for " << m_name);
}
}
return m_port;
}
H225_LocationRequest & Neighbor::BuildLRQ(H225_RasMessage & lrq_ras, WORD seqnum, const H225_ArrayOf_AliasAddress & dest)
{
lrq_ras.SetTag(H225_RasMessage::e_locationRequest);
H225_LocationRequest & lrq = lrq_ras;
lrq.m_requestSeqNum = seqnum;
lrq.m_destinationInfo = dest;
// perform outbound per GK rewrite on the destination of the LRQ
Toolkit::Instance()->GWRewriteE164(m_id, GW_REWRITE_OUT, lrq.m_destinationInfo[0]);
if (m_gkid != m_id)
Toolkit::Instance()->GWRewriteE164(m_gkid, GW_REWRITE_OUT, lrq.m_destinationInfo[0]);
lrq.m_replyAddress = m_rasSrv->GetRasAddress(GetIP());
// lrq.IncludeOptionalField(H225_LocationRequest::e_gatekeeperIdentifier);
// lrq.m_gatekeeperIdentifier = Toolkit::GKName();
// lrq.IncludeOptionalField(H225_LocationRequest::e_nonStandardData);
// lrq.m_nonStandardData.m_data.SetValue(m_id);
lrq.IncludeOptionalField(H225_LocationRequest::e_sourceInfo);
lrq.m_sourceInfo.SetSize(1);
H323SetAliasAddress(Toolkit::GKName(), lrq.m_sourceInfo[0], H225_AliasAddress::e_h323_ID);
// TODO: is this right ?
if (m_externalGK) {
m_rasSrv->GetGkClient()->SetNBPassword(lrq, Toolkit::GKName());
}
if (m_forwardHopCount >= 1) { // what if set hopCount = 1?
lrq.IncludeOptionalField(H225_LocationRequest::e_hopCount);
lrq.m_hopCount = m_forwardHopCount;
}
return lrq;
}
bool Neighbor::SetProfile(const PString & id, const PString & type, bool reload)
{
PConfig *config = GkConfig();
PString section("Neighbor::" + (m_id = id));
m_gkid = config->GetString(section, "GatekeeperIdentifier", id);
m_name = config->GetString(section, "Host", "");
m_dynamic = Toolkit::AsBool(config->GetString(section, "Dynamic", "0"));
m_externalGK = false;
m_authUser = config->GetString(section, "AuthUser", m_gkid); // defaults to GatekeeperIdentifier
m_password = Toolkit::Instance()->ReadPassword(section, "Password"); // checking incoming password in LRQ (not implemented, yet)
m_sendAuthUser = config->GetString(section, "SendAuthUser", Toolkit::GKName()); // defaults to own GatekeeperId
m_sendPassword = Toolkit::Instance()->ReadPassword(section, "SendPassword"); // password to send to neighbor
#ifdef HAS_H46018
m_H46018Server = Toolkit::AsBool(config->GetString(section, "H46018Server", "0"));
#endif // HAS_H46018
if (!m_dynamic
#ifdef HAS_H46018
&& !m_H46018Server
#endif // HAS_H46018
&& !GetTransportAddress(m_name, GK_DEF_UNICAST_RAS_PORT, m_ip, m_port)) {
return false;
}
m_sendPrefixes.clear();
PString sprefix(config->GetString(section, "SendPrefixes", ""));
PStringArray sprefixes(sprefix.Tokenise(",", false));
for (PINDEX i = 0; i < sprefixes.GetSize(); ++i) {
PStringArray p(sprefixes[i].Tokenise(":=", false));
m_sendPrefixes[p[0]] = (p.GetSize() > 1) ? p[1].AsInteger() : 1;
}
m_sendIPs = config->GetString(section, "SendIPs", "");
PString salias(config->GetString(section, "SendAliases", ""));
PStringArray defs(salias.Tokenise(",", FALSE));
m_sendAliases.SetSize(0);
for (PINDEX i = 0; i < defs.GetSize(); i++) {
if (defs[i].Find("-") != P_MAX_INDEX) {
// range
PStringArray bounds(defs[i].Tokenise("-", FALSE));
PUInt64 lower = bounds[0].AsUnsigned64();
PUInt64 upper = 0;
if (bounds.GetSize() == 2) {
upper = bounds[1].AsUnsigned64();
} else {
PTRACE(1, "SendAliases: Invalid range definition: " << defs[i]);
continue;
}
if (upper <= lower) {
PTRACE(1, "SendAliases: Invalid range bounds: " << defs[i]);
continue;
}
PUInt64 num = upper - lower;
for (unsigned j = 0; j <= num; j++) {
PString number(lower + j);
PTRACE(4, "Adding alias " << number << " to neighbor " << m_id << " (from range)");
m_sendAliases.AppendString(number);
}
} else {
// single alias
PTRACE(4, "Adding alias " << defs[i] << " to neighbor " << m_id);
m_sendAliases.AppendString(defs[i]);
}
}
PString aprefix(config->GetString(section, "AcceptPrefixes", "*"));
m_acceptPrefixes = PStringArray(aprefix.Tokenise(",", false));
if (m_keepAliveTimer != GkTimerManager::INVALID_HANDLE)
Toolkit::Instance()->GetTimerManager()->UnregisterTimer(m_keepAliveTimer);
#ifdef HAS_H46018
if (Toolkit::AsBool(config->GetString(section, "H46018Client", "0"))) {
m_H46018Client = true;
// this is our initial interval, the server will tell the client the real interval
int h46018GkKeepAliveInterval = config->GetInteger(RoutedSec, "H46018KeepAliveInterval", 19);
SetH46018GkKeepAliveInterval(h46018GkKeepAliveInterval);
}
#endif // HAS_H46018
if (m_lrqPingTimer != GkTimerManager::INVALID_HANDLE)
Toolkit::Instance()->GetTimerManager()->UnregisterTimer(m_lrqPingTimer);
if (config->GetBoolean(LRQFeaturesSection, "SendLRQPing", false) || config->GetBoolean(section, "SendLRQPing", false)) {
SetLRQPingInterval(config->GetInteger(LRQFeaturesSection, "LRQPingInterval", 60));
} else {
if (m_pingThread != NULL) {
// config changed: we had a ping thread, but now we don't need it anymore
m_pingThread->StopThread();
m_pingThread = NULL; // auto delete thread will delete itself
}
}
#ifdef HAS_TLS
m_useTLS = Toolkit::AsBool(config->GetString(section, "UseTLS", "0")); // forced use of TLS
#endif
m_loopDetection = config->GetBoolean(LRQFeaturesSection, "LoopDetection", false);
SetForwardedInfo(section);
PString info = " of type " + type;
if (!sprefix)
info = " send=" + sprefix;
if (!aprefix)
info += " accept=" + aprefix;
PTRACE(1, "Set neighbor " << id << '(' << (m_dynamic ? m_name : AsString(m_ip, m_port)) << ')' << info);
if (!reload && (m_H46018Client || m_H46018Server)) {
// H.460 client and server start out disabled and get enabled on the first SCI/SCR
// don't do on reload, otherwise working neighbors become unavailable for a short time on config reload
SetDisabled(true);
}
return true;
}
void Neighbor::SendLRQPing(GkTimer * timer)
{
if (m_pingThread == NULL)
m_pingThread = new NeighborPingThread(this);
m_pingThread->Resume(); // send 1 ping, process and suspend yourself
}
void Neighbor::SetLRQPingInterval(int interval)
{
if (m_lrqPingInterval != interval) {
m_lrqPingInterval = interval;
if (m_keepAliveTimer != GkTimerManager::INVALID_HANDLE) {
Toolkit::Instance()->GetTimerManager()->UnregisterTimer(m_keepAliveTimer);
m_keepAliveTimer = GkTimerManager::INVALID_HANDLE;
}
if (m_lrqPingInterval > 0) {
PTime now;
m_keepAliveTimer = Toolkit::Instance()->GetTimerManager()->RegisterTimer(
this, &Neighbor::SendLRQPing, now, m_lrqPingInterval);
}
}
}
void Neighbor::SendH46018GkKeepAlive(GkTimer* timer)
{
#ifdef HAS_H46018
// TODO: set this neighbor to disabled if we didn't receive any messages since INTERVAL sec
// send SCI to open the pinhole to neighbor GK
H225_RasMessage sci_ras;
sci_ras.SetTag(H225_RasMessage::e_serviceControlIndication);
H225_ServiceControlIndication & sci = sci_ras;
sci.m_requestSeqNum = m_rasSrv->GetRequestSeqNum();
// Tandberg GK adds open here, the standard doesn't mention this
H225_ServiceControlSession controlOpen;
controlOpen.m_sessionId = 0;
controlOpen.m_reason = H225_ServiceControlSession_reason::e_open;
sci.m_serviceControl.SetSize(1);
sci.m_serviceControl[0] = controlOpen;
H460_FeatureStd feat = H460_FeatureStd(18);
sci.IncludeOptionalField(H225_ServiceControlIndication::e_featureSet);
sci.m_featureSet.IncludeOptionalField(H225_FeatureSet::e_supportedFeatures);
H225_ArrayOf_FeatureDescriptor & desc = sci.m_featureSet.m_supportedFeatures;
desc.SetSize(1);
desc[0] = feat;
if (!m_sendPassword.IsEmpty()) {
sci.IncludeOptionalField(H225_ServiceControlIndication::e_cryptoTokens);
sci.m_cryptoTokens.SetSize(1);
SetCryptoGkTokens(sci.m_cryptoTokens, m_sendAuthUser, m_sendPassword);
}
m_rasSrv->SendRas(sci_ras, GetIP(), m_port);
#endif
}
void Neighbor::SetH46018GkKeepAliveInterval(int interval)
{
if (m_keepAliveTimerInterval != interval) {
m_keepAliveTimerInterval = interval;
if (m_keepAliveTimer != GkTimerManager::INVALID_HANDLE)
Toolkit::Instance()->GetTimerManager()->UnregisterTimer(m_keepAliveTimer);
if (m_keepAliveTimerInterval > 0) {
PTime now;
m_keepAliveTimer = Toolkit::Instance()->GetTimerManager()->RegisterTimer(
this, &Neighbor::SendH46018GkKeepAlive, now, m_keepAliveTimerInterval); // do it now and every n seconds
}
}
}
// initialize neighbor object created by SRV policy
bool Neighbor::SetProfile(const PString & name, const H323TransportAddress & addr)
{
addr.GetIpAndPort(m_ip, m_port);
m_id = "SRVrec";
m_name = name;
m_dynamic = false;
m_externalGK = true;
m_sendPrefixes.clear();
m_sendPrefixes["*"] = 1;
SetForwardedInfo(LRQFeaturesSection);
return true;
}
PrefixInfo Neighbor::GetPrefixInfo(const H225_ArrayOf_AliasAddress & aliases, H225_ArrayOf_AliasAddress & dest)
{
if (IsDisabled()) {
PTRACE(3, "NB\tSkipping disabled neighbor " << GetId());
return nomatch;
}
Prefixes::iterator iter, biter = m_sendPrefixes.begin(), eiter = m_sendPrefixes.end();
for (PINDEX i = 0; i < aliases.GetSize(); ++i) {
H225_AliasAddress & alias = aliases[i];
// send by alias type
iter = m_sendPrefixes.find(alias.GetTagName());
if (iter != eiter) {
dest.SetSize(1);
dest[0] = alias;
return PrefixInfo(100, (short)iter->second);
}
PString destination(AsString(alias, false));
// send by exact alias match
for (PINDEX j = 0; j < m_sendAliases.GetSize(); j++) {
if (destination == m_sendAliases[j]) {
dest.SetSize(1);
dest[0] = alias;
return PrefixInfo(100, 1);
}
}
// send by prefix
while (iter != biter) {
--iter; // search in reverse order
const int len = MatchPrefix(destination, iter->first);
if (len < 0) {
return nomatch;
}
else if (len > 0) {
dest.SetSize(1);
dest[0] = alias;
return PrefixInfo((short)len, (short)iter->second);
}
}
}
// send always ? (handled last, treated as shortest match)
iter = m_sendPrefixes.find("*");
if (iter == eiter)
return nomatch;
dest = aliases;
return PrefixInfo(0, (short)iter->second);
}
PrefixInfo Neighbor::GetIPInfo(const H225_TransportAddress & ip, H225_ArrayOf_AliasAddress & dest) const
{
if (IsDisabled()) {
PTRACE(3, "NB\tSkipping disabled neighbor " << GetId());
return nomatch;
}
PStringArray sendNet(m_sendIPs.Tokenise(","));
for (PINDEX i = 0; i < sendNet.GetSize(); ++i) {
bool noMatch = false;
if (sendNet[i].Left(1) == "!") {
noMatch = true;
sendNet[i] = sendNet[i].Mid(1); // cut away first char ("!")
}
NetworkAddress network = NetworkAddress(sendNet[i]);
PIPSocket::Address addr;
bool validNetwork = GetIPFromTransportAddr(ip, addr);
if ((sendNet[i] == "*")
|| ((sendNet[i] == "public") && !IsPrivate(addr))
|| ((sendNet[i] == "private") && IsPrivate(addr))
|| (validNetwork && !noMatch && (NetworkAddress(addr) << network))
|| (validNetwork && noMatch && !(NetworkAddress(addr) << network)) )
{
dest.SetSize(1);
H323SetAliasAddress(AsDotString(ip), dest[0], H225_AliasAddress::e_transportID);
return PrefixInfo(100, 1);
}
}
return nomatch; // don't send to this neighbor
}
bool Neighbor::OnSendingLRQ(H225_LocationRequest & lrq)
{
return true;
}
bool Neighbor::OnSendingLRQ(H225_LocationRequest & lrq, const AdmissionRequest &)
{
return OnSendingLRQ(lrq);
}
bool Neighbor::OnSendingLRQ(H225_LocationRequest & lrq, const LocationRequest & orig_lrq)
{
// adjust hopCount to be lesser or equal to the original value
if (orig_lrq.GetRequest().HasOptionalField(H225_LocationRequest::e_hopCount)) {
if (lrq.HasOptionalField(H225_LocationRequest::e_hopCount)) {
if (lrq.m_hopCount > orig_lrq.GetRequest().m_hopCount)
lrq.m_hopCount = orig_lrq.GetRequest().m_hopCount;
} else {
lrq.IncludeOptionalField(H225_LocationRequest::e_hopCount);
lrq.m_hopCount = orig_lrq.GetRequest().m_hopCount;
}
}
// copy over canMapAlias
if (orig_lrq.GetRequest().HasOptionalField(H225_LocationRequest::e_canMapAlias)) {
lrq.IncludeOptionalField(H225_LocationRequest::e_canMapAlias);
lrq.m_canMapAlias = orig_lrq.GetRequest().m_canMapAlias;
}
if (m_loopDetection) {
if (orig_lrq.GetRequest().HasOptionalField(H225_LocationRequest::e_callIdentifier)) {
lrq.IncludeOptionalField(H225_LocationRequest::e_callIdentifier);
lrq.m_callIdentifier = orig_lrq.GetRequest().m_callIdentifier;
}
if (orig_lrq.GetRequest().HasOptionalField(H225_LocationRequest::e_sourceEndpointInfo)) {
lrq.IncludeOptionalField(H225_LocationRequest::e_sourceEndpointInfo);
lrq.m_sourceEndpointInfo = orig_lrq.GetRequest().m_sourceEndpointInfo;
}
}
return OnSendingLRQ(lrq);
}
bool Neighbor::OnSendingLRQ(H225_LocationRequest & lrq, const SetupRequest &)
{
return OnSendingLRQ(lrq);
}
bool Neighbor::OnSendingLRQ(H225_LocationRequest & lrq, const FacilityRequest &)
{
return OnSendingLRQ(lrq);
}
bool Neighbor::CheckReply(RasMsg *ras) const
{
if( ras->IsFrom(GetIP(), 0) )
return true;
const H225_NonStandardParameter *param = ras->GetNonStandardParam();
if (param == NULL)
return false;
int iec = Toolkit::iecUnknown;
if (param->m_nonStandardIdentifier.GetTag() == H225_NonStandardIdentifier::e_h221NonStandard) {
iec = Toolkit::Instance()->GetInternalExtensionCode((const H225_H221NonStandard&)param->m_nonStandardIdentifier);
} else if (param->m_nonStandardIdentifier.GetTag() == H225_NonStandardIdentifier::e_object) {
const PASN_ObjectId &oid = param->m_nonStandardIdentifier;
if (oid.GetDataLength() == 0)
iec = Toolkit::iecNeighborId;
}
return iec == Toolkit::iecNeighborId
? strncmp(m_id, param->m_data.AsString(), m_id.GetLength()) == 0
: false;
}
bool Neighbor::Authenticate(RasMsg *ras) const
{
if (m_password.IsEmpty()) {
return true; // no password, no check needed
} else {
// check tokens
H225_ArrayOf_CryptoH323Token tokens;
// check LRQs and SCIs
switch (ras->GetTag()) {
case H225_RasMessage::e_locationRequest:
{
H225_LocationRequest & lrq = (*ras)->m_recvRAS;
if (lrq.HasOptionalField(H225_LocationRequest::e_cryptoTokens))
tokens = lrq.m_cryptoTokens;
}
break;
case H225_RasMessage::e_serviceControlIndication:
{
H225_ServiceControlIndication & sci = (*ras)->m_recvRAS;
if (sci.HasOptionalField(H225_ServiceControlIndication::e_cryptoTokens))
tokens = sci.m_cryptoTokens;
}
break;
default:
break;
}
H235AuthSimpleMD5 authMD5;
PBYTEArray dummy;
authMD5.SetLocalId(m_authUser);
authMD5.SetPassword(m_password);
for (PINDEX i = 0 ; i < tokens.GetSize(); i++) {
H225_CryptoH323Token cryptoToken;
if (tokens[i].GetTag() == H225_CryptoH323Token::e_cryptoGKPwdHash) {
// convert the GKPwdHash into an EPPwdHash that H323Plus is able to check
H225_CryptoH323Token_cryptoGKPwdHash & cryptoGKPwdHash = tokens[i];
cryptoToken.SetTag(H225_CryptoH323Token::e_cryptoEPPwdHash);
H225_CryptoH323Token_cryptoEPPwdHash & cryptoEPPwdHash = cryptoToken;
H323SetAliasAddress(cryptoGKPwdHash.m_gatekeeperId, cryptoEPPwdHash.m_alias);
cryptoEPPwdHash.m_timeStamp = cryptoGKPwdHash.m_timeStamp;
cryptoEPPwdHash.m_token.m_algorithmOID = OID_MD5;
cryptoEPPwdHash.m_token.m_hash = cryptoGKPwdHash.m_token.m_hash;
} else {
cryptoToken = tokens[i]; // use other tokens as they are
}
if (authMD5.ValidateCryptoToken(cryptoToken, dummy) == H235Authenticator::e_OK) {
PTRACE(5, "Neighbor\tMD5 password match");
return true;
}
}
PTRACE(1, "Neighbor\tPassword required, but no match");
return false; // no token found that allows access
}
}
bool Neighbor::IsAcceptable(RasMsg *ras) const
{
if (ras->IsFrom(GetIP(), 0)) {
// ras must be an LRQ
H225_LocationRequest & lrq = (*ras)->m_recvRAS;
PINDEX i, j, sz = m_acceptPrefixes.GetSize();
H225_ArrayOf_AliasAddress & aliases = lrq.m_destinationInfo;
for (j = 0; j < aliases.GetSize(); ++j) {
H225_AliasAddress & alias = aliases[j];
for (i = 0; i < sz; ++i) {
if (m_acceptPrefixes[i] == alias.GetTagName()) {
return true;
}
}
PString destination(AsString(alias, false));
int maxlen = 0;
for (i = 0; i < sz; ++i) {
const PString & prefix = m_acceptPrefixes[i];
const int len = MatchPrefix(destination, prefix);
if (len < 0)
return false;
else if (len > maxlen)
maxlen = len;
}
if (maxlen > 0)
return true;
}
for (i = 0; i < sz; ++i) {
if (m_acceptPrefixes[i] == "*") {
return true;
}
}
}
return false;
}
void Neighbor::SetForwardedInfo(const PString & section)
{
PConfig * config = GkConfig();
m_forwardHopCount = (WORD)config->GetInteger(section, "ForwardHopCount", config->GetInteger(LRQFeaturesSection, "ForwardHopCount", 0));
m_acceptForwarded = config->GetBoolean(section, "AcceptForwardedLRQ", config->GetBoolean(LRQFeaturesSection, "AcceptForwardedLRQ", true));
m_forwardResponse = config->GetBoolean(section, "ForwardResponse", config->GetBoolean(LRQFeaturesSection, "ForwardResponse", true));
PString forwardto(config->GetString(section, "ForwardLRQ", config->GetString(LRQFeaturesSection, "ForwardLRQ", "0")));
if (forwardto *= "never")
m_forwardto = -1;
else if (forwardto *= "always")
m_forwardto = 1;
else
m_forwardto = 0;
}
// class OldGK
bool OldGK::SetProfile(const PString & id, const PString & args)
{
m_authUser = m_id = m_gkid = id;
PStringArray cfg(args.Tokenise(";", true));
m_name = cfg[0].Trim();
m_sendPrefixes.clear();
if (cfg.GetSize() > 1) {
PStringArray p = cfg[1].Tokenise(",", false);
for (PINDEX i = 0; i < p.GetSize(); ++i)
m_sendPrefixes[p[i]] = 1;
} else
m_sendPrefixes["*"] = 1;
m_acceptPrefixes.SetSize(1);
m_acceptPrefixes[0] = "*";
if (cfg.GetSize() > 2)
m_password = cfg[2];
m_dynamic = (cfg.GetSize() > 3) ? Toolkit::AsBool(cfg[3]) : false;
if (!m_dynamic && !GetTransportAddress(m_name, GK_DEF_UNICAST_RAS_PORT, m_ip, m_port))
return false;
SetForwardedInfo(LRQFeaturesSection);
if (Toolkit::AsBool(GkConfig()->GetString(LRQFeaturesSection, "AlwaysForwardLRQ", "0")))
m_forwardto = 1;
PTRACE(1, "Set neighbor " << m_gkid << '(' << (m_dynamic ? m_name : AsString(m_ip, m_port)) << ')' << (cfg.GetSize() > 1 ? (" for prefix " + cfg[1]) : PString::Empty()));
return true;
}
// class GnuGK
bool GnuGK::OnSendingLRQ(H225_LocationRequest & lrq, const AdmissionRequest & request)
{
lrq.IncludeOptionalField(H225_LocationRequest::e_gatekeeperIdentifier);
lrq.m_gatekeeperIdentifier = Toolkit::GKName();
lrq.IncludeOptionalField(H225_LocationRequest::e_nonStandardData);
lrq.m_nonStandardData.m_nonStandardIdentifier.SetTag(H225_NonStandardIdentifier::e_h221NonStandard);
H225_H221NonStandard & t35 = lrq.m_nonStandardData.m_nonStandardIdentifier;
t35.m_t35CountryCode = Toolkit::t35cPoland;
t35.m_manufacturerCode = Toolkit::t35mGnuGk;
t35.m_t35Extension = Toolkit::t35eNeighborId;
lrq.m_nonStandardData.m_data.SetValue(m_id);
const H225_AdmissionRequest & arq = request.GetRequest();
lrq.IncludeOptionalField(H225_LocationRequest::e_sourceInfo);
lrq.m_sourceInfo = arq.m_srcInfo;
if (arq.HasOptionalField(H225_AdmissionRequest::e_canMapAlias)) {
lrq.IncludeOptionalField(H225_LocationRequest::e_canMapAlias);
lrq.m_canMapAlias = arq.m_canMapAlias;
}
// must include callID to traversal servers and clients, no harm to always include it
if (arq.HasOptionalField(H225_AdmissionRequest::e_callIdentifier)) {
lrq.IncludeOptionalField(H225_LocationRequest::e_callIdentifier);
lrq.m_callIdentifier = arq.m_callIdentifier;
}
lrq.IncludeOptionalField(H225_LocationRequest::e_sourceEndpointInfo);
lrq.m_sourceEndpointInfo = arq.m_srcInfo;
if (m_loopDetection) {
CallLoopTable::Instance()->CollectLoopData(lrq, "");
}
#if defined(HAS_TLS) && defined(HAS_H460)
// H.460.22
if (RasServer::Instance()->IsGKRouted()) {
// in routed mode we signal gatekeeper capabilities
if (Toolkit::Instance()->IsTLSEnabled()) {
// include H.460.22 in supported features
H460_FeatureStd h46022 = H460_FeatureStd(22);
H460_FeatureStd settings;
settings.Add(Std22_Priority, H460_FeatureContent(1, 8)); // Priority=1, type=number8
WORD tlsSignalPort = (WORD)GkConfig()->GetInteger(RoutedSec, "TLSCallSignalPort", GK_DEF_TLS_CALL_SIGNAL_PORT);
H225_TransportAddress h225Addr = m_rasSrv->GetRasAddress(GetIP());
SetH225Port(h225Addr, tlsSignalPort);
H323TransportAddress signalAddr = h225Addr;
settings.Add(Std22_ConnectionAddress, H460_FeatureContent(signalAddr));
h46022.Add(Std22_TLS, H460_FeatureContent(settings.GetCurrentTable()));
lrq.IncludeOptionalField(H225_LocationRequest::e_featureSet);