OneService.cpp 71 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062
  1. /*
  2. * ZeroTier One - Network Virtualization Everywhere
  3. * Copyright (C) 2011-2016 ZeroTier, Inc. https://www.zerotier.com/
  4. *
  5. * This program is free software: you can redistribute it and/or modify
  6. * it under the terms of the GNU General Public License as published by
  7. * the Free Software Foundation, either version 3 of the License, or
  8. * (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU General Public License
  16. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  17. */
  18. #include <stdio.h>
  19. #include <stdlib.h>
  20. #include <string.h>
  21. #include <stdint.h>
  22. #include <string>
  23. #include <map>
  24. #include <set>
  25. #include <vector>
  26. #include <algorithm>
  27. #include <list>
  28. #include "../version.h"
  29. #include "../include/ZeroTierOne.h"
  30. #include "../node/Constants.hpp"
  31. #include "../node/Mutex.hpp"
  32. #include "../node/Node.hpp"
  33. #include "../node/Utils.hpp"
  34. #include "../node/InetAddress.hpp"
  35. #include "../node/MAC.hpp"
  36. #include "../node/Identity.hpp"
  37. #include "../osdep/Phy.hpp"
  38. #include "../osdep/Thread.hpp"
  39. #include "../osdep/OSUtils.hpp"
  40. #include "../osdep/Http.hpp"
  41. #include "../osdep/PortMapper.hpp"
  42. #include "../osdep/Binder.hpp"
  43. #include "../osdep/ManagedRoute.hpp"
  44. #include "OneService.hpp"
  45. #include "ControlPlane.hpp"
  46. #include "ClusterGeoIpService.hpp"
  47. #include "ClusterDefinition.hpp"
  48. #include "SoftwareUpdater.hpp"
  49. #ifdef ZT_USE_SYSTEM_HTTP_PARSER
  50. #include <http_parser.h>
  51. #else
  52. #include "../ext/http-parser/http_parser.h"
  53. #endif
  54. #include "../ext/json/json.hpp"
  55. using json = nlohmann::json;
  56. /**
  57. * Uncomment to enable UDP breakage switch
  58. *
  59. * If this is defined, the presence of a file called /tmp/ZT_BREAK_UDP
  60. * will cause direct UDP TX/RX to stop working. This can be used to
  61. * test TCP tunneling fallback and other robustness features. Deleting
  62. * this file will cause it to start working again.
  63. */
  64. //#define ZT_BREAK_UDP
  65. #include "../controller/EmbeddedNetworkController.hpp"
  66. #ifdef __WINDOWS__
  67. #include <WinSock2.h>
  68. #include <Windows.h>
  69. #include <ShlObj.h>
  70. #include <netioapi.h>
  71. #include <iphlpapi.h>
  72. #else
  73. #include <sys/types.h>
  74. #include <sys/socket.h>
  75. #include <sys/wait.h>
  76. #include <unistd.h>
  77. #include <ifaddrs.h>
  78. #endif
  79. // Include the right tap device driver for this platform -- add new platforms here
  80. #ifdef ZT_SERVICE_NETCON
  81. // In network containers builds, use the virtual netcon endpoint instead of a tun/tap port driver
  82. #include "../netcon/NetconEthernetTap.hpp"
  83. namespace ZeroTier { typedef NetconEthernetTap EthernetTap; }
  84. #else // not ZT_SERVICE_NETCON so pick a tap driver
  85. #ifdef __APPLE__
  86. #include "../osdep/OSXEthernetTap.hpp"
  87. namespace ZeroTier { typedef OSXEthernetTap EthernetTap; }
  88. #endif // __APPLE__
  89. #ifdef __LINUX__
  90. #include "../osdep/LinuxEthernetTap.hpp"
  91. namespace ZeroTier { typedef LinuxEthernetTap EthernetTap; }
  92. #endif // __LINUX__
  93. #ifdef __WINDOWS__
  94. #include "../osdep/WindowsEthernetTap.hpp"
  95. namespace ZeroTier { typedef WindowsEthernetTap EthernetTap; }
  96. #endif // __WINDOWS__
  97. #ifdef __FreeBSD__
  98. #include "../osdep/BSDEthernetTap.hpp"
  99. namespace ZeroTier { typedef BSDEthernetTap EthernetTap; }
  100. #endif // __FreeBSD__
  101. #ifdef __OpenBSD__
  102. #include "../osdep/BSDEthernetTap.hpp"
  103. namespace ZeroTier { typedef BSDEthernetTap EthernetTap; }
  104. #endif // __OpenBSD__
  105. #endif // ZT_SERVICE_NETCON
  106. // Sanity limits for HTTP
  107. #define ZT_MAX_HTTP_MESSAGE_SIZE (1024 * 1024 * 64)
  108. #define ZT_MAX_HTTP_CONNECTIONS 64
  109. // Interface metric for ZeroTier taps -- this ensures that if we are on WiFi and also
  110. // bridged via ZeroTier to the same LAN traffic will (if the OS is sane) prefer WiFi.
  111. #define ZT_IF_METRIC 5000
  112. // How often to check for new multicast subscriptions on a tap device
  113. #define ZT_TAP_CHECK_MULTICAST_INTERVAL 5000
  114. // Path under ZT1 home for controller database if controller is enabled
  115. #define ZT_CONTROLLER_DB_PATH "controller.d"
  116. // TCP fallback relay (run by ZeroTier, Inc. -- this will eventually go away)
  117. #define ZT_TCP_FALLBACK_RELAY "204.80.128.1/443"
  118. // Frequency at which we re-resolve the TCP fallback relay
  119. #define ZT_TCP_FALLBACK_RERESOLVE_DELAY 86400000
  120. // Attempt to engage TCP fallback after this many ms of no reply to packets sent to global-scope IPs
  121. #define ZT_TCP_FALLBACK_AFTER 60000
  122. // How often to check for local interface addresses
  123. #define ZT_LOCAL_INTERFACE_CHECK_INTERVAL 60000
  124. namespace ZeroTier {
  125. namespace {
  126. static std::string _trimString(const std::string &s)
  127. {
  128. unsigned long end = (unsigned long)s.length();
  129. while (end) {
  130. char c = s[end - 1];
  131. if ((c == ' ')||(c == '\r')||(c == '\n')||(!c)||(c == '\t'))
  132. --end;
  133. else break;
  134. }
  135. unsigned long start = 0;
  136. while (start < end) {
  137. char c = s[start];
  138. if ((c == ' ')||(c == '\r')||(c == '\n')||(!c)||(c == '\t'))
  139. ++start;
  140. else break;
  141. }
  142. return s.substr(start,end - start);
  143. }
  144. class OneServiceImpl;
  145. static int SnodeVirtualNetworkConfigFunction(ZT_Node *node,void *uptr,uint64_t nwid,void **nuptr,enum ZT_VirtualNetworkConfigOperation op,const ZT_VirtualNetworkConfig *nwconf);
  146. static void SnodeEventCallback(ZT_Node *node,void *uptr,enum ZT_Event event,const void *metaData);
  147. static long SnodeDataStoreGetFunction(ZT_Node *node,void *uptr,const char *name,void *buf,unsigned long bufSize,unsigned long readIndex,unsigned long *totalSize);
  148. static int SnodeDataStorePutFunction(ZT_Node *node,void *uptr,const char *name,const void *data,unsigned long len,int secure);
  149. static int SnodeWirePacketSendFunction(ZT_Node *node,void *uptr,const struct sockaddr_storage *localAddr,const struct sockaddr_storage *addr,const void *data,unsigned int len,unsigned int ttl);
  150. static void SnodeVirtualNetworkFrameFunction(ZT_Node *node,void *uptr,uint64_t nwid,void **nuptr,uint64_t sourceMac,uint64_t destMac,unsigned int etherType,unsigned int vlanId,const void *data,unsigned int len);
  151. static int SnodePathCheckFunction(ZT_Node *node,void *uptr,uint64_t ztaddr,const struct sockaddr_storage *localAddr,const struct sockaddr_storage *remoteAddr);
  152. static int SnodePathLookupFunction(ZT_Node *node,void *uptr,uint64_t ztaddr,int family,struct sockaddr_storage *result);
  153. #ifdef ZT_ENABLE_CLUSTER
  154. static void SclusterSendFunction(void *uptr,unsigned int toMemberId,const void *data,unsigned int len);
  155. static int SclusterGeoIpFunction(void *uptr,const struct sockaddr_storage *addr,int *x,int *y,int *z);
  156. #endif
  157. static void StapFrameHandler(void *uptr,uint64_t nwid,const MAC &from,const MAC &to,unsigned int etherType,unsigned int vlanId,const void *data,unsigned int len);
  158. static int ShttpOnMessageBegin(http_parser *parser);
  159. static int ShttpOnUrl(http_parser *parser,const char *ptr,size_t length);
  160. #if (HTTP_PARSER_VERSION_MAJOR >= 2) && (HTTP_PARSER_VERSION_MINOR >= 2)
  161. static int ShttpOnStatus(http_parser *parser,const char *ptr,size_t length);
  162. #else
  163. static int ShttpOnStatus(http_parser *parser);
  164. #endif
  165. static int ShttpOnHeaderField(http_parser *parser,const char *ptr,size_t length);
  166. static int ShttpOnValue(http_parser *parser,const char *ptr,size_t length);
  167. static int ShttpOnHeadersComplete(http_parser *parser);
  168. static int ShttpOnBody(http_parser *parser,const char *ptr,size_t length);
  169. static int ShttpOnMessageComplete(http_parser *parser);
  170. #if (HTTP_PARSER_VERSION_MAJOR >= 2) && (HTTP_PARSER_VERSION_MINOR >= 1)
  171. static const struct http_parser_settings HTTP_PARSER_SETTINGS = {
  172. ShttpOnMessageBegin,
  173. ShttpOnUrl,
  174. ShttpOnStatus,
  175. ShttpOnHeaderField,
  176. ShttpOnValue,
  177. ShttpOnHeadersComplete,
  178. ShttpOnBody,
  179. ShttpOnMessageComplete
  180. };
  181. #else
  182. static const struct http_parser_settings HTTP_PARSER_SETTINGS = {
  183. ShttpOnMessageBegin,
  184. ShttpOnUrl,
  185. ShttpOnHeaderField,
  186. ShttpOnValue,
  187. ShttpOnHeadersComplete,
  188. ShttpOnBody,
  189. ShttpOnMessageComplete
  190. };
  191. #endif
  192. struct TcpConnection
  193. {
  194. enum {
  195. TCP_HTTP_INCOMING,
  196. TCP_HTTP_OUTGOING, // not currently used
  197. TCP_TUNNEL_OUTGOING // fale-SSL outgoing tunnel -- HTTP-related fields are not used
  198. } type;
  199. bool shouldKeepAlive;
  200. OneServiceImpl *parent;
  201. PhySocket *sock;
  202. InetAddress from;
  203. http_parser parser;
  204. unsigned long messageSize;
  205. uint64_t lastActivity;
  206. std::string currentHeaderField;
  207. std::string currentHeaderValue;
  208. std::string url;
  209. std::string status;
  210. std::map< std::string,std::string > headers;
  211. std::string body;
  212. std::string writeBuf;
  213. Mutex writeBuf_m;
  214. };
  215. // Used to pseudo-randomize local source port picking
  216. static volatile unsigned int _udpPortPickerCounter = 0;
  217. class OneServiceImpl : public OneService
  218. {
  219. public:
  220. // begin member variables --------------------------------------------------
  221. const std::string _homePath;
  222. EmbeddedNetworkController *_controller;
  223. Phy<OneServiceImpl *> _phy;
  224. Node *_node;
  225. SoftwareUpdater *_updater;
  226. bool _updateAutoApply;
  227. unsigned int _primaryPort;
  228. // Local configuration and memo-ized static path definitions
  229. json _localConfig;
  230. Hashtable< uint64_t,std::vector<InetAddress> > _v4Hints;
  231. Hashtable< uint64_t,std::vector<InetAddress> > _v6Hints;
  232. Hashtable< uint64_t,std::vector<InetAddress> > _v4Blacklists;
  233. Hashtable< uint64_t,std::vector<InetAddress> > _v6Blacklists;
  234. std::vector< InetAddress > _globalV4Blacklist;
  235. std::vector< InetAddress > _globalV6Blacklist;
  236. std::vector< InetAddress > _allowManagementFrom;
  237. std::vector< std::string > _interfacePrefixBlacklist;
  238. Mutex _localConfig_m;
  239. /*
  240. * To attempt to handle NAT/gateway craziness we use three local UDP ports:
  241. *
  242. * [0] is the normal/default port, usually 9993
  243. * [1] is a port dervied from our ZeroTier address
  244. * [2] is a port computed from the normal/default for use with uPnP/NAT-PMP mappings
  245. *
  246. * [2] exists because on some gateways trying to do regular NAT-t interferes
  247. * destructively with uPnP port mapping behavior in very weird buggy ways.
  248. * It's only used if uPnP/NAT-PMP is enabled in this build.
  249. */
  250. Binder _bindings[3];
  251. unsigned int _ports[3];
  252. uint16_t _portsBE[3]; // ports in big-endian network byte order as in sockaddr
  253. // Sockets for JSON API -- bound only to V4 and V6 localhost
  254. PhySocket *_v4TcpControlSocket;
  255. PhySocket *_v6TcpControlSocket;
  256. // JSON API handler
  257. ControlPlane *_controlPlane;
  258. // Time we last received a packet from a global address
  259. uint64_t _lastDirectReceiveFromGlobal;
  260. #ifdef ZT_TCP_FALLBACK_RELAY
  261. uint64_t _lastSendToGlobalV4;
  262. #endif
  263. // Last potential sleep/wake event
  264. uint64_t _lastRestart;
  265. // Deadline for the next background task service function
  266. volatile uint64_t _nextBackgroundTaskDeadline;
  267. // Configured networks
  268. struct NetworkState
  269. {
  270. NetworkState() :
  271. tap((EthernetTap *)0)
  272. {
  273. // Real defaults are in network 'up' code in network event handler
  274. settings.allowManaged = true;
  275. settings.allowGlobal = false;
  276. settings.allowDefault = false;
  277. }
  278. EthernetTap *tap;
  279. ZT_VirtualNetworkConfig config; // memcpy() of raw config from core
  280. std::vector<InetAddress> managedIps;
  281. std::list< SharedPtr<ManagedRoute> > managedRoutes;
  282. NetworkSettings settings;
  283. };
  284. std::map<uint64_t,NetworkState> _nets;
  285. Mutex _nets_m;
  286. // Active TCP/IP connections
  287. std::set< TcpConnection * > _tcpConnections; // no mutex for this since it's done in the main loop thread only
  288. TcpConnection *_tcpFallbackTunnel;
  289. // Termination status information
  290. ReasonForTermination _termReason;
  291. std::string _fatalErrorMessage;
  292. Mutex _termReason_m;
  293. // uPnP/NAT-PMP port mapper if enabled
  294. bool _portMappingEnabled; // local.conf settings
  295. #ifdef ZT_USE_MINIUPNPC
  296. PortMapper *_portMapper;
  297. #endif
  298. // Cluster management instance if enabled
  299. #ifdef ZT_ENABLE_CLUSTER
  300. PhySocket *_clusterMessageSocket;
  301. ClusterDefinition *_clusterDefinition;
  302. unsigned int _clusterMemberId;
  303. #endif
  304. // Set to false to force service to stop
  305. volatile bool _run;
  306. Mutex _run_m;
  307. // end member variables ----------------------------------------------------
  308. OneServiceImpl(const char *hp,unsigned int port) :
  309. _homePath((hp) ? hp : ".")
  310. ,_controller((EmbeddedNetworkController *)0)
  311. ,_phy(this,false,true)
  312. ,_node((Node *)0)
  313. ,_updater((SoftwareUpdater *)0)
  314. ,_updateAutoApply(false)
  315. ,_primaryPort(port)
  316. ,_controlPlane((ControlPlane *)0)
  317. ,_lastDirectReceiveFromGlobal(0)
  318. #ifdef ZT_TCP_FALLBACK_RELAY
  319. ,_lastSendToGlobalV4(0)
  320. #endif
  321. ,_lastRestart(0)
  322. ,_nextBackgroundTaskDeadline(0)
  323. ,_tcpFallbackTunnel((TcpConnection *)0)
  324. ,_termReason(ONE_STILL_RUNNING)
  325. ,_portMappingEnabled(true)
  326. #ifdef ZT_USE_MINIUPNPC
  327. ,_portMapper((PortMapper *)0)
  328. #endif
  329. #ifdef ZT_ENABLE_CLUSTER
  330. ,_clusterMessageSocket((PhySocket *)0)
  331. ,_clusterDefinition((ClusterDefinition *)0)
  332. ,_clusterMemberId(0)
  333. #endif
  334. ,_run(true)
  335. {
  336. _ports[0] = 0;
  337. _ports[1] = 0;
  338. _ports[2] = 0;
  339. }
  340. virtual ~OneServiceImpl()
  341. {
  342. for(int i=0;i<3;++i)
  343. _bindings[i].closeAll(_phy);
  344. _phy.close(_v4TcpControlSocket);
  345. _phy.close(_v6TcpControlSocket);
  346. #ifdef ZT_ENABLE_CLUSTER
  347. _phy.close(_clusterMessageSocket);
  348. #endif
  349. #ifdef ZT_USE_MINIUPNPC
  350. delete _portMapper;
  351. #endif
  352. delete _controller;
  353. #ifdef ZT_ENABLE_CLUSTER
  354. delete _clusterDefinition;
  355. #endif
  356. }
  357. virtual ReasonForTermination run()
  358. {
  359. try {
  360. std::string authToken;
  361. {
  362. std::string authTokenPath(_homePath + ZT_PATH_SEPARATOR_S "authtoken.secret");
  363. if (!OSUtils::readFile(authTokenPath.c_str(),authToken)) {
  364. unsigned char foo[24];
  365. Utils::getSecureRandom(foo,sizeof(foo));
  366. authToken = "";
  367. for(unsigned int i=0;i<sizeof(foo);++i)
  368. authToken.push_back("abcdefghijklmnopqrstuvwxyz0123456789"[(unsigned long)foo[i] % 36]);
  369. if (!OSUtils::writeFile(authTokenPath.c_str(),authToken)) {
  370. Mutex::Lock _l(_termReason_m);
  371. _termReason = ONE_UNRECOVERABLE_ERROR;
  372. _fatalErrorMessage = "authtoken.secret could not be written";
  373. return _termReason;
  374. } else {
  375. OSUtils::lockDownFile(authTokenPath.c_str(),false);
  376. }
  377. }
  378. }
  379. authToken = _trimString(authToken);
  380. // Clean up any legacy files if present
  381. OSUtils::rm((_homePath + ZT_PATH_SEPARATOR_S "peers.save").c_str());
  382. OSUtils::rm((_homePath + ZT_PATH_SEPARATOR_S "world").c_str());
  383. {
  384. struct ZT_Node_Callbacks cb;
  385. cb.version = 0;
  386. cb.dataStoreGetFunction = SnodeDataStoreGetFunction;
  387. cb.dataStorePutFunction = SnodeDataStorePutFunction;
  388. cb.wirePacketSendFunction = SnodeWirePacketSendFunction;
  389. cb.virtualNetworkFrameFunction = SnodeVirtualNetworkFrameFunction;
  390. cb.virtualNetworkConfigFunction = SnodeVirtualNetworkConfigFunction;
  391. cb.eventCallback = SnodeEventCallback;
  392. cb.pathCheckFunction = SnodePathCheckFunction;
  393. cb.pathLookupFunction = SnodePathLookupFunction;
  394. _node = new Node(this,&cb,OSUtils::now());
  395. }
  396. // Read local configuration
  397. {
  398. uint64_t trustedPathIds[ZT_MAX_TRUSTED_PATHS];
  399. InetAddress trustedPathNetworks[ZT_MAX_TRUSTED_PATHS];
  400. unsigned int trustedPathCount = 0;
  401. // Old style "trustedpaths" flat file -- will eventually go away
  402. FILE *trustpaths = fopen((_homePath + ZT_PATH_SEPARATOR_S "trustedpaths").c_str(),"r");
  403. if (trustpaths) {
  404. char buf[1024];
  405. while ((fgets(buf,sizeof(buf),trustpaths))&&(trustedPathCount < ZT_MAX_TRUSTED_PATHS)) {
  406. int fno = 0;
  407. char *saveptr = (char *)0;
  408. uint64_t trustedPathId = 0;
  409. InetAddress trustedPathNetwork;
  410. for(char *f=Utils::stok(buf,"=\r\n \t",&saveptr);(f);f=Utils::stok((char *)0,"=\r\n \t",&saveptr)) {
  411. if (fno == 0) {
  412. trustedPathId = Utils::hexStrToU64(f);
  413. } else if (fno == 1) {
  414. trustedPathNetwork = InetAddress(f);
  415. } else break;
  416. ++fno;
  417. }
  418. if ( (trustedPathId != 0) && ((trustedPathNetwork.ss_family == AF_INET)||(trustedPathNetwork.ss_family == AF_INET6)) && (trustedPathNetwork.ipScope() != InetAddress::IP_SCOPE_GLOBAL) && (trustedPathNetwork.netmaskBits() > 0) ) {
  419. trustedPathIds[trustedPathCount] = trustedPathId;
  420. trustedPathNetworks[trustedPathCount] = trustedPathNetwork;
  421. ++trustedPathCount;
  422. }
  423. }
  424. fclose(trustpaths);
  425. }
  426. // Read local config file
  427. Mutex::Lock _l2(_localConfig_m);
  428. std::string lcbuf;
  429. if (OSUtils::readFile((_homePath + ZT_PATH_SEPARATOR_S "local.conf").c_str(),lcbuf)) {
  430. try {
  431. _localConfig = OSUtils::jsonParse(lcbuf);
  432. if (!_localConfig.is_object()) {
  433. fprintf(stderr,"WARNING: unable to parse local.conf (root element is not a JSON object)" ZT_EOL_S);
  434. }
  435. } catch ( ... ) {
  436. fprintf(stderr,"WARNING: unable to parse local.conf (invalid JSON)" ZT_EOL_S);
  437. }
  438. }
  439. // Get any trusted paths in local.conf (we'll parse the rest of physical[] elsewhere)
  440. json &physical = _localConfig["physical"];
  441. if (physical.is_object()) {
  442. for(json::iterator phy(physical.begin());phy!=physical.end();++phy) {
  443. InetAddress net(OSUtils::jsonString(phy.key(),""));
  444. if (net) {
  445. if (phy.value().is_object()) {
  446. uint64_t tpid;
  447. if ((tpid = OSUtils::jsonInt(phy.value()["trustedPathId"],0ULL)) != 0ULL) {
  448. if ( ((net.ss_family == AF_INET)||(net.ss_family == AF_INET6)) && (trustedPathCount < ZT_MAX_TRUSTED_PATHS) && (net.ipScope() != InetAddress::IP_SCOPE_GLOBAL) && (net.netmaskBits() > 0) ) {
  449. trustedPathIds[trustedPathCount] = tpid;
  450. trustedPathNetworks[trustedPathCount] = net;
  451. ++trustedPathCount;
  452. }
  453. }
  454. }
  455. }
  456. }
  457. }
  458. // Set trusted paths if there are any
  459. if (trustedPathCount)
  460. _node->setTrustedPaths(reinterpret_cast<const struct sockaddr_storage *>(trustedPathNetworks),trustedPathIds,trustedPathCount);
  461. }
  462. applyLocalConfig();
  463. // Bind TCP control socket
  464. const int portTrials = (_primaryPort == 0) ? 256 : 1; // if port is 0, pick random
  465. for(int k=0;k<portTrials;++k) {
  466. if (_primaryPort == 0) {
  467. unsigned int randp = 0;
  468. Utils::getSecureRandom(&randp,sizeof(randp));
  469. _primaryPort = 20000 + (randp % 45500);
  470. }
  471. if (_trialBind(_primaryPort)) {
  472. struct sockaddr_in in4;
  473. memset(&in4,0,sizeof(in4));
  474. in4.sin_family = AF_INET;
  475. in4.sin_addr.s_addr = Utils::hton((uint32_t)((_allowManagementFrom.size() > 0) ? 0 : 0x7f000001)); // right now we just listen for TCP @127.0.0.1
  476. in4.sin_port = Utils::hton((uint16_t)_primaryPort);
  477. _v4TcpControlSocket = _phy.tcpListen((const struct sockaddr *)&in4,this);
  478. struct sockaddr_in6 in6;
  479. memset((void *)&in6,0,sizeof(in6));
  480. in6.sin6_family = AF_INET6;
  481. in6.sin6_port = in4.sin_port;
  482. if (_allowManagementFrom.size() == 0)
  483. in6.sin6_addr.s6_addr[15] = 1; // IPv6 localhost == ::1
  484. _v6TcpControlSocket = _phy.tcpListen((const struct sockaddr *)&in6,this);
  485. // We must bind one of IPv4 or IPv6 -- support either failing to support hosts that
  486. // have only IPv4 or only IPv6 stacks.
  487. if ((_v4TcpControlSocket)||(_v6TcpControlSocket)) {
  488. _ports[0] = _primaryPort;
  489. break;
  490. } else {
  491. if (_v4TcpControlSocket)
  492. _phy.close(_v4TcpControlSocket,false);
  493. if (_v6TcpControlSocket)
  494. _phy.close(_v6TcpControlSocket,false);
  495. _primaryPort = 0;
  496. }
  497. } else {
  498. _primaryPort = 0;
  499. }
  500. }
  501. if (_ports[0] == 0) {
  502. Mutex::Lock _l(_termReason_m);
  503. _termReason = ONE_UNRECOVERABLE_ERROR;
  504. _fatalErrorMessage = "cannot bind to local control interface port";
  505. return _termReason;
  506. }
  507. // Write file containing primary port to be read by CLIs, etc.
  508. char portstr[64];
  509. Utils::snprintf(portstr,sizeof(portstr),"%u",_ports[0]);
  510. OSUtils::writeFile((_homePath + ZT_PATH_SEPARATOR_S "zerotier-one.port").c_str(),std::string(portstr));
  511. // Attempt to bind to a secondary port chosen from our ZeroTier address.
  512. // This exists because there are buggy NATs out there that fail if more
  513. // than one device behind the same NAT tries to use the same internal
  514. // private address port number.
  515. _ports[1] = 20000 + ((unsigned int)_node->address() % 45500);
  516. for(int i=0;;++i) {
  517. if (i > 1000) {
  518. _ports[1] = 0;
  519. break;
  520. } else if (++_ports[1] >= 65536) {
  521. _ports[1] = 20000;
  522. }
  523. if (_trialBind(_ports[1]))
  524. break;
  525. }
  526. #ifdef ZT_USE_MINIUPNPC
  527. if (_portMappingEnabled) {
  528. // If we're running uPnP/NAT-PMP, bind a *third* port for that. We can't
  529. // use the other two ports for that because some NATs do really funky
  530. // stuff with ports that are explicitly mapped that breaks things.
  531. if (_ports[1]) {
  532. _ports[2] = _ports[1];
  533. for(int i=0;;++i) {
  534. if (i > 1000) {
  535. _ports[2] = 0;
  536. break;
  537. } else if (++_ports[2] >= 65536) {
  538. _ports[2] = 20000;
  539. }
  540. if (_trialBind(_ports[2]))
  541. break;
  542. }
  543. if (_ports[2]) {
  544. char uniqueName[64];
  545. Utils::snprintf(uniqueName,sizeof(uniqueName),"ZeroTier/%.10llx@%u",_node->address(),_ports[2]);
  546. _portMapper = new PortMapper(_ports[2],uniqueName);
  547. }
  548. }
  549. }
  550. #endif
  551. // Populate ports in big-endian format for quick compare
  552. for(int i=0;i<3;++i)
  553. _portsBE[i] = Utils::hton((uint16_t)_ports[i]);
  554. // Check for legacy controller.db and terminate if present to prevent nasty surprises for DIY controller folks
  555. if (OSUtils::fileExists((_homePath + ZT_PATH_SEPARATOR_S "controller.db").c_str())) {
  556. Mutex::Lock _l(_termReason_m);
  557. _termReason = ONE_UNRECOVERABLE_ERROR;
  558. _fatalErrorMessage = "controller.db is present in our home path! run migrate-sqlite to migrate to new controller.d format.";
  559. return _termReason;
  560. }
  561. _controller = new EmbeddedNetworkController(_node,(_homePath + ZT_PATH_SEPARATOR_S ZT_CONTROLLER_DB_PATH).c_str());
  562. _node->setNetconfMaster((void *)_controller);
  563. #ifdef ZT_ENABLE_CLUSTER
  564. if (OSUtils::fileExists((_homePath + ZT_PATH_SEPARATOR_S "cluster").c_str())) {
  565. _clusterDefinition = new ClusterDefinition(_node->address(),(_homePath + ZT_PATH_SEPARATOR_S "cluster").c_str());
  566. if (_clusterDefinition->size() > 0) {
  567. std::vector<ClusterDefinition::MemberDefinition> members(_clusterDefinition->members());
  568. for(std::vector<ClusterDefinition::MemberDefinition>::iterator m(members.begin());m!=members.end();++m) {
  569. PhySocket *cs = _phy.udpBind(reinterpret_cast<const struct sockaddr *>(&(m->clusterEndpoint)));
  570. if (cs) {
  571. if (_clusterMessageSocket) {
  572. _phy.close(_clusterMessageSocket,false);
  573. _phy.close(cs,false);
  574. Mutex::Lock _l(_termReason_m);
  575. _termReason = ONE_UNRECOVERABLE_ERROR;
  576. _fatalErrorMessage = "cluster: can't determine my cluster member ID: able to bind more than one cluster message socket IP/port!";
  577. return _termReason;
  578. }
  579. _clusterMessageSocket = cs;
  580. _clusterMemberId = m->id;
  581. }
  582. }
  583. if (!_clusterMessageSocket) {
  584. Mutex::Lock _l(_termReason_m);
  585. _termReason = ONE_UNRECOVERABLE_ERROR;
  586. _fatalErrorMessage = "cluster: can't determine my cluster member ID: unable to bind to any cluster message socket IP/port.";
  587. return _termReason;
  588. }
  589. const ClusterDefinition::MemberDefinition &me = (*_clusterDefinition)[_clusterMemberId];
  590. InetAddress endpoints[255];
  591. unsigned int numEndpoints = 0;
  592. for(std::vector<InetAddress>::const_iterator i(me.zeroTierEndpoints.begin());i!=me.zeroTierEndpoints.end();++i)
  593. endpoints[numEndpoints++] = *i;
  594. if (_node->clusterInit(_clusterMemberId,reinterpret_cast<const struct sockaddr_storage *>(endpoints),numEndpoints,me.x,me.y,me.z,&SclusterSendFunction,this,_clusterDefinition->geo().available() ? &SclusterGeoIpFunction : 0,this) == ZT_RESULT_OK) {
  595. std::vector<ClusterDefinition::MemberDefinition> members(_clusterDefinition->members());
  596. for(std::vector<ClusterDefinition::MemberDefinition>::iterator m(members.begin());m!=members.end();++m) {
  597. if (m->id != _clusterMemberId)
  598. _node->clusterAddMember(m->id);
  599. }
  600. }
  601. } else {
  602. delete _clusterDefinition;
  603. _clusterDefinition = (ClusterDefinition *)0;
  604. }
  605. }
  606. #endif
  607. _controlPlane = new ControlPlane(this,_node);
  608. _controlPlane->addAuthToken(authToken.c_str());
  609. _controlPlane->setController(_controller);
  610. { // Load existing networks
  611. std::vector<std::string> networksDotD(OSUtils::listDirectory((_homePath + ZT_PATH_SEPARATOR_S "networks.d").c_str()));
  612. for(std::vector<std::string>::iterator f(networksDotD.begin());f!=networksDotD.end();++f) {
  613. std::size_t dot = f->find_last_of('.');
  614. if ((dot == 16)&&(f->substr(16) == ".conf"))
  615. _node->join(Utils::hexStrToU64(f->substr(0,dot).c_str()),(void *)0);
  616. }
  617. }
  618. { // Load existing moons
  619. std::vector<std::string> moonsDotD(OSUtils::listDirectory((_homePath + ZT_PATH_SEPARATOR_S "moons.d").c_str()));
  620. for(std::vector<std::string>::iterator f(moonsDotD.begin());f!=moonsDotD.end();++f) {
  621. std::size_t dot = f->find_last_of('.');
  622. if ((dot == 16)&&(f->substr(16) == ".moon"))
  623. _node->orbit(Utils::hexStrToU64(f->substr(0,dot).c_str()),0);
  624. }
  625. }
  626. _nextBackgroundTaskDeadline = 0;
  627. uint64_t clockShouldBe = OSUtils::now();
  628. _lastRestart = clockShouldBe;
  629. uint64_t lastTapMulticastGroupCheck = 0;
  630. uint64_t lastBindRefresh = 0;
  631. uint64_t lastUpdateCheck = clockShouldBe;
  632. uint64_t lastLocalInterfaceAddressCheck = (clockShouldBe - ZT_LOCAL_INTERFACE_CHECK_INTERVAL) + 15000; // do this in 15s to give portmapper time to configure and other things time to settle
  633. for(;;) {
  634. _run_m.lock();
  635. if (!_run) {
  636. _run_m.unlock();
  637. _termReason_m.lock();
  638. _termReason = ONE_NORMAL_TERMINATION;
  639. _termReason_m.unlock();
  640. break;
  641. } else {
  642. _run_m.unlock();
  643. }
  644. const uint64_t now = OSUtils::now();
  645. // Attempt to detect sleep/wake events by detecting delay overruns
  646. bool restarted = false;
  647. if ((now > clockShouldBe)&&((now - clockShouldBe) > 10000)) {
  648. _lastRestart = now;
  649. restarted = true;
  650. }
  651. // Check for updates (if enabled)
  652. if ((_updater)&&((now - lastUpdateCheck) > 10000)) {
  653. lastUpdateCheck = now;
  654. if (_updater->check(now) && _updateAutoApply)
  655. _updater->apply();
  656. }
  657. // Refresh bindings in case device's interfaces have changed, and also sync routes to update any shadow routes (e.g. shadow default)
  658. if (((now - lastBindRefresh) >= ZT_BINDER_REFRESH_PERIOD)||(restarted)) {
  659. lastBindRefresh = now;
  660. for(int i=0;i<3;++i) {
  661. if (_ports[i]) {
  662. _bindings[i].refresh(_phy,_ports[i],*this);
  663. }
  664. }
  665. {
  666. Mutex::Lock _l(_nets_m);
  667. for(std::map<uint64_t,NetworkState>::iterator n(_nets.begin());n!=_nets.end();++n) {
  668. if (n->second.tap)
  669. syncManagedStuff(n->second,false,true);
  670. }
  671. }
  672. }
  673. uint64_t dl = _nextBackgroundTaskDeadline;
  674. if (dl <= now) {
  675. _node->processBackgroundTasks(now,&_nextBackgroundTaskDeadline);
  676. dl = _nextBackgroundTaskDeadline;
  677. }
  678. if ((_tcpFallbackTunnel)&&((now - _lastDirectReceiveFromGlobal) < (ZT_TCP_FALLBACK_AFTER / 2)))
  679. _phy.close(_tcpFallbackTunnel->sock);
  680. if ((now - lastTapMulticastGroupCheck) >= ZT_TAP_CHECK_MULTICAST_INTERVAL) {
  681. lastTapMulticastGroupCheck = now;
  682. Mutex::Lock _l(_nets_m);
  683. for(std::map<uint64_t,NetworkState>::const_iterator n(_nets.begin());n!=_nets.end();++n) {
  684. if (n->second.tap) {
  685. std::vector<MulticastGroup> added,removed;
  686. n->second.tap->scanMulticastGroups(added,removed);
  687. for(std::vector<MulticastGroup>::iterator m(added.begin());m!=added.end();++m)
  688. _node->multicastSubscribe(n->first,m->mac().toInt(),m->adi());
  689. for(std::vector<MulticastGroup>::iterator m(removed.begin());m!=removed.end();++m)
  690. _node->multicastUnsubscribe(n->first,m->mac().toInt(),m->adi());
  691. }
  692. }
  693. }
  694. if ((now - lastLocalInterfaceAddressCheck) >= ZT_LOCAL_INTERFACE_CHECK_INTERVAL) {
  695. lastLocalInterfaceAddressCheck = now;
  696. _node->clearLocalInterfaceAddresses();
  697. #ifdef ZT_USE_MINIUPNPC
  698. if (_portMapper) {
  699. std::vector<InetAddress> mappedAddresses(_portMapper->get());
  700. for(std::vector<InetAddress>::const_iterator ext(mappedAddresses.begin());ext!=mappedAddresses.end();++ext)
  701. _node->addLocalInterfaceAddress(reinterpret_cast<const struct sockaddr_storage *>(&(*ext)));
  702. }
  703. #endif
  704. std::vector<InetAddress> boundAddrs(_bindings[0].allBoundLocalInterfaceAddresses());
  705. for(std::vector<InetAddress>::const_iterator i(boundAddrs.begin());i!=boundAddrs.end();++i)
  706. _node->addLocalInterfaceAddress(reinterpret_cast<const struct sockaddr_storage *>(&(*i)));
  707. }
  708. const unsigned long delay = (dl > now) ? (unsigned long)(dl - now) : 100;
  709. clockShouldBe = now + (uint64_t)delay;
  710. _phy.poll(delay);
  711. }
  712. } catch (std::exception &exc) {
  713. Mutex::Lock _l(_termReason_m);
  714. _termReason = ONE_UNRECOVERABLE_ERROR;
  715. _fatalErrorMessage = exc.what();
  716. } catch ( ... ) {
  717. Mutex::Lock _l(_termReason_m);
  718. _termReason = ONE_UNRECOVERABLE_ERROR;
  719. _fatalErrorMessage = "unexpected exception in main thread";
  720. }
  721. try {
  722. while (!_tcpConnections.empty())
  723. _phy.close((*_tcpConnections.begin())->sock);
  724. } catch ( ... ) {}
  725. {
  726. Mutex::Lock _l(_nets_m);
  727. for(std::map<uint64_t,NetworkState>::iterator n(_nets.begin());n!=_nets.end();++n)
  728. delete n->second.tap;
  729. _nets.clear();
  730. }
  731. delete _controlPlane;
  732. _controlPlane = (ControlPlane *)0;
  733. delete _updater;
  734. _updater = (SoftwareUpdater *)0;
  735. delete _node;
  736. _node = (Node *)0;
  737. return _termReason;
  738. }
  739. virtual ReasonForTermination reasonForTermination() const
  740. {
  741. Mutex::Lock _l(_termReason_m);
  742. return _termReason;
  743. }
  744. virtual std::string fatalErrorMessage() const
  745. {
  746. Mutex::Lock _l(_termReason_m);
  747. return _fatalErrorMessage;
  748. }
  749. virtual std::string portDeviceName(uint64_t nwid) const
  750. {
  751. Mutex::Lock _l(_nets_m);
  752. std::map<uint64_t,NetworkState>::const_iterator n(_nets.find(nwid));
  753. if ((n != _nets.end())&&(n->second.tap))
  754. return n->second.tap->deviceName();
  755. else return std::string();
  756. }
  757. virtual bool tcpFallbackActive() const
  758. {
  759. return (_tcpFallbackTunnel != (TcpConnection *)0);
  760. }
  761. virtual void terminate()
  762. {
  763. _run_m.lock();
  764. _run = false;
  765. _run_m.unlock();
  766. _phy.whack();
  767. }
  768. virtual bool getNetworkSettings(const uint64_t nwid,NetworkSettings &settings) const
  769. {
  770. Mutex::Lock _l(_nets_m);
  771. std::map<uint64_t,NetworkState>::const_iterator n(_nets.find(nwid));
  772. if (n == _nets.end())
  773. return false;
  774. memcpy(&settings,&(n->second.settings),sizeof(NetworkSettings));
  775. return true;
  776. }
  777. virtual bool setNetworkSettings(const uint64_t nwid,const NetworkSettings &settings)
  778. {
  779. Mutex::Lock _l(_nets_m);
  780. std::map<uint64_t,NetworkState>::iterator n(_nets.find(nwid));
  781. if (n == _nets.end())
  782. return false;
  783. memcpy(&(n->second.settings),&settings,sizeof(NetworkSettings));
  784. char nlcpath[256];
  785. Utils::snprintf(nlcpath,sizeof(nlcpath),"%s" ZT_PATH_SEPARATOR_S "networks.d" ZT_PATH_SEPARATOR_S "%.16llx.local.conf",_homePath.c_str(),nwid);
  786. FILE *out = fopen(nlcpath,"w");
  787. if (out) {
  788. fprintf(out,"allowManaged=%d\n",(int)n->second.settings.allowManaged);
  789. fprintf(out,"allowGlobal=%d\n",(int)n->second.settings.allowGlobal);
  790. fprintf(out,"allowDefault=%d\n",(int)n->second.settings.allowDefault);
  791. fclose(out);
  792. }
  793. if (n->second.tap)
  794. syncManagedStuff(n->second,true,true);
  795. return true;
  796. }
  797. // Internal implementation methods -----------------------------------------
  798. // Must be called after _localConfig is read or modified
  799. void applyLocalConfig()
  800. {
  801. Mutex::Lock _l(_localConfig_m);
  802. _v4Hints.clear();
  803. _v6Hints.clear();
  804. _v4Blacklists.clear();
  805. _v6Blacklists.clear();
  806. json &virt = _localConfig["virtual"];
  807. if (virt.is_object()) {
  808. for(json::iterator v(virt.begin());v!=virt.end();++v) {
  809. const std::string nstr = v.key();
  810. if ((nstr.length() == ZT_ADDRESS_LENGTH_HEX)&&(v.value().is_object())) {
  811. const Address ztaddr(Utils::hexStrToU64(nstr.c_str()));
  812. if (ztaddr) {
  813. const uint64_t ztaddr2 = ztaddr.toInt();
  814. std::vector<InetAddress> &v4h = _v4Hints[ztaddr2];
  815. std::vector<InetAddress> &v6h = _v6Hints[ztaddr2];
  816. std::vector<InetAddress> &v4b = _v4Blacklists[ztaddr2];
  817. std::vector<InetAddress> &v6b = _v6Blacklists[ztaddr2];
  818. json &tryAddrs = v.value()["try"];
  819. if (tryAddrs.is_array()) {
  820. for(unsigned long i=0;i<tryAddrs.size();++i) {
  821. const InetAddress ip(OSUtils::jsonString(tryAddrs[i],""));
  822. if (ip.ss_family == AF_INET)
  823. v4h.push_back(ip);
  824. else if (ip.ss_family == AF_INET6)
  825. v6h.push_back(ip);
  826. }
  827. }
  828. json &blAddrs = v.value()["blacklist"];
  829. if (blAddrs.is_array()) {
  830. for(unsigned long i=0;i<blAddrs.size();++i) {
  831. const InetAddress ip(OSUtils::jsonString(tryAddrs[i],""));
  832. if (ip.ss_family == AF_INET)
  833. v4b.push_back(ip);
  834. else if (ip.ss_family == AF_INET6)
  835. v6b.push_back(ip);
  836. }
  837. }
  838. if (v4h.empty()) _v4Hints.erase(ztaddr2);
  839. if (v6h.empty()) _v6Hints.erase(ztaddr2);
  840. if (v4b.empty()) _v4Blacklists.erase(ztaddr2);
  841. if (v6b.empty()) _v6Blacklists.erase(ztaddr2);
  842. }
  843. }
  844. }
  845. }
  846. _globalV4Blacklist.clear();
  847. _globalV6Blacklist.clear();
  848. json &physical = _localConfig["physical"];
  849. if (physical.is_object()) {
  850. for(json::iterator phy(physical.begin());phy!=physical.end();++phy) {
  851. const InetAddress net(OSUtils::jsonString(phy.key(),""));
  852. if ((net)&&(net.netmaskBits() > 0)) {
  853. if (phy.value().is_object()) {
  854. if (OSUtils::jsonBool(phy.value()["blacklist"],false)) {
  855. if (net.ss_family == AF_INET)
  856. _globalV4Blacklist.push_back(net);
  857. else if (net.ss_family == AF_INET6)
  858. _globalV6Blacklist.push_back(net);
  859. }
  860. }
  861. }
  862. }
  863. }
  864. _allowManagementFrom.clear();
  865. _interfacePrefixBlacklist.clear();
  866. json &settings = _localConfig["settings"];
  867. if (settings.is_object()) {
  868. _primaryPort = (unsigned int)OSUtils::jsonInt(settings["primaryPort"],(uint64_t)_primaryPort) & 0xffff;
  869. _portMappingEnabled = OSUtils::jsonBool(settings["portMappingEnabled"],true);
  870. const std::string up(OSUtils::jsonString(settings["softwareUpdate"],ZT_SOFTWARE_UPDATE_DEFAULT));
  871. const bool udist = OSUtils::jsonBool(settings["softwareUpdateDist"],false);
  872. if (((up == "apply")||(up == "download"))||(udist)) {
  873. if (!_updater)
  874. _updater = new SoftwareUpdater(*_node,_homePath);
  875. _updateAutoApply = (up == "apply");
  876. _updater->setUpdateDistribution(udist);
  877. _updater->setChannel(OSUtils::jsonString(settings["softwareUpdateChannel"],ZT_SOFTWARE_UPDATE_DEFAULT_CHANNEL));
  878. } else {
  879. delete _updater;
  880. _updater = (SoftwareUpdater *)0;
  881. _updateAutoApply = false;
  882. }
  883. json &ignoreIfs = settings["interfacePrefixBlacklist"];
  884. if (ignoreIfs.is_array()) {
  885. for(unsigned long i=0;i<ignoreIfs.size();++i) {
  886. const std::string tmp(OSUtils::jsonString(ignoreIfs[i],""));
  887. if (tmp.length() > 0)
  888. _interfacePrefixBlacklist.push_back(tmp);
  889. }
  890. }
  891. json &amf = settings["allowManagementFrom"];
  892. if (amf.is_array()) {
  893. for(unsigned long i=0;i<amf.size();++i) {
  894. const InetAddress nw(OSUtils::jsonString(amf[i],""));
  895. if (nw)
  896. _allowManagementFrom.push_back(nw);
  897. }
  898. }
  899. }
  900. }
  901. // Checks if a managed IP or route target is allowed
  902. bool checkIfManagedIsAllowed(const NetworkState &n,const InetAddress &target)
  903. {
  904. if (!n.settings.allowManaged)
  905. return false;
  906. if (n.settings.allowManagedWhitelist.size() > 0) {
  907. bool allowed = false;
  908. for (InetAddress addr : n.settings.allowManagedWhitelist) {
  909. if (addr.containsAddress(target) && addr.netmaskBits() <= target.netmaskBits()) {
  910. allowed = true;
  911. break;
  912. }
  913. }
  914. if (!allowed) return false;
  915. }
  916. if (target.isDefaultRoute())
  917. return n.settings.allowDefault;
  918. switch(target.ipScope()) {
  919. case InetAddress::IP_SCOPE_NONE:
  920. case InetAddress::IP_SCOPE_MULTICAST:
  921. case InetAddress::IP_SCOPE_LOOPBACK:
  922. case InetAddress::IP_SCOPE_LINK_LOCAL:
  923. return false;
  924. case InetAddress::IP_SCOPE_GLOBAL:
  925. return n.settings.allowGlobal;
  926. default:
  927. return true;
  928. }
  929. }
  930. // Match only an IP from a vector of IPs -- used in syncManagedStuff()
  931. bool matchIpOnly(const std::vector<InetAddress> &ips,const InetAddress &ip) const
  932. {
  933. for(std::vector<InetAddress>::const_iterator i(ips.begin());i!=ips.end();++i) {
  934. if (i->ipsEqual(ip))
  935. return true;
  936. }
  937. return false;
  938. }
  939. // Apply or update managed IPs for a configured network (be sure n.tap exists)
  940. void syncManagedStuff(NetworkState &n,bool syncIps,bool syncRoutes)
  941. {
  942. // assumes _nets_m is locked
  943. if (syncIps) {
  944. std::vector<InetAddress> newManagedIps;
  945. newManagedIps.reserve(n.config.assignedAddressCount);
  946. for(unsigned int i=0;i<n.config.assignedAddressCount;++i) {
  947. const InetAddress *ii = reinterpret_cast<const InetAddress *>(&(n.config.assignedAddresses[i]));
  948. if (checkIfManagedIsAllowed(n,*ii))
  949. newManagedIps.push_back(*ii);
  950. }
  951. std::sort(newManagedIps.begin(),newManagedIps.end());
  952. newManagedIps.erase(std::unique(newManagedIps.begin(),newManagedIps.end()),newManagedIps.end());
  953. for(std::vector<InetAddress>::iterator ip(n.managedIps.begin());ip!=n.managedIps.end();++ip) {
  954. if (std::find(newManagedIps.begin(),newManagedIps.end(),*ip) == newManagedIps.end()) {
  955. if (!n.tap->removeIp(*ip))
  956. fprintf(stderr,"ERROR: unable to remove ip address %s" ZT_EOL_S, ip->toString().c_str());
  957. }
  958. }
  959. #ifdef __SYNOLOGY__
  960. if (!n.tap->addIpSyn(newManagedIps))
  961. fprintf(stderr,"ERROR: unable to add ip addresses to ifcfg" ZT_EOL_S);
  962. #else
  963. for(std::vector<InetAddress>::iterator ip(newManagedIps.begin());ip!=newManagedIps.end();++ip) {
  964. if (std::find(n.managedIps.begin(),n.managedIps.end(),*ip) == n.managedIps.end()) {
  965. if (!n.tap->addIp(*ip))
  966. fprintf(stderr,"ERROR: unable to add ip address %s" ZT_EOL_S, ip->toString().c_str());
  967. }
  968. }
  969. #endif
  970. n.managedIps.swap(newManagedIps);
  971. }
  972. if (syncRoutes) {
  973. char tapdev[64];
  974. #ifdef __WINDOWS__
  975. Utils::snprintf(tapdev,sizeof(tapdev),"%.16llx",(unsigned long long)n.tap->luid().Value);
  976. #else
  977. Utils::scopy(tapdev,sizeof(tapdev),n.tap->deviceName().c_str());
  978. #endif
  979. std::vector<InetAddress> myIps(n.tap->ips());
  980. // Nuke applied routes that are no longer in n.config.routes[] and/or are not allowed
  981. for(std::list< SharedPtr<ManagedRoute> >::iterator mr(n.managedRoutes.begin());mr!=n.managedRoutes.end();) {
  982. bool haveRoute = false;
  983. if ( (checkIfManagedIsAllowed(n,(*mr)->target())) && (((*mr)->via().ss_family != (*mr)->target().ss_family)||(!matchIpOnly(myIps,(*mr)->via()))) ) {
  984. for(unsigned int i=0;i<n.config.routeCount;++i) {
  985. const InetAddress *const target = reinterpret_cast<const InetAddress *>(&(n.config.routes[i].target));
  986. const InetAddress *const via = reinterpret_cast<const InetAddress *>(&(n.config.routes[i].via));
  987. if ( ((*mr)->target() == *target) && ( ((via->ss_family == target->ss_family)&&((*mr)->via().ipsEqual(*via))) || (tapdev == (*mr)->device()) ) ) {
  988. haveRoute = true;
  989. break;
  990. }
  991. }
  992. }
  993. if (haveRoute) {
  994. ++mr;
  995. } else {
  996. n.managedRoutes.erase(mr++);
  997. }
  998. }
  999. // Apply routes in n.config.routes[] that we haven't applied yet, and sync those we have in case shadow routes need to change
  1000. for(unsigned int i=0;i<n.config.routeCount;++i) {
  1001. const InetAddress *const target = reinterpret_cast<const InetAddress *>(&(n.config.routes[i].target));
  1002. const InetAddress *const via = reinterpret_cast<const InetAddress *>(&(n.config.routes[i].via));
  1003. if ( (!checkIfManagedIsAllowed(n,*target)) || ((via->ss_family == target->ss_family)&&(matchIpOnly(myIps,*via))) )
  1004. continue;
  1005. bool haveRoute = false;
  1006. // Ignore routes implied by local managed IPs since adding the IP adds the route
  1007. for(std::vector<InetAddress>::iterator ip(n.managedIps.begin());ip!=n.managedIps.end();++ip) {
  1008. if ((target->netmaskBits() == ip->netmaskBits())&&(target->containsAddress(*ip))) {
  1009. haveRoute = true;
  1010. break;
  1011. }
  1012. }
  1013. if (haveRoute)
  1014. continue;
  1015. // If we've already applied this route, just sync it and continue
  1016. for(std::list< SharedPtr<ManagedRoute> >::iterator mr(n.managedRoutes.begin());mr!=n.managedRoutes.end();++mr) {
  1017. if ( ((*mr)->target() == *target) && ( ((via->ss_family == target->ss_family)&&((*mr)->via().ipsEqual(*via))) || (tapdev == (*mr)->device()) ) ) {
  1018. haveRoute = true;
  1019. (*mr)->sync();
  1020. break;
  1021. }
  1022. }
  1023. if (haveRoute)
  1024. continue;
  1025. // Add and apply new routes
  1026. n.managedRoutes.push_back(SharedPtr<ManagedRoute>(new ManagedRoute(*target,*via,tapdev)));
  1027. if (!n.managedRoutes.back()->sync())
  1028. n.managedRoutes.pop_back();
  1029. }
  1030. }
  1031. }
  1032. // Handlers for Node and Phy<> callbacks -----------------------------------
  1033. inline void phyOnDatagram(PhySocket *sock,void **uptr,const struct sockaddr *localAddr,const struct sockaddr *from,void *data,unsigned long len)
  1034. {
  1035. #ifdef ZT_ENABLE_CLUSTER
  1036. if (sock == _clusterMessageSocket) {
  1037. _lastDirectReceiveFromGlobal = OSUtils::now();
  1038. _node->clusterHandleIncomingMessage(data,len);
  1039. return;
  1040. }
  1041. #endif
  1042. #ifdef ZT_BREAK_UDP
  1043. if (OSUtils::fileExists("/tmp/ZT_BREAK_UDP"))
  1044. return;
  1045. #endif
  1046. if ((len >= 16)&&(reinterpret_cast<const InetAddress *>(from)->ipScope() == InetAddress::IP_SCOPE_GLOBAL))
  1047. _lastDirectReceiveFromGlobal = OSUtils::now();
  1048. const ZT_ResultCode rc = _node->processWirePacket(
  1049. OSUtils::now(),
  1050. reinterpret_cast<const struct sockaddr_storage *>(localAddr),
  1051. (const struct sockaddr_storage *)from, // Phy<> uses sockaddr_storage, so it'll always be that big
  1052. data,
  1053. len,
  1054. &_nextBackgroundTaskDeadline);
  1055. if (ZT_ResultCode_isFatal(rc)) {
  1056. char tmp[256];
  1057. Utils::snprintf(tmp,sizeof(tmp),"fatal error code from processWirePacket: %d",(int)rc);
  1058. Mutex::Lock _l(_termReason_m);
  1059. _termReason = ONE_UNRECOVERABLE_ERROR;
  1060. _fatalErrorMessage = tmp;
  1061. this->terminate();
  1062. }
  1063. }
  1064. inline void phyOnTcpConnect(PhySocket *sock,void **uptr,bool success)
  1065. {
  1066. if (!success)
  1067. return;
  1068. // Outgoing TCP connections are always TCP fallback tunnel connections.
  1069. TcpConnection *tc = new TcpConnection();
  1070. _tcpConnections.insert(tc);
  1071. tc->type = TcpConnection::TCP_TUNNEL_OUTGOING;
  1072. tc->shouldKeepAlive = true;
  1073. tc->parent = this;
  1074. tc->sock = sock;
  1075. // from and parser are not used
  1076. tc->messageSize = 0; // unused
  1077. tc->lastActivity = OSUtils::now();
  1078. // HTTP stuff is not used
  1079. tc->writeBuf = "";
  1080. *uptr = (void *)tc;
  1081. // Send "hello" message
  1082. tc->writeBuf.push_back((char)0x17);
  1083. tc->writeBuf.push_back((char)0x03);
  1084. tc->writeBuf.push_back((char)0x03); // fake TLS 1.2 header
  1085. tc->writeBuf.push_back((char)0x00);
  1086. tc->writeBuf.push_back((char)0x04); // mlen == 4
  1087. tc->writeBuf.push_back((char)ZEROTIER_ONE_VERSION_MAJOR);
  1088. tc->writeBuf.push_back((char)ZEROTIER_ONE_VERSION_MINOR);
  1089. tc->writeBuf.push_back((char)((ZEROTIER_ONE_VERSION_REVISION >> 8) & 0xff));
  1090. tc->writeBuf.push_back((char)(ZEROTIER_ONE_VERSION_REVISION & 0xff));
  1091. _phy.setNotifyWritable(sock,true);
  1092. _tcpFallbackTunnel = tc;
  1093. }
  1094. inline void phyOnTcpAccept(PhySocket *sockL,PhySocket *sockN,void **uptrL,void **uptrN,const struct sockaddr *from)
  1095. {
  1096. if (!from) {
  1097. _phy.close(sockN,false);
  1098. return;
  1099. } else {
  1100. TcpConnection *tc = new TcpConnection();
  1101. _tcpConnections.insert(tc);
  1102. tc->type = TcpConnection::TCP_HTTP_INCOMING;
  1103. tc->shouldKeepAlive = true;
  1104. tc->parent = this;
  1105. tc->sock = sockN;
  1106. tc->from = from;
  1107. http_parser_init(&(tc->parser),HTTP_REQUEST);
  1108. tc->parser.data = (void *)tc;
  1109. tc->messageSize = 0;
  1110. tc->lastActivity = OSUtils::now();
  1111. tc->currentHeaderField = "";
  1112. tc->currentHeaderValue = "";
  1113. tc->url = "";
  1114. tc->status = "";
  1115. tc->headers.clear();
  1116. tc->body = "";
  1117. tc->writeBuf = "";
  1118. *uptrN = (void *)tc;
  1119. }
  1120. }
  1121. inline void phyOnTcpClose(PhySocket *sock,void **uptr)
  1122. {
  1123. TcpConnection *tc = (TcpConnection *)*uptr;
  1124. if (tc) {
  1125. if (tc == _tcpFallbackTunnel)
  1126. _tcpFallbackTunnel = (TcpConnection *)0;
  1127. _tcpConnections.erase(tc);
  1128. delete tc;
  1129. }
  1130. }
  1131. inline void phyOnTcpData(PhySocket *sock,void **uptr,void *data,unsigned long len)
  1132. {
  1133. TcpConnection *tc = reinterpret_cast<TcpConnection *>(*uptr);
  1134. switch(tc->type) {
  1135. case TcpConnection::TCP_HTTP_INCOMING:
  1136. case TcpConnection::TCP_HTTP_OUTGOING:
  1137. http_parser_execute(&(tc->parser),&HTTP_PARSER_SETTINGS,(const char *)data,len);
  1138. if ((tc->parser.upgrade)||(tc->parser.http_errno != HPE_OK)) {
  1139. _phy.close(sock);
  1140. return;
  1141. }
  1142. break;
  1143. case TcpConnection::TCP_TUNNEL_OUTGOING:
  1144. tc->body.append((const char *)data,len);
  1145. while (tc->body.length() >= 5) {
  1146. const char *data = tc->body.data();
  1147. const unsigned long mlen = ( ((((unsigned long)data[3]) & 0xff) << 8) | (((unsigned long)data[4]) & 0xff) );
  1148. if (tc->body.length() >= (mlen + 5)) {
  1149. InetAddress from;
  1150. unsigned long plen = mlen; // payload length, modified if there's an IP header
  1151. data += 5; // skip forward past pseudo-TLS junk and mlen
  1152. if (plen == 4) {
  1153. // Hello message, which isn't sent by proxy and would be ignored by client
  1154. } else if (plen) {
  1155. // Messages should contain IPv4 or IPv6 source IP address data
  1156. switch(data[0]) {
  1157. case 4: // IPv4
  1158. if (plen >= 7) {
  1159. from.set((const void *)(data + 1),4,((((unsigned int)data[5]) & 0xff) << 8) | (((unsigned int)data[6]) & 0xff));
  1160. data += 7; // type + 4 byte IP + 2 byte port
  1161. plen -= 7;
  1162. } else {
  1163. _phy.close(sock);
  1164. return;
  1165. }
  1166. break;
  1167. case 6: // IPv6
  1168. if (plen >= 19) {
  1169. from.set((const void *)(data + 1),16,((((unsigned int)data[17]) & 0xff) << 8) | (((unsigned int)data[18]) & 0xff));
  1170. data += 19; // type + 16 byte IP + 2 byte port
  1171. plen -= 19;
  1172. } else {
  1173. _phy.close(sock);
  1174. return;
  1175. }
  1176. break;
  1177. case 0: // none/omitted
  1178. ++data;
  1179. --plen;
  1180. break;
  1181. default: // invalid address type
  1182. _phy.close(sock);
  1183. return;
  1184. }
  1185. if (from) {
  1186. InetAddress fakeTcpLocalInterfaceAddress((uint32_t)0xffffffff,0xffff);
  1187. const ZT_ResultCode rc = _node->processWirePacket(
  1188. OSUtils::now(),
  1189. reinterpret_cast<struct sockaddr_storage *>(&fakeTcpLocalInterfaceAddress),
  1190. reinterpret_cast<struct sockaddr_storage *>(&from),
  1191. data,
  1192. plen,
  1193. &_nextBackgroundTaskDeadline);
  1194. if (ZT_ResultCode_isFatal(rc)) {
  1195. char tmp[256];
  1196. Utils::snprintf(tmp,sizeof(tmp),"fatal error code from processWirePacket: %d",(int)rc);
  1197. Mutex::Lock _l(_termReason_m);
  1198. _termReason = ONE_UNRECOVERABLE_ERROR;
  1199. _fatalErrorMessage = tmp;
  1200. this->terminate();
  1201. _phy.close(sock);
  1202. return;
  1203. }
  1204. }
  1205. }
  1206. if (tc->body.length() > (mlen + 5))
  1207. tc->body = tc->body.substr(mlen + 5);
  1208. else tc->body = "";
  1209. } else break;
  1210. }
  1211. break;
  1212. }
  1213. }
  1214. inline void phyOnTcpWritable(PhySocket *sock,void **uptr)
  1215. {
  1216. TcpConnection *tc = reinterpret_cast<TcpConnection *>(*uptr);
  1217. Mutex::Lock _l(tc->writeBuf_m);
  1218. if (tc->writeBuf.length() > 0) {
  1219. long sent = (long)_phy.streamSend(sock,tc->writeBuf.data(),(unsigned long)tc->writeBuf.length(),true);
  1220. if (sent > 0) {
  1221. tc->lastActivity = OSUtils::now();
  1222. if ((unsigned long)sent >= (unsigned long)tc->writeBuf.length()) {
  1223. tc->writeBuf = "";
  1224. _phy.setNotifyWritable(sock,false);
  1225. if (!tc->shouldKeepAlive)
  1226. _phy.close(sock); // will call close handler to delete from _tcpConnections
  1227. } else {
  1228. tc->writeBuf = tc->writeBuf.substr(sent);
  1229. }
  1230. }
  1231. } else {
  1232. _phy.setNotifyWritable(sock,false);
  1233. }
  1234. }
  1235. inline void phyOnFileDescriptorActivity(PhySocket *sock,void **uptr,bool readable,bool writable) {}
  1236. inline void phyOnUnixAccept(PhySocket *sockL,PhySocket *sockN,void **uptrL,void **uptrN) {}
  1237. inline void phyOnUnixClose(PhySocket *sock,void **uptr) {}
  1238. inline void phyOnUnixData(PhySocket *sock,void **uptr,void *data,unsigned long len) {}
  1239. inline void phyOnUnixWritable(PhySocket *sock,void **uptr,bool lwip_invoked) {}
  1240. inline int nodeVirtualNetworkConfigFunction(uint64_t nwid,void **nuptr,enum ZT_VirtualNetworkConfigOperation op,const ZT_VirtualNetworkConfig *nwc)
  1241. {
  1242. Mutex::Lock _l(_nets_m);
  1243. NetworkState &n = _nets[nwid];
  1244. switch(op) {
  1245. case ZT_VIRTUAL_NETWORK_CONFIG_OPERATION_UP:
  1246. if (!n.tap) {
  1247. try {
  1248. char friendlyName[128];
  1249. Utils::snprintf(friendlyName,sizeof(friendlyName),"ZeroTier One [%.16llx]",nwid);
  1250. n.tap = new EthernetTap(
  1251. _homePath.c_str(),
  1252. MAC(nwc->mac),
  1253. nwc->mtu,
  1254. (unsigned int)ZT_IF_METRIC,
  1255. nwid,
  1256. friendlyName,
  1257. StapFrameHandler,
  1258. (void *)this);
  1259. *nuptr = (void *)&n;
  1260. char nlcpath[256];
  1261. Utils::snprintf(nlcpath,sizeof(nlcpath),"%s" ZT_PATH_SEPARATOR_S "networks.d" ZT_PATH_SEPARATOR_S "%.16llx.local.conf",_homePath.c_str(),nwid);
  1262. std::string nlcbuf;
  1263. if (OSUtils::readFile(nlcpath,nlcbuf)) {
  1264. Dictionary<4096> nc;
  1265. nc.load(nlcbuf.c_str());
  1266. Buffer<1024> allowManaged;
  1267. if (nc.get("allowManaged", allowManaged) && allowManaged.size() != 0) {
  1268. std::string addresses (allowManaged.begin(), allowManaged.size());
  1269. if (allowManaged.size() <= 5) { // untidy parsing for backward compatibility
  1270. if (allowManaged[0] == '1' || allowManaged[0] == 't' || allowManaged[0] == 'T') {
  1271. n.settings.allowManaged = true;
  1272. } else {
  1273. n.settings.allowManaged = false;
  1274. }
  1275. } else {
  1276. // this should be a list of IP addresses
  1277. n.settings.allowManaged = true;
  1278. size_t pos = 0;
  1279. while (true) {
  1280. size_t nextPos = addresses.find(',', pos);
  1281. std::string address = addresses.substr(pos, (nextPos == std::string::npos ? addresses.size() : nextPos) - pos);
  1282. n.settings.allowManagedWhitelist.push_back(InetAddress(address));
  1283. if (nextPos == std::string::npos) break;
  1284. pos = nextPos + 1;
  1285. }
  1286. }
  1287. } else {
  1288. n.settings.allowManaged = true;
  1289. }
  1290. n.settings.allowGlobal = nc.getB("allowGlobal", false);
  1291. n.settings.allowDefault = nc.getB("allowDefault", false);
  1292. }
  1293. } catch (std::exception &exc) {
  1294. #ifdef __WINDOWS__
  1295. FILE *tapFailLog = fopen((_homePath + ZT_PATH_SEPARATOR_S"port_error_log.txt").c_str(),"a");
  1296. if (tapFailLog) {
  1297. fprintf(tapFailLog,"%.16llx: %s" ZT_EOL_S,(unsigned long long)nwid,exc.what());
  1298. fclose(tapFailLog);
  1299. }
  1300. #else
  1301. fprintf(stderr,"ERROR: unable to configure virtual network port: %s" ZT_EOL_S,exc.what());
  1302. #endif
  1303. _nets.erase(nwid);
  1304. return -999;
  1305. } catch ( ... ) {
  1306. return -999; // tap init failed
  1307. }
  1308. }
  1309. // After setting up tap, fall through to CONFIG_UPDATE since we also want to do this...
  1310. case ZT_VIRTUAL_NETWORK_CONFIG_OPERATION_CONFIG_UPDATE:
  1311. memcpy(&(n.config),nwc,sizeof(ZT_VirtualNetworkConfig));
  1312. if (n.tap) { // sanity check
  1313. #ifdef __WINDOWS__
  1314. // wait for up to 5 seconds for the WindowsEthernetTap to actually be initialized
  1315. //
  1316. // without WindowsEthernetTap::isInitialized() returning true, the won't actually
  1317. // be online yet and setting managed routes on it will fail.
  1318. const int MAX_SLEEP_COUNT = 500;
  1319. for (int i = 0; !n.tap->isInitialized() && i < MAX_SLEEP_COUNT; i++) {
  1320. Sleep(10);
  1321. }
  1322. #endif
  1323. syncManagedStuff(n,true,true);
  1324. } else {
  1325. _nets.erase(nwid);
  1326. return -999; // tap init failed
  1327. }
  1328. break;
  1329. case ZT_VIRTUAL_NETWORK_CONFIG_OPERATION_DOWN:
  1330. case ZT_VIRTUAL_NETWORK_CONFIG_OPERATION_DESTROY:
  1331. if (n.tap) { // sanity check
  1332. #ifdef __WINDOWS__
  1333. std::string winInstanceId(n.tap->instanceId());
  1334. #endif
  1335. *nuptr = (void *)0;
  1336. delete n.tap;
  1337. _nets.erase(nwid);
  1338. #ifdef __WINDOWS__
  1339. if ((op == ZT_VIRTUAL_NETWORK_CONFIG_OPERATION_DESTROY)&&(winInstanceId.length() > 0))
  1340. WindowsEthernetTap::deletePersistentTapDevice(winInstanceId.c_str());
  1341. #endif
  1342. if (op == ZT_VIRTUAL_NETWORK_CONFIG_OPERATION_DESTROY) {
  1343. char nlcpath[256];
  1344. Utils::snprintf(nlcpath,sizeof(nlcpath),"%s" ZT_PATH_SEPARATOR_S "networks.d" ZT_PATH_SEPARATOR_S "%.16llx.local.conf",_homePath.c_str(),nwid);
  1345. OSUtils::rm(nlcpath);
  1346. }
  1347. } else {
  1348. _nets.erase(nwid);
  1349. }
  1350. break;
  1351. }
  1352. return 0;
  1353. }
  1354. inline void nodeEventCallback(enum ZT_Event event,const void *metaData)
  1355. {
  1356. switch(event) {
  1357. case ZT_EVENT_FATAL_ERROR_IDENTITY_COLLISION: {
  1358. Mutex::Lock _l(_termReason_m);
  1359. _termReason = ONE_IDENTITY_COLLISION;
  1360. _fatalErrorMessage = "identity/address collision";
  1361. this->terminate();
  1362. } break;
  1363. case ZT_EVENT_TRACE: {
  1364. if (metaData) {
  1365. ::fprintf(stderr,"%s" ZT_EOL_S,(const char *)metaData);
  1366. ::fflush(stderr);
  1367. }
  1368. } break;
  1369. case ZT_EVENT_USER_MESSAGE: {
  1370. const ZT_UserMessage *um = reinterpret_cast<const ZT_UserMessage *>(metaData);
  1371. if ((um->typeId == ZT_SOFTWARE_UPDATE_USER_MESSAGE_TYPE)&&(_updater)) {
  1372. _updater->handleSoftwareUpdateUserMessage(um->origin,um->data,um->length);
  1373. }
  1374. } break;
  1375. default:
  1376. break;
  1377. }
  1378. }
  1379. inline long nodeDataStoreGetFunction(const char *name,void *buf,unsigned long bufSize,unsigned long readIndex,unsigned long *totalSize)
  1380. {
  1381. std::string p(_dataStorePrepPath(name));
  1382. if (!p.length())
  1383. return -2;
  1384. FILE *f = fopen(p.c_str(),"rb");
  1385. if (!f)
  1386. return -1;
  1387. if (fseek(f,0,SEEK_END) != 0) {
  1388. fclose(f);
  1389. return -2;
  1390. }
  1391. long ts = ftell(f);
  1392. if (ts < 0) {
  1393. fclose(f);
  1394. return -2;
  1395. }
  1396. *totalSize = (unsigned long)ts;
  1397. if (fseek(f,(long)readIndex,SEEK_SET) != 0) {
  1398. fclose(f);
  1399. return -2;
  1400. }
  1401. long n = (long)fread(buf,1,bufSize,f);
  1402. fclose(f);
  1403. return n;
  1404. }
  1405. inline int nodeDataStorePutFunction(const char *name,const void *data,unsigned long len,int secure)
  1406. {
  1407. std::string p(_dataStorePrepPath(name));
  1408. if (!p.length())
  1409. return -2;
  1410. if (!data) {
  1411. OSUtils::rm(p.c_str());
  1412. return 0;
  1413. }
  1414. FILE *f = fopen(p.c_str(),"wb");
  1415. if (!f)
  1416. return -1;
  1417. if (fwrite(data,len,1,f) == 1) {
  1418. fclose(f);
  1419. if (secure)
  1420. OSUtils::lockDownFile(p.c_str(),false);
  1421. return 0;
  1422. } else {
  1423. fclose(f);
  1424. OSUtils::rm(p.c_str());
  1425. return -1;
  1426. }
  1427. }
  1428. inline int nodeWirePacketSendFunction(const struct sockaddr_storage *localAddr,const struct sockaddr_storage *addr,const void *data,unsigned int len,unsigned int ttl)
  1429. {
  1430. unsigned int fromBindingNo = 0;
  1431. if (addr->ss_family == AF_INET) {
  1432. if (reinterpret_cast<const struct sockaddr_in *>(localAddr)->sin_port == 0) {
  1433. // If sender is sending from wildcard (null address), choose the secondary backup
  1434. // port 1/4 of the time. (but only for IPv4)
  1435. fromBindingNo = (++_udpPortPickerCounter & 0x4) >> 2;
  1436. if (!_ports[fromBindingNo])
  1437. fromBindingNo = 0;
  1438. } else {
  1439. const uint16_t lp = reinterpret_cast<const struct sockaddr_in *>(localAddr)->sin_port;
  1440. if (lp == _portsBE[1])
  1441. fromBindingNo = 1;
  1442. else if (lp == _portsBE[2])
  1443. fromBindingNo = 2;
  1444. }
  1445. #ifdef ZT_TCP_FALLBACK_RELAY
  1446. // TCP fallback tunnel support, currently IPv4 only
  1447. if ((len >= 16)&&(reinterpret_cast<const InetAddress *>(addr)->ipScope() == InetAddress::IP_SCOPE_GLOBAL)) {
  1448. // Engage TCP tunnel fallback if we haven't received anything valid from a global
  1449. // IP address in ZT_TCP_FALLBACK_AFTER milliseconds. If we do start getting
  1450. // valid direct traffic we'll stop using it and close the socket after a while.
  1451. const uint64_t now = OSUtils::now();
  1452. if (((now - _lastDirectReceiveFromGlobal) > ZT_TCP_FALLBACK_AFTER)&&((now - _lastRestart) > ZT_TCP_FALLBACK_AFTER)) {
  1453. if (_tcpFallbackTunnel) {
  1454. Mutex::Lock _l(_tcpFallbackTunnel->writeBuf_m);
  1455. if (!_tcpFallbackTunnel->writeBuf.length())
  1456. _phy.setNotifyWritable(_tcpFallbackTunnel->sock,true);
  1457. unsigned long mlen = len + 7;
  1458. _tcpFallbackTunnel->writeBuf.push_back((char)0x17);
  1459. _tcpFallbackTunnel->writeBuf.push_back((char)0x03);
  1460. _tcpFallbackTunnel->writeBuf.push_back((char)0x03); // fake TLS 1.2 header
  1461. _tcpFallbackTunnel->writeBuf.push_back((char)((mlen >> 8) & 0xff));
  1462. _tcpFallbackTunnel->writeBuf.push_back((char)(mlen & 0xff));
  1463. _tcpFallbackTunnel->writeBuf.push_back((char)4); // IPv4
  1464. _tcpFallbackTunnel->writeBuf.append(reinterpret_cast<const char *>(reinterpret_cast<const void *>(&(reinterpret_cast<const struct sockaddr_in *>(addr)->sin_addr.s_addr))),4);
  1465. _tcpFallbackTunnel->writeBuf.append(reinterpret_cast<const char *>(reinterpret_cast<const void *>(&(reinterpret_cast<const struct sockaddr_in *>(addr)->sin_port))),2);
  1466. _tcpFallbackTunnel->writeBuf.append((const char *)data,len);
  1467. } else if (((now - _lastSendToGlobalV4) < ZT_TCP_FALLBACK_AFTER)&&((now - _lastSendToGlobalV4) > (ZT_PING_CHECK_INVERVAL / 2))) {
  1468. bool connected = false;
  1469. const InetAddress addr(ZT_TCP_FALLBACK_RELAY);
  1470. _phy.tcpConnect(reinterpret_cast<const struct sockaddr *>(&addr),connected);
  1471. }
  1472. }
  1473. _lastSendToGlobalV4 = now;
  1474. }
  1475. #endif // ZT_TCP_FALLBACK_RELAY
  1476. } else if (addr->ss_family == AF_INET6) {
  1477. if (reinterpret_cast<const struct sockaddr_in6 *>(localAddr)->sin6_port != 0) {
  1478. const uint16_t lp = reinterpret_cast<const struct sockaddr_in6 *>(localAddr)->sin6_port;
  1479. if (lp == _portsBE[1])
  1480. fromBindingNo = 1;
  1481. else if (lp == _portsBE[2])
  1482. fromBindingNo = 2;
  1483. }
  1484. } else {
  1485. return -1;
  1486. }
  1487. #ifdef ZT_BREAK_UDP
  1488. if (OSUtils::fileExists("/tmp/ZT_BREAK_UDP"))
  1489. return 0; // silently break UDP
  1490. #endif
  1491. return (_bindings[fromBindingNo].udpSend(_phy,*(reinterpret_cast<const InetAddress *>(localAddr)),*(reinterpret_cast<const InetAddress *>(addr)),data,len,ttl)) ? 0 : -1;
  1492. }
  1493. inline void nodeVirtualNetworkFrameFunction(uint64_t nwid,void **nuptr,uint64_t sourceMac,uint64_t destMac,unsigned int etherType,unsigned int vlanId,const void *data,unsigned int len)
  1494. {
  1495. NetworkState *n = reinterpret_cast<NetworkState *>(*nuptr);
  1496. if ((!n)||(!n->tap))
  1497. return;
  1498. n->tap->put(MAC(sourceMac),MAC(destMac),etherType,data,len);
  1499. }
  1500. inline int nodePathCheckFunction(uint64_t ztaddr,const struct sockaddr_storage *localAddr,const struct sockaddr_storage *remoteAddr)
  1501. {
  1502. // Make sure we're not trying to do ZeroTier-over-ZeroTier
  1503. {
  1504. Mutex::Lock _l(_nets_m);
  1505. for(std::map<uint64_t,NetworkState>::const_iterator n(_nets.begin());n!=_nets.end();++n) {
  1506. if (n->second.tap) {
  1507. std::vector<InetAddress> ips(n->second.tap->ips());
  1508. for(std::vector<InetAddress>::const_iterator i(ips.begin());i!=ips.end();++i) {
  1509. if (i->containsAddress(*(reinterpret_cast<const InetAddress *>(remoteAddr)))) {
  1510. return 0;
  1511. }
  1512. }
  1513. }
  1514. }
  1515. }
  1516. /* Note: I do not think we need to scan for overlap with managed routes
  1517. * because of the "route forking" and interface binding that we do. This
  1518. * ensures (we hope) that ZeroTier traffic will still take the physical
  1519. * path even if its managed routes override this for other traffic. Will
  1520. * revisit if we see recursion problems. */
  1521. // Check blacklists
  1522. const Hashtable< uint64_t,std::vector<InetAddress> > *blh = (const Hashtable< uint64_t,std::vector<InetAddress> > *)0;
  1523. const std::vector<InetAddress> *gbl = (const std::vector<InetAddress> *)0;
  1524. if (remoteAddr->ss_family == AF_INET) {
  1525. blh = &_v4Blacklists;
  1526. gbl = &_globalV4Blacklist;
  1527. } else if (remoteAddr->ss_family == AF_INET6) {
  1528. blh = &_v6Blacklists;
  1529. gbl = &_globalV6Blacklist;
  1530. }
  1531. if (blh) {
  1532. Mutex::Lock _l(_localConfig_m);
  1533. const std::vector<InetAddress> *l = blh->get(ztaddr);
  1534. if (l) {
  1535. for(std::vector<InetAddress>::const_iterator a(l->begin());a!=l->end();++a) {
  1536. if (a->containsAddress(*reinterpret_cast<const InetAddress *>(remoteAddr)))
  1537. return 0;
  1538. }
  1539. }
  1540. for(std::vector<InetAddress>::const_iterator a(gbl->begin());a!=gbl->end();++a) {
  1541. if (a->containsAddress(*reinterpret_cast<const InetAddress *>(remoteAddr)))
  1542. return 0;
  1543. }
  1544. }
  1545. return 1;
  1546. }
  1547. inline int nodePathLookupFunction(uint64_t ztaddr,int family,struct sockaddr_storage *result)
  1548. {
  1549. const Hashtable< uint64_t,std::vector<InetAddress> > *lh = (const Hashtable< uint64_t,std::vector<InetAddress> > *)0;
  1550. if (family < 0)
  1551. lh = (_node->prng() & 1) ? &_v4Hints : &_v6Hints;
  1552. else if (family == AF_INET)
  1553. lh = &_v4Hints;
  1554. else if (family == AF_INET6)
  1555. lh = &_v6Hints;
  1556. else return 0;
  1557. const std::vector<InetAddress> *l = lh->get(ztaddr);
  1558. if ((l)&&(l->size() > 0)) {
  1559. memcpy(result,&((*l)[(unsigned long)_node->prng() % l->size()]),sizeof(struct sockaddr_storage));
  1560. return 1;
  1561. } else return 0;
  1562. }
  1563. inline void tapFrameHandler(uint64_t nwid,const MAC &from,const MAC &to,unsigned int etherType,unsigned int vlanId,const void *data,unsigned int len)
  1564. {
  1565. _node->processVirtualNetworkFrame(OSUtils::now(),nwid,from.toInt(),to.toInt(),etherType,vlanId,data,len,&_nextBackgroundTaskDeadline);
  1566. }
  1567. inline void onHttpRequestToServer(TcpConnection *tc)
  1568. {
  1569. char tmpn[256];
  1570. std::string data;
  1571. std::string contentType("text/plain"); // default if not changed in handleRequest()
  1572. unsigned int scode = 404;
  1573. bool allow;
  1574. {
  1575. Mutex::Lock _l(_localConfig_m);
  1576. if (_allowManagementFrom.size() == 0) {
  1577. allow = (tc->from.ipScope() == InetAddress::IP_SCOPE_LOOPBACK);
  1578. } else {
  1579. allow = false;
  1580. for(std::vector<InetAddress>::const_iterator i(_allowManagementFrom.begin());i!=_allowManagementFrom.end();++i) {
  1581. if (i->containsAddress(tc->from)) {
  1582. allow = true;
  1583. break;
  1584. }
  1585. }
  1586. }
  1587. }
  1588. if (allow) {
  1589. try {
  1590. if (_controlPlane)
  1591. scode = _controlPlane->handleRequest(tc->from,tc->parser.method,tc->url,tc->headers,tc->body,data,contentType);
  1592. else scode = 500;
  1593. } catch (std::exception &exc) {
  1594. fprintf(stderr,"WARNING: unexpected exception processing control HTTP request: %s" ZT_EOL_S,exc.what());
  1595. scode = 500;
  1596. } catch ( ... ) {
  1597. fprintf(stderr,"WARNING: unexpected exception processing control HTTP request: unknown exceptino" ZT_EOL_S);
  1598. scode = 500;
  1599. }
  1600. } else {
  1601. scode = 401;
  1602. }
  1603. const char *scodestr;
  1604. switch(scode) {
  1605. case 200: scodestr = "OK"; break;
  1606. case 400: scodestr = "Bad Request"; break;
  1607. case 401: scodestr = "Unauthorized"; break;
  1608. case 403: scodestr = "Forbidden"; break;
  1609. case 404: scodestr = "Not Found"; break;
  1610. case 500: scodestr = "Internal Server Error"; break;
  1611. case 501: scodestr = "Not Implemented"; break;
  1612. case 503: scodestr = "Service Unavailable"; break;
  1613. default: scodestr = "Error"; break;
  1614. }
  1615. Utils::snprintf(tmpn,sizeof(tmpn),"HTTP/1.1 %.3u %s\r\nCache-Control: no-cache\r\nPragma: no-cache\r\n",scode,scodestr);
  1616. {
  1617. Mutex::Lock _l(tc->writeBuf_m);
  1618. tc->writeBuf.assign(tmpn);
  1619. tc->writeBuf.append("Content-Type: ");
  1620. tc->writeBuf.append(contentType);
  1621. Utils::snprintf(tmpn,sizeof(tmpn),"\r\nContent-Length: %lu\r\n",(unsigned long)data.length());
  1622. tc->writeBuf.append(tmpn);
  1623. if (!tc->shouldKeepAlive)
  1624. tc->writeBuf.append("Connection: close\r\n");
  1625. tc->writeBuf.append("\r\n");
  1626. if (tc->parser.method != HTTP_HEAD)
  1627. tc->writeBuf.append(data);
  1628. }
  1629. _phy.setNotifyWritable(tc->sock,true);
  1630. }
  1631. inline void onHttpResponseFromClient(TcpConnection *tc)
  1632. {
  1633. if (!tc->shouldKeepAlive)
  1634. _phy.close(tc->sock); // will call close handler, which deletes from _tcpConnections
  1635. }
  1636. bool shouldBindInterface(const char *ifname,const InetAddress &ifaddr)
  1637. {
  1638. #if defined(__linux__) || defined(linux) || defined(__LINUX__) || defined(__linux)
  1639. if ((ifname[0] == 'l')&&(ifname[1] == 'o')) return false; // loopback
  1640. if ((ifname[0] == 'z')&&(ifname[1] == 't')) return false; // sanity check: zt#
  1641. if ((ifname[0] == 't')&&(ifname[1] == 'u')&&(ifname[2] == 'n')) return false; // tun# is probably an OpenVPN tunnel or similar
  1642. if ((ifname[0] == 't')&&(ifname[1] == 'a')&&(ifname[2] == 'p')) return false; // tap# is probably an OpenVPN tunnel or similar
  1643. #endif
  1644. #ifdef __APPLE__
  1645. if ((ifname[0] == 'l')&&(ifname[1] == 'o')) return false; // loopback
  1646. if ((ifname[0] == 'z')&&(ifname[1] == 't')) return false; // sanity check: zt#
  1647. if ((ifname[0] == 't')&&(ifname[1] == 'u')&&(ifname[2] == 'n')) return false; // tun# is probably an OpenVPN tunnel or similar
  1648. if ((ifname[0] == 't')&&(ifname[1] == 'a')&&(ifname[2] == 'p')) return false; // tap# is probably an OpenVPN tunnel or similar
  1649. if ((ifname[0] == 'u')&&(ifname[1] == 't')&&(ifname[2] == 'u')&&(ifname[3] == 'n')) return false; // ... as is utun#
  1650. #endif
  1651. {
  1652. Mutex::Lock _l(_localConfig_m);
  1653. for(std::vector<std::string>::const_iterator p(_interfacePrefixBlacklist.begin());p!=_interfacePrefixBlacklist.end();++p) {
  1654. if (!strncmp(p->c_str(),ifname,p->length()))
  1655. return false;
  1656. }
  1657. }
  1658. {
  1659. Mutex::Lock _l(_nets_m);
  1660. for(std::map<uint64_t,NetworkState>::const_iterator n(_nets.begin());n!=_nets.end();++n) {
  1661. if (n->second.tap) {
  1662. std::vector<InetAddress> ips(n->second.tap->ips());
  1663. for(std::vector<InetAddress>::const_iterator i(ips.begin());i!=ips.end();++i) {
  1664. if (i->ipsEqual(ifaddr))
  1665. return false;
  1666. }
  1667. }
  1668. }
  1669. }
  1670. return true;
  1671. }
  1672. std::string _dataStorePrepPath(const char *name) const
  1673. {
  1674. std::string p(_homePath);
  1675. p.push_back(ZT_PATH_SEPARATOR);
  1676. char lastc = (char)0;
  1677. for(const char *n=name;(*n);++n) {
  1678. if ((*n == '.')&&(lastc == '.'))
  1679. return std::string(); // don't allow ../../ stuff as a precaution
  1680. if (*n == '/') {
  1681. OSUtils::mkdir(p.c_str());
  1682. p.push_back(ZT_PATH_SEPARATOR);
  1683. } else p.push_back(*n);
  1684. lastc = *n;
  1685. }
  1686. return p;
  1687. }
  1688. bool _trialBind(unsigned int port)
  1689. {
  1690. struct sockaddr_in in4;
  1691. struct sockaddr_in6 in6;
  1692. PhySocket *tb;
  1693. memset(&in4,0,sizeof(in4));
  1694. in4.sin_family = AF_INET;
  1695. in4.sin_port = Utils::hton((uint16_t)port);
  1696. tb = _phy.udpBind(reinterpret_cast<const struct sockaddr *>(&in4),(void *)0,0);
  1697. if (tb) {
  1698. _phy.close(tb,false);
  1699. tb = _phy.tcpListen(reinterpret_cast<const struct sockaddr *>(&in4),(void *)0);
  1700. if (tb) {
  1701. _phy.close(tb,false);
  1702. return true;
  1703. }
  1704. }
  1705. memset(&in6,0,sizeof(in6));
  1706. in6.sin6_family = AF_INET6;
  1707. in6.sin6_port = Utils::hton((uint16_t)port);
  1708. tb = _phy.udpBind(reinterpret_cast<const struct sockaddr *>(&in6),(void *)0,0);
  1709. if (tb) {
  1710. _phy.close(tb,false);
  1711. tb = _phy.tcpListen(reinterpret_cast<const struct sockaddr *>(&in6),(void *)0);
  1712. if (tb) {
  1713. _phy.close(tb,false);
  1714. return true;
  1715. }
  1716. }
  1717. return false;
  1718. }
  1719. };
  1720. static int SnodeVirtualNetworkConfigFunction(ZT_Node *node,void *uptr,uint64_t nwid,void **nuptr,enum ZT_VirtualNetworkConfigOperation op,const ZT_VirtualNetworkConfig *nwconf)
  1721. { return reinterpret_cast<OneServiceImpl *>(uptr)->nodeVirtualNetworkConfigFunction(nwid,nuptr,op,nwconf); }
  1722. static void SnodeEventCallback(ZT_Node *node,void *uptr,enum ZT_Event event,const void *metaData)
  1723. { reinterpret_cast<OneServiceImpl *>(uptr)->nodeEventCallback(event,metaData); }
  1724. static long SnodeDataStoreGetFunction(ZT_Node *node,void *uptr,const char *name,void *buf,unsigned long bufSize,unsigned long readIndex,unsigned long *totalSize)
  1725. { return reinterpret_cast<OneServiceImpl *>(uptr)->nodeDataStoreGetFunction(name,buf,bufSize,readIndex,totalSize); }
  1726. static int SnodeDataStorePutFunction(ZT_Node *node,void *uptr,const char *name,const void *data,unsigned long len,int secure)
  1727. { return reinterpret_cast<OneServiceImpl *>(uptr)->nodeDataStorePutFunction(name,data,len,secure); }
  1728. static int SnodeWirePacketSendFunction(ZT_Node *node,void *uptr,const struct sockaddr_storage *localAddr,const struct sockaddr_storage *addr,const void *data,unsigned int len,unsigned int ttl)
  1729. { return reinterpret_cast<OneServiceImpl *>(uptr)->nodeWirePacketSendFunction(localAddr,addr,data,len,ttl); }
  1730. static void SnodeVirtualNetworkFrameFunction(ZT_Node *node,void *uptr,uint64_t nwid,void **nuptr,uint64_t sourceMac,uint64_t destMac,unsigned int etherType,unsigned int vlanId,const void *data,unsigned int len)
  1731. { reinterpret_cast<OneServiceImpl *>(uptr)->nodeVirtualNetworkFrameFunction(nwid,nuptr,sourceMac,destMac,etherType,vlanId,data,len); }
  1732. static int SnodePathCheckFunction(ZT_Node *node,void *uptr,uint64_t ztaddr,const struct sockaddr_storage *localAddr,const struct sockaddr_storage *remoteAddr)
  1733. { return reinterpret_cast<OneServiceImpl *>(uptr)->nodePathCheckFunction(ztaddr,localAddr,remoteAddr); }
  1734. static int SnodePathLookupFunction(ZT_Node *node,void *uptr,uint64_t ztaddr,int family,struct sockaddr_storage *result)
  1735. { return reinterpret_cast<OneServiceImpl *>(uptr)->nodePathLookupFunction(ztaddr,family,result); }
  1736. #ifdef ZT_ENABLE_CLUSTER
  1737. static void SclusterSendFunction(void *uptr,unsigned int toMemberId,const void *data,unsigned int len)
  1738. {
  1739. OneServiceImpl *const impl = reinterpret_cast<OneServiceImpl *>(uptr);
  1740. const ClusterDefinition::MemberDefinition &md = (*(impl->_clusterDefinition))[toMemberId];
  1741. if (md.clusterEndpoint)
  1742. impl->_phy.udpSend(impl->_clusterMessageSocket,reinterpret_cast<const struct sockaddr *>(&(md.clusterEndpoint)),data,len);
  1743. }
  1744. static int SclusterGeoIpFunction(void *uptr,const struct sockaddr_storage *addr,int *x,int *y,int *z)
  1745. {
  1746. OneServiceImpl *const impl = reinterpret_cast<OneServiceImpl *>(uptr);
  1747. return (int)(impl->_clusterDefinition->geo().locate(*(reinterpret_cast<const InetAddress *>(addr)),*x,*y,*z));
  1748. }
  1749. #endif
  1750. static void StapFrameHandler(void *uptr,uint64_t nwid,const MAC &from,const MAC &to,unsigned int etherType,unsigned int vlanId,const void *data,unsigned int len)
  1751. { reinterpret_cast<OneServiceImpl *>(uptr)->tapFrameHandler(nwid,from,to,etherType,vlanId,data,len); }
  1752. static int ShttpOnMessageBegin(http_parser *parser)
  1753. {
  1754. TcpConnection *tc = reinterpret_cast<TcpConnection *>(parser->data);
  1755. tc->currentHeaderField = "";
  1756. tc->currentHeaderValue = "";
  1757. tc->messageSize = 0;
  1758. tc->url = "";
  1759. tc->status = "";
  1760. tc->headers.clear();
  1761. tc->body = "";
  1762. return 0;
  1763. }
  1764. static int ShttpOnUrl(http_parser *parser,const char *ptr,size_t length)
  1765. {
  1766. TcpConnection *tc = reinterpret_cast<TcpConnection *>(parser->data);
  1767. tc->messageSize += (unsigned long)length;
  1768. if (tc->messageSize > ZT_MAX_HTTP_MESSAGE_SIZE)
  1769. return -1;
  1770. tc->url.append(ptr,length);
  1771. return 0;
  1772. }
  1773. #if (HTTP_PARSER_VERSION_MAJOR >= 2) && (HTTP_PARSER_VERSION_MINOR >= 2)
  1774. static int ShttpOnStatus(http_parser *parser,const char *ptr,size_t length)
  1775. #else
  1776. static int ShttpOnStatus(http_parser *parser)
  1777. #endif
  1778. {
  1779. /*
  1780. TcpConnection *tc = reinterpret_cast<TcpConnection *>(parser->data);
  1781. tc->messageSize += (unsigned long)length;
  1782. if (tc->messageSize > ZT_MAX_HTTP_MESSAGE_SIZE)
  1783. return -1;
  1784. tc->status.append(ptr,length);
  1785. */
  1786. return 0;
  1787. }
  1788. static int ShttpOnHeaderField(http_parser *parser,const char *ptr,size_t length)
  1789. {
  1790. TcpConnection *tc = reinterpret_cast<TcpConnection *>(parser->data);
  1791. tc->messageSize += (unsigned long)length;
  1792. if (tc->messageSize > ZT_MAX_HTTP_MESSAGE_SIZE)
  1793. return -1;
  1794. if ((tc->currentHeaderField.length())&&(tc->currentHeaderValue.length())) {
  1795. tc->headers[tc->currentHeaderField] = tc->currentHeaderValue;
  1796. tc->currentHeaderField = "";
  1797. tc->currentHeaderValue = "";
  1798. }
  1799. for(size_t i=0;i<length;++i)
  1800. tc->currentHeaderField.push_back(OSUtils::toLower(ptr[i]));
  1801. return 0;
  1802. }
  1803. static int ShttpOnValue(http_parser *parser,const char *ptr,size_t length)
  1804. {
  1805. TcpConnection *tc = reinterpret_cast<TcpConnection *>(parser->data);
  1806. tc->messageSize += (unsigned long)length;
  1807. if (tc->messageSize > ZT_MAX_HTTP_MESSAGE_SIZE)
  1808. return -1;
  1809. tc->currentHeaderValue.append(ptr,length);
  1810. return 0;
  1811. }
  1812. static int ShttpOnHeadersComplete(http_parser *parser)
  1813. {
  1814. TcpConnection *tc = reinterpret_cast<TcpConnection *>(parser->data);
  1815. if ((tc->currentHeaderField.length())&&(tc->currentHeaderValue.length()))
  1816. tc->headers[tc->currentHeaderField] = tc->currentHeaderValue;
  1817. return 0;
  1818. }
  1819. static int ShttpOnBody(http_parser *parser,const char *ptr,size_t length)
  1820. {
  1821. TcpConnection *tc = reinterpret_cast<TcpConnection *>(parser->data);
  1822. tc->messageSize += (unsigned long)length;
  1823. if (tc->messageSize > ZT_MAX_HTTP_MESSAGE_SIZE)
  1824. return -1;
  1825. tc->body.append(ptr,length);
  1826. return 0;
  1827. }
  1828. static int ShttpOnMessageComplete(http_parser *parser)
  1829. {
  1830. TcpConnection *tc = reinterpret_cast<TcpConnection *>(parser->data);
  1831. tc->shouldKeepAlive = (http_should_keep_alive(parser) != 0);
  1832. tc->lastActivity = OSUtils::now();
  1833. if (tc->type == TcpConnection::TCP_HTTP_INCOMING) {
  1834. tc->parent->onHttpRequestToServer(tc);
  1835. } else {
  1836. tc->parent->onHttpResponseFromClient(tc);
  1837. }
  1838. return 0;
  1839. }
  1840. } // anonymous namespace
  1841. std::string OneService::platformDefaultHomePath()
  1842. {
  1843. return OSUtils::platformDefaultHomePath();
  1844. }
  1845. OneService *OneService::newInstance(const char *hp,unsigned int port) { return new OneServiceImpl(hp,port); }
  1846. OneService::~OneService() {}
  1847. } // namespace ZeroTier