forked from zerotier/ZeroTierOne
-
Notifications
You must be signed in to change notification settings - Fork 0
/
SqliteNetworkController.cpp
2195 lines (1963 loc) · 96.7 KB
/
SqliteNetworkController.cpp
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
/*
* ZeroTier One - Network Virtualization Everywhere
* Copyright (C) 2011-2015 ZeroTier, Inc.
*
* 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 3 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, see <http://www.gnu.org/licenses/>.
*
* --
*
* ZeroTier may be used and distributed under the terms of the GPLv3, which
* are available at: http://www.gnu.org/licenses/gpl-3.0.html
*
* If you would like to embed ZeroTier into a commercial application or
* redistribute it in a modified binary form, please contact ZeroTier Networks
* LLC. Start here: http://www.zerotier.com/
*/
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <sys/time.h>
#include <sys/types.h>
#include <algorithm>
#include <utility>
#include <stdexcept>
#include <set>
#include "../include/ZeroTierOne.h"
#include "../node/Constants.hpp"
#ifdef ZT_USE_SYSTEM_JSON_PARSER
#include <json-parser/json.h>
#else
#include "../ext/json-parser/json.h"
#endif
#include "SqliteNetworkController.hpp"
#include "../node/Node.hpp"
#include "../node/Utils.hpp"
#include "../node/CertificateOfMembership.hpp"
#include "../node/NetworkConfig.hpp"
#include "../node/Dictionary.hpp"
#include "../node/InetAddress.hpp"
#include "../node/MAC.hpp"
#include "../node/Address.hpp"
#include "../osdep/OSUtils.hpp"
// Include ZT_NETCONF_SCHEMA_SQL constant to init database
#include "schema.sql.c"
// Stored in database as schemaVersion key in Config.
// If not present, database is assumed to be empty and at the current schema version
// and this key/value is added automatically.
#define ZT_NETCONF_SQLITE_SCHEMA_VERSION 4
#define ZT_NETCONF_SQLITE_SCHEMA_VERSION_STR "4"
// API version reported via JSON control plane
#define ZT_NETCONF_CONTROLLER_API_VERSION 2
// Number of requests to remember in member history
#define ZT_NETCONF_DB_MEMBER_HISTORY_LENGTH 8
// Min duration between requests for an address/nwid combo to prevent floods
#define ZT_NETCONF_MIN_REQUEST_PERIOD 1000
// Delay between backups in milliseconds
#define ZT_NETCONF_BACKUP_PERIOD 300000
// Nodes are considered active if they've queried in less than this long
#define ZT_NETCONF_NODE_ACTIVE_THRESHOLD ((ZT_NETWORK_AUTOCONF_DELAY * 2) + 5000)
// Flags for Network 'flags' field in table
#define ZT_DB_NETWORK_FLAG_ZT_MANAGED_V4_AUTO_ASSIGN 1
#define ZT_DB_NETWORK_FLAG_ZT_MANAGED_V6_RFC4193 2
#define ZT_DB_NETWORK_FLAG_ZT_MANAGED_V6_6PLANE 4
#define ZT_DB_NETWORK_FLAG_ZT_MANAGED_V6_AUTO_ASSIGN 8
// Flags with all V6 managed mode flags flipped off -- for masking in update operation and in string form for SQL building
#define ZT_DB_NETWORK_FLAG_ZT_MANAGED_V6_MASK_S "268435441"
// Uncomment to trace Sqlite for debugging
//#define ZT_NETCONF_SQLITE_TRACE 1
namespace ZeroTier {
namespace {
static std::string _jsonEscape(const char *s)
{
if (!s)
return std::string();
std::string buf;
for(const char *p=s;(*p);++p) {
switch(*p) {
case '\t': buf.append("\\t"); break;
case '\b': buf.append("\\b"); break;
case '\r': buf.append("\\r"); break;
case '\n': buf.append("\\n"); break;
case '\f': buf.append("\\f"); break;
case '"': buf.append("\\\""); break;
case '\\': buf.append("\\\\"); break;
case '/': buf.append("\\/"); break;
default: buf.push_back(*p); break;
}
}
return buf;
}
static std::string _jsonEscape(const std::string &s) { return _jsonEscape(s.c_str()); }
// Converts an InetAddress to a blob and an int for storage in database
static void _ipToBlob(const InetAddress &a,char *ipBlob,int &ipVersion) /* blob[16] */
{
switch(a.ss_family) {
case AF_INET:
memset(ipBlob,0,12);
memcpy(ipBlob + 12,a.rawIpData(),4);
ipVersion = 4;
break;
case AF_INET6:
memcpy(ipBlob,a.rawIpData(),16);
ipVersion = 6;
break;
}
}
// Member.recentHistory is stored in a BLOB as an array of strings containing JSON objects.
// This is kind of hacky but efficient and quick to parse and send to the client.
class MemberRecentHistory : public std::list<std::string>
{
public:
inline std::string toBlob() const
{
std::string b;
for(const_iterator i(begin());i!=end();++i) {
b.append(*i);
b.push_back((char)0);
}
return b;
}
inline void fromBlob(const char *blob,unsigned int len)
{
for(unsigned int i=0,k=0;i<len;++i) {
if (!blob[i]) {
push_back(std::string(blob + k,i - k));
k = i + 1;
}
}
}
};
struct MemberRecord
{
sqlite3_int64 rowid;
char nodeId[16];
bool authorized;
bool activeBridge;
uint64_t lastRequestTime;
MemberRecentHistory recentHistory;
MemberRecord() :
rowid(0),
authorized(false),
activeBridge(false),
lastRequestTime(0)
{
nodeId[0] = (char)0;
}
};
struct NetworkRecord
{
char id[24];
const char *name;
int flags;
bool isPrivate;
bool enableBroadcast;
bool allowPassiveBridging;
int multicastLimit;
uint64_t creationTime;
uint64_t revision;
uint64_t memberRevisionCounter;
NetworkRecord() :
name((const char *)0),
flags(0),
isPrivate(true),
enableBroadcast(false),
allowPassiveBridging(false),
multicastLimit(0),
creationTime(0),
revision(0),
memberRevisionCounter(0)
{
id[0] = (char)0;
}
};
#ifdef ZT_NETCONF_SQLITE_TRACE
static void sqliteTraceFunc(void *ptr,const char *s)
{
fprintf(stderr,"SQLITE: %s\n",s);
}
#endif
} // anonymous namespace
SqliteNetworkController::SqliteNetworkController(Node *node,const char *dbPath,const char *circuitTestPath) :
_node(node),
_backupThreadRun(true),
_backupNeeded(true),
_dbPath(dbPath),
_circuitTestPath(circuitTestPath),
_db((sqlite3 *)0)
{
if (sqlite3_open_v2(dbPath,&_db,SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE,(const char *)0) != SQLITE_OK)
throw std::runtime_error("SqliteNetworkController cannot open database file");
sqlite3_busy_timeout(_db,10000);
sqlite3_exec(_db,"PRAGMA synchronous = OFF",0,0,0);
sqlite3_exec(_db,"PRAGMA journal_mode = MEMORY",0,0,0);
sqlite3_stmt *s = (sqlite3_stmt *)0;
if ((sqlite3_prepare_v2(_db,"SELECT v FROM Config WHERE k = 'schemaVersion';",-1,&s,(const char **)0) == SQLITE_OK)&&(s)) {
int schemaVersion = -1234;
if (sqlite3_step(s) == SQLITE_ROW) {
schemaVersion = sqlite3_column_int(s,0);
}
sqlite3_finalize(s);
if (schemaVersion == -1234) {
sqlite3_close(_db);
throw std::runtime_error("SqliteNetworkController schemaVersion not found in Config table (init failure?)");
}
if (schemaVersion < 2) {
// Create NodeHistory table to upgrade from version 1 to version 2
if (sqlite3_exec(_db,
"CREATE TABLE NodeHistory (\n"
" nodeId char(10) NOT NULL REFERENCES Node(id) ON DELETE CASCADE,\n"
" networkId char(16) NOT NULL REFERENCES Network(id) ON DELETE CASCADE,\n"
" networkVisitCounter INTEGER NOT NULL DEFAULT(0),\n"
" networkRequestAuthorized INTEGER NOT NULL DEFAULT(0),\n"
" requestTime INTEGER NOT NULL DEFAULT(0),\n"
" clientMajorVersion INTEGER NOT NULL DEFAULT(0),\n"
" clientMinorVersion INTEGER NOT NULL DEFAULT(0),\n"
" clientRevision INTEGER NOT NULL DEFAULT(0),\n"
" networkRequestMetaData VARCHAR(1024),\n"
" fromAddress VARCHAR(128)\n"
");\n"
"CREATE INDEX NodeHistory_nodeId ON NodeHistory (nodeId);\n"
"CREATE INDEX NodeHistory_networkId ON NodeHistory (networkId);\n"
"CREATE INDEX NodeHistory_requestTime ON NodeHistory (requestTime);\n"
"UPDATE \"Config\" SET \"v\" = 2 WHERE \"k\" = 'schemaVersion';\n"
,0,0,0) != SQLITE_OK) {
char err[1024];
Utils::snprintf(err,sizeof(err),"SqliteNetworkController cannot upgrade the database to version 2: %s",sqlite3_errmsg(_db));
sqlite3_close(_db);
throw std::runtime_error(err);
} else {
schemaVersion = 2;
}
}
if (schemaVersion < 3) {
// Create Route table to upgrade from version 2 to version 3 and migrate old
// data. Also delete obsolete Gateway table that was never actually used, and
// migrate Network flags to a bitwise flags field instead of ASCII cruft.
if (sqlite3_exec(_db,
"DROP TABLE Gateway;\n"
"CREATE TABLE Route (\n"
" networkId char(16) NOT NULL REFERENCES Network(id) ON DELETE CASCADE,\n"
" target blob(16) NOT NULL,\n"
" via blob(16),\n"
" targetNetmaskBits integer NOT NULL,\n"
" ipVersion integer NOT NULL,\n"
" flags integer NOT NULL,\n"
" metric integer NOT NULL\n"
");\n"
"CREATE INDEX Route_networkId ON Route (networkId);\n"
"INSERT INTO Route SELECT DISTINCT networkId,\"ip\" AS \"target\",NULL AS \"via\",ipNetmaskBits AS targetNetmaskBits,ipVersion,0 AS \"flags\",0 AS \"metric\" FROM IpAssignment WHERE nodeId IS NULL AND \"type\" = 1;\n"
"ALTER TABLE Network ADD COLUMN \"flags\" integer NOT NULL DEFAULT(0);\n"
"UPDATE Network SET \"flags\" = (\"flags\" | 1) WHERE v4AssignMode = 'zt';\n"
"UPDATE Network SET \"flags\" = (\"flags\" | 2) WHERE v6AssignMode = 'rfc4193';\n"
"UPDATE Network SET \"flags\" = (\"flags\" | 4) WHERE v6AssignMode = '6plane';\n"
"ALTER TABLE Member ADD COLUMN \"flags\" integer NOT NULL DEFAULT(0);\n"
"DELETE FROM IpAssignment WHERE nodeId IS NULL AND \"type\" = 1;\n"
"UPDATE \"Config\" SET \"v\" = 3 WHERE \"k\" = 'schemaVersion';\n"
,0,0,0) != SQLITE_OK) {
char err[1024];
Utils::snprintf(err,sizeof(err),"SqliteNetworkController cannot upgrade the database to version 3: %s",sqlite3_errmsg(_db));
sqlite3_close(_db);
throw std::runtime_error(err);
} else {
schemaVersion = 3;
}
}
if (schemaVersion < 4) {
// Turns out this was overkill and a huge performance drag. Will be revisiting this
// more later but for now a brief snapshot of recent history stored in Member is fine.
// Also prepare for implementation of proof of work requests.
if (sqlite3_exec(_db,
"DROP TABLE NodeHistory;\n"
"ALTER TABLE Member ADD COLUMN lastRequestTime integer NOT NULL DEFAULT(0);\n"
"ALTER TABLE Member ADD COLUMN lastPowDifficulty integer NOT NULL DEFAULT(0);\n"
"ALTER TABLE Member ADD COLUMN lastPowTime integer NOT NULL DEFAULT(0);\n"
"ALTER TABLE Member ADD COLUMN recentHistory blob;\n"
"CREATE INDEX Member_networkId_lastRequestTime ON Member(networkId, lastRequestTime);\n"
"UPDATE \"Config\" SET \"v\" = 4 WHERE \"k\" = 'schemaVersion';\n"
,0,0,0) != SQLITE_OK) {
char err[1024];
Utils::snprintf(err,sizeof(err),"SqliteNetworkController cannot upgrade the database to version 3: %s",sqlite3_errmsg(_db));
sqlite3_close(_db);
throw std::runtime_error(err);
} else {
schemaVersion = 4;
}
}
if (schemaVersion != ZT_NETCONF_SQLITE_SCHEMA_VERSION) {
sqlite3_close(_db);
throw std::runtime_error("SqliteNetworkController database schema version mismatch");
}
} else {
// Prepare statement will fail if Config table doesn't exist, which means our DB
// needs to be initialized.
if (sqlite3_exec(_db,ZT_NETCONF_SCHEMA_SQL"INSERT INTO Config (k,v) VALUES ('schemaVersion',"ZT_NETCONF_SQLITE_SCHEMA_VERSION_STR");",0,0,0) != SQLITE_OK) {
char err[1024];
Utils::snprintf(err,sizeof(err),"SqliteNetworkController cannot initialize database and/or insert schemaVersion into Config table: %s",sqlite3_errmsg(_db));
sqlite3_close(_db);
throw std::runtime_error(err);
}
}
if (
/* Network */
(sqlite3_prepare_v2(_db,"SELECT name,private,enableBroadcast,allowPassiveBridging,\"flags\",multicastLimit,creationTime,revision,memberRevisionCounter,(SELECT COUNT(1) FROM Member WHERE Member.networkId = Network.id AND Member.authorized > 0) FROM Network WHERE id = ?",-1,&_sGetNetworkById,(const char **)0) != SQLITE_OK)
||(sqlite3_prepare_v2(_db,"SELECT revision FROM Network WHERE id = ?",-1,&_sGetNetworkRevision,(const char **)0) != SQLITE_OK)
||(sqlite3_prepare_v2(_db,"UPDATE Network SET revision = ? WHERE id = ?",-1,&_sSetNetworkRevision,(const char **)0) != SQLITE_OK)
||(sqlite3_prepare_v2(_db,"INSERT INTO Network (id,name,creationTime,revision) VALUES (?,?,?,1)",-1,&_sCreateNetwork,(const char **)0) != SQLITE_OK)
||(sqlite3_prepare_v2(_db,"DELETE FROM Network WHERE id = ?",-1,&_sDeleteNetwork,(const char **)0) != SQLITE_OK)
||(sqlite3_prepare_v2(_db,"SELECT id FROM Network ORDER BY id ASC",-1,&_sListNetworks,(const char **)0) != SQLITE_OK)
||(sqlite3_prepare_v2(_db,"UPDATE Network SET memberRevisionCounter = (memberRevisionCounter + 1) WHERE id = ?",-1,&_sIncrementMemberRevisionCounter,(const char **)0) != SQLITE_OK)
/* Node */
||(sqlite3_prepare_v2(_db,"SELECT identity FROM Node WHERE id = ?",-1,&_sGetNodeIdentity,(const char **)0) != SQLITE_OK)
||(sqlite3_prepare_v2(_db,"INSERT OR REPLACE INTO Node (id,identity) VALUES (?,?)",-1,&_sCreateOrReplaceNode,(const char **)0) != SQLITE_OK)
/* Rule */
||(sqlite3_prepare_v2(_db,"SELECT etherType FROM Rule WHERE networkId = ? AND \"action\" = 'accept'",-1,&_sGetEtherTypesFromRuleTable,(const char **)0) != SQLITE_OK)
||(sqlite3_prepare_v2(_db,"INSERT INTO Rule (networkId,ruleNo,nodeId,sourcePort,destPort,vlanId,vlanPcP,etherType,macSource,macDest,ipSource,ipDest,ipTos,ipProtocol,ipSourcePort,ipDestPort,flags,invFlags,\"action\") VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)",-1,&_sCreateRule,(const char **)0) != SQLITE_OK)
||(sqlite3_prepare_v2(_db,"SELECT ruleNo,nodeId,sourcePort,destPort,vlanId,vlanPcp,etherType,macSource,macDest,ipSource,ipDest,ipTos,ipProtocol,ipSourcePort,ipDestPort,\"flags\",invFlags,\"action\" FROM Rule WHERE networkId = ? ORDER BY ruleNo ASC",-1,&_sListRules,(const char **)0) != SQLITE_OK)
||(sqlite3_prepare_v2(_db,"DELETE FROM Rule WHERE networkId = ?",-1,&_sDeleteRulesForNetwork,(const char **)0) != SQLITE_OK)
/* IpAssignmentPool */
||(sqlite3_prepare_v2(_db,"SELECT ipRangeStart,ipRangeEnd FROM IpAssignmentPool WHERE networkId = ? AND ipVersion = ?",-1,&_sGetIpAssignmentPools,(const char **)0) != SQLITE_OK)
||(sqlite3_prepare_v2(_db,"SELECT ipRangeStart,ipRangeEnd,ipVersion FROM IpAssignmentPool WHERE networkId = ? ORDER BY ipRangeStart ASC",-1,&_sGetIpAssignmentPools2,(const char **)0) != SQLITE_OK)
||(sqlite3_prepare_v2(_db,"INSERT INTO IpAssignmentPool (networkId,ipRangeStart,ipRangeEnd,ipVersion) VALUES (?,?,?,?)",-1,&_sCreateIpAssignmentPool,(const char **)0) != SQLITE_OK)
||(sqlite3_prepare_v2(_db,"DELETE FROM IpAssignmentPool WHERE networkId = ?",-1,&_sDeleteIpAssignmentPoolsForNetwork,(const char **)0) != SQLITE_OK)
/* IpAssignment */
||(sqlite3_prepare_v2(_db,"SELECT ip,ipNetmaskBits,ipVersion FROM IpAssignment WHERE networkId = ? AND nodeId = ? AND \"type\" = 0 ORDER BY ip ASC",-1,&_sGetIpAssignmentsForNode,(const char **)0) != SQLITE_OK)
||(sqlite3_prepare_v2(_db,"SELECT 1 FROM IpAssignment WHERE networkId = ? AND ip = ? AND ipVersion = ? AND \"type\" = ?",-1,&_sCheckIfIpIsAllocated,(const char **)0) != SQLITE_OK)
||(sqlite3_prepare_v2(_db,"INSERT INTO IpAssignment (networkId,nodeId,\"type\",ip,ipNetmaskBits,ipVersion) VALUES (?,?,?,?,?,?)",-1,&_sAllocateIp,(const char **)0) != SQLITE_OK)
||(sqlite3_prepare_v2(_db,"DELETE FROM IpAssignment WHERE networkId = ? AND nodeId = ? AND \"type\" = ?",-1,&_sDeleteIpAllocations,(const char **)0) != SQLITE_OK)
/* Relay */
||(sqlite3_prepare_v2(_db,"SELECT \"address\",\"phyAddress\" FROM Relay WHERE \"networkId\" = ? ORDER BY \"address\" ASC",-1,&_sGetRelays,(const char **)0) != SQLITE_OK)
||(sqlite3_prepare_v2(_db,"DELETE FROM Relay WHERE networkId = ?",-1,&_sDeleteRelaysForNetwork,(const char **)0) != SQLITE_OK)
||(sqlite3_prepare_v2(_db,"INSERT INTO Relay (\"networkId\",\"address\",\"phyAddress\") VALUES (?,?,?)",-1,&_sCreateRelay,(const char **)0) != SQLITE_OK)
/* Member */
||(sqlite3_prepare_v2(_db,"SELECT rowid,authorized,activeBridge,memberRevision,\"flags\",lastRequestTime,recentHistory FROM Member WHERE networkId = ? AND nodeId = ?",-1,&_sGetMember,(const char **)0) != SQLITE_OK)
||(sqlite3_prepare_v2(_db,"SELECT m.authorized,m.activeBridge,m.memberRevision,n.identity,m.flags,m.lastRequestTime,m.recentHistory FROM Member AS m LEFT OUTER JOIN Node AS n ON n.id = m.nodeId WHERE m.networkId = ? AND m.nodeId = ?",-1,&_sGetMember2,(const char **)0) != SQLITE_OK)
||(sqlite3_prepare_v2(_db,"INSERT INTO Member (networkId,nodeId,authorized,activeBridge,memberRevision) VALUES (?,?,?,0,(SELECT memberRevisionCounter FROM Network WHERE id = ?))",-1,&_sCreateMember,(const char **)0) != SQLITE_OK)
||(sqlite3_prepare_v2(_db,"SELECT nodeId FROM Member WHERE networkId = ? AND activeBridge > 0 AND authorized > 0",-1,&_sGetActiveBridges,(const char **)0) != SQLITE_OK)
||(sqlite3_prepare_v2(_db,"SELECT m.nodeId,m.memberRevision FROM Member AS m WHERE m.networkId = ? ORDER BY m.nodeId ASC",-1,&_sListNetworkMembers,(const char **)0) != SQLITE_OK)
||(sqlite3_prepare_v2(_db,"UPDATE Member SET authorized = ?,memberRevision = (SELECT memberRevisionCounter FROM Network WHERE id = ?) WHERE rowid = ?",-1,&_sUpdateMemberAuthorized,(const char **)0) != SQLITE_OK)
||(sqlite3_prepare_v2(_db,"UPDATE Member SET activeBridge = ?,memberRevision = (SELECT memberRevisionCounter FROM Network WHERE id = ?) WHERE rowid = ?",-1,&_sUpdateMemberActiveBridge,(const char **)0) != SQLITE_OK)
||(sqlite3_prepare_v2(_db,"UPDATE Member SET \"lastRequestTime\" = ?, \"recentHistory\" = ? WHERE rowid = ?",-1,&_sUpdateMemberHistory,(const char **)0) != SQLITE_OK)
||(sqlite3_prepare_v2(_db,"DELETE FROM Member WHERE networkId = ? AND nodeId = ?",-1,&_sDeleteMember,(const char **)0) != SQLITE_OK)
||(sqlite3_prepare_v2(_db,"DELETE FROM Member WHERE networkId = ?",-1,&_sDeleteAllNetworkMembers,(const char **)0) != SQLITE_OK)
||(sqlite3_prepare_v2(_db,"SELECT nodeId,recentHistory FROM Member WHERE networkId = ? AND lastRequestTime >= ?",-1,&_sGetActiveNodesOnNetwork,(const char **)0) != SQLITE_OK)
/* Route */
||(sqlite3_prepare_v2(_db,"INSERT INTO Route (networkId,target,via,targetNetmaskBits,ipVersion,flags,metric) VALUES (?,?,?,?,?,?,?)",-1,&_sCreateRoute,(const char **)0) != SQLITE_OK)
||(sqlite3_prepare_v2(_db,"SELECT DISTINCT target,via,targetNetmaskBits,ipVersion,flags,metric FROM \"Route\" WHERE networkId = ? ORDER BY ipVersion,target,via",-1,&_sGetRoutes,(const char **)0) != SQLITE_OK)
||(sqlite3_prepare_v2(_db,"DELETE FROM \"Route\" WHERE networkId = ?",-1,&_sDeleteRoutes,(const char **)0) != SQLITE_OK)
/* Config */
||(sqlite3_prepare_v2(_db,"SELECT \"v\" FROM \"Config\" WHERE \"k\" = ?",-1,&_sGetConfig,(const char **)0) != SQLITE_OK)
||(sqlite3_prepare_v2(_db,"INSERT OR REPLACE INTO \"Config\" (\"k\",\"v\") VALUES (?,?)",-1,&_sSetConfig,(const char **)0) != SQLITE_OK)
) {
std::string err(std::string("SqliteNetworkController unable to initialize one or more prepared statements: ") + sqlite3_errmsg(_db));
sqlite3_close(_db);
throw std::runtime_error(err);
}
/* Generate a 128-bit / 32-character "instance ID" if one isn't already
* defined. Clients can use this to determine if this is the same controller
* database they know and love. */
sqlite3_reset(_sGetConfig);
sqlite3_bind_text(_sGetConfig,1,"instanceId",10,SQLITE_STATIC);
if (sqlite3_step(_sGetConfig) != SQLITE_ROW) {
unsigned char sr[32];
Utils::getSecureRandom(sr,32);
for(unsigned int i=0;i<32;++i)
_instanceId.push_back("0123456789abcdef"[(unsigned int)sr[i] & 0xf]);
sqlite3_reset(_sSetConfig);
sqlite3_bind_text(_sSetConfig,1,"instanceId",10,SQLITE_STATIC);
sqlite3_bind_text(_sSetConfig,2,_instanceId.c_str(),-1,SQLITE_STATIC);
if (sqlite3_step(_sSetConfig) != SQLITE_DONE)
throw std::runtime_error("SqliteNetworkController unable to read or initialize instanceId");
} else {
const char *iid = reinterpret_cast<const char *>(sqlite3_column_text(_sGetConfig,0));
if (!iid)
throw std::runtime_error("SqliteNetworkController unable to read instanceId (it's NULL)");
_instanceId = iid;
}
#ifdef ZT_NETCONF_SQLITE_TRACE
sqlite3_trace(_db,sqliteTraceFunc,(void *)0);
#endif
_backupThread = Thread::start(this);
}
SqliteNetworkController::~SqliteNetworkController()
{
_backupThreadRun = false;
Thread::join(_backupThread);
Mutex::Lock _l(_lock);
if (_db) {
sqlite3_finalize(_sGetNetworkById);
sqlite3_finalize(_sGetMember);
sqlite3_finalize(_sCreateMember);
sqlite3_finalize(_sGetNodeIdentity);
sqlite3_finalize(_sCreateOrReplaceNode);
sqlite3_finalize(_sGetEtherTypesFromRuleTable);
sqlite3_finalize(_sGetActiveBridges);
sqlite3_finalize(_sGetIpAssignmentsForNode);
sqlite3_finalize(_sGetIpAssignmentPools);
sqlite3_finalize(_sCheckIfIpIsAllocated);
sqlite3_finalize(_sAllocateIp);
sqlite3_finalize(_sDeleteIpAllocations);
sqlite3_finalize(_sGetRelays);
sqlite3_finalize(_sListNetworks);
sqlite3_finalize(_sListNetworkMembers);
sqlite3_finalize(_sGetMember2);
sqlite3_finalize(_sGetIpAssignmentPools2);
sqlite3_finalize(_sListRules);
sqlite3_finalize(_sCreateRule);
sqlite3_finalize(_sCreateNetwork);
sqlite3_finalize(_sGetNetworkRevision);
sqlite3_finalize(_sSetNetworkRevision);
sqlite3_finalize(_sDeleteRelaysForNetwork);
sqlite3_finalize(_sCreateRelay);
sqlite3_finalize(_sDeleteIpAssignmentPoolsForNetwork);
sqlite3_finalize(_sDeleteRulesForNetwork);
sqlite3_finalize(_sCreateIpAssignmentPool);
sqlite3_finalize(_sUpdateMemberAuthorized);
sqlite3_finalize(_sUpdateMemberActiveBridge);
sqlite3_finalize(_sUpdateMemberHistory);
sqlite3_finalize(_sDeleteMember);
sqlite3_finalize(_sDeleteAllNetworkMembers);
sqlite3_finalize(_sGetActiveNodesOnNetwork);
sqlite3_finalize(_sDeleteNetwork);
sqlite3_finalize(_sCreateRoute);
sqlite3_finalize(_sGetRoutes);
sqlite3_finalize(_sDeleteRoutes);
sqlite3_finalize(_sIncrementMemberRevisionCounter);
sqlite3_finalize(_sGetConfig);
sqlite3_finalize(_sSetConfig);
sqlite3_close(_db);
}
}
NetworkController::ResultCode SqliteNetworkController::doNetworkConfigRequest(const InetAddress &fromAddr,const Identity &signingId,const Identity &identity,uint64_t nwid,const Dictionary<ZT_NETWORKCONFIG_DICT_CAPACITY> &metaData,NetworkConfig &nc)
{
if (((!signingId)||(!signingId.hasPrivate()))||(signingId.address().toInt() != (nwid >> 24))) {
return NetworkController::NETCONF_QUERY_INTERNAL_SERVER_ERROR;
}
const uint64_t now = OSUtils::now();
NetworkRecord network;
Utils::snprintf(network.id,sizeof(network.id),"%.16llx",(unsigned long long)nwid);
MemberRecord member;
Utils::snprintf(member.nodeId,sizeof(member.nodeId),"%.10llx",(unsigned long long)identity.address().toInt());
{ // begin lock
Mutex::Lock _l(_lock);
// Check rate limit circuit breaker to prevent flooding
{
uint64_t &lrt = _lastRequestTime[std::pair<uint64_t,uint64_t>(identity.address().toInt(),nwid)];
if ((now - lrt) <= ZT_NETCONF_MIN_REQUEST_PERIOD)
return NetworkController::NETCONF_QUERY_IGNORE;
lrt = now;
}
_backupNeeded = true;
// Create Node record or do full identity check if we already have one
sqlite3_reset(_sGetNodeIdentity);
sqlite3_bind_text(_sGetNodeIdentity,1,member.nodeId,10,SQLITE_STATIC);
if (sqlite3_step(_sGetNodeIdentity) == SQLITE_ROW) {
try {
Identity alreadyKnownIdentity((const char *)sqlite3_column_text(_sGetNodeIdentity,0));
if (alreadyKnownIdentity != identity)
return NetworkController::NETCONF_QUERY_ACCESS_DENIED;
} catch ( ... ) { // identity stored in database is not valid or is NULL
return NetworkController::NETCONF_QUERY_ACCESS_DENIED;
}
} else {
std::string idstr(identity.toString(false));
sqlite3_reset(_sCreateOrReplaceNode);
sqlite3_bind_text(_sCreateOrReplaceNode,1,member.nodeId,10,SQLITE_STATIC);
sqlite3_bind_text(_sCreateOrReplaceNode,2,idstr.c_str(),-1,SQLITE_STATIC);
if (sqlite3_step(_sCreateOrReplaceNode) != SQLITE_DONE) {
return NetworkController::NETCONF_QUERY_INTERNAL_SERVER_ERROR;
}
}
// Fetch Network record
sqlite3_reset(_sGetNetworkById);
sqlite3_bind_text(_sGetNetworkById,1,network.id,16,SQLITE_STATIC);
if (sqlite3_step(_sGetNetworkById) == SQLITE_ROW) {
network.name = (const char *)sqlite3_column_text(_sGetNetworkById,0);
network.isPrivate = (sqlite3_column_int(_sGetNetworkById,1) > 0);
network.enableBroadcast = (sqlite3_column_int(_sGetNetworkById,2) > 0);
network.allowPassiveBridging = (sqlite3_column_int(_sGetNetworkById,3) > 0);
network.flags = sqlite3_column_int(_sGetNetworkById,4);
network.multicastLimit = sqlite3_column_int(_sGetNetworkById,5);
network.creationTime = (uint64_t)sqlite3_column_int64(_sGetNetworkById,6);
network.revision = (uint64_t)sqlite3_column_int64(_sGetNetworkById,7);
network.memberRevisionCounter = (uint64_t)sqlite3_column_int64(_sGetNetworkById,8);
} else {
return NetworkController::NETCONF_QUERY_OBJECT_NOT_FOUND;
}
// Fetch or create Member record
sqlite3_reset(_sGetMember);
sqlite3_bind_text(_sGetMember,1,network.id,16,SQLITE_STATIC);
sqlite3_bind_text(_sGetMember,2,member.nodeId,10,SQLITE_STATIC);
if (sqlite3_step(_sGetMember) == SQLITE_ROW) {
member.rowid = sqlite3_column_int64(_sGetMember,0);
member.authorized = (sqlite3_column_int(_sGetMember,1) > 0);
member.activeBridge = (sqlite3_column_int(_sGetMember,2) > 0);
member.lastRequestTime = (uint64_t)sqlite3_column_int64(_sGetMember,5);
const char *rhblob = (const char *)sqlite3_column_blob(_sGetMember,6);
if (rhblob)
member.recentHistory.fromBlob(rhblob,(unsigned int)sqlite3_column_bytes(_sGetMember,6));
} else {
member.authorized = (network.isPrivate ? false : true);
member.activeBridge = false;
sqlite3_reset(_sCreateMember);
sqlite3_bind_text(_sCreateMember,1,network.id,16,SQLITE_STATIC);
sqlite3_bind_text(_sCreateMember,2,member.nodeId,10,SQLITE_STATIC);
sqlite3_bind_int(_sCreateMember,3,(member.authorized ? 1 : 0));
sqlite3_bind_text(_sCreateMember,4,network.id,16,SQLITE_STATIC);
if (sqlite3_step(_sCreateMember) != SQLITE_DONE) {
return NetworkController::NETCONF_QUERY_INTERNAL_SERVER_ERROR;
}
member.rowid = sqlite3_last_insert_rowid(_db);
sqlite3_reset(_sIncrementMemberRevisionCounter);
sqlite3_bind_text(_sIncrementMemberRevisionCounter,1,network.id,16,SQLITE_STATIC);
sqlite3_step(_sIncrementMemberRevisionCounter);
}
// Update Member.history
{
char mh[1024];
Utils::snprintf(mh,sizeof(mh),
"{\"ts\":%llu,\"authorized\":%s,\"clientMajorVersion\":%u,\"clientMinorVersion\":%u,\"clientRevision\":%u,\"fromAddr\":",
(unsigned long long)now,
((member.authorized) ? "true" : "false"),
metaData.getUI(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_NODE_MAJOR_VERSION,0),
metaData.getUI(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_NODE_MINOR_VERSION,0),
metaData.getUI(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_NODE_REVISION,0));
member.recentHistory.push_front(std::string(mh));
if (fromAddr) {
member.recentHistory.front().push_back('"');
member.recentHistory.front().append(_jsonEscape(fromAddr.toString()));
member.recentHistory.front().append("\"}");
} else {
member.recentHistory.front().append("null}");
}
while (member.recentHistory.size() > ZT_NETCONF_DB_MEMBER_HISTORY_LENGTH)
member.recentHistory.pop_back();
std::string rhblob(member.recentHistory.toBlob());
sqlite3_reset(_sUpdateMemberHistory);
sqlite3_clear_bindings(_sUpdateMemberHistory);
sqlite3_bind_int64(_sUpdateMemberHistory,1,(sqlite3_int64)now);
sqlite3_bind_blob(_sUpdateMemberHistory,2,(const void *)rhblob.data(),(int)rhblob.length(),SQLITE_STATIC);
sqlite3_bind_int64(_sUpdateMemberHistory,3,member.rowid);
sqlite3_step(_sUpdateMemberHistory);
}
// Don't proceed if member is not authorized! ---------------------------
if (!member.authorized)
return NetworkController::NETCONF_QUERY_ACCESS_DENIED;
// Create network configuration -- we create both legacy and new types and send both for backward compatibility
// New network config structure
nc.networkId = Utils::hexStrToU64(network.id);
nc.type = network.isPrivate ? ZT_NETWORK_TYPE_PRIVATE : ZT_NETWORK_TYPE_PUBLIC;
nc.timestamp = now;
nc.revision = network.revision;
nc.issuedTo = member.nodeId;
if (network.enableBroadcast) nc.flags |= ZT_NETWORKCONFIG_FLAG_ENABLE_BROADCAST;
if (network.allowPassiveBridging) nc.flags |= ZT_NETWORKCONFIG_FLAG_ALLOW_PASSIVE_BRIDGING;
memcpy(nc.name,network.name,std::min((unsigned int)ZT_MAX_NETWORK_SHORT_NAME_LENGTH,(unsigned int)strlen(network.name)));
{ // TODO: right now only etherTypes are supported in rules
std::vector<int> allowedEtherTypes;
sqlite3_reset(_sGetEtherTypesFromRuleTable);
sqlite3_bind_text(_sGetEtherTypesFromRuleTable,1,network.id,16,SQLITE_STATIC);
while (sqlite3_step(_sGetEtherTypesFromRuleTable) == SQLITE_ROW) {
if (sqlite3_column_type(_sGetEtherTypesFromRuleTable,0) == SQLITE_NULL) {
allowedEtherTypes.clear();
allowedEtherTypes.push_back(0); // NULL 'allow' matches ANY
break;
} else {
int et = sqlite3_column_int(_sGetEtherTypesFromRuleTable,0);
if ((et >= 0)&&(et <= 0xffff))
allowedEtherTypes.push_back(et);
}
}
std::sort(allowedEtherTypes.begin(),allowedEtherTypes.end());
allowedEtherTypes.erase(std::unique(allowedEtherTypes.begin(),allowedEtherTypes.end()),allowedEtherTypes.end());
for(long i=0;i<(long)allowedEtherTypes.size();++i) {
if ((nc.ruleCount + 2) > ZT_MAX_NETWORK_RULES)
break;
if (allowedEtherTypes[i] > 0) {
nc.rules[nc.ruleCount].t = ZT_NETWORK_RULE_MATCH_ETHERTYPE;
nc.rules[nc.ruleCount].v.etherType = (uint16_t)allowedEtherTypes[i];
++nc.ruleCount;
}
nc.rules[nc.ruleCount++].t = ZT_NETWORK_RULE_ACTION_ACCEPT;
}
}
nc.multicastLimit = network.multicastLimit;
bool amActiveBridge = false;
{
sqlite3_reset(_sGetActiveBridges);
sqlite3_bind_text(_sGetActiveBridges,1,network.id,16,SQLITE_STATIC);
while (sqlite3_step(_sGetActiveBridges) == SQLITE_ROW) {
const char *ab = (const char *)sqlite3_column_text(_sGetActiveBridges,0);
if ((ab)&&(strlen(ab) == 10)) {
const uint64_t ab2 = Utils::hexStrToU64(ab);
nc.addSpecialist(Address(ab2),ZT_NETWORKCONFIG_SPECIALIST_TYPE_ACTIVE_BRIDGE);
if (!strcmp(member.nodeId,ab))
amActiveBridge = true;
}
}
}
// Do not send relays to 1.1.0 since it had a serious bug in using them
// 1.1.0 will still work, it'll just fall back to roots instead of using network preferred relays
if (!((metaData.getUI(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_NODE_MAJOR_VERSION,0) == 1)&&(metaData.getUI(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_NODE_MINOR_VERSION,0) == 1)&&(metaData.getUI(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_NODE_REVISION,0) == 0))) {
sqlite3_reset(_sGetRelays);
sqlite3_bind_text(_sGetRelays,1,network.id,16,SQLITE_STATIC);
while (sqlite3_step(_sGetRelays) == SQLITE_ROW) {
const char *n = (const char *)sqlite3_column_text(_sGetRelays,0);
const char *a = (const char *)sqlite3_column_text(_sGetRelays,1);
if ((n)&&(a)) {
Address node(n);
InetAddress addr(a);
if (node)
nc.addSpecialist(node,ZT_NETWORKCONFIG_SPECIALIST_TYPE_NETWORK_PREFERRED_RELAY);
}
}
}
sqlite3_reset(_sGetRoutes);
sqlite3_bind_text(_sGetRoutes,1,network.id,16,SQLITE_STATIC);
while ((sqlite3_step(_sGetRoutes) == SQLITE_ROW)&&(nc.routeCount < ZT_MAX_NETWORK_ROUTES)) {
ZT_VirtualNetworkRoute *r = &(nc.routes[nc.routeCount]);
memset(r,0,sizeof(ZT_VirtualNetworkRoute));
switch(sqlite3_column_int(_sGetRoutes,3)) { // ipVersion
case 4:
*(reinterpret_cast<InetAddress *>(&(r->target))) = InetAddress((const void *)((const char *)sqlite3_column_blob(_sGetRoutes,0) + 12),4,(unsigned int)sqlite3_column_int(_sGetRoutes,2));
break;
case 6:
*(reinterpret_cast<InetAddress *>(&(r->target))) = InetAddress((const void *)sqlite3_column_blob(_sGetRoutes,0),16,(unsigned int)sqlite3_column_int(_sGetRoutes,2));
break;
default:
continue;
}
if (sqlite3_column_type(_sGetRoutes,1) != SQLITE_NULL) {
switch(sqlite3_column_int(_sGetRoutes,3)) { // ipVersion
case 4:
*(reinterpret_cast<InetAddress *>(&(r->via))) = InetAddress((const void *)((const char *)sqlite3_column_blob(_sGetRoutes,1) + 12),4,0);
break;
case 6:
*(reinterpret_cast<InetAddress *>(&(r->via))) = InetAddress((const void *)sqlite3_column_blob(_sGetRoutes,1),16,0);
break;
default:
continue;
}
}
r->flags = (uint16_t)sqlite3_column_int(_sGetRoutes,4);
r->metric = (uint16_t)sqlite3_column_int(_sGetRoutes,5);
++nc.routeCount;
}
// Assign special IPv6 addresses if these are enabled
if (((network.flags & ZT_DB_NETWORK_FLAG_ZT_MANAGED_V6_RFC4193) != 0)&&(nc.staticIpCount < ZT_MAX_ZT_ASSIGNED_ADDRESSES)) {
nc.staticIps[nc.staticIpCount++] = InetAddress::makeIpv6rfc4193(nwid,identity.address().toInt());
nc.flags |= ZT_NETWORKCONFIG_FLAG_ENABLE_IPV6_NDP_EMULATION;
}
if (((network.flags & ZT_DB_NETWORK_FLAG_ZT_MANAGED_V6_6PLANE) != 0)&&(nc.staticIpCount < ZT_MAX_ZT_ASSIGNED_ADDRESSES)) {
nc.staticIps[nc.staticIpCount++] = InetAddress::makeIpv66plane(nwid,identity.address().toInt());
nc.flags |= ZT_NETWORKCONFIG_FLAG_ENABLE_IPV6_NDP_EMULATION;
}
// Get managed addresses that are assigned to this member
bool haveManagedIpv4AutoAssignment = false;
bool haveManagedIpv6AutoAssignment = false; // "special" NDP-emulated address types do not count
sqlite3_reset(_sGetIpAssignmentsForNode);
sqlite3_bind_text(_sGetIpAssignmentsForNode,1,network.id,16,SQLITE_STATIC);
sqlite3_bind_text(_sGetIpAssignmentsForNode,2,member.nodeId,10,SQLITE_STATIC);
while (sqlite3_step(_sGetIpAssignmentsForNode) == SQLITE_ROW) {
const unsigned char *const ipbytes = (const unsigned char *)sqlite3_column_blob(_sGetIpAssignmentsForNode,0);
if ((!ipbytes)||(sqlite3_column_bytes(_sGetIpAssignmentsForNode,0) != 16))
continue;
//const int ipNetmaskBits = sqlite3_column_int(_sGetIpAssignmentsForNode,1);
const int ipVersion = sqlite3_column_int(_sGetIpAssignmentsForNode,2);
InetAddress ip;
if (ipVersion == 4)
ip = InetAddress(ipbytes + 12,4,0);
else if (ipVersion == 6)
ip = InetAddress(ipbytes,16,0);
else continue;
// IP assignments are only pushed if there is a corresponding local route. We also now get the netmask bits from
// this route, ignoring the netmask bits field of the assigned IP itself. Using that was worthless and a source
// of user error / poor UX.
int routedNetmaskBits = 0;
for(unsigned int rk=0;rk<nc.routeCount;++rk) {
if ( (!nc.routes[rk].via.ss_family) && (reinterpret_cast<const InetAddress *>(&(nc.routes[rk].target))->containsAddress(ip)) )
routedNetmaskBits = reinterpret_cast<const InetAddress *>(&(nc.routes[rk].target))->netmaskBits();
}
if (routedNetmaskBits > 0) {
if (nc.staticIpCount < ZT_MAX_ZT_ASSIGNED_ADDRESSES) {
ip.setPort(routedNetmaskBits);
nc.staticIps[nc.staticIpCount++] = ip;
}
if (ipVersion == 4)
haveManagedIpv4AutoAssignment = true;
else if (ipVersion == 6)
haveManagedIpv6AutoAssignment = true;
}
}
// Auto-assign IPv6 address if auto-assignment is enabled and it's needed
if ( ((network.flags & ZT_DB_NETWORK_FLAG_ZT_MANAGED_V6_AUTO_ASSIGN) != 0) && (!haveManagedIpv6AutoAssignment) && (!amActiveBridge) ) {
sqlite3_reset(_sGetIpAssignmentPools);
sqlite3_bind_text(_sGetIpAssignmentPools,1,network.id,16,SQLITE_STATIC);
sqlite3_bind_int(_sGetIpAssignmentPools,2,6); // 6 == IPv6
while (sqlite3_step(_sGetIpAssignmentPools) == SQLITE_ROW) {
const uint8_t *const ipRangeStartB = reinterpret_cast<const unsigned char *>(sqlite3_column_blob(_sGetIpAssignmentPools,0));
const uint8_t *const ipRangeEndB = reinterpret_cast<const unsigned char *>(sqlite3_column_blob(_sGetIpAssignmentPools,1));
if ((!ipRangeStartB)||(!ipRangeEndB)||(sqlite3_column_bytes(_sGetIpAssignmentPools,0) != 16)||(sqlite3_column_bytes(_sGetIpAssignmentPools,1) != 16))
continue;
uint64_t s[2],e[2],x[2],xx[2];
memcpy(s,ipRangeStartB,16);
memcpy(e,ipRangeEndB,16);
s[0] = Utils::ntoh(s[0]);
s[1] = Utils::ntoh(s[1]);
e[0] = Utils::ntoh(e[0]);
e[1] = Utils::ntoh(e[1]);
x[0] = s[0];
x[1] = s[1];
for(unsigned int trialCount=0;trialCount<1000;++trialCount) {
if ((trialCount == 0)&&(e[1] > s[1])&&((e[1] - s[1]) >= 0xffffffffffULL)) {
// First see if we can just cram a ZeroTier ID into the higher 64 bits. If so do that.
xx[0] = Utils::hton(x[0]);
xx[1] = Utils::hton(x[1] + identity.address().toInt());
} else {
// Otherwise pick random addresses -- this technically doesn't explore the whole range if the lower 64 bit range is >= 1 but that won't matter since that would be huge anyway
Utils::getSecureRandom((void *)xx,16);
if ((e[0] > s[0]))
xx[0] %= (e[0] - s[0]);
else xx[0] = 0;
if ((e[1] > s[1]))
xx[1] %= (e[1] - s[1]);
else xx[1] = 0;
xx[0] = Utils::hton(x[0] + xx[0]);
xx[1] = Utils::hton(x[1] + xx[1]);
}
InetAddress ip6((const void *)xx,16,0);
// Check if this IP is within a local-to-Ethernet routed network
int routedNetmaskBits = 0;
for(unsigned int rk=0;rk<nc.routeCount;++rk) {
if ( (!nc.routes[rk].via.ss_family) && (nc.routes[rk].target.ss_family == AF_INET6) && (reinterpret_cast<const InetAddress *>(&(nc.routes[rk].target))->containsAddress(ip6)) )
routedNetmaskBits = reinterpret_cast<const InetAddress *>(&(nc.routes[rk].target))->netmaskBits();
}
// If it's routed, then try to claim and assign it and if successful end loop
if (routedNetmaskBits > 0) {
sqlite3_reset(_sCheckIfIpIsAllocated);
sqlite3_bind_text(_sCheckIfIpIsAllocated,1,network.id,16,SQLITE_STATIC);
sqlite3_bind_blob(_sCheckIfIpIsAllocated,2,(const void *)ip6.rawIpData(),16,SQLITE_STATIC);
sqlite3_bind_int(_sCheckIfIpIsAllocated,3,6); // 6 == IPv6
sqlite3_bind_int(_sCheckIfIpIsAllocated,4,(int)0 /*ZT_IP_ASSIGNMENT_TYPE_ADDRESS*/);
if (sqlite3_step(_sCheckIfIpIsAllocated) != SQLITE_ROW) {
// No rows returned, so the IP is available
sqlite3_reset(_sAllocateIp);
sqlite3_bind_text(_sAllocateIp,1,network.id,16,SQLITE_STATIC);
sqlite3_bind_text(_sAllocateIp,2,member.nodeId,10,SQLITE_STATIC);
sqlite3_bind_int(_sAllocateIp,3,(int)0 /*ZT_IP_ASSIGNMENT_TYPE_ADDRESS*/);
sqlite3_bind_blob(_sAllocateIp,4,(const void *)ip6.rawIpData(),16,SQLITE_STATIC);
sqlite3_bind_int(_sAllocateIp,5,routedNetmaskBits); // IP netmask bits from matching route
sqlite3_bind_int(_sAllocateIp,6,6); // 6 == IPv6
if (sqlite3_step(_sAllocateIp) == SQLITE_DONE) {
ip6.setPort(routedNetmaskBits);
if (nc.staticIpCount < ZT_MAX_ZT_ASSIGNED_ADDRESSES)
nc.staticIps[nc.staticIpCount++] = ip6;
break;
}
}
}
}
}
}
// Auto-assign IPv4 address if auto-assignment is enabled and it's needed
if ( ((network.flags & ZT_DB_NETWORK_FLAG_ZT_MANAGED_V4_AUTO_ASSIGN) != 0) && (!haveManagedIpv4AutoAssignment) && (!amActiveBridge) ) {
sqlite3_reset(_sGetIpAssignmentPools);
sqlite3_bind_text(_sGetIpAssignmentPools,1,network.id,16,SQLITE_STATIC);
sqlite3_bind_int(_sGetIpAssignmentPools,2,4); // 4 == IPv4
while (sqlite3_step(_sGetIpAssignmentPools) == SQLITE_ROW) {
const unsigned char *ipRangeStartB = reinterpret_cast<const unsigned char *>(sqlite3_column_blob(_sGetIpAssignmentPools,0));
const unsigned char *ipRangeEndB = reinterpret_cast<const unsigned char *>(sqlite3_column_blob(_sGetIpAssignmentPools,1));
if ((!ipRangeStartB)||(!ipRangeEndB)||(sqlite3_column_bytes(_sGetIpAssignmentPools,0) != 16)||(sqlite3_column_bytes(_sGetIpAssignmentPools,1) != 16))
continue;
uint32_t ipRangeStart = Utils::ntoh(*(reinterpret_cast<const uint32_t *>(ipRangeStartB + 12)));
uint32_t ipRangeEnd = Utils::ntoh(*(reinterpret_cast<const uint32_t *>(ipRangeEndB + 12)));
if ((ipRangeEnd <= ipRangeStart)||(ipRangeStart == 0))
continue;
uint32_t ipRangeLen = ipRangeEnd - ipRangeStart;
// Start with the LSB of the member's address
uint32_t ipTrialCounter = (uint32_t)(identity.address().toInt() & 0xffffffff);
for(uint32_t k=ipRangeStart,trialCount=0;(k<=ipRangeEnd)&&(trialCount < 1000);++k,++trialCount) {
uint32_t ip = (ipRangeLen > 0) ? (ipRangeStart + (ipTrialCounter % ipRangeLen)) : ipRangeStart;
++ipTrialCounter;
if ((ip & 0x000000ff) == 0x000000ff)
continue; // don't allow addresses that end in .255
// Check if this IP is within a local-to-Ethernet routed network
int routedNetmaskBits = 0;
for(unsigned int rk=0;rk<nc.routeCount;++rk) {
if ((!nc.routes[rk].via.ss_family)&&(nc.routes[rk].target.ss_family == AF_INET)) {
uint32_t targetIp = Utils::ntoh((uint32_t)(reinterpret_cast<const struct sockaddr_in *>(&(nc.routes[rk].target))->sin_addr.s_addr));
int targetBits = Utils::ntoh((uint16_t)(reinterpret_cast<const struct sockaddr_in *>(&(nc.routes[rk].target))->sin_port));
if ((ip & (0xffffffff << (32 - targetBits))) == targetIp) {
routedNetmaskBits = targetBits;
break;
}
}
}
// If it's routed, then try to claim and assign it and if successful end loop
if (routedNetmaskBits > 0) {
uint32_t ipBlob[4]; // actually a 16-byte blob, we put IPv4s in the last 4 bytes
ipBlob[0] = 0; ipBlob[1] = 0; ipBlob[2] = 0; ipBlob[3] = Utils::hton(ip);
sqlite3_reset(_sCheckIfIpIsAllocated);
sqlite3_bind_text(_sCheckIfIpIsAllocated,1,network.id,16,SQLITE_STATIC);
sqlite3_bind_blob(_sCheckIfIpIsAllocated,2,(const void *)ipBlob,16,SQLITE_STATIC);
sqlite3_bind_int(_sCheckIfIpIsAllocated,3,4); // 4 == IPv4
sqlite3_bind_int(_sCheckIfIpIsAllocated,4,(int)0 /*ZT_IP_ASSIGNMENT_TYPE_ADDRESS*/);
if (sqlite3_step(_sCheckIfIpIsAllocated) != SQLITE_ROW) {
// No rows returned, so the IP is available
sqlite3_reset(_sAllocateIp);
sqlite3_bind_text(_sAllocateIp,1,network.id,16,SQLITE_STATIC);
sqlite3_bind_text(_sAllocateIp,2,member.nodeId,10,SQLITE_STATIC);
sqlite3_bind_int(_sAllocateIp,3,(int)0 /*ZT_IP_ASSIGNMENT_TYPE_ADDRESS*/);
sqlite3_bind_blob(_sAllocateIp,4,(const void *)ipBlob,16,SQLITE_STATIC);
sqlite3_bind_int(_sAllocateIp,5,routedNetmaskBits); // IP netmask bits from matching route
sqlite3_bind_int(_sAllocateIp,6,4); // 4 == IPv4
if (sqlite3_step(_sAllocateIp) == SQLITE_DONE) {
if (nc.staticIpCount < ZT_MAX_ZT_ASSIGNED_ADDRESSES) {
struct sockaddr_in *const v4ip = reinterpret_cast<struct sockaddr_in *>(&(nc.staticIps[nc.staticIpCount++]));
v4ip->sin_family = AF_INET;
v4ip->sin_port = Utils::hton((uint16_t)routedNetmaskBits);
v4ip->sin_addr.s_addr = Utils::hton(ip);
}
break;
}
}
}
}
}
}
} // end lock
// Perform signing outside lock to enable concurrency
if (network.isPrivate) {
CertificateOfMembership com(now,ZT_NETWORK_COM_DEFAULT_REVISION_MAX_DELTA,nwid,identity.address());
if (com.sign(signingId)) {
nc.com = com;
} else {
return NETCONF_QUERY_INTERNAL_SERVER_ERROR;
}
}
return NetworkController::NETCONF_QUERY_OK;
}
unsigned int SqliteNetworkController::handleControlPlaneHttpGET(
const std::vector<std::string> &path,
const std::map<std::string,std::string> &urlArgs,
const std::map<std::string,std::string> &headers,
const std::string &body,
std::string &responseBody,
std::string &responseContentType)
{
Mutex::Lock _l(_lock);
return _doCPGet(path,urlArgs,headers,body,responseBody,responseContentType);
}
unsigned int SqliteNetworkController::handleControlPlaneHttpPOST(
const std::vector<std::string> &path,
const std::map<std::string,std::string> &urlArgs,
const std::map<std::string,std::string> &headers,
const std::string &body,
std::string &responseBody,
std::string &responseContentType)
{
if (path.empty())
return 404;
Mutex::Lock _l(_lock);
_backupNeeded = true;
if (path[0] == "network") {
if ((path.size() >= 2)&&(path[1].length() == 16)) {
uint64_t nwid = Utils::hexStrToU64(path[1].c_str());
char nwids[24];
Utils::snprintf(nwids,sizeof(nwids),"%.16llx",(unsigned long long)nwid);
int64_t revision = 0;
sqlite3_reset(_sGetNetworkRevision);
sqlite3_bind_text(_sGetNetworkRevision,1,nwids,16,SQLITE_STATIC);
bool networkExists = false;
if (sqlite3_step(_sGetNetworkRevision) == SQLITE_ROW) {
networkExists = true;
revision = sqlite3_column_int64(_sGetNetworkRevision,0);
}
if (path.size() >= 3) {
if (!networkExists)
return 404;