OneService.cpp 78 KB

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