OneService.cpp 70 KB

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