-
Notifications
You must be signed in to change notification settings - Fork 22
/
Toolkit.cxx
4401 lines (3892 loc) · 140 KB
/
Toolkit.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
//////////////////////////////////////////////////////////////////
//
// Toolkit base class for the GnuGk
//
// Copyright (c) 2000-2024, 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/cypher.h>
#include <ptclib/http.h>
#include <ptclib/pstun.h>
#include <h323pdu.h>
#include <map>
#include <vector>
#include <cstdlib>
#if !defined(_WIN32) && !defined(_WIN64)
#include <unistd.h>
#endif // _WIN32
#if (__cplusplus >= 201703L) // C++17
#include <random>
#endif
#include "stl_supp.h"
#include "gktimer.h"
#include "h323util.h"
#include "GkStatus.h"
#include "gkconfig.h"
#if HAS_DATABASE
#include "gksql.h"
#endif
#include "clirw.h"
#include "capctrl.h"
#include "RasSrv.h"
#include "Toolkit.h"
#include "gk_const.h"
#include "SoftPBX.h"
#include "snmp.h"
#include "gk.h"
#ifdef H323_H350
const char * H350Section = "GkH350::Settings";
#include <ptclib/pldap.h>
#include "h350/h350.h"
#endif
#ifdef HAS_LIBCURL
#include <curl/curl.h>
#endif // HAS_LIBCURL
#ifdef HAS_OLM
#include "api/license++.h"
#include "pc-identifiers.h"
#endif
#if (!_WIN32) && (GCC_VERSION >= 40600)
#pragma GCC diagnostic ignored "-Wstrict-overflow"
#endif
using namespace std;
PIPSocket::Address GNUGK_INADDR_ANY(INADDR_ANY);
PReadWriteMutex ConfigReloadMutex;
PSemaphore ShutdownMutex(1, 1);
bool ShutdownFlag = false; // you may only set this flag if you own the ShutdownMutex, once it is set, it can never be cleared!
bool g_disableSettingUDPSourceIP = false;
extern const char *ProxySection;
extern const char *RoutedSec;
extern const char *TLSSec;
extern int g_maxSocketQueue;
bool IsGatekeeperShutdown()
{
return ShutdownFlag;
}
namespace {
const PString paddingByteConfigKey("KeyFilled");
const BYTE AnyRawAddress[16] = {
255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255
};
} /* namespace */
NetworkAddress::NetworkAddress() : m_address(0), m_netmask(0)
{
}
NetworkAddress::NetworkAddress(
const PIPSocket::Address & addr
) : m_address(addr), m_netmask(addr.GetSize(), AnyRawAddress)
{
}
NetworkAddress::NetworkAddress(
const PIPSocket::Address & addr,
const PIPSocket::Address & nm
) : m_netmask(nm)
{
// normalize the address
if (addr.GetSize() == nm.GetSize()) {
BYTE rawdata[16];
const unsigned sz = addr.GetSize();
for (unsigned i = 0; i < sz; i++)
rawdata[i] = addr[i] & nm[i];
m_address = PIPSocket::Address(sz, rawdata);
} else {
PTRACE(1, "Error: Non-matching network and netmask");
}
}
NetworkAddress::NetworkAddress(
const PString & str /// an address in a form A.B.C.D, A.B.C.D/24 or A.B.C.D/255.255.255.0
)
{
Toolkit::GetNetworkFromString(str, m_address, m_netmask);
}
unsigned NetworkAddress::GetNetmaskLen() const
{
unsigned len = 0;
const unsigned sz = m_netmask.GetSize() * 8;
const char *rawdata = m_netmask.GetPointer();
for (int b = sz - 1; b >= 0; b--)
if (rawdata[b >> 3] & (0x80 >> (b & 7)))
break;
else
len++;
return sz - len;
}
bool NetworkAddress::operator==(const NetworkAddress & addr) const
{
if (m_address.GetSize() != addr.m_address.GetSize())
return false;
const unsigned sz = m_address.GetSize();
for (unsigned i = 0; i < sz; i++)
if (m_address[i] != addr.m_address[i] || m_netmask[i] != addr.m_netmask[i])
return false;
return true;
}
bool NetworkAddress::operator==(const PIPSocket::Address & addr) const
{
if (m_address.GetSize() != addr.GetSize())
return false;
const unsigned sz = m_address.GetSize();
for (unsigned i = 0; i < sz; i++)
if (m_netmask[i] != 255 || m_address[i] != addr[i])
return false;
return true;
}
bool NetworkAddress::operator>>(const NetworkAddress & addr) const
{
if (m_address.GetSize() != addr.m_address.GetSize())
return false;
const unsigned sz = m_address.GetSize();
for (unsigned i = 0; i < sz; i++)
if (m_netmask[i] != (addr.m_netmask[i] & m_netmask[i])
|| m_address[i] != (addr.m_address[i] & m_netmask[i]))
return false;
return true;
}
bool NetworkAddress::operator<<(const NetworkAddress & addr) const
{
return addr >> *this;
}
bool NetworkAddress::operator>>(const PIPSocket::Address & addr) const
{
if (m_address.GetSize() != addr.GetSize())
return false;
const unsigned sz = m_address.GetSize();
for (unsigned i = 0; i < sz; i++)
if (m_address[i] != (addr[i] & m_netmask[i]))
return false;
return true;
}
int NetworkAddress::Compare(const NetworkAddress & addr) const
{
int diff = m_address.GetSize() - addr.m_address.GetSize();
if (diff == 0) {
diff = GetNetmaskLen() - addr.GetNetmaskLen();
if (diff == 0) {
const unsigned sz = m_address.GetSize();
for (unsigned i = 0; i < sz; i++) {
diff = m_address[i] - addr.m_address[i];
if (diff != 0)
break;
}
}
}
return diff;
}
PString NetworkAddress::AsString() const
{
return m_address.AsString() + "/" + PString(GetNetmaskLen());
}
bool NetworkAddress::IsAny() const
{
return m_address.IsAny() && (GetNetmaskLen() == 0);
}
bool NetworkAddress::operator<(const NetworkAddress & addr) const
{
return Compare(addr) < 0;
}
bool NetworkAddress::operator<=(const NetworkAddress & addr) const
{
return Compare(addr) <= 0;
}
bool NetworkAddress::operator>(const NetworkAddress & addr) const
{
return Compare(addr) > 0;
}
bool NetworkAddress::operator>=(const NetworkAddress & addr) const
{
return Compare(addr) >= 0;
}
bool operator==(const PIPSocket::Address & addr, const NetworkAddress & net)
{
return net == addr;
}
bool operator<<(const PIPSocket::Address & addr, const NetworkAddress & net)
{
return net >> addr;
}
// class Toolkit::RouteTable::RouteEntry
Toolkit::RouteTable::RouteEntry::RouteEntry(const PString & net) : PIPSocket::RouteEntry(0)
{
if (net.Find('-') != P_MAX_INDEX) {
// format: net/mask-dest eg. 10.0.0.0/8-20.1.1.1
destination = net.Tokenise("-", FALSE)[1];
GetNetworkFromString(net.Tokenise("-", FALSE)[0], network, net_mask);
} else {
// format: net/mask-dest eg. 10.1.1.1/8
destination = net.Tokenise("/", FALSE)[0];
GetNetworkFromString(net, network, net_mask);
}
}
Toolkit::RouteTable::RouteEntry::RouteEntry(
const PIPSocket::RouteEntry & re,
const InterfaceTable & it
) : PIPSocket::RouteEntry(re)
{
// look at the interface table which local IP to use for this route entry
PINDEX i;
// try to select outgoing IP from network - check if IP is valid with netmask
for (i = 0; i < it.GetSize(); ++i) {
const Address & ip = it[i].GetAddress();
if (Toolkit::Instance()->IsGKHome(ip) && CompareWithMask(&ip)) {
destination = ip;
return;
}
}
for (i = 0; i < it.GetSize(); ++i) {
const Address & ip = it[i].GetAddress();
if (Toolkit::Instance()->IsGKHome(ip) && CompareWithoutMask(&ip)) { // skip IPs we don't listen to
destination = ip;
return;
}
}
for (i = 0; i < it.GetSize(); ++i) {
if ((it[i].GetName() == interfaceName) && Toolkit::Instance()->IsGKHome(it[i].GetAddress())) {
destination = it[i].GetAddress();
return;
}
}
}
inline bool Toolkit::RouteTable::RouteEntry::CompareWithoutMask(const Address *ip) const
{
return (*ip == destination) || (((*ip & net_mask) == network) && (ip->GetVersion() == network.GetVersion()));
}
bool Toolkit::RouteTable::RouteEntry::CompareWithMask(const Address *ip) const
{
if (ip->GetVersion() != network.GetVersion())
return false;
#if P_HAS_IPV6
PINDEX mmax = ip->GetVersion() == 6 ? 16 : 4;
#else
PINDEX mmax = 4;
#endif
bool maskValid = true;
bool networkStarted = false; // this is a non-zero network byte
for (PINDEX m = mmax - 1; m >= 0 ; --m) {
BYTE ipByte = (*ip)[m];
BYTE maskByte = net_mask[m];
if (maskByte == 0) {
if (networkStarted && (ipByte > 0)){
return false;
}
// mask non-zero bits not reached yet
continue;
}
networkStarted = true;
BYTE match = (unsigned char)ipByte & (unsigned char)maskByte;
if ((unsigned char)match != (unsigned char)network[m]){
maskValid = false;
break;
}
}
return (maskValid);
}
// class Toolkit::RouteTable
void Toolkit::RouteTable::InitTable()
{
// workaround for OS that don't support GetRouteTable
PIPSocket::GetHostAddress(defAddr);
#ifdef hasIPV6
PIPSocket::GetHostAddress(defAddrV6);
#endif
ClearTable();
if (!CreateTable())
return;
// get Home IPs (all detected IPs or set through config file)
std::vector<PIPSocket::Address> home;
Toolkit::Instance()->GetGKHome(home);
// if we only have 1 Home IP, then thats also the default IP
if (home.size() == 1) {
defAddr = home[0];
#ifdef hasIPV6
defAddrV6 = home[0];
#endif
}
// Bind= always sets the default IP
PString bind = GkConfig()->GetString("Bind", "");
if (!bind.IsEmpty()) {
defAddr = bind;
#ifdef hasIPV6
defAddrV6 = bind;
#endif
}
// if we do not already have a valid entry, try and retrieve the default interface
if ((defAddr.GetVersion() != 4) || defAddr.IsLoopback() || !defAddr.IsValid()) {
// Set default IP according to route table
defAddr = GetDefaultIP(4);
if ((defAddr.GetVersion() != 4) || defAddr.IsLoopback() || !defAddr.IsValid()) {
// no default gateway, use first interface as default
PIPSocket::GetNetworkInterface(defAddr);
}
}
#ifdef hasIPV6
// if we do not already have a valid entry, try and retrieve the default interface
if ((defAddrV6.GetVersion() != 6) || defAddrV6.IsLoopback() || !defAddrV6.IsValid()) {
// Set default IP according to route table
defAddrV6 = GetDefaultIP(6);
if ((defAddrV6.GetVersion() != 6) || defAddrV6.IsLoopback() || !defAddrV6.IsValid()) {
// no default gateway, use first interface as default
PIPSocket::GetNetworkInterface(defAddrV6);
}
}
#endif
// if we have a list of Home IPs and the default address is not in it, use the first IPv4 Home IP,
// unless the default IP was explicitly specified in Bind=
if (bind.IsEmpty() &&
!home.empty() && (find(home.begin(), home.end(), defAddr) == home.end())) {
for (unsigned i = 0; i < home.size(); ++i) {
if (home[i].GetVersion() == 4) {
defAddr = home[i];
break;
}
}
}
#ifdef hasIPV6
if (bind.IsEmpty() &&
!home.empty() && (find(home.begin(), home.end(), defAddrV6) == home.end())) {
for (unsigned i = 0; i < home.size(); ++i) {
if (home[i].GetVersion() == 6) {
defAddrV6 = home[i];
break;
}
}
}
#endif
for (RouteEntry *entry = rtable_begin; entry != rtable_end; ++entry) {
PTRACE(2, "Network=" << NetworkAddress(entry->GetNetwork(), entry->GetNetMask()).AsString() <<
", IP=" << entry->GetDestination());
}
#ifdef hasIPV6
if (Toolkit::Instance()->IsIPv6Enabled())
PTRACE(2, "Default IP IPv4=" << defAddr << " IPv6=" << defAddrV6);
else
#endif
{
PTRACE(2, "Default IP=" << defAddr);
}
if (defAddr.IsLoopback()) {
PTRACE(1, "WARNING: Your default IP=" << defAddr << " is a loopback address. That probably won't work!");
}
}
// get default route from route table, because GetGatewayAddress() is broken until PTLib 2.11.1
PIPSocket::Address Toolkit::RouteTable::GetDefaultIP(unsigned version) const
{
for (RouteEntry *entry = rtable_begin; entry != rtable_end; ++entry) {
if ((entry->GetNetMask() == 0) && (entry->GetDestination().GetVersion() == version))
return GetLocalAddress(entry->GetDestination());
}
return Address(0);
}
void Toolkit::RouteTable::ClearTable()
{
if (rtable_begin) {
for (RouteEntry *r = rtable_begin; r != rtable_end; ++r)
r->~RouteEntry();
::free(rtable_begin);
rtable_begin = 0;
}
}
void Toolkit::RouteTable::ClearInternalNetworks()
{
m_internalnetworks.clear();
}
void Toolkit::RouteTable::AddInternalNetwork(const NetworkAddress & network)
{
if (find(m_internalnetworks.begin(), m_internalnetworks.end(), network) == m_internalnetworks.end())
m_internalnetworks.push_back(network);
}
PIPSocket::Address Toolkit::RouteTable::GetLocalAddress(unsigned version) const
{
#ifdef hasIPV6
if (version == 6)
return defAddrV6;
#endif
return defAddr;
}
PIPSocket::Address Toolkit::RouteTable::GetLocalAddress(const Address & addr) const
{
// look through internal networks and make sure we don't return the external IP for them
for (unsigned j = 0; j < m_internalnetworks.size(); ++j) {
if (addr << m_internalnetworks[j]) {
// check if internal network is in route table, but don't use the default route
RouteEntry *entry = find_if(rtable_begin, rtable_end,
#if (__cplusplus >= 201703L) // C++17
bind(mem_fn(&RouteEntry::CompareWithoutMask), std::placeholders::_1, &addr));
#else
bind2nd(mem_fun_ref(&RouteEntry::CompareWithoutMask), &addr));
#endif
if ((entry != rtable_end) && (entry->GetNetMask() != INADDR_ANY)
#ifdef hasIPV6
&& (entry->GetNetMask() != in6addr_any)
#endif
) {
return entry->GetDestination();
}
else {
#ifdef hasIPV6
if (addr.GetVersion() == 6)
return defAddrV6;
#endif
return defAddr;
}
}
}
// if external IP is configured
if (!ExtIP.IsEmpty()) {
if (DynExtIP) { // if dynamic resolve DNS entry
PIPSocket::Address extip;
H323TransportAddress ex = H323TransportAddress(ExtIP);
ex.GetIpAddress(extip);
if (extip.IsValid()) {
return extip;
} else {
PTRACE(2, "NAT\tERROR: External IP " << ExtIP << " unresolvable." );
SNMP_TRAP(10, SNMPError, Configuration, "External IP " + ExtIP + " unresolvable");
}
} else { // If valid IP then use the ExtIP value
PIPSocket::Address extip(ExtIP);
if (extip.IsValid()) {
return extip;
} else {
PTRACE(2, "NAT\tERROR: ExtIP " << ExtIP << " unusable." );
SNMP_TRAP(10, SNMPError, Configuration, "External IP " + ExtIP + " unusable");
}
}
}
RouteEntry *entry = find_if(rtable_begin, rtable_end,
#if (__cplusplus >= 201703L) // C++17
bind(mem_fn(&RouteEntry::CompareWithMask), std::placeholders::_1, &addr));
#else
bind2nd(mem_fun_ref(&RouteEntry::CompareWithMask), &addr));
#endif
if (entry != rtable_end) {
return entry->GetDestination();
}
#ifdef hasIPV6
if (addr.GetVersion() == 6) {
return defAddrV6;
}
#endif
return defAddr;
}
bool Toolkit::RouteTable::CreateRouteTable(const PString & extroute)
{
InterfaceTable if_table;
if (!PIPSocket::GetInterfaceTable(if_table)) {
PTRACE(1, "Error: Can't get interface table");
SNMP_TRAP(10, SNMPError, Configuration, "Error fetching interface table");
return false;
}
PTRACE(4, "InterfaceTable:\n" << setfill('\n') << if_table << setfill(' '));
PIPSocket::RouteTable r_table;
if (!PIPSocket::GetRouteTable(r_table)) {
PTRACE(1, "Error: Can't get route table");
SNMP_TRAP(10, SNMPError, Configuration, "Error fetching route table");
return false;
}
// filter out route with destination localhost
// we can't use those for routing calls, unless the net itself is localhost
for(PINDEX i = 0; i < r_table.GetSize(); ++i) {
if ((r_table[i].GetDestination().IsLoopback())
&& !r_table[i].GetNetwork().IsLoopback()) {
r_table.RemoveAt(i--);
}
}
// filter out IPv6 networks if IPv6 is not enabled
for(PINDEX i = 0; i < r_table.GetSize(); ++i) {
if ((r_table[i].GetNetwork().GetVersion() == 6)
&& !Toolkit::Instance()->IsIPv6Enabled()) {
r_table.RemoveAt(i--);
}
}
if (AsBool(GkConfig()->GetString(ProxySection, "Enable", "0"))) {
for (PINDEX i = 0; i < r_table.GetSize(); ++i) {
if (IsPrivate(r_table[i].GetNetwork())
&& (r_table[i].GetNetMask().AsString() != "255.255.255.255")
&& (r_table[i].GetNetMask().AsString() != "ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff")) {
m_internalnetworks.resize( m_internalnetworks.size() + 1);
m_internalnetworks[m_internalnetworks.size() - 1] = NetworkAddress(r_table[i].GetNetwork(), r_table[i].GetNetMask());
PTRACE(2, "Internal Network Detected " << m_internalnetworks.back().AsString());
}
}
}
PString tmpRoutes = GkConfig()->GetString(ProxySection, "ExplicitRoutes", "");
PStringArray explicitRoutes;
if (!tmpRoutes.IsEmpty()) {
explicitRoutes = tmpRoutes.Tokenise(",", false);
PString defaultRoute;
PINDEX e = 0;
while (e < explicitRoutes.GetSize()) {
PString explicitRoute = explicitRoutes[e].Trim();
if (explicitRoute.Left(9) == "0.0.0.0/0" || PCaselessString(explicitRoute.Left(7)) == "default") {
explicitRoutes.RemoveAt(e);
defaultRoute = explicitRoute;
} else {
RouteEntry entry(explicitRoute);
if (Toolkit::Instance()->IsGKHome(entry.GetDestination())) {
PTRACE(2, "Adding explicit route: " << entry.GetNetwork() << "/" << entry.GetNetMask() << "->" << entry.GetDestination());
e++;
} else {
PTRACE(1, "Ignoring explicit route (invalid source IP): "
<< entry.GetNetwork() << "/" << entry.GetNetMask() << "->" << entry.GetDestination());
explicitRoutes.RemoveAt(e);
}
}
}
if (!defaultRoute.IsEmpty()) {
// replace 0.0.0.0/0 or "default" with 2 routes (0.0.0.0/1 + 128.0.0.0/1), because "0.0.0.0/0" is also treated as invalid network
if (PCaselessString(defaultRoute.Left(7)) == "default") {
defaultRoute = PString("0.0.0.0/0") + defaultRoute.Mid(7);
}
defaultRoute.Replace("0.0.0.0/0", "0.0.0.0/1"); // 1st part
// check if source is a Home= IP
RouteEntry entry(defaultRoute);
if (Toolkit::Instance()->IsGKHome(entry.GetDestination())) {
explicitRoutes.AppendString(defaultRoute);
defaultRoute.Replace("0.0.0.0/1", "128.0.0.0/1"); // 2nd part
explicitRoutes.AppendString(defaultRoute);
} else {
PTRACE(1, "Ignoring explicit default route: Invalid source IP " << entry.GetDestination());
}
}
}
int i = (!extroute) ? r_table.GetSize()+1 : r_table.GetSize();
i += explicitRoutes.GetSize();
rtable_end = rtable_begin = static_cast<RouteEntry *>(::malloc(i * sizeof(RouteEntry)));
// prepend explicit routes
for (PINDEX e = 0; e < explicitRoutes.GetSize(); ++e) {
::new (rtable_end++) RouteEntry(explicitRoutes[e]);
}
for (PINDEX r = 0; r < (i - explicitRoutes.GetSize()); ++r) {
if (!extroute && (r==r_table.GetSize())) {
::new (rtable_end++) RouteEntry(extroute);
} else {
PIPSocket::RouteEntry & r_entry = r_table[r];
if (!r_entry.GetNetMask().IsAny()) {
::new (rtable_end++) RouteEntry(r_entry, if_table);
}
}
}
return true;
}
bool Toolkit::VirtualRouteTable::CreateTable()
{
PString nets = GkConfig()->GetString("NetworkInterfaces", "");
if (!nets) {
PStringArray networks(nets.Tokenise(" ,;\t", FALSE));
int i = networks.GetSize();
if (i > 0) {
rtable_end = rtable_begin = static_cast<RouteEntry *>(::malloc(i * sizeof(RouteEntry)));
for (PINDEX r = 0; r < i; ++r) {
::new (rtable_end++) RouteEntry(networks[r]);
}
}
}
// If we have an external IP setting then load the detected Route Table and add a route for the external IP
// If dynamic IP then only store the PString value and resolve the DNS when required.
PString extip = Toolkit::Instance()->GetExternalIP();
if (!extip.IsEmpty()) {
DynExtIP = AsBool(GkConfig()->GetString("ExternalIsDynamic", "0"));
PIPSocket::Address ext((DWORD)0);
H323TransportAddress ex = H323TransportAddress(extip);
ex.GetIpAddress(ext);
if (ext.IsValid()) {
ExtIP = extip;
PString extroute;
if (!DynExtIP)
extroute = ext.AsString() + "/0";
CreateRouteTable(extroute);
PTRACE(1, "External IP=" << ExtIP << " dynamic=" << DynExtIP);
return true;
} else
DynExtIP = false;
}
return false;
}
bool Toolkit::VirtualRouteTable::IsMasquerade(PIPSocket::Address & addr) const
{
if (!ExtIP) {
H323TransportAddress ex = H323TransportAddress(ExtIP);
ex.GetIpAddress(addr);
return true;
}
return false;
}
// class Toolkit::ProxyCriterion
Toolkit::ProxyCriterion::ProxyCriterion() : m_enable(false)
{
}
Toolkit::ProxyCriterion::~ProxyCriterion()
{
}
void Toolkit::ProxyCriterion::LoadConfig(PConfig *config)
{
// read switch for default proxy mode
m_enable = AsBool(config->GetString(ProxySection, "Enable", "0"));
if (!m_enable) {
PTRACE(2, "GK\tH.323 Proxy not enabled by default");
} else {
PTRACE(2, "GK\tH.323 Proxy enabled");
}
m_internalnetworks.clear();
m_modeselection.clear();
PStringArray networks(config->GetString(ProxySection, "InternalNetwork", "").Tokenise(" ,;\t", FALSE));
// if no networks specified then use the detected values
int signalRoutingMode = CallRec::Undefined;
if (RasServer::Instance()->IsGKRouted()) {
if (RasServer::Instance()->IsH245Routed()) {
signalRoutingMode = CallRec::H245Routed;
} else {
signalRoutingMode = CallRec::SignalRouted;
}
}
NetworkModes internal_netmode;
internal_netmode.fromExternal = m_enable ? CallRec::Proxied : signalRoutingMode;
internal_netmode.insideNetwork = signalRoutingMode;
if (networks.GetSize() == 0) {
m_internalnetworks = Toolkit::Instance()->GetInternalNetworks();
for (unsigned j = 0; j < m_internalnetworks.size(); ++j) {
m_modeselection[m_internalnetworks[j]] = internal_netmode;
PTRACE(2, "GK\tInternal Network " << j << " = " << m_internalnetworks[j].AsString()
<< " (" << internal_netmode.fromExternal << "," << internal_netmode.insideNetwork << ")");
}
} else {
m_internalnetworks.clear();
Toolkit::Instance()->GetRouteTable()->ClearInternalNetworks();
for (PINDEX i = 0; i < networks.GetSize(); ++i) {
m_internalnetworks.push_back(networks[i]);
Toolkit::Instance()->GetRouteTable()->AddInternalNetwork(networks[i]);
m_modeselection[networks[i]] = internal_netmode;
PTRACE(2, "GK\tINI Internal Network " << i << " = " << m_internalnetworks[i].AsString()
<< " (" << internal_netmode.fromExternal << "," << internal_netmode.insideNetwork << ")");
}
}
// read [ModeSelection] section
PStringToString mode_rules(config->GetAllKeyValues("ModeSelection"));
if (mode_rules.GetSize() > 0) {
// if we have ModeSelection rules, only use those, don't try to merge them with detected
m_modeselection.clear();
}
for (PINDEX i = 0; i < mode_rules.GetSize(); ++i) {
PString network = mode_rules.GetKeyAt(i);
if (!network.IsEmpty()) {
PStringArray modes((mode_rules.GetDataAt(i)).Tokenise(" ,;\t", FALSE));
if (modes.GetSize() >= 1 && modes.GetSize() <= 2) {
NetworkAddress addr = NetworkAddress(network);
NetworkModes netmode;
netmode.fromExternal = ToRoutingMode(modes[0].Trim());
netmode.insideNetwork = netmode.fromExternal;
if (modes.GetSize() == 2)
netmode.insideNetwork = ToRoutingMode(modes[1].Trim());
// replace 0.0.0.0/0 with 2 rules (0.0.0.0/1 + 128.0.0.0/1), because 0.0.0.0/0 is also treated as invalid network
if (network == "0.0.0.0/0" || network == PCaselessString("default")) {
m_modeselection[NetworkAddress("0.0.0.0/1")] = netmode;
PTRACE(2, "GK\tModeSelection rule: 0.0.0.0/1=" << netmode.fromExternal << "," << netmode.insideNetwork);
m_modeselection[NetworkAddress("128.0.0.0/1")] = netmode;
PTRACE(2, "GK\tModeSelection rule: 128.0.0.0/1=" << netmode.fromExternal << "," << netmode.insideNetwork);
} else {
m_modeselection[addr] = netmode;
PTRACE(2, "GK\tModeSelection rule: " << addr.AsString() << "=" << netmode.fromExternal << "," << netmode.insideNetwork);
}
} else {
PTRACE(1, "GK\tInvalid ModeSelection rule: " << mode_rules.GetKeyAt(i) << "=" << mode_rules.GetDataAt(i) );
}
}
}
}
int Toolkit::ProxyCriterion::ToRoutingMode(const PCaselessString & mode) const
{
if (mode == "Routed")
return CallRec::SignalRouted;
else if (mode == "H245Routed")
return CallRec::H245Routed;
else if (mode == "Proxy")
return CallRec::Proxied;
else
return CallRec::Undefined;
}
// returns network for the rule or IsAny() when no is rule found
NetworkAddress Toolkit::ProxyCriterion::FindModeRule(const NetworkAddress & ip) const
{
NetworkAddress bestmatch;
std::map<NetworkAddress, NetworkModes>::const_iterator iter = m_modeselection.begin();
while (iter != m_modeselection.end()) {
if ((ip << iter->first) && (iter->first.GetNetmaskLen() >= bestmatch.GetNetmaskLen())) {
bestmatch = iter->first;
}
++iter;
}
return bestmatch;
}
int Toolkit::ProxyCriterion::SelectRoutingMode(const Address & ip1, const Address & ip2) const
{
// default mode
int mode = m_enable ? CallRec::Proxied : CallRec::SignalRouted;
if (mode == CallRec::SignalRouted && RasServer::Instance()->IsH245Routed())
mode = CallRec::H245Routed;
PTRACE(5, "ModeSelection for " << ip1.AsString() << " -> " << ip2.AsString() << " default=" << mode);
// check if we have a more specific setting
NetworkAddress bestMatchIP1 = FindModeRule(ip1);
NetworkAddress bestMatchIP2 = FindModeRule(ip2);
std::map<NetworkAddress, NetworkModes>::const_iterator iter;
// check for same network
if (!bestMatchIP1.IsAny() && !bestMatchIP2.IsAny()) {
// rules for both IPs
if (bestMatchIP1.Compare(bestMatchIP2) == 0) {
// both on same network
iter = m_modeselection.find(bestMatchIP1);
if (iter != m_modeselection.end()) {
mode = iter->second.insideNetwork;
PTRACE(5, "ModeSelection: Both IPs on same network: mode=" << mode);
}
} else {
// on different networks, use maximum proxying
iter = m_modeselection.find(bestMatchIP1);
if (iter != m_modeselection.end()) { // must exist
int mode1 = iter->second.fromExternal;
iter = m_modeselection.find(bestMatchIP2);
if (iter != m_modeselection.end()) { // must exist
int mode2 = iter->second.fromExternal;
mode = max(mode1, mode2);
PTRACE(5, "ModeSelection: Both IPs on different networks: mode1=" << mode1 << " mode2=" << mode2 << " => " << mode);
}
}
}
} else {
// only one rule, use that
if (!bestMatchIP1.IsAny()) {
iter = m_modeselection.find(bestMatchIP1);
if (iter != m_modeselection.end()) {
mode = iter->second.fromExternal;
PTRACE(5, "ModeSelection: Only rule for IP 1 = " << ip1.AsString() << " mode=" << mode);
}
}
if (!bestMatchIP2.IsAny()) {
iter = m_modeselection.find(bestMatchIP2);
if (iter != m_modeselection.end()) {
mode = iter->second.fromExternal;
PTRACE(5, "ModeSelection: Only rule for IP 2 = " << ip2.AsString() << " mode=" << mode);
}
}
}
return mode;
}
int Toolkit::ProxyCriterion::IsInternal(const Address & ip) const
{
// Return the network Id. Addresses may be on different internal networks
int retval = 0;
std::vector<NetworkAddress>::const_iterator i = m_internalnetworks.begin();
while (i != m_internalnetworks.end()) {
retval++;
if (ip << *i++)
return retval;
}
return 0;
}
// class Toolkit::RewriteTool
static const char *RewriteSection = "RasSrv::RewriteE164";
static const char *AliasRewriteSection = "RasSrv::RewriteAlias";
static const char *AssignedAliasSection = "RasSrv::AssignedAlias";
#ifdef h323v6
static const char *AssignedGatekeeperSection = "RasSrv::AssignedGatekeeper";
#endif
static const char *ModeVendorSection = "ModeVendorSelection";
void Toolkit::RewriteData::AddSection(PConfig * config, const PString & section)
{
PStringToString cfgs(config->GetAllKeyValues(section));
PINDEX n_size = cfgs.GetSize();
if (n_size > 0) {
std::map<PString, PString, pstr_prefix_lesser> rules;
for (PINDEX i = 0; i < n_size; ++i) {
PString key = cfgs.GetKeyAt(i);
PCaselessString first = PCaselessString(key[0]);
if (!key && (isdigit(static_cast<unsigned char>(key[0])) || (first.FindOneOf("+!.%*#ABCDEFGHIGKLMNOPQRSTUVWXYZ") != P_MAX_INDEX)))
rules[key] = cfgs.GetDataAt(i);
}
// now the rules are ascendantly sorted by the keys
if ((n_size = rules.size()) > 0) {
// add any existing rules to be resorted
if (m_size > 0) {
for (PINDEX j = 0; j < m_size; ++j) {
rules[Key(j)] = Value(j);
}
}
m_size = m_size + n_size;
// replace array constructor with explicit memory allocation
// and in-place new operators - workaround for VC compiler
m_RewriteKey = (PString*)(new BYTE[sizeof(PString) * m_size * 2]);
m_RewriteValue = m_RewriteKey + m_size;
std::map<PString, PString, pstr_prefix_lesser>::iterator iter = rules.begin();
// reverse the order
for (int i = m_size; i-- > 0; ++iter) {
::new(m_RewriteKey + i) PString(iter->first);
::new(m_RewriteValue + i) PString(iter->second);
}
}
}
}
Toolkit::RewriteData::RewriteData(PConfig *config, const PString & section)
{
m_RewriteKey = NULL;
m_RewriteValue = NULL;
m_size = 0;
AddSection(config, section);
}
Toolkit::RewriteData::~RewriteData()
{
if (m_RewriteKey) {
for (int i = 0; i < m_size * 2; i++) {
(m_RewriteKey+i)->~PString();
}
}
delete[] ((BYTE*)m_RewriteKey);
}
void Toolkit::RewriteTool::LoadConfig(PConfig *config)
{
m_RewriteFastmatch = config->GetString(RewriteSection, "Fastmatch", "");
m_TrailingChar = config->GetString("RasSrv::ARQFeatures", "RemoveTrailingChar", " ")[0];
PString defDomain = config->GetString("Gatekeeper::Main", "DefaultDomain", "");
m_defaultDomain = defDomain.Tokenise(",");
m_externalIP = config->GetString("Gatekeeper::Main", "ExternalIP", "");
delete m_Rewrite;
m_Rewrite = new RewriteData(config, RewriteSection);
m_Rewrite->AddSection(config,AliasRewriteSection);
}
bool Toolkit::RewriteTool::RewritePString(PString & s) const
{
bool changed = false;
// remove trailing character TODO: loop and replace multiple chars ?
if (s.GetLength() > 1 && s[s.GetLength() - 1] == m_TrailingChar) {
s = s.Left(s.GetLength() - 1);
changed = true;
}
// if URL remove the domain if default domain
PINDEX at = s.Find('@');
if (at != P_MAX_INDEX) {
PString num = s.Left(at);
if (num.Left(5) *= "h323:") num = num.Mid(5);
PString domain = s.Mid(at+1);
PIPSocket::Address domIP(domain);
// Check if we have a default domain and strip it
for (PINDEX i = 0; i < m_defaultDomain.GetSize(); i++) {
if (domain == m_defaultDomain[i]) {
PTRACE(2, "\tRewriteDomain (default domain): " << s << " to " << num);
s = num;
changed = true;
break;
}
}
// Check that the domain is not a local IP address.
if (!changed && domIP.IsValid() && Toolkit::Instance()->IsGKHome(domIP)) {
PTRACE(2, "\tRemoveDomain (local IP): " << domain << " to " << num);
s = num;
changed = true;
}
if (!changed && domIP.IsValid() && !m_externalIP.IsEmpty() && domIP.AsString() == m_externalIP) {
PTRACE(2, "\tRemoveDomain (external IP): " << domain << " to " << num);
s = num;
changed = true;