OneService.cpp 101 KB

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