OneService.cpp 79 KB

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