OneService.cpp 99 KB

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