OneService.cpp 113 KB

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