OneService.cpp 79 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260
  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/ZeroTierOne.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. _ports[1] = (_secondaryPort == 0) ? 20000 + ((unsigned int)_node->address() % 45500) : _secondaryPort;
  483. for(int i=0;;++i) {
  484. if (i > 1000) {
  485. _ports[1] = 0;
  486. break;
  487. } else if (++_ports[1] >= 65536) {
  488. _ports[1] = 20000;
  489. }
  490. if (_trialBind(_ports[1]))
  491. break;
  492. }
  493. }
  494. if (_portMappingEnabled) {
  495. // If we're running uPnP/NAT-PMP, bind a *third* port for that. We can't
  496. // use the other two ports for that because some NATs do really funky
  497. // stuff with ports that are explicitly mapped that breaks things.
  498. if (_ports[1]) {
  499. _ports[2] = (_tertiaryPort == 0) ? _ports[1] : _tertiaryPort;
  500. for(int i=0;;++i) {
  501. if (i > 1000) {
  502. _ports[2] = 0;
  503. break;
  504. } else if (++_ports[2] >= 65536) {
  505. _ports[2] = 20000;
  506. }
  507. if (_trialBind(_ports[2]))
  508. break;
  509. }
  510. if (_ports[2]) {
  511. char uniqueName[64];
  512. OSUtils::ztsnprintf(uniqueName,sizeof(uniqueName),"ZeroTier/%.10llx@%u",_node->address(),_ports[2]);
  513. _portMapper = new PortMapper(_ports[2],uniqueName);
  514. }
  515. }
  516. }
  517. // Delete legacy iddb.d if present (cleanup)
  518. OSUtils::rmDashRf((_homePath + ZT_PATH_SEPARATOR_S "iddb.d").c_str());
  519. // Network controller is now enabled by default for desktop and server
  520. _controller = new EmbeddedNetworkController(_node,_homePath.c_str(),_controllerDbPath.c_str(),_ports[0], _mqc);
  521. _node->setController((void *)_controller);
  522. // Join existing networks in networks.d
  523. {
  524. std::vector<std::string> networksDotD(OSUtils::listDirectory((_homePath + ZT_PATH_SEPARATOR_S "networks.d").c_str()));
  525. for(std::vector<std::string>::iterator f(networksDotD.begin());f!=networksDotD.end();++f) {
  526. std::size_t dot = f->find_last_of('.');
  527. if ((dot == 16)&&(f->substr(16) == ".conf"))
  528. _node->join(Utils::hexStrToU64(f->substr(0,dot).c_str()),(void *)0,(void *)0);
  529. }
  530. }
  531. // Main I/O loop
  532. _nextBackgroundTaskDeadline = 0;
  533. int64_t clockShouldBe = OSUtils::now();
  534. _lastRestart = clockShouldBe;
  535. int64_t lastTapMulticastGroupCheck = 0;
  536. int64_t lastBindRefresh = 0;
  537. int64_t lastMultipathModeUpdate = 0;
  538. int64_t lastCleanedPeersDb = 0;
  539. 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
  540. int64_t lastLocalConfFileCheck = OSUtils::now();
  541. for(;;) {
  542. _run_m.lock();
  543. if (!_run) {
  544. _run_m.unlock();
  545. _termReason_m.lock();
  546. _termReason = ONE_NORMAL_TERMINATION;
  547. _termReason_m.unlock();
  548. break;
  549. } else {
  550. _run_m.unlock();
  551. }
  552. const int64_t now = OSUtils::now();
  553. // Attempt to detect sleep/wake events by detecting delay overruns
  554. bool restarted = false;
  555. if ((now > clockShouldBe)&&((now - clockShouldBe) > 10000)) {
  556. _lastRestart = now;
  557. restarted = true;
  558. }
  559. // Reload local.conf if anything changed recently
  560. if ((now - lastLocalConfFileCheck) >= ZT_LOCAL_CONF_FILE_CHECK_INTERVAL) {
  561. lastLocalConfFileCheck = now;
  562. struct stat result;
  563. if(stat((_homePath + ZT_PATH_SEPARATOR_S "local.conf").c_str(), &result)==0) {
  564. int64_t mod_time = result.st_mtime * 1000;
  565. if ((now - mod_time) <= ZT_LOCAL_CONF_FILE_CHECK_INTERVAL) {
  566. readLocalSettings();
  567. applyLocalConfig();
  568. }
  569. }
  570. }
  571. // Refresh bindings in case device's interfaces have changed, and also sync routes to update any shadow routes (e.g. shadow default)
  572. if (((now - lastBindRefresh) >= (_multipathMode ? ZT_BINDER_REFRESH_PERIOD / 8 : ZT_BINDER_REFRESH_PERIOD))||(restarted)) {
  573. lastBindRefresh = now;
  574. unsigned int p[3];
  575. unsigned int pc = 0;
  576. for(int i=0;i<3;++i) {
  577. if (_ports[i])
  578. p[pc++] = _ports[i];
  579. }
  580. _binder.refresh(_phy,p,pc,_explicitBind,*this);
  581. {
  582. Mutex::Lock _l(_nets_m);
  583. for(std::map<uint64_t,NetworkState>::iterator n(_nets.begin());n!=_nets.end();++n) {
  584. if (n->second.tap)
  585. syncManagedStuff(n->second,false,true);
  586. }
  587. }
  588. }
  589. // Update multipath mode (if needed)
  590. if (((now - lastMultipathModeUpdate) >= ZT_BINDER_REFRESH_PERIOD / 8)||(restarted)) {
  591. lastMultipathModeUpdate = now;
  592. _node->setMultipathMode(_multipathMode);
  593. }
  594. // Run background task processor in core if it's time to do so
  595. int64_t dl = _nextBackgroundTaskDeadline;
  596. if (dl <= now) {
  597. _node->processBackgroundTasks((void *)0,now,&_nextBackgroundTaskDeadline);
  598. dl = _nextBackgroundTaskDeadline;
  599. }
  600. // Sync multicast group memberships
  601. if ((now - lastTapMulticastGroupCheck) >= ZT_TAP_CHECK_MULTICAST_INTERVAL) {
  602. lastTapMulticastGroupCheck = now;
  603. std::vector< std::pair< uint64_t,std::pair< std::vector<MulticastGroup>,std::vector<MulticastGroup> > > > mgChanges;
  604. {
  605. Mutex::Lock _l(_nets_m);
  606. mgChanges.reserve(_nets.size() + 1);
  607. for(std::map<uint64_t,NetworkState>::const_iterator n(_nets.begin());n!=_nets.end();++n) {
  608. if (n->second.tap) {
  609. 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> >()));
  610. n->second.tap->scanMulticastGroups(mgChanges.back().second.first,mgChanges.back().second.second);
  611. }
  612. }
  613. }
  614. for(std::vector< std::pair< uint64_t,std::pair< std::vector<MulticastGroup>,std::vector<MulticastGroup> > > >::iterator c(mgChanges.begin());c!=mgChanges.end();++c) {
  615. for(std::vector<MulticastGroup>::iterator m(c->second.first.begin());m!=c->second.first.end();++m)
  616. _node->multicastSubscribe((void *)0,c->first,m->mac().toInt(),m->adi());
  617. for(std::vector<MulticastGroup>::iterator m(c->second.second.begin());m!=c->second.second.end();++m)
  618. _node->multicastUnsubscribe(c->first,m->mac().toInt(),m->adi());
  619. }
  620. }
  621. // Sync information about physical network interfaces
  622. if ((now - lastLocalInterfaceAddressCheck) >= (_multipathMode ? ZT_LOCAL_INTERFACE_CHECK_INTERVAL / 8 : ZT_LOCAL_INTERFACE_CHECK_INTERVAL)) {
  623. lastLocalInterfaceAddressCheck = now;
  624. _node->clearLocalInterfaceAddresses();
  625. if (_portMapper) {
  626. std::vector<InetAddress> mappedAddresses(_portMapper->get());
  627. for(std::vector<InetAddress>::const_iterator ext(mappedAddresses.begin());ext!=mappedAddresses.end();++ext)
  628. _node->addLocalInterfaceAddress(reinterpret_cast<const struct sockaddr_storage *>(&(*ext)));
  629. }
  630. std::vector<InetAddress> boundAddrs(_binder.allBoundLocalInterfaceAddresses());
  631. for(std::vector<InetAddress>::const_iterator i(boundAddrs.begin());i!=boundAddrs.end();++i)
  632. _node->addLocalInterfaceAddress(reinterpret_cast<const struct sockaddr_storage *>(&(*i)));
  633. }
  634. // Clean peers.d periodically
  635. if ((now - lastCleanedPeersDb) >= 3600000) {
  636. lastCleanedPeersDb = now;
  637. OSUtils::cleanDirectory((_homePath + ZT_PATH_SEPARATOR_S "peers.d").c_str(),now - 2592000000LL); // delete older than 30 days
  638. }
  639. const unsigned long delay = (dl > now) ? (unsigned long)(dl - now) : 100;
  640. clockShouldBe = now + (uint64_t)delay;
  641. _phy.poll(delay);
  642. }
  643. } catch (std::exception &e) {
  644. Mutex::Lock _l(_termReason_m);
  645. _termReason = ONE_UNRECOVERABLE_ERROR;
  646. _fatalErrorMessage = std::string("unexpected exception in main thread: ")+e.what();
  647. } catch ( ... ) {
  648. Mutex::Lock _l(_termReason_m);
  649. _termReason = ONE_UNRECOVERABLE_ERROR;
  650. _fatalErrorMessage = "unexpected exception in main thread: unknown exception";
  651. }
  652. try {
  653. Mutex::Lock _l(_tcpConnections_m);
  654. while (!_tcpConnections.empty())
  655. _phy.close((*_tcpConnections.begin())->sock);
  656. } catch ( ... ) {}
  657. {
  658. Mutex::Lock _l(_nets_m);
  659. _nets.clear();
  660. }
  661. delete _node;
  662. _node = (Node *)0;
  663. return _termReason;
  664. }
  665. void readLocalSettings()
  666. {
  667. // Read local configuration
  668. std::map<InetAddress,ZT_PhysicalPathConfiguration> ppc;
  669. // LEGACY: support old "trustedpaths" flat file
  670. FILE *trustpaths = fopen((_homePath + ZT_PATH_SEPARATOR_S "trustedpaths").c_str(),"r");
  671. if (trustpaths) {
  672. fprintf(stderr,"WARNING: 'trustedpaths' flat file format is deprecated in favor of path definitions in local.conf" ZT_EOL_S);
  673. char buf[1024];
  674. while (fgets(buf,sizeof(buf),trustpaths)) {
  675. int fno = 0;
  676. char *saveptr = (char *)0;
  677. uint64_t trustedPathId = 0;
  678. InetAddress trustedPathNetwork;
  679. for(char *f=Utils::stok(buf,"=\r\n \t",&saveptr);(f);f=Utils::stok((char *)0,"=\r\n \t",&saveptr)) {
  680. if (fno == 0) {
  681. trustedPathId = Utils::hexStrToU64(f);
  682. } else if (fno == 1) {
  683. trustedPathNetwork = InetAddress(f);
  684. } else break;
  685. ++fno;
  686. }
  687. if ( (trustedPathId != 0) && ((trustedPathNetwork.ss_family == AF_INET)||(trustedPathNetwork.ss_family == AF_INET6)) && (trustedPathNetwork.netmaskBits() > 0) ) {
  688. ppc[trustedPathNetwork].trustedPathId = trustedPathId;
  689. ppc[trustedPathNetwork].mtu = 0; // use default
  690. }
  691. }
  692. fclose(trustpaths);
  693. }
  694. // Read local config file
  695. Mutex::Lock _l2(_localConfig_m);
  696. std::string lcbuf;
  697. if (OSUtils::readFile((_homePath + ZT_PATH_SEPARATOR_S "local.conf").c_str(),lcbuf)) {
  698. if (lcbuf.length() > 0) {
  699. try {
  700. _localConfig = OSUtils::jsonParse(lcbuf);
  701. if (!_localConfig.is_object()) {
  702. fprintf(stderr,"ERROR: unable to parse local.conf (root element is not a JSON object)" ZT_EOL_S);
  703. exit(1);
  704. }
  705. } catch ( ... ) {
  706. fprintf(stderr,"ERROR: unable to parse local.conf (invalid JSON)" ZT_EOL_S);
  707. exit(1);
  708. }
  709. }
  710. }
  711. // Get any trusted paths in local.conf (we'll parse the rest of physical[] elsewhere)
  712. json &physical = _localConfig["physical"];
  713. if (physical.is_object()) {
  714. for(json::iterator phy(physical.begin());phy!=physical.end();++phy) {
  715. InetAddress net(OSUtils::jsonString(phy.key(),"").c_str());
  716. if (net) {
  717. if (phy.value().is_object()) {
  718. uint64_t tpid;
  719. if ((tpid = OSUtils::jsonInt(phy.value()["trustedPathId"],0ULL)) != 0ULL) {
  720. if ((net.ss_family == AF_INET)||(net.ss_family == AF_INET6))
  721. ppc[net].trustedPathId = tpid;
  722. }
  723. ppc[net].mtu = (int)OSUtils::jsonInt(phy.value()["mtu"],0ULL); // 0 means use default
  724. }
  725. }
  726. }
  727. }
  728. json &settings = _localConfig["settings"];
  729. if (settings.is_object()) {
  730. // Allow controller DB path to be put somewhere else
  731. const std::string cdbp(OSUtils::jsonString(settings["controllerDbPath"],""));
  732. if (cdbp.length() > 0)
  733. _controllerDbPath = cdbp;
  734. json &rmq = settings["rabbitmq"];
  735. if (rmq.is_object() && _mqc == NULL) {
  736. fprintf(stderr, "Reading RabbitMQ Config\n");
  737. _mqc = new MQConfig;
  738. _mqc->port = rmq["port"];
  739. _mqc->host = OSUtils::jsonString(rmq["host"], "").c_str();
  740. _mqc->username = OSUtils::jsonString(rmq["username"], "").c_str();
  741. _mqc->password = OSUtils::jsonString(rmq["password"], "").c_str();
  742. }
  743. // Bind to wildcard instead of to specific interfaces (disables full tunnel capability)
  744. json &bind = settings["bind"];
  745. if (bind.is_array()) {
  746. for(unsigned long i=0;i<bind.size();++i) {
  747. const std::string ips(OSUtils::jsonString(bind[i],""));
  748. if (ips.length() > 0) {
  749. InetAddress ip(ips.c_str());
  750. if ((ip.ss_family == AF_INET)||(ip.ss_family == AF_INET6))
  751. _explicitBind.push_back(ip);
  752. }
  753. }
  754. }
  755. }
  756. // Set trusted paths if there are any
  757. if (ppc.size() > 0) {
  758. for(std::map<InetAddress,ZT_PhysicalPathConfiguration>::iterator i(ppc.begin());i!=ppc.end();++i)
  759. _node->setPhysicalPathConfiguration(reinterpret_cast<const struct sockaddr_storage *>(&(i->first)),&(i->second));
  760. }
  761. }
  762. virtual ReasonForTermination reasonForTermination() const
  763. {
  764. Mutex::Lock _l(_termReason_m);
  765. return _termReason;
  766. }
  767. virtual std::string fatalErrorMessage() const
  768. {
  769. Mutex::Lock _l(_termReason_m);
  770. return _fatalErrorMessage;
  771. }
  772. virtual std::string portDeviceName(uint64_t nwid) const
  773. {
  774. Mutex::Lock _l(_nets_m);
  775. std::map<uint64_t,NetworkState>::const_iterator n(_nets.find(nwid));
  776. if ((n != _nets.end())&&(n->second.tap))
  777. return n->second.tap->deviceName();
  778. else return std::string();
  779. }
  780. #ifdef ZT_SDK
  781. virtual std::string givenHomePath()
  782. {
  783. return _homePath;
  784. }
  785. void getRoutes(uint64_t nwid, void *routeArray, unsigned int *numRoutes)
  786. {
  787. Mutex::Lock _l(_nets_m);
  788. NetworkState &n = _nets[nwid];
  789. *numRoutes = *numRoutes < n.config.routeCount ? *numRoutes : n.config.routeCount;
  790. for(unsigned int i=0; i<*numRoutes; i++) {
  791. ZT_VirtualNetworkRoute *vnr = (ZT_VirtualNetworkRoute*)routeArray;
  792. memcpy(&vnr[i], &(n.config.routes[i]), sizeof(ZT_VirtualNetworkRoute));
  793. }
  794. }
  795. virtual Node *getNode()
  796. {
  797. return _node;
  798. }
  799. #endif // ZT_SDK
  800. virtual void terminate()
  801. {
  802. _run_m.lock();
  803. _run = false;
  804. _run_m.unlock();
  805. _phy.whack();
  806. }
  807. virtual bool getNetworkSettings(const uint64_t nwid,NetworkSettings &settings) const
  808. {
  809. Mutex::Lock _l(_nets_m);
  810. std::map<uint64_t,NetworkState>::const_iterator n(_nets.find(nwid));
  811. if (n == _nets.end())
  812. return false;
  813. settings = n->second.settings;
  814. return true;
  815. }
  816. virtual bool setNetworkSettings(const uint64_t nwid,const NetworkSettings &settings)
  817. {
  818. Mutex::Lock _l(_nets_m);
  819. std::map<uint64_t,NetworkState>::iterator n(_nets.find(nwid));
  820. if (n == _nets.end())
  821. return false;
  822. n->second.settings = settings;
  823. char nlcpath[4096];
  824. OSUtils::ztsnprintf(nlcpath,sizeof(nlcpath),"%s" ZT_PATH_SEPARATOR_S "%.16llx.local.conf",_networksPath.c_str(),nwid);
  825. FILE *out = fopen(nlcpath,"w");
  826. if (out) {
  827. fprintf(out,"allowManaged=%d\n",(int)n->second.settings.allowManaged);
  828. fprintf(out,"allowGlobal=%d\n",(int)n->second.settings.allowGlobal);
  829. fprintf(out,"allowDefault=%d\n",(int)n->second.settings.allowDefault);
  830. fclose(out);
  831. }
  832. if (n->second.tap)
  833. syncManagedStuff(n->second,true,true);
  834. return true;
  835. }
  836. // =========================================================================
  837. // Internal implementation methods for control plane, route setup, etc.
  838. // =========================================================================
  839. inline unsigned int handleControlPlaneHttpRequest(
  840. const InetAddress &fromAddress,
  841. unsigned int httpMethod,
  842. const std::string &path,
  843. const std::map<std::string,std::string> &headers,
  844. const std::string &body,
  845. std::string &responseBody,
  846. std::string &responseContentType)
  847. {
  848. char tmp[256];
  849. unsigned int scode = 404;
  850. json res;
  851. std::vector<std::string> ps(OSUtils::split(path.c_str(),"/","",""));
  852. std::map<std::string,std::string> urlArgs;
  853. /* Note: this is kind of restricted in what it'll take. It does not support
  854. * URL encoding, and /'s in URL args will screw it up. But the only URL args
  855. * it really uses in ?jsonp=funcionName, and otherwise it just takes simple
  856. * paths to simply-named resources. */
  857. if (ps.size() > 0) {
  858. std::size_t qpos = ps[ps.size() - 1].find('?');
  859. if (qpos != std::string::npos) {
  860. std::string args(ps[ps.size() - 1].substr(qpos + 1));
  861. ps[ps.size() - 1] = ps[ps.size() - 1].substr(0,qpos);
  862. std::vector<std::string> asplit(OSUtils::split(args.c_str(),"&","",""));
  863. for(std::vector<std::string>::iterator a(asplit.begin());a!=asplit.end();++a) {
  864. std::size_t eqpos = a->find('=');
  865. if (eqpos == std::string::npos)
  866. urlArgs[*a] = "";
  867. else urlArgs[a->substr(0,eqpos)] = a->substr(eqpos + 1);
  868. }
  869. }
  870. } else {
  871. return 404;
  872. }
  873. bool isAuth = false;
  874. {
  875. std::map<std::string,std::string>::const_iterator ah(headers.find("x-zt1-auth"));
  876. if ((ah != headers.end())&&(_authToken == ah->second)) {
  877. isAuth = true;
  878. } else {
  879. ah = urlArgs.find("auth");
  880. if ((ah != urlArgs.end())&&(_authToken == ah->second))
  881. isAuth = true;
  882. }
  883. }
  884. #ifdef __SYNOLOGY__
  885. // Authenticate via Synology's built-in cgi script
  886. if (!isAuth) {
  887. int synotoken_pos = path.find("SynoToken");
  888. int argpos = path.find("?");
  889. if(synotoken_pos != std::string::npos && argpos != std::string::npos) {
  890. std::string cookie = path.substr(argpos+1, synotoken_pos-(argpos+1));
  891. std::string synotoken = path.substr(synotoken_pos);
  892. std::string cookie_val = cookie.substr(cookie.find("=")+1);
  893. std::string synotoken_val = synotoken.substr(synotoken.find("=")+1);
  894. // Set necessary env for auth script
  895. std::map<std::string,std::string>::const_iterator ah2(headers.find("x-forwarded-for"));
  896. setenv("HTTP_COOKIE", cookie_val.c_str(), true);
  897. setenv("HTTP_X_SYNO_TOKEN", synotoken_val.c_str(), true);
  898. setenv("REMOTE_ADDR", ah2->second.c_str(),true);
  899. char user[256], buf[1024];
  900. FILE *fp = NULL;
  901. bzero(user, 256);
  902. fp = popen("/usr/syno/synoman/webman/modules/authenticate.cgi", "r");
  903. if(!fp)
  904. isAuth = false;
  905. else {
  906. bzero(buf, sizeof(buf));
  907. fread(buf, 1024, 1, fp);
  908. if(strlen(buf) > 0) {
  909. snprintf(user, 256, "%s", buf);
  910. isAuth = true;
  911. }
  912. }
  913. pclose(fp);
  914. }
  915. }
  916. #endif
  917. if (httpMethod == HTTP_GET) {
  918. if (isAuth) {
  919. if (ps[0] == "status") {
  920. ZT_NodeStatus status;
  921. _node->status(&status);
  922. OSUtils::ztsnprintf(tmp,sizeof(tmp),"%.10llx",status.address);
  923. res["address"] = tmp;
  924. res["publicIdentity"] = status.publicIdentity;
  925. res["online"] = (bool)(status.online != 0);
  926. res["versionMajor"] = ZEROTIER_ONE_VERSION_MAJOR;
  927. res["versionMinor"] = ZEROTIER_ONE_VERSION_MINOR;
  928. res["versionRev"] = ZEROTIER_ONE_VERSION_REVISION;
  929. res["versionBuild"] = ZEROTIER_ONE_VERSION_BUILD;
  930. OSUtils::ztsnprintf(tmp,sizeof(tmp),"%d.%d.%d",ZEROTIER_ONE_VERSION_MAJOR,ZEROTIER_ONE_VERSION_MINOR,ZEROTIER_ONE_VERSION_REVISION);
  931. res["version"] = tmp;
  932. res["clock"] = OSUtils::now();
  933. {
  934. Mutex::Lock _l(_localConfig_m);
  935. res["config"] = _localConfig;
  936. }
  937. json &settings = res["config"]["settings"];
  938. settings["primaryPort"] = OSUtils::jsonInt(settings["primaryPort"],(uint64_t)_primaryPort) & 0xffff;
  939. if (_multipathMode) {
  940. json &multipathConfig = res["multipath"];
  941. ZT_PeerList *pl = _node->peers();
  942. char peerAddrStr[256];
  943. if (pl) {
  944. for(unsigned long i=0;i<pl->peerCount;++i) {
  945. if (pl->peers[i].hadAggregateLink) {
  946. nlohmann::json pj;
  947. _peerAggregateLinkToJson(pj,&(pl->peers[i]));
  948. OSUtils::ztsnprintf(peerAddrStr,sizeof(peerAddrStr),"%.10llx",pl->peers[i].address);
  949. multipathConfig[peerAddrStr] = (pj);
  950. }
  951. }
  952. }
  953. }
  954. settings["portMappingEnabled"] = OSUtils::jsonBool(settings["portMappingEnabled"],true);
  955. scode = 200;
  956. } else if (ps[0] == "network") {
  957. ZT_VirtualNetworkList *nws = _node->networks();
  958. if (nws) {
  959. if (ps.size() == 1) {
  960. // Return [array] of all networks
  961. res = nlohmann::json::array();
  962. for(unsigned long i=0;i<nws->networkCount;++i) {
  963. OneService::NetworkSettings localSettings;
  964. getNetworkSettings(nws->networks[i].nwid,localSettings);
  965. nlohmann::json nj;
  966. _networkToJson(nj,&(nws->networks[i]),portDeviceName(nws->networks[i].nwid),localSettings);
  967. res.push_back(nj);
  968. }
  969. scode = 200;
  970. } else if (ps.size() == 2) {
  971. // Return a single network by ID or 404 if not found
  972. const uint64_t wantnw = Utils::hexStrToU64(ps[1].c_str());
  973. for(unsigned long i=0;i<nws->networkCount;++i) {
  974. if (nws->networks[i].nwid == wantnw) {
  975. OneService::NetworkSettings localSettings;
  976. getNetworkSettings(nws->networks[i].nwid,localSettings);
  977. _networkToJson(res,&(nws->networks[i]),portDeviceName(nws->networks[i].nwid),localSettings);
  978. scode = 200;
  979. break;
  980. }
  981. }
  982. } else scode = 404;
  983. _node->freeQueryResult((void *)nws);
  984. } else scode = 500;
  985. } else if (ps[0] == "peer") {
  986. ZT_PeerList *pl = _node->peers();
  987. if (pl) {
  988. if (ps.size() == 1) {
  989. // Return [array] of all peers
  990. res = nlohmann::json::array();
  991. for(unsigned long i=0;i<pl->peerCount;++i) {
  992. nlohmann::json pj;
  993. _peerToJson(pj,&(pl->peers[i]));
  994. res.push_back(pj);
  995. }
  996. scode = 200;
  997. } else if (ps.size() == 2) {
  998. // Return a single peer by ID or 404 if not found
  999. uint64_t wantp = Utils::hexStrToU64(ps[1].c_str());
  1000. for(unsigned long i=0;i<pl->peerCount;++i) {
  1001. if (pl->peers[i].address == wantp) {
  1002. _peerToJson(res,&(pl->peers[i]));
  1003. scode = 200;
  1004. break;
  1005. }
  1006. }
  1007. } else scode = 404;
  1008. _node->freeQueryResult((void *)pl);
  1009. } else scode = 500;
  1010. } else {
  1011. if (_controller) {
  1012. scode = _controller->handleControlPlaneHttpGET(std::vector<std::string>(ps.begin()+1,ps.end()),urlArgs,headers,body,responseBody,responseContentType);
  1013. } else scode = 404;
  1014. }
  1015. } else scode = 401; // isAuth == false
  1016. } else if ((httpMethod == HTTP_POST)||(httpMethod == HTTP_PUT)) {
  1017. if (isAuth) {
  1018. if (ps[0] == "network") {
  1019. if (ps.size() == 2) {
  1020. uint64_t wantnw = Utils::hexStrToU64(ps[1].c_str());
  1021. _node->join(wantnw,(void *)0,(void *)0); // does nothing if we are a member
  1022. ZT_VirtualNetworkList *nws = _node->networks();
  1023. if (nws) {
  1024. for(unsigned long i=0;i<nws->networkCount;++i) {
  1025. if (nws->networks[i].nwid == wantnw) {
  1026. OneService::NetworkSettings localSettings;
  1027. getNetworkSettings(nws->networks[i].nwid,localSettings);
  1028. try {
  1029. json j(OSUtils::jsonParse(body));
  1030. if (j.is_object()) {
  1031. json &allowManaged = j["allowManaged"];
  1032. if (allowManaged.is_boolean()) localSettings.allowManaged = (bool)allowManaged;
  1033. json &allowGlobal = j["allowGlobal"];
  1034. if (allowGlobal.is_boolean()) localSettings.allowGlobal = (bool)allowGlobal;
  1035. json &allowDefault = j["allowDefault"];
  1036. if (allowDefault.is_boolean()) localSettings.allowDefault = (bool)allowDefault;
  1037. }
  1038. } catch ( ... ) {
  1039. // discard invalid JSON
  1040. }
  1041. setNetworkSettings(nws->networks[i].nwid,localSettings);
  1042. _networkToJson(res,&(nws->networks[i]),portDeviceName(nws->networks[i].nwid),localSettings);
  1043. scode = 200;
  1044. break;
  1045. }
  1046. }
  1047. _node->freeQueryResult((void *)nws);
  1048. } else scode = 500;
  1049. } else scode = 404;
  1050. } else {
  1051. if (_controller)
  1052. scode = _controller->handleControlPlaneHttpPOST(std::vector<std::string>(ps.begin()+1,ps.end()),urlArgs,headers,body,responseBody,responseContentType);
  1053. else scode = 404;
  1054. }
  1055. } else scode = 401; // isAuth == false
  1056. } else if (httpMethod == HTTP_DELETE) {
  1057. if (isAuth) {
  1058. if (ps[0] == "network") {
  1059. ZT_VirtualNetworkList *nws = _node->networks();
  1060. if (nws) {
  1061. if (ps.size() == 2) {
  1062. uint64_t wantnw = Utils::hexStrToU64(ps[1].c_str());
  1063. for(unsigned long i=0;i<nws->networkCount;++i) {
  1064. if (nws->networks[i].nwid == wantnw) {
  1065. _node->leave(wantnw,(void **)0,(void *)0);
  1066. res["result"] = true;
  1067. scode = 200;
  1068. break;
  1069. }
  1070. }
  1071. } // else 404
  1072. _node->freeQueryResult((void *)nws);
  1073. } else scode = 500;
  1074. } else {
  1075. if (_controller)
  1076. scode = _controller->handleControlPlaneHttpDELETE(std::vector<std::string>(ps.begin()+1,ps.end()),urlArgs,headers,body,responseBody,responseContentType);
  1077. else scode = 404;
  1078. }
  1079. } else scode = 401; // isAuth = false
  1080. } else {
  1081. scode = 400;
  1082. }
  1083. if (responseBody.length() == 0) {
  1084. if ((res.is_object())||(res.is_array()))
  1085. responseBody = OSUtils::jsonDump(res);
  1086. else responseBody = "{}";
  1087. responseContentType = "application/json";
  1088. }
  1089. // Wrap result in jsonp function call if the user included a jsonp= url argument.
  1090. // Also double-check isAuth since forbidding this without auth feels safer.
  1091. std::map<std::string,std::string>::const_iterator jsonp(urlArgs.find("jsonp"));
  1092. if ((isAuth)&&(jsonp != urlArgs.end())&&(responseContentType == "application/json")) {
  1093. if (responseBody.length() > 0)
  1094. responseBody = jsonp->second + "(" + responseBody + ");";
  1095. else responseBody = jsonp->second + "(null);";
  1096. responseContentType = "application/javascript";
  1097. }
  1098. return scode;
  1099. }
  1100. // Must be called after _localConfig is read or modified
  1101. void applyLocalConfig()
  1102. {
  1103. Mutex::Lock _l(_localConfig_m);
  1104. json lc(_localConfig);
  1105. _v4Hints.clear();
  1106. _v6Hints.clear();
  1107. _v4Blacklists.clear();
  1108. _v6Blacklists.clear();
  1109. json &virt = lc["virtual"];
  1110. if (virt.is_object()) {
  1111. for(json::iterator v(virt.begin());v!=virt.end();++v) {
  1112. const std::string nstr = v.key();
  1113. if ((nstr.length() == ZT_ADDRESS_LENGTH_HEX)&&(v.value().is_object())) {
  1114. const Address ztaddr(Utils::hexStrToU64(nstr.c_str()));
  1115. if (ztaddr) {
  1116. const uint64_t ztaddr2 = ztaddr.toInt();
  1117. std::vector<InetAddress> &v4h = _v4Hints[ztaddr2];
  1118. std::vector<InetAddress> &v6h = _v6Hints[ztaddr2];
  1119. std::vector<InetAddress> &v4b = _v4Blacklists[ztaddr2];
  1120. std::vector<InetAddress> &v6b = _v6Blacklists[ztaddr2];
  1121. json &tryAddrs = v.value()["try"];
  1122. if (tryAddrs.is_array()) {
  1123. for(unsigned long i=0;i<tryAddrs.size();++i) {
  1124. const InetAddress ip(OSUtils::jsonString(tryAddrs[i],"").c_str());
  1125. if (ip.ss_family == AF_INET)
  1126. v4h.push_back(ip);
  1127. else if (ip.ss_family == AF_INET6)
  1128. v6h.push_back(ip);
  1129. }
  1130. }
  1131. json &blAddrs = v.value()["blacklist"];
  1132. if (blAddrs.is_array()) {
  1133. for(unsigned long i=0;i<blAddrs.size();++i) {
  1134. const InetAddress ip(OSUtils::jsonString(blAddrs[i],"").c_str());
  1135. if (ip.ss_family == AF_INET)
  1136. v4b.push_back(ip);
  1137. else if (ip.ss_family == AF_INET6)
  1138. v6b.push_back(ip);
  1139. }
  1140. }
  1141. if (v4h.empty()) _v4Hints.erase(ztaddr2);
  1142. if (v6h.empty()) _v6Hints.erase(ztaddr2);
  1143. if (v4b.empty()) _v4Blacklists.erase(ztaddr2);
  1144. if (v6b.empty()) _v6Blacklists.erase(ztaddr2);
  1145. }
  1146. }
  1147. }
  1148. }
  1149. _globalV4Blacklist.clear();
  1150. _globalV6Blacklist.clear();
  1151. json &physical = lc["physical"];
  1152. if (physical.is_object()) {
  1153. for(json::iterator phy(physical.begin());phy!=physical.end();++phy) {
  1154. const InetAddress net(OSUtils::jsonString(phy.key(),"").c_str());
  1155. if ((net)&&(net.netmaskBits() > 0)) {
  1156. if (phy.value().is_object()) {
  1157. if (OSUtils::jsonBool(phy.value()["blacklist"],false)) {
  1158. if (net.ss_family == AF_INET)
  1159. _globalV4Blacklist.push_back(net);
  1160. else if (net.ss_family == AF_INET6)
  1161. _globalV6Blacklist.push_back(net);
  1162. }
  1163. }
  1164. }
  1165. }
  1166. }
  1167. _allowManagementFrom.clear();
  1168. _interfacePrefixBlacklist.clear();
  1169. json &settings = lc["settings"];
  1170. _primaryPort = (unsigned int)OSUtils::jsonInt(settings["primaryPort"],(uint64_t)_primaryPort) & 0xffff;
  1171. _allowSecondaryPort = OSUtils::jsonBool(settings["allowSecondaryPort"],true);
  1172. _secondaryPort = (unsigned int)OSUtils::jsonInt(settings["secondaryPort"],0);
  1173. _tertiaryPort = (unsigned int)OSUtils::jsonInt(settings["tertiaryPort"],0);
  1174. if (_secondaryPort != 0 || _tertiaryPort != 0) {
  1175. fprintf(stderr,"WARNING: using manually-specified ports. This can cause NAT issues." ZT_EOL_S);
  1176. }
  1177. _multipathMode = (unsigned int)OSUtils::jsonInt(settings["multipathMode"],0);
  1178. _portMappingEnabled = OSUtils::jsonBool(settings["portMappingEnabled"],true);
  1179. json &ignoreIfs = settings["interfacePrefixBlacklist"];
  1180. if (ignoreIfs.is_array()) {
  1181. for(unsigned long i=0;i<ignoreIfs.size();++i) {
  1182. const std::string tmp(OSUtils::jsonString(ignoreIfs[i],""));
  1183. if (tmp.length() > 0)
  1184. _interfacePrefixBlacklist.push_back(tmp);
  1185. }
  1186. }
  1187. json &amf = settings["allowManagementFrom"];
  1188. if (amf.is_array()) {
  1189. for(unsigned long i=0;i<amf.size();++i) {
  1190. const InetAddress nw(OSUtils::jsonString(amf[i],"").c_str());
  1191. if (nw)
  1192. _allowManagementFrom.push_back(nw);
  1193. }
  1194. }
  1195. }
  1196. // Checks if a managed IP or route target is allowed
  1197. bool checkIfManagedIsAllowed(const NetworkState &n,const InetAddress &target)
  1198. {
  1199. if (!n.settings.allowManaged)
  1200. return false;
  1201. if (n.settings.allowManagedWhitelist.size() > 0) {
  1202. bool allowed = false;
  1203. for (InetAddress addr : n.settings.allowManagedWhitelist) {
  1204. if (addr.containsAddress(target) && addr.netmaskBits() <= target.netmaskBits()) {
  1205. allowed = true;
  1206. break;
  1207. }
  1208. }
  1209. if (!allowed) return false;
  1210. }
  1211. if (target.isDefaultRoute())
  1212. return n.settings.allowDefault;
  1213. switch(target.ipScope()) {
  1214. case InetAddress::IP_SCOPE_NONE:
  1215. case InetAddress::IP_SCOPE_MULTICAST:
  1216. case InetAddress::IP_SCOPE_LOOPBACK:
  1217. case InetAddress::IP_SCOPE_LINK_LOCAL:
  1218. return false;
  1219. case InetAddress::IP_SCOPE_GLOBAL:
  1220. return n.settings.allowGlobal;
  1221. default:
  1222. return true;
  1223. }
  1224. }
  1225. // Match only an IP from a vector of IPs -- used in syncManagedStuff()
  1226. bool matchIpOnly(const std::vector<InetAddress> &ips,const InetAddress &ip) const
  1227. {
  1228. for(std::vector<InetAddress>::const_iterator i(ips.begin());i!=ips.end();++i) {
  1229. if (i->ipsEqual(ip))
  1230. return true;
  1231. }
  1232. return false;
  1233. }
  1234. // Apply or update managed IPs for a configured network (be sure n.tap exists)
  1235. void syncManagedStuff(NetworkState &n,bool syncIps,bool syncRoutes)
  1236. {
  1237. char ipbuf[64];
  1238. // assumes _nets_m is locked
  1239. if (syncIps) {
  1240. std::vector<InetAddress> newManagedIps;
  1241. newManagedIps.reserve(n.config.assignedAddressCount);
  1242. for(unsigned int i=0;i<n.config.assignedAddressCount;++i) {
  1243. const InetAddress *ii = reinterpret_cast<const InetAddress *>(&(n.config.assignedAddresses[i]));
  1244. if (checkIfManagedIsAllowed(n,*ii))
  1245. newManagedIps.push_back(*ii);
  1246. }
  1247. std::sort(newManagedIps.begin(),newManagedIps.end());
  1248. newManagedIps.erase(std::unique(newManagedIps.begin(),newManagedIps.end()),newManagedIps.end());
  1249. for(std::vector<InetAddress>::iterator ip(n.managedIps.begin());ip!=n.managedIps.end();++ip) {
  1250. if (std::find(newManagedIps.begin(),newManagedIps.end(),*ip) == newManagedIps.end()) {
  1251. if (!n.tap->removeIp(*ip))
  1252. fprintf(stderr,"ERROR: unable to remove ip address %s" ZT_EOL_S, ip->toString(ipbuf));
  1253. }
  1254. }
  1255. #ifdef __SYNOLOGY__
  1256. if (!n.tap->addIps(newManagedIps)) {
  1257. fprintf(stderr,"ERROR: unable to add ip addresses to ifcfg" ZT_EOL_S);
  1258. }
  1259. #else
  1260. for(std::vector<InetAddress>::iterator ip(newManagedIps.begin());ip!=newManagedIps.end();++ip) {
  1261. if (std::find(n.managedIps.begin(),n.managedIps.end(),*ip) == n.managedIps.end()) {
  1262. if (!n.tap->addIp(*ip))
  1263. fprintf(stderr,"ERROR: unable to add ip address %s" ZT_EOL_S, ip->toString(ipbuf));
  1264. }
  1265. }
  1266. #endif
  1267. n.managedIps.swap(newManagedIps);
  1268. }
  1269. if (syncRoutes) {
  1270. char tapdev[64];
  1271. #if defined(__WINDOWS__) && !defined(ZT_SDK)
  1272. OSUtils::ztsnprintf(tapdev,sizeof(tapdev),"%.16llx",(unsigned long long)((WindowsEthernetTap *)(n.tap.get()))->luid().Value);
  1273. #else
  1274. Utils::scopy(tapdev,sizeof(tapdev),n.tap->deviceName().c_str());
  1275. #endif
  1276. std::vector<InetAddress> myIps(n.tap->ips());
  1277. // Nuke applied routes that are no longer in n.config.routes[] and/or are not allowed
  1278. for(std::list< SharedPtr<ManagedRoute> >::iterator mr(n.managedRoutes.begin());mr!=n.managedRoutes.end();) {
  1279. bool haveRoute = false;
  1280. if ( (checkIfManagedIsAllowed(n,(*mr)->target())) && (((*mr)->via().ss_family != (*mr)->target().ss_family)||(!matchIpOnly(myIps,(*mr)->via()))) ) {
  1281. for(unsigned int i=0;i<n.config.routeCount;++i) {
  1282. const InetAddress *const target = reinterpret_cast<const InetAddress *>(&(n.config.routes[i].target));
  1283. const InetAddress *const via = reinterpret_cast<const InetAddress *>(&(n.config.routes[i].via));
  1284. if ( ((*mr)->target() == *target) && ( ((via->ss_family == target->ss_family)&&((*mr)->via().ipsEqual(*via))) || (strcmp(tapdev,(*mr)->device())==0) ) ) {
  1285. haveRoute = true;
  1286. break;
  1287. }
  1288. }
  1289. }
  1290. if (haveRoute) {
  1291. ++mr;
  1292. } else {
  1293. n.managedRoutes.erase(mr++);
  1294. }
  1295. }
  1296. // Apply routes in n.config.routes[] that we haven't applied yet, and sync those we have in case shadow routes need to change
  1297. for(unsigned int i=0;i<n.config.routeCount;++i) {
  1298. const InetAddress *const target = reinterpret_cast<const InetAddress *>(&(n.config.routes[i].target));
  1299. const InetAddress *const via = reinterpret_cast<const InetAddress *>(&(n.config.routes[i].via));
  1300. const InetAddress *src = NULL;
  1301. for (unsigned int j=0; j<n.config.assignedAddressCount; ++j) {
  1302. const InetAddress *const tmp = reinterpret_cast<const InetAddress *>(&(n.config.assignedAddresses[j]));
  1303. if (target->isV4() && tmp->isV4()) {
  1304. src = reinterpret_cast<InetAddress *>(&(n.config.assignedAddresses[j]));
  1305. break;
  1306. } else if (target->isV6() && tmp->isV6()) {
  1307. src = reinterpret_cast<InetAddress *>(&(n.config.assignedAddresses[j]));
  1308. break;
  1309. }
  1310. }
  1311. if (!src)
  1312. src = &InetAddress::NIL;
  1313. if ( (!checkIfManagedIsAllowed(n,*target)) || ((via->ss_family == target->ss_family)&&(matchIpOnly(myIps,*via))) )
  1314. continue;
  1315. bool haveRoute = false;
  1316. // Ignore routes implied by local managed IPs since adding the IP adds the route
  1317. #ifndef __APPLE__
  1318. for(std::vector<InetAddress>::iterator ip(n.managedIps.begin());ip!=n.managedIps.end();++ip) {
  1319. if ((target->netmaskBits() == ip->netmaskBits())&&(target->containsAddress(*ip))) {
  1320. haveRoute = true;
  1321. break;
  1322. }
  1323. }
  1324. #endif
  1325. if (haveRoute)
  1326. continue;
  1327. #ifndef ZT_SDK
  1328. // If we've already applied this route, just sync it and continue
  1329. for(std::list< SharedPtr<ManagedRoute> >::iterator mr(n.managedRoutes.begin());mr!=n.managedRoutes.end();++mr) {
  1330. if ( ((*mr)->target() == *target) && ( ((via->ss_family == target->ss_family)&&((*mr)->via().ipsEqual(*via))) || (tapdev == (*mr)->device()) ) ) {
  1331. haveRoute = true;
  1332. (*mr)->sync();
  1333. break;
  1334. }
  1335. }
  1336. if (haveRoute)
  1337. continue;
  1338. // Add and apply new routes
  1339. n.managedRoutes.push_back(SharedPtr<ManagedRoute>(new ManagedRoute(*target,*via,*src,tapdev)));
  1340. if (!n.managedRoutes.back()->sync())
  1341. n.managedRoutes.pop_back();
  1342. #endif
  1343. }
  1344. }
  1345. }
  1346. // =========================================================================
  1347. // Handlers for Node and Phy<> callbacks
  1348. // =========================================================================
  1349. inline void phyOnDatagram(PhySocket *sock,void **uptr,const struct sockaddr *localAddr,const struct sockaddr *from,void *data,unsigned long len)
  1350. {
  1351. const uint64_t now = OSUtils::now();
  1352. if ((len >= 16)&&(reinterpret_cast<const InetAddress *>(from)->ipScope() == InetAddress::IP_SCOPE_GLOBAL))
  1353. _lastDirectReceiveFromGlobal = now;
  1354. const ZT_ResultCode rc = _node->processWirePacket(nullptr,now,reinterpret_cast<int64_t>(sock),reinterpret_cast<const struct sockaddr_storage *>(from),data,len,&_nextBackgroundTaskDeadline);
  1355. if (ZT_ResultCode_isFatal(rc)) {
  1356. char tmp[256];
  1357. OSUtils::ztsnprintf(tmp,sizeof(tmp),"fatal error code from processWirePacket: %d",(int)rc);
  1358. Mutex::Lock _l(_termReason_m);
  1359. _termReason = ONE_UNRECOVERABLE_ERROR;
  1360. _fatalErrorMessage = tmp;
  1361. this->terminate();
  1362. }
  1363. }
  1364. inline void phyOnTcpConnect(PhySocket *sock,void **uptr,bool success)
  1365. {
  1366. _phy.close(sock,true);
  1367. }
  1368. inline void phyOnTcpAccept(PhySocket *sockL,PhySocket *sockN,void **uptrL,void **uptrN,const struct sockaddr *from)
  1369. {
  1370. if (!from) {
  1371. _phy.close(sockN,false);
  1372. return;
  1373. } else {
  1374. #ifdef ZT_SDK
  1375. // Immediately close new local connections. The intention is to prevent the backplane from being accessed when operating as libzt
  1376. if (!allowHttpBackplaneManagement && ((InetAddress*)from)->ipScope() == InetAddress::IP_SCOPE_LOOPBACK) {
  1377. _phy.close(sockN,false);
  1378. return;
  1379. }
  1380. #endif
  1381. TcpConnection *tc = new TcpConnection();
  1382. {
  1383. Mutex::Lock _l(_tcpConnections_m);
  1384. _tcpConnections.push_back(tc);
  1385. }
  1386. tc->type = TcpConnection::TCP_UNCATEGORIZED_INCOMING;
  1387. tc->parent = this;
  1388. tc->sock = sockN;
  1389. tc->remoteAddr = from;
  1390. tc->lastReceive = OSUtils::now();
  1391. http_parser_init(&(tc->parser),HTTP_REQUEST);
  1392. tc->parser.data = (void *)tc;
  1393. tc->messageSize = 0;
  1394. *uptrN = (void *)tc;
  1395. }
  1396. }
  1397. void phyOnTcpClose(PhySocket *sock,void **uptr)
  1398. {
  1399. TcpConnection *tc = (TcpConnection *)*uptr;
  1400. if (tc) {
  1401. {
  1402. Mutex::Lock _l(_tcpConnections_m);
  1403. _tcpConnections.erase(std::remove(_tcpConnections.begin(),_tcpConnections.end(),tc),_tcpConnections.end());
  1404. }
  1405. delete tc;
  1406. }
  1407. }
  1408. void phyOnTcpData(PhySocket *sock,void **uptr,void *data,unsigned long len)
  1409. {
  1410. try {
  1411. if (!len) return; // sanity check, should never happen
  1412. TcpConnection *tc = reinterpret_cast<TcpConnection *>(*uptr);
  1413. tc->lastReceive = OSUtils::now();
  1414. switch(tc->type) {
  1415. case TcpConnection::TCP_UNCATEGORIZED_INCOMING:
  1416. switch(reinterpret_cast<uint8_t *>(data)[0]) {
  1417. // HTTP: GET, PUT, POST, HEAD, DELETE
  1418. case 'G':
  1419. case 'P':
  1420. case 'D':
  1421. case 'H': {
  1422. // This is only allowed from IPs permitted to access the management
  1423. // backplane, which is just 127.0.0.1/::1 unless otherwise configured.
  1424. bool allow;
  1425. {
  1426. Mutex::Lock _l(_localConfig_m);
  1427. if (_allowManagementFrom.size() == 0) {
  1428. allow = (tc->remoteAddr.ipScope() == InetAddress::IP_SCOPE_LOOPBACK);
  1429. } else {
  1430. allow = false;
  1431. for(std::vector<InetAddress>::const_iterator i(_allowManagementFrom.begin());i!=_allowManagementFrom.end();++i) {
  1432. if (i->containsAddress(tc->remoteAddr)) {
  1433. allow = true;
  1434. break;
  1435. }
  1436. }
  1437. }
  1438. }
  1439. if (allow) {
  1440. tc->type = TcpConnection::TCP_HTTP_INCOMING;
  1441. phyOnTcpData(sock,uptr,data,len);
  1442. } else {
  1443. _phy.close(sock);
  1444. }
  1445. } break;
  1446. // Drop unknown protocols
  1447. default:
  1448. _phy.close(sock);
  1449. break;
  1450. }
  1451. return;
  1452. case TcpConnection::TCP_HTTP_INCOMING:
  1453. http_parser_execute(&(tc->parser),&HTTP_PARSER_SETTINGS,(const char *)data,len);
  1454. if ((tc->parser.upgrade)||(tc->parser.http_errno != HPE_OK))
  1455. _phy.close(sock);
  1456. return;
  1457. }
  1458. } catch ( ... ) {
  1459. _phy.close(sock);
  1460. }
  1461. }
  1462. inline void phyOnTcpWritable(PhySocket *sock,void **uptr)
  1463. {
  1464. TcpConnection *tc = reinterpret_cast<TcpConnection *>(*uptr);
  1465. bool closeit = false;
  1466. {
  1467. Mutex::Lock _l(tc->writeq_m);
  1468. if (tc->writeq.length() > 0) {
  1469. long sent = (long)_phy.streamSend(sock,tc->writeq.data(),(unsigned long)tc->writeq.length(),true);
  1470. if (sent > 0) {
  1471. if ((unsigned long)sent >= (unsigned long)tc->writeq.length()) {
  1472. tc->writeq.clear();
  1473. _phy.setNotifyWritable(sock,false);
  1474. if (tc->type == TcpConnection::TCP_HTTP_INCOMING)
  1475. closeit = true; // HTTP keep alive not supported
  1476. } else {
  1477. tc->writeq.erase(tc->writeq.begin(),tc->writeq.begin() + sent);
  1478. }
  1479. }
  1480. } else {
  1481. _phy.setNotifyWritable(sock,false);
  1482. }
  1483. }
  1484. if (closeit)
  1485. _phy.close(sock);
  1486. }
  1487. inline void phyOnFileDescriptorActivity(PhySocket *sock,void **uptr,bool readable,bool writable) {}
  1488. inline void phyOnUnixAccept(PhySocket *sockL,PhySocket *sockN,void **uptrL,void **uptrN) {}
  1489. inline void phyOnUnixClose(PhySocket *sock,void **uptr) {}
  1490. inline void phyOnUnixData(PhySocket *sock,void **uptr,void *data,unsigned long len) {}
  1491. inline void phyOnUnixWritable(PhySocket *sock,void **uptr) {}
  1492. inline int nodeVirtualNetworkConfigFunction(uint64_t nwid,void **nuptr,enum ZT_VirtualNetworkConfigOperation op,const ZT_VirtualNetworkConfig *nwc)
  1493. {
  1494. Mutex::Lock _l(_nets_m);
  1495. NetworkState &n = _nets[nwid];
  1496. switch(op) {
  1497. case ZT_VIRTUAL_NETWORK_CONFIG_OPERATION_UP:
  1498. if (!n.tap) {
  1499. try {
  1500. char friendlyName[128];
  1501. OSUtils::ztsnprintf(friendlyName,sizeof(friendlyName),"ZeroTier One [%.16llx]",nwid);
  1502. n.tap = EthernetTap::newInstance(
  1503. nullptr,
  1504. _homePath.c_str(),
  1505. MAC(nwc->mac),
  1506. nwc->mtu,
  1507. (unsigned int)ZT_IF_METRIC,
  1508. nwid,
  1509. friendlyName,
  1510. StapFrameHandler,
  1511. (void *)this);
  1512. *nuptr = (void *)&n;
  1513. char nlcpath[256];
  1514. OSUtils::ztsnprintf(nlcpath,sizeof(nlcpath),"%s" ZT_PATH_SEPARATOR_S "networks.d" ZT_PATH_SEPARATOR_S "%.16llx.local.conf",_homePath.c_str(),nwid);
  1515. std::string nlcbuf;
  1516. if (OSUtils::readFile(nlcpath,nlcbuf)) {
  1517. Dictionary<4096> nc;
  1518. nc.load(nlcbuf.c_str());
  1519. Buffer<1024> allowManaged;
  1520. if (nc.get("allowManaged", allowManaged) && allowManaged.size() != 0) {
  1521. std::string addresses (allowManaged.begin(), allowManaged.size());
  1522. if (allowManaged.size() <= 5) { // untidy parsing for backward compatibility
  1523. if (allowManaged[0] == '1' || allowManaged[0] == 't' || allowManaged[0] == 'T') {
  1524. n.settings.allowManaged = true;
  1525. } else {
  1526. n.settings.allowManaged = false;
  1527. }
  1528. } else {
  1529. // this should be a list of IP addresses
  1530. n.settings.allowManaged = true;
  1531. size_t pos = 0;
  1532. while (true) {
  1533. size_t nextPos = addresses.find(',', pos);
  1534. std::string address = addresses.substr(pos, (nextPos == std::string::npos ? addresses.size() : nextPos) - pos);
  1535. n.settings.allowManagedWhitelist.push_back(InetAddress(address.c_str()));
  1536. if (nextPos == std::string::npos) break;
  1537. pos = nextPos + 1;
  1538. }
  1539. }
  1540. } else {
  1541. n.settings.allowManaged = true;
  1542. }
  1543. n.settings.allowGlobal = nc.getB("allowGlobal", false);
  1544. n.settings.allowDefault = nc.getB("allowDefault", false);
  1545. }
  1546. } catch (std::exception &exc) {
  1547. #ifdef __WINDOWS__
  1548. FILE *tapFailLog = fopen((_homePath + ZT_PATH_SEPARATOR_S"port_error_log.txt").c_str(),"a");
  1549. if (tapFailLog) {
  1550. fprintf(tapFailLog,"%.16llx: %s" ZT_EOL_S,(unsigned long long)nwid,exc.what());
  1551. fclose(tapFailLog);
  1552. }
  1553. #else
  1554. fprintf(stderr,"ERROR: unable to configure virtual network port: %s" ZT_EOL_S,exc.what());
  1555. #endif
  1556. _nets.erase(nwid);
  1557. return -999;
  1558. } catch ( ... ) {
  1559. return -999; // tap init failed
  1560. }
  1561. }
  1562. // After setting up tap, fall through to CONFIG_UPDATE since we also want to do this...
  1563. case ZT_VIRTUAL_NETWORK_CONFIG_OPERATION_CONFIG_UPDATE:
  1564. memcpy(&(n.config),nwc,sizeof(ZT_VirtualNetworkConfig));
  1565. if (n.tap) { // sanity check
  1566. #if defined(__WINDOWS__) && !defined(ZT_SDK)
  1567. // wait for up to 5 seconds for the WindowsEthernetTap to actually be initialized
  1568. //
  1569. // without WindowsEthernetTap::isInitialized() returning true, the won't actually
  1570. // be online yet and setting managed routes on it will fail.
  1571. const int MAX_SLEEP_COUNT = 500;
  1572. for (int i = 0; !((WindowsEthernetTap *)(n.tap.get()))->isInitialized() && i < MAX_SLEEP_COUNT; i++) {
  1573. Sleep(10);
  1574. }
  1575. #endif
  1576. syncManagedStuff(n,true,true);
  1577. n.tap->setMtu(nwc->mtu);
  1578. } else {
  1579. _nets.erase(nwid);
  1580. return -999; // tap init failed
  1581. }
  1582. break;
  1583. case ZT_VIRTUAL_NETWORK_CONFIG_OPERATION_DOWN:
  1584. case ZT_VIRTUAL_NETWORK_CONFIG_OPERATION_DESTROY:
  1585. if (n.tap) { // sanity check
  1586. #if defined(__WINDOWS__) && !defined(ZT_SDK)
  1587. std::string winInstanceId(((WindowsEthernetTap *)(n.tap.get()))->instanceId());
  1588. #endif
  1589. *nuptr = (void *)0;
  1590. n.tap.reset();
  1591. _nets.erase(nwid);
  1592. #if defined(__WINDOWS__) && !defined(ZT_SDK)
  1593. if ((op == ZT_VIRTUAL_NETWORK_CONFIG_OPERATION_DESTROY)&&(winInstanceId.length() > 0))
  1594. WindowsEthernetTap::deletePersistentTapDevice(winInstanceId.c_str());
  1595. #endif
  1596. if (op == ZT_VIRTUAL_NETWORK_CONFIG_OPERATION_DESTROY) {
  1597. char nlcpath[256];
  1598. OSUtils::ztsnprintf(nlcpath,sizeof(nlcpath),"%s" ZT_PATH_SEPARATOR_S "networks.d" ZT_PATH_SEPARATOR_S "%.16llx.local.conf",_homePath.c_str(),nwid);
  1599. OSUtils::rm(nlcpath);
  1600. }
  1601. } else {
  1602. _nets.erase(nwid);
  1603. }
  1604. break;
  1605. }
  1606. return 0;
  1607. }
  1608. inline void nodeEventCallback(enum ZT_Event event,const void *metaData)
  1609. {
  1610. switch(event) {
  1611. case ZT_EVENT_TRACE: {
  1612. if (metaData) {
  1613. ::fprintf(stderr,"%s" ZT_EOL_S,(const char *)metaData);
  1614. ::fflush(stderr);
  1615. }
  1616. } break;
  1617. case ZT_EVENT_REMOTE_TRACE: {
  1618. // TODO
  1619. }
  1620. default:
  1621. break;
  1622. }
  1623. }
  1624. inline void nodeStatePutFunction(enum ZT_StateObjectType type,const uint64_t id[2],const void *data,int len)
  1625. {
  1626. char p[1024];
  1627. FILE *f;
  1628. bool secure = false;
  1629. char dirname[1024];
  1630. dirname[0] = 0;
  1631. switch(type) {
  1632. case ZT_STATE_OBJECT_IDENTITY_PUBLIC:
  1633. OSUtils::ztsnprintf(p,sizeof(p),"%s" ZT_PATH_SEPARATOR_S "identity.public",_homePath.c_str());
  1634. break;
  1635. case ZT_STATE_OBJECT_IDENTITY_SECRET:
  1636. OSUtils::ztsnprintf(p,sizeof(p),"%s" ZT_PATH_SEPARATOR_S "identity.secret",_homePath.c_str());
  1637. secure = true;
  1638. break;
  1639. case ZT_STATE_OBJECT_NETWORK_CONFIG:
  1640. OSUtils::ztsnprintf(dirname,sizeof(dirname),"%s" ZT_PATH_SEPARATOR_S "networks.d",_homePath.c_str());
  1641. OSUtils::ztsnprintf(p,sizeof(p),"%s" ZT_PATH_SEPARATOR_S "%.16llx.conf",dirname,(unsigned long long)id[0]);
  1642. secure = true;
  1643. break;
  1644. case ZT_STATE_OBJECT_PEER:
  1645. OSUtils::ztsnprintf(dirname,sizeof(dirname),"%s" ZT_PATH_SEPARATOR_S "peers.d",_homePath.c_str());
  1646. OSUtils::ztsnprintf(p,sizeof(p),"%s" ZT_PATH_SEPARATOR_S "%.10llx.peer",dirname,(unsigned long long)id[0]);
  1647. break;
  1648. default:
  1649. return;
  1650. }
  1651. if ((len >= 0)&&(data)) {
  1652. // Check to see if we've already written this first. This reduces
  1653. // redundant writes and I/O overhead on most platforms and has
  1654. // little effect on others.
  1655. f = fopen(p,"rb");
  1656. if (f) {
  1657. char *const buf = (char *)malloc(len*4);
  1658. if (buf) {
  1659. long l = (long)fread(buf,1,(size_t)(len*4),f);
  1660. fclose(f);
  1661. if ((l == (long)len)&&(memcmp(data,buf,l) == 0)) {
  1662. free(buf);
  1663. return;
  1664. }
  1665. free(buf);
  1666. }
  1667. }
  1668. f = fopen(p,"wb");
  1669. if ((!f)&&(dirname[0])) { // create subdirectory if it does not exist
  1670. OSUtils::mkdir(dirname);
  1671. f = fopen(p,"wb");
  1672. }
  1673. if (f) {
  1674. if (fwrite(data,len,1,f) != 1)
  1675. fprintf(stderr,"WARNING: unable to write to file: %s (I/O error)" ZT_EOL_S,p);
  1676. fclose(f);
  1677. if (secure)
  1678. OSUtils::lockDownFile(p,false);
  1679. } else {
  1680. fprintf(stderr,"WARNING: unable to write to file: %s (unable to open)" ZT_EOL_S,p);
  1681. }
  1682. } else {
  1683. OSUtils::rm(p);
  1684. }
  1685. }
  1686. inline int nodeStateGetFunction(enum ZT_StateObjectType type,const uint64_t id[2],void *data,unsigned int maxlen)
  1687. {
  1688. char p[4096];
  1689. switch(type) {
  1690. case ZT_STATE_OBJECT_IDENTITY_PUBLIC:
  1691. OSUtils::ztsnprintf(p,sizeof(p),"%s" ZT_PATH_SEPARATOR_S "identity.public",_homePath.c_str());
  1692. break;
  1693. case ZT_STATE_OBJECT_IDENTITY_SECRET:
  1694. OSUtils::ztsnprintf(p,sizeof(p),"%s" ZT_PATH_SEPARATOR_S "identity.secret",_homePath.c_str());
  1695. break;
  1696. case ZT_STATE_OBJECT_NETWORK_CONFIG:
  1697. 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]);
  1698. break;
  1699. case ZT_STATE_OBJECT_PEER:
  1700. 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]);
  1701. break;
  1702. default:
  1703. return -1;
  1704. }
  1705. FILE *f = fopen(p,"rb");
  1706. if (f) {
  1707. int n = (int)fread(data,1,maxlen,f);
  1708. fclose(f);
  1709. if (n >= 0)
  1710. return n;
  1711. }
  1712. return -1;
  1713. }
  1714. inline int nodeWirePacketSendFunction(const int64_t localSocket,const struct sockaddr_storage *addr,const void *data,unsigned int len,unsigned int ttl)
  1715. {
  1716. if ((localSocket != -1)&&(localSocket != 0)&&(_binder.isUdpSocketValid((PhySocket *)((uintptr_t)localSocket)))) {
  1717. if ((ttl)&&(addr->ss_family == AF_INET)) _phy.setIp4UdpTtl((PhySocket *)((uintptr_t)localSocket),ttl);
  1718. const bool r = _phy.udpSend((PhySocket *)((uintptr_t)localSocket),(const struct sockaddr *)addr,data,len);
  1719. if ((ttl)&&(addr->ss_family == AF_INET)) _phy.setIp4UdpTtl((PhySocket *)((uintptr_t)localSocket),255);
  1720. return ((r) ? 0 : -1);
  1721. } else {
  1722. return ((_binder.udpSendAll(_phy,addr,data,len,ttl)) ? 0 : -1);
  1723. }
  1724. }
  1725. 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)
  1726. {
  1727. NetworkState *n = reinterpret_cast<NetworkState *>(*nuptr);
  1728. if ((!n)||(!n->tap))
  1729. return;
  1730. n->tap->put(MAC(sourceMac),MAC(destMac),etherType,data,len);
  1731. }
  1732. inline int nodePathCheckFunction(uint64_t ztaddr,const int64_t localSocket,const struct sockaddr_storage *remoteAddr)
  1733. {
  1734. // Make sure we're not trying to do ZeroTier-over-ZeroTier
  1735. {
  1736. Mutex::Lock _l(_nets_m);
  1737. for(std::map<uint64_t,NetworkState>::const_iterator n(_nets.begin());n!=_nets.end();++n) {
  1738. if (n->second.tap) {
  1739. std::vector<InetAddress> ips(n->second.tap->ips());
  1740. for(std::vector<InetAddress>::const_iterator i(ips.begin());i!=ips.end();++i) {
  1741. if (i->containsAddress(*(reinterpret_cast<const InetAddress *>(remoteAddr)))) {
  1742. return 0;
  1743. }
  1744. }
  1745. }
  1746. }
  1747. }
  1748. /* Note: I do not think we need to scan for overlap with managed routes
  1749. * because of the "route forking" and interface binding that we do. This
  1750. * ensures (we hope) that ZeroTier traffic will still take the physical
  1751. * path even if its managed routes override this for other traffic. Will
  1752. * revisit if we see recursion problems. */
  1753. // Check blacklists
  1754. const Hashtable< uint64_t,std::vector<InetAddress> > *blh = (const Hashtable< uint64_t,std::vector<InetAddress> > *)0;
  1755. const std::vector<InetAddress> *gbl = (const std::vector<InetAddress> *)0;
  1756. if (remoteAddr->ss_family == AF_INET) {
  1757. blh = &_v4Blacklists;
  1758. gbl = &_globalV4Blacklist;
  1759. } else if (remoteAddr->ss_family == AF_INET6) {
  1760. blh = &_v6Blacklists;
  1761. gbl = &_globalV6Blacklist;
  1762. }
  1763. if (blh) {
  1764. Mutex::Lock _l(_localConfig_m);
  1765. const std::vector<InetAddress> *l = blh->get(ztaddr);
  1766. if (l) {
  1767. for(std::vector<InetAddress>::const_iterator a(l->begin());a!=l->end();++a) {
  1768. if (a->containsAddress(*reinterpret_cast<const InetAddress *>(remoteAddr)))
  1769. return 0;
  1770. }
  1771. }
  1772. }
  1773. if (gbl) {
  1774. for(std::vector<InetAddress>::const_iterator a(gbl->begin());a!=gbl->end();++a) {
  1775. if (a->containsAddress(*reinterpret_cast<const InetAddress *>(remoteAddr)))
  1776. return 0;
  1777. }
  1778. }
  1779. return 1;
  1780. }
  1781. inline int nodePathLookupFunction(uint64_t ztaddr,int family,struct sockaddr_storage *result)
  1782. {
  1783. const Hashtable< uint64_t,std::vector<InetAddress> > *lh = (const Hashtable< uint64_t,std::vector<InetAddress> > *)0;
  1784. if (family < 0)
  1785. lh = (Utils::random() & 1) ? &_v4Hints : &_v6Hints;
  1786. else if (family == AF_INET)
  1787. lh = &_v4Hints;
  1788. else if (family == AF_INET6)
  1789. lh = &_v6Hints;
  1790. else return 0;
  1791. const std::vector<InetAddress> *l = lh->get(ztaddr);
  1792. if ((l)&&(l->size() > 0)) {
  1793. memcpy(result,&((*l)[(unsigned long)Utils::random() % l->size()]),sizeof(struct sockaddr_storage));
  1794. return 1;
  1795. } else return 0;
  1796. }
  1797. inline void tapFrameHandler(uint64_t nwid,const MAC &from,const MAC &to,unsigned int etherType,unsigned int vlanId,const void *data,unsigned int len)
  1798. {
  1799. _node->processVirtualNetworkFrame((void *)0,OSUtils::now(),nwid,from.toInt(),to.toInt(),etherType,vlanId,data,len,&_nextBackgroundTaskDeadline);
  1800. }
  1801. inline void onHttpRequestToServer(TcpConnection *tc)
  1802. {
  1803. char tmpn[4096];
  1804. std::string data;
  1805. std::string contentType("text/plain"); // default if not changed in handleRequest()
  1806. unsigned int scode = 404;
  1807. // Note that we check allowed IP ranges when HTTP connections are first detected in
  1808. // phyOnTcpData(). If we made it here the source IP is okay.
  1809. try {
  1810. scode = handleControlPlaneHttpRequest(tc->remoteAddr,tc->parser.method,tc->url,tc->headers,tc->readq,data,contentType);
  1811. } catch (std::exception &exc) {
  1812. fprintf(stderr,"WARNING: unexpected exception processing control HTTP request: %s" ZT_EOL_S,exc.what());
  1813. scode = 500;
  1814. } catch ( ... ) {
  1815. fprintf(stderr,"WARNING: unexpected exception processing control HTTP request: unknown exception" ZT_EOL_S);
  1816. scode = 500;
  1817. }
  1818. const char *scodestr;
  1819. switch(scode) {
  1820. case 200: scodestr = "OK"; break;
  1821. case 400: scodestr = "Bad Request"; break;
  1822. case 401: scodestr = "Unauthorized"; break;
  1823. case 403: scodestr = "Forbidden"; break;
  1824. case 404: scodestr = "Not Found"; break;
  1825. case 500: scodestr = "Internal Server Error"; break;
  1826. case 501: scodestr = "Not Implemented"; break;
  1827. case 503: scodestr = "Service Unavailable"; break;
  1828. default: scodestr = "Error"; break;
  1829. }
  1830. 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",
  1831. scode,
  1832. scodestr,
  1833. contentType.c_str(),
  1834. (unsigned long)data.length());
  1835. {
  1836. Mutex::Lock _l(tc->writeq_m);
  1837. tc->writeq = tmpn;
  1838. if (tc->parser.method != HTTP_HEAD)
  1839. tc->writeq.append(data);
  1840. }
  1841. _phy.setNotifyWritable(tc->sock,true);
  1842. }
  1843. inline void onHttpResponseFromClient(TcpConnection *tc)
  1844. {
  1845. _phy.close(tc->sock);
  1846. }
  1847. bool shouldBindInterface(const char *ifname,const InetAddress &ifaddr)
  1848. {
  1849. #if defined(__linux__) || defined(linux) || defined(__LINUX__) || defined(__linux)
  1850. if ((ifname[0] == 'l')&&(ifname[1] == 'o')) return false; // loopback
  1851. if ((ifname[0] == 'z')&&(ifname[1] == 't')) return false; // sanity check: zt#
  1852. if ((ifname[0] == 't')&&(ifname[1] == 'u')&&(ifname[2] == 'n')) return false; // tun# is probably an OpenVPN tunnel or similar
  1853. if ((ifname[0] == 't')&&(ifname[1] == 'a')&&(ifname[2] == 'p')) return false; // tap# is probably an OpenVPN tunnel or similar
  1854. #endif
  1855. #ifdef __APPLE__
  1856. if ((ifname[0] == 'f')&&(ifname[1] == 'e')&&(ifname[2] == 't')&&(ifname[3] == 'h')) return false; // ... as is feth#
  1857. if ((ifname[0] == 'l')&&(ifname[1] == 'o')) return false; // loopback
  1858. if ((ifname[0] == 'z')&&(ifname[1] == 't')) return false; // sanity check: zt#
  1859. if ((ifname[0] == 't')&&(ifname[1] == 'u')&&(ifname[2] == 'n')) return false; // tun# is probably an OpenVPN tunnel or similar
  1860. if ((ifname[0] == 't')&&(ifname[1] == 'a')&&(ifname[2] == 'p')) return false; // tap# is probably an OpenVPN tunnel or similar
  1861. if ((ifname[0] == 'u')&&(ifname[1] == 't')&&(ifname[2] == 'u')&&(ifname[3] == 'n')) return false; // ... as is utun#
  1862. #endif
  1863. {
  1864. Mutex::Lock _l(_localConfig_m);
  1865. for(std::vector<std::string>::const_iterator p(_interfacePrefixBlacklist.begin());p!=_interfacePrefixBlacklist.end();++p) {
  1866. if (!strncmp(p->c_str(),ifname,p->length()))
  1867. return false;
  1868. }
  1869. }
  1870. {
  1871. // Check global blacklists
  1872. const std::vector<InetAddress> *gbl = (const std::vector<InetAddress> *)0;
  1873. if (ifaddr.ss_family == AF_INET) {
  1874. gbl = &_globalV4Blacklist;
  1875. } else if (ifaddr.ss_family == AF_INET6) {
  1876. gbl = &_globalV6Blacklist;
  1877. }
  1878. if (gbl) {
  1879. Mutex::Lock _l(_localConfig_m);
  1880. for(std::vector<InetAddress>::const_iterator a(gbl->begin());a!=gbl->end();++a) {
  1881. if (a->containsAddress(ifaddr))
  1882. return false;
  1883. }
  1884. }
  1885. }
  1886. {
  1887. Mutex::Lock _l(_nets_m);
  1888. for(std::map<uint64_t,NetworkState>::const_iterator n(_nets.begin());n!=_nets.end();++n) {
  1889. if (n->second.tap) {
  1890. std::vector<InetAddress> ips(n->second.tap->ips());
  1891. for(std::vector<InetAddress>::const_iterator i(ips.begin());i!=ips.end();++i) {
  1892. if (i->ipsEqual(ifaddr))
  1893. return false;
  1894. }
  1895. }
  1896. }
  1897. }
  1898. return true;
  1899. }
  1900. bool _trialBind(unsigned int port)
  1901. {
  1902. struct sockaddr_in in4;
  1903. struct sockaddr_in6 in6;
  1904. PhySocket *tb;
  1905. memset(&in4,0,sizeof(in4));
  1906. in4.sin_family = AF_INET;
  1907. in4.sin_port = Utils::hton((uint16_t)port);
  1908. tb = _phy.udpBind(reinterpret_cast<const struct sockaddr *>(&in4),(void *)0,0);
  1909. if (tb) {
  1910. _phy.close(tb,false);
  1911. tb = _phy.tcpListen(reinterpret_cast<const struct sockaddr *>(&in4),(void *)0);
  1912. if (tb) {
  1913. _phy.close(tb,false);
  1914. return true;
  1915. }
  1916. }
  1917. memset(&in6,0,sizeof(in6));
  1918. in6.sin6_family = AF_INET6;
  1919. in6.sin6_port = Utils::hton((uint16_t)port);
  1920. tb = _phy.udpBind(reinterpret_cast<const struct sockaddr *>(&in6),(void *)0,0);
  1921. if (tb) {
  1922. _phy.close(tb,false);
  1923. tb = _phy.tcpListen(reinterpret_cast<const struct sockaddr *>(&in6),(void *)0);
  1924. if (tb) {
  1925. _phy.close(tb,false);
  1926. return true;
  1927. }
  1928. }
  1929. return false;
  1930. }
  1931. };
  1932. static int SnodeVirtualNetworkConfigFunction(ZT_Node *node,void *uptr,void *tptr,uint64_t nwid,void **nuptr,enum ZT_VirtualNetworkConfigOperation op,const ZT_VirtualNetworkConfig *nwconf)
  1933. { return reinterpret_cast<OneServiceImpl *>(uptr)->nodeVirtualNetworkConfigFunction(nwid,nuptr,op,nwconf); }
  1934. static void SnodeEventCallback(ZT_Node *node,void *uptr,void *tptr,enum ZT_Event event,const void *metaData)
  1935. { reinterpret_cast<OneServiceImpl *>(uptr)->nodeEventCallback(event,metaData); }
  1936. static void SnodeStatePutFunction(ZT_Node *node,void *uptr,void *tptr,enum ZT_StateObjectType type,const uint64_t id[2],const void *data,int len)
  1937. { reinterpret_cast<OneServiceImpl *>(uptr)->nodeStatePutFunction(type,id,data,len); }
  1938. static int SnodeStateGetFunction(ZT_Node *node,void *uptr,void *tptr,enum ZT_StateObjectType type,const uint64_t id[2],void *data,unsigned int maxlen)
  1939. { return reinterpret_cast<OneServiceImpl *>(uptr)->nodeStateGetFunction(type,id,data,maxlen); }
  1940. 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)
  1941. { return reinterpret_cast<OneServiceImpl *>(uptr)->nodeWirePacketSendFunction(localSocket,addr,data,len,ttl); }
  1942. 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)
  1943. { reinterpret_cast<OneServiceImpl *>(uptr)->nodeVirtualNetworkFrameFunction(nwid,nuptr,sourceMac,destMac,etherType,vlanId,data,len); }
  1944. static int SnodePathCheckFunction(ZT_Node *node,void *uptr,void *tptr,uint64_t ztaddr,int64_t localSocket,const struct sockaddr_storage *remoteAddr)
  1945. { return reinterpret_cast<OneServiceImpl *>(uptr)->nodePathCheckFunction(ztaddr,localSocket,remoteAddr); }
  1946. static int SnodePathLookupFunction(ZT_Node *node,void *uptr,void *tptr,uint64_t ztaddr,int family,struct sockaddr_storage *result)
  1947. { return reinterpret_cast<OneServiceImpl *>(uptr)->nodePathLookupFunction(ztaddr,family,result); }
  1948. 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)
  1949. { reinterpret_cast<OneServiceImpl *>(uptr)->tapFrameHandler(nwid,from,to,etherType,vlanId,data,len); }
  1950. static int ShttpOnMessageBegin(http_parser *parser)
  1951. {
  1952. TcpConnection *tc = reinterpret_cast<TcpConnection *>(parser->data);
  1953. tc->currentHeaderField = "";
  1954. tc->currentHeaderValue = "";
  1955. tc->messageSize = 0;
  1956. tc->url.clear();
  1957. tc->status.clear();
  1958. tc->headers.clear();
  1959. tc->readq.clear();
  1960. return 0;
  1961. }
  1962. static int ShttpOnUrl(http_parser *parser,const char *ptr,size_t length)
  1963. {
  1964. TcpConnection *tc = reinterpret_cast<TcpConnection *>(parser->data);
  1965. tc->messageSize += (unsigned long)length;
  1966. if (tc->messageSize > ZT_MAX_HTTP_MESSAGE_SIZE)
  1967. return -1;
  1968. tc->url.append(ptr,length);
  1969. return 0;
  1970. }
  1971. #if (HTTP_PARSER_VERSION_MAJOR >= 2) && (HTTP_PARSER_VERSION_MINOR >= 2)
  1972. static int ShttpOnStatus(http_parser *parser,const char *ptr,size_t length)
  1973. #else
  1974. static int ShttpOnStatus(http_parser *parser)
  1975. #endif
  1976. { return 0; }
  1977. static int ShttpOnHeaderField(http_parser *parser,const char *ptr,size_t length)
  1978. {
  1979. TcpConnection *tc = reinterpret_cast<TcpConnection *>(parser->data);
  1980. tc->messageSize += (unsigned long)length;
  1981. if (tc->messageSize > ZT_MAX_HTTP_MESSAGE_SIZE)
  1982. return -1;
  1983. if ((tc->currentHeaderField.length())&&(tc->currentHeaderValue.length())) {
  1984. tc->headers[tc->currentHeaderField] = tc->currentHeaderValue;
  1985. tc->currentHeaderField = "";
  1986. tc->currentHeaderValue = "";
  1987. }
  1988. for(size_t i=0;i<length;++i)
  1989. tc->currentHeaderField.push_back(OSUtils::toLower(ptr[i]));
  1990. return 0;
  1991. }
  1992. static int ShttpOnValue(http_parser *parser,const char *ptr,size_t length)
  1993. {
  1994. TcpConnection *tc = reinterpret_cast<TcpConnection *>(parser->data);
  1995. tc->messageSize += (unsigned long)length;
  1996. if (tc->messageSize > ZT_MAX_HTTP_MESSAGE_SIZE)
  1997. return -1;
  1998. tc->currentHeaderValue.append(ptr,length);
  1999. return 0;
  2000. }
  2001. static int ShttpOnHeadersComplete(http_parser *parser)
  2002. {
  2003. TcpConnection *tc = reinterpret_cast<TcpConnection *>(parser->data);
  2004. if ((tc->currentHeaderField.length())&&(tc->currentHeaderValue.length()))
  2005. tc->headers[tc->currentHeaderField] = tc->currentHeaderValue;
  2006. return 0;
  2007. }
  2008. static int ShttpOnBody(http_parser *parser,const char *ptr,size_t length)
  2009. {
  2010. TcpConnection *tc = reinterpret_cast<TcpConnection *>(parser->data);
  2011. tc->messageSize += (unsigned long)length;
  2012. if (tc->messageSize > ZT_MAX_HTTP_MESSAGE_SIZE)
  2013. return -1;
  2014. tc->readq.append(ptr,length);
  2015. return 0;
  2016. }
  2017. static int ShttpOnMessageComplete(http_parser *parser)
  2018. {
  2019. TcpConnection *tc = reinterpret_cast<TcpConnection *>(parser->data);
  2020. if (tc->type == TcpConnection::TCP_HTTP_INCOMING) {
  2021. tc->parent->onHttpRequestToServer(tc);
  2022. } else {
  2023. tc->parent->onHttpResponseFromClient(tc);
  2024. }
  2025. return 0;
  2026. }
  2027. } // anonymous namespace
  2028. std::string OneService::platformDefaultHomePath()
  2029. {
  2030. return OSUtils::platformDefaultHomePath();
  2031. }
  2032. OneService *OneService::newInstance(const char *hp,unsigned int port) { return new OneServiceImpl(hp,port); }
  2033. OneService::~OneService() {}
  2034. } // namespace ZeroTier