OneService.cpp 89 KB

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