OneService.cpp 80 KB

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