OneService.cpp 70 KB

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