OneService.cpp 100 KB

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