OneService.cpp 78 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261
  1. /*
  2. * Copyright (c)2019 ZeroTier, Inc.
  3. *
  4. * Use of this software is governed by the Business Source License included
  5. * in the LICENSE.TXT file in the project's root directory.
  6. *
  7. * Change Date: 2023-01-01
  8. *
  9. * On the date above, in accordance with the Business Source License, use
  10. * of this software will be governed by version 2.0 of the Apache License.
  11. */
  12. /****/
  13. #include <stdio.h>
  14. #include <stdlib.h>
  15. #include <string.h>
  16. #include <stdint.h>
  17. #include <string>
  18. #include <map>
  19. #include <vector>
  20. #include <algorithm>
  21. #include <list>
  22. #include <thread>
  23. #include <mutex>
  24. #include <condition_variable>
  25. #include "../include/ZeroTierCore.h"
  26. #include "../node/Constants.hpp"
  27. #include "../node/Mutex.hpp"
  28. #include "../node/Node.hpp"
  29. #include "../node/Utils.hpp"
  30. #include "../node/InetAddress.hpp"
  31. #include "../node/MAC.hpp"
  32. #include "../node/Identity.hpp"
  33. #include "../node/Salsa20.hpp"
  34. #include "../node/Poly1305.hpp"
  35. #include "../node/SHA512.hpp"
  36. #include "../osdep/Phy.hpp"
  37. #include "../osdep/Thread.hpp"
  38. #include "../osdep/OSUtils.hpp"
  39. #include "../osdep/Http.hpp"
  40. #include "../osdep/PortMapper.hpp"
  41. #include "../osdep/Binder.hpp"
  42. #include "../osdep/ManagedRoute.hpp"
  43. #include "../osdep/BlockingQueue.hpp"
  44. #include "OneService.hpp"
  45. #ifdef __WINDOWS__
  46. #include <WinSock2.h>
  47. #include <Windows.h>
  48. #include <ShlObj.h>
  49. #include <netioapi.h>
  50. #include <iphlpapi.h>
  51. //#include <unistd.h>
  52. #define stat _stat
  53. #else
  54. #include <sys/types.h>
  55. #include <sys/socket.h>
  56. #include <sys/stat.h>
  57. #include <sys/wait.h>
  58. #include <unistd.h>
  59. #include <ifaddrs.h>
  60. #endif
  61. #ifdef ZT_USE_SYSTEM_HTTP_PARSER
  62. #include <http_parser.h>
  63. #else
  64. #include "../ext/http-parser/http_parser.h"
  65. #endif
  66. #include "../ext/json/json.hpp"
  67. using json = nlohmann::json;
  68. #include "../controller/EmbeddedNetworkController.hpp"
  69. #include "../controller/RabbitMQ.hpp"
  70. #include "../osdep/EthernetTap.hpp"
  71. #ifdef __WINDOWS__
  72. #include "../osdep/WindowsEthernetTap.hpp"
  73. #endif
  74. // Sanity limits for HTTP
  75. #define ZT_MAX_HTTP_MESSAGE_SIZE (1024 * 1024 * 64)
  76. #define ZT_MAX_HTTP_CONNECTIONS 65536
  77. // Interface metric for ZeroTier taps -- this ensures that if we are on WiFi and also
  78. // bridged via ZeroTier to the same LAN traffic will (if the OS is sane) prefer WiFi.
  79. #define ZT_IF_METRIC 5000
  80. // How often to check for new multicast subscriptions on a tap device
  81. #define ZT_TAP_CHECK_MULTICAST_INTERVAL 5000
  82. // How often to check for local interface addresses
  83. #define ZT_LOCAL_INTERFACE_CHECK_INTERVAL 60000
  84. // How often local.conf is checked for changes
  85. #define ZT_LOCAL_CONF_FILE_CHECK_INTERVAL 10000
  86. namespace ZeroTier {
  87. namespace {
  88. static void _networkToJson(nlohmann::json &nj,const ZT_VirtualNetworkConfig *nc,const std::string &portDeviceName,const OneService::NetworkSettings &localSettings)
  89. {
  90. char tmp[256];
  91. const char *nstatus = "",*ntype = "";
  92. switch(nc->status) {
  93. case ZT_NETWORK_STATUS_REQUESTING_CONFIGURATION: nstatus = "REQUESTING_CONFIGURATION"; break;
  94. case ZT_NETWORK_STATUS_OK: nstatus = "OK"; break;
  95. case ZT_NETWORK_STATUS_ACCESS_DENIED: nstatus = "ACCESS_DENIED"; break;
  96. case ZT_NETWORK_STATUS_NOT_FOUND: nstatus = "NOT_FOUND"; break;
  97. case ZT_NETWORK_STATUS_PORT_ERROR: nstatus = "PORT_ERROR"; break;
  98. case ZT_NETWORK_STATUS_CLIENT_TOO_OLD: nstatus = "CLIENT_TOO_OLD"; break;
  99. }
  100. switch(nc->type) {
  101. case ZT_NETWORK_TYPE_PRIVATE: ntype = "PRIVATE"; break;
  102. case ZT_NETWORK_TYPE_PUBLIC: ntype = "PUBLIC"; break;
  103. }
  104. OSUtils::ztsnprintf(tmp,sizeof(tmp),"%.16llx",nc->nwid);
  105. nj["id"] = tmp;
  106. nj["nwid"] = tmp;
  107. OSUtils::ztsnprintf(tmp,sizeof(tmp),"%.2x:%.2x:%.2x:%.2x:%.2x:%.2x",(unsigned int)((nc->mac >> 40) & 0xff),(unsigned int)((nc->mac >> 32) & 0xff),(unsigned int)((nc->mac >> 24) & 0xff),(unsigned int)((nc->mac >> 16) & 0xff),(unsigned int)((nc->mac >> 8) & 0xff),(unsigned int)(nc->mac & 0xff));
  108. nj["mac"] = tmp;
  109. nj["name"] = nc->name;
  110. nj["status"] = nstatus;
  111. nj["type"] = ntype;
  112. nj["mtu"] = nc->mtu;
  113. nj["dhcp"] = (bool)(nc->dhcp != 0);
  114. nj["bridge"] = (bool)(nc->bridge != 0);
  115. nj["broadcastEnabled"] = (bool)(nc->broadcastEnabled != 0);
  116. nj["portError"] = nc->portError;
  117. nj["netconfRevision"] = nc->netconfRevision;
  118. nj["portDeviceName"] = portDeviceName;
  119. nj["allowManaged"] = localSettings.allowManaged;
  120. nj["allowGlobal"] = localSettings.allowGlobal;
  121. nj["allowDefault"] = localSettings.allowDefault;
  122. nlohmann::json aa = nlohmann::json::array();
  123. for(unsigned int i=0;i<nc->assignedAddressCount;++i) {
  124. aa.push_back(reinterpret_cast<const InetAddress *>(&(nc->assignedAddresses[i]))->toString(tmp));
  125. }
  126. nj["assignedAddresses"] = aa;
  127. nlohmann::json ra = nlohmann::json::array();
  128. for(unsigned int i=0;i<nc->routeCount;++i) {
  129. nlohmann::json rj;
  130. rj["target"] = reinterpret_cast<const InetAddress *>(&(nc->routes[i].target))->toString(tmp);
  131. if (nc->routes[i].via.ss_family == nc->routes[i].target.ss_family)
  132. rj["via"] = reinterpret_cast<const InetAddress *>(&(nc->routes[i].via))->toIpString(tmp);
  133. else rj["via"] = nlohmann::json();
  134. rj["flags"] = (int)nc->routes[i].flags;
  135. rj["metric"] = (int)nc->routes[i].metric;
  136. ra.push_back(rj);
  137. }
  138. nj["routes"] = ra;
  139. nlohmann::json mca = nlohmann::json::array();
  140. for(unsigned int i=0;i<nc->multicastSubscriptionCount;++i) {
  141. nlohmann::json m;
  142. m["mac"] = MAC(nc->multicastSubscriptions[i].mac).toString(tmp);
  143. m["adi"] = nc->multicastSubscriptions[i].adi;
  144. mca.push_back(m);
  145. }
  146. nj["multicastSubscriptions"] = mca;
  147. }
  148. static void _peerToJson(nlohmann::json &pj,const ZT_Peer *peer)
  149. {
  150. char tmp[256];
  151. const char *prole = "";
  152. switch(peer->role) {
  153. case ZT_PEER_ROLE_LEAF: prole = "LEAF"; break;
  154. case ZT_PEER_ROLE_MOON: prole = "MOON"; break;
  155. case ZT_PEER_ROLE_PLANET: prole = "PLANET"; break;
  156. }
  157. OSUtils::ztsnprintf(tmp,sizeof(tmp),"%.10llx",peer->address);
  158. pj["address"] = tmp;
  159. pj["versionMajor"] = peer->versionMajor;
  160. pj["versionMinor"] = peer->versionMinor;
  161. pj["versionRev"] = peer->versionRev;
  162. OSUtils::ztsnprintf(tmp,sizeof(tmp),"%d.%d.%d",peer->versionMajor,peer->versionMinor,peer->versionRev);
  163. pj["version"] = tmp;
  164. pj["latency"] = peer->latency;
  165. pj["role"] = prole;
  166. nlohmann::json pa = nlohmann::json::array();
  167. for(unsigned int i=0;i<peer->pathCount;++i) {
  168. int64_t lastSend = peer->paths[i].lastSend;
  169. int64_t lastReceive = peer->paths[i].lastReceive;
  170. nlohmann::json j;
  171. j["address"] = reinterpret_cast<const InetAddress *>(&(peer->paths[i].address))->toString(tmp);
  172. j["lastSend"] = (lastSend < 0) ? 0 : lastSend;
  173. j["lastReceive"] = (lastReceive < 0) ? 0 : lastReceive;
  174. j["trustedPathId"] = peer->paths[i].trustedPathId;
  175. j["active"] = (bool)(peer->paths[i].expired == 0);
  176. j["expired"] = (bool)(peer->paths[i].expired != 0);
  177. j["preferred"] = (bool)(peer->paths[i].preferred != 0);
  178. pa.push_back(j);
  179. }
  180. pj["paths"] = pa;
  181. }
  182. static void _peerAggregateLinkToJson(nlohmann::json &pj,const ZT_Peer *peer)
  183. {
  184. char tmp[256];
  185. OSUtils::ztsnprintf(tmp,sizeof(tmp),"%.10llx",peer->address);
  186. pj["aggregateLinkLatency"] = peer->latency;
  187. nlohmann::json pa = nlohmann::json::array();
  188. for(unsigned int i=0;i<peer->pathCount;++i) {
  189. int64_t lastSend = peer->paths[i].lastSend;
  190. int64_t lastReceive = peer->paths[i].lastReceive;
  191. nlohmann::json j;
  192. j["address"] = reinterpret_cast<const InetAddress *>(&(peer->paths[i].address))->toString(tmp);
  193. j["lastSend"] = (lastSend < 0) ? 0 : lastSend;
  194. j["lastReceive"] = (lastReceive < 0) ? 0 : lastReceive;
  195. //j["trustedPathId"] = peer->paths[i].trustedPathId;
  196. //j["active"] = (bool)(peer->paths[i].expired == 0);
  197. //j["expired"] = (bool)(peer->paths[i].expired != 0);
  198. //j["preferred"] = (bool)(peer->paths[i].preferred != 0);
  199. j["latency"] = peer->paths[i].latency;
  200. j["pdv"] = peer->paths[i].packetDelayVariance;
  201. //j["throughputDisturbCoeff"] = peer->paths[i].throughputDisturbCoeff;
  202. //j["packetErrorRatio"] = peer->paths[i].packetErrorRatio;
  203. //j["packetLossRatio"] = peer->paths[i].packetLossRatio;
  204. j["stability"] = peer->paths[i].stability;
  205. j["throughput"] = peer->paths[i].throughput;
  206. //j["maxThroughput"] = peer->paths[i].maxThroughput;
  207. j["allocation"] = peer->paths[i].allocation;
  208. j["ifname"] = peer->paths[i].ifname;
  209. pa.push_back(j);
  210. }
  211. pj["paths"] = pa;
  212. }
  213. class OneServiceImpl;
  214. static int SnodeVirtualNetworkConfigFunction(ZT_Node *node,void *uptr,void *tptr,uint64_t nwid,void **nuptr,enum ZT_VirtualNetworkConfigOperation op,const ZT_VirtualNetworkConfig *nwconf);
  215. static void SnodeEventCallback(ZT_Node *node,void *uptr,void *tptr,enum ZT_Event event,const void *metaData);
  216. static void SnodeStatePutFunction(ZT_Node *node,void *uptr,void *tptr,enum ZT_StateObjectType type,const uint64_t id[2],const void *data,int len);
  217. static int SnodeStateGetFunction(ZT_Node *node,void *uptr,void *tptr,enum ZT_StateObjectType type,const uint64_t id[2],void *data,unsigned int maxlen);
  218. static int SnodeWirePacketSendFunction(ZT_Node *node,void *uptr,void *tptr,int64_t localSocket,const struct sockaddr_storage *addr,const void *data,unsigned int len,unsigned int ttl);
  219. static void SnodeVirtualNetworkFrameFunction(ZT_Node *node,void *uptr,void *tptr,uint64_t nwid,void **nuptr,uint64_t sourceMac,uint64_t destMac,unsigned int etherType,unsigned int vlanId,const void *data,unsigned int len);
  220. static int SnodePathCheckFunction(ZT_Node *node,void *uptr,void *tptr,uint64_t ztaddr,int64_t localSocket,const struct sockaddr_storage *remoteAddr);
  221. static int SnodePathLookupFunction(ZT_Node *node,void *uptr,void *tptr,uint64_t ztaddr,int family,struct sockaddr_storage *result);
  222. static void StapFrameHandler(void *uptr,void *tptr,uint64_t nwid,const MAC &from,const MAC &to,unsigned int etherType,unsigned int vlanId,const void *data,unsigned int len);
  223. static int ShttpOnMessageBegin(http_parser *parser);
  224. static int ShttpOnUrl(http_parser *parser,const char *ptr,size_t length);
  225. #if (HTTP_PARSER_VERSION_MAJOR >= 2) && (HTTP_PARSER_VERSION_MINOR >= 2)
  226. static int ShttpOnStatus(http_parser *parser,const char *ptr,size_t length);
  227. #else
  228. static int ShttpOnStatus(http_parser *parser);
  229. #endif
  230. static int ShttpOnHeaderField(http_parser *parser,const char *ptr,size_t length);
  231. static int ShttpOnValue(http_parser *parser,const char *ptr,size_t length);
  232. static int ShttpOnHeadersComplete(http_parser *parser);
  233. static int ShttpOnBody(http_parser *parser,const char *ptr,size_t length);
  234. static int ShttpOnMessageComplete(http_parser *parser);
  235. #if (HTTP_PARSER_VERSION_MAJOR >= 2) && (HTTP_PARSER_VERSION_MINOR >= 1)
  236. static const struct http_parser_settings HTTP_PARSER_SETTINGS = {
  237. ShttpOnMessageBegin,
  238. ShttpOnUrl,
  239. ShttpOnStatus,
  240. ShttpOnHeaderField,
  241. ShttpOnValue,
  242. ShttpOnHeadersComplete,
  243. ShttpOnBody,
  244. ShttpOnMessageComplete
  245. };
  246. #else
  247. static const struct http_parser_settings HTTP_PARSER_SETTINGS = {
  248. ShttpOnMessageBegin,
  249. ShttpOnUrl,
  250. ShttpOnHeaderField,
  251. ShttpOnValue,
  252. ShttpOnHeadersComplete,
  253. ShttpOnBody,
  254. ShttpOnMessageComplete
  255. };
  256. #endif
  257. /**
  258. * A TCP connection and related state and buffers
  259. */
  260. struct TcpConnection
  261. {
  262. enum {
  263. TCP_UNCATEGORIZED_INCOMING, // uncategorized incoming connection
  264. TCP_HTTP_INCOMING,
  265. } type;
  266. OneServiceImpl *parent;
  267. PhySocket *sock;
  268. InetAddress remoteAddr;
  269. uint64_t lastReceive;
  270. // Used for inbound HTTP connections
  271. http_parser parser;
  272. unsigned long messageSize;
  273. std::string currentHeaderField;
  274. std::string currentHeaderValue;
  275. std::string url;
  276. std::string status;
  277. std::map< std::string,std::string > headers;
  278. std::string readq;
  279. std::string writeq;
  280. Mutex writeq_m;
  281. };
  282. class OneServiceImpl : public OneService
  283. {
  284. public:
  285. // begin member variables --------------------------------------------------
  286. const std::string _homePath;
  287. std::string _authToken;
  288. std::string _controllerDbPath;
  289. const std::string _networksPath;
  290. const std::string _moonsPath;
  291. EmbeddedNetworkController *_controller;
  292. Phy<OneServiceImpl *> _phy;
  293. Node *_node;
  294. PhySocket *_localControlSocket4;
  295. PhySocket *_localControlSocket6;
  296. bool _updateAutoApply;
  297. bool _allowSecondaryPort;
  298. unsigned int _multipathMode;
  299. unsigned int _primaryPort;
  300. unsigned int _secondaryPort;
  301. unsigned int _tertiaryPort;
  302. // Local configuration and memo-ized information from it
  303. json _localConfig;
  304. Hashtable< uint64_t,std::vector<InetAddress> > _v4Hints;
  305. Hashtable< uint64_t,std::vector<InetAddress> > _v6Hints;
  306. Hashtable< uint64_t,std::vector<InetAddress> > _v4Blacklists;
  307. Hashtable< uint64_t,std::vector<InetAddress> > _v6Blacklists;
  308. std::vector< InetAddress > _globalV4Blacklist;
  309. std::vector< InetAddress > _globalV6Blacklist;
  310. std::vector< InetAddress > _allowManagementFrom;
  311. std::vector< std::string > _interfacePrefixBlacklist;
  312. Mutex _localConfig_m;
  313. std::vector<InetAddress> _explicitBind;
  314. /*
  315. * To attempt to handle NAT/gateway craziness we use three local UDP ports:
  316. *
  317. * [0] is the normal/default port, usually 9993
  318. * [1] is a port derived from our ZeroTier address
  319. * [2] is a port computed from the normal/default for use with uPnP/NAT-PMP mappings
  320. *
  321. * [2] exists because on some gateways trying to do regular NAT-t interferes
  322. * destructively with uPnP port mapping behavior in very weird buggy ways.
  323. * It's only used if uPnP/NAT-PMP is enabled in this build.
  324. */
  325. unsigned int _ports[3];
  326. Binder _binder;
  327. // Time we last received a packet from a global address
  328. uint64_t _lastDirectReceiveFromGlobal;
  329. // Last potential sleep/wake event
  330. uint64_t _lastRestart;
  331. // Deadline for the next background task service function
  332. volatile int64_t _nextBackgroundTaskDeadline;
  333. // Configured networks
  334. struct NetworkState
  335. {
  336. NetworkState() :
  337. tap((EthernetTap *)0)
  338. {
  339. // Real defaults are in network 'up' code in network event handler
  340. settings.allowManaged = true;
  341. settings.allowGlobal = false;
  342. settings.allowDefault = false;
  343. }
  344. std::shared_ptr<EthernetTap> tap;
  345. ZT_VirtualNetworkConfig config; // memcpy() of raw config from core
  346. std::vector<InetAddress> managedIps;
  347. std::list< SharedPtr<ManagedRoute> > managedRoutes;
  348. NetworkSettings settings;
  349. };
  350. std::map<uint64_t,NetworkState> _nets;
  351. Mutex _nets_m;
  352. // Active TCP/IP connections
  353. std::vector< TcpConnection * > _tcpConnections;
  354. Mutex _tcpConnections_m;
  355. // Termination status information
  356. ReasonForTermination _termReason;
  357. std::string _fatalErrorMessage;
  358. Mutex _termReason_m;
  359. // uPnP/NAT-PMP port mapper if enabled
  360. bool _portMappingEnabled; // local.conf settings
  361. PortMapper *_portMapper;
  362. // Set to false to force service to stop
  363. volatile bool _run;
  364. Mutex _run_m;
  365. MQConfig *_mqc;
  366. // end member variables ----------------------------------------------------
  367. OneServiceImpl(const char *hp,unsigned int port) :
  368. _homePath((hp) ? hp : ".")
  369. ,_controllerDbPath(_homePath + ZT_PATH_SEPARATOR_S "controller.d")
  370. ,_networksPath(_homePath + ZT_PATH_SEPARATOR_S "networks.d")
  371. ,_moonsPath(_homePath + ZT_PATH_SEPARATOR_S "moons.d")
  372. ,_controller((EmbeddedNetworkController *)0)
  373. ,_phy(this,false,true)
  374. ,_node((Node *)0)
  375. ,_localControlSocket4((PhySocket *)0)
  376. ,_localControlSocket6((PhySocket *)0)
  377. ,_updateAutoApply(false)
  378. ,_primaryPort(port)
  379. ,_lastDirectReceiveFromGlobal(0)
  380. ,_lastRestart(0)
  381. ,_nextBackgroundTaskDeadline(0)
  382. ,_termReason(ONE_STILL_RUNNING)
  383. ,_portMappingEnabled(true)
  384. ,_portMapper((PortMapper *)0)
  385. ,_run(true)
  386. ,_mqc(NULL)
  387. {
  388. _ports[0] = 0;
  389. _ports[1] = 0;
  390. _ports[2] = 0;
  391. }
  392. virtual ~OneServiceImpl()
  393. {
  394. _binder.closeAll(_phy);
  395. _phy.close(_localControlSocket4);
  396. _phy.close(_localControlSocket6);
  397. delete _portMapper;
  398. delete _controller;
  399. delete _mqc;
  400. }
  401. virtual ReasonForTermination run()
  402. {
  403. try {
  404. {
  405. const std::string authTokenPath(_homePath + ZT_PATH_SEPARATOR_S "authtoken.secret");
  406. if (!OSUtils::readFile(authTokenPath.c_str(),_authToken)) {
  407. unsigned char foo[24];
  408. Utils::getSecureRandom(foo,sizeof(foo));
  409. _authToken = "";
  410. for(unsigned int i=0;i<sizeof(foo);++i)
  411. _authToken.push_back("abcdefghijklmnopqrstuvwxyz0123456789"[(unsigned long)foo[i] % 36]);
  412. if (!OSUtils::writeFile(authTokenPath.c_str(),_authToken)) {
  413. Mutex::Lock _l(_termReason_m);
  414. _termReason = ONE_UNRECOVERABLE_ERROR;
  415. _fatalErrorMessage = "authtoken.secret could not be written";
  416. return _termReason;
  417. } else {
  418. OSUtils::lockDownFile(authTokenPath.c_str(),false);
  419. }
  420. }
  421. _authToken = OSUtils::trimString(_authToken);
  422. }
  423. {
  424. struct ZT_Node_Callbacks cb;
  425. cb.stateGetFunction = SnodeStateGetFunction;
  426. cb.statePutFunction = SnodeStatePutFunction;
  427. cb.wirePacketSendFunction = SnodeWirePacketSendFunction;
  428. cb.virtualNetworkFrameFunction = SnodeVirtualNetworkFrameFunction;
  429. cb.virtualNetworkConfigFunction = SnodeVirtualNetworkConfigFunction;
  430. cb.eventCallback = SnodeEventCallback;
  431. cb.pathCheckFunction = SnodePathCheckFunction;
  432. cb.pathLookupFunction = SnodePathLookupFunction;
  433. _node = new Node(this,(void *)0,&cb,OSUtils::now());
  434. }
  435. // local.conf
  436. readLocalSettings();
  437. applyLocalConfig();
  438. // Make sure we can use the primary port, and hunt for one if configured to do so
  439. const int portTrials = (_primaryPort == 0) ? 256 : 1; // if port is 0, pick random
  440. for(int k=0;k<portTrials;++k) {
  441. if (_primaryPort == 0) {
  442. unsigned int randp = 0;
  443. Utils::getSecureRandom(&randp,sizeof(randp));
  444. _primaryPort = 20000 + (randp % 45500);
  445. }
  446. if (_trialBind(_primaryPort)) {
  447. _ports[0] = _primaryPort;
  448. } else {
  449. _primaryPort = 0;
  450. }
  451. }
  452. if (_ports[0] == 0) {
  453. Mutex::Lock _l(_termReason_m);
  454. _termReason = ONE_UNRECOVERABLE_ERROR;
  455. _fatalErrorMessage = "cannot bind to local control interface port";
  456. return _termReason;
  457. }
  458. // Bind TCP control socket to 127.0.0.1 and ::1 as well for loopback TCP control socket queries
  459. {
  460. struct sockaddr_in lo4;
  461. memset(&lo4,0,sizeof(lo4));
  462. lo4.sin_family = AF_INET;
  463. lo4.sin_addr.s_addr = Utils::hton((uint32_t)0x7f000001);
  464. lo4.sin_port = Utils::hton((uint16_t)_ports[0]);
  465. _localControlSocket4 = _phy.tcpListen((const struct sockaddr *)&lo4);
  466. struct sockaddr_in6 lo6;
  467. memset(&lo6,0,sizeof(lo6));
  468. lo6.sin6_family = AF_INET6;
  469. lo6.sin6_addr.s6_addr[15] = 1;
  470. lo6.sin6_port = lo4.sin_port;
  471. _localControlSocket6 = _phy.tcpListen((const struct sockaddr *)&lo6);
  472. }
  473. // Save primary port to a file so CLIs and GUIs can learn it easily
  474. char portstr[64];
  475. OSUtils::ztsnprintf(portstr,sizeof(portstr),"%u",_ports[0]);
  476. OSUtils::writeFile((_homePath + ZT_PATH_SEPARATOR_S "zerotier-one.port").c_str(),std::string(portstr));
  477. // Attempt to bind to a secondary port chosen from our ZeroTier address.
  478. // This exists because there are buggy NATs out there that fail if more
  479. // than one device behind the same NAT tries to use the same internal
  480. // private address port number. Buggy NATs are a running theme.
  481. if (_allowSecondaryPort) {
  482. if (_secondaryPort) {
  483. _ports[1] = _secondaryPort;
  484. } else {
  485. _ports[1] = 20000 + ((unsigned int)_node->address() % 45500);
  486. for(int i=0;;++i) {
  487. if (i > 1000) {
  488. _ports[1] = 0;
  489. break;
  490. } else if (++_ports[1] >= 65536) {
  491. _ports[1] = 20000;
  492. }
  493. if (_trialBind(_ports[1]))
  494. break;
  495. }
  496. }
  497. }
  498. if (_portMappingEnabled) {
  499. // If we're running uPnP/NAT-PMP, bind a *third* port for that. We can't
  500. // use the other two ports for that because some NATs do really funky
  501. // stuff with ports that are explicitly mapped that breaks things.
  502. if (_ports[1]) {
  503. if (_tertiaryPort) {
  504. _ports[2] = _tertiaryPort;
  505. } else {
  506. _ports[2] = _ports[1];
  507. for(int i=0;;++i) {
  508. if (i > 1000) {
  509. _ports[2] = 0;
  510. break;
  511. } else if (++_ports[2] >= 65536) {
  512. _ports[2] = 20000;
  513. }
  514. if (_trialBind(_ports[2]))
  515. break;
  516. }
  517. if (_ports[2]) {
  518. char uniqueName[64];
  519. OSUtils::ztsnprintf(uniqueName,sizeof(uniqueName),"ZeroTier/%.10llx@%u",_node->address(),_ports[2]);
  520. _portMapper = new PortMapper(_ports[2],uniqueName);
  521. }
  522. }
  523. }
  524. }
  525. // Delete legacy iddb.d if present (cleanup)
  526. OSUtils::rmDashRf((_homePath + ZT_PATH_SEPARATOR_S "iddb.d").c_str());
  527. // Network controller is now enabled by default for desktop and server
  528. _controller = new EmbeddedNetworkController(_node,_homePath.c_str(),_controllerDbPath.c_str(),_ports[0], _mqc);
  529. _node->setController((void *)_controller);
  530. // Join existing networks in networks.d
  531. {
  532. std::vector<std::string> networksDotD(OSUtils::listDirectory((_homePath + ZT_PATH_SEPARATOR_S "networks.d").c_str()));
  533. for(std::vector<std::string>::iterator f(networksDotD.begin());f!=networksDotD.end();++f) {
  534. std::size_t dot = f->find_last_of('.');
  535. if ((dot == 16)&&(f->substr(16) == ".conf"))
  536. _node->join(Utils::hexStrToU64(f->substr(0,dot).c_str()),(void *)0,(void *)0);
  537. }
  538. }
  539. // Main I/O loop
  540. _nextBackgroundTaskDeadline = 0;
  541. int64_t clockShouldBe = OSUtils::now();
  542. _lastRestart = clockShouldBe;
  543. int64_t lastTapMulticastGroupCheck = 0;
  544. int64_t lastBindRefresh = 0;
  545. int64_t lastMultipathModeUpdate = 0;
  546. int64_t lastCleanedPeersDb = 0;
  547. int64_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
  548. int64_t lastLocalConfFileCheck = OSUtils::now();
  549. for(;;) {
  550. _run_m.lock();
  551. if (!_run) {
  552. _run_m.unlock();
  553. _termReason_m.lock();
  554. _termReason = ONE_NORMAL_TERMINATION;
  555. _termReason_m.unlock();
  556. break;
  557. } else {
  558. _run_m.unlock();
  559. }
  560. const int64_t now = OSUtils::now();
  561. // Attempt to detect sleep/wake events by detecting delay overruns
  562. bool restarted = false;
  563. if ((now > clockShouldBe)&&((now - clockShouldBe) > 10000)) {
  564. _lastRestart = now;
  565. restarted = true;
  566. }
  567. // Reload local.conf if anything changed recently
  568. if ((now - lastLocalConfFileCheck) >= ZT_LOCAL_CONF_FILE_CHECK_INTERVAL) {
  569. lastLocalConfFileCheck = now;
  570. struct stat result;
  571. if(stat((_homePath + ZT_PATH_SEPARATOR_S "local.conf").c_str(), &result)==0) {
  572. int64_t mod_time = result.st_mtime * 1000;
  573. if ((now - mod_time) <= ZT_LOCAL_CONF_FILE_CHECK_INTERVAL) {
  574. readLocalSettings();
  575. applyLocalConfig();
  576. }
  577. }
  578. }
  579. // Refresh bindings in case device's interfaces have changed, and also sync routes to update any shadow routes (e.g. shadow default)
  580. if (((now - lastBindRefresh) >= (_multipathMode ? ZT_BINDER_REFRESH_PERIOD / 8 : ZT_BINDER_REFRESH_PERIOD))||(restarted)) {
  581. lastBindRefresh = now;
  582. unsigned int p[3];
  583. unsigned int pc = 0;
  584. for(int i=0;i<3;++i) {
  585. if (_ports[i])
  586. p[pc++] = _ports[i];
  587. }
  588. _binder.refresh(_phy,p,pc,_explicitBind,*this);
  589. {
  590. Mutex::Lock _l(_nets_m);
  591. for(std::map<uint64_t,NetworkState>::iterator n(_nets.begin());n!=_nets.end();++n) {
  592. if (n->second.tap)
  593. syncManagedStuff(n->second,false,true);
  594. }
  595. }
  596. }
  597. // Update multipath mode (if needed)
  598. if (((now - lastMultipathModeUpdate) >= ZT_BINDER_REFRESH_PERIOD / 8)||(restarted)) {
  599. lastMultipathModeUpdate = now;
  600. _node->setMultipathMode(_multipathMode);
  601. }
  602. // Run background task processor in core if it's time to do so
  603. int64_t dl = _nextBackgroundTaskDeadline;
  604. if (dl <= now) {
  605. _node->processBackgroundTasks((void *)0,now,&_nextBackgroundTaskDeadline);
  606. dl = _nextBackgroundTaskDeadline;
  607. }
  608. // Sync multicast group memberships
  609. if ((now - lastTapMulticastGroupCheck) >= ZT_TAP_CHECK_MULTICAST_INTERVAL) {
  610. lastTapMulticastGroupCheck = now;
  611. std::vector< std::pair< uint64_t,std::pair< std::vector<MulticastGroup>,std::vector<MulticastGroup> > > > mgChanges;
  612. {
  613. Mutex::Lock _l(_nets_m);
  614. mgChanges.reserve(_nets.size() + 1);
  615. for(std::map<uint64_t,NetworkState>::const_iterator n(_nets.begin());n!=_nets.end();++n) {
  616. if (n->second.tap) {
  617. mgChanges.push_back(std::pair< uint64_t,std::pair< std::vector<MulticastGroup>,std::vector<MulticastGroup> > >(n->first,std::pair< std::vector<MulticastGroup>,std::vector<MulticastGroup> >()));
  618. n->second.tap->scanMulticastGroups(mgChanges.back().second.first,mgChanges.back().second.second);
  619. }
  620. }
  621. }
  622. for(std::vector< std::pair< uint64_t,std::pair< std::vector<MulticastGroup>,std::vector<MulticastGroup> > > >::iterator c(mgChanges.begin());c!=mgChanges.end();++c) {
  623. for(std::vector<MulticastGroup>::iterator m(c->second.first.begin());m!=c->second.first.end();++m)
  624. _node->multicastSubscribe((void *)0,c->first,m->mac().toInt(),m->adi());
  625. for(std::vector<MulticastGroup>::iterator m(c->second.second.begin());m!=c->second.second.end();++m)
  626. _node->multicastUnsubscribe(c->first,m->mac().toInt(),m->adi());
  627. }
  628. }
  629. // Sync information about physical network interfaces
  630. if ((now - lastLocalInterfaceAddressCheck) >= (_multipathMode ? ZT_LOCAL_INTERFACE_CHECK_INTERVAL / 8 : ZT_LOCAL_INTERFACE_CHECK_INTERVAL)) {
  631. lastLocalInterfaceAddressCheck = now;
  632. _node->clearLocalInterfaceAddresses();
  633. if (_portMapper) {
  634. std::vector<InetAddress> mappedAddresses(_portMapper->get());
  635. for(std::vector<InetAddress>::const_iterator ext(mappedAddresses.begin());ext!=mappedAddresses.end();++ext)
  636. _node->addLocalInterfaceAddress(reinterpret_cast<const struct sockaddr_storage *>(&(*ext)));
  637. }
  638. std::vector<InetAddress> boundAddrs(_binder.allBoundLocalInterfaceAddresses());
  639. for(std::vector<InetAddress>::const_iterator i(boundAddrs.begin());i!=boundAddrs.end();++i)
  640. _node->addLocalInterfaceAddress(reinterpret_cast<const struct sockaddr_storage *>(&(*i)));
  641. }
  642. // Clean peers.d periodically
  643. if ((now - lastCleanedPeersDb) >= 3600000) {
  644. lastCleanedPeersDb = now;
  645. OSUtils::cleanDirectory((_homePath + ZT_PATH_SEPARATOR_S "peers.d").c_str(),now - 2592000000LL); // delete older than 30 days
  646. }
  647. const unsigned long delay = (dl > now) ? (unsigned long)(dl - now) : 100;
  648. clockShouldBe = now + (uint64_t)delay;
  649. _phy.poll(delay);
  650. }
  651. } catch (std::exception &e) {
  652. Mutex::Lock _l(_termReason_m);
  653. _termReason = ONE_UNRECOVERABLE_ERROR;
  654. _fatalErrorMessage = std::string("unexpected exception in main thread: ")+e.what();
  655. } catch ( ... ) {
  656. Mutex::Lock _l(_termReason_m);
  657. _termReason = ONE_UNRECOVERABLE_ERROR;
  658. _fatalErrorMessage = "unexpected exception in main thread: unknown exception";
  659. }
  660. try {
  661. Mutex::Lock _l(_tcpConnections_m);
  662. while (!_tcpConnections.empty())
  663. _phy.close((*_tcpConnections.begin())->sock);
  664. } catch ( ... ) {}
  665. {
  666. Mutex::Lock _l(_nets_m);
  667. _nets.clear();
  668. }
  669. delete _node;
  670. _node = (Node *)0;
  671. return _termReason;
  672. }
  673. void readLocalSettings()
  674. {
  675. // Read local configuration
  676. std::map<InetAddress,ZT_PhysicalPathConfiguration> ppc;
  677. // LEGACY: support old "trustedpaths" flat file
  678. FILE *trustpaths = fopen((_homePath + ZT_PATH_SEPARATOR_S "trustedpaths").c_str(),"r");
  679. if (trustpaths) {
  680. fprintf(stderr,"WARNING: 'trustedpaths' flat file format is deprecated in favor of path definitions in local.conf" ZT_EOL_S);
  681. char buf[1024];
  682. while (fgets(buf,sizeof(buf),trustpaths)) {
  683. int fno = 0;
  684. char *saveptr = (char *)0;
  685. uint64_t trustedPathId = 0;
  686. InetAddress trustedPathNetwork;
  687. for(char *f=Utils::stok(buf,"=\r\n \t",&saveptr);(f);f=Utils::stok((char *)0,"=\r\n \t",&saveptr)) {
  688. if (fno == 0) {
  689. trustedPathId = Utils::hexStrToU64(f);
  690. } else if (fno == 1) {
  691. trustedPathNetwork = InetAddress(f);
  692. } else break;
  693. ++fno;
  694. }
  695. if ( (trustedPathId != 0) && ((trustedPathNetwork.ss_family == AF_INET)||(trustedPathNetwork.ss_family == AF_INET6)) && (trustedPathNetwork.netmaskBits() > 0) ) {
  696. ppc[trustedPathNetwork].trustedPathId = trustedPathId;
  697. ppc[trustedPathNetwork].mtu = 0; // use default
  698. }
  699. }
  700. fclose(trustpaths);
  701. }
  702. // Read local config file
  703. Mutex::Lock _l2(_localConfig_m);
  704. std::string lcbuf;
  705. if (OSUtils::readFile((_homePath + ZT_PATH_SEPARATOR_S "local.conf").c_str(),lcbuf)) {
  706. if (lcbuf.length() > 0) {
  707. try {
  708. _localConfig = OSUtils::jsonParse(lcbuf);
  709. if (!_localConfig.is_object()) {
  710. fprintf(stderr,"ERROR: unable to parse local.conf (root element is not a JSON object)" ZT_EOL_S);
  711. exit(1);
  712. }
  713. } catch ( ... ) {
  714. fprintf(stderr,"ERROR: unable to parse local.conf (invalid JSON)" ZT_EOL_S);
  715. exit(1);
  716. }
  717. }
  718. }
  719. // Get any trusted paths in local.conf (we'll parse the rest of physical[] elsewhere)
  720. json &physical = _localConfig["physical"];
  721. if (physical.is_object()) {
  722. for(json::iterator phy(physical.begin());phy!=physical.end();++phy) {
  723. InetAddress net(OSUtils::jsonString(phy.key(),"").c_str());
  724. if (net) {
  725. if (phy.value().is_object()) {
  726. uint64_t tpid;
  727. if ((tpid = OSUtils::jsonInt(phy.value()["trustedPathId"],0ULL)) != 0ULL) {
  728. if ((net.ss_family == AF_INET)||(net.ss_family == AF_INET6))
  729. ppc[net].trustedPathId = tpid;
  730. }
  731. ppc[net].mtu = (int)OSUtils::jsonInt(phy.value()["mtu"],0ULL); // 0 means use default
  732. }
  733. }
  734. }
  735. }
  736. json &settings = _localConfig["settings"];
  737. if (settings.is_object()) {
  738. // Allow controller DB path to be put somewhere else
  739. const std::string cdbp(OSUtils::jsonString(settings["controllerDbPath"],""));
  740. if (cdbp.length() > 0)
  741. _controllerDbPath = cdbp;
  742. json &rmq = settings["rabbitmq"];
  743. if (rmq.is_object() && _mqc == NULL) {
  744. fprintf(stderr, "Reading RabbitMQ Config\n");
  745. _mqc = new MQConfig;
  746. _mqc->port = rmq["port"];
  747. _mqc->host = OSUtils::jsonString(rmq["host"], "");
  748. _mqc->username = OSUtils::jsonString(rmq["username"], "");
  749. _mqc->password = OSUtils::jsonString(rmq["password"], "");
  750. }
  751. // Bind to wildcard instead of to specific interfaces (disables full tunnel capability)
  752. json &bind = settings["bind"];
  753. if (bind.is_array()) {
  754. for(unsigned long i=0;i<bind.size();++i) {
  755. const std::string ips(OSUtils::jsonString(bind[i],""));
  756. if (ips.length() > 0) {
  757. InetAddress ip(ips.c_str());
  758. if ((ip.ss_family == AF_INET)||(ip.ss_family == AF_INET6))
  759. _explicitBind.push_back(ip);
  760. }
  761. }
  762. }
  763. }
  764. // Set trusted paths if there are any
  765. if (ppc.size() > 0) {
  766. for(std::map<InetAddress,ZT_PhysicalPathConfiguration>::iterator i(ppc.begin());i!=ppc.end();++i)
  767. _node->setPhysicalPathConfiguration(reinterpret_cast<const struct sockaddr_storage *>(&(i->first)),&(i->second));
  768. }
  769. }
  770. virtual ReasonForTermination reasonForTermination() const
  771. {
  772. Mutex::Lock _l(_termReason_m);
  773. return _termReason;
  774. }
  775. virtual std::string fatalErrorMessage() const
  776. {
  777. Mutex::Lock _l(_termReason_m);
  778. return _fatalErrorMessage;
  779. }
  780. virtual std::string portDeviceName(uint64_t nwid) const
  781. {
  782. Mutex::Lock _l(_nets_m);
  783. std::map<uint64_t,NetworkState>::const_iterator n(_nets.find(nwid));
  784. if ((n != _nets.end())&&(n->second.tap))
  785. return n->second.tap->deviceName();
  786. else return std::string();
  787. }
  788. #ifdef ZT_SDK
  789. virtual std::string givenHomePath()
  790. {
  791. return _homePath;
  792. }
  793. void getRoutes(uint64_t nwid, void *routeArray, unsigned int *numRoutes)
  794. {
  795. Mutex::Lock _l(_nets_m);
  796. NetworkState &n = _nets[nwid];
  797. *numRoutes = *numRoutes < n.config.routeCount ? *numRoutes : n.config.routeCount;
  798. for(unsigned int i=0; i<*numRoutes; i++) {
  799. ZT_VirtualNetworkRoute *vnr = (ZT_VirtualNetworkRoute*)routeArray;
  800. memcpy(&vnr[i], &(n.config.routes[i]), sizeof(ZT_VirtualNetworkRoute));
  801. }
  802. }
  803. virtual Node *getNode()
  804. {
  805. return _node;
  806. }
  807. #endif // ZT_SDK
  808. virtual void terminate()
  809. {
  810. _run_m.lock();
  811. _run = false;
  812. _run_m.unlock();
  813. _phy.whack();
  814. }
  815. virtual bool getNetworkSettings(const uint64_t nwid,NetworkSettings &settings) const
  816. {
  817. Mutex::Lock _l(_nets_m);
  818. std::map<uint64_t,NetworkState>::const_iterator n(_nets.find(nwid));
  819. if (n == _nets.end())
  820. return false;
  821. settings = n->second.settings;
  822. return true;
  823. }
  824. virtual bool setNetworkSettings(const uint64_t nwid,const NetworkSettings &settings)
  825. {
  826. Mutex::Lock _l(_nets_m);
  827. std::map<uint64_t,NetworkState>::iterator n(_nets.find(nwid));
  828. if (n == _nets.end())
  829. return false;
  830. n->second.settings = settings;
  831. char nlcpath[4096];
  832. OSUtils::ztsnprintf(nlcpath,sizeof(nlcpath),"%s" ZT_PATH_SEPARATOR_S "%.16llx.local.conf",_networksPath.c_str(),nwid);
  833. FILE *out = fopen(nlcpath,"w");
  834. if (out) {
  835. fprintf(out,"allowManaged=%d\n",(int)n->second.settings.allowManaged);
  836. fprintf(out,"allowGlobal=%d\n",(int)n->second.settings.allowGlobal);
  837. fprintf(out,"allowDefault=%d\n",(int)n->second.settings.allowDefault);
  838. fclose(out);
  839. }
  840. if (n->second.tap)
  841. syncManagedStuff(n->second,true,true);
  842. return true;
  843. }
  844. // =========================================================================
  845. // Internal implementation methods for control plane, route setup, etc.
  846. // =========================================================================
  847. inline unsigned int handleControlPlaneHttpRequest(
  848. const InetAddress &fromAddress,
  849. unsigned int httpMethod,
  850. const std::string &path,
  851. const std::map<std::string,std::string> &headers,
  852. const std::string &body,
  853. std::string &responseBody,
  854. std::string &responseContentType)
  855. {
  856. char tmp[256];
  857. unsigned int scode = 404;
  858. json res;
  859. std::vector<std::string> ps(OSUtils::split(path.c_str(),"/","",""));
  860. std::map<std::string,std::string> urlArgs;
  861. /* Note: this is kind of restricted in what it'll take. It does not support
  862. * URL encoding, and /'s in URL args will screw it up. But the only URL args
  863. * it really uses in ?jsonp=funcionName, and otherwise it just takes simple
  864. * paths to simply-named resources. */
  865. if (ps.size() > 0) {
  866. std::size_t qpos = ps[ps.size() - 1].find('?');
  867. if (qpos != std::string::npos) {
  868. std::string args(ps[ps.size() - 1].substr(qpos + 1));
  869. ps[ps.size() - 1] = ps[ps.size() - 1].substr(0,qpos);
  870. std::vector<std::string> asplit(OSUtils::split(args.c_str(),"&","",""));
  871. for(std::vector<std::string>::iterator a(asplit.begin());a!=asplit.end();++a) {
  872. std::size_t eqpos = a->find('=');
  873. if (eqpos == std::string::npos)
  874. urlArgs[*a] = "";
  875. else urlArgs[a->substr(0,eqpos)] = a->substr(eqpos + 1);
  876. }
  877. }
  878. } else {
  879. return 404;
  880. }
  881. bool isAuth = false;
  882. {
  883. std::map<std::string,std::string>::const_iterator ah(headers.find("x-zt1-auth"));
  884. if ((ah != headers.end())&&(_authToken == ah->second)) {
  885. isAuth = true;
  886. } else {
  887. ah = urlArgs.find("auth");
  888. if ((ah != urlArgs.end())&&(_authToken == ah->second))
  889. isAuth = true;
  890. }
  891. }
  892. #ifdef __SYNOLOGY__
  893. // Authenticate via Synology's built-in cgi script
  894. if (!isAuth) {
  895. int synotoken_pos = path.find("SynoToken");
  896. int argpos = path.find("?");
  897. if(synotoken_pos != std::string::npos && argpos != std::string::npos) {
  898. std::string cookie = path.substr(argpos+1, synotoken_pos-(argpos+1));
  899. std::string synotoken = path.substr(synotoken_pos);
  900. std::string cookie_val = cookie.substr(cookie.find("=")+1);
  901. std::string synotoken_val = synotoken.substr(synotoken.find("=")+1);
  902. // Set necessary env for auth script
  903. std::map<std::string,std::string>::const_iterator ah2(headers.find("x-forwarded-for"));
  904. setenv("HTTP_COOKIE", cookie_val.c_str(), true);
  905. setenv("HTTP_X_SYNO_TOKEN", synotoken_val.c_str(), true);
  906. setenv("REMOTE_ADDR", ah2->second.c_str(),true);
  907. char user[256], buf[1024];
  908. FILE *fp = NULL;
  909. bzero(user, 256);
  910. fp = popen("/usr/syno/synoman/webman/modules/authenticate.cgi", "r");
  911. if(!fp)
  912. isAuth = false;
  913. else {
  914. bzero(buf, sizeof(buf));
  915. fread(buf, 1024, 1, fp);
  916. if(strlen(buf) > 0) {
  917. snprintf(user, 256, "%s", buf);
  918. isAuth = true;
  919. }
  920. }
  921. pclose(fp);
  922. }
  923. }
  924. #endif
  925. if (httpMethod == HTTP_GET) {
  926. if (isAuth) {
  927. if (ps[0] == "status") {
  928. ZT_NodeStatus status;
  929. _node->status(&status);
  930. OSUtils::ztsnprintf(tmp,sizeof(tmp),"%.10llx",status.address);
  931. res["address"] = tmp;
  932. res["publicIdentity"] = status.publicIdentity;
  933. res["online"] = (bool)(status.online != 0);
  934. res["versionMajor"] = ZEROTIER_ONE_VERSION_MAJOR;
  935. res["versionMinor"] = ZEROTIER_ONE_VERSION_MINOR;
  936. res["versionRev"] = ZEROTIER_ONE_VERSION_REVISION;
  937. res["versionBuild"] = ZEROTIER_ONE_VERSION_BUILD;
  938. OSUtils::ztsnprintf(tmp,sizeof(tmp),"%d.%d.%d",ZEROTIER_ONE_VERSION_MAJOR,ZEROTIER_ONE_VERSION_MINOR,ZEROTIER_ONE_VERSION_REVISION);
  939. res["version"] = tmp;
  940. res["clock"] = OSUtils::now();
  941. {
  942. Mutex::Lock _l(_localConfig_m);
  943. res["config"] = _localConfig;
  944. }
  945. json &settings = res["config"]["settings"];
  946. settings["primaryPort"] = OSUtils::jsonInt(settings["primaryPort"],(uint64_t)_primaryPort) & 0xffff;
  947. if (_multipathMode) {
  948. json &multipathConfig = res["multipath"];
  949. ZT_PeerList *pl = _node->peers();
  950. char peerAddrStr[256];
  951. if (pl) {
  952. for(unsigned long i=0;i<pl->peerCount;++i) {
  953. if (pl->peers[i].hadAggregateLink) {
  954. nlohmann::json pj;
  955. _peerAggregateLinkToJson(pj,&(pl->peers[i]));
  956. OSUtils::ztsnprintf(peerAddrStr,sizeof(peerAddrStr),"%.10llx",pl->peers[i].address);
  957. multipathConfig[peerAddrStr] = (pj);
  958. }
  959. }
  960. }
  961. }
  962. settings["portMappingEnabled"] = OSUtils::jsonBool(settings["portMappingEnabled"],true);
  963. scode = 200;
  964. } else if (ps[0] == "network") {
  965. ZT_VirtualNetworkList *nws = _node->networks();
  966. if (nws) {
  967. if (ps.size() == 1) {
  968. // Return [array] of all networks
  969. res = nlohmann::json::array();
  970. for(unsigned long i=0;i<nws->networkCount;++i) {
  971. OneService::NetworkSettings localSettings;
  972. getNetworkSettings(nws->networks[i].nwid,localSettings);
  973. nlohmann::json nj;
  974. _networkToJson(nj,&(nws->networks[i]),portDeviceName(nws->networks[i].nwid),localSettings);
  975. res.push_back(nj);
  976. }
  977. scode = 200;
  978. } else if (ps.size() == 2) {
  979. // Return a single network by ID or 404 if not found
  980. const uint64_t wantnw = Utils::hexStrToU64(ps[1].c_str());
  981. for(unsigned long i=0;i<nws->networkCount;++i) {
  982. if (nws->networks[i].nwid == wantnw) {
  983. OneService::NetworkSettings localSettings;
  984. getNetworkSettings(nws->networks[i].nwid,localSettings);
  985. _networkToJson(res,&(nws->networks[i]),portDeviceName(nws->networks[i].nwid),localSettings);
  986. scode = 200;
  987. break;
  988. }
  989. }
  990. } else scode = 404;
  991. _node->freeQueryResult((void *)nws);
  992. } else scode = 500;
  993. } else if (ps[0] == "peer") {
  994. ZT_PeerList *pl = _node->peers();
  995. if (pl) {
  996. if (ps.size() == 1) {
  997. // Return [array] of all peers
  998. res = nlohmann::json::array();
  999. for(unsigned long i=0;i<pl->peerCount;++i) {
  1000. nlohmann::json pj;
  1001. _peerToJson(pj,&(pl->peers[i]));
  1002. res.push_back(pj);
  1003. }
  1004. scode = 200;
  1005. } else if (ps.size() == 2) {
  1006. // Return a single peer by ID or 404 if not found
  1007. uint64_t wantp = Utils::hexStrToU64(ps[1].c_str());
  1008. for(unsigned long i=0;i<pl->peerCount;++i) {
  1009. if (pl->peers[i].address == wantp) {
  1010. _peerToJson(res,&(pl->peers[i]));
  1011. scode = 200;
  1012. break;
  1013. }
  1014. }
  1015. } else scode = 404;
  1016. _node->freeQueryResult((void *)pl);
  1017. } else scode = 500;
  1018. } else {
  1019. if (_controller) {
  1020. scode = _controller->handleControlPlaneHttpGET(std::vector<std::string>(ps.begin()+1,ps.end()),urlArgs,headers,body,responseBody,responseContentType);
  1021. } else scode = 404;
  1022. }
  1023. } else scode = 401; // isAuth == false
  1024. } else if ((httpMethod == HTTP_POST)||(httpMethod == HTTP_PUT)) {
  1025. if (isAuth) {
  1026. if (ps[0] == "network") {
  1027. if (ps.size() == 2) {
  1028. uint64_t wantnw = Utils::hexStrToU64(ps[1].c_str());
  1029. _node->join(wantnw,(void *)0,(void *)0); // does nothing if we are a member
  1030. ZT_VirtualNetworkList *nws = _node->networks();
  1031. if (nws) {
  1032. for(unsigned long i=0;i<nws->networkCount;++i) {
  1033. if (nws->networks[i].nwid == wantnw) {
  1034. OneService::NetworkSettings localSettings;
  1035. getNetworkSettings(nws->networks[i].nwid,localSettings);
  1036. try {
  1037. json j(OSUtils::jsonParse(body));
  1038. if (j.is_object()) {
  1039. json &allowManaged = j["allowManaged"];
  1040. if (allowManaged.is_boolean()) localSettings.allowManaged = (bool)allowManaged;
  1041. json &allowGlobal = j["allowGlobal"];
  1042. if (allowGlobal.is_boolean()) localSettings.allowGlobal = (bool)allowGlobal;
  1043. json &allowDefault = j["allowDefault"];
  1044. if (allowDefault.is_boolean()) localSettings.allowDefault = (bool)allowDefault;
  1045. }
  1046. } catch (std::exception &exc) {
  1047. } catch ( ... ) {
  1048. }
  1049. setNetworkSettings(nws->networks[i].nwid,localSettings);
  1050. _networkToJson(res,&(nws->networks[i]),portDeviceName(nws->networks[i].nwid),localSettings);
  1051. scode = 200;
  1052. break;
  1053. }
  1054. }
  1055. _node->freeQueryResult((void *)nws);
  1056. } else scode = 500;
  1057. } else scode = 404;
  1058. } else {
  1059. if (_controller)
  1060. scode = _controller->handleControlPlaneHttpPOST(std::vector<std::string>(ps.begin()+1,ps.end()),urlArgs,headers,body,responseBody,responseContentType);
  1061. else scode = 404;
  1062. }
  1063. } else scode = 401; // isAuth == false
  1064. } else if (httpMethod == HTTP_DELETE) {
  1065. if (isAuth) {
  1066. if (ps[0] == "network") {
  1067. ZT_VirtualNetworkList *nws = _node->networks();
  1068. if (nws) {
  1069. if (ps.size() == 2) {
  1070. uint64_t wantnw = Utils::hexStrToU64(ps[1].c_str());
  1071. for(unsigned long i=0;i<nws->networkCount;++i) {
  1072. if (nws->networks[i].nwid == wantnw) {
  1073. _node->leave(wantnw,(void **)0,(void *)0);
  1074. res["result"] = true;
  1075. scode = 200;
  1076. break;
  1077. }
  1078. }
  1079. } // else 404
  1080. _node->freeQueryResult((void *)nws);
  1081. } else scode = 500;
  1082. } else {
  1083. if (_controller)
  1084. scode = _controller->handleControlPlaneHttpDELETE(std::vector<std::string>(ps.begin()+1,ps.end()),urlArgs,headers,body,responseBody,responseContentType);
  1085. else scode = 404;
  1086. }
  1087. } else scode = 401; // isAuth = false
  1088. } else {
  1089. scode = 400;
  1090. }
  1091. if (responseBody.length() == 0) {
  1092. if ((res.is_object())||(res.is_array()))
  1093. responseBody = OSUtils::jsonDump(res);
  1094. else responseBody = "{}";
  1095. responseContentType = "application/json";
  1096. }
  1097. // Wrap result in jsonp function call if the user included a jsonp= url argument.
  1098. // Also double-check isAuth since forbidding this without auth feels safer.
  1099. std::map<std::string,std::string>::const_iterator jsonp(urlArgs.find("jsonp"));
  1100. if ((isAuth)&&(jsonp != urlArgs.end())&&(responseContentType == "application/json")) {
  1101. if (responseBody.length() > 0)
  1102. responseBody = jsonp->second + "(" + responseBody + ");";
  1103. else responseBody = jsonp->second + "(null);";
  1104. responseContentType = "application/javascript";
  1105. }
  1106. return scode;
  1107. }
  1108. // Must be called after _localConfig is read or modified
  1109. void applyLocalConfig()
  1110. {
  1111. Mutex::Lock _l(_localConfig_m);
  1112. json lc(_localConfig);
  1113. _v4Hints.clear();
  1114. _v6Hints.clear();
  1115. _v4Blacklists.clear();
  1116. _v6Blacklists.clear();
  1117. json &virt = lc["virtual"];
  1118. if (virt.is_object()) {
  1119. for(json::iterator v(virt.begin());v!=virt.end();++v) {
  1120. const std::string nstr = v.key();
  1121. if ((nstr.length() == ZT_ADDRESS_LENGTH_HEX)&&(v.value().is_object())) {
  1122. const Address ztaddr(Utils::hexStrToU64(nstr.c_str()));
  1123. if (ztaddr) {
  1124. const uint64_t ztaddr2 = ztaddr.toInt();
  1125. std::vector<InetAddress> &v4h = _v4Hints[ztaddr2];
  1126. std::vector<InetAddress> &v6h = _v6Hints[ztaddr2];
  1127. std::vector<InetAddress> &v4b = _v4Blacklists[ztaddr2];
  1128. std::vector<InetAddress> &v6b = _v6Blacklists[ztaddr2];
  1129. json &tryAddrs = v.value()["try"];
  1130. if (tryAddrs.is_array()) {
  1131. for(unsigned long i=0;i<tryAddrs.size();++i) {
  1132. const InetAddress ip(OSUtils::jsonString(tryAddrs[i],"").c_str());
  1133. if (ip.ss_family == AF_INET)
  1134. v4h.push_back(ip);
  1135. else if (ip.ss_family == AF_INET6)
  1136. v6h.push_back(ip);
  1137. }
  1138. }
  1139. json &blAddrs = v.value()["blacklist"];
  1140. if (blAddrs.is_array()) {
  1141. for(unsigned long i=0;i<blAddrs.size();++i) {
  1142. const InetAddress ip(OSUtils::jsonString(blAddrs[i],"").c_str());
  1143. if (ip.ss_family == AF_INET)
  1144. v4b.push_back(ip);
  1145. else if (ip.ss_family == AF_INET6)
  1146. v6b.push_back(ip);
  1147. }
  1148. }
  1149. if (v4h.empty()) _v4Hints.erase(ztaddr2);
  1150. if (v6h.empty()) _v6Hints.erase(ztaddr2);
  1151. if (v4b.empty()) _v4Blacklists.erase(ztaddr2);
  1152. if (v6b.empty()) _v6Blacklists.erase(ztaddr2);
  1153. }
  1154. }
  1155. }
  1156. }
  1157. _globalV4Blacklist.clear();
  1158. _globalV6Blacklist.clear();
  1159. json &physical = lc["physical"];
  1160. if (physical.is_object()) {
  1161. for(json::iterator phy(physical.begin());phy!=physical.end();++phy) {
  1162. const InetAddress net(OSUtils::jsonString(phy.key(),"").c_str());
  1163. if ((net)&&(net.netmaskBits() > 0)) {
  1164. if (phy.value().is_object()) {
  1165. if (OSUtils::jsonBool(phy.value()["blacklist"],false)) {
  1166. if (net.ss_family == AF_INET)
  1167. _globalV4Blacklist.push_back(net);
  1168. else if (net.ss_family == AF_INET6)
  1169. _globalV6Blacklist.push_back(net);
  1170. }
  1171. }
  1172. }
  1173. }
  1174. }
  1175. _allowManagementFrom.clear();
  1176. _interfacePrefixBlacklist.clear();
  1177. json &settings = lc["settings"];
  1178. _primaryPort = (unsigned int)OSUtils::jsonInt(settings["primaryPort"],(uint64_t)_primaryPort) & 0xffff;
  1179. _allowSecondaryPort = OSUtils::jsonBool(settings["allowSecondaryPort"],true);
  1180. _secondaryPort = (unsigned int)OSUtils::jsonInt(settings["secondaryPort"],0);
  1181. _tertiaryPort = (unsigned int)OSUtils::jsonInt(settings["tertiaryPort"],0);
  1182. if (_secondaryPort != 0 || _tertiaryPort != 0) {
  1183. fprintf(stderr,"WARNING: using manually-specified ports. This can cause NAT issues." ZT_EOL_S);
  1184. }
  1185. _multipathMode = (unsigned int)OSUtils::jsonInt(settings["multipathMode"],0);
  1186. _portMappingEnabled = OSUtils::jsonBool(settings["portMappingEnabled"],true);
  1187. json &ignoreIfs = settings["interfacePrefixBlacklist"];
  1188. if (ignoreIfs.is_array()) {
  1189. for(unsigned long i=0;i<ignoreIfs.size();++i) {
  1190. const std::string tmp(OSUtils::jsonString(ignoreIfs[i],""));
  1191. if (tmp.length() > 0)
  1192. _interfacePrefixBlacklist.push_back(tmp);
  1193. }
  1194. }
  1195. json &amf = settings["allowManagementFrom"];
  1196. if (amf.is_array()) {
  1197. for(unsigned long i=0;i<amf.size();++i) {
  1198. const InetAddress nw(OSUtils::jsonString(amf[i],"").c_str());
  1199. if (nw)
  1200. _allowManagementFrom.push_back(nw);
  1201. }
  1202. }
  1203. }
  1204. // Checks if a managed IP or route target is allowed
  1205. bool checkIfManagedIsAllowed(const NetworkState &n,const InetAddress &target)
  1206. {
  1207. if (!n.settings.allowManaged)
  1208. return false;
  1209. if (n.settings.allowManagedWhitelist.size() > 0) {
  1210. bool allowed = false;
  1211. for (InetAddress addr : n.settings.allowManagedWhitelist) {
  1212. if (addr.containsAddress(target) && addr.netmaskBits() <= target.netmaskBits()) {
  1213. allowed = true;
  1214. break;
  1215. }
  1216. }
  1217. if (!allowed) return false;
  1218. }
  1219. if (target.isDefaultRoute())
  1220. return n.settings.allowDefault;
  1221. switch(target.ipScope()) {
  1222. case InetAddress::IP_SCOPE_NONE:
  1223. case InetAddress::IP_SCOPE_MULTICAST:
  1224. case InetAddress::IP_SCOPE_LOOPBACK:
  1225. case InetAddress::IP_SCOPE_LINK_LOCAL:
  1226. return false;
  1227. case InetAddress::IP_SCOPE_GLOBAL:
  1228. return n.settings.allowGlobal;
  1229. default:
  1230. return true;
  1231. }
  1232. }
  1233. // Match only an IP from a vector of IPs -- used in syncManagedStuff()
  1234. bool matchIpOnly(const std::vector<InetAddress> &ips,const InetAddress &ip) const
  1235. {
  1236. for(std::vector<InetAddress>::const_iterator i(ips.begin());i!=ips.end();++i) {
  1237. if (i->ipsEqual(ip))
  1238. return true;
  1239. }
  1240. return false;
  1241. }
  1242. // Apply or update managed IPs for a configured network (be sure n.tap exists)
  1243. void syncManagedStuff(NetworkState &n,bool syncIps,bool syncRoutes)
  1244. {
  1245. char ipbuf[64];
  1246. // assumes _nets_m is locked
  1247. if (syncIps) {
  1248. std::vector<InetAddress> newManagedIps;
  1249. newManagedIps.reserve(n.config.assignedAddressCount);
  1250. for(unsigned int i=0;i<n.config.assignedAddressCount;++i) {
  1251. const InetAddress *ii = reinterpret_cast<const InetAddress *>(&(n.config.assignedAddresses[i]));
  1252. if (checkIfManagedIsAllowed(n,*ii))
  1253. newManagedIps.push_back(*ii);
  1254. }
  1255. std::sort(newManagedIps.begin(),newManagedIps.end());
  1256. newManagedIps.erase(std::unique(newManagedIps.begin(),newManagedIps.end()),newManagedIps.end());
  1257. for(std::vector<InetAddress>::iterator ip(n.managedIps.begin());ip!=n.managedIps.end();++ip) {
  1258. if (std::find(newManagedIps.begin(),newManagedIps.end(),*ip) == newManagedIps.end()) {
  1259. if (!n.tap->removeIp(*ip))
  1260. fprintf(stderr,"ERROR: unable to remove ip address %s" ZT_EOL_S, ip->toString(ipbuf));
  1261. }
  1262. }
  1263. #ifdef __SYNOLOGY__
  1264. if (!n.tap->addIps(newManagedIps)) {
  1265. fprintf(stderr,"ERROR: unable to add ip addresses to ifcfg" ZT_EOL_S);
  1266. }
  1267. #else
  1268. for(std::vector<InetAddress>::iterator ip(newManagedIps.begin());ip!=newManagedIps.end();++ip) {
  1269. if (std::find(n.managedIps.begin(),n.managedIps.end(),*ip) == n.managedIps.end()) {
  1270. if (!n.tap->addIp(*ip))
  1271. fprintf(stderr,"ERROR: unable to add ip address %s" ZT_EOL_S, ip->toString(ipbuf));
  1272. }
  1273. }
  1274. #endif
  1275. n.managedIps.swap(newManagedIps);
  1276. }
  1277. if (syncRoutes) {
  1278. char tapdev[64];
  1279. #if defined(__WINDOWS__) && !defined(ZT_SDK)
  1280. OSUtils::ztsnprintf(tapdev,sizeof(tapdev),"%.16llx",(unsigned long long)((WindowsEthernetTap *)(n.tap.get()))->luid().Value);
  1281. #else
  1282. Utils::scopy(tapdev,sizeof(tapdev),n.tap->deviceName().c_str());
  1283. #endif
  1284. std::vector<InetAddress> myIps(n.tap->ips());
  1285. // Nuke applied routes that are no longer in n.config.routes[] and/or are not allowed
  1286. for(std::list< SharedPtr<ManagedRoute> >::iterator mr(n.managedRoutes.begin());mr!=n.managedRoutes.end();) {
  1287. bool haveRoute = false;
  1288. if ( (checkIfManagedIsAllowed(n,(*mr)->target())) && (((*mr)->via().ss_family != (*mr)->target().ss_family)||(!matchIpOnly(myIps,(*mr)->via()))) ) {
  1289. for(unsigned int i=0;i<n.config.routeCount;++i) {
  1290. const InetAddress *const target = reinterpret_cast<const InetAddress *>(&(n.config.routes[i].target));
  1291. const InetAddress *const via = reinterpret_cast<const InetAddress *>(&(n.config.routes[i].via));
  1292. if ( ((*mr)->target() == *target) && ( ((via->ss_family == target->ss_family)&&((*mr)->via().ipsEqual(*via))) || (strcmp(tapdev,(*mr)->device())==0) ) ) {
  1293. haveRoute = true;
  1294. break;
  1295. }
  1296. }
  1297. }
  1298. if (haveRoute) {
  1299. ++mr;
  1300. } else {
  1301. n.managedRoutes.erase(mr++);
  1302. }
  1303. }
  1304. // Apply routes in n.config.routes[] that we haven't applied yet, and sync those we have in case shadow routes need to change
  1305. for(unsigned int i=0;i<n.config.routeCount;++i) {
  1306. const InetAddress *const target = reinterpret_cast<const InetAddress *>(&(n.config.routes[i].target));
  1307. const InetAddress *const via = reinterpret_cast<const InetAddress *>(&(n.config.routes[i].via));
  1308. if ( (!checkIfManagedIsAllowed(n,*target)) || ((via->ss_family == target->ss_family)&&(matchIpOnly(myIps,*via))) )
  1309. continue;
  1310. bool haveRoute = false;
  1311. // Ignore routes implied by local managed IPs since adding the IP adds the route
  1312. #ifndef __APPLE__
  1313. for(std::vector<InetAddress>::iterator ip(n.managedIps.begin());ip!=n.managedIps.end();++ip) {
  1314. if ((target->netmaskBits() == ip->netmaskBits())&&(target->containsAddress(*ip))) {
  1315. haveRoute = true;
  1316. break;
  1317. }
  1318. }
  1319. #endif
  1320. if (haveRoute)
  1321. continue;
  1322. #ifndef ZT_SDK
  1323. // If we've already applied this route, just sync it and continue
  1324. for(std::list< SharedPtr<ManagedRoute> >::iterator mr(n.managedRoutes.begin());mr!=n.managedRoutes.end();++mr) {
  1325. if ( ((*mr)->target() == *target) && ( ((via->ss_family == target->ss_family)&&((*mr)->via().ipsEqual(*via))) || (tapdev == (*mr)->device()) ) ) {
  1326. haveRoute = true;
  1327. (*mr)->sync();
  1328. break;
  1329. }
  1330. }
  1331. if (haveRoute)
  1332. continue;
  1333. // Add and apply new routes
  1334. n.managedRoutes.push_back(SharedPtr<ManagedRoute>(new ManagedRoute(*target,*via,tapdev)));
  1335. if (!n.managedRoutes.back()->sync())
  1336. n.managedRoutes.pop_back();
  1337. #endif
  1338. }
  1339. }
  1340. }
  1341. // =========================================================================
  1342. // Handlers for Node and Phy<> callbacks
  1343. // =========================================================================
  1344. inline void phyOnDatagram(PhySocket *sock,void **uptr,const struct sockaddr *localAddr,const struct sockaddr *from,void *data,unsigned long len)
  1345. {
  1346. const uint64_t now = OSUtils::now();
  1347. if ((len >= 16)&&(reinterpret_cast<const InetAddress *>(from)->ipScope() == InetAddress::IP_SCOPE_GLOBAL))
  1348. _lastDirectReceiveFromGlobal = now;
  1349. const ZT_ResultCode rc = _node->processWirePacket(nullptr,now,reinterpret_cast<int64_t>(sock),reinterpret_cast<const struct sockaddr_storage *>(from),data,len,&_nextBackgroundTaskDeadline);
  1350. if (ZT_ResultCode_isFatal(rc)) {
  1351. char tmp[256];
  1352. OSUtils::ztsnprintf(tmp,sizeof(tmp),"fatal error code from processWirePacket: %d",(int)rc);
  1353. Mutex::Lock _l(_termReason_m);
  1354. _termReason = ONE_UNRECOVERABLE_ERROR;
  1355. _fatalErrorMessage = tmp;
  1356. this->terminate();
  1357. }
  1358. }
  1359. inline void phyOnTcpConnect(PhySocket *sock,void **uptr,bool success)
  1360. {
  1361. _phy.close(sock,true);
  1362. }
  1363. inline void phyOnTcpAccept(PhySocket *sockL,PhySocket *sockN,void **uptrL,void **uptrN,const struct sockaddr *from)
  1364. {
  1365. if (!from) {
  1366. _phy.close(sockN,false);
  1367. return;
  1368. } else {
  1369. #ifdef ZT_SDK
  1370. // Immediately close new local connections. The intention is to prevent the backplane from being accessed when operating as libzt
  1371. if (!allowHttpBackplaneManagement && ((InetAddress*)from)->ipScope() == InetAddress::IP_SCOPE_LOOPBACK) {
  1372. _phy.close(sockN,false);
  1373. return;
  1374. }
  1375. #endif
  1376. TcpConnection *tc = new TcpConnection();
  1377. {
  1378. Mutex::Lock _l(_tcpConnections_m);
  1379. _tcpConnections.push_back(tc);
  1380. }
  1381. tc->type = TcpConnection::TCP_UNCATEGORIZED_INCOMING;
  1382. tc->parent = this;
  1383. tc->sock = sockN;
  1384. tc->remoteAddr = from;
  1385. tc->lastReceive = OSUtils::now();
  1386. http_parser_init(&(tc->parser),HTTP_REQUEST);
  1387. tc->parser.data = (void *)tc;
  1388. tc->messageSize = 0;
  1389. *uptrN = (void *)tc;
  1390. }
  1391. }
  1392. void phyOnTcpClose(PhySocket *sock,void **uptr)
  1393. {
  1394. TcpConnection *tc = (TcpConnection *)*uptr;
  1395. if (tc) {
  1396. {
  1397. Mutex::Lock _l(_tcpConnections_m);
  1398. _tcpConnections.erase(std::remove(_tcpConnections.begin(),_tcpConnections.end(),tc),_tcpConnections.end());
  1399. }
  1400. delete tc;
  1401. }
  1402. }
  1403. void phyOnTcpData(PhySocket *sock,void **uptr,void *data,unsigned long len)
  1404. {
  1405. try {
  1406. if (!len) return; // sanity check, should never happen
  1407. TcpConnection *tc = reinterpret_cast<TcpConnection *>(*uptr);
  1408. tc->lastReceive = OSUtils::now();
  1409. switch(tc->type) {
  1410. case TcpConnection::TCP_UNCATEGORIZED_INCOMING:
  1411. switch(reinterpret_cast<uint8_t *>(data)[0]) {
  1412. // HTTP: GET, PUT, POST, HEAD, DELETE
  1413. case 'G':
  1414. case 'P':
  1415. case 'D':
  1416. case 'H': {
  1417. // This is only allowed from IPs permitted to access the management
  1418. // backplane, which is just 127.0.0.1/::1 unless otherwise configured.
  1419. bool allow;
  1420. {
  1421. Mutex::Lock _l(_localConfig_m);
  1422. if (_allowManagementFrom.size() == 0) {
  1423. allow = (tc->remoteAddr.ipScope() == InetAddress::IP_SCOPE_LOOPBACK);
  1424. } else {
  1425. allow = false;
  1426. for(std::vector<InetAddress>::const_iterator i(_allowManagementFrom.begin());i!=_allowManagementFrom.end();++i) {
  1427. if (i->containsAddress(tc->remoteAddr)) {
  1428. allow = true;
  1429. break;
  1430. }
  1431. }
  1432. }
  1433. }
  1434. if (allow) {
  1435. tc->type = TcpConnection::TCP_HTTP_INCOMING;
  1436. phyOnTcpData(sock,uptr,data,len);
  1437. } else {
  1438. _phy.close(sock);
  1439. }
  1440. } break;
  1441. // Drop unknown protocols
  1442. default:
  1443. _phy.close(sock);
  1444. break;
  1445. }
  1446. return;
  1447. case TcpConnection::TCP_HTTP_INCOMING:
  1448. http_parser_execute(&(tc->parser),&HTTP_PARSER_SETTINGS,(const char *)data,len);
  1449. if ((tc->parser.upgrade)||(tc->parser.http_errno != HPE_OK))
  1450. _phy.close(sock);
  1451. return;
  1452. }
  1453. } catch (std::exception &exc) {
  1454. _phy.close(sock);
  1455. } catch ( ... ) {
  1456. _phy.close(sock);
  1457. }
  1458. }
  1459. inline void phyOnTcpWritable(PhySocket *sock,void **uptr)
  1460. {
  1461. TcpConnection *tc = reinterpret_cast<TcpConnection *>(*uptr);
  1462. bool closeit = false;
  1463. {
  1464. Mutex::Lock _l(tc->writeq_m);
  1465. if (tc->writeq.length() > 0) {
  1466. long sent = (long)_phy.streamSend(sock,tc->writeq.data(),(unsigned long)tc->writeq.length(),true);
  1467. if (sent > 0) {
  1468. if ((unsigned long)sent >= (unsigned long)tc->writeq.length()) {
  1469. tc->writeq.clear();
  1470. _phy.setNotifyWritable(sock,false);
  1471. if (tc->type == TcpConnection::TCP_HTTP_INCOMING)
  1472. closeit = true; // HTTP keep alive not supported
  1473. } else {
  1474. tc->writeq.erase(tc->writeq.begin(),tc->writeq.begin() + sent);
  1475. }
  1476. }
  1477. } else {
  1478. _phy.setNotifyWritable(sock,false);
  1479. }
  1480. }
  1481. if (closeit)
  1482. _phy.close(sock);
  1483. }
  1484. inline void phyOnFileDescriptorActivity(PhySocket *sock,void **uptr,bool readable,bool writable) {}
  1485. inline void phyOnUnixAccept(PhySocket *sockL,PhySocket *sockN,void **uptrL,void **uptrN) {}
  1486. inline void phyOnUnixClose(PhySocket *sock,void **uptr) {}
  1487. inline void phyOnUnixData(PhySocket *sock,void **uptr,void *data,unsigned long len) {}
  1488. inline void phyOnUnixWritable(PhySocket *sock,void **uptr) {}
  1489. inline int nodeVirtualNetworkConfigFunction(uint64_t nwid,void **nuptr,enum ZT_VirtualNetworkConfigOperation op,const ZT_VirtualNetworkConfig *nwc)
  1490. {
  1491. Mutex::Lock _l(_nets_m);
  1492. NetworkState &n = _nets[nwid];
  1493. switch(op) {
  1494. case ZT_VIRTUAL_NETWORK_CONFIG_OPERATION_UP:
  1495. if (!n.tap) {
  1496. try {
  1497. char friendlyName[128];
  1498. OSUtils::ztsnprintf(friendlyName,sizeof(friendlyName),"ZeroTier One [%.16llx]",nwid);
  1499. n.tap = EthernetTap::newInstance(
  1500. nullptr,
  1501. _homePath.c_str(),
  1502. MAC(nwc->mac),
  1503. nwc->mtu,
  1504. (unsigned int)ZT_IF_METRIC,
  1505. nwid,
  1506. friendlyName,
  1507. StapFrameHandler,
  1508. (void *)this);
  1509. *nuptr = (void *)&n;
  1510. char nlcpath[256];
  1511. OSUtils::ztsnprintf(nlcpath,sizeof(nlcpath),"%s" ZT_PATH_SEPARATOR_S "networks.d" ZT_PATH_SEPARATOR_S "%.16llx.local.conf",_homePath.c_str(),nwid);
  1512. std::string nlcbuf;
  1513. if (OSUtils::readFile(nlcpath,nlcbuf)) {
  1514. Dictionary<4096> nc;
  1515. nc.load(nlcbuf.c_str());
  1516. Buffer<1024> allowManaged;
  1517. if (nc.get("allowManaged", allowManaged) && allowManaged.size() != 0) {
  1518. std::string addresses (allowManaged.begin(), allowManaged.size());
  1519. if (allowManaged.size() <= 5) { // untidy parsing for backward compatibility
  1520. if (allowManaged[0] == '1' || allowManaged[0] == 't' || allowManaged[0] == 'T') {
  1521. n.settings.allowManaged = true;
  1522. } else {
  1523. n.settings.allowManaged = false;
  1524. }
  1525. } else {
  1526. // this should be a list of IP addresses
  1527. n.settings.allowManaged = true;
  1528. size_t pos = 0;
  1529. while (true) {
  1530. size_t nextPos = addresses.find(',', pos);
  1531. std::string address = addresses.substr(pos, (nextPos == std::string::npos ? addresses.size() : nextPos) - pos);
  1532. n.settings.allowManagedWhitelist.push_back(InetAddress(address.c_str()));
  1533. if (nextPos == std::string::npos) break;
  1534. pos = nextPos + 1;
  1535. }
  1536. }
  1537. } else {
  1538. n.settings.allowManaged = true;
  1539. }
  1540. n.settings.allowGlobal = nc.getB("allowGlobal", false);
  1541. n.settings.allowDefault = nc.getB("allowDefault", false);
  1542. }
  1543. } catch (std::exception &exc) {
  1544. #ifdef __WINDOWS__
  1545. FILE *tapFailLog = fopen((_homePath + ZT_PATH_SEPARATOR_S"port_error_log.txt").c_str(),"a");
  1546. if (tapFailLog) {
  1547. fprintf(tapFailLog,"%.16llx: %s" ZT_EOL_S,(unsigned long long)nwid,exc.what());
  1548. fclose(tapFailLog);
  1549. }
  1550. #else
  1551. fprintf(stderr,"ERROR: unable to configure virtual network port: %s" ZT_EOL_S,exc.what());
  1552. #endif
  1553. _nets.erase(nwid);
  1554. return -999;
  1555. } catch (int exc) {
  1556. return -999;
  1557. } catch ( ... ) {
  1558. return -999; // tap init failed
  1559. }
  1560. }
  1561. // After setting up tap, fall through to CONFIG_UPDATE since we also want to do this...
  1562. case ZT_VIRTUAL_NETWORK_CONFIG_OPERATION_CONFIG_UPDATE:
  1563. memcpy(&(n.config),nwc,sizeof(ZT_VirtualNetworkConfig));
  1564. if (n.tap) { // sanity check
  1565. #if defined(__WINDOWS__) && !defined(ZT_SDK)
  1566. // wait for up to 5 seconds for the WindowsEthernetTap to actually be initialized
  1567. //
  1568. // without WindowsEthernetTap::isInitialized() returning true, the won't actually
  1569. // be online yet and setting managed routes on it will fail.
  1570. const int MAX_SLEEP_COUNT = 500;
  1571. for (int i = 0; !((WindowsEthernetTap *)(n.tap.get()))->isInitialized() && i < MAX_SLEEP_COUNT; i++) {
  1572. Sleep(10);
  1573. }
  1574. #endif
  1575. syncManagedStuff(n,true,true);
  1576. n.tap->setMtu(nwc->mtu);
  1577. } else {
  1578. _nets.erase(nwid);
  1579. return -999; // tap init failed
  1580. }
  1581. break;
  1582. case ZT_VIRTUAL_NETWORK_CONFIG_OPERATION_DOWN:
  1583. case ZT_VIRTUAL_NETWORK_CONFIG_OPERATION_DESTROY:
  1584. if (n.tap) { // sanity check
  1585. #if defined(__WINDOWS__) && !defined(ZT_SDK)
  1586. std::string winInstanceId(((WindowsEthernetTap *)(n.tap.get()))->instanceId());
  1587. #endif
  1588. *nuptr = (void *)0;
  1589. n.tap.reset();
  1590. _nets.erase(nwid);
  1591. #if defined(__WINDOWS__) && !defined(ZT_SDK)
  1592. if ((op == ZT_VIRTUAL_NETWORK_CONFIG_OPERATION_DESTROY)&&(winInstanceId.length() > 0))
  1593. WindowsEthernetTap::deletePersistentTapDevice(winInstanceId.c_str());
  1594. #endif
  1595. if (op == ZT_VIRTUAL_NETWORK_CONFIG_OPERATION_DESTROY) {
  1596. char nlcpath[256];
  1597. OSUtils::ztsnprintf(nlcpath,sizeof(nlcpath),"%s" ZT_PATH_SEPARATOR_S "networks.d" ZT_PATH_SEPARATOR_S "%.16llx.local.conf",_homePath.c_str(),nwid);
  1598. OSUtils::rm(nlcpath);
  1599. }
  1600. } else {
  1601. _nets.erase(nwid);
  1602. }
  1603. break;
  1604. }
  1605. return 0;
  1606. }
  1607. inline void nodeEventCallback(enum ZT_Event event,const void *metaData)
  1608. {
  1609. switch(event) {
  1610. case ZT_EVENT_TRACE: {
  1611. if (metaData) {
  1612. ::fprintf(stderr,"%s" ZT_EOL_S,(const char *)metaData);
  1613. ::fflush(stderr);
  1614. }
  1615. } break;
  1616. case ZT_EVENT_REMOTE_TRACE: {
  1617. // TODO
  1618. }
  1619. default:
  1620. break;
  1621. }
  1622. }
  1623. inline void nodeStatePutFunction(enum ZT_StateObjectType type,const uint64_t id[2],const void *data,int len)
  1624. {
  1625. char p[1024];
  1626. FILE *f;
  1627. bool secure = false;
  1628. char dirname[1024];
  1629. dirname[0] = 0;
  1630. switch(type) {
  1631. case ZT_STATE_OBJECT_IDENTITY_PUBLIC:
  1632. OSUtils::ztsnprintf(p,sizeof(p),"%s" ZT_PATH_SEPARATOR_S "identity.public",_homePath.c_str());
  1633. break;
  1634. case ZT_STATE_OBJECT_IDENTITY_SECRET:
  1635. OSUtils::ztsnprintf(p,sizeof(p),"%s" ZT_PATH_SEPARATOR_S "identity.secret",_homePath.c_str());
  1636. secure = true;
  1637. break;
  1638. case ZT_STATE_OBJECT_NETWORK_CONFIG:
  1639. OSUtils::ztsnprintf(dirname,sizeof(dirname),"%s" ZT_PATH_SEPARATOR_S "networks.d",_homePath.c_str());
  1640. OSUtils::ztsnprintf(p,sizeof(p),"%s" ZT_PATH_SEPARATOR_S "%.16llx.conf",dirname,(unsigned long long)id[0]);
  1641. secure = true;
  1642. break;
  1643. case ZT_STATE_OBJECT_PEER:
  1644. OSUtils::ztsnprintf(dirname,sizeof(dirname),"%s" ZT_PATH_SEPARATOR_S "peers.d",_homePath.c_str());
  1645. OSUtils::ztsnprintf(p,sizeof(p),"%s" ZT_PATH_SEPARATOR_S "%.10llx.peer",dirname,(unsigned long long)id[0]);
  1646. break;
  1647. case ZT_STATE_OBJECT_ROOT_LIST:
  1648. OSUtils::ztsnprintf(p,sizeof(p),"%s" ZT_PATH_SEPARATOR_S "roots",_homePath.c_str());
  1649. break;
  1650. default:
  1651. return;
  1652. }
  1653. if ((len >= 0)&&(data)) {
  1654. // Check to see if we've already written this first. This reduces
  1655. // redundant writes and I/O overhead on most platforms and has
  1656. // little effect on others.
  1657. f = fopen(p,"rb");
  1658. if (f) {
  1659. char *const buf = (char *)malloc(len*4);
  1660. if (buf) {
  1661. long l = (long)fread(buf,1,(size_t)(len*4),f);
  1662. fclose(f);
  1663. if ((l == (long)len)&&(memcmp(data,buf,l) == 0)) {
  1664. free(buf);
  1665. return;
  1666. }
  1667. free(buf);
  1668. }
  1669. }
  1670. f = fopen(p,"wb");
  1671. if ((!f)&&(dirname[0])) { // create subdirectory if it does not exist
  1672. OSUtils::mkdir(dirname);
  1673. f = fopen(p,"wb");
  1674. }
  1675. if (f) {
  1676. if (fwrite(data,len,1,f) != 1)
  1677. fprintf(stderr,"WARNING: unable to write to file: %s (I/O error)" ZT_EOL_S,p);
  1678. fclose(f);
  1679. if (secure)
  1680. OSUtils::lockDownFile(p,false);
  1681. } else {
  1682. fprintf(stderr,"WARNING: unable to write to file: %s (unable to open)" ZT_EOL_S,p);
  1683. }
  1684. } else {
  1685. OSUtils::rm(p);
  1686. }
  1687. }
  1688. inline int nodeStateGetFunction(enum ZT_StateObjectType type,const uint64_t id[2],void *data,unsigned int maxlen)
  1689. {
  1690. char p[4096];
  1691. switch(type) {
  1692. case ZT_STATE_OBJECT_IDENTITY_PUBLIC:
  1693. OSUtils::ztsnprintf(p,sizeof(p),"%s" ZT_PATH_SEPARATOR_S "identity.public",_homePath.c_str());
  1694. break;
  1695. case ZT_STATE_OBJECT_IDENTITY_SECRET:
  1696. OSUtils::ztsnprintf(p,sizeof(p),"%s" ZT_PATH_SEPARATOR_S "identity.secret",_homePath.c_str());
  1697. break;
  1698. case ZT_STATE_OBJECT_NETWORK_CONFIG:
  1699. OSUtils::ztsnprintf(p,sizeof(p),"%s" ZT_PATH_SEPARATOR_S "networks.d" ZT_PATH_SEPARATOR_S "%.16llx.conf",_homePath.c_str(),(unsigned long long)id[0]);
  1700. break;
  1701. case ZT_STATE_OBJECT_PEER:
  1702. OSUtils::ztsnprintf(p,sizeof(p),"%s" ZT_PATH_SEPARATOR_S "peers.d" ZT_PATH_SEPARATOR_S "%.10llx.peer",_homePath.c_str(),(unsigned long long)id[0]);
  1703. break;
  1704. default:
  1705. return -1;
  1706. }
  1707. FILE *f = fopen(p,"rb");
  1708. if (f) {
  1709. int n = (int)fread(data,1,maxlen,f);
  1710. fclose(f);
  1711. if (n >= 0)
  1712. return n;
  1713. }
  1714. return -1;
  1715. }
  1716. inline int nodeWirePacketSendFunction(const int64_t localSocket,const struct sockaddr_storage *addr,const void *data,unsigned int len,unsigned int ttl)
  1717. {
  1718. if ((localSocket != -1)&&(localSocket != 0)&&(_binder.isUdpSocketValid((PhySocket *)((uintptr_t)localSocket)))) {
  1719. if ((ttl)&&(addr->ss_family == AF_INET)) _phy.setIp4UdpTtl((PhySocket *)((uintptr_t)localSocket),ttl);
  1720. const bool r = _phy.udpSend((PhySocket *)((uintptr_t)localSocket),(const struct sockaddr *)addr,data,len);
  1721. if ((ttl)&&(addr->ss_family == AF_INET)) _phy.setIp4UdpTtl((PhySocket *)((uintptr_t)localSocket),255);
  1722. return ((r) ? 0 : -1);
  1723. } else {
  1724. return ((_binder.udpSendAll(_phy,addr,data,len,ttl)) ? 0 : -1);
  1725. }
  1726. }
  1727. 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)
  1728. {
  1729. NetworkState *n = reinterpret_cast<NetworkState *>(*nuptr);
  1730. if ((!n)||(!n->tap))
  1731. return;
  1732. n->tap->put(MAC(sourceMac),MAC(destMac),etherType,data,len);
  1733. }
  1734. inline int nodePathCheckFunction(uint64_t ztaddr,const int64_t localSocket,const struct sockaddr_storage *remoteAddr)
  1735. {
  1736. // Make sure we're not trying to do ZeroTier-over-ZeroTier
  1737. {
  1738. Mutex::Lock _l(_nets_m);
  1739. for(std::map<uint64_t,NetworkState>::const_iterator n(_nets.begin());n!=_nets.end();++n) {
  1740. if (n->second.tap) {
  1741. std::vector<InetAddress> ips(n->second.tap->ips());
  1742. for(std::vector<InetAddress>::const_iterator i(ips.begin());i!=ips.end();++i) {
  1743. if (i->containsAddress(*(reinterpret_cast<const InetAddress *>(remoteAddr)))) {
  1744. return 0;
  1745. }
  1746. }
  1747. }
  1748. }
  1749. }
  1750. /* Note: I do not think we need to scan for overlap with managed routes
  1751. * because of the "route forking" and interface binding that we do. This
  1752. * ensures (we hope) that ZeroTier traffic will still take the physical
  1753. * path even if its managed routes override this for other traffic. Will
  1754. * revisit if we see recursion problems. */
  1755. // Check blacklists
  1756. const Hashtable< uint64_t,std::vector<InetAddress> > *blh = (const Hashtable< uint64_t,std::vector<InetAddress> > *)0;
  1757. const std::vector<InetAddress> *gbl = (const std::vector<InetAddress> *)0;
  1758. if (remoteAddr->ss_family == AF_INET) {
  1759. blh = &_v4Blacklists;
  1760. gbl = &_globalV4Blacklist;
  1761. } else if (remoteAddr->ss_family == AF_INET6) {
  1762. blh = &_v6Blacklists;
  1763. gbl = &_globalV6Blacklist;
  1764. }
  1765. if (blh) {
  1766. Mutex::Lock _l(_localConfig_m);
  1767. const std::vector<InetAddress> *l = blh->get(ztaddr);
  1768. if (l) {
  1769. for(std::vector<InetAddress>::const_iterator a(l->begin());a!=l->end();++a) {
  1770. if (a->containsAddress(*reinterpret_cast<const InetAddress *>(remoteAddr)))
  1771. return 0;
  1772. }
  1773. }
  1774. }
  1775. if (gbl) {
  1776. for(std::vector<InetAddress>::const_iterator a(gbl->begin());a!=gbl->end();++a) {
  1777. if (a->containsAddress(*reinterpret_cast<const InetAddress *>(remoteAddr)))
  1778. return 0;
  1779. }
  1780. }
  1781. return 1;
  1782. }
  1783. inline int nodePathLookupFunction(uint64_t ztaddr,int family,struct sockaddr_storage *result)
  1784. {
  1785. const Hashtable< uint64_t,std::vector<InetAddress> > *lh = (const Hashtable< uint64_t,std::vector<InetAddress> > *)0;
  1786. if (family < 0)
  1787. lh = (Utils::random() & 1) ? &_v4Hints : &_v6Hints;
  1788. else if (family == AF_INET)
  1789. lh = &_v4Hints;
  1790. else if (family == AF_INET6)
  1791. lh = &_v6Hints;
  1792. else return 0;
  1793. const std::vector<InetAddress> *l = lh->get(ztaddr);
  1794. if ((l)&&(l->size() > 0)) {
  1795. memcpy(result,&((*l)[(unsigned long)Utils::random() % l->size()]),sizeof(struct sockaddr_storage));
  1796. return 1;
  1797. } else return 0;
  1798. }
  1799. inline void tapFrameHandler(uint64_t nwid,const MAC &from,const MAC &to,unsigned int etherType,unsigned int vlanId,const void *data,unsigned int len)
  1800. {
  1801. _node->processVirtualNetworkFrame((void *)0,OSUtils::now(),nwid,from.toInt(),to.toInt(),etherType,vlanId,data,len,&_nextBackgroundTaskDeadline);
  1802. }
  1803. inline void onHttpRequestToServer(TcpConnection *tc)
  1804. {
  1805. char tmpn[4096];
  1806. std::string data;
  1807. std::string contentType("text/plain"); // default if not changed in handleRequest()
  1808. unsigned int scode = 404;
  1809. // Note that we check allowed IP ranges when HTTP connections are first detected in
  1810. // phyOnTcpData(). If we made it here the source IP is okay.
  1811. try {
  1812. scode = handleControlPlaneHttpRequest(tc->remoteAddr,tc->parser.method,tc->url,tc->headers,tc->readq,data,contentType);
  1813. } catch (std::exception &exc) {
  1814. fprintf(stderr,"WARNING: unexpected exception processing control HTTP request: %s" ZT_EOL_S,exc.what());
  1815. scode = 500;
  1816. } catch ( ... ) {
  1817. fprintf(stderr,"WARNING: unexpected exception processing control HTTP request: unknown exception" ZT_EOL_S);
  1818. scode = 500;
  1819. }
  1820. const char *scodestr;
  1821. switch(scode) {
  1822. case 200: scodestr = "OK"; break;
  1823. case 400: scodestr = "Bad Request"; break;
  1824. case 401: scodestr = "Unauthorized"; break;
  1825. case 403: scodestr = "Forbidden"; break;
  1826. case 404: scodestr = "Not Found"; break;
  1827. case 500: scodestr = "Internal Server Error"; break;
  1828. case 501: scodestr = "Not Implemented"; break;
  1829. case 503: scodestr = "Service Unavailable"; break;
  1830. default: scodestr = "Error"; break;
  1831. }
  1832. OSUtils::ztsnprintf(tmpn,sizeof(tmpn),"HTTP/1.1 %.3u %s\r\nCache-Control: no-cache\r\nPragma: no-cache\r\nContent-Type: %s\r\nContent-Length: %lu\r\nConnection: close\r\n\r\n",
  1833. scode,
  1834. scodestr,
  1835. contentType.c_str(),
  1836. (unsigned long)data.length());
  1837. {
  1838. Mutex::Lock _l(tc->writeq_m);
  1839. tc->writeq = tmpn;
  1840. if (tc->parser.method != HTTP_HEAD)
  1841. tc->writeq.append(data);
  1842. }
  1843. _phy.setNotifyWritable(tc->sock,true);
  1844. }
  1845. inline void onHttpResponseFromClient(TcpConnection *tc)
  1846. {
  1847. _phy.close(tc->sock);
  1848. }
  1849. bool shouldBindInterface(const char *ifname,const InetAddress &ifaddr)
  1850. {
  1851. #if defined(__linux__) || defined(linux) || defined(__LINUX__) || defined(__linux)
  1852. if ((ifname[0] == 'l')&&(ifname[1] == 'o')) return false; // loopback
  1853. if ((ifname[0] == 'z')&&(ifname[1] == 't')) return false; // sanity check: zt#
  1854. if ((ifname[0] == 't')&&(ifname[1] == 'u')&&(ifname[2] == 'n')) return false; // tun# is probably an OpenVPN tunnel or similar
  1855. if ((ifname[0] == 't')&&(ifname[1] == 'a')&&(ifname[2] == 'p')) return false; // tap# is probably an OpenVPN tunnel or similar
  1856. #endif
  1857. #ifdef __APPLE__
  1858. if ((ifname[0] == 'f')&&(ifname[1] == 'e')&&(ifname[2] == 't')&&(ifname[3] == 'h')) return false; // ... as is feth#
  1859. if ((ifname[0] == 'l')&&(ifname[1] == 'o')) return false; // loopback
  1860. if ((ifname[0] == 'z')&&(ifname[1] == 't')) return false; // sanity check: zt#
  1861. if ((ifname[0] == 't')&&(ifname[1] == 'u')&&(ifname[2] == 'n')) return false; // tun# is probably an OpenVPN tunnel or similar
  1862. if ((ifname[0] == 't')&&(ifname[1] == 'a')&&(ifname[2] == 'p')) return false; // tap# is probably an OpenVPN tunnel or similar
  1863. if ((ifname[0] == 'u')&&(ifname[1] == 't')&&(ifname[2] == 'u')&&(ifname[3] == 'n')) return false; // ... as is utun#
  1864. #endif
  1865. {
  1866. Mutex::Lock _l(_localConfig_m);
  1867. for(std::vector<std::string>::const_iterator p(_interfacePrefixBlacklist.begin());p!=_interfacePrefixBlacklist.end();++p) {
  1868. if (!strncmp(p->c_str(),ifname,p->length()))
  1869. return false;
  1870. }
  1871. }
  1872. {
  1873. // Check global blacklists
  1874. const std::vector<InetAddress> *gbl = (const std::vector<InetAddress> *)0;
  1875. if (ifaddr.ss_family == AF_INET) {
  1876. gbl = &_globalV4Blacklist;
  1877. } else if (ifaddr.ss_family == AF_INET6) {
  1878. gbl = &_globalV6Blacklist;
  1879. }
  1880. if (gbl) {
  1881. Mutex::Lock _l(_localConfig_m);
  1882. for(std::vector<InetAddress>::const_iterator a(gbl->begin());a!=gbl->end();++a) {
  1883. if (a->containsAddress(ifaddr))
  1884. return false;
  1885. }
  1886. }
  1887. }
  1888. {
  1889. Mutex::Lock _l(_nets_m);
  1890. for(std::map<uint64_t,NetworkState>::const_iterator n(_nets.begin());n!=_nets.end();++n) {
  1891. if (n->second.tap) {
  1892. std::vector<InetAddress> ips(n->second.tap->ips());
  1893. for(std::vector<InetAddress>::const_iterator i(ips.begin());i!=ips.end();++i) {
  1894. if (i->ipsEqual(ifaddr))
  1895. return false;
  1896. }
  1897. }
  1898. }
  1899. }
  1900. return true;
  1901. }
  1902. bool _trialBind(unsigned int port)
  1903. {
  1904. struct sockaddr_in in4;
  1905. struct sockaddr_in6 in6;
  1906. PhySocket *tb;
  1907. memset(&in4,0,sizeof(in4));
  1908. in4.sin_family = AF_INET;
  1909. in4.sin_port = Utils::hton((uint16_t)port);
  1910. tb = _phy.udpBind(reinterpret_cast<const struct sockaddr *>(&in4),(void *)0,0);
  1911. if (tb) {
  1912. _phy.close(tb,false);
  1913. tb = _phy.tcpListen(reinterpret_cast<const struct sockaddr *>(&in4),(void *)0);
  1914. if (tb) {
  1915. _phy.close(tb,false);
  1916. return true;
  1917. }
  1918. }
  1919. memset(&in6,0,sizeof(in6));
  1920. in6.sin6_family = AF_INET6;
  1921. in6.sin6_port = Utils::hton((uint16_t)port);
  1922. tb = _phy.udpBind(reinterpret_cast<const struct sockaddr *>(&in6),(void *)0,0);
  1923. if (tb) {
  1924. _phy.close(tb,false);
  1925. tb = _phy.tcpListen(reinterpret_cast<const struct sockaddr *>(&in6),(void *)0);
  1926. if (tb) {
  1927. _phy.close(tb,false);
  1928. return true;
  1929. }
  1930. }
  1931. return false;
  1932. }
  1933. };
  1934. static int SnodeVirtualNetworkConfigFunction(ZT_Node *node,void *uptr,void *tptr,uint64_t nwid,void **nuptr,enum ZT_VirtualNetworkConfigOperation op,const ZT_VirtualNetworkConfig *nwconf)
  1935. { return reinterpret_cast<OneServiceImpl *>(uptr)->nodeVirtualNetworkConfigFunction(nwid,nuptr,op,nwconf); }
  1936. static void SnodeEventCallback(ZT_Node *node,void *uptr,void *tptr,enum ZT_Event event,const void *metaData)
  1937. { reinterpret_cast<OneServiceImpl *>(uptr)->nodeEventCallback(event,metaData); }
  1938. static void SnodeStatePutFunction(ZT_Node *node,void *uptr,void *tptr,enum ZT_StateObjectType type,const uint64_t id[2],const void *data,int len)
  1939. { reinterpret_cast<OneServiceImpl *>(uptr)->nodeStatePutFunction(type,id,data,len); }
  1940. static int SnodeStateGetFunction(ZT_Node *node,void *uptr,void *tptr,enum ZT_StateObjectType type,const uint64_t id[2],void *data,unsigned int maxlen)
  1941. { return reinterpret_cast<OneServiceImpl *>(uptr)->nodeStateGetFunction(type,id,data,maxlen); }
  1942. static int SnodeWirePacketSendFunction(ZT_Node *node,void *uptr,void *tptr,int64_t localSocket,const struct sockaddr_storage *addr,const void *data,unsigned int len,unsigned int ttl)
  1943. { return reinterpret_cast<OneServiceImpl *>(uptr)->nodeWirePacketSendFunction(localSocket,addr,data,len,ttl); }
  1944. static void SnodeVirtualNetworkFrameFunction(ZT_Node *node,void *uptr,void *tptr,uint64_t nwid,void **nuptr,uint64_t sourceMac,uint64_t destMac,unsigned int etherType,unsigned int vlanId,const void *data,unsigned int len)
  1945. { reinterpret_cast<OneServiceImpl *>(uptr)->nodeVirtualNetworkFrameFunction(nwid,nuptr,sourceMac,destMac,etherType,vlanId,data,len); }
  1946. static int SnodePathCheckFunction(ZT_Node *node,void *uptr,void *tptr,uint64_t ztaddr,int64_t localSocket,const struct sockaddr_storage *remoteAddr)
  1947. { return reinterpret_cast<OneServiceImpl *>(uptr)->nodePathCheckFunction(ztaddr,localSocket,remoteAddr); }
  1948. static int SnodePathLookupFunction(ZT_Node *node,void *uptr,void *tptr,uint64_t ztaddr,int family,struct sockaddr_storage *result)
  1949. { return reinterpret_cast<OneServiceImpl *>(uptr)->nodePathLookupFunction(ztaddr,family,result); }
  1950. static void StapFrameHandler(void *uptr,void *tptr,uint64_t nwid,const MAC &from,const MAC &to,unsigned int etherType,unsigned int vlanId,const void *data,unsigned int len)
  1951. { reinterpret_cast<OneServiceImpl *>(uptr)->tapFrameHandler(nwid,from,to,etherType,vlanId,data,len); }
  1952. static int ShttpOnMessageBegin(http_parser *parser)
  1953. {
  1954. TcpConnection *tc = reinterpret_cast<TcpConnection *>(parser->data);
  1955. tc->currentHeaderField = "";
  1956. tc->currentHeaderValue = "";
  1957. tc->messageSize = 0;
  1958. tc->url.clear();
  1959. tc->status.clear();
  1960. tc->headers.clear();
  1961. tc->readq.clear();
  1962. return 0;
  1963. }
  1964. static int ShttpOnUrl(http_parser *parser,const char *ptr,size_t length)
  1965. {
  1966. TcpConnection *tc = reinterpret_cast<TcpConnection *>(parser->data);
  1967. tc->messageSize += (unsigned long)length;
  1968. if (tc->messageSize > ZT_MAX_HTTP_MESSAGE_SIZE)
  1969. return -1;
  1970. tc->url.append(ptr,length);
  1971. return 0;
  1972. }
  1973. #if (HTTP_PARSER_VERSION_MAJOR >= 2) && (HTTP_PARSER_VERSION_MINOR >= 2)
  1974. static int ShttpOnStatus(http_parser *parser,const char *ptr,size_t length)
  1975. #else
  1976. static int ShttpOnStatus(http_parser *parser)
  1977. #endif
  1978. { return 0; }
  1979. static int ShttpOnHeaderField(http_parser *parser,const char *ptr,size_t length)
  1980. {
  1981. TcpConnection *tc = reinterpret_cast<TcpConnection *>(parser->data);
  1982. tc->messageSize += (unsigned long)length;
  1983. if (tc->messageSize > ZT_MAX_HTTP_MESSAGE_SIZE)
  1984. return -1;
  1985. if ((tc->currentHeaderField.length())&&(tc->currentHeaderValue.length())) {
  1986. tc->headers[tc->currentHeaderField] = tc->currentHeaderValue;
  1987. tc->currentHeaderField = "";
  1988. tc->currentHeaderValue = "";
  1989. }
  1990. for(size_t i=0;i<length;++i)
  1991. tc->currentHeaderField.push_back(OSUtils::toLower(ptr[i]));
  1992. return 0;
  1993. }
  1994. static int ShttpOnValue(http_parser *parser,const char *ptr,size_t length)
  1995. {
  1996. TcpConnection *tc = reinterpret_cast<TcpConnection *>(parser->data);
  1997. tc->messageSize += (unsigned long)length;
  1998. if (tc->messageSize > ZT_MAX_HTTP_MESSAGE_SIZE)
  1999. return -1;
  2000. tc->currentHeaderValue.append(ptr,length);
  2001. return 0;
  2002. }
  2003. static int ShttpOnHeadersComplete(http_parser *parser)
  2004. {
  2005. TcpConnection *tc = reinterpret_cast<TcpConnection *>(parser->data);
  2006. if ((tc->currentHeaderField.length())&&(tc->currentHeaderValue.length()))
  2007. tc->headers[tc->currentHeaderField] = tc->currentHeaderValue;
  2008. return 0;
  2009. }
  2010. static int ShttpOnBody(http_parser *parser,const char *ptr,size_t length)
  2011. {
  2012. TcpConnection *tc = reinterpret_cast<TcpConnection *>(parser->data);
  2013. tc->messageSize += (unsigned long)length;
  2014. if (tc->messageSize > ZT_MAX_HTTP_MESSAGE_SIZE)
  2015. return -1;
  2016. tc->readq.append(ptr,length);
  2017. return 0;
  2018. }
  2019. static int ShttpOnMessageComplete(http_parser *parser)
  2020. {
  2021. TcpConnection *tc = reinterpret_cast<TcpConnection *>(parser->data);
  2022. if (tc->type == TcpConnection::TCP_HTTP_INCOMING) {
  2023. tc->parent->onHttpRequestToServer(tc);
  2024. } else {
  2025. tc->parent->onHttpResponseFromClient(tc);
  2026. }
  2027. return 0;
  2028. }
  2029. } // anonymous namespace
  2030. std::string OneService::platformDefaultHomePath()
  2031. {
  2032. return OSUtils::platformDefaultHomePath();
  2033. }
  2034. OneService *OneService::newInstance(const char *hp,unsigned int port) { return new OneServiceImpl(hp,port); }
  2035. OneService::~OneService() {}
  2036. } // namespace ZeroTier