OneService.cpp 80 KB

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