OneService.cpp 93 KB

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