OneService.cpp 102 KB

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