OneService.cpp 99 KB

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