OneService.cpp 70 KB

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