OneService.cpp 114 KB

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