OneService.cpp 113 KB

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