forked from jamulussoftware/jamulus
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserverlist.cpp
More file actions
1035 lines (868 loc) · 38.1 KB
/
Copy pathserverlist.cpp
File metadata and controls
1035 lines (868 loc) · 38.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/******************************************************************************\
* Copyright (c) 2004-2026
*
* Author(s):
* Volker Fischer
*
******************************************************************************
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software
* Foundation; either version 2 of the License, or (at your option) any later
* version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
*
\******************************************************************************/
#include "serverlist.h"
/* *\
--port sets the port the server listens to locally
--serverbindip sets the IP the server listens to locally
--serverpublicip sets the public IP where server and directory are on the same LAN
Manual port forwarding is not supported: the internal port must be open to external requests.
Where a router modem does automatic port forwarding, directory pings MAY open the server to requests
from clients not on the same LAN as the directory.
*
PROTMESSID_CLM_SERVER_LIST
- SERVER internal to DIRECTORY (list entry external IP same LAN)
- CLIENT internal to DIRECTORY (CLM msg same LAN): use "external" fields (local LAN address)
- CLIENT external to DIRECTORY (CLM msg not same LAN): use "internal" fields (registered server public IP)
- SERVER external to DIRECTORY (list entry external IP not same LAN)
- CLIENT internal to SERVER (CLM same IP as list entry external IP): use "internal" fields (local LAN address)
- CLIENT external to SERVER (CLM not same IP as list entry external IP): use "external" fields (public IP address from protocol)
---
*
PROTMESSID_CLM_REGISTER_SERVER
- As SERVER create CLM message using "internal" fields (IP layer is the "external" fields):
- DIRECTORY not on my LAN: self-determined IP address and --port value
- DIRECTORY on my LAN: --serverpublicip IP address and --port value
- As DIRECTORY store received CLM message as is (IP layer address is used to access the server list)
*
\* */
/* Implementation *************************************************************/
// --- CServerListEntry ---
CServerListEntry CServerListEntry::parse ( QString strHAddr,
QString strLHAddr,
QString sName,
QString sCity,
QString strCountry,
QString strNumClients,
bool isPermanent,
bool bEnableIPv6 )
{
CHostAddress haServerHostAddr;
NetworkUtil::ParseNetworkAddress ( strHAddr, haServerHostAddr, bEnableIPv6 );
if ( CHostAddress() == haServerHostAddr )
{
// do not proceed without server host address!
return CServerListEntry();
}
CHostAddress haServerLocalAddr;
NetworkUtil::ParseNetworkAddress ( strLHAddr, haServerLocalAddr, bEnableIPv6 );
if ( haServerLocalAddr.iPort == 0 )
{
haServerLocalAddr.iPort = haServerHostAddr.iPort;
}
// Capture parsing success of integers
bool ok;
QLocale::Country lcCountry = QLocale::AnyCountry;
int iCountry = strCountry.trimmed().toInt ( &ok );
if ( ok && iCountry >= 0 && iCountry <= QLocale::LastCountry )
{
lcCountry = static_cast<QLocale::Country> ( iCountry );
}
int iNumClients = strNumClients.trimmed().toInt ( &ok );
if ( !ok )
{
iNumClients = 10;
}
return CServerListEntry ( haServerHostAddr,
haServerLocalAddr,
CServerCoreInfo ( FromBase64ToString ( sName.trimmed() ).left ( MAX_LEN_SERVER_NAME ),
lcCountry,
FromBase64ToString ( sCity.trimmed() ).left ( MAX_LEN_SERVER_CITY ),
iNumClients,
isPermanent ) );
}
QString CServerListEntry::toCSV()
{
QStringList sl;
sl.append ( this->HostAddr.toString() );
sl.append ( this->LHostAddr.toString() );
sl.append ( ToBase64 ( this->strName ) );
sl.append ( ToBase64 ( this->strCity ) );
sl.append ( QString::number ( this->eCountry ) );
sl.append ( QString::number ( this->iMaxNumClients ) );
sl.append ( QString::number ( this->bPermanentOnline ) );
return sl.join ( ";" );
}
// --- CServerListManager ---
CServerListManager::CServerListManager ( const quint16 iNPortNum,
const QString& sNDirectoryAddress,
const QString& strServerListFileName,
const QString& strServerInfo,
const QString& strServerListFilter,
const QString& strServerPublicIP,
const int iNumChannels,
const bool bNEnableIPv6,
CProtocol* pNConLProt ) :
DirectoryType ( AT_NONE ),
bEnableIPv6 ( bNEnableIPv6 ),
ServerListFileName ( strServerListFileName ),
strDirectoryAddress ( "" ),
bIsDirectory ( false ),
eSvrRegStatus ( SRS_NOT_REGISTERED ),
strMinServerVersion ( "" ), // disable version check with empty version
pConnLessProtocol ( pNConLProt ),
iSvrRegRetries ( 0 )
{
CHostAddress haServerAddr ( NetworkUtil::GetLocalAddress().InetAddr, iNPortNum );
// set the server internal address, including internal port number
QHostAddress qhaServerPublicIP;
if ( strServerPublicIP == "" )
{
// No user-supplied override via --serverpublicip -> use auto-detection
qhaServerPublicIP = haServerAddr.InetAddr;
}
else
{
// User-supplied --serverpublicip
qhaServerPublicIP = QHostAddress ( strServerPublicIP );
}
qDebug() << "Using" << qhaServerPublicIP.toString() << "as external IP.";
ServerPublicIP = CHostAddress ( qhaServerPublicIP, iNPortNum );
if ( bEnableIPv6 )
{
// set the server internal address, including internal port number
QHostAddress qhaServerPublicIP6;
qhaServerPublicIP6 = NetworkUtil::GetLocalAddress6().InetAddr;
qDebug() << "Using" << qhaServerPublicIP6.toString() << "as external IPv6.";
ServerPublicIP6 = CHostAddress ( qhaServerPublicIP6, iNPortNum );
}
// prepare the server info information
QStringList slServInfoSeparateParams;
int iServInfoNumSplitItems = 0;
if ( !strServerInfo.isEmpty() )
{
// split the different parameter strings
slServInfoSeparateParams = strServerInfo.split ( ";" );
// get the number of items in the split list
iServInfoNumSplitItems = slServInfoSeparateParams.count();
}
/*
* Init server list entry (server info for this server) with defaults.
*
* The values supplied here only apply when using the server as a server, not as a directory.
* Note that the client will use the directory address (i.e. the address the server list was returned from)
* when connecting to a directory as a server.
*
* If we are a directory, we assume that we are a permanent server.
*/
CServerListEntry ThisServerListEntry ( haServerAddr, ServerPublicIP, "", QLocale::system().country(), "", iNumChannels, bIsDirectory );
// parse the server info string according to definition:
// [this server name];[this server city];[this server country as QLocale ID] (; ... ignored)
// per definition, we expect at least three parameters
if ( iServInfoNumSplitItems >= 3 )
{
// [this server name]
ThisServerListEntry.strName = slServInfoSeparateParams[0].left ( MAX_LEN_SERVER_NAME );
// [this server city]
ThisServerListEntry.strCity = slServInfoSeparateParams[1].left ( MAX_LEN_SERVER_CITY );
// [this server country as QLocale ID]
bool ok;
const int iCountry = slServInfoSeparateParams[2].toInt ( &ok );
if ( ok )
{
if ( iCountry >= 0 && CLocale::IsCountryCodeSupported ( iCountry ) )
{
// Convert from externally-supplied format ("wire format", Qt5 codes) to
// native format. On Qt5 builds, this is a noop, on Qt6 builds, a conversion
// takes place.
// We try to do such conversions at the outer-most interface which is capable of doing it.
// Although the value comes from src/main -> src/server, this very place is
// the first where we have access to the parsed country code:
ThisServerListEntry.eCountry = CLocale::WireFormatCountryCodeToQtCountry ( iCountry );
}
}
else
{
QLocale::Country qlCountry = CLocale::GetCountryCodeByTwoLetterCode ( slServInfoSeparateParams[2] );
if ( qlCountry != QLocale::AnyCountry )
{
ThisServerListEntry.eCountry = qlCountry;
}
}
qInfo() << qUtf8Printable ( QString ( "Using server info: name = \"%1\", city = \"%2\", country/region = \"%3\" (%4)" )
.arg ( ThisServerListEntry.strName )
.arg ( ThisServerListEntry.strCity )
.arg ( slServInfoSeparateParams[2] )
.arg ( QLocale::countryToString ( ThisServerListEntry.eCountry ) ) );
}
// per definition, the very first entry is this server and this entry will
// never be deleted
ServerList.clear();
// per definition, the first entry in the server list is the own server
ServerList.append ( ThisServerListEntry );
// set the directory address - not the type, that gets done by app start up
SetDirectoryAddress ( sNDirectoryAddress );
// whitelist parsing - only used when bIsDirectory
if ( !strServerListFilter.isEmpty() )
{
// split the different parameter strings
QStringList slWhitelistAddresses = strServerListFilter.split ( ";" );
QHostAddress CurWhiteListAddress;
for ( int iIdx = 0; iIdx < slWhitelistAddresses.size(); iIdx++ )
{
// check for special case: [version]
if ( ( slWhitelistAddresses.at ( iIdx ).length() > 2 ) && ( slWhitelistAddresses.at ( iIdx ).left ( 1 ) == "[" ) &&
( slWhitelistAddresses.at ( iIdx ).right ( 1 ) == "]" ) )
{
strMinServerVersion = slWhitelistAddresses.at ( iIdx ).mid ( 1, slWhitelistAddresses.at ( iIdx ).length() - 2 );
}
else if ( CurWhiteListAddress.setAddress ( slWhitelistAddresses.at ( iIdx ) ) )
{
vWhiteList << CurWhiteListAddress;
}
}
}
// assume directoryType will get set to AT_CUSTOM
if ( !strDirectoryAddress.compare ( "localhost", Qt::CaseInsensitive ) || !strDirectoryAddress.compare ( "127.0.0.1" ) )
{
if ( !strMinServerVersion.isEmpty() )
{
qInfo() << "Registering servers must be version" << strMinServerVersion << "or later.";
}
if ( !vWhiteList.isEmpty() )
{
qInfo() << "Directory registration white list active. Only the following addresses can register:";
foreach ( QHostAddress hostAddress, vWhiteList )
{
qInfo() << " -" << hostAddress.toString();
}
}
}
// prepare the one shot timer for determining if this is a
// permanent registered server
TimerIsPermanent.setSingleShot ( true );
TimerIsPermanent.setInterval ( SERVLIST_TIME_PERMSERV_MINUTES * 60000 );
// prepare the register server response timer (single shot timer)
TimerCLRegisterServerResp.setSingleShot ( true );
TimerCLRegisterServerResp.setInterval ( REGISTER_SERVER_TIME_OUT_MS );
// Connections -------------------------------------------------------------
QObject::connect ( &TimerPollList, &QTimer::timeout, this, &CServerListManager::OnTimerPollList );
QObject::connect ( &TimerPingServerInList, &QTimer::timeout, this, &CServerListManager::OnTimerPingServerInList );
QObject::connect ( &TimerPingServers, &QTimer::timeout, this, &CServerListManager::OnTimerPingServers );
QObject::connect ( &TimerRefreshRegistration, &QTimer::timeout, this, &CServerListManager::OnTimerRefreshRegistration );
QObject::connect ( &TimerCLRegisterServerResp, &QTimer::timeout, this, &CServerListManager::OnTimerCLRegisterServerResp );
QObject::connect ( &TimerIsPermanent, &QTimer::timeout, this, &CServerListManager::OnTimerIsPermanent );
QObject::connect ( QCoreApplication::instance(), &QCoreApplication::aboutToQuit, this, &CServerListManager::OnAboutToQuit );
}
// set server infos -> per definition the server info of this server is
// stored in the first entry of the list, we assume here that the first
// entry is correctly created in the constructor of the class
// and, if registered, refresh the server list entry
void CServerListManager::SetServerName ( const QString& strNewName )
{
if ( ServerList[0].strName != strNewName )
{
ServerList[0].strName = strNewName;
SetRegistered ( eSvrRegStatus != SRS_NOT_REGISTERED );
}
}
void CServerListManager::SetServerCity ( const QString& strNewCity )
{
if ( ServerList[0].strCity != strNewCity )
{
ServerList[0].strCity = strNewCity;
SetRegistered ( eSvrRegStatus != SRS_NOT_REGISTERED );
}
}
void CServerListManager::SetServerCountry ( const QLocale::Country eNewCountry )
{
if ( ServerList[0].eCountry != eNewCountry )
{
ServerList[0].eCountry = eNewCountry;
SetRegistered ( eSvrRegStatus != SRS_NOT_REGISTERED );
}
}
void CServerListManager::SetDirectoryAddress ( const QString sNDirectoryAddress )
{
// if the address has not actually changed, do nothing
if ( sNDirectoryAddress == strDirectoryAddress )
{
return;
}
if ( DirectoryType != AT_CUSTOM )
{
// just save the new name
strDirectoryAddress = sNDirectoryAddress;
return;
}
// sets the lock
Unregister();
QMutexLocker locker ( &Mutex );
// now save the new name
strDirectoryAddress = sNDirectoryAddress;
SetIsDirectory();
locker.unlock();
// sets the lock
Register();
}
void CServerListManager::SetDirectoryType ( const EDirectoryType eNCSAT )
{
// if the directory type is not changing, do nothing
if ( eNCSAT == DirectoryType )
{
return;
}
// sets the lock
Unregister();
QMutexLocker locker ( &Mutex );
// now update the server type
DirectoryType = eNCSAT;
SetIsDirectory();
locker.unlock();
// sets the lock
Register();
}
void CServerListManager::SetIsDirectory()
{
// this is called with the lock set
// per definition: If we are registered and the directory
// is the localhost address, we are in directory mode.
bool bNIsDirectory = DirectoryType == AT_CUSTOM &&
( !strDirectoryAddress.compare ( "localhost", Qt::CaseInsensitive ) || !strDirectoryAddress.compare ( "127.0.0.1" ) );
if ( bIsDirectory == bNIsDirectory )
{
return;
}
bIsDirectory = bNIsDirectory;
if ( bIsDirectory )
{
qInfo() << qUtf8Printable ( tr ( "Now a directory" ) );
// Load any persistent server list (create it if it is not there)
(void) Load();
}
else
{
qInfo() << qUtf8Printable ( tr ( "No longer a directory" ) );
}
}
// When we unregister, set the status and stop timers
void CServerListManager::Unregister()
{
// if not currently registered, nothing needs doing
if ( DirectoryType == AT_NONE || ( DirectoryType == AT_CUSTOM && strDirectoryAddress.isEmpty() ) || eSvrRegStatus == SRS_NOT_REGISTERED )
{
return;
}
// Update server registration status - sets the lock
SetRegistered ( false );
// this is called without the lock set
QMutexLocker locker ( &Mutex );
// disable service -> stop timer
if ( bIsDirectory )
{
TimerPollList.stop();
TimerPingServerInList.stop();
}
else
{
TimerCLRegisterServerResp.stop();
TimerRefreshRegistration.stop();
TimerPingServers.stop();
TimerIsPermanent.stop();
}
ServerList[0].bPermanentOnline = false;
}
// When we register, set the status and start timers
void CServerListManager::Register()
{
// if cannot currently register, or we have registered, nothing needs doing
if ( DirectoryType == AT_NONE || ( DirectoryType == AT_CUSTOM && strDirectoryAddress.isEmpty() ) || eSvrRegStatus == SRS_REGISTERED )
{
// there are edge cases during registration...
// maybe ! ( SRS_NOT_REGISTERED || SRS_BAD_ADDRESS )
return;
}
// Update server registration status - sets the lock
SetRegistered ( true );
// this is called without the lock set
QMutexLocker locker ( &Mutex );
if ( bIsDirectory )
{
// start timer for polling the server list if enabled
// 1 minute = 60 * 1000 ms
TimerPollList.start ( SERVLIST_POLL_TIME_MINUTES * 60000 );
// start timer for sending ping messages to servers in the list
TimerPingServerInList.start ( SERVLIST_UPDATE_PING_SERVERS_MS );
// directory is permanent
ServerList[0].bPermanentOnline = true;
}
else
{
// reset the retry counter to zero because update was called
iSvrRegRetries = 0;
// start timer for registration timeout - this gets restarted
// in OnTimerCLRegisterServerResp on failure
TimerCLRegisterServerResp.start();
// start timer for registering this server at the directory
// 1 minute = 60 * 1000 ms
TimerRefreshRegistration.start ( SERVLIST_REGIST_INTERV_MINUTES * 60000 );
// Start timer for ping the directory in short intervals to
// keep the port open at the NAT router.
// If no NAT is used, we send the messages anyway since they do
// not hurt (very low traffic). We also reuse the same update
// time as used in the directory for pinging the registered
// servers.
TimerPingServers.start ( SERVLIST_UPDATE_PING_SERVERS_MS );
// start the one shot timer for determining if this is a
// permanent registered server
TimerIsPermanent.start();
}
}
/* Server list functionality **************************************************/
void CServerListManager::OnTimerPingServerInList()
{
QMutexLocker locker ( &Mutex );
const int iCurServerListSize = ServerList.size();
// send ping to list entries except of the very first one (which is the directory
// server entry)
for ( int iIdx = 1; iIdx < iCurServerListSize; iIdx++ )
{
// send empty message to keep NAT port open at registered server
pConnLessProtocol->CreateCLEmptyMes ( ServerList[iIdx].HostAddr );
}
}
void CServerListManager::OnTimerPollList()
{
CVector<CHostAddress> vecRemovedHostAddr;
QMutexLocker locker ( &Mutex );
// Check all list entries are still valid (omitting the directory itself)
for ( int iIdx = ServerList.size() - 1; iIdx > 0; iIdx-- )
{
// 1 minute = 60 * 1000 ms
if ( ServerList[iIdx].RegisterTime.elapsed() > ( SERVLIST_TIME_OUT_MINUTES * 60000 ) )
{
// remove this list entry
vecRemovedHostAddr.Add ( ServerList[iIdx].HostAddr );
ServerList.removeAt ( iIdx );
}
}
locker.unlock();
foreach ( const CHostAddress HostAddr, vecRemovedHostAddr )
{
qInfo() << qUtf8Printable ( QString ( "Expired entry for %1" ).arg ( HostAddr.toString() ) );
}
}
void CServerListManager::Append ( const CHostAddress& InetAddr,
const CHostAddress& LInetAddr,
const CServerCoreInfo& ServerInfo,
const QString strVersion )
{
if ( bIsDirectory )
{
// if the client IP address is a private one, it's on the same LAN as the directory
bool serverIsExternal = !NetworkUtil::IsPrivateNetworkIP ( InetAddr.InetAddr );
qInfo() << qUtf8Printable ( QString ( "Requested to register entry for %1 (%2): %3 (%4)" )
.arg ( InetAddr.toString() )
.arg ( LInetAddr.toString() )
.arg ( ServerInfo.strName )
.arg ( serverIsExternal ? "external" : "local" ) );
// check for minimum server version
if ( !strMinServerVersion.isEmpty() )
{
#if ( QT_VERSION >= QT_VERSION_CHECK( 5, 6, 0 ) )
if ( strVersion.isEmpty() ||
QVersionNumber::compare ( QVersionNumber::fromString ( strMinServerVersion ), QVersionNumber::fromString ( strVersion ) ) > 0 )
{
pConnLessProtocol->CreateCLRegisterServerResp ( InetAddr, SRR_VERSION_TOO_OLD );
return; // leave function early, i.e., we do not register this server
}
#endif
}
// check for whitelist (it is enabled if it is not empty per definition)
if ( !vWhiteList.empty() )
{
// if the server is not listed, refuse registration and send registration response
if ( !vWhiteList.contains ( InetAddr.InetAddr ) )
{
pConnLessProtocol->CreateCLRegisterServerResp ( InetAddr, SRR_NOT_FULFILL_REQIREMENTS );
return; // leave function early, i.e., we do not register this server
}
}
// access/modifications to the server list needs to be mutexed
QMutexLocker locker ( &Mutex );
const int iCurServerListSize = ServerList.size();
// Check if server is already registered.
// The very first list entry must not be checked since
// this is per definition the directory (i.e., this server)
int iSelIdx = IndexOf ( InetAddr );
// if server is not yet registered, we have to create a new entry
if ( iSelIdx == INVALID_INDEX )
{
// check for maximum allowed number of servers in the server list
if ( iCurServerListSize < MAX_NUM_SERVERS_IN_SERVER_LIST )
{
// create a new server list entry and init with received data
ServerList.append ( CServerListEntry ( InetAddr, LInetAddr, ServerInfo ) );
iSelIdx = iCurServerListSize;
}
}
else
{
// update all data and call update registration function
ServerList[iSelIdx].LHostAddr = LInetAddr;
ServerList[iSelIdx].strName = ServerInfo.strName;
ServerList[iSelIdx].eCountry = ServerInfo.eCountry;
ServerList[iSelIdx].strCity = ServerInfo.strCity;
ServerList[iSelIdx].iMaxNumClients = ServerInfo.iMaxNumClients;
ServerList[iSelIdx].bPermanentOnline = ServerInfo.bPermanentOnline;
ServerList[iSelIdx].UpdateRegistration();
}
pConnLessProtocol->CreateCLRegisterServerResp ( InetAddr,
iSelIdx == INVALID_INDEX ? ESvrRegResult::SRR_SERVER_LIST_FULL
: ESvrRegResult::SRR_REGISTERED );
}
}
void CServerListManager::Remove ( const CHostAddress& InetAddr )
{
if ( bIsDirectory )
{
qInfo() << qUtf8Printable ( QString ( "Requested to unregister entry for %1" ).arg ( InetAddr.toString() ) );
QMutexLocker locker ( &Mutex );
// Find the server to unregister in the list. The very first list entry
// must not be removed since this is per definition the directory
// (i.e., this server).
int iIdx = IndexOf ( InetAddr );
if ( iIdx > 0 )
{
ServerList.removeAt ( iIdx );
}
}
}
/*
PROTMESSID_CLM_SERVER_LIST
- SERVER internal to DIRECTORY (list entry external IP same LAN)
- CLIENT internal to DIRECTORY (CLM msg same LAN): use "external" fields (local LAN address)
- CLIENT external to DIRECTORY (CLM msg not same LAN): use "internal" fields (registered server public IP)
- SERVER external to DIRECTORY (list entry external IP same LAN)
- CLIENT internal to SERVER (CLM same IP as list entry external IP): use "internal" fields (local LAN address)
- CLIENT external to SERVER (CLM not same IP as list entry external IP): use "external" fields (public IP address from protocol)
Finally, when retrieving the entry for the directory itself life is more complicated still. It's easiest just to return "0"
and allow the client connect dialogue instead to use the IP and Port from which the list was received.
*/
void CServerListManager::RetrieveAll ( const CHostAddress& InetAddr )
{
QMutexLocker locker ( &Mutex );
if ( bIsDirectory )
{
// if the client IP address is a private one, it's on the same LAN as the directory
bool clientIsInternal = NetworkUtil::IsPrivateNetworkIP ( InetAddr.InetAddr );
CHostAddress clientPublicAddr = InetAddr;
if ( clientIsInternal && CHostAddress().InetAddr != ServerList[0].LHostAddr.InetAddr &&
!NetworkUtil::IsPrivateNetworkIP ( ServerList[0].LHostAddr.InetAddr ) )
{
// client and directory on same LAN, directory has public IP set, that should be suitable for the
// client, too (i.e. same router with same public IP will be used for both), so use it for client public IP
clientPublicAddr.InetAddr = ServerList[0].LHostAddr.InetAddr;
}
const ushort iCurServerListSize = static_cast<ushort> ( ServerList.size() );
// allocate memory for the entire list
CVector<CServerInfo> vecServerInfo ( iCurServerListSize );
// copy list item for the directory and just let the protocol sort out the actual details
vecServerInfo[0] = ServerList[0];
vecServerInfo[0].HostAddr = CHostAddress();
// copy the list (we have to copy it since the message requires a vector but the list is actually stored in a QList object
// and not in a vector object)
for ( int iIdx = 1; iIdx < iCurServerListSize; iIdx++ )
{
// copy list item
CServerInfo& siCurListEntry = vecServerInfo[iIdx] = ServerList[iIdx];
bool serverIsInternal = NetworkUtil::IsPrivateNetworkIP ( siCurListEntry.HostAddr.InetAddr );
bool wantHostAddr = clientIsInternal /* HostAddr is local IP if local server else external IP, so do not replace */ ||
( !serverIsInternal &&
InetAddr.InetAddr != siCurListEntry.HostAddr.InetAddr /* external server and client have different public IPs */ );
if ( !wantHostAddr )
{
vecServerInfo[iIdx].HostAddr = siCurListEntry.LHostAddr;
}
// do not send a "ping" to a server local to the directory (no need)
if ( !serverIsInternal )
{
// create "send empty message" for all other registered servers
// this causes the server (vecServerInfo[iIdx].HostAddr)
// to send a "reply" to the client (InetAddr or best guess public IP address if internal to directory)
// - with the intent of opening the server firewall for the client
pConnLessProtocol->CreateCLSendEmptyMesMes ( siCurListEntry.HostAddr, clientPublicAddr );
}
}
// send the server list to the client, since we do not know that the client
// has a UDP fragmentation issue, we send both lists, the reduced and the
// normal list after each other
pConnLessProtocol->CreateCLRedServerListMes ( InetAddr, vecServerInfo );
pConnLessProtocol->CreateCLServerListMes ( InetAddr, vecServerInfo );
}
}
int CServerListManager::IndexOf ( const CHostAddress& haSearchTerm )
{
// Called with lock set.
// Find the server in the list. The very first list entry
// per definition is the directory
// (i.e., this server).
for ( int iIdx = ServerList.size() - 1; iIdx > 0; iIdx-- )
{
if ( ServerList[iIdx].HostAddr == haSearchTerm )
{
return iIdx;
}
}
return INVALID_INDEX;
}
bool CServerListManager::SetServerListFileName ( QString strFilename )
{
QMutexLocker locker ( &Mutex );
if ( ServerListFileName == strFilename )
{
return true;
}
if ( !ServerListFileName.isEmpty() )
{
// Save once to the old filename
Save();
}
ServerListFileName = strFilename;
return Load();
}
bool CServerListManager::Load()
{
// this is called with the lock set
if ( !bIsDirectory || ServerListFileName.isEmpty() )
{
// this gets called again if either of the above change
return true;
}
QFile file ( ServerListFileName );
if ( !file.open ( QIODevice::ReadWrite | QIODevice::Text ) )
{
qWarning() << qUtf8Printable ( QString ( tr ( "Could not open '%1' for read/write. "
"Please check that %2 has permission (and that there is free space)." ) )
.arg ( ServerListFileName )
.arg ( APP_NAME ) );
ServerListFileName.clear();
return false;
}
qInfo() << qUtf8Printable ( QString ( tr ( "Loading persistent server list file: %1" ) ).arg ( ServerListFileName ) );
// do not lose our entry
CServerListEntry serverListEntry = ServerList[0];
ServerList.clear();
ServerList.append ( serverListEntry );
// use entire file content for the persistent server list
CHostAddress haServerHostAddr;
QTextStream in ( &file );
while ( !in.atEnd() )
{
QString line = in.readLine();
QStringList slLine = line.split ( ";" );
if ( slLine.count() != 7 )
{
qWarning() << qUtf8Printable ( QString ( "Could not parse '%1' successfully - bad line" ).arg ( line ) );
continue;
}
NetworkUtil::ParseNetworkAddressBare ( slLine[0], haServerHostAddr, bEnableIPv6 );
int iIdx = IndexOf ( haServerHostAddr );
if ( iIdx != INVALID_INDEX )
{
qWarning() << qUtf8Printable ( QString ( "Skipping '%1' - duplicate host %2" ).arg ( line ).arg ( haServerHostAddr.toString() ) );
continue;
}
serverListEntry =
CServerListEntry::parse ( slLine[0], slLine[1], slLine[2], slLine[3], slLine[4], slLine[5], slLine[6].toInt() != 0, bEnableIPv6 );
// We expect servers to have addresses...
if ( ( CHostAddress() == serverListEntry.HostAddr ) )
{
qWarning() << qUtf8Printable ( QString ( "Could not parse '%1' successfully - invalid host" ).arg ( line ) );
continue;
}
qInfo() << qUtf8Printable ( QString ( "Loading registration for %1 (%2): %3" )
.arg ( serverListEntry.HostAddr.toString() )
.arg ( serverListEntry.LHostAddr.toString() )
.arg ( serverListEntry.strName ) );
ServerList.append ( serverListEntry );
}
return true;
}
void CServerListManager::Save()
{
// this is called with the lock set
if ( ServerListFileName.isEmpty() )
{
return;
}
QFile file ( ServerListFileName );
if ( !file.open ( QIODevice::WriteOnly | QIODevice::Truncate | QIODevice::Text ) )
{
// Not a useable file
qWarning() << qUtf8Printable ( QString ( tr ( "Could not write to '%1'" ) ).arg ( ServerListFileName ) );
ServerListFileName.clear();
return;
}
QTextStream out ( &file );
// This loop *deliberately* omits the first element in the list
// (that's this server, which is added automatically on start up, not read)
for ( int iIdx = ServerList.size() - 1; iIdx > 0; iIdx-- )
{
qInfo() << qUtf8Printable ( QString ( tr ( "Saving registration for %1 (%2): %3" ) )
.arg ( ServerList[iIdx].HostAddr.toString() )
.arg ( ServerList[iIdx].LHostAddr.toString() )
.arg ( ServerList[iIdx].strName ) );
out << ServerList[iIdx].toCSV() << '\n';
}
}
/* Registered server functionality *************************************************/
void CServerListManager::StoreRegistrationResult ( ESvrRegResult eResult )
{
// we need the lock since the user might change the server properties at
// any time so another response could arrive
QMutexLocker locker ( &Mutex );
// we got some response, so stop the retry timer
TimerCLRegisterServerResp.stop();
switch ( eResult )
{
case ESvrRegResult::SRR_REGISTERED:
SetSvrRegStatus ( ESvrRegStatus::SRS_REGISTERED );
break;
case ESvrRegResult::SRR_SERVER_LIST_FULL:
SetSvrRegStatus ( ESvrRegStatus::SRS_SERVER_LIST_FULL );
break;
case ESvrRegResult::SRR_VERSION_TOO_OLD:
SetSvrRegStatus ( ESvrRegStatus::SRS_VERSION_TOO_OLD );
break;
case ESvrRegResult::SRR_NOT_FULFILL_REQIREMENTS:
SetSvrRegStatus ( ESvrRegStatus::SRS_NOT_FULFILL_REQUIREMENTS );
break;
default:
SetSvrRegStatus ( ESvrRegStatus::SRS_UNKNOWN_RESP );
break;
}
}
void CServerListManager::OnTimerPingServers()
{
QMutexLocker locker ( &Mutex );
// first check if directory address is valid
if ( !( DirectoryAddress == CHostAddress() ) )
{
// send empty message to directory to keep NAT port open -> we do
// not require any answer from the directory
pConnLessProtocol->CreateCLEmptyMes ( DirectoryAddress );
}
}
void CServerListManager::OnTimerCLRegisterServerResp()
{
QMutexLocker locker ( &Mutex );
if ( eSvrRegStatus == SRS_REQUESTED )
{
iSvrRegRetries++;
if ( iSvrRegRetries >= REGISTER_SERVER_RETRY_LIMIT )
{
SetSvrRegStatus ( SRS_TIME_OUT );
}
else
{
locker.unlock();
{
OnTimerRefreshRegistration();
}
locker.relock();
// re-start timer for registration timeout
TimerCLRegisterServerResp.start();
}
}
}
void CServerListManager::OnAboutToQuit()
{
{
QMutexLocker locker ( &Mutex );
Save();
}
// Sets the lock - also needs to come after Save()
Unregister();
}
void CServerListManager::SetRegistered ( const bool bIsRegister )
{
// we need the lock since the user might change the server properties at
// any time
QMutexLocker locker ( &Mutex );
if ( !bIsRegister && eSvrRegStatus == SRS_NOT_REGISTERED )
{
// not wanting to set registered, not registered, nothing to do
return;
}
if ( bIsDirectory )
{
// this IS the directory, no network message to worry about
SetSvrRegStatus ( bIsRegister ? SRS_REGISTERED : SRS_NOT_REGISTERED );
return;
}
// It is very important to unlock the Mutex before doing address resolution,
// so that the event loop can run and any other timers that need the mutex
// can obtain it. Otherwise there is the possibility of deadlock when doing
// the SRV lookup, if another timer fires that needs the same mutex.
locker.unlock();
// get the correct directory address
// Note that we always have to parse the server address again since if
// it is an URL of a dynamic IP address, the IP address might have
// changed in the meanwhile.
// Allow IPv4 only for communicating with Directories
// Use SRV DNS discovery for directory connections, fallback to A/AAAA if none.
const QString strNetworkAddress = NetworkUtil::GetDirectoryAddress ( DirectoryType, strDirectoryAddress );
const bool bDirectoryAddressValid = NetworkUtil::ParseNetworkAddress ( strNetworkAddress, DirectoryAddress, false );
// lock the mutex again now that the address has been resolved.
locker.relock();
if ( bIsRegister )
{
if ( bDirectoryAddressValid )
{
// register server
SetSvrRegStatus ( SRS_REQUESTED );
// For a registered server, the server properties are stored in the
// very first item in the server list (which is actually no server list
// but just one item long for the registered server).
pConnLessProtocol->CreateCLRegisterServerExMes ( DirectoryAddress, ServerList[0].LHostAddr, ServerList[0] );