OneService.cpp 96 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826
  1. /*
  2. * ZeroTier One - Network Virtualization Everywhere
  3. * Copyright (C) 2011-2018 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 "../version.h"
  36. #include "../include/ZeroTierOne.h"
  37. #include "../node/Constants.hpp"
  38. #include "../node/Mutex.hpp"
  39. #include "../node/Node.hpp"
  40. #include "../node/Utils.hpp"
  41. #include "../node/InetAddress.hpp"
  42. #include "../node/MAC.hpp"
  43. #include "../node/Identity.hpp"
  44. #include "../node/World.hpp"
  45. #include "../node/Salsa20.hpp"
  46. #include "../node/Poly1305.hpp"
  47. #include "../node/SHA512.hpp"
  48. #include "../osdep/Phy.hpp"
  49. #include "../osdep/Thread.hpp"
  50. #include "../osdep/OSUtils.hpp"
  51. #include "../osdep/Http.hpp"
  52. #include "../osdep/PortMapper.hpp"
  53. #include "../osdep/Binder.hpp"
  54. #include "../osdep/ManagedRoute.hpp"
  55. #include "OneService.hpp"
  56. #include "SoftwareUpdater.hpp"
  57. #ifdef __WINDOWS__
  58. #include <WinSock2.h>
  59. #include <Windows.h>
  60. #include <ShlObj.h>
  61. #include <netioapi.h>
  62. #include <iphlpapi.h>
  63. #else
  64. #include <sys/types.h>
  65. #include <sys/socket.h>
  66. #include <sys/wait.h>
  67. #include <unistd.h>
  68. #include <ifaddrs.h>
  69. #endif
  70. #ifdef ZT_USE_SYSTEM_HTTP_PARSER
  71. #include <http_parser.h>
  72. #else
  73. #include "../ext/http-parser/http_parser.h"
  74. #endif
  75. #if ZT_VAULT_SUPPORT
  76. extern "C" {
  77. #include <curl/curl.h>
  78. }
  79. #endif
  80. #include "../ext/json/json.hpp"
  81. using json = nlohmann::json;
  82. #include "../controller/EmbeddedNetworkController.hpp"
  83. #ifdef ZT_USE_TEST_TAP
  84. #include "../osdep/TestEthernetTap.hpp"
  85. namespace ZeroTier { typedef TestEthernetTap EthernetTap; }
  86. #else
  87. #ifdef ZT_SDK
  88. #include "../controller/EmbeddedNetworkController.hpp"
  89. #include "../node/Node.hpp"
  90. // Use the virtual netcon endpoint instead of a tun/tap port driver
  91. #include "../include/VirtualTap.h"
  92. namespace ZeroTier { typedef VirtualTap EthernetTap; }
  93. #else
  94. #ifdef __APPLE__
  95. #include "../osdep/OSXEthernetTap.hpp"
  96. namespace ZeroTier { typedef OSXEthernetTap EthernetTap; }
  97. #endif // __APPLE__
  98. #ifdef __LINUX__
  99. #include "../osdep/LinuxEthernetTap.hpp"
  100. namespace ZeroTier { typedef LinuxEthernetTap EthernetTap; }
  101. #endif // __LINUX__
  102. #ifdef __WINDOWS__
  103. #include "../osdep/WindowsEthernetTap.hpp"
  104. namespace ZeroTier { typedef WindowsEthernetTap EthernetTap; }
  105. #endif // __WINDOWS__
  106. #ifdef __FreeBSD__
  107. #include "../osdep/BSDEthernetTap.hpp"
  108. namespace ZeroTier { typedef BSDEthernetTap EthernetTap; }
  109. #endif // __FreeBSD__
  110. #ifdef __OpenBSD__
  111. #include "../osdep/BSDEthernetTap.hpp"
  112. namespace ZeroTier { typedef BSDEthernetTap EthernetTap; }
  113. #endif // __OpenBSD__
  114. #endif // ZT_SERVICE_NETCON
  115. #endif // ZT_USE_TEST_TAP
  116. // Sanity limits for HTTP
  117. #define ZT_MAX_HTTP_MESSAGE_SIZE (1024 * 1024 * 64)
  118. #define ZT_MAX_HTTP_CONNECTIONS 65536
  119. // Interface metric for ZeroTier taps -- this ensures that if we are on WiFi and also
  120. // bridged via ZeroTier to the same LAN traffic will (if the OS is sane) prefer WiFi.
  121. #define ZT_IF_METRIC 5000
  122. // How often to check for new multicast subscriptions on a tap device
  123. #define ZT_TAP_CHECK_MULTICAST_INTERVAL 5000
  124. // TCP fallback relay (run by ZeroTier, Inc. -- this will eventually go away)
  125. #define ZT_TCP_FALLBACK_RELAY "204.80.128.1/443"
  126. // Frequency at which we re-resolve the TCP fallback relay
  127. #define ZT_TCP_FALLBACK_RERESOLVE_DELAY 86400000
  128. // Attempt to engage TCP fallback after this many ms of no reply to packets sent to global-scope IPs
  129. #define ZT_TCP_FALLBACK_AFTER 60000
  130. // How often to check for local interface addresses
  131. #define ZT_LOCAL_INTERFACE_CHECK_INTERVAL 60000
  132. // Maximum write buffer size for outgoing TCP connections (sanity limit)
  133. #define ZT_TCP_MAX_WRITEQ_SIZE 33554432
  134. // TCP activity timeout
  135. #define ZT_TCP_ACTIVITY_TIMEOUT 60000
  136. #if ZT_VAULT_SUPPORT
  137. size_t curlResponseWrite(void *ptr, size_t size, size_t nmemb, std::string *data)
  138. {
  139. data->append((char*)ptr, size * nmemb);
  140. return size * nmemb;
  141. }
  142. #endif
  143. namespace ZeroTier {
  144. namespace {
  145. // Fake TLS hello for TCP tunnel outgoing connections (TUNNELED mode)
  146. static const char ZT_TCP_TUNNEL_HELLO[9] = { 0x17,0x03,0x03,0x00,0x04,(char)ZEROTIER_ONE_VERSION_MAJOR,(char)ZEROTIER_ONE_VERSION_MINOR,(char)((ZEROTIER_ONE_VERSION_REVISION >> 8) & 0xff),(char)(ZEROTIER_ONE_VERSION_REVISION & 0xff) };
  147. static std::string _trimString(const std::string &s)
  148. {
  149. unsigned long end = (unsigned long)s.length();
  150. while (end) {
  151. char c = s[end - 1];
  152. if ((c == ' ')||(c == '\r')||(c == '\n')||(!c)||(c == '\t'))
  153. --end;
  154. else break;
  155. }
  156. unsigned long start = 0;
  157. while (start < end) {
  158. char c = s[start];
  159. if ((c == ' ')||(c == '\r')||(c == '\n')||(!c)||(c == '\t'))
  160. ++start;
  161. else break;
  162. }
  163. return s.substr(start,end - start);
  164. }
  165. static void _networkToJson(nlohmann::json &nj,const ZT_VirtualNetworkConfig *nc,const std::string &portDeviceName,const OneService::NetworkSettings &localSettings)
  166. {
  167. char tmp[256];
  168. const char *nstatus = "",*ntype = "";
  169. switch(nc->status) {
  170. case ZT_NETWORK_STATUS_REQUESTING_CONFIGURATION: nstatus = "REQUESTING_CONFIGURATION"; break;
  171. case ZT_NETWORK_STATUS_OK: nstatus = "OK"; break;
  172. case ZT_NETWORK_STATUS_ACCESS_DENIED: nstatus = "ACCESS_DENIED"; break;
  173. case ZT_NETWORK_STATUS_NOT_FOUND: nstatus = "NOT_FOUND"; break;
  174. case ZT_NETWORK_STATUS_PORT_ERROR: nstatus = "PORT_ERROR"; break;
  175. case ZT_NETWORK_STATUS_CLIENT_TOO_OLD: nstatus = "CLIENT_TOO_OLD"; break;
  176. }
  177. switch(nc->type) {
  178. case ZT_NETWORK_TYPE_PRIVATE: ntype = "PRIVATE"; break;
  179. case ZT_NETWORK_TYPE_PUBLIC: ntype = "PUBLIC"; break;
  180. }
  181. OSUtils::ztsnprintf(tmp,sizeof(tmp),"%.16llx",nc->nwid);
  182. nj["id"] = tmp;
  183. nj["nwid"] = tmp;
  184. 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));
  185. nj["mac"] = tmp;
  186. nj["name"] = nc->name;
  187. nj["status"] = nstatus;
  188. nj["type"] = ntype;
  189. nj["mtu"] = nc->mtu;
  190. nj["dhcp"] = (bool)(nc->dhcp != 0);
  191. nj["bridge"] = (bool)(nc->bridge != 0);
  192. nj["broadcastEnabled"] = (bool)(nc->broadcastEnabled != 0);
  193. nj["portError"] = nc->portError;
  194. nj["netconfRevision"] = nc->netconfRevision;
  195. nj["portDeviceName"] = portDeviceName;
  196. nj["allowManaged"] = localSettings.allowManaged;
  197. nj["allowGlobal"] = localSettings.allowGlobal;
  198. nj["allowDefault"] = localSettings.allowDefault;
  199. nlohmann::json aa = nlohmann::json::array();
  200. for(unsigned int i=0;i<nc->assignedAddressCount;++i) {
  201. aa.push_back(reinterpret_cast<const InetAddress *>(&(nc->assignedAddresses[i]))->toString(tmp));
  202. }
  203. nj["assignedAddresses"] = aa;
  204. nlohmann::json ra = nlohmann::json::array();
  205. for(unsigned int i=0;i<nc->routeCount;++i) {
  206. nlohmann::json rj;
  207. rj["target"] = reinterpret_cast<const InetAddress *>(&(nc->routes[i].target))->toString(tmp);
  208. if (nc->routes[i].via.ss_family == nc->routes[i].target.ss_family)
  209. rj["via"] = reinterpret_cast<const InetAddress *>(&(nc->routes[i].via))->toIpString(tmp);
  210. else rj["via"] = nlohmann::json();
  211. rj["flags"] = (int)nc->routes[i].flags;
  212. rj["metric"] = (int)nc->routes[i].metric;
  213. ra.push_back(rj);
  214. }
  215. nj["routes"] = ra;
  216. }
  217. static void _peerToJson(nlohmann::json &pj,const ZT_Peer *peer)
  218. {
  219. char tmp[256];
  220. const char *prole = "";
  221. switch(peer->role) {
  222. case ZT_PEER_ROLE_LEAF: prole = "LEAF"; break;
  223. case ZT_PEER_ROLE_MOON: prole = "MOON"; break;
  224. case ZT_PEER_ROLE_PLANET: prole = "PLANET"; break;
  225. }
  226. OSUtils::ztsnprintf(tmp,sizeof(tmp),"%.10llx",peer->address);
  227. pj["address"] = tmp;
  228. pj["versionMajor"] = peer->versionMajor;
  229. pj["versionMinor"] = peer->versionMinor;
  230. pj["versionRev"] = peer->versionRev;
  231. OSUtils::ztsnprintf(tmp,sizeof(tmp),"%d.%d.%d",peer->versionMajor,peer->versionMinor,peer->versionRev);
  232. pj["version"] = tmp;
  233. pj["latency"] = peer->latency;
  234. pj["role"] = prole;
  235. nlohmann::json pa = nlohmann::json::array();
  236. for(unsigned int i=0;i<peer->pathCount;++i) {
  237. int64_t lastSend = peer->paths[i].lastSend;
  238. int64_t lastReceive = peer->paths[i].lastReceive;
  239. nlohmann::json j;
  240. j["address"] = reinterpret_cast<const InetAddress *>(&(peer->paths[i].address))->toString(tmp);
  241. j["lastSend"] = (lastSend < 0) ? 0 : lastSend;
  242. j["lastReceive"] = (lastReceive < 0) ? 0 : lastReceive;
  243. j["trustedPathId"] = peer->paths[i].trustedPathId;
  244. j["active"] = (bool)(peer->paths[i].expired == 0);
  245. j["expired"] = (bool)(peer->paths[i].expired != 0);
  246. j["preferred"] = (bool)(peer->paths[i].preferred != 0);
  247. pa.push_back(j);
  248. }
  249. pj["paths"] = pa;
  250. }
  251. static void _moonToJson(nlohmann::json &mj,const World &world)
  252. {
  253. char tmp[4096];
  254. OSUtils::ztsnprintf(tmp,sizeof(tmp),"%.16llx",world.id());
  255. mj["id"] = tmp;
  256. mj["timestamp"] = world.timestamp();
  257. mj["signature"] = Utils::hex(world.signature().data,ZT_C25519_SIGNATURE_LEN,tmp);
  258. mj["updatesMustBeSignedBy"] = Utils::hex(world.updatesMustBeSignedBy().data,ZT_C25519_PUBLIC_KEY_LEN,tmp);
  259. nlohmann::json ra = nlohmann::json::array();
  260. for(std::vector<World::Root>::const_iterator r(world.roots().begin());r!=world.roots().end();++r) {
  261. nlohmann::json rj;
  262. rj["identity"] = r->identity.toString(false,tmp);
  263. nlohmann::json eps = nlohmann::json::array();
  264. for(std::vector<InetAddress>::const_iterator a(r->stableEndpoints.begin());a!=r->stableEndpoints.end();++a)
  265. eps.push_back(a->toString(tmp));
  266. rj["stableEndpoints"] = eps;
  267. ra.push_back(rj);
  268. }
  269. mj["roots"] = ra;
  270. mj["waiting"] = false;
  271. }
  272. class OneServiceImpl;
  273. static int SnodeVirtualNetworkConfigFunction(ZT_Node *node,void *uptr,void *tptr,uint64_t nwid,void **nuptr,enum ZT_VirtualNetworkConfigOperation op,const ZT_VirtualNetworkConfig *nwconf);
  274. static void SnodeEventCallback(ZT_Node *node,void *uptr,void *tptr,enum ZT_Event event,const void *metaData);
  275. static void SnodeStatePutFunction(ZT_Node *node,void *uptr,void *tptr,enum ZT_StateObjectType type,const uint64_t id[2],const void *data,int len);
  276. static int SnodeStateGetFunction(ZT_Node *node,void *uptr,void *tptr,enum ZT_StateObjectType type,const uint64_t id[2],void *data,unsigned int maxlen);
  277. 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);
  278. 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);
  279. static int SnodePathCheckFunction(ZT_Node *node,void *uptr,void *tptr,uint64_t ztaddr,int64_t localSocket,const struct sockaddr_storage *remoteAddr);
  280. static int SnodePathLookupFunction(ZT_Node *node,void *uptr,void *tptr,uint64_t ztaddr,int family,struct sockaddr_storage *result);
  281. 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);
  282. static int ShttpOnMessageBegin(http_parser *parser);
  283. static int ShttpOnUrl(http_parser *parser,const char *ptr,size_t length);
  284. #if (HTTP_PARSER_VERSION_MAJOR >= 2) && (HTTP_PARSER_VERSION_MINOR >= 2)
  285. static int ShttpOnStatus(http_parser *parser,const char *ptr,size_t length);
  286. #else
  287. static int ShttpOnStatus(http_parser *parser);
  288. #endif
  289. static int ShttpOnHeaderField(http_parser *parser,const char *ptr,size_t length);
  290. static int ShttpOnValue(http_parser *parser,const char *ptr,size_t length);
  291. static int ShttpOnHeadersComplete(http_parser *parser);
  292. static int ShttpOnBody(http_parser *parser,const char *ptr,size_t length);
  293. static int ShttpOnMessageComplete(http_parser *parser);
  294. #if (HTTP_PARSER_VERSION_MAJOR >= 2) && (HTTP_PARSER_VERSION_MINOR >= 1)
  295. static const struct http_parser_settings HTTP_PARSER_SETTINGS = {
  296. ShttpOnMessageBegin,
  297. ShttpOnUrl,
  298. ShttpOnStatus,
  299. ShttpOnHeaderField,
  300. ShttpOnValue,
  301. ShttpOnHeadersComplete,
  302. ShttpOnBody,
  303. ShttpOnMessageComplete
  304. };
  305. #else
  306. static const struct http_parser_settings HTTP_PARSER_SETTINGS = {
  307. ShttpOnMessageBegin,
  308. ShttpOnUrl,
  309. ShttpOnHeaderField,
  310. ShttpOnValue,
  311. ShttpOnHeadersComplete,
  312. ShttpOnBody,
  313. ShttpOnMessageComplete
  314. };
  315. #endif
  316. /**
  317. * A TCP connection and related state and buffers
  318. */
  319. struct TcpConnection
  320. {
  321. enum {
  322. TCP_UNCATEGORIZED_INCOMING, // uncategorized incoming connection
  323. TCP_HTTP_INCOMING,
  324. TCP_HTTP_OUTGOING,
  325. TCP_TUNNEL_OUTGOING // TUNNELED mode proxy outbound connection
  326. } type;
  327. OneServiceImpl *parent;
  328. PhySocket *sock;
  329. InetAddress remoteAddr;
  330. uint64_t lastReceive;
  331. // Used for inbound HTTP connections
  332. http_parser parser;
  333. unsigned long messageSize;
  334. std::string currentHeaderField;
  335. std::string currentHeaderValue;
  336. std::string url;
  337. std::string status;
  338. std::map< std::string,std::string > headers;
  339. std::string readq;
  340. std::string writeq;
  341. Mutex writeq_m;
  342. };
  343. class OneServiceImpl : public OneService
  344. {
  345. public:
  346. // begin member variables --------------------------------------------------
  347. const std::string _homePath;
  348. std::string _authToken;
  349. std::string _controllerDbPath;
  350. const std::string _networksPath;
  351. const std::string _moonsPath;
  352. EmbeddedNetworkController *_controller;
  353. Phy<OneServiceImpl *> _phy;
  354. Node *_node;
  355. SoftwareUpdater *_updater;
  356. PhySocket *_localControlSocket4;
  357. PhySocket *_localControlSocket6;
  358. bool _updateAutoApply;
  359. bool _allowTcpFallbackRelay;
  360. unsigned int _primaryPort;
  361. volatile unsigned int _udpPortPickerCounter;
  362. // Local configuration and memo-ized information from it
  363. json _localConfig;
  364. Hashtable< uint64_t,std::vector<InetAddress> > _v4Hints;
  365. Hashtable< uint64_t,std::vector<InetAddress> > _v6Hints;
  366. Hashtable< uint64_t,std::vector<InetAddress> > _v4Blacklists;
  367. Hashtable< uint64_t,std::vector<InetAddress> > _v6Blacklists;
  368. std::vector< InetAddress > _globalV4Blacklist;
  369. std::vector< InetAddress > _globalV6Blacklist;
  370. std::vector< InetAddress > _allowManagementFrom;
  371. std::vector< std::string > _interfacePrefixBlacklist;
  372. Mutex _localConfig_m;
  373. /*
  374. * To attempt to handle NAT/gateway craziness we use three local UDP ports:
  375. *
  376. * [0] is the normal/default port, usually 9993
  377. * [1] is a port dervied from our ZeroTier address
  378. * [2] is a port computed from the normal/default for use with uPnP/NAT-PMP mappings
  379. *
  380. * [2] exists because on some gateways trying to do regular NAT-t interferes
  381. * destructively with uPnP port mapping behavior in very weird buggy ways.
  382. * It's only used if uPnP/NAT-PMP is enabled in this build.
  383. */
  384. unsigned int _ports[3];
  385. Binder _binder;
  386. // Time we last received a packet from a global address
  387. uint64_t _lastDirectReceiveFromGlobal;
  388. #ifdef ZT_TCP_FALLBACK_RELAY
  389. uint64_t _lastSendToGlobalV4;
  390. #endif
  391. // Last potential sleep/wake event
  392. uint64_t _lastRestart;
  393. // Deadline for the next background task service function
  394. volatile int64_t _nextBackgroundTaskDeadline;
  395. // Configured networks
  396. struct NetworkState
  397. {
  398. NetworkState() :
  399. tap((EthernetTap *)0)
  400. {
  401. // Real defaults are in network 'up' code in network event handler
  402. settings.allowManaged = true;
  403. settings.allowGlobal = false;
  404. settings.allowDefault = false;
  405. }
  406. EthernetTap *tap;
  407. ZT_VirtualNetworkConfig config; // memcpy() of raw config from core
  408. std::vector<InetAddress> managedIps;
  409. std::list< SharedPtr<ManagedRoute> > managedRoutes;
  410. NetworkSettings settings;
  411. };
  412. std::map<uint64_t,NetworkState> _nets;
  413. Mutex _nets_m;
  414. // Active TCP/IP connections
  415. std::vector< TcpConnection * > _tcpConnections;
  416. Mutex _tcpConnections_m;
  417. TcpConnection *_tcpFallbackTunnel;
  418. // Termination status information
  419. ReasonForTermination _termReason;
  420. std::string _fatalErrorMessage;
  421. Mutex _termReason_m;
  422. // uPnP/NAT-PMP port mapper if enabled
  423. bool _portMappingEnabled; // local.conf settings
  424. #ifdef ZT_USE_MINIUPNPC
  425. PortMapper *_portMapper;
  426. #endif
  427. // HashiCorp Vault Settings
  428. #if ZT_VAULT_SUPPORT
  429. bool _vaultEnabled;
  430. std::string _vaultURL;
  431. std::string _vaultToken;
  432. std::string _vaultPath; // defaults to cubbyhole/zerotier/identity.secret for per-access key storage
  433. #endif
  434. // Set to false to force service to stop
  435. volatile bool _run;
  436. Mutex _run_m;
  437. // end member variables ----------------------------------------------------
  438. OneServiceImpl(const char *hp,unsigned int port) :
  439. _homePath((hp) ? hp : ".")
  440. ,_controllerDbPath(_homePath + ZT_PATH_SEPARATOR_S "controller.d")
  441. ,_networksPath(_homePath + ZT_PATH_SEPARATOR_S "networks.d")
  442. ,_moonsPath(_homePath + ZT_PATH_SEPARATOR_S "moons.d")
  443. ,_controller((EmbeddedNetworkController *)0)
  444. ,_phy(this,false,true)
  445. ,_node((Node *)0)
  446. ,_updater((SoftwareUpdater *)0)
  447. ,_localControlSocket4((PhySocket *)0)
  448. ,_localControlSocket6((PhySocket *)0)
  449. ,_updateAutoApply(false)
  450. ,_primaryPort(port)
  451. ,_udpPortPickerCounter(0)
  452. ,_lastDirectReceiveFromGlobal(0)
  453. #ifdef ZT_TCP_FALLBACK_RELAY
  454. ,_lastSendToGlobalV4(0)
  455. #endif
  456. ,_lastRestart(0)
  457. ,_nextBackgroundTaskDeadline(0)
  458. ,_tcpFallbackTunnel((TcpConnection *)0)
  459. ,_termReason(ONE_STILL_RUNNING)
  460. ,_portMappingEnabled(true)
  461. #ifdef ZT_USE_MINIUPNPC
  462. ,_portMapper((PortMapper *)0)
  463. #endif
  464. ,_vaultEnabled(false)
  465. ,_vaultURL()
  466. ,_vaultToken()
  467. ,_vaultPath("cubbyhole/zerotier")
  468. ,_run(true)
  469. {
  470. _ports[0] = 0;
  471. _ports[1] = 0;
  472. _ports[2] = 0;
  473. #if ZT_VAULT_SUPPORT
  474. curl_global_init(CURL_GLOBAL_DEFAULT);
  475. #endif
  476. }
  477. virtual ~OneServiceImpl()
  478. {
  479. _binder.closeAll(_phy);
  480. _phy.close(_localControlSocket4);
  481. _phy.close(_localControlSocket6);
  482. #ifdef ZT_USE_MINIUPNPC
  483. delete _portMapper;
  484. #endif
  485. delete _controller;
  486. }
  487. virtual ReasonForTermination run()
  488. {
  489. try {
  490. {
  491. const std::string authTokenPath(_homePath + ZT_PATH_SEPARATOR_S "authtoken.secret");
  492. if (!OSUtils::readFile(authTokenPath.c_str(),_authToken)) {
  493. unsigned char foo[24];
  494. Utils::getSecureRandom(foo,sizeof(foo));
  495. _authToken = "";
  496. for(unsigned int i=0;i<sizeof(foo);++i)
  497. _authToken.push_back("abcdefghijklmnopqrstuvwxyz0123456789"[(unsigned long)foo[i] % 36]);
  498. if (!OSUtils::writeFile(authTokenPath.c_str(),_authToken)) {
  499. Mutex::Lock _l(_termReason_m);
  500. _termReason = ONE_UNRECOVERABLE_ERROR;
  501. _fatalErrorMessage = "authtoken.secret could not be written";
  502. return _termReason;
  503. } else {
  504. OSUtils::lockDownFile(authTokenPath.c_str(),false);
  505. }
  506. }
  507. _authToken = _trimString(_authToken);
  508. }
  509. // Read local configuration
  510. std::vector<InetAddress> explicitBind;
  511. {
  512. std::map<InetAddress,ZT_PhysicalPathConfiguration> ppc;
  513. // LEGACY: support old "trustedpaths" flat file
  514. FILE *trustpaths = fopen((_homePath + ZT_PATH_SEPARATOR_S "trustedpaths").c_str(),"r");
  515. if (trustpaths) {
  516. fprintf(stderr,"WARNING: 'trustedpaths' flat file format is deprecated in favor of path definitions in local.conf" ZT_EOL_S);
  517. char buf[1024];
  518. while (fgets(buf,sizeof(buf),trustpaths)) {
  519. int fno = 0;
  520. char *saveptr = (char *)0;
  521. uint64_t trustedPathId = 0;
  522. InetAddress trustedPathNetwork;
  523. for(char *f=Utils::stok(buf,"=\r\n \t",&saveptr);(f);f=Utils::stok((char *)0,"=\r\n \t",&saveptr)) {
  524. if (fno == 0) {
  525. trustedPathId = Utils::hexStrToU64(f);
  526. } else if (fno == 1) {
  527. trustedPathNetwork = InetAddress(f);
  528. } else break;
  529. ++fno;
  530. }
  531. if ( (trustedPathId != 0) && ((trustedPathNetwork.ss_family == AF_INET)||(trustedPathNetwork.ss_family == AF_INET6)) && (trustedPathNetwork.netmaskBits() > 0) ) {
  532. ppc[trustedPathNetwork].trustedPathId = trustedPathId;
  533. ppc[trustedPathNetwork].mtu = 0; // use default
  534. }
  535. }
  536. fclose(trustpaths);
  537. }
  538. // Read local config file
  539. Mutex::Lock _l2(_localConfig_m);
  540. std::string lcbuf;
  541. if (OSUtils::readFile((_homePath + ZT_PATH_SEPARATOR_S "local.conf").c_str(),lcbuf)) {
  542. try {
  543. _localConfig = OSUtils::jsonParse(lcbuf);
  544. if (!_localConfig.is_object()) {
  545. fprintf(stderr,"WARNING: unable to parse local.conf (root element is not a JSON object)" ZT_EOL_S);
  546. }
  547. } catch ( ... ) {
  548. fprintf(stderr,"WARNING: unable to parse local.conf (invalid JSON)" ZT_EOL_S);
  549. }
  550. }
  551. // Get any trusted paths in local.conf (we'll parse the rest of physical[] elsewhere)
  552. json &physical = _localConfig["physical"];
  553. if (physical.is_object()) {
  554. for(json::iterator phy(physical.begin());phy!=physical.end();++phy) {
  555. InetAddress net(OSUtils::jsonString(phy.key(),"").c_str());
  556. if (net) {
  557. if (phy.value().is_object()) {
  558. uint64_t tpid;
  559. if ((tpid = OSUtils::jsonInt(phy.value()["trustedPathId"],0ULL)) != 0ULL) {
  560. if ((net.ss_family == AF_INET)||(net.ss_family == AF_INET6))
  561. ppc[net].trustedPathId = tpid;
  562. }
  563. ppc[net].mtu = (int)OSUtils::jsonInt(phy.value()["mtu"],0ULL); // 0 means use default
  564. }
  565. }
  566. }
  567. }
  568. json &settings = _localConfig["settings"];
  569. if (settings.is_object()) {
  570. // Allow controller DB path to be put somewhere else
  571. const std::string cdbp(OSUtils::jsonString(settings["controllerDbPath"],""));
  572. if (cdbp.length() > 0)
  573. _controllerDbPath = cdbp;
  574. // Bind to wildcard instead of to specific interfaces (disables full tunnel capability)
  575. json &bind = settings["bind"];
  576. if (bind.is_array()) {
  577. for(unsigned long i=0;i<bind.size();++i) {
  578. const std::string ips(OSUtils::jsonString(bind[i],""));
  579. if (ips.length() > 0) {
  580. InetAddress ip(ips.c_str());
  581. if ((ip.ss_family == AF_INET)||(ip.ss_family == AF_INET6))
  582. explicitBind.push_back(ip);
  583. }
  584. }
  585. }
  586. }
  587. // Set trusted paths if there are any
  588. if (ppc.size() > 0) {
  589. for(std::map<InetAddress,ZT_PhysicalPathConfiguration>::iterator i(ppc.begin());i!=ppc.end();++i)
  590. _node->setPhysicalPathConfiguration(reinterpret_cast<const struct sockaddr_storage *>(&(i->first)),&(i->second));
  591. }
  592. }
  593. // Apply other runtime configuration from local.conf
  594. applyLocalConfig();
  595. {
  596. struct ZT_Node_Callbacks cb;
  597. cb.version = 0;
  598. cb.stateGetFunction = SnodeStateGetFunction;
  599. cb.statePutFunction = SnodeStatePutFunction;
  600. cb.wirePacketSendFunction = SnodeWirePacketSendFunction;
  601. cb.virtualNetworkFrameFunction = SnodeVirtualNetworkFrameFunction;
  602. cb.virtualNetworkConfigFunction = SnodeVirtualNetworkConfigFunction;
  603. cb.eventCallback = SnodeEventCallback;
  604. cb.pathCheckFunction = SnodePathCheckFunction;
  605. cb.pathLookupFunction = SnodePathLookupFunction;
  606. _node = new Node(this, (void *)0, &cb, OSUtils::now());
  607. }
  608. // Make sure we can use the primary port, and hunt for one if configured to do so
  609. const int portTrials = (_primaryPort == 0) ? 256 : 1; // if port is 0, pick random
  610. for(int k=0;k<portTrials;++k) {
  611. if (_primaryPort == 0) {
  612. unsigned int randp = 0;
  613. Utils::getSecureRandom(&randp,sizeof(randp));
  614. _primaryPort = 20000 + (randp % 45500);
  615. }
  616. if (_trialBind(_primaryPort)) {
  617. _ports[0] = _primaryPort;
  618. } else {
  619. _primaryPort = 0;
  620. }
  621. }
  622. if (_ports[0] == 0) {
  623. Mutex::Lock _l(_termReason_m);
  624. _termReason = ONE_UNRECOVERABLE_ERROR;
  625. _fatalErrorMessage = "cannot bind to local control interface port";
  626. return _termReason;
  627. }
  628. // Bind TCP control socket to 127.0.0.1 and ::1 as well for loopback TCP control socket queries
  629. {
  630. struct sockaddr_in lo4;
  631. memset(&lo4,0,sizeof(lo4));
  632. lo4.sin_family = AF_INET;
  633. lo4.sin_addr.s_addr = Utils::hton((uint32_t)0x7f000001);
  634. lo4.sin_port = Utils::hton((uint16_t)_ports[0]);
  635. _localControlSocket4 = _phy.tcpListen((const struct sockaddr *)&lo4);
  636. struct sockaddr_in6 lo6;
  637. memset(&lo6,0,sizeof(lo6));
  638. lo6.sin6_family = AF_INET6;
  639. lo6.sin6_addr.s6_addr[15] = 1;
  640. lo6.sin6_port = lo4.sin_port;
  641. _localControlSocket6 = _phy.tcpListen((const struct sockaddr *)&lo6);
  642. }
  643. // Save primary port to a file so CLIs and GUIs can learn it easily
  644. char portstr[64];
  645. OSUtils::ztsnprintf(portstr,sizeof(portstr),"%u",_ports[0]);
  646. OSUtils::writeFile((_homePath + ZT_PATH_SEPARATOR_S "zerotier-one.port").c_str(),std::string(portstr));
  647. // Attempt to bind to a secondary port chosen from our ZeroTier address.
  648. // This exists because there are buggy NATs out there that fail if more
  649. // than one device behind the same NAT tries to use the same internal
  650. // private address port number. Buggy NATs are a running theme.
  651. _ports[1] = 20000 + ((unsigned int)_node->address() % 45500);
  652. for(int i=0;;++i) {
  653. if (i > 1000) {
  654. _ports[1] = 0;
  655. break;
  656. } else if (++_ports[1] >= 65536) {
  657. _ports[1] = 20000;
  658. }
  659. if (_trialBind(_ports[1]))
  660. break;
  661. }
  662. #ifdef ZT_USE_MINIUPNPC
  663. if (_portMappingEnabled) {
  664. // If we're running uPnP/NAT-PMP, bind a *third* port for that. We can't
  665. // use the other two ports for that because some NATs do really funky
  666. // stuff with ports that are explicitly mapped that breaks things.
  667. if (_ports[1]) {
  668. _ports[2] = _ports[1];
  669. for(int i=0;;++i) {
  670. if (i > 1000) {
  671. _ports[2] = 0;
  672. break;
  673. } else if (++_ports[2] >= 65536) {
  674. _ports[2] = 20000;
  675. }
  676. if (_trialBind(_ports[2]))
  677. break;
  678. }
  679. if (_ports[2]) {
  680. char uniqueName[64];
  681. OSUtils::ztsnprintf(uniqueName,sizeof(uniqueName),"ZeroTier/%.10llx@%u",_node->address(),_ports[2]);
  682. _portMapper = new PortMapper(_ports[2],uniqueName);
  683. }
  684. }
  685. }
  686. #endif
  687. // Delete legacy iddb.d if present (cleanup)
  688. OSUtils::rmDashRf((_homePath + ZT_PATH_SEPARATOR_S "iddb.d").c_str());
  689. // Network controller is now enabled by default for desktop and server
  690. _controller = new EmbeddedNetworkController(_node,_controllerDbPath.c_str());
  691. _node->setNetconfMaster((void *)_controller);
  692. // Join existing networks in networks.d
  693. {
  694. std::vector<std::string> networksDotD(OSUtils::listDirectory((_homePath + ZT_PATH_SEPARATOR_S "networks.d").c_str()));
  695. for(std::vector<std::string>::iterator f(networksDotD.begin());f!=networksDotD.end();++f) {
  696. std::size_t dot = f->find_last_of('.');
  697. if ((dot == 16)&&(f->substr(16) == ".conf"))
  698. _node->join(Utils::hexStrToU64(f->substr(0,dot).c_str()),(void *)0,(void *)0);
  699. }
  700. }
  701. // Orbit existing moons in moons.d
  702. {
  703. std::vector<std::string> moonsDotD(OSUtils::listDirectory((_homePath + ZT_PATH_SEPARATOR_S "moons.d").c_str()));
  704. for(std::vector<std::string>::iterator f(moonsDotD.begin());f!=moonsDotD.end();++f) {
  705. std::size_t dot = f->find_last_of('.');
  706. if ((dot == 16)&&(f->substr(16) == ".moon"))
  707. _node->orbit((void *)0,Utils::hexStrToU64(f->substr(0,dot).c_str()),0);
  708. }
  709. }
  710. // Main I/O loop
  711. _nextBackgroundTaskDeadline = 0;
  712. int64_t clockShouldBe = OSUtils::now();
  713. _lastRestart = clockShouldBe;
  714. int64_t lastTapMulticastGroupCheck = 0;
  715. int64_t lastBindRefresh = 0;
  716. int64_t lastUpdateCheck = clockShouldBe;
  717. int64_t lastCleanedPeersDb = 0;
  718. 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
  719. for(;;) {
  720. _run_m.lock();
  721. if (!_run) {
  722. _run_m.unlock();
  723. _termReason_m.lock();
  724. _termReason = ONE_NORMAL_TERMINATION;
  725. _termReason_m.unlock();
  726. break;
  727. } else {
  728. _run_m.unlock();
  729. }
  730. const int64_t now = OSUtils::now();
  731. // Attempt to detect sleep/wake events by detecting delay overruns
  732. bool restarted = false;
  733. if ((now > clockShouldBe)&&((now - clockShouldBe) > 10000)) {
  734. _lastRestart = now;
  735. restarted = true;
  736. }
  737. // Check for updates (if enabled)
  738. if ((_updater)&&((now - lastUpdateCheck) > 10000)) {
  739. lastUpdateCheck = now;
  740. if (_updater->check(now) && _updateAutoApply)
  741. _updater->apply();
  742. }
  743. // Refresh bindings in case device's interfaces have changed, and also sync routes to update any shadow routes (e.g. shadow default)
  744. if (((now - lastBindRefresh) >= ZT_BINDER_REFRESH_PERIOD)||(restarted)) {
  745. lastBindRefresh = now;
  746. unsigned int p[3];
  747. unsigned int pc = 0;
  748. for(int i=0;i<3;++i) {
  749. if (_ports[i])
  750. p[pc++] = _ports[i];
  751. }
  752. _binder.refresh(_phy,p,pc,explicitBind,*this);
  753. {
  754. Mutex::Lock _l(_nets_m);
  755. for(std::map<uint64_t,NetworkState>::iterator n(_nets.begin());n!=_nets.end();++n) {
  756. if (n->second.tap)
  757. syncManagedStuff(n->second,false,true);
  758. }
  759. }
  760. }
  761. // Run background task processor in core if it's time to do so
  762. int64_t dl = _nextBackgroundTaskDeadline;
  763. if (dl <= now) {
  764. _node->processBackgroundTasks((void *)0,now,&_nextBackgroundTaskDeadline);
  765. dl = _nextBackgroundTaskDeadline;
  766. }
  767. // Close TCP fallback tunnel if we have direct UDP
  768. if ((_tcpFallbackTunnel)&&((now - _lastDirectReceiveFromGlobal) < (ZT_TCP_FALLBACK_AFTER / 2)))
  769. _phy.close(_tcpFallbackTunnel->sock);
  770. // Sync multicast group memberships
  771. if ((now - lastTapMulticastGroupCheck) >= ZT_TAP_CHECK_MULTICAST_INTERVAL) {
  772. lastTapMulticastGroupCheck = now;
  773. std::vector< std::pair< uint64_t,std::pair< std::vector<MulticastGroup>,std::vector<MulticastGroup> > > > mgChanges;
  774. {
  775. Mutex::Lock _l(_nets_m);
  776. mgChanges.reserve(_nets.size() + 1);
  777. for(std::map<uint64_t,NetworkState>::const_iterator n(_nets.begin());n!=_nets.end();++n) {
  778. if (n->second.tap) {
  779. 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> >()));
  780. n->second.tap->scanMulticastGroups(mgChanges.back().second.first,mgChanges.back().second.second);
  781. }
  782. }
  783. }
  784. for(std::vector< std::pair< uint64_t,std::pair< std::vector<MulticastGroup>,std::vector<MulticastGroup> > > >::iterator c(mgChanges.begin());c!=mgChanges.end();++c) {
  785. for(std::vector<MulticastGroup>::iterator m(c->second.first.begin());m!=c->second.first.end();++m)
  786. _node->multicastSubscribe((void *)0,c->first,m->mac().toInt(),m->adi());
  787. for(std::vector<MulticastGroup>::iterator m(c->second.second.begin());m!=c->second.second.end();++m)
  788. _node->multicastUnsubscribe(c->first,m->mac().toInt(),m->adi());
  789. }
  790. }
  791. // Sync information about physical network interfaces
  792. if ((now - lastLocalInterfaceAddressCheck) >= ZT_LOCAL_INTERFACE_CHECK_INTERVAL) {
  793. lastLocalInterfaceAddressCheck = now;
  794. _node->clearLocalInterfaceAddresses();
  795. #ifdef ZT_USE_MINIUPNPC
  796. if (_portMapper) {
  797. std::vector<InetAddress> mappedAddresses(_portMapper->get());
  798. for(std::vector<InetAddress>::const_iterator ext(mappedAddresses.begin());ext!=mappedAddresses.end();++ext)
  799. _node->addLocalInterfaceAddress(reinterpret_cast<const struct sockaddr_storage *>(&(*ext)));
  800. }
  801. #endif
  802. std::vector<InetAddress> boundAddrs(_binder.allBoundLocalInterfaceAddresses());
  803. for(std::vector<InetAddress>::const_iterator i(boundAddrs.begin());i!=boundAddrs.end();++i)
  804. _node->addLocalInterfaceAddress(reinterpret_cast<const struct sockaddr_storage *>(&(*i)));
  805. }
  806. // Clean peers.d periodically
  807. if ((now - lastCleanedPeersDb) >= 3600000) {
  808. lastCleanedPeersDb = now;
  809. OSUtils::cleanDirectory((_homePath + ZT_PATH_SEPARATOR_S "peers.d").c_str(),now - 2592000000LL); // delete older than 30 days
  810. }
  811. const unsigned long delay = (dl > now) ? (unsigned long)(dl - now) : 100;
  812. clockShouldBe = now + (uint64_t)delay;
  813. _phy.poll(delay);
  814. }
  815. } catch (std::exception &e) {
  816. Mutex::Lock _l(_termReason_m);
  817. _termReason = ONE_UNRECOVERABLE_ERROR;
  818. _fatalErrorMessage = std::string("unexpected exception in main thread: ")+e.what();
  819. } catch ( ... ) {
  820. Mutex::Lock _l(_termReason_m);
  821. _termReason = ONE_UNRECOVERABLE_ERROR;
  822. _fatalErrorMessage = "unexpected exception in main thread: unknown exception";
  823. }
  824. try {
  825. Mutex::Lock _l(_tcpConnections_m);
  826. while (!_tcpConnections.empty())
  827. _phy.close((*_tcpConnections.begin())->sock);
  828. } catch ( ... ) {}
  829. {
  830. Mutex::Lock _l(_nets_m);
  831. for(std::map<uint64_t,NetworkState>::iterator n(_nets.begin());n!=_nets.end();++n)
  832. delete n->second.tap;
  833. _nets.clear();
  834. }
  835. delete _updater;
  836. _updater = (SoftwareUpdater *)0;
  837. delete _node;
  838. _node = (Node *)0;
  839. return _termReason;
  840. }
  841. virtual ReasonForTermination reasonForTermination() const
  842. {
  843. Mutex::Lock _l(_termReason_m);
  844. return _termReason;
  845. }
  846. virtual std::string fatalErrorMessage() const
  847. {
  848. Mutex::Lock _l(_termReason_m);
  849. return _fatalErrorMessage;
  850. }
  851. virtual std::string portDeviceName(uint64_t nwid) const
  852. {
  853. Mutex::Lock _l(_nets_m);
  854. std::map<uint64_t,NetworkState>::const_iterator n(_nets.find(nwid));
  855. if ((n != _nets.end())&&(n->second.tap))
  856. return n->second.tap->deviceName();
  857. else return std::string();
  858. }
  859. #ifdef ZT_SDK
  860. virtual void leave(const uint64_t hp)
  861. {
  862. _node->leave(hp, NULL, NULL);
  863. }
  864. virtual void join(const uint64_t hp)
  865. {
  866. _node->join(hp, NULL, NULL);
  867. }
  868. virtual std::string givenHomePath()
  869. {
  870. return _homePath;
  871. }
  872. std::vector<ZT_VirtualNetworkRoute> *getRoutes(uint64_t nwid)
  873. {
  874. Mutex::Lock _l(_nets_m);
  875. NetworkState &n = _nets[nwid];
  876. std::vector<ZT_VirtualNetworkRoute> *routes = new std::vector<ZT_VirtualNetworkRoute>();
  877. for(int i=0; i<ZT_MAX_NETWORK_ROUTES; i++) {
  878. routes->push_back(n.config.routes[i]);
  879. }
  880. return routes;
  881. }
  882. virtual Node *getNode()
  883. {
  884. return _node;
  885. }
  886. virtual void removeNets()
  887. {
  888. Mutex::Lock _l(_nets_m);
  889. std::map<uint64_t,NetworkState>::iterator i;
  890. for(i = _nets.begin(); i != _nets.end(); i++)
  891. delete i->second.tap;
  892. }
  893. #endif // ZT_SDK
  894. virtual void terminate()
  895. {
  896. _run_m.lock();
  897. _run = false;
  898. _run_m.unlock();
  899. _phy.whack();
  900. }
  901. virtual bool getNetworkSettings(const uint64_t nwid,NetworkSettings &settings) const
  902. {
  903. Mutex::Lock _l(_nets_m);
  904. std::map<uint64_t,NetworkState>::const_iterator n(_nets.find(nwid));
  905. if (n == _nets.end())
  906. return false;
  907. settings = n->second.settings;
  908. return true;
  909. }
  910. virtual bool setNetworkSettings(const uint64_t nwid,const NetworkSettings &settings)
  911. {
  912. Mutex::Lock _l(_nets_m);
  913. std::map<uint64_t,NetworkState>::iterator n(_nets.find(nwid));
  914. if (n == _nets.end())
  915. return false;
  916. n->second.settings = settings;
  917. char nlcpath[4096];
  918. OSUtils::ztsnprintf(nlcpath,sizeof(nlcpath),"%s" ZT_PATH_SEPARATOR_S "%.16llx.local.conf",_networksPath.c_str(),nwid);
  919. FILE *out = fopen(nlcpath,"w");
  920. if (out) {
  921. fprintf(out,"allowManaged=%d\n",(int)n->second.settings.allowManaged);
  922. fprintf(out,"allowGlobal=%d\n",(int)n->second.settings.allowGlobal);
  923. fprintf(out,"allowDefault=%d\n",(int)n->second.settings.allowDefault);
  924. fclose(out);
  925. }
  926. if (n->second.tap)
  927. syncManagedStuff(n->second,true,true);
  928. return true;
  929. }
  930. // =========================================================================
  931. // Internal implementation methods for control plane, route setup, etc.
  932. // =========================================================================
  933. inline unsigned int handleControlPlaneHttpRequest(
  934. const InetAddress &fromAddress,
  935. unsigned int httpMethod,
  936. const std::string &path,
  937. const std::map<std::string,std::string> &headers,
  938. const std::string &body,
  939. std::string &responseBody,
  940. std::string &responseContentType)
  941. {
  942. char tmp[256];
  943. unsigned int scode = 404;
  944. json res;
  945. std::vector<std::string> ps(OSUtils::split(path.c_str(),"/","",""));
  946. std::map<std::string,std::string> urlArgs;
  947. /* Note: this is kind of restricted in what it'll take. It does not support
  948. * URL encoding, and /'s in URL args will screw it up. But the only URL args
  949. * it really uses in ?jsonp=funcionName, and otherwise it just takes simple
  950. * paths to simply-named resources. */
  951. if (ps.size() > 0) {
  952. std::size_t qpos = ps[ps.size() - 1].find('?');
  953. if (qpos != std::string::npos) {
  954. std::string args(ps[ps.size() - 1].substr(qpos + 1));
  955. ps[ps.size() - 1] = ps[ps.size() - 1].substr(0,qpos);
  956. std::vector<std::string> asplit(OSUtils::split(args.c_str(),"&","",""));
  957. for(std::vector<std::string>::iterator a(asplit.begin());a!=asplit.end();++a) {
  958. std::size_t eqpos = a->find('=');
  959. if (eqpos == std::string::npos)
  960. urlArgs[*a] = "";
  961. else urlArgs[a->substr(0,eqpos)] = a->substr(eqpos + 1);
  962. }
  963. }
  964. }
  965. bool isAuth = false;
  966. {
  967. std::map<std::string,std::string>::const_iterator ah(headers.find("x-zt1-auth"));
  968. if ((ah != headers.end())&&(_authToken == ah->second)) {
  969. isAuth = true;
  970. } else {
  971. ah = urlArgs.find("auth");
  972. if ((ah != urlArgs.end())&&(_authToken == ah->second))
  973. isAuth = true;
  974. }
  975. }
  976. #ifdef __SYNOLOGY__
  977. // Authenticate via Synology's built-in cgi script
  978. if (!isAuth) {
  979. /*
  980. fprintf(stderr, "path = %s\n", path.c_str());
  981. fprintf(stderr, "headers.size=%d\n", headers.size());
  982. std::map<std::string, std::string>::const_iterator it(headers.begin());
  983. while(it != headers.end()) {
  984. fprintf(stderr,"header[%s] = %s\n", (it->first).c_str(), (it->second).c_str());
  985. it++;
  986. }
  987. */
  988. // parse out url args
  989. int synotoken_pos = path.find("SynoToken");
  990. int argpos = path.find("?");
  991. if(synotoken_pos != std::string::npos && argpos != std::string::npos) {
  992. std::string cookie = path.substr(argpos+1, synotoken_pos-(argpos+1));
  993. std::string synotoken = path.substr(synotoken_pos);
  994. std::string cookie_val = cookie.substr(cookie.find("=")+1);
  995. std::string synotoken_val = synotoken.substr(synotoken.find("=")+1);
  996. // Set necessary env for auth script
  997. std::map<std::string,std::string>::const_iterator ah2(headers.find("x-forwarded-for"));
  998. setenv("HTTP_COOKIE", cookie_val.c_str(), true);
  999. setenv("HTTP_X_SYNO_TOKEN", synotoken_val.c_str(), true);
  1000. setenv("REMOTE_ADDR", ah2->second.c_str(),true);
  1001. //fprintf(stderr, "HTTP_COOKIE: %s\n",std::getenv ("HTTP_COOKIE"));
  1002. //fprintf(stderr, "HTTP_X_SYNO_TOKEN: %s\n",std::getenv ("HTTP_X_SYNO_TOKEN"));
  1003. //fprintf(stderr, "REMOTE_ADDR: %s\n",std::getenv ("REMOTE_ADDR"));
  1004. // check synology web auth
  1005. char user[256], buf[1024];
  1006. FILE *fp = NULL;
  1007. bzero(user, 256);
  1008. fp = popen("/usr/syno/synoman/webman/modules/authenticate.cgi", "r");
  1009. if(!fp)
  1010. isAuth = false;
  1011. else {
  1012. bzero(buf, sizeof(buf));
  1013. fread(buf, 1024, 1, fp);
  1014. if(strlen(buf) > 0) {
  1015. snprintf(user, 256, "%s", buf);
  1016. isAuth = true;
  1017. }
  1018. }
  1019. pclose(fp);
  1020. }
  1021. }
  1022. #endif
  1023. if (httpMethod == HTTP_GET) {
  1024. if (isAuth) {
  1025. if (ps[0] == "status") {
  1026. ZT_NodeStatus status;
  1027. _node->status(&status);
  1028. OSUtils::ztsnprintf(tmp,sizeof(tmp),"%.10llx",status.address);
  1029. res["address"] = tmp;
  1030. res["publicIdentity"] = status.publicIdentity;
  1031. res["online"] = (bool)(status.online != 0);
  1032. res["tcpFallbackActive"] = (_tcpFallbackTunnel != (TcpConnection *)0);
  1033. res["versionMajor"] = ZEROTIER_ONE_VERSION_MAJOR;
  1034. res["versionMinor"] = ZEROTIER_ONE_VERSION_MINOR;
  1035. res["versionRev"] = ZEROTIER_ONE_VERSION_REVISION;
  1036. res["versionBuild"] = ZEROTIER_ONE_VERSION_BUILD;
  1037. OSUtils::ztsnprintf(tmp,sizeof(tmp),"%d.%d.%d",ZEROTIER_ONE_VERSION_MAJOR,ZEROTIER_ONE_VERSION_MINOR,ZEROTIER_ONE_VERSION_REVISION);
  1038. res["version"] = tmp;
  1039. res["clock"] = OSUtils::now();
  1040. {
  1041. Mutex::Lock _l(_localConfig_m);
  1042. res["config"] = _localConfig;
  1043. }
  1044. json &settings = res["config"]["settings"];
  1045. settings["primaryPort"] = OSUtils::jsonInt(settings["primaryPort"],(uint64_t)_primaryPort) & 0xffff;
  1046. settings["allowTcpFallbackRelay"] = OSUtils::jsonBool(settings["allowTcpFallbackRelay"],_allowTcpFallbackRelay);
  1047. #ifdef ZT_USE_MINIUPNPC
  1048. settings["portMappingEnabled"] = OSUtils::jsonBool(settings["portMappingEnabled"],true);
  1049. #else
  1050. settings["portMappingEnabled"] = false; // not supported in build
  1051. #endif
  1052. #ifndef ZT_SDK
  1053. settings["softwareUpdate"] = OSUtils::jsonString(settings["softwareUpdate"],ZT_SOFTWARE_UPDATE_DEFAULT);
  1054. settings["softwareUpdateChannel"] = OSUtils::jsonString(settings["softwareUpdateChannel"],ZT_SOFTWARE_UPDATE_DEFAULT_CHANNEL);
  1055. #endif
  1056. const World planet(_node->planet());
  1057. res["planetWorldId"] = planet.id();
  1058. res["planetWorldTimestamp"] = planet.timestamp();
  1059. scode = 200;
  1060. } else if (ps[0] == "moon") {
  1061. std::vector<World> moons(_node->moons());
  1062. if (ps.size() == 1) {
  1063. // Return [array] of all moons
  1064. res = json::array();
  1065. for(std::vector<World>::const_iterator m(moons.begin());m!=moons.end();++m) {
  1066. json mj;
  1067. _moonToJson(mj,*m);
  1068. res.push_back(mj);
  1069. }
  1070. scode = 200;
  1071. } else {
  1072. // Return a single moon by ID
  1073. const uint64_t id = Utils::hexStrToU64(ps[1].c_str());
  1074. for(std::vector<World>::const_iterator m(moons.begin());m!=moons.end();++m) {
  1075. if (m->id() == id) {
  1076. _moonToJson(res,*m);
  1077. scode = 200;
  1078. break;
  1079. }
  1080. }
  1081. }
  1082. } else if (ps[0] == "network") {
  1083. ZT_VirtualNetworkList *nws = _node->networks();
  1084. if (nws) {
  1085. if (ps.size() == 1) {
  1086. // Return [array] of all networks
  1087. res = nlohmann::json::array();
  1088. for(unsigned long i=0;i<nws->networkCount;++i) {
  1089. OneService::NetworkSettings localSettings;
  1090. getNetworkSettings(nws->networks[i].nwid,localSettings);
  1091. nlohmann::json nj;
  1092. _networkToJson(nj,&(nws->networks[i]),portDeviceName(nws->networks[i].nwid),localSettings);
  1093. res.push_back(nj);
  1094. }
  1095. scode = 200;
  1096. } else if (ps.size() == 2) {
  1097. // Return a single network by ID or 404 if not found
  1098. const uint64_t wantnw = Utils::hexStrToU64(ps[1].c_str());
  1099. for(unsigned long i=0;i<nws->networkCount;++i) {
  1100. if (nws->networks[i].nwid == wantnw) {
  1101. OneService::NetworkSettings localSettings;
  1102. getNetworkSettings(nws->networks[i].nwid,localSettings);
  1103. _networkToJson(res,&(nws->networks[i]),portDeviceName(nws->networks[i].nwid),localSettings);
  1104. scode = 200;
  1105. break;
  1106. }
  1107. }
  1108. } else scode = 404;
  1109. _node->freeQueryResult((void *)nws);
  1110. } else scode = 500;
  1111. } else if (ps[0] == "peer") {
  1112. ZT_PeerList *pl = _node->peers();
  1113. if (pl) {
  1114. if (ps.size() == 1) {
  1115. // Return [array] of all peers
  1116. res = nlohmann::json::array();
  1117. for(unsigned long i=0;i<pl->peerCount;++i) {
  1118. nlohmann::json pj;
  1119. _peerToJson(pj,&(pl->peers[i]));
  1120. res.push_back(pj);
  1121. }
  1122. scode = 200;
  1123. } else if (ps.size() == 2) {
  1124. // Return a single peer by ID or 404 if not found
  1125. uint64_t wantp = Utils::hexStrToU64(ps[1].c_str());
  1126. for(unsigned long i=0;i<pl->peerCount;++i) {
  1127. if (pl->peers[i].address == wantp) {
  1128. _peerToJson(res,&(pl->peers[i]));
  1129. scode = 200;
  1130. break;
  1131. }
  1132. }
  1133. } else scode = 404;
  1134. _node->freeQueryResult((void *)pl);
  1135. } else scode = 500;
  1136. } else {
  1137. if (_controller) {
  1138. scode = _controller->handleControlPlaneHttpGET(std::vector<std::string>(ps.begin()+1,ps.end()),urlArgs,headers,body,responseBody,responseContentType);
  1139. } else scode = 404;
  1140. }
  1141. } else scode = 401; // isAuth == false
  1142. } else if ((httpMethod == HTTP_POST)||(httpMethod == HTTP_PUT)) {
  1143. if (isAuth) {
  1144. if (ps[0] == "moon") {
  1145. if (ps.size() == 2) {
  1146. uint64_t seed = 0;
  1147. try {
  1148. json j(OSUtils::jsonParse(body));
  1149. if (j.is_object()) {
  1150. seed = Utils::hexStrToU64(OSUtils::jsonString(j["seed"],"0").c_str());
  1151. }
  1152. } catch ( ... ) {
  1153. // discard invalid JSON
  1154. }
  1155. std::vector<World> moons(_node->moons());
  1156. const uint64_t id = Utils::hexStrToU64(ps[1].c_str());
  1157. for(std::vector<World>::const_iterator m(moons.begin());m!=moons.end();++m) {
  1158. if (m->id() == id) {
  1159. _moonToJson(res,*m);
  1160. scode = 200;
  1161. break;
  1162. }
  1163. }
  1164. if ((scode != 200)&&(seed != 0)) {
  1165. char tmp[64];
  1166. OSUtils::ztsnprintf(tmp,sizeof(tmp),"%.16llx",id);
  1167. res["id"] = tmp;
  1168. res["roots"] = json::array();
  1169. res["timestamp"] = 0;
  1170. res["signature"] = json();
  1171. res["updatesMustBeSignedBy"] = json();
  1172. res["waiting"] = true;
  1173. _node->orbit((void *)0,id,seed);
  1174. scode = 200;
  1175. }
  1176. } else scode = 404;
  1177. } else if (ps[0] == "network") {
  1178. if (ps.size() == 2) {
  1179. uint64_t wantnw = Utils::hexStrToU64(ps[1].c_str());
  1180. _node->join(wantnw,(void *)0,(void *)0); // does nothing if we are a member
  1181. ZT_VirtualNetworkList *nws = _node->networks();
  1182. if (nws) {
  1183. for(unsigned long i=0;i<nws->networkCount;++i) {
  1184. if (nws->networks[i].nwid == wantnw) {
  1185. OneService::NetworkSettings localSettings;
  1186. getNetworkSettings(nws->networks[i].nwid,localSettings);
  1187. try {
  1188. json j(OSUtils::jsonParse(body));
  1189. if (j.is_object()) {
  1190. json &allowManaged = j["allowManaged"];
  1191. if (allowManaged.is_boolean()) localSettings.allowManaged = (bool)allowManaged;
  1192. json &allowGlobal = j["allowGlobal"];
  1193. if (allowGlobal.is_boolean()) localSettings.allowGlobal = (bool)allowGlobal;
  1194. json &allowDefault = j["allowDefault"];
  1195. if (allowDefault.is_boolean()) localSettings.allowDefault = (bool)allowDefault;
  1196. }
  1197. } catch ( ... ) {
  1198. // discard invalid JSON
  1199. }
  1200. setNetworkSettings(nws->networks[i].nwid,localSettings);
  1201. _networkToJson(res,&(nws->networks[i]),portDeviceName(nws->networks[i].nwid),localSettings);
  1202. scode = 200;
  1203. break;
  1204. }
  1205. }
  1206. _node->freeQueryResult((void *)nws);
  1207. } else scode = 500;
  1208. } else scode = 404;
  1209. } else {
  1210. if (_controller)
  1211. scode = _controller->handleControlPlaneHttpPOST(std::vector<std::string>(ps.begin()+1,ps.end()),urlArgs,headers,body,responseBody,responseContentType);
  1212. else scode = 404;
  1213. }
  1214. } else scode = 401; // isAuth == false
  1215. } else if (httpMethod == HTTP_DELETE) {
  1216. if (isAuth) {
  1217. if (ps[0] == "moon") {
  1218. if (ps.size() == 2) {
  1219. _node->deorbit((void *)0,Utils::hexStrToU64(ps[1].c_str()));
  1220. res["result"] = true;
  1221. scode = 200;
  1222. } // else 404
  1223. } else if (ps[0] == "network") {
  1224. ZT_VirtualNetworkList *nws = _node->networks();
  1225. if (nws) {
  1226. if (ps.size() == 2) {
  1227. uint64_t wantnw = Utils::hexStrToU64(ps[1].c_str());
  1228. for(unsigned long i=0;i<nws->networkCount;++i) {
  1229. if (nws->networks[i].nwid == wantnw) {
  1230. _node->leave(wantnw,(void **)0,(void *)0);
  1231. res["result"] = true;
  1232. scode = 200;
  1233. break;
  1234. }
  1235. }
  1236. } // else 404
  1237. _node->freeQueryResult((void *)nws);
  1238. } else scode = 500;
  1239. } else {
  1240. if (_controller)
  1241. scode = _controller->handleControlPlaneHttpDELETE(std::vector<std::string>(ps.begin()+1,ps.end()),urlArgs,headers,body,responseBody,responseContentType);
  1242. else scode = 404;
  1243. }
  1244. } else scode = 401; // isAuth = false
  1245. } else {
  1246. scode = 400;
  1247. }
  1248. if (responseBody.length() == 0) {
  1249. if ((res.is_object())||(res.is_array()))
  1250. responseBody = OSUtils::jsonDump(res);
  1251. else responseBody = "{}";
  1252. responseContentType = "application/json";
  1253. }
  1254. // Wrap result in jsonp function call if the user included a jsonp= url argument.
  1255. // Also double-check isAuth since forbidding this without auth feels safer.
  1256. std::map<std::string,std::string>::const_iterator jsonp(urlArgs.find("jsonp"));
  1257. if ((isAuth)&&(jsonp != urlArgs.end())&&(responseContentType == "application/json")) {
  1258. if (responseBody.length() > 0)
  1259. responseBody = jsonp->second + "(" + responseBody + ");";
  1260. else responseBody = jsonp->second + "(null);";
  1261. responseContentType = "application/javascript";
  1262. }
  1263. return scode;
  1264. }
  1265. // Must be called after _localConfig is read or modified
  1266. void applyLocalConfig()
  1267. {
  1268. Mutex::Lock _l(_localConfig_m);
  1269. json lc(_localConfig);
  1270. _v4Hints.clear();
  1271. _v6Hints.clear();
  1272. _v4Blacklists.clear();
  1273. _v6Blacklists.clear();
  1274. json &virt = lc["virtual"];
  1275. if (virt.is_object()) {
  1276. for(json::iterator v(virt.begin());v!=virt.end();++v) {
  1277. const std::string nstr = v.key();
  1278. if ((nstr.length() == ZT_ADDRESS_LENGTH_HEX)&&(v.value().is_object())) {
  1279. const Address ztaddr(Utils::hexStrToU64(nstr.c_str()));
  1280. if (ztaddr) {
  1281. const uint64_t ztaddr2 = ztaddr.toInt();
  1282. std::vector<InetAddress> &v4h = _v4Hints[ztaddr2];
  1283. std::vector<InetAddress> &v6h = _v6Hints[ztaddr2];
  1284. std::vector<InetAddress> &v4b = _v4Blacklists[ztaddr2];
  1285. std::vector<InetAddress> &v6b = _v6Blacklists[ztaddr2];
  1286. json &tryAddrs = v.value()["try"];
  1287. if (tryAddrs.is_array()) {
  1288. for(unsigned long i=0;i<tryAddrs.size();++i) {
  1289. const InetAddress ip(OSUtils::jsonString(tryAddrs[i],"").c_str());
  1290. if (ip.ss_family == AF_INET)
  1291. v4h.push_back(ip);
  1292. else if (ip.ss_family == AF_INET6)
  1293. v6h.push_back(ip);
  1294. }
  1295. }
  1296. json &blAddrs = v.value()["blacklist"];
  1297. if (blAddrs.is_array()) {
  1298. for(unsigned long i=0;i<blAddrs.size();++i) {
  1299. const InetAddress ip(OSUtils::jsonString(blAddrs[i],"").c_str());
  1300. if (ip.ss_family == AF_INET)
  1301. v4b.push_back(ip);
  1302. else if (ip.ss_family == AF_INET6)
  1303. v6b.push_back(ip);
  1304. }
  1305. }
  1306. if (v4h.empty()) _v4Hints.erase(ztaddr2);
  1307. if (v6h.empty()) _v6Hints.erase(ztaddr2);
  1308. if (v4b.empty()) _v4Blacklists.erase(ztaddr2);
  1309. if (v6b.empty()) _v6Blacklists.erase(ztaddr2);
  1310. }
  1311. }
  1312. }
  1313. }
  1314. _globalV4Blacklist.clear();
  1315. _globalV6Blacklist.clear();
  1316. json &physical = lc["physical"];
  1317. if (physical.is_object()) {
  1318. for(json::iterator phy(physical.begin());phy!=physical.end();++phy) {
  1319. const InetAddress net(OSUtils::jsonString(phy.key(),"").c_str());
  1320. if ((net)&&(net.netmaskBits() > 0)) {
  1321. if (phy.value().is_object()) {
  1322. if (OSUtils::jsonBool(phy.value()["blacklist"],false)) {
  1323. if (net.ss_family == AF_INET)
  1324. _globalV4Blacklist.push_back(net);
  1325. else if (net.ss_family == AF_INET6)
  1326. _globalV6Blacklist.push_back(net);
  1327. }
  1328. }
  1329. }
  1330. }
  1331. }
  1332. _allowManagementFrom.clear();
  1333. _interfacePrefixBlacklist.clear();
  1334. json &settings = lc["settings"];
  1335. _primaryPort = (unsigned int)OSUtils::jsonInt(settings["primaryPort"],(uint64_t)_primaryPort) & 0xffff;
  1336. _allowTcpFallbackRelay = OSUtils::jsonBool(settings["allowTcpFallbackRelay"],true);
  1337. _portMappingEnabled = OSUtils::jsonBool(settings["portMappingEnabled"],true);
  1338. #ifndef ZT_SDK
  1339. const std::string up(OSUtils::jsonString(settings["softwareUpdate"],ZT_SOFTWARE_UPDATE_DEFAULT));
  1340. const bool udist = OSUtils::jsonBool(settings["softwareUpdateDist"],false);
  1341. if (((up == "apply")||(up == "download"))||(udist)) {
  1342. if (!_updater)
  1343. _updater = new SoftwareUpdater(*_node,_homePath);
  1344. _updateAutoApply = (up == "apply");
  1345. _updater->setUpdateDistribution(udist);
  1346. _updater->setChannel(OSUtils::jsonString(settings["softwareUpdateChannel"],ZT_SOFTWARE_UPDATE_DEFAULT_CHANNEL));
  1347. } else {
  1348. delete _updater;
  1349. _updater = (SoftwareUpdater *)0;
  1350. _updateAutoApply = false;
  1351. }
  1352. #endif
  1353. json &ignoreIfs = settings["interfacePrefixBlacklist"];
  1354. if (ignoreIfs.is_array()) {
  1355. for(unsigned long i=0;i<ignoreIfs.size();++i) {
  1356. const std::string tmp(OSUtils::jsonString(ignoreIfs[i],""));
  1357. if (tmp.length() > 0)
  1358. _interfacePrefixBlacklist.push_back(tmp);
  1359. }
  1360. }
  1361. json &amf = settings["allowManagementFrom"];
  1362. if (amf.is_array()) {
  1363. for(unsigned long i=0;i<amf.size();++i) {
  1364. const InetAddress nw(OSUtils::jsonString(amf[i],"").c_str());
  1365. if (nw)
  1366. _allowManagementFrom.push_back(nw);
  1367. }
  1368. }
  1369. json &vault = settings["vault"];
  1370. if (vault.is_object()) {
  1371. const std::string url(OSUtils::jsonString(vault["vaultURL"], "").c_str());
  1372. if (!url.empty()) {
  1373. _vaultURL = url;
  1374. }
  1375. const std::string token(OSUtils::jsonString(vault["vaultToken"], "").c_str());
  1376. if (!token.empty()) {
  1377. _vaultToken = token;
  1378. }
  1379. const std::string path(OSUtils::jsonString(vault["vaultPath"], "").c_str());
  1380. if (!path.empty()) {
  1381. _vaultPath = path;
  1382. }
  1383. }
  1384. // also check environment variables for values. Environment variables
  1385. // will override local.conf variables
  1386. const std::string envURL(getenv("VAULT_ADDR"));
  1387. if (!envURL.empty()) {
  1388. _vaultURL = envURL;
  1389. }
  1390. const std::string envToken(getenv("VAULT_TOKEN"));
  1391. if (!envToken.empty()) {
  1392. _vaultToken = envToken;
  1393. }
  1394. const std::string envPath(getenv("VAULT_PATH"));
  1395. if (!envPath.empty()) {
  1396. _vaultPath = envPath;
  1397. }
  1398. if (!_vaultURL.empty() && !_vaultToken.empty()) {
  1399. _vaultEnabled = true;
  1400. }
  1401. }
  1402. // Checks if a managed IP or route target is allowed
  1403. bool checkIfManagedIsAllowed(const NetworkState &n,const InetAddress &target)
  1404. {
  1405. if (!n.settings.allowManaged)
  1406. return false;
  1407. if (n.settings.allowManagedWhitelist.size() > 0) {
  1408. bool allowed = false;
  1409. for (InetAddress addr : n.settings.allowManagedWhitelist) {
  1410. if (addr.containsAddress(target) && addr.netmaskBits() <= target.netmaskBits()) {
  1411. allowed = true;
  1412. break;
  1413. }
  1414. }
  1415. if (!allowed) return false;
  1416. }
  1417. if (target.isDefaultRoute())
  1418. return n.settings.allowDefault;
  1419. switch(target.ipScope()) {
  1420. case InetAddress::IP_SCOPE_NONE:
  1421. case InetAddress::IP_SCOPE_MULTICAST:
  1422. case InetAddress::IP_SCOPE_LOOPBACK:
  1423. case InetAddress::IP_SCOPE_LINK_LOCAL:
  1424. return false;
  1425. case InetAddress::IP_SCOPE_GLOBAL:
  1426. return n.settings.allowGlobal;
  1427. default:
  1428. return true;
  1429. }
  1430. }
  1431. // Match only an IP from a vector of IPs -- used in syncManagedStuff()
  1432. bool matchIpOnly(const std::vector<InetAddress> &ips,const InetAddress &ip) const
  1433. {
  1434. for(std::vector<InetAddress>::const_iterator i(ips.begin());i!=ips.end();++i) {
  1435. if (i->ipsEqual(ip))
  1436. return true;
  1437. }
  1438. return false;
  1439. }
  1440. // Apply or update managed IPs for a configured network (be sure n.tap exists)
  1441. void syncManagedStuff(NetworkState &n,bool syncIps,bool syncRoutes)
  1442. {
  1443. char ipbuf[64];
  1444. // assumes _nets_m is locked
  1445. if (syncIps) {
  1446. std::vector<InetAddress> newManagedIps;
  1447. newManagedIps.reserve(n.config.assignedAddressCount);
  1448. for(unsigned int i=0;i<n.config.assignedAddressCount;++i) {
  1449. const InetAddress *ii = reinterpret_cast<const InetAddress *>(&(n.config.assignedAddresses[i]));
  1450. if (checkIfManagedIsAllowed(n,*ii))
  1451. newManagedIps.push_back(*ii);
  1452. }
  1453. std::sort(newManagedIps.begin(),newManagedIps.end());
  1454. newManagedIps.erase(std::unique(newManagedIps.begin(),newManagedIps.end()),newManagedIps.end());
  1455. for(std::vector<InetAddress>::iterator ip(n.managedIps.begin());ip!=n.managedIps.end();++ip) {
  1456. if (std::find(newManagedIps.begin(),newManagedIps.end(),*ip) == newManagedIps.end()) {
  1457. if (!n.tap->removeIp(*ip))
  1458. fprintf(stderr,"ERROR: unable to remove ip address %s" ZT_EOL_S, ip->toString(ipbuf));
  1459. }
  1460. }
  1461. #ifdef __SYNOLOGY__
  1462. if (!n.tap->addIpSyn(newManagedIps))
  1463. fprintf(stderr,"ERROR: unable to add ip addresses to ifcfg" ZT_EOL_S);
  1464. #else
  1465. for(std::vector<InetAddress>::iterator ip(newManagedIps.begin());ip!=newManagedIps.end();++ip) {
  1466. if (std::find(n.managedIps.begin(),n.managedIps.end(),*ip) == n.managedIps.end()) {
  1467. if (!n.tap->addIp(*ip))
  1468. fprintf(stderr,"ERROR: unable to add ip address %s" ZT_EOL_S, ip->toString(ipbuf));
  1469. }
  1470. }
  1471. #endif
  1472. n.managedIps.swap(newManagedIps);
  1473. }
  1474. if (syncRoutes) {
  1475. char tapdev[64];
  1476. #if defined(__WINDOWS__) && !defined(ZT_SDK)
  1477. OSUtils::ztsnprintf(tapdev,sizeof(tapdev),"%.16llx",(unsigned long long)n.tap->luid().Value);
  1478. #else
  1479. Utils::scopy(tapdev,sizeof(tapdev),n.tap->deviceName().c_str());
  1480. #endif
  1481. std::vector<InetAddress> myIps(n.tap->ips());
  1482. // Nuke applied routes that are no longer in n.config.routes[] and/or are not allowed
  1483. for(std::list< SharedPtr<ManagedRoute> >::iterator mr(n.managedRoutes.begin());mr!=n.managedRoutes.end();) {
  1484. bool haveRoute = false;
  1485. if ( (checkIfManagedIsAllowed(n,(*mr)->target())) && (((*mr)->via().ss_family != (*mr)->target().ss_family)||(!matchIpOnly(myIps,(*mr)->via()))) ) {
  1486. for(unsigned int i=0;i<n.config.routeCount;++i) {
  1487. const InetAddress *const target = reinterpret_cast<const InetAddress *>(&(n.config.routes[i].target));
  1488. const InetAddress *const via = reinterpret_cast<const InetAddress *>(&(n.config.routes[i].via));
  1489. if ( ((*mr)->target() == *target) && ( ((via->ss_family == target->ss_family)&&((*mr)->via().ipsEqual(*via))) || (tapdev == (*mr)->device()) ) ) {
  1490. haveRoute = true;
  1491. break;
  1492. }
  1493. }
  1494. }
  1495. if (haveRoute) {
  1496. ++mr;
  1497. } else {
  1498. n.managedRoutes.erase(mr++);
  1499. }
  1500. }
  1501. // Apply routes in n.config.routes[] that we haven't applied yet, and sync those we have in case shadow routes need to change
  1502. for(unsigned int i=0;i<n.config.routeCount;++i) {
  1503. const InetAddress *const target = reinterpret_cast<const InetAddress *>(&(n.config.routes[i].target));
  1504. const InetAddress *const via = reinterpret_cast<const InetAddress *>(&(n.config.routes[i].via));
  1505. if ( (!checkIfManagedIsAllowed(n,*target)) || ((via->ss_family == target->ss_family)&&(matchIpOnly(myIps,*via))) )
  1506. continue;
  1507. bool haveRoute = false;
  1508. // Ignore routes implied by local managed IPs since adding the IP adds the route
  1509. // Commented out to fix ticket #600 (disappearing routes on macOS). Remove this block when we're sure there's no side effects
  1510. /*
  1511. for(std::vector<InetAddress>::iterator ip(n.managedIps.begin());ip!=n.managedIps.end();++ip) {
  1512. if ((target->netmaskBits() == ip->netmaskBits())&&(target->containsAddress(*ip))) {
  1513. haveRoute = true;
  1514. break;
  1515. }
  1516. }
  1517. */
  1518. if (haveRoute)
  1519. continue;
  1520. // If we've already applied this route, just sync it and continue
  1521. for(std::list< SharedPtr<ManagedRoute> >::iterator mr(n.managedRoutes.begin());mr!=n.managedRoutes.end();++mr) {
  1522. if ( ((*mr)->target() == *target) && ( ((via->ss_family == target->ss_family)&&((*mr)->via().ipsEqual(*via))) || (tapdev == (*mr)->device()) ) ) {
  1523. haveRoute = true;
  1524. (*mr)->sync();
  1525. break;
  1526. }
  1527. }
  1528. if (haveRoute)
  1529. continue;
  1530. // Add and apply new routes
  1531. n.managedRoutes.push_back(SharedPtr<ManagedRoute>(new ManagedRoute(*target,*via,tapdev)));
  1532. if (!n.managedRoutes.back()->sync())
  1533. n.managedRoutes.pop_back();
  1534. }
  1535. }
  1536. }
  1537. // =========================================================================
  1538. // Handlers for Node and Phy<> callbacks
  1539. // =========================================================================
  1540. inline void phyOnDatagram(PhySocket *sock,void **uptr,const struct sockaddr *localAddr,const struct sockaddr *from,void *data,unsigned long len)
  1541. {
  1542. if ((len >= 16)&&(reinterpret_cast<const InetAddress *>(from)->ipScope() == InetAddress::IP_SCOPE_GLOBAL))
  1543. _lastDirectReceiveFromGlobal = OSUtils::now();
  1544. const ZT_ResultCode rc = _node->processWirePacket(
  1545. (void *)0,
  1546. OSUtils::now(),
  1547. reinterpret_cast<int64_t>(sock),
  1548. reinterpret_cast<const struct sockaddr_storage *>(from), // Phy<> uses sockaddr_storage, so it'll always be that big
  1549. data,
  1550. len,
  1551. &_nextBackgroundTaskDeadline);
  1552. if (ZT_ResultCode_isFatal(rc)) {
  1553. char tmp[256];
  1554. OSUtils::ztsnprintf(tmp,sizeof(tmp),"fatal error code from processWirePacket: %d",(int)rc);
  1555. Mutex::Lock _l(_termReason_m);
  1556. _termReason = ONE_UNRECOVERABLE_ERROR;
  1557. _fatalErrorMessage = tmp;
  1558. this->terminate();
  1559. }
  1560. }
  1561. inline void phyOnTcpConnect(PhySocket *sock,void **uptr,bool success)
  1562. {
  1563. if (!success) {
  1564. phyOnTcpClose(sock,uptr);
  1565. return;
  1566. }
  1567. TcpConnection *const tc = reinterpret_cast<TcpConnection *>(*uptr);
  1568. if (!tc) { // sanity check
  1569. _phy.close(sock,true);
  1570. return;
  1571. }
  1572. tc->sock = sock;
  1573. if (tc->type == TcpConnection::TCP_TUNNEL_OUTGOING) {
  1574. if (_tcpFallbackTunnel)
  1575. _phy.close(_tcpFallbackTunnel->sock);
  1576. _tcpFallbackTunnel = tc;
  1577. _phy.streamSend(sock,ZT_TCP_TUNNEL_HELLO,sizeof(ZT_TCP_TUNNEL_HELLO));
  1578. } else {
  1579. _phy.close(sock,true);
  1580. }
  1581. }
  1582. inline void phyOnTcpAccept(PhySocket *sockL,PhySocket *sockN,void **uptrL,void **uptrN,const struct sockaddr *from)
  1583. {
  1584. if (!from) {
  1585. _phy.close(sockN,false);
  1586. return;
  1587. } else {
  1588. TcpConnection *tc = new TcpConnection();
  1589. {
  1590. Mutex::Lock _l(_tcpConnections_m);
  1591. _tcpConnections.push_back(tc);
  1592. }
  1593. tc->type = TcpConnection::TCP_UNCATEGORIZED_INCOMING;
  1594. tc->parent = this;
  1595. tc->sock = sockN;
  1596. tc->remoteAddr = from;
  1597. tc->lastReceive = OSUtils::now();
  1598. http_parser_init(&(tc->parser),HTTP_REQUEST);
  1599. tc->parser.data = (void *)tc;
  1600. tc->messageSize = 0;
  1601. *uptrN = (void *)tc;
  1602. }
  1603. }
  1604. void phyOnTcpClose(PhySocket *sock,void **uptr)
  1605. {
  1606. TcpConnection *tc = (TcpConnection *)*uptr;
  1607. if (tc) {
  1608. if (tc == _tcpFallbackTunnel) {
  1609. _tcpFallbackTunnel = (TcpConnection *)0;
  1610. }
  1611. {
  1612. Mutex::Lock _l(_tcpConnections_m);
  1613. _tcpConnections.erase(std::remove(_tcpConnections.begin(),_tcpConnections.end(),tc),_tcpConnections.end());
  1614. }
  1615. delete tc;
  1616. }
  1617. }
  1618. void phyOnTcpData(PhySocket *sock,void **uptr,void *data,unsigned long len)
  1619. {
  1620. try {
  1621. if (!len) return; // sanity check, should never happen
  1622. TcpConnection *tc = reinterpret_cast<TcpConnection *>(*uptr);
  1623. tc->lastReceive = OSUtils::now();
  1624. switch(tc->type) {
  1625. case TcpConnection::TCP_UNCATEGORIZED_INCOMING:
  1626. switch(reinterpret_cast<uint8_t *>(data)[0]) {
  1627. // HTTP: GET, PUT, POST, HEAD, DELETE
  1628. case 'G':
  1629. case 'P':
  1630. case 'D':
  1631. case 'H': {
  1632. // This is only allowed from IPs permitted to access the management
  1633. // backplane, which is just 127.0.0.1/::1 unless otherwise configured.
  1634. bool allow;
  1635. {
  1636. Mutex::Lock _l(_localConfig_m);
  1637. if (_allowManagementFrom.size() == 0) {
  1638. allow = (tc->remoteAddr.ipScope() == InetAddress::IP_SCOPE_LOOPBACK);
  1639. } else {
  1640. allow = false;
  1641. for(std::vector<InetAddress>::const_iterator i(_allowManagementFrom.begin());i!=_allowManagementFrom.end();++i) {
  1642. if (i->containsAddress(tc->remoteAddr)) {
  1643. allow = true;
  1644. break;
  1645. }
  1646. }
  1647. }
  1648. }
  1649. if (allow) {
  1650. tc->type = TcpConnection::TCP_HTTP_INCOMING;
  1651. phyOnTcpData(sock,uptr,data,len);
  1652. } else {
  1653. _phy.close(sock);
  1654. }
  1655. } break;
  1656. // Drop unknown protocols
  1657. default:
  1658. _phy.close(sock);
  1659. break;
  1660. }
  1661. return;
  1662. case TcpConnection::TCP_HTTP_INCOMING:
  1663. case TcpConnection::TCP_HTTP_OUTGOING:
  1664. http_parser_execute(&(tc->parser),&HTTP_PARSER_SETTINGS,(const char *)data,len);
  1665. if ((tc->parser.upgrade)||(tc->parser.http_errno != HPE_OK))
  1666. _phy.close(sock);
  1667. return;
  1668. case TcpConnection::TCP_TUNNEL_OUTGOING:
  1669. tc->readq.append((const char *)data,len);
  1670. while (tc->readq.length() >= 5) {
  1671. const char *data = tc->readq.data();
  1672. const unsigned long mlen = ( ((((unsigned long)data[3]) & 0xff) << 8) | (((unsigned long)data[4]) & 0xff) );
  1673. if (tc->readq.length() >= (mlen + 5)) {
  1674. InetAddress from;
  1675. unsigned long plen = mlen; // payload length, modified if there's an IP header
  1676. data += 5; // skip forward past pseudo-TLS junk and mlen
  1677. if (plen == 4) {
  1678. // Hello message, which isn't sent by proxy and would be ignored by client
  1679. } else if (plen) {
  1680. // Messages should contain IPv4 or IPv6 source IP address data
  1681. switch(data[0]) {
  1682. case 4: // IPv4
  1683. if (plen >= 7) {
  1684. from.set((const void *)(data + 1),4,((((unsigned int)data[5]) & 0xff) << 8) | (((unsigned int)data[6]) & 0xff));
  1685. data += 7; // type + 4 byte IP + 2 byte port
  1686. plen -= 7;
  1687. } else {
  1688. _phy.close(sock);
  1689. return;
  1690. }
  1691. break;
  1692. case 6: // IPv6
  1693. if (plen >= 19) {
  1694. from.set((const void *)(data + 1),16,((((unsigned int)data[17]) & 0xff) << 8) | (((unsigned int)data[18]) & 0xff));
  1695. data += 19; // type + 16 byte IP + 2 byte port
  1696. plen -= 19;
  1697. } else {
  1698. _phy.close(sock);
  1699. return;
  1700. }
  1701. break;
  1702. case 0: // none/omitted
  1703. ++data;
  1704. --plen;
  1705. break;
  1706. default: // invalid address type
  1707. _phy.close(sock);
  1708. return;
  1709. }
  1710. if (from) {
  1711. InetAddress fakeTcpLocalInterfaceAddress((uint32_t)0xffffffff,0xffff);
  1712. const ZT_ResultCode rc = _node->processWirePacket(
  1713. (void *)0,
  1714. OSUtils::now(),
  1715. -1,
  1716. reinterpret_cast<struct sockaddr_storage *>(&from),
  1717. data,
  1718. plen,
  1719. &_nextBackgroundTaskDeadline);
  1720. if (ZT_ResultCode_isFatal(rc)) {
  1721. char tmp[256];
  1722. OSUtils::ztsnprintf(tmp,sizeof(tmp),"fatal error code from processWirePacket: %d",(int)rc);
  1723. Mutex::Lock _l(_termReason_m);
  1724. _termReason = ONE_UNRECOVERABLE_ERROR;
  1725. _fatalErrorMessage = tmp;
  1726. this->terminate();
  1727. _phy.close(sock);
  1728. return;
  1729. }
  1730. }
  1731. }
  1732. if (tc->readq.length() > (mlen + 5))
  1733. tc->readq.erase(tc->readq.begin(),tc->readq.begin() + (mlen + 5));
  1734. else tc->readq.clear();
  1735. } else break;
  1736. }
  1737. return;
  1738. }
  1739. } catch ( ... ) {
  1740. _phy.close(sock);
  1741. }
  1742. }
  1743. inline void phyOnTcpWritable(PhySocket *sock,void **uptr)
  1744. {
  1745. TcpConnection *tc = reinterpret_cast<TcpConnection *>(*uptr);
  1746. bool closeit = false;
  1747. {
  1748. Mutex::Lock _l(tc->writeq_m);
  1749. if (tc->writeq.length() > 0) {
  1750. long sent = (long)_phy.streamSend(sock,tc->writeq.data(),(unsigned long)tc->writeq.length(),true);
  1751. if (sent > 0) {
  1752. if ((unsigned long)sent >= (unsigned long)tc->writeq.length()) {
  1753. tc->writeq.clear();
  1754. _phy.setNotifyWritable(sock,false);
  1755. if (tc->type == TcpConnection::TCP_HTTP_INCOMING)
  1756. closeit = true; // HTTP keep alive not supported
  1757. } else {
  1758. tc->writeq.erase(tc->writeq.begin(),tc->writeq.begin() + sent);
  1759. }
  1760. }
  1761. } else {
  1762. _phy.setNotifyWritable(sock,false);
  1763. }
  1764. }
  1765. if (closeit)
  1766. _phy.close(sock);
  1767. }
  1768. inline void phyOnFileDescriptorActivity(PhySocket *sock,void **uptr,bool readable,bool writable) {}
  1769. inline void phyOnUnixAccept(PhySocket *sockL,PhySocket *sockN,void **uptrL,void **uptrN) {}
  1770. inline void phyOnUnixClose(PhySocket *sock,void **uptr) {}
  1771. inline void phyOnUnixData(PhySocket *sock,void **uptr,void *data,unsigned long len) {}
  1772. inline void phyOnUnixWritable(PhySocket *sock,void **uptr,bool lwip_invoked) {}
  1773. inline int nodeVirtualNetworkConfigFunction(uint64_t nwid,void **nuptr,enum ZT_VirtualNetworkConfigOperation op,const ZT_VirtualNetworkConfig *nwc)
  1774. {
  1775. Mutex::Lock _l(_nets_m);
  1776. NetworkState &n = _nets[nwid];
  1777. switch(op) {
  1778. case ZT_VIRTUAL_NETWORK_CONFIG_OPERATION_UP:
  1779. if (!n.tap) {
  1780. try {
  1781. char friendlyName[128];
  1782. OSUtils::ztsnprintf(friendlyName,sizeof(friendlyName),"ZeroTier One [%.16llx]",nwid);
  1783. n.tap = new EthernetTap(
  1784. _homePath.c_str(),
  1785. MAC(nwc->mac),
  1786. nwc->mtu,
  1787. (unsigned int)ZT_IF_METRIC,
  1788. nwid,
  1789. friendlyName,
  1790. StapFrameHandler,
  1791. (void *)this);
  1792. *nuptr = (void *)&n;
  1793. char nlcpath[256];
  1794. OSUtils::ztsnprintf(nlcpath,sizeof(nlcpath),"%s" ZT_PATH_SEPARATOR_S "networks.d" ZT_PATH_SEPARATOR_S "%.16llx.local.conf",_homePath.c_str(),nwid);
  1795. std::string nlcbuf;
  1796. if (OSUtils::readFile(nlcpath,nlcbuf)) {
  1797. Dictionary<4096> nc;
  1798. nc.load(nlcbuf.c_str());
  1799. Buffer<1024> allowManaged;
  1800. if (nc.get("allowManaged", allowManaged) && allowManaged.size() != 0) {
  1801. std::string addresses (allowManaged.begin(), allowManaged.size());
  1802. if (allowManaged.size() <= 5) { // untidy parsing for backward compatibility
  1803. if (allowManaged[0] == '1' || allowManaged[0] == 't' || allowManaged[0] == 'T') {
  1804. n.settings.allowManaged = true;
  1805. } else {
  1806. n.settings.allowManaged = false;
  1807. }
  1808. } else {
  1809. // this should be a list of IP addresses
  1810. n.settings.allowManaged = true;
  1811. size_t pos = 0;
  1812. while (true) {
  1813. size_t nextPos = addresses.find(',', pos);
  1814. std::string address = addresses.substr(pos, (nextPos == std::string::npos ? addresses.size() : nextPos) - pos);
  1815. n.settings.allowManagedWhitelist.push_back(InetAddress(address.c_str()));
  1816. if (nextPos == std::string::npos) break;
  1817. pos = nextPos + 1;
  1818. }
  1819. }
  1820. } else {
  1821. n.settings.allowManaged = true;
  1822. }
  1823. n.settings.allowGlobal = nc.getB("allowGlobal", false);
  1824. n.settings.allowDefault = nc.getB("allowDefault", false);
  1825. }
  1826. } catch (std::exception &exc) {
  1827. #ifdef __WINDOWS__
  1828. FILE *tapFailLog = fopen((_homePath + ZT_PATH_SEPARATOR_S"port_error_log.txt").c_str(),"a");
  1829. if (tapFailLog) {
  1830. fprintf(tapFailLog,"%.16llx: %s" ZT_EOL_S,(unsigned long long)nwid,exc.what());
  1831. fclose(tapFailLog);
  1832. }
  1833. #else
  1834. fprintf(stderr,"ERROR: unable to configure virtual network port: %s" ZT_EOL_S,exc.what());
  1835. #endif
  1836. _nets.erase(nwid);
  1837. return -999;
  1838. } catch ( ... ) {
  1839. return -999; // tap init failed
  1840. }
  1841. }
  1842. // After setting up tap, fall through to CONFIG_UPDATE since we also want to do this...
  1843. case ZT_VIRTUAL_NETWORK_CONFIG_OPERATION_CONFIG_UPDATE:
  1844. ZT_FAST_MEMCPY(&(n.config),nwc,sizeof(ZT_VirtualNetworkConfig));
  1845. if (n.tap) { // sanity check
  1846. #if defined(__WINDOWS__) && !defined(ZT_SDK)
  1847. // wait for up to 5 seconds for the WindowsEthernetTap to actually be initialized
  1848. //
  1849. // without WindowsEthernetTap::isInitialized() returning true, the won't actually
  1850. // be online yet and setting managed routes on it will fail.
  1851. const int MAX_SLEEP_COUNT = 500;
  1852. for (int i = 0; !n.tap->isInitialized() && i < MAX_SLEEP_COUNT; i++) {
  1853. Sleep(10);
  1854. }
  1855. #endif
  1856. syncManagedStuff(n,true,true);
  1857. n.tap->setMtu(nwc->mtu);
  1858. } else {
  1859. _nets.erase(nwid);
  1860. return -999; // tap init failed
  1861. }
  1862. break;
  1863. case ZT_VIRTUAL_NETWORK_CONFIG_OPERATION_DOWN:
  1864. case ZT_VIRTUAL_NETWORK_CONFIG_OPERATION_DESTROY:
  1865. if (n.tap) { // sanity check
  1866. #if defined(__WINDOWS__) && !defined(ZT_SDK)
  1867. std::string winInstanceId(n.tap->instanceId());
  1868. #endif
  1869. *nuptr = (void *)0;
  1870. delete n.tap;
  1871. _nets.erase(nwid);
  1872. #if defined(__WINDOWS__) && !defined(ZT_SDK)
  1873. if ((op == ZT_VIRTUAL_NETWORK_CONFIG_OPERATION_DESTROY)&&(winInstanceId.length() > 0))
  1874. WindowsEthernetTap::deletePersistentTapDevice(winInstanceId.c_str());
  1875. #endif
  1876. if (op == ZT_VIRTUAL_NETWORK_CONFIG_OPERATION_DESTROY) {
  1877. char nlcpath[256];
  1878. OSUtils::ztsnprintf(nlcpath,sizeof(nlcpath),"%s" ZT_PATH_SEPARATOR_S "networks.d" ZT_PATH_SEPARATOR_S "%.16llx.local.conf",_homePath.c_str(),nwid);
  1879. OSUtils::rm(nlcpath);
  1880. }
  1881. } else {
  1882. _nets.erase(nwid);
  1883. }
  1884. break;
  1885. }
  1886. return 0;
  1887. }
  1888. inline void nodeEventCallback(enum ZT_Event event,const void *metaData)
  1889. {
  1890. switch(event) {
  1891. case ZT_EVENT_FATAL_ERROR_IDENTITY_COLLISION: {
  1892. Mutex::Lock _l(_termReason_m);
  1893. _termReason = ONE_IDENTITY_COLLISION;
  1894. _fatalErrorMessage = "identity/address collision";
  1895. this->terminate();
  1896. } break;
  1897. case ZT_EVENT_TRACE: {
  1898. if (metaData) {
  1899. ::fprintf(stderr,"%s" ZT_EOL_S,(const char *)metaData);
  1900. ::fflush(stderr);
  1901. }
  1902. } break;
  1903. case ZT_EVENT_USER_MESSAGE: {
  1904. const ZT_UserMessage *um = reinterpret_cast<const ZT_UserMessage *>(metaData);
  1905. if ((um->typeId == ZT_SOFTWARE_UPDATE_USER_MESSAGE_TYPE)&&(_updater)) {
  1906. _updater->handleSoftwareUpdateUserMessage(um->origin,um->data,um->length);
  1907. }
  1908. } break;
  1909. case ZT_EVENT_REMOTE_TRACE: {
  1910. const ZT_RemoteTrace *rt = reinterpret_cast<const ZT_RemoteTrace *>(metaData);
  1911. if ((rt)&&(rt->len > 0)&&(rt->len <= ZT_MAX_REMOTE_TRACE_SIZE)&&(rt->data))
  1912. _controller->handleRemoteTrace(*rt);
  1913. }
  1914. default:
  1915. break;
  1916. }
  1917. }
  1918. #if ZT_VAULT_SUPPORT
  1919. inline bool nodeVaultPutIdentity(enum ZT_StateObjectType type, const void *data, int len)
  1920. {
  1921. bool retval = false;
  1922. if (type != ZT_STATE_OBJECT_IDENTITY_PUBLIC && type != ZT_STATE_OBJECT_IDENTITY_SECRET) {
  1923. return retval;
  1924. }
  1925. CURL *curl = curl_easy_init();
  1926. if (curl) {
  1927. char token[512] = { 0 };
  1928. snprintf(token, sizeof(token), "X-Vault-Token: %s", _vaultToken.c_str());
  1929. struct curl_slist *chunk = NULL;
  1930. chunk = curl_slist_append(chunk, token);
  1931. char content_type[512] = { 0 };
  1932. snprintf(content_type, sizeof(content_type), "Content-Type: application/json");
  1933. chunk = curl_slist_append(chunk, content_type);
  1934. curl_easy_setopt(curl, CURLOPT_HTTPHEADER, chunk);
  1935. char url[2048] = { 0 };
  1936. snprintf(url, sizeof(url), "%s/v1/%s", _vaultURL.c_str(), _vaultPath.c_str());
  1937. curl_easy_setopt(curl, CURLOPT_URL, url);
  1938. json d = json::object();
  1939. if (type == ZT_STATE_OBJECT_IDENTITY_PUBLIC) {
  1940. std::string key((const char*)data, len);
  1941. d["public"] = key;
  1942. }
  1943. else if (type == ZT_STATE_OBJECT_IDENTITY_SECRET) {
  1944. std::string key((const char*)data, len);
  1945. d["secret"] = key;
  1946. }
  1947. if (!d.empty()) {
  1948. std::string post = d.dump();
  1949. if (!post.empty()) {
  1950. curl_easy_setopt(curl, CURLOPT_POSTFIELDS, post.c_str());
  1951. curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, post.length());
  1952. #ifndef NDEBUG
  1953. curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L);
  1954. #endif
  1955. CURLcode res = curl_easy_perform(curl);
  1956. if (res == CURLE_OK) {
  1957. long response_code = 0;
  1958. curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &response_code);
  1959. if (response_code == 200 || response_code == 204) {
  1960. retval = true;
  1961. }
  1962. }
  1963. }
  1964. }
  1965. curl_easy_cleanup(curl);
  1966. curl = NULL;
  1967. curl_slist_free_all(chunk);
  1968. chunk = NULL;
  1969. }
  1970. return retval;
  1971. }
  1972. #endif
  1973. inline void nodeStatePutFunction(enum ZT_StateObjectType type,const uint64_t id[2],const void *data,int len)
  1974. {
  1975. #if ZT_VAULT_SUPPORT
  1976. if (_vaultEnabled && (type == ZT_STATE_OBJECT_IDENTITY_SECRET || type == ZT_STATE_OBJECT_IDENTITY_PUBLIC)) {
  1977. if (nodeVaultPutIdentity(type, data, len)) {
  1978. // value successfully written to Vault
  1979. return;
  1980. }
  1981. // else fallback to disk
  1982. }
  1983. #endif
  1984. char p[1024];
  1985. FILE *f;
  1986. bool secure = false;
  1987. char dirname[1024];
  1988. dirname[0] = 0;
  1989. switch(type) {
  1990. case ZT_STATE_OBJECT_IDENTITY_PUBLIC:
  1991. OSUtils::ztsnprintf(p,sizeof(p),"%s" ZT_PATH_SEPARATOR_S "identity.public",_homePath.c_str());
  1992. break;
  1993. case ZT_STATE_OBJECT_IDENTITY_SECRET:
  1994. OSUtils::ztsnprintf(p,sizeof(p),"%s" ZT_PATH_SEPARATOR_S "identity.secret",_homePath.c_str());
  1995. secure = true;
  1996. break;
  1997. case ZT_STATE_OBJECT_PLANET:
  1998. OSUtils::ztsnprintf(p,sizeof(p),"%s" ZT_PATH_SEPARATOR_S "planet",_homePath.c_str());
  1999. break;
  2000. case ZT_STATE_OBJECT_MOON:
  2001. OSUtils::ztsnprintf(dirname,sizeof(dirname),"%s" ZT_PATH_SEPARATOR_S "moons.d",_homePath.c_str());
  2002. OSUtils::ztsnprintf(p,sizeof(p),"%s" ZT_PATH_SEPARATOR_S "%.16llx.moon",dirname,(unsigned long long)id[0]);
  2003. break;
  2004. case ZT_STATE_OBJECT_NETWORK_CONFIG:
  2005. OSUtils::ztsnprintf(dirname,sizeof(dirname),"%s" ZT_PATH_SEPARATOR_S "networks.d",_homePath.c_str());
  2006. OSUtils::ztsnprintf(p,sizeof(p),"%s" ZT_PATH_SEPARATOR_S "%.16llx.conf",dirname,(unsigned long long)id[0]);
  2007. secure = true;
  2008. break;
  2009. case ZT_STATE_OBJECT_PEER:
  2010. OSUtils::ztsnprintf(dirname,sizeof(dirname),"%s" ZT_PATH_SEPARATOR_S "peers.d",_homePath.c_str());
  2011. OSUtils::ztsnprintf(p,sizeof(p),"%s" ZT_PATH_SEPARATOR_S "%.10llx.peer",dirname,(unsigned long long)id[0]);
  2012. break;
  2013. default:
  2014. return;
  2015. }
  2016. if (len >= 0) {
  2017. // Check to see if we've already written this first. This reduces
  2018. // redundant writes and I/O overhead on most platforms and has
  2019. // little effect on others.
  2020. f = fopen(p,"r");
  2021. if (f) {
  2022. char buf[65535];
  2023. long l = (long)fread(buf,1,sizeof(buf),f);
  2024. fclose(f);
  2025. if ((l == (long)len)&&(memcmp(data,buf,l) == 0))
  2026. return;
  2027. }
  2028. f = fopen(p,"w");
  2029. if ((!f)&&(dirname[0])) { // create subdirectory if it does not exist
  2030. OSUtils::mkdir(dirname);
  2031. f = fopen(p,"w");
  2032. }
  2033. if (f) {
  2034. if (fwrite(data,len,1,f) != 1)
  2035. fprintf(stderr,"WARNING: unable to write to file: %s (I/O error)" ZT_EOL_S,p);
  2036. fclose(f);
  2037. if (secure)
  2038. OSUtils::lockDownFile(p,false);
  2039. } else {
  2040. fprintf(stderr,"WARNING: unable to write to file: %s (unable to open)" ZT_EOL_S,p);
  2041. }
  2042. } else {
  2043. OSUtils::rm(p);
  2044. }
  2045. }
  2046. #if ZT_VAULT_SUPPORT
  2047. inline int nodeVaultGetIdentity(enum ZT_StateObjectType type, void *data, unsigned int maxlen)
  2048. {
  2049. if (type != ZT_STATE_OBJECT_IDENTITY_SECRET && type != ZT_STATE_OBJECT_IDENTITY_PUBLIC) {
  2050. return -1;
  2051. }
  2052. int ret = -1;
  2053. CURL *curl = curl_easy_init();
  2054. if (curl) {
  2055. char token[512] = { 0 };
  2056. snprintf(token, sizeof(token), "X-Vault-Token: %s", _vaultToken.c_str());
  2057. struct curl_slist *chunk = NULL;
  2058. chunk = curl_slist_append(chunk, token);
  2059. curl_easy_setopt(curl, CURLOPT_HTTPHEADER, chunk);
  2060. char url[2048] = { 0 };
  2061. snprintf(url, sizeof(url), "%s/v1/%s", _vaultURL.c_str(), _vaultPath.c_str());
  2062. curl_easy_setopt(curl, CURLOPT_URL, url);
  2063. std::string response;
  2064. std::string res_headers;
  2065. curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, &curlResponseWrite);
  2066. curl_easy_setopt(curl, CURLOPT_WRITEDATA, &response);
  2067. curl_easy_setopt(curl, CURLOPT_HEADERDATA, &res_headers);
  2068. #ifndef NDEBUG
  2069. curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L);
  2070. #endif
  2071. CURLcode res = curl_easy_perform(curl);
  2072. if (res == CURLE_OK) {
  2073. long response_code = 0;
  2074. curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &response_code);
  2075. if (response_code == 200) {
  2076. try {
  2077. json payload = json::parse(response);
  2078. if (!payload["data"].is_null()) {
  2079. json &d = payload["data"];
  2080. if (type == ZT_STATE_OBJECT_IDENTITY_SECRET) {
  2081. std::string secret = OSUtils::jsonString(d["secret"],"");
  2082. if (!secret.empty()) {
  2083. ret = (int)secret.length();
  2084. memcpy(data, secret.c_str(), ret);
  2085. }
  2086. }
  2087. else if (type == ZT_STATE_OBJECT_IDENTITY_PUBLIC) {
  2088. std::string pub = OSUtils::jsonString(d["public"],"");
  2089. if (!pub.empty()) {
  2090. ret = (int)pub.length();
  2091. memcpy(data, pub.c_str(), ret);
  2092. }
  2093. }
  2094. }
  2095. }
  2096. catch (...) {
  2097. ret = -1;
  2098. }
  2099. }
  2100. }
  2101. curl_easy_cleanup(curl);
  2102. curl = NULL;
  2103. curl_slist_free_all(chunk);
  2104. chunk = NULL;
  2105. }
  2106. return ret;
  2107. }
  2108. #endif
  2109. inline int nodeStateGetFunction(enum ZT_StateObjectType type,const uint64_t id[2],void *data,unsigned int maxlen)
  2110. {
  2111. #if ZT_VAULT_SUPPORT
  2112. if (_vaultEnabled && (type == ZT_STATE_OBJECT_IDENTITY_SECRET || type == ZT_STATE_OBJECT_IDENTITY_PUBLIC) ) {
  2113. int retval = nodeVaultGetIdentity(type, data, maxlen);
  2114. if (retval >= 0)
  2115. return retval;
  2116. // else continue file based lookup
  2117. }
  2118. #endif
  2119. char p[4096];
  2120. switch(type) {
  2121. case ZT_STATE_OBJECT_IDENTITY_PUBLIC:
  2122. OSUtils::ztsnprintf(p,sizeof(p),"%s" ZT_PATH_SEPARATOR_S "identity.public",_homePath.c_str());
  2123. break;
  2124. case ZT_STATE_OBJECT_IDENTITY_SECRET:
  2125. OSUtils::ztsnprintf(p,sizeof(p),"%s" ZT_PATH_SEPARATOR_S "identity.secret",_homePath.c_str());
  2126. break;
  2127. case ZT_STATE_OBJECT_PLANET:
  2128. OSUtils::ztsnprintf(p,sizeof(p),"%s" ZT_PATH_SEPARATOR_S "planet",_homePath.c_str());
  2129. break;
  2130. case ZT_STATE_OBJECT_MOON:
  2131. OSUtils::ztsnprintf(p,sizeof(p),"%s" ZT_PATH_SEPARATOR_S "moons.d" ZT_PATH_SEPARATOR_S "%.16llx.moon",_homePath.c_str(),(unsigned long long)id);
  2132. break;
  2133. case ZT_STATE_OBJECT_NETWORK_CONFIG:
  2134. 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);
  2135. break;
  2136. case ZT_STATE_OBJECT_PEER:
  2137. 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]);
  2138. break;
  2139. default:
  2140. return -1;
  2141. }
  2142. FILE *f = fopen(p,"r");
  2143. if (f) {
  2144. int n = (int)fread(data,1,maxlen,f);
  2145. fclose(f);
  2146. #if ZT_VAULT_SUPPORT
  2147. if (_vaultEnabled && (type == ZT_STATE_OBJECT_IDENTITY_SECRET || type == ZT_STATE_OBJECT_IDENTITY_PUBLIC)) {
  2148. // If we've gotten here while Vault is enabled, Vault does not know the key and it's been
  2149. // read from disk instead.
  2150. //
  2151. // We should put the value in Vault and remove the local file.
  2152. if (nodeVaultPutIdentity(type, data, n)) {
  2153. unlink(p);
  2154. }
  2155. }
  2156. #endif
  2157. if (n >= 0)
  2158. return n;
  2159. }
  2160. return -1;
  2161. }
  2162. inline int nodeWirePacketSendFunction(const int64_t localSocket,const struct sockaddr_storage *addr,const void *data,unsigned int len,unsigned int ttl)
  2163. {
  2164. #ifdef ZT_TCP_FALLBACK_RELAY
  2165. if(_allowTcpFallbackRelay) {
  2166. if (addr->ss_family == AF_INET) {
  2167. // TCP fallback tunnel support, currently IPv4 only
  2168. if ((len >= 16)&&(reinterpret_cast<const InetAddress *>(addr)->ipScope() == InetAddress::IP_SCOPE_GLOBAL)) {
  2169. // Engage TCP tunnel fallback if we haven't received anything valid from a global
  2170. // IP address in ZT_TCP_FALLBACK_AFTER milliseconds. If we do start getting
  2171. // valid direct traffic we'll stop using it and close the socket after a while.
  2172. const int64_t now = OSUtils::now();
  2173. if (((now - _lastDirectReceiveFromGlobal) > ZT_TCP_FALLBACK_AFTER)&&((now - _lastRestart) > ZT_TCP_FALLBACK_AFTER)) {
  2174. if (_tcpFallbackTunnel) {
  2175. bool flushNow = false;
  2176. {
  2177. Mutex::Lock _l(_tcpFallbackTunnel->writeq_m);
  2178. if (_tcpFallbackTunnel->writeq.size() < (1024 * 64)) {
  2179. if (_tcpFallbackTunnel->writeq.length() == 0) {
  2180. _phy.setNotifyWritable(_tcpFallbackTunnel->sock,true);
  2181. flushNow = true;
  2182. }
  2183. const unsigned long mlen = len + 7;
  2184. _tcpFallbackTunnel->writeq.push_back((char)0x17);
  2185. _tcpFallbackTunnel->writeq.push_back((char)0x03);
  2186. _tcpFallbackTunnel->writeq.push_back((char)0x03); // fake TLS 1.2 header
  2187. _tcpFallbackTunnel->writeq.push_back((char)((mlen >> 8) & 0xff));
  2188. _tcpFallbackTunnel->writeq.push_back((char)(mlen & 0xff));
  2189. _tcpFallbackTunnel->writeq.push_back((char)4); // IPv4
  2190. _tcpFallbackTunnel->writeq.append(reinterpret_cast<const char *>(reinterpret_cast<const void *>(&(reinterpret_cast<const struct sockaddr_in *>(addr)->sin_addr.s_addr))),4);
  2191. _tcpFallbackTunnel->writeq.append(reinterpret_cast<const char *>(reinterpret_cast<const void *>(&(reinterpret_cast<const struct sockaddr_in *>(addr)->sin_port))),2);
  2192. _tcpFallbackTunnel->writeq.append((const char *)data,len);
  2193. }
  2194. }
  2195. if (flushNow) {
  2196. void *tmpptr = (void *)_tcpFallbackTunnel;
  2197. phyOnTcpWritable(_tcpFallbackTunnel->sock,&tmpptr);
  2198. }
  2199. } else if (((now - _lastSendToGlobalV4) < ZT_TCP_FALLBACK_AFTER)&&((now - _lastSendToGlobalV4) > (ZT_PING_CHECK_INVERVAL / 2))) {
  2200. const InetAddress addr(ZT_TCP_FALLBACK_RELAY);
  2201. TcpConnection *tc = new TcpConnection();
  2202. {
  2203. Mutex::Lock _l(_tcpConnections_m);
  2204. _tcpConnections.push_back(tc);
  2205. }
  2206. tc->type = TcpConnection::TCP_TUNNEL_OUTGOING;
  2207. tc->remoteAddr = addr;
  2208. tc->lastReceive = OSUtils::now();
  2209. tc->parent = this;
  2210. tc->sock = (PhySocket *)0; // set in connect handler
  2211. tc->messageSize = 0;
  2212. bool connected = false;
  2213. _phy.tcpConnect(reinterpret_cast<const struct sockaddr *>(&addr),connected,(void *)tc,true);
  2214. }
  2215. }
  2216. _lastSendToGlobalV4 = now;
  2217. }
  2218. }
  2219. }
  2220. #endif // ZT_TCP_FALLBACK_RELAY
  2221. // Even when relaying we still send via UDP. This way if UDP starts
  2222. // working we can instantly "fail forward" to it and stop using TCP
  2223. // proxy fallback, which is slow.
  2224. if ((localSocket != -1)&&(localSocket != 0)&&(_binder.isUdpSocketValid((PhySocket *)((uintptr_t)localSocket)))) {
  2225. if ((ttl)&&(addr->ss_family == AF_INET)) _phy.setIp4UdpTtl((PhySocket *)((uintptr_t)localSocket),ttl);
  2226. const bool r = _phy.udpSend((PhySocket *)((uintptr_t)localSocket),(const struct sockaddr *)addr,data,len);
  2227. if ((ttl)&&(addr->ss_family == AF_INET)) _phy.setIp4UdpTtl((PhySocket *)((uintptr_t)localSocket),255);
  2228. return ((r) ? 0 : -1);
  2229. } else {
  2230. return ((_binder.udpSendAll(_phy,addr,data,len,ttl)) ? 0 : -1);
  2231. }
  2232. }
  2233. 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)
  2234. {
  2235. NetworkState *n = reinterpret_cast<NetworkState *>(*nuptr);
  2236. if ((!n)||(!n->tap))
  2237. return;
  2238. n->tap->put(MAC(sourceMac),MAC(destMac),etherType,data,len);
  2239. }
  2240. inline int nodePathCheckFunction(uint64_t ztaddr,const int64_t localSocket,const struct sockaddr_storage *remoteAddr)
  2241. {
  2242. // Make sure we're not trying to do ZeroTier-over-ZeroTier
  2243. {
  2244. Mutex::Lock _l(_nets_m);
  2245. for(std::map<uint64_t,NetworkState>::const_iterator n(_nets.begin());n!=_nets.end();++n) {
  2246. if (n->second.tap) {
  2247. std::vector<InetAddress> ips(n->second.tap->ips());
  2248. for(std::vector<InetAddress>::const_iterator i(ips.begin());i!=ips.end();++i) {
  2249. if (i->containsAddress(*(reinterpret_cast<const InetAddress *>(remoteAddr)))) {
  2250. return 0;
  2251. }
  2252. }
  2253. }
  2254. }
  2255. }
  2256. /* Note: I do not think we need to scan for overlap with managed routes
  2257. * because of the "route forking" and interface binding that we do. This
  2258. * ensures (we hope) that ZeroTier traffic will still take the physical
  2259. * path even if its managed routes override this for other traffic. Will
  2260. * revisit if we see recursion problems. */
  2261. // Check blacklists
  2262. const Hashtable< uint64_t,std::vector<InetAddress> > *blh = (const Hashtable< uint64_t,std::vector<InetAddress> > *)0;
  2263. const std::vector<InetAddress> *gbl = (const std::vector<InetAddress> *)0;
  2264. if (remoteAddr->ss_family == AF_INET) {
  2265. blh = &_v4Blacklists;
  2266. gbl = &_globalV4Blacklist;
  2267. } else if (remoteAddr->ss_family == AF_INET6) {
  2268. blh = &_v6Blacklists;
  2269. gbl = &_globalV6Blacklist;
  2270. }
  2271. if (blh) {
  2272. Mutex::Lock _l(_localConfig_m);
  2273. const std::vector<InetAddress> *l = blh->get(ztaddr);
  2274. if (l) {
  2275. for(std::vector<InetAddress>::const_iterator a(l->begin());a!=l->end();++a) {
  2276. if (a->containsAddress(*reinterpret_cast<const InetAddress *>(remoteAddr)))
  2277. return 0;
  2278. }
  2279. }
  2280. }
  2281. if (gbl) {
  2282. for(std::vector<InetAddress>::const_iterator a(gbl->begin());a!=gbl->end();++a) {
  2283. if (a->containsAddress(*reinterpret_cast<const InetAddress *>(remoteAddr)))
  2284. return 0;
  2285. }
  2286. }
  2287. return 1;
  2288. }
  2289. inline int nodePathLookupFunction(uint64_t ztaddr,int family,struct sockaddr_storage *result)
  2290. {
  2291. const Hashtable< uint64_t,std::vector<InetAddress> > *lh = (const Hashtable< uint64_t,std::vector<InetAddress> > *)0;
  2292. if (family < 0)
  2293. lh = (_node->prng() & 1) ? &_v4Hints : &_v6Hints;
  2294. else if (family == AF_INET)
  2295. lh = &_v4Hints;
  2296. else if (family == AF_INET6)
  2297. lh = &_v6Hints;
  2298. else return 0;
  2299. const std::vector<InetAddress> *l = lh->get(ztaddr);
  2300. if ((l)&&(l->size() > 0)) {
  2301. ZT_FAST_MEMCPY(result,&((*l)[(unsigned long)_node->prng() % l->size()]),sizeof(struct sockaddr_storage));
  2302. return 1;
  2303. } else return 0;
  2304. }
  2305. inline void tapFrameHandler(uint64_t nwid,const MAC &from,const MAC &to,unsigned int etherType,unsigned int vlanId,const void *data,unsigned int len)
  2306. {
  2307. _node->processVirtualNetworkFrame((void *)0,OSUtils::now(),nwid,from.toInt(),to.toInt(),etherType,vlanId,data,len,&_nextBackgroundTaskDeadline);
  2308. }
  2309. inline void onHttpRequestToServer(TcpConnection *tc)
  2310. {
  2311. char tmpn[4096];
  2312. std::string data;
  2313. std::string contentType("text/plain"); // default if not changed in handleRequest()
  2314. unsigned int scode = 404;
  2315. // Note that we check allowed IP ranges when HTTP connections are first detected in
  2316. // phyOnTcpData(). If we made it here the source IP is okay.
  2317. try {
  2318. scode = handleControlPlaneHttpRequest(tc->remoteAddr,tc->parser.method,tc->url,tc->headers,tc->readq,data,contentType);
  2319. } catch (std::exception &exc) {
  2320. fprintf(stderr,"WARNING: unexpected exception processing control HTTP request: %s" ZT_EOL_S,exc.what());
  2321. scode = 500;
  2322. } catch ( ... ) {
  2323. fprintf(stderr,"WARNING: unexpected exception processing control HTTP request: unknown exception" ZT_EOL_S);
  2324. scode = 500;
  2325. }
  2326. const char *scodestr;
  2327. switch(scode) {
  2328. case 200: scodestr = "OK"; break;
  2329. case 400: scodestr = "Bad Request"; break;
  2330. case 401: scodestr = "Unauthorized"; break;
  2331. case 403: scodestr = "Forbidden"; break;
  2332. case 404: scodestr = "Not Found"; break;
  2333. case 500: scodestr = "Internal Server Error"; break;
  2334. case 501: scodestr = "Not Implemented"; break;
  2335. case 503: scodestr = "Service Unavailable"; break;
  2336. default: scodestr = "Error"; break;
  2337. }
  2338. 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",
  2339. scode,
  2340. scodestr,
  2341. contentType.c_str(),
  2342. (unsigned long)data.length());
  2343. {
  2344. Mutex::Lock _l(tc->writeq_m);
  2345. tc->writeq = tmpn;
  2346. if (tc->parser.method != HTTP_HEAD)
  2347. tc->writeq.append(data);
  2348. }
  2349. _phy.setNotifyWritable(tc->sock,true);
  2350. }
  2351. inline void onHttpResponseFromClient(TcpConnection *tc)
  2352. {
  2353. _phy.close(tc->sock);
  2354. }
  2355. bool shouldBindInterface(const char *ifname,const InetAddress &ifaddr)
  2356. {
  2357. #if defined(__linux__) || defined(linux) || defined(__LINUX__) || defined(__linux)
  2358. if ((ifname[0] == 'l')&&(ifname[1] == 'o')) return false; // loopback
  2359. if ((ifname[0] == 'z')&&(ifname[1] == 't')) return false; // sanity check: zt#
  2360. if ((ifname[0] == 't')&&(ifname[1] == 'u')&&(ifname[2] == 'n')) return false; // tun# is probably an OpenVPN tunnel or similar
  2361. if ((ifname[0] == 't')&&(ifname[1] == 'a')&&(ifname[2] == 'p')) return false; // tap# is probably an OpenVPN tunnel or similar
  2362. #endif
  2363. #ifdef __APPLE__
  2364. if ((ifname[0] == 'l')&&(ifname[1] == 'o')) return false; // loopback
  2365. if ((ifname[0] == 'z')&&(ifname[1] == 't')) return false; // sanity check: zt#
  2366. if ((ifname[0] == 't')&&(ifname[1] == 'u')&&(ifname[2] == 'n')) return false; // tun# is probably an OpenVPN tunnel or similar
  2367. if ((ifname[0] == 't')&&(ifname[1] == 'a')&&(ifname[2] == 'p')) return false; // tap# is probably an OpenVPN tunnel or similar
  2368. if ((ifname[0] == 'u')&&(ifname[1] == 't')&&(ifname[2] == 'u')&&(ifname[3] == 'n')) return false; // ... as is utun#
  2369. #endif
  2370. {
  2371. Mutex::Lock _l(_localConfig_m);
  2372. for(std::vector<std::string>::const_iterator p(_interfacePrefixBlacklist.begin());p!=_interfacePrefixBlacklist.end();++p) {
  2373. if (!strncmp(p->c_str(),ifname,p->length()))
  2374. return false;
  2375. }
  2376. }
  2377. {
  2378. Mutex::Lock _l(_nets_m);
  2379. for(std::map<uint64_t,NetworkState>::const_iterator n(_nets.begin());n!=_nets.end();++n) {
  2380. if (n->second.tap) {
  2381. std::vector<InetAddress> ips(n->second.tap->ips());
  2382. for(std::vector<InetAddress>::const_iterator i(ips.begin());i!=ips.end();++i) {
  2383. if (i->ipsEqual(ifaddr))
  2384. return false;
  2385. }
  2386. }
  2387. }
  2388. }
  2389. return true;
  2390. }
  2391. bool _trialBind(unsigned int port)
  2392. {
  2393. struct sockaddr_in in4;
  2394. struct sockaddr_in6 in6;
  2395. PhySocket *tb;
  2396. memset(&in4,0,sizeof(in4));
  2397. in4.sin_family = AF_INET;
  2398. in4.sin_port = Utils::hton((uint16_t)port);
  2399. tb = _phy.udpBind(reinterpret_cast<const struct sockaddr *>(&in4),(void *)0,0);
  2400. if (tb) {
  2401. _phy.close(tb,false);
  2402. tb = _phy.tcpListen(reinterpret_cast<const struct sockaddr *>(&in4),(void *)0);
  2403. if (tb) {
  2404. _phy.close(tb,false);
  2405. return true;
  2406. }
  2407. }
  2408. memset(&in6,0,sizeof(in6));
  2409. in6.sin6_family = AF_INET6;
  2410. in6.sin6_port = Utils::hton((uint16_t)port);
  2411. tb = _phy.udpBind(reinterpret_cast<const struct sockaddr *>(&in6),(void *)0,0);
  2412. if (tb) {
  2413. _phy.close(tb,false);
  2414. tb = _phy.tcpListen(reinterpret_cast<const struct sockaddr *>(&in6),(void *)0);
  2415. if (tb) {
  2416. _phy.close(tb,false);
  2417. return true;
  2418. }
  2419. }
  2420. return false;
  2421. }
  2422. };
  2423. static int SnodeVirtualNetworkConfigFunction(ZT_Node *node,void *uptr,void *tptr,uint64_t nwid,void **nuptr,enum ZT_VirtualNetworkConfigOperation op,const ZT_VirtualNetworkConfig *nwconf)
  2424. { return reinterpret_cast<OneServiceImpl *>(uptr)->nodeVirtualNetworkConfigFunction(nwid,nuptr,op,nwconf); }
  2425. static void SnodeEventCallback(ZT_Node *node,void *uptr,void *tptr,enum ZT_Event event,const void *metaData)
  2426. { reinterpret_cast<OneServiceImpl *>(uptr)->nodeEventCallback(event,metaData); }
  2427. static void SnodeStatePutFunction(ZT_Node *node,void *uptr,void *tptr,enum ZT_StateObjectType type,const uint64_t id[2],const void *data,int len)
  2428. { reinterpret_cast<OneServiceImpl *>(uptr)->nodeStatePutFunction(type,id,data,len); }
  2429. static int SnodeStateGetFunction(ZT_Node *node,void *uptr,void *tptr,enum ZT_StateObjectType type,const uint64_t id[2],void *data,unsigned int maxlen)
  2430. { return reinterpret_cast<OneServiceImpl *>(uptr)->nodeStateGetFunction(type,id,data,maxlen); }
  2431. 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)
  2432. { return reinterpret_cast<OneServiceImpl *>(uptr)->nodeWirePacketSendFunction(localSocket,addr,data,len,ttl); }
  2433. 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)
  2434. { reinterpret_cast<OneServiceImpl *>(uptr)->nodeVirtualNetworkFrameFunction(nwid,nuptr,sourceMac,destMac,etherType,vlanId,data,len); }
  2435. static int SnodePathCheckFunction(ZT_Node *node,void *uptr,void *tptr,uint64_t ztaddr,int64_t localSocket,const struct sockaddr_storage *remoteAddr)
  2436. { return reinterpret_cast<OneServiceImpl *>(uptr)->nodePathCheckFunction(ztaddr,localSocket,remoteAddr); }
  2437. static int SnodePathLookupFunction(ZT_Node *node,void *uptr,void *tptr,uint64_t ztaddr,int family,struct sockaddr_storage *result)
  2438. { return reinterpret_cast<OneServiceImpl *>(uptr)->nodePathLookupFunction(ztaddr,family,result); }
  2439. 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)
  2440. { reinterpret_cast<OneServiceImpl *>(uptr)->tapFrameHandler(nwid,from,to,etherType,vlanId,data,len); }
  2441. static int ShttpOnMessageBegin(http_parser *parser)
  2442. {
  2443. TcpConnection *tc = reinterpret_cast<TcpConnection *>(parser->data);
  2444. tc->currentHeaderField = "";
  2445. tc->currentHeaderValue = "";
  2446. tc->messageSize = 0;
  2447. tc->url.clear();
  2448. tc->status.clear();
  2449. tc->headers.clear();
  2450. tc->readq.clear();
  2451. return 0;
  2452. }
  2453. static int ShttpOnUrl(http_parser *parser,const char *ptr,size_t length)
  2454. {
  2455. TcpConnection *tc = reinterpret_cast<TcpConnection *>(parser->data);
  2456. tc->messageSize += (unsigned long)length;
  2457. if (tc->messageSize > ZT_MAX_HTTP_MESSAGE_SIZE)
  2458. return -1;
  2459. tc->url.append(ptr,length);
  2460. return 0;
  2461. }
  2462. #if (HTTP_PARSER_VERSION_MAJOR >= 2) && (HTTP_PARSER_VERSION_MINOR >= 2)
  2463. static int ShttpOnStatus(http_parser *parser,const char *ptr,size_t length)
  2464. #else
  2465. static int ShttpOnStatus(http_parser *parser)
  2466. #endif
  2467. { return 0; }
  2468. static int ShttpOnHeaderField(http_parser *parser,const char *ptr,size_t length)
  2469. {
  2470. TcpConnection *tc = reinterpret_cast<TcpConnection *>(parser->data);
  2471. tc->messageSize += (unsigned long)length;
  2472. if (tc->messageSize > ZT_MAX_HTTP_MESSAGE_SIZE)
  2473. return -1;
  2474. if ((tc->currentHeaderField.length())&&(tc->currentHeaderValue.length())) {
  2475. tc->headers[tc->currentHeaderField] = tc->currentHeaderValue;
  2476. tc->currentHeaderField = "";
  2477. tc->currentHeaderValue = "";
  2478. }
  2479. for(size_t i=0;i<length;++i)
  2480. tc->currentHeaderField.push_back(OSUtils::toLower(ptr[i]));
  2481. return 0;
  2482. }
  2483. static int ShttpOnValue(http_parser *parser,const char *ptr,size_t length)
  2484. {
  2485. TcpConnection *tc = reinterpret_cast<TcpConnection *>(parser->data);
  2486. tc->messageSize += (unsigned long)length;
  2487. if (tc->messageSize > ZT_MAX_HTTP_MESSAGE_SIZE)
  2488. return -1;
  2489. tc->currentHeaderValue.append(ptr,length);
  2490. return 0;
  2491. }
  2492. static int ShttpOnHeadersComplete(http_parser *parser)
  2493. {
  2494. TcpConnection *tc = reinterpret_cast<TcpConnection *>(parser->data);
  2495. if ((tc->currentHeaderField.length())&&(tc->currentHeaderValue.length()))
  2496. tc->headers[tc->currentHeaderField] = tc->currentHeaderValue;
  2497. return 0;
  2498. }
  2499. static int ShttpOnBody(http_parser *parser,const char *ptr,size_t length)
  2500. {
  2501. TcpConnection *tc = reinterpret_cast<TcpConnection *>(parser->data);
  2502. tc->messageSize += (unsigned long)length;
  2503. if (tc->messageSize > ZT_MAX_HTTP_MESSAGE_SIZE)
  2504. return -1;
  2505. tc->readq.append(ptr,length);
  2506. return 0;
  2507. }
  2508. static int ShttpOnMessageComplete(http_parser *parser)
  2509. {
  2510. TcpConnection *tc = reinterpret_cast<TcpConnection *>(parser->data);
  2511. if (tc->type == TcpConnection::TCP_HTTP_INCOMING) {
  2512. tc->parent->onHttpRequestToServer(tc);
  2513. } else {
  2514. tc->parent->onHttpResponseFromClient(tc);
  2515. }
  2516. return 0;
  2517. }
  2518. } // anonymous namespace
  2519. std::string OneService::platformDefaultHomePath()
  2520. {
  2521. return OSUtils::platformDefaultHomePath();
  2522. }
  2523. OneService *OneService::newInstance(const char *hp,unsigned int port) { return new OneServiceImpl(hp,port); }
  2524. OneService::~OneService() {}
  2525. } // namespace ZeroTier