OneService.cpp 90 KB

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