OneService.cpp 98 KB

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