OneService.cpp 100 KB

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