OneService.cpp 109 KB

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