OneService.cpp 81 KB

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