-
Notifications
You must be signed in to change notification settings - Fork 1.7k
/
OneService.cpp
3943 lines (3518 loc) · 134 KB
/
OneService.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
/*
* Copyright (c)2013-2020 ZeroTier, Inc.
*
* Use of this software is governed by the Business Source License included
* in the LICENSE.TXT file in the project's root directory.
*
* Change Date: 2026-01-01
*
* On the date above, in accordance with the Business Source License, use
* of this software will be governed by version 2.0 of the Apache License.
*/
/****/
#include <exception>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
#include <string>
#include <map>
#include <vector>
#include <algorithm>
#include <list>
#include <thread>
#include <mutex>
#include <condition_variable>
#include "../version.h"
#include "../include/ZeroTierOne.h"
#include "../node/Constants.hpp"
#include "../node/Mutex.hpp"
#include "../node/Node.hpp"
#include "../node/Utils.hpp"
#include "../node/InetAddress.hpp"
#include "../node/MAC.hpp"
#include "../node/Identity.hpp"
#include "../node/World.hpp"
#include "../node/Salsa20.hpp"
#include "../node/Poly1305.hpp"
#include "../node/SHA512.hpp"
#include "../node/Bond.hpp"
#include "../node/Peer.hpp"
#include "../osdep/Phy.hpp"
#include "../osdep/OSUtils.hpp"
#include "../osdep/Http.hpp"
#include "../osdep/PortMapper.hpp"
#include "../osdep/Binder.hpp"
#include "../osdep/ManagedRoute.hpp"
#include "../osdep/BlockingQueue.hpp"
#include "OneService.hpp"
#include "SoftwareUpdater.hpp"
#include <cpp-httplib/httplib.h>
#if ZT_SSO_ENABLED
#include <zeroidc.h>
#endif
#ifdef __WINDOWS__
#include <winsock2.h>
#include <windows.h>
#include <shlobj.h>
#include <netioapi.h>
#include <iphlpapi.h>
//#include <unistd.h>
#define stat _stat
#else
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <sys/wait.h>
#include <unistd.h>
#include <ifaddrs.h>
#endif
#ifdef __APPLE__
#include "../osdep/MacDNSHelper.hpp"
#elif defined(__WINDOWS__)
#include "../osdep/WinDNSHelper.hpp"
#include "../osdep/WinFWHelper.hpp"
#endif
#ifdef ZT_USE_SYSTEM_HTTP_PARSER
#include <http_parser.h>
#else
#include "../ext/http-parser/http_parser.h"
#endif
#include "../node/Metrics.hpp"
#if ZT_VAULT_SUPPORT
extern "C" {
#include <curl/curl.h>
}
#endif
#include <nlohmann/json.hpp>
#include <inja/inja.hpp>
using json = nlohmann::json;
#include "../controller/EmbeddedNetworkController.hpp"
#include "../controller/PostgreSQL.hpp"
#include "../controller/Redis.hpp"
#include "../osdep/EthernetTap.hpp"
#ifdef __WINDOWS__
#include "../osdep/WindowsEthernetTap.hpp"
#endif
#ifndef ZT_SOFTWARE_UPDATE_DEFAULT
#define ZT_SOFTWARE_UPDATE_DEFAULT "disable"
#endif
// Sanity limits for HTTP
#define ZT_MAX_HTTP_MESSAGE_SIZE (1024 * 1024 * 64)
#define ZT_MAX_HTTP_CONNECTIONS 65536
// Interface metric for ZeroTier taps -- this ensures that if we are on WiFi and also
// bridged via ZeroTier to the same LAN traffic will (if the OS is sane) prefer WiFi.
#define ZT_IF_METRIC 5000
// How often to check for new multicast subscriptions on a tap device
#define ZT_TAP_CHECK_MULTICAST_INTERVAL 5000
// TCP fallback relay (run by ZeroTier, Inc. -- this will eventually go away)
#ifndef ZT_SDK
#define ZT_TCP_FALLBACK_RELAY "204.80.128.1/443"
#endif
// Frequency at which we re-resolve the TCP fallback relay
#define ZT_TCP_FALLBACK_RERESOLVE_DELAY 86400000
// Attempt to engage TCP fallback after this many ms of no reply to packets sent to global-scope IPs
#define ZT_TCP_FALLBACK_AFTER 60000
// How often to check for local interface addresses
#define ZT_LOCAL_INTERFACE_CHECK_INTERVAL 60000
// Maximum write buffer size for outgoing TCP connections (sanity limit)
#define ZT_TCP_MAX_WRITEQ_SIZE 33554432
// TCP activity timeout
#define ZT_TCP_ACTIVITY_TIMEOUT 60000
#if ZT_VAULT_SUPPORT
size_t curlResponseWrite(void *ptr, size_t size, size_t nmemb, std::string *data)
{
data->append((char*)ptr, size * nmemb);
return size * nmemb;
}
#endif
namespace ZeroTier {
std::string ssoResponseTemplate = R"""(
<!doctype html>
<html class="no-js" lang="">
<head>
<meta charset="utf-8">
<meta http-equiv="x-ua-compatible" content="ie=edge">
<title>Network SSO Login {{ networkId }}</title>
<meta name="description" content="">
<meta name="viewport" content="width=device-width, initial-scale=1">
<style type="text/css">
html,body {
background: #eeeeee;
margin: 0;
padding: 0;
font-family: "System Sans Serif";
font-weight: normal;
font-size: 12pt;
height: 100%;
width: 100%;
}
.container {
position: absolute;
left: 50%;
top: 50%;
-webkit-transform: translate(-50%, -50%);
transform: translate(-50%, -50%);
}
.iconwrapper {
margin: 10px 10px 10px 10px;
}
</style>
</head>
<body>
<div class="container">
<div class="iconwrapper">
<svg id="Layer_1" width="225px" height="225px" data-name="Layer 1" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 225 225"><defs><style>.cls-1{fill:#fdb25d;}.cls-2{fill:none;stroke:#000;stroke-miterlimit:10;stroke-width:6.99px;}</style></defs><rect class="cls-1" width="225" height="225" rx="35.74"/><line class="cls-2" x1="25.65" y1="32.64" x2="199.35" y2="32.64"/><line class="cls-2" x1="112.5" y1="201.02" x2="112.5" y2="32.64"/><circle class="cls-2" cx="112.5" cy="115.22" r="56.54"/></svg>
</div>
<div class="text">{{ messageText }}</div>
</div>
</body>
</html>
)""";
bool bearerTokenValid(const std::string authHeader, const std::string &checkToken) {
std::vector<std::string> tokens = OSUtils::split(authHeader.c_str(), " ", NULL, NULL);
if (tokens.size() != 2) {
return false;
}
std::string bearer = tokens[0];
std::string token = tokens[1];
std::transform(bearer.begin(), bearer.end(), bearer.begin(), [](unsigned char c){return std::tolower(c);});
if (bearer != "bearer") {
return false;
}
if (token != checkToken) {
return false;
}
return true;
}
#if ZT_DEBUG==1
std::string dump_headers(const httplib::Headers &headers) {
std::string s;
char buf[BUFSIZ];
for (auto it = headers.begin(); it != headers.end(); ++it) {
const auto &x = *it;
snprintf(buf, sizeof(buf), "%s: %s\n", x.first.c_str(), x.second.c_str());
s += buf;
}
return s;
}
std::string http_log(const httplib::Request &req, const httplib::Response &res) {
std::string s;
char buf[BUFSIZ];
s += "================================\n";
snprintf(buf, sizeof(buf), "%s %s %s", req.method.c_str(),
req.version.c_str(), req.path.c_str());
s += buf;
std::string query;
for (auto it = req.params.begin(); it != req.params.end(); ++it) {
const auto &x = *it;
snprintf(buf, sizeof(buf), "%c%s=%s",
(it == req.params.begin()) ? '?' : '&', x.first.c_str(),
x.second.c_str());
query += buf;
}
snprintf(buf, sizeof(buf), "%s\n", query.c_str());
s += buf;
s += dump_headers(req.headers);
s += "--------------------------------\n";
snprintf(buf, sizeof(buf), "%d %s\n", res.status, res.version.c_str());
s += buf;
s += dump_headers(res.headers);
s += "\n";
if (!res.body.empty()) { s += res.body; }
s += "\n";
return s;
}
#endif
// Configured networks
class NetworkState
{
public:
NetworkState()
: _webPort(9993)
, _tap((EthernetTap *)0)
#if ZT_SSO_ENABLED
, _idc(nullptr)
#endif
{
// Real defaults are in network 'up' code in network event handler
_settings.allowManaged = true;
_settings.allowGlobal = false;
_settings.allowDefault = false;
_settings.allowDNS = false;
memset(&_config, 0, sizeof(ZT_VirtualNetworkConfig));
}
~NetworkState()
{
this->_managedRoutes.clear();
this->_tap.reset();
#if ZT_SSO_ENABLED
if (_idc) {
zeroidc::zeroidc_stop(_idc);
zeroidc::zeroidc_delete(_idc);
_idc = nullptr;
}
#endif
}
void setWebPort(unsigned int port) {
_webPort = port;
}
void setTap(std::shared_ptr<EthernetTap> tap) {
this->_tap = tap;
}
std::shared_ptr<EthernetTap> tap() const {
return _tap;
}
OneService::NetworkSettings settings() const {
return _settings;
}
void setSettings(const OneService::NetworkSettings &settings) {
_settings = settings;
}
void setAllowManaged(bool allow) {
_settings.allowManaged = allow;
}
bool allowManaged() const {
return _settings.allowManaged;
}
void setAllowGlobal(bool allow) {
_settings.allowGlobal = allow;
}
bool allowGlobal() const {
return _settings.allowGlobal;
}
void setAllowDefault(bool allow) {
_settings.allowDefault = allow;
}
bool allowDefault() const {
return _settings.allowDefault;
}
void setAllowDNS(bool allow) {
_settings.allowDNS = allow;
}
bool allowDNS() const {
return _settings.allowDNS;
}
std::vector<InetAddress> allowManagedWhitelist() const {
return _settings.allowManagedWhitelist;
}
void addToAllowManagedWhiteList(const InetAddress& addr) {
_settings.allowManagedWhitelist.push_back(addr);
}
const ZT_VirtualNetworkConfig& config() {
return _config;
}
void setConfig(const ZT_VirtualNetworkConfig *nwc) {
memcpy(&_config, nwc, sizeof(ZT_VirtualNetworkConfig));
if (_config.ssoEnabled && _config.ssoVersion == 1) {
#if ZT_SSO_ENABLED
if (_idc == nullptr)
{
assert(_config.issuerURL != nullptr);
assert(_config.ssoClientID != nullptr);
assert(_config.centralAuthURL != nullptr);
assert(_config.ssoProvider != nullptr);
_idc = zeroidc::zeroidc_new(
_config.issuerURL,
_config.ssoClientID,
_config.centralAuthURL,
_config.ssoProvider,
_webPort
);
if (_idc == nullptr) {
fprintf(stderr, "idc is null\n");
return;
}
}
zeroidc::zeroidc_set_nonce_and_csrf(
_idc,
_config.ssoState,
_config.ssoNonce
);
char* url = zeroidc::zeroidc_get_auth_url(_idc);
memcpy(_config.authenticationURL, url, strlen(url));
_config.authenticationURL[strlen(url)] = 0;
zeroidc::free_cstr(url);
if (zeroidc::zeroidc_is_running(_idc) && nwc->status == ZT_NETWORK_STATUS_AUTHENTICATION_REQUIRED) {
zeroidc::zeroidc_kick_refresh_thread(_idc);
}
#endif
}
}
std::vector<InetAddress>& managedIps() {
return _managedIps;
}
void setManagedIps(const std::vector<InetAddress> &managedIps) {
_managedIps = managedIps;
}
std::map< InetAddress, SharedPtr<ManagedRoute> >& managedRoutes() {
return _managedRoutes;
}
char* doTokenExchange(const char *code) {
char *ret = nullptr;
#if ZT_SSO_ENABLED
if (_idc == nullptr) {
fprintf(stderr, "ainfo or idc null\n");
return ret;
}
ret = zeroidc::zeroidc_token_exchange(_idc, code);
zeroidc::zeroidc_set_nonce_and_csrf(
_idc,
_config.ssoState,
_config.ssoNonce
);
char* url = zeroidc::zeroidc_get_auth_url(_idc);
memcpy(_config.authenticationURL, url, strlen(url));
_config.authenticationURL[strlen(url)] = 0;
zeroidc::free_cstr(url);
#endif
return ret;
}
uint64_t getExpiryTime() {
#if ZT_SSO_ENABLED
if (_idc == nullptr) {
fprintf(stderr, "idc is null\n");
return 0;
}
return zeroidc::zeroidc_get_exp_time(_idc);
#else
return 0;
#endif
}
private:
unsigned int _webPort;
std::shared_ptr<EthernetTap> _tap;
ZT_VirtualNetworkConfig _config; // memcpy() of raw config from core
std::vector<InetAddress> _managedIps;
std::map< InetAddress, SharedPtr<ManagedRoute> > _managedRoutes;
OneService::NetworkSettings _settings;
#if ZT_SSO_ENABLED
zeroidc::ZeroIDC *_idc;
#endif
};
namespace {
static const InetAddress NULL_INET_ADDR;
// Fake TLS hello for TCP tunnel outgoing connections (TUNNELED mode)
static const char ZT_TCP_TUNNEL_HELLO[9] = { 0x17,0x03,0x03,0x00,0x04,(char)ZEROTIER_ONE_VERSION_MAJOR,(char)ZEROTIER_ONE_VERSION_MINOR,(char)((ZEROTIER_ONE_VERSION_REVISION >> 8) & 0xff),(char)(ZEROTIER_ONE_VERSION_REVISION & 0xff) };
static std::string _trimString(const std::string &s)
{
unsigned long end = (unsigned long)s.length();
while (end) {
char c = s[end - 1];
if ((c == ' ')||(c == '\r')||(c == '\n')||(!c)||(c == '\t'))
--end;
else break;
}
unsigned long start = 0;
while (start < end) {
char c = s[start];
if ((c == ' ')||(c == '\r')||(c == '\n')||(!c)||(c == '\t'))
++start;
else break;
}
return s.substr(start,end - start);
}
static void _networkToJson(nlohmann::json &nj,NetworkState &ns)
{
char tmp[256];
const char *nstatus = "",*ntype = "";
switch(ns.config().status) {
case ZT_NETWORK_STATUS_REQUESTING_CONFIGURATION: nstatus = "REQUESTING_CONFIGURATION"; break;
case ZT_NETWORK_STATUS_OK: nstatus = "OK"; break;
case ZT_NETWORK_STATUS_ACCESS_DENIED: nstatus = "ACCESS_DENIED"; break;
case ZT_NETWORK_STATUS_NOT_FOUND: nstatus = "NOT_FOUND"; break;
case ZT_NETWORK_STATUS_PORT_ERROR: nstatus = "PORT_ERROR"; break;
case ZT_NETWORK_STATUS_CLIENT_TOO_OLD: nstatus = "CLIENT_TOO_OLD"; break;
case ZT_NETWORK_STATUS_AUTHENTICATION_REQUIRED: nstatus = "AUTHENTICATION_REQUIRED"; break;
}
switch(ns.config().type) {
case ZT_NETWORK_TYPE_PRIVATE: ntype = "PRIVATE"; break;
case ZT_NETWORK_TYPE_PUBLIC: ntype = "PUBLIC"; break;
}
OSUtils::ztsnprintf(tmp,sizeof(tmp),"%.16llx",ns.config().nwid);
nj["id"] = tmp;
nj["nwid"] = tmp;
OSUtils::ztsnprintf(tmp,sizeof(tmp),"%.2x:%.2x:%.2x:%.2x:%.2x:%.2x",(unsigned int)((ns.config().mac >> 40) & 0xff),(unsigned int)((ns.config().mac >> 32) & 0xff),(unsigned int)((ns.config().mac >> 24) & 0xff),(unsigned int)((ns.config().mac >> 16) & 0xff),(unsigned int)((ns.config().mac >> 8) & 0xff),(unsigned int)(ns.config().mac & 0xff));
nj["mac"] = tmp;
nj["name"] = ns.config().name;
nj["status"] = nstatus;
nj["type"] = ntype;
nj["mtu"] = ns.config().mtu;
nj["dhcp"] = (bool)(ns.config().dhcp != 0);
nj["bridge"] = (bool)(ns.config().bridge != 0);
nj["broadcastEnabled"] = (bool)(ns.config().broadcastEnabled != 0);
nj["portError"] = ns.config().portError;
nj["netconfRevision"] = ns.config().netconfRevision;
nj["portDeviceName"] = ns.tap()->deviceName();
OneService::NetworkSettings localSettings = ns.settings();
nj["allowManaged"] = localSettings.allowManaged;
nj["allowGlobal"] = localSettings.allowGlobal;
nj["allowDefault"] = localSettings.allowDefault;
nj["allowDNS"] = localSettings.allowDNS;
nlohmann::json aa = nlohmann::json::array();
for(unsigned int i=0;i<ns.config().assignedAddressCount;++i) {
aa.push_back(reinterpret_cast<const InetAddress *>(&(ns.config().assignedAddresses[i]))->toString(tmp));
}
nj["assignedAddresses"] = aa;
nlohmann::json ra = nlohmann::json::array();
for(unsigned int i=0;i<ns.config().routeCount;++i) {
nlohmann::json rj;
rj["target"] = reinterpret_cast<const InetAddress *>(&(ns.config().routes[i].target))->toString(tmp);
if (ns.config().routes[i].via.ss_family == ns.config().routes[i].target.ss_family)
rj["via"] = reinterpret_cast<const InetAddress *>(&(ns.config().routes[i].via))->toIpString(tmp);
else rj["via"] = nlohmann::json();
rj["flags"] = (int)ns.config().routes[i].flags;
rj["metric"] = (int)ns.config().routes[i].metric;
ra.push_back(rj);
}
nj["routes"] = ra;
nlohmann::json mca = nlohmann::json::array();
for(unsigned int i=0;i<ns.config().multicastSubscriptionCount;++i) {
nlohmann::json m;
m["mac"] = MAC(ns.config().multicastSubscriptions[i].mac).toString(tmp);
m["adi"] = ns.config().multicastSubscriptions[i].adi;
mca.push_back(m);
}
nj["multicastSubscriptions"] = mca;
nlohmann::json m;
m["domain"] = ns.config().dns.domain;
m["servers"] = nlohmann::json::array();
for(int j=0;j<ZT_MAX_DNS_SERVERS;++j) {
InetAddress a(ns.config().dns.server_addr[j]);
if (a.isV4() || a.isV6()) {
char buf[256];
m["servers"].push_back(a.toIpString(buf));
}
}
nj["dns"] = m;
if (ns.config().ssoEnabled) {
const char* authURL = ns.config().authenticationURL;
//fprintf(stderr, "Auth URL: %s\n", authURL);
nj["authenticationURL"] = authURL;
nj["authenticationExpiryTime"] = (ns.getExpiryTime()*1000);
nj["ssoEnabled"] = ns.config().ssoEnabled;
}
}
static void _peerToJson(nlohmann::json &pj,const ZT_Peer *peer, SharedPtr<Bond> &bond, bool isTunneled)
{
char tmp[256];
const char *prole = "";
switch(peer->role) {
case ZT_PEER_ROLE_LEAF: prole = "LEAF"; break;
case ZT_PEER_ROLE_MOON: prole = "MOON"; break;
case ZT_PEER_ROLE_PLANET: prole = "PLANET"; break;
}
OSUtils::ztsnprintf(tmp,sizeof(tmp),"%.10llx",peer->address);
pj["address"] = tmp;
pj["versionMajor"] = peer->versionMajor;
pj["versionMinor"] = peer->versionMinor;
pj["versionRev"] = peer->versionRev;
OSUtils::ztsnprintf(tmp,sizeof(tmp),"%d.%d.%d",peer->versionMajor,peer->versionMinor,peer->versionRev);
pj["version"] = tmp;
pj["latency"] = peer->latency;
pj["role"] = prole;
pj["isBonded"] = peer->isBonded;
pj["tunneled"] = isTunneled;
if (bond && peer->isBonded) {
pj["bondingPolicyCode"] = peer->bondingPolicy;
pj["bondingPolicyStr"] = Bond::getPolicyStrByCode(peer->bondingPolicy);
pj["numAliveLinks"] = peer->numAliveLinks;
pj["numTotalLinks"] = peer->numTotalLinks;
pj["failoverInterval"] = bond->getFailoverInterval();
pj["downDelay"] = bond->getDownDelay();
pj["upDelay"] = bond->getUpDelay();
pj["packetsPerLink"] = bond->getPacketsPerLink();
}
nlohmann::json pa = nlohmann::json::array();
for(unsigned int i=0;i<peer->pathCount;++i) {
int64_t lastSend = peer->paths[i].lastSend;
int64_t lastReceive = peer->paths[i].lastReceive;
nlohmann::json j;
j["address"] = reinterpret_cast<const InetAddress *>(&(peer->paths[i].address))->toString(tmp);
j["lastSend"] = (lastSend < 0) ? 0 : lastSend;
j["lastReceive"] = (lastReceive < 0) ? 0 : lastReceive;
j["trustedPathId"] = peer->paths[i].trustedPathId;
j["active"] = (bool)(peer->paths[i].expired == 0);
j["expired"] = (bool)(peer->paths[i].expired != 0);
j["preferred"] = (bool)(peer->paths[i].preferred != 0);
j["localSocket"] = peer->paths[i].localSocket;
j["localPort"] = peer->paths[i].localPort;
if (bond && peer->isBonded) {
uint64_t now = OSUtils::now();
j["ifname"] = std::string(peer->paths[i].ifname);
j["latencyMean"] = peer->paths[i].latencyMean;
j["latencyVariance"] = peer->paths[i].latencyVariance;
j["packetLossRatio"] = peer->paths[i].packetLossRatio;
j["packetErrorRatio"] = peer->paths[i].packetErrorRatio;
j["assignedFlowCount"] = peer->paths[i].assignedFlowCount;
j["lastInAge"] = (now - lastReceive);
j["lastOutAge"] = (now - lastSend);
j["bonded"] = peer->paths[i].bonded;
j["eligible"] = peer->paths[i].eligible;
j["givenLinkSpeed"] = peer->paths[i].linkSpeed;
j["relativeQuality"] = peer->paths[i].relativeQuality;
}
pa.push_back(j);
}
pj["paths"] = pa;
}
static void _moonToJson(nlohmann::json &mj,const World &world)
{
char tmp[4096];
OSUtils::ztsnprintf(tmp,sizeof(tmp),"%.16llx",world.id());
mj["id"] = tmp;
mj["timestamp"] = world.timestamp();
mj["signature"] = Utils::hex(world.signature().data,ZT_C25519_SIGNATURE_LEN,tmp);
mj["updatesMustBeSignedBy"] = Utils::hex(world.updatesMustBeSignedBy().data,ZT_C25519_PUBLIC_KEY_LEN,tmp);
nlohmann::json ra = nlohmann::json::array();
for(std::vector<World::Root>::const_iterator r(world.roots().begin());r!=world.roots().end();++r) {
nlohmann::json rj;
rj["identity"] = r->identity.toString(false,tmp);
nlohmann::json eps = nlohmann::json::array();
for(std::vector<InetAddress>::const_iterator a(r->stableEndpoints.begin());a!=r->stableEndpoints.end();++a)
eps.push_back(a->toString(tmp));
rj["stableEndpoints"] = eps;
ra.push_back(rj);
}
mj["roots"] = ra;
mj["waiting"] = false;
}
class OneServiceImpl;
static int SnodeVirtualNetworkConfigFunction(ZT_Node *node,void *uptr,void *tptr,uint64_t nwid,void **nuptr,enum ZT_VirtualNetworkConfigOperation op,const ZT_VirtualNetworkConfig *nwconf);
static void SnodeEventCallback(ZT_Node *node,void *uptr,void *tptr,enum ZT_Event event,const void *metaData);
static void SnodeStatePutFunction(ZT_Node *node,void *uptr,void *tptr,enum ZT_StateObjectType type,const uint64_t id[2],const void *data,int len);
static int SnodeStateGetFunction(ZT_Node *node,void *uptr,void *tptr,enum ZT_StateObjectType type,const uint64_t id[2],void *data,unsigned int maxlen);
static int SnodeWirePacketSendFunction(ZT_Node *node,void *uptr,void *tptr,int64_t localSocket,const struct sockaddr_storage *addr,const void *data,unsigned int len,unsigned int ttl);
static void SnodeVirtualNetworkFrameFunction(ZT_Node *node,void *uptr,void *tptr,uint64_t nwid,void **nuptr,uint64_t sourceMac,uint64_t destMac,unsigned int etherType,unsigned int vlanId,const void *data,unsigned int len);
static int SnodePathCheckFunction(ZT_Node *node,void *uptr,void *tptr,uint64_t ztaddr,int64_t localSocket,const struct sockaddr_storage *remoteAddr);
static int SnodePathLookupFunction(ZT_Node *node,void *uptr,void *tptr,uint64_t ztaddr,int family,struct sockaddr_storage *result);
static void StapFrameHandler(void *uptr,void *tptr,uint64_t nwid,const MAC &from,const MAC &to,unsigned int etherType,unsigned int vlanId,const void *data,unsigned int len);
static int ShttpOnMessageBegin(http_parser *parser);
static int ShttpOnUrl(http_parser *parser,const char *ptr,size_t length);
#if (HTTP_PARSER_VERSION_MAJOR >= 2) && (HTTP_PARSER_VERSION_MINOR >= 2)
static int ShttpOnStatus(http_parser *parser,const char *ptr,size_t length);
#else
static int ShttpOnStatus(http_parser *parser);
#endif
static int ShttpOnHeaderField(http_parser *parser,const char *ptr,size_t length);
static int ShttpOnValue(http_parser *parser,const char *ptr,size_t length);
static int ShttpOnHeadersComplete(http_parser *parser);
static int ShttpOnBody(http_parser *parser,const char *ptr,size_t length);
static int ShttpOnMessageComplete(http_parser *parser);
#if (HTTP_PARSER_VERSION_MAJOR >= 2) && (HTTP_PARSER_VERSION_MINOR >= 1)
static const struct http_parser_settings HTTP_PARSER_SETTINGS = {
ShttpOnMessageBegin,
ShttpOnUrl,
ShttpOnStatus,
ShttpOnHeaderField,
ShttpOnValue,
ShttpOnHeadersComplete,
ShttpOnBody,
ShttpOnMessageComplete
};
#else
static const struct http_parser_settings HTTP_PARSER_SETTINGS = {
ShttpOnMessageBegin,
ShttpOnUrl,
ShttpOnHeaderField,
ShttpOnValue,
ShttpOnHeadersComplete,
ShttpOnBody,
ShttpOnMessageComplete
};
#endif
/**
* A TCP connection and related state and buffers
*/
struct TcpConnection
{
enum {
TCP_UNCATEGORIZED_INCOMING, // uncategorized incoming connection
TCP_HTTP_INCOMING,
TCP_HTTP_OUTGOING,
TCP_TUNNEL_OUTGOING // TUNNELED mode proxy outbound connection
} type;
OneServiceImpl *parent;
PhySocket *sock;
InetAddress remoteAddr;
uint64_t lastReceive;
// Used for inbound HTTP connections
http_parser parser;
unsigned long messageSize;
std::string currentHeaderField;
std::string currentHeaderValue;
std::string url;
std::string status;
std::map< std::string,std::string > headers;
std::string readq;
std::string writeq;
Mutex writeq_m;
};
struct OneServiceIncomingPacket
{
uint64_t now;
int64_t sock;
struct sockaddr_storage from;
unsigned int size;
uint8_t data[ZT_MAX_MTU];
};
class OneServiceImpl : public OneService
{
public:
// begin member variables --------------------------------------------------
const std::string _homePath;
std::string _authToken;
std::string _metricsToken;
std::string _controllerDbPath;
const std::string _networksPath;
const std::string _moonsPath;
EmbeddedNetworkController *_controller;
Phy<OneServiceImpl *> _phy;
Node *_node;
SoftwareUpdater *_updater;
bool _updateAutoApply;
httplib::Server _controlPlane;
httplib::Server _controlPlaneV6;
std::thread _serverThread;
std::thread _serverThreadV6;
bool _serverThreadRunning;
bool _serverThreadRunningV6;
bool _allowTcpFallbackRelay;
bool _forceTcpRelay;
bool _allowSecondaryPort;
bool _enableWebServer;
unsigned int _primaryPort;
unsigned int _secondaryPort;
unsigned int _tertiaryPort;
volatile unsigned int _udpPortPickerCounter;
// Local configuration and memo-ized information from it
json _localConfig;
Hashtable< uint64_t,std::vector<InetAddress> > _v4Hints;
Hashtable< uint64_t,std::vector<InetAddress> > _v6Hints;
Hashtable< uint64_t,std::vector<InetAddress> > _v4Blacklists;
Hashtable< uint64_t,std::vector<InetAddress> > _v6Blacklists;
std::vector< InetAddress > _globalV4Blacklist;
std::vector< InetAddress > _globalV6Blacklist;
std::vector< InetAddress > _allowManagementFrom;
std::vector< std::string > _interfacePrefixBlacklist;
Mutex _localConfig_m;
std::vector<InetAddress> explicitBind;
/*
* To attempt to handle NAT/gateway craziness we use three local UDP ports:
*
* [0] is the normal/default port, usually 9993
* [1] is a port derived from our ZeroTier address
* [2] is a port computed from the normal/default for use with uPnP/NAT-PMP mappings
*
* [2] exists because on some gateways trying to do regular NAT-t interferes
* destructively with uPnP port mapping behavior in very weird buggy ways.
* It's only used if uPnP/NAT-PMP is enabled in this build.
*/
unsigned int _ports[3];
Binder _binder;
// Time we last received a packet from a global address
uint64_t _lastDirectReceiveFromGlobal;
#ifdef ZT_TCP_FALLBACK_RELAY
InetAddress _fallbackRelayAddress;
uint64_t _lastSendToGlobalV4;
#endif
// Last potential sleep/wake event
uint64_t _lastRestart;
// Deadline for the next background task service function
volatile int64_t _nextBackgroundTaskDeadline;
std::map<uint64_t,NetworkState> _nets;
Mutex _nets_m;
// Active TCP/IP connections
std::vector< TcpConnection * > _tcpConnections;
Mutex _tcpConnections_m;
TcpConnection *_tcpFallbackTunnel;
// Termination status information
ReasonForTermination _termReason;
std::string _fatalErrorMessage;
Mutex _termReason_m;
// uPnP/NAT-PMP port mapper if enabled
bool _portMappingEnabled; // local.conf settings
#ifdef ZT_USE_MINIUPNPC
PortMapper *_portMapper;
#endif
// HashiCorp Vault Settings
#if ZT_VAULT_SUPPORT
bool _vaultEnabled;
std::string _vaultURL;
std::string _vaultToken;
std::string _vaultPath; // defaults to cubbyhole/zerotier/identity.secret for per-access key storage
#endif
// Set to false to force service to stop
volatile bool _run;
Mutex _run_m;
RedisConfig *_rc;
std::string _ssoRedirectURL;
// end member variables ----------------------------------------------------
OneServiceImpl(const char *hp,unsigned int port) :
_homePath((hp) ? hp : ".")
,_controllerDbPath(_homePath + ZT_PATH_SEPARATOR_S "controller.d")
,_networksPath(_homePath + ZT_PATH_SEPARATOR_S "networks.d")
,_moonsPath(_homePath + ZT_PATH_SEPARATOR_S "moons.d")
,_controller((EmbeddedNetworkController *)0)
,_phy(this,false,true)
,_node((Node *)0)
,_updater((SoftwareUpdater *)0)
,_updateAutoApply(false)
,_controlPlane()
,_controlPlaneV6()
,_serverThread()
,_serverThreadV6()
,_serverThreadRunning(false)
,_serverThreadRunningV6(false)
,_forceTcpRelay(false)
,_primaryPort(port)
,_udpPortPickerCounter(0)
,_lastDirectReceiveFromGlobal(0)
#ifdef ZT_TCP_FALLBACK_RELAY
, _fallbackRelayAddress(ZT_TCP_FALLBACK_RELAY)
,_lastSendToGlobalV4(0)
#endif
,_lastRestart(0)
,_nextBackgroundTaskDeadline(0)
,_tcpFallbackTunnel((TcpConnection *)0)
,_termReason(ONE_STILL_RUNNING)
,_portMappingEnabled(true)
#ifdef ZT_USE_MINIUPNPC
,_portMapper((PortMapper *)0)
#endif
#ifdef ZT_VAULT_SUPPORT
,_vaultEnabled(false)
,_vaultURL()
,_vaultToken()
,_vaultPath("cubbyhole/zerotier")
#endif
,_run(true)
,_rc(NULL)
,_ssoRedirectURL()
{
_ports[0] = 0;
_ports[1] = 0;
_ports[2] = 0;
prometheus::simpleapi::saver.set_registry(prometheus::simpleapi::registry_ptr);
prometheus::simpleapi::saver.set_delay(std::chrono::seconds(5));
prometheus::simpleapi::saver.set_out_file(_homePath + ZT_PATH_SEPARATOR + "metrics.prom");
#if ZT_VAULT_SUPPORT
curl_global_init(CURL_GLOBAL_DEFAULT);
#endif
}
virtual ~OneServiceImpl()
{
#ifdef __WINDOWS__
WinFWHelper::removeICMPRules();
#endif
_binder.closeAll(_phy);
#if ZT_VAULT_SUPPORT
curl_global_cleanup();
#endif
_controlPlane.stop();
if (_serverThreadRunning) {
_serverThread.join();
}
_controlPlaneV6.stop();
if (_serverThreadRunningV6) {
_serverThreadV6.join();
}
#ifdef ZT_USE_MINIUPNPC
delete _portMapper;
#endif
delete _controller;
delete _rc;
}
virtual ReasonForTermination run()
{
try {
{
const std::string authTokenPath(_homePath + ZT_PATH_SEPARATOR_S "authtoken.secret");
if (!OSUtils::readFile(authTokenPath.c_str(),_authToken)) {
unsigned char foo[24];
Utils::getSecureRandom(foo,sizeof(foo));
_authToken = "";
for(unsigned int i=0;i<sizeof(foo);++i)
_authToken.push_back("abcdefghijklmnopqrstuvwxyz0123456789"[(unsigned long)foo[i] % 36]);
if (!OSUtils::writeFile(authTokenPath.c_str(),_authToken)) {
Mutex::Lock _l(_termReason_m);
_termReason = ONE_UNRECOVERABLE_ERROR;
_fatalErrorMessage = "authtoken.secret could not be written (try running with -U to prevent dropping of privileges)";
return _termReason;
} else {
OSUtils::lockDownFile(authTokenPath.c_str(),false);
}
}
_authToken = _trimString(_authToken);
}
{
const std::string metricsTokenPath(_homePath + ZT_PATH_SEPARATOR_S "metricstoken.secret");
if (!OSUtils::readFile(metricsTokenPath.c_str(),_metricsToken)) {
unsigned char foo[24];
Utils::getSecureRandom(foo,sizeof(foo));
_metricsToken = "";
for(unsigned int i=0;i<sizeof(foo);++i)
_metricsToken.push_back("abcdefghijklmnopqrstuvwxyz0123456789"[(unsigned long)foo[i] % 36]);
if (!OSUtils::writeFile(metricsTokenPath.c_str(),_metricsToken)) {
Mutex::Lock _l(_termReason_m);
_termReason = ONE_UNRECOVERABLE_ERROR;