OneService.cpp 88 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548
  1. /*
  2. * ZeroTier One - Network Virtualization Everywhere
  3. * Copyright (C) 2011-2017 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["linkQuality"] = (double)peer->paths[i].linkQuality / (double)ZT_PATH_LINK_QUALITY_MAX;
  233. j["active"] = (bool)(peer->paths[i].expired == 0);
  234. j["expired"] = (bool)(peer->paths[i].expired != 0);
  235. j["preferred"] = (bool)(peer->paths[i].preferred != 0);
  236. pa.push_back(j);
  237. }
  238. pj["paths"] = pa;
  239. }
  240. static void _moonToJson(nlohmann::json &mj,const World &world)
  241. {
  242. char tmp[4096];
  243. OSUtils::ztsnprintf(tmp,sizeof(tmp),"%.16llx",world.id());
  244. mj["id"] = tmp;
  245. mj["timestamp"] = world.timestamp();
  246. mj["signature"] = Utils::hex(world.signature().data,(unsigned int)world.signature().size(),tmp);
  247. mj["updatesMustBeSignedBy"] = Utils::hex(world.updatesMustBeSignedBy().data,(unsigned int)world.updatesMustBeSignedBy().size(),tmp);
  248. nlohmann::json ra = nlohmann::json::array();
  249. for(std::vector<World::Root>::const_iterator r(world.roots().begin());r!=world.roots().end();++r) {
  250. nlohmann::json rj;
  251. rj["identity"] = r->identity.toString(false,tmp);
  252. nlohmann::json eps = nlohmann::json::array();
  253. for(std::vector<InetAddress>::const_iterator a(r->stableEndpoints.begin());a!=r->stableEndpoints.end();++a)
  254. eps.push_back(a->toString(tmp));
  255. rj["stableEndpoints"] = eps;
  256. ra.push_back(rj);
  257. }
  258. mj["roots"] = ra;
  259. mj["waiting"] = false;
  260. }
  261. class OneServiceImpl;
  262. static int SnodeVirtualNetworkConfigFunction(ZT_Node *node,void *uptr,void *tptr,uint64_t nwid,void **nuptr,enum ZT_VirtualNetworkConfigOperation op,const ZT_VirtualNetworkConfig *nwconf);
  263. static void SnodeEventCallback(ZT_Node *node,void *uptr,void *tptr,enum ZT_Event event,const void *metaData);
  264. static void SnodeStatePutFunction(ZT_Node *node,void *uptr,void *tptr,enum ZT_StateObjectType type,const uint64_t id[2],const void *data,int len);
  265. static int SnodeStateGetFunction(ZT_Node *node,void *uptr,void *tptr,enum ZT_StateObjectType type,const uint64_t id[2],void *data,unsigned int maxlen);
  266. 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);
  267. 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);
  268. static int SnodePathCheckFunction(ZT_Node *node,void *uptr,void *tptr,uint64_t ztaddr,int64_t localSocket,const struct sockaddr_storage *remoteAddr);
  269. static int SnodePathLookupFunction(ZT_Node *node,void *uptr,void *tptr,uint64_t ztaddr,int family,struct sockaddr_storage *result);
  270. 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);
  271. static int ShttpOnMessageBegin(http_parser *parser);
  272. static int ShttpOnUrl(http_parser *parser,const char *ptr,size_t length);
  273. #if (HTTP_PARSER_VERSION_MAJOR >= 2) && (HTTP_PARSER_VERSION_MINOR >= 2)
  274. static int ShttpOnStatus(http_parser *parser,const char *ptr,size_t length);
  275. #else
  276. static int ShttpOnStatus(http_parser *parser);
  277. #endif
  278. static int ShttpOnHeaderField(http_parser *parser,const char *ptr,size_t length);
  279. static int ShttpOnValue(http_parser *parser,const char *ptr,size_t length);
  280. static int ShttpOnHeadersComplete(http_parser *parser);
  281. static int ShttpOnBody(http_parser *parser,const char *ptr,size_t length);
  282. static int ShttpOnMessageComplete(http_parser *parser);
  283. #if (HTTP_PARSER_VERSION_MAJOR >= 2) && (HTTP_PARSER_VERSION_MINOR >= 1)
  284. static const struct http_parser_settings HTTP_PARSER_SETTINGS = {
  285. ShttpOnMessageBegin,
  286. ShttpOnUrl,
  287. ShttpOnStatus,
  288. ShttpOnHeaderField,
  289. ShttpOnValue,
  290. ShttpOnHeadersComplete,
  291. ShttpOnBody,
  292. ShttpOnMessageComplete
  293. };
  294. #else
  295. static const struct http_parser_settings HTTP_PARSER_SETTINGS = {
  296. ShttpOnMessageBegin,
  297. ShttpOnUrl,
  298. ShttpOnHeaderField,
  299. ShttpOnValue,
  300. ShttpOnHeadersComplete,
  301. ShttpOnBody,
  302. ShttpOnMessageComplete
  303. };
  304. #endif
  305. /**
  306. * A TCP connection and related state and buffers
  307. */
  308. struct TcpConnection
  309. {
  310. enum {
  311. TCP_UNCATEGORIZED_INCOMING, // uncategorized incoming connection
  312. TCP_HTTP_INCOMING,
  313. TCP_HTTP_OUTGOING,
  314. TCP_TUNNEL_OUTGOING // TUNNELED mode proxy outbound connection
  315. } type;
  316. OneServiceImpl *parent;
  317. PhySocket *sock;
  318. InetAddress remoteAddr;
  319. uint64_t lastReceive;
  320. // Used for inbound HTTP connections
  321. http_parser parser;
  322. unsigned long messageSize;
  323. std::string currentHeaderField;
  324. std::string currentHeaderValue;
  325. std::string url;
  326. std::string status;
  327. std::map< std::string,std::string > headers;
  328. std::string readq;
  329. std::string writeq;
  330. Mutex writeq_m;
  331. };
  332. class OneServiceImpl : public OneService
  333. {
  334. public:
  335. // begin member variables --------------------------------------------------
  336. const std::string _homePath;
  337. std::string _authToken;
  338. std::string _controllerDbPath;
  339. const std::string _networksPath;
  340. const std::string _moonsPath;
  341. EmbeddedNetworkController *_controller;
  342. Phy<OneServiceImpl *> _phy;
  343. Node *_node;
  344. SoftwareUpdater *_updater;
  345. PhySocket *_localControlSocket4;
  346. PhySocket *_localControlSocket6;
  347. bool _updateAutoApply;
  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.ipScope() != InetAddress::IP_SCOPE_GLOBAL) && (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. Mutex::Lock _l(_nets_m);
  735. for(std::map<uint64_t,NetworkState>::const_iterator n(_nets.begin());n!=_nets.end();++n) {
  736. if (n->second.tap) {
  737. std::vector<MulticastGroup> added,removed;
  738. n->second.tap->scanMulticastGroups(added,removed);
  739. for(std::vector<MulticastGroup>::iterator m(added.begin());m!=added.end();++m)
  740. _node->multicastSubscribe((void *)0,n->first,m->mac().toInt(),m->adi());
  741. for(std::vector<MulticastGroup>::iterator m(removed.begin());m!=removed.end();++m)
  742. _node->multicastUnsubscribe(n->first,m->mac().toInt(),m->adi());
  743. }
  744. }
  745. }
  746. // Sync information about physical network interfaces
  747. if ((now - lastLocalInterfaceAddressCheck) >= ZT_LOCAL_INTERFACE_CHECK_INTERVAL) {
  748. lastLocalInterfaceAddressCheck = now;
  749. _node->clearLocalInterfaceAddresses();
  750. #ifdef ZT_USE_MINIUPNPC
  751. if (_portMapper) {
  752. std::vector<InetAddress> mappedAddresses(_portMapper->get());
  753. for(std::vector<InetAddress>::const_iterator ext(mappedAddresses.begin());ext!=mappedAddresses.end();++ext)
  754. _node->addLocalInterfaceAddress(reinterpret_cast<const struct sockaddr_storage *>(&(*ext)));
  755. }
  756. #endif
  757. std::vector<InetAddress> boundAddrs(_binder.allBoundLocalInterfaceAddresses());
  758. for(std::vector<InetAddress>::const_iterator i(boundAddrs.begin());i!=boundAddrs.end();++i)
  759. _node->addLocalInterfaceAddress(reinterpret_cast<const struct sockaddr_storage *>(&(*i)));
  760. }
  761. // Clean peers.d periodically
  762. if ((now - lastCleanedPeersDb) >= 3600000) {
  763. lastCleanedPeersDb = now;
  764. OSUtils::cleanDirectory((_homePath + ZT_PATH_SEPARATOR_S "peers.d").c_str(),now - 2592000000LL); // delete older than 30 days
  765. }
  766. const unsigned long delay = (dl > now) ? (unsigned long)(dl - now) : 100;
  767. clockShouldBe = now + (uint64_t)delay;
  768. _phy.poll(delay);
  769. }
  770. } catch (std::exception &e) {
  771. Mutex::Lock _l(_termReason_m);
  772. _termReason = ONE_UNRECOVERABLE_ERROR;
  773. _fatalErrorMessage = std::string("unexpected exception in main thread: ")+e.what();
  774. } catch ( ... ) {
  775. Mutex::Lock _l(_termReason_m);
  776. _termReason = ONE_UNRECOVERABLE_ERROR;
  777. _fatalErrorMessage = "unexpected exception in main thread: unknown exception";
  778. }
  779. try {
  780. Mutex::Lock _l(_tcpConnections_m);
  781. while (!_tcpConnections.empty())
  782. _phy.close((*_tcpConnections.begin())->sock);
  783. } catch ( ... ) {}
  784. {
  785. Mutex::Lock _l(_nets_m);
  786. for(std::map<uint64_t,NetworkState>::iterator n(_nets.begin());n!=_nets.end();++n)
  787. delete n->second.tap;
  788. _nets.clear();
  789. }
  790. delete _updater;
  791. _updater = (SoftwareUpdater *)0;
  792. delete _node;
  793. _node = (Node *)0;
  794. return _termReason;
  795. }
  796. virtual ReasonForTermination reasonForTermination() const
  797. {
  798. Mutex::Lock _l(_termReason_m);
  799. return _termReason;
  800. }
  801. virtual std::string fatalErrorMessage() const
  802. {
  803. Mutex::Lock _l(_termReason_m);
  804. return _fatalErrorMessage;
  805. }
  806. virtual std::string portDeviceName(uint64_t nwid) const
  807. {
  808. Mutex::Lock _l(_nets_m);
  809. std::map<uint64_t,NetworkState>::const_iterator n(_nets.find(nwid));
  810. if ((n != _nets.end())&&(n->second.tap))
  811. return n->second.tap->deviceName();
  812. else return std::string();
  813. }
  814. #ifdef ZT_SDK
  815. virtual void leave(const uint64_t hp)
  816. {
  817. _node->leave(hp, NULL, NULL);
  818. }
  819. virtual void join(const uint64_t hp)
  820. {
  821. _node->join(hp, NULL, NULL);
  822. }
  823. virtual std::string givenHomePath()
  824. {
  825. return _homePath;
  826. }
  827. std::vector<ZT_VirtualNetworkRoute> *getRoutes(uint64_t nwid)
  828. {
  829. Mutex::Lock _l(_nets_m);
  830. NetworkState &n = _nets[nwid];
  831. std::vector<ZT_VirtualNetworkRoute> *routes = new std::vector<ZT_VirtualNetworkRoute>();
  832. for(int i=0; i<ZT_MAX_NETWORK_ROUTES; i++) {
  833. routes->push_back(n.config.routes[i]);
  834. }
  835. return routes;
  836. }
  837. virtual Node *getNode()
  838. {
  839. return _node;
  840. }
  841. virtual void removeNets()
  842. {
  843. Mutex::Lock _l(_nets_m);
  844. std::map<uint64_t,NetworkState>::iterator i;
  845. for(i = _nets.begin(); i != _nets.end(); i++)
  846. delete i->second.tap;
  847. }
  848. #endif // ZT_SDK
  849. virtual void terminate()
  850. {
  851. _run_m.lock();
  852. _run = false;
  853. _run_m.unlock();
  854. _phy.whack();
  855. }
  856. virtual bool getNetworkSettings(const uint64_t nwid,NetworkSettings &settings) const
  857. {
  858. Mutex::Lock _l(_nets_m);
  859. std::map<uint64_t,NetworkState>::const_iterator n(_nets.find(nwid));
  860. if (n == _nets.end())
  861. return false;
  862. settings = n->second.settings;
  863. return true;
  864. }
  865. virtual bool setNetworkSettings(const uint64_t nwid,const NetworkSettings &settings)
  866. {
  867. Mutex::Lock _l(_nets_m);
  868. std::map<uint64_t,NetworkState>::iterator n(_nets.find(nwid));
  869. if (n == _nets.end())
  870. return false;
  871. n->second.settings = settings;
  872. char nlcpath[4096];
  873. OSUtils::ztsnprintf(nlcpath,sizeof(nlcpath),"%s" ZT_PATH_SEPARATOR_S "%.16llx.local.conf",_networksPath.c_str(),nwid);
  874. FILE *out = fopen(nlcpath,"w");
  875. if (out) {
  876. fprintf(out,"allowManaged=%d\n",(int)n->second.settings.allowManaged);
  877. fprintf(out,"allowGlobal=%d\n",(int)n->second.settings.allowGlobal);
  878. fprintf(out,"allowDefault=%d\n",(int)n->second.settings.allowDefault);
  879. fclose(out);
  880. }
  881. if (n->second.tap)
  882. syncManagedStuff(n->second,true,true);
  883. return true;
  884. }
  885. // =========================================================================
  886. // Internal implementation methods for control plane, route setup, etc.
  887. // =========================================================================
  888. inline unsigned int handleControlPlaneHttpRequest(
  889. const InetAddress &fromAddress,
  890. unsigned int httpMethod,
  891. const std::string &path,
  892. const std::map<std::string,std::string> &headers,
  893. const std::string &body,
  894. std::string &responseBody,
  895. std::string &responseContentType)
  896. {
  897. char tmp[256];
  898. unsigned int scode = 404;
  899. json res;
  900. std::vector<std::string> ps(OSUtils::split(path.c_str(),"/","",""));
  901. std::map<std::string,std::string> urlArgs;
  902. /* Note: this is kind of restricted in what it'll take. It does not support
  903. * URL encoding, and /'s in URL args will screw it up. But the only URL args
  904. * it really uses in ?jsonp=funcionName, and otherwise it just takes simple
  905. * paths to simply-named resources. */
  906. if (ps.size() > 0) {
  907. std::size_t qpos = ps[ps.size() - 1].find('?');
  908. if (qpos != std::string::npos) {
  909. std::string args(ps[ps.size() - 1].substr(qpos + 1));
  910. ps[ps.size() - 1] = ps[ps.size() - 1].substr(0,qpos);
  911. std::vector<std::string> asplit(OSUtils::split(args.c_str(),"&","",""));
  912. for(std::vector<std::string>::iterator a(asplit.begin());a!=asplit.end();++a) {
  913. std::size_t eqpos = a->find('=');
  914. if (eqpos == std::string::npos)
  915. urlArgs[*a] = "";
  916. else urlArgs[a->substr(0,eqpos)] = a->substr(eqpos + 1);
  917. }
  918. }
  919. }
  920. bool isAuth = false;
  921. {
  922. std::map<std::string,std::string>::const_iterator ah(headers.find("x-zt1-auth"));
  923. if ((ah != headers.end())&&(_authToken == ah->second)) {
  924. isAuth = true;
  925. } else {
  926. ah = urlArgs.find("auth");
  927. if ((ah != urlArgs.end())&&(_authToken == ah->second))
  928. isAuth = true;
  929. }
  930. }
  931. #ifdef __SYNOLOGY__
  932. // Authenticate via Synology's built-in cgi script
  933. if (!isAuth) {
  934. /*
  935. fprintf(stderr, "path = %s\n", path.c_str());
  936. fprintf(stderr, "headers.size=%d\n", headers.size());
  937. std::map<std::string, std::string>::const_iterator it(headers.begin());
  938. while(it != headers.end()) {
  939. fprintf(stderr,"header[%s] = %s\n", (it->first).c_str(), (it->second).c_str());
  940. it++;
  941. }
  942. */
  943. // parse out url args
  944. int synotoken_pos = path.find("SynoToken");
  945. int argpos = path.find("?");
  946. if(synotoken_pos != std::string::npos && argpos != std::string::npos) {
  947. std::string cookie = path.substr(argpos+1, synotoken_pos-(argpos+1));
  948. std::string synotoken = path.substr(synotoken_pos);
  949. std::string cookie_val = cookie.substr(cookie.find("=")+1);
  950. std::string synotoken_val = synotoken.substr(synotoken.find("=")+1);
  951. // Set necessary env for auth script
  952. std::map<std::string,std::string>::const_iterator ah2(headers.find("x-forwarded-for"));
  953. setenv("HTTP_COOKIE", cookie_val.c_str(), true);
  954. setenv("HTTP_X_SYNO_TOKEN", synotoken_val.c_str(), true);
  955. setenv("REMOTE_ADDR", ah2->second.c_str(),true);
  956. //fprintf(stderr, "HTTP_COOKIE: %s\n",std::getenv ("HTTP_COOKIE"));
  957. //fprintf(stderr, "HTTP_X_SYNO_TOKEN: %s\n",std::getenv ("HTTP_X_SYNO_TOKEN"));
  958. //fprintf(stderr, "REMOTE_ADDR: %s\n",std::getenv ("REMOTE_ADDR"));
  959. // check synology web auth
  960. char user[256], buf[1024];
  961. FILE *fp = NULL;
  962. bzero(user, 256);
  963. fp = popen("/usr/syno/synoman/webman/modules/authenticate.cgi", "r");
  964. if(!fp)
  965. isAuth = false;
  966. else {
  967. bzero(buf, sizeof(buf));
  968. fread(buf, 1024, 1, fp);
  969. if(strlen(buf) > 0) {
  970. snprintf(user, 256, "%s", buf);
  971. isAuth = true;
  972. }
  973. }
  974. pclose(fp);
  975. }
  976. }
  977. #endif
  978. if (httpMethod == HTTP_GET) {
  979. if (isAuth) {
  980. if (ps[0] == "status") {
  981. ZT_NodeStatus status;
  982. _node->status(&status);
  983. OSUtils::ztsnprintf(tmp,sizeof(tmp),"%.10llx",status.address);
  984. res["address"] = tmp;
  985. res["publicIdentity"] = status.publicIdentity;
  986. res["online"] = (bool)(status.online != 0);
  987. res["tcpFallbackActive"] = (_tcpFallbackTunnel != (TcpConnection *)0);
  988. res["versionMajor"] = ZEROTIER_ONE_VERSION_MAJOR;
  989. res["versionMinor"] = ZEROTIER_ONE_VERSION_MINOR;
  990. res["versionRev"] = ZEROTIER_ONE_VERSION_REVISION;
  991. res["versionBuild"] = ZEROTIER_ONE_VERSION_BUILD;
  992. OSUtils::ztsnprintf(tmp,sizeof(tmp),"%d.%d.%d",ZEROTIER_ONE_VERSION_MAJOR,ZEROTIER_ONE_VERSION_MINOR,ZEROTIER_ONE_VERSION_REVISION);
  993. res["version"] = tmp;
  994. res["clock"] = OSUtils::now();
  995. {
  996. Mutex::Lock _l(_localConfig_m);
  997. res["config"] = _localConfig;
  998. }
  999. json &settings = res["config"]["settings"];
  1000. settings["primaryPort"] = OSUtils::jsonInt(settings["primaryPort"],(uint64_t)_primaryPort) & 0xffff;
  1001. #ifdef ZT_USE_MINIUPNPC
  1002. settings["portMappingEnabled"] = OSUtils::jsonBool(settings["portMappingEnabled"],true);
  1003. #else
  1004. settings["portMappingEnabled"] = false; // not supported in build
  1005. #endif
  1006. #ifndef ZT_SDK
  1007. settings["softwareUpdate"] = OSUtils::jsonString(settings["softwareUpdate"],ZT_SOFTWARE_UPDATE_DEFAULT);
  1008. settings["softwareUpdateChannel"] = OSUtils::jsonString(settings["softwareUpdateChannel"],ZT_SOFTWARE_UPDATE_DEFAULT_CHANNEL);
  1009. #endif
  1010. const World planet(_node->planet());
  1011. res["planetWorldId"] = planet.id();
  1012. res["planetWorldTimestamp"] = planet.timestamp();
  1013. scode = 200;
  1014. } else if (ps[0] == "moon") {
  1015. std::vector<World> moons(_node->moons());
  1016. if (ps.size() == 1) {
  1017. // Return [array] of all moons
  1018. res = json::array();
  1019. for(std::vector<World>::const_iterator m(moons.begin());m!=moons.end();++m) {
  1020. json mj;
  1021. _moonToJson(mj,*m);
  1022. res.push_back(mj);
  1023. }
  1024. scode = 200;
  1025. } else {
  1026. // Return a single moon by ID
  1027. const uint64_t id = Utils::hexStrToU64(ps[1].c_str());
  1028. for(std::vector<World>::const_iterator m(moons.begin());m!=moons.end();++m) {
  1029. if (m->id() == id) {
  1030. _moonToJson(res,*m);
  1031. scode = 200;
  1032. break;
  1033. }
  1034. }
  1035. }
  1036. } else if (ps[0] == "network") {
  1037. ZT_VirtualNetworkList *nws = _node->networks();
  1038. if (nws) {
  1039. if (ps.size() == 1) {
  1040. // Return [array] of all networks
  1041. res = nlohmann::json::array();
  1042. for(unsigned long i=0;i<nws->networkCount;++i) {
  1043. OneService::NetworkSettings localSettings;
  1044. getNetworkSettings(nws->networks[i].nwid,localSettings);
  1045. nlohmann::json nj;
  1046. _networkToJson(nj,&(nws->networks[i]),portDeviceName(nws->networks[i].nwid),localSettings);
  1047. res.push_back(nj);
  1048. }
  1049. scode = 200;
  1050. } else if (ps.size() == 2) {
  1051. // Return a single network by ID or 404 if not found
  1052. const uint64_t wantnw = Utils::hexStrToU64(ps[1].c_str());
  1053. for(unsigned long i=0;i<nws->networkCount;++i) {
  1054. if (nws->networks[i].nwid == wantnw) {
  1055. OneService::NetworkSettings localSettings;
  1056. getNetworkSettings(nws->networks[i].nwid,localSettings);
  1057. _networkToJson(res,&(nws->networks[i]),portDeviceName(nws->networks[i].nwid),localSettings);
  1058. scode = 200;
  1059. break;
  1060. }
  1061. }
  1062. } else scode = 404;
  1063. _node->freeQueryResult((void *)nws);
  1064. } else scode = 500;
  1065. } else if (ps[0] == "peer") {
  1066. ZT_PeerList *pl = _node->peers();
  1067. if (pl) {
  1068. if (ps.size() == 1) {
  1069. // Return [array] of all peers
  1070. res = nlohmann::json::array();
  1071. for(unsigned long i=0;i<pl->peerCount;++i) {
  1072. nlohmann::json pj;
  1073. _peerToJson(pj,&(pl->peers[i]));
  1074. res.push_back(pj);
  1075. }
  1076. scode = 200;
  1077. } else if (ps.size() == 2) {
  1078. // Return a single peer by ID or 404 if not found
  1079. uint64_t wantp = Utils::hexStrToU64(ps[1].c_str());
  1080. for(unsigned long i=0;i<pl->peerCount;++i) {
  1081. if (pl->peers[i].address == wantp) {
  1082. _peerToJson(res,&(pl->peers[i]));
  1083. scode = 200;
  1084. break;
  1085. }
  1086. }
  1087. } else scode = 404;
  1088. _node->freeQueryResult((void *)pl);
  1089. } else scode = 500;
  1090. } else {
  1091. if (_controller) {
  1092. scode = _controller->handleControlPlaneHttpGET(std::vector<std::string>(ps.begin()+1,ps.end()),urlArgs,headers,body,responseBody,responseContentType);
  1093. } else scode = 404;
  1094. }
  1095. } else scode = 401; // isAuth == false
  1096. } else if ((httpMethod == HTTP_POST)||(httpMethod == HTTP_PUT)) {
  1097. if (isAuth) {
  1098. if (ps[0] == "moon") {
  1099. if (ps.size() == 2) {
  1100. uint64_t seed = 0;
  1101. try {
  1102. json j(OSUtils::jsonParse(body));
  1103. if (j.is_object()) {
  1104. seed = Utils::hexStrToU64(OSUtils::jsonString(j["seed"],"0").c_str());
  1105. }
  1106. } catch ( ... ) {
  1107. // discard invalid JSON
  1108. }
  1109. std::vector<World> moons(_node->moons());
  1110. const uint64_t id = Utils::hexStrToU64(ps[1].c_str());
  1111. for(std::vector<World>::const_iterator m(moons.begin());m!=moons.end();++m) {
  1112. if (m->id() == id) {
  1113. _moonToJson(res,*m);
  1114. scode = 200;
  1115. break;
  1116. }
  1117. }
  1118. if ((scode != 200)&&(seed != 0)) {
  1119. char tmp[64];
  1120. OSUtils::ztsnprintf(tmp,sizeof(tmp),"%.16llx",id);
  1121. res["id"] = tmp;
  1122. res["roots"] = json::array();
  1123. res["timestamp"] = 0;
  1124. res["signature"] = json();
  1125. res["updatesMustBeSignedBy"] = json();
  1126. res["waiting"] = true;
  1127. _node->orbit((void *)0,id,seed);
  1128. scode = 200;
  1129. }
  1130. } else scode = 404;
  1131. } else if (ps[0] == "network") {
  1132. if (ps.size() == 2) {
  1133. uint64_t wantnw = Utils::hexStrToU64(ps[1].c_str());
  1134. _node->join(wantnw,(void *)0,(void *)0); // does nothing if we are a member
  1135. ZT_VirtualNetworkList *nws = _node->networks();
  1136. if (nws) {
  1137. for(unsigned long i=0;i<nws->networkCount;++i) {
  1138. if (nws->networks[i].nwid == wantnw) {
  1139. OneService::NetworkSettings localSettings;
  1140. getNetworkSettings(nws->networks[i].nwid,localSettings);
  1141. try {
  1142. json j(OSUtils::jsonParse(body));
  1143. if (j.is_object()) {
  1144. json &allowManaged = j["allowManaged"];
  1145. if (allowManaged.is_boolean()) localSettings.allowManaged = (bool)allowManaged;
  1146. json &allowGlobal = j["allowGlobal"];
  1147. if (allowGlobal.is_boolean()) localSettings.allowGlobal = (bool)allowGlobal;
  1148. json &allowDefault = j["allowDefault"];
  1149. if (allowDefault.is_boolean()) localSettings.allowDefault = (bool)allowDefault;
  1150. }
  1151. } catch ( ... ) {
  1152. // discard invalid JSON
  1153. }
  1154. setNetworkSettings(nws->networks[i].nwid,localSettings);
  1155. _networkToJson(res,&(nws->networks[i]),portDeviceName(nws->networks[i].nwid),localSettings);
  1156. scode = 200;
  1157. break;
  1158. }
  1159. }
  1160. _node->freeQueryResult((void *)nws);
  1161. } else scode = 500;
  1162. } else scode = 404;
  1163. } else {
  1164. if (_controller)
  1165. scode = _controller->handleControlPlaneHttpPOST(std::vector<std::string>(ps.begin()+1,ps.end()),urlArgs,headers,body,responseBody,responseContentType);
  1166. else scode = 404;
  1167. }
  1168. } else scode = 401; // isAuth == false
  1169. } else if (httpMethod == HTTP_DELETE) {
  1170. if (isAuth) {
  1171. if (ps[0] == "moon") {
  1172. if (ps.size() == 2) {
  1173. _node->deorbit((void *)0,Utils::hexStrToU64(ps[1].c_str()));
  1174. res["result"] = true;
  1175. scode = 200;
  1176. } // else 404
  1177. } else if (ps[0] == "network") {
  1178. ZT_VirtualNetworkList *nws = _node->networks();
  1179. if (nws) {
  1180. if (ps.size() == 2) {
  1181. uint64_t wantnw = Utils::hexStrToU64(ps[1].c_str());
  1182. for(unsigned long i=0;i<nws->networkCount;++i) {
  1183. if (nws->networks[i].nwid == wantnw) {
  1184. _node->leave(wantnw,(void **)0,(void *)0);
  1185. res["result"] = true;
  1186. scode = 200;
  1187. break;
  1188. }
  1189. }
  1190. } // else 404
  1191. _node->freeQueryResult((void *)nws);
  1192. } else scode = 500;
  1193. } else {
  1194. if (_controller)
  1195. scode = _controller->handleControlPlaneHttpDELETE(std::vector<std::string>(ps.begin()+1,ps.end()),urlArgs,headers,body,responseBody,responseContentType);
  1196. else scode = 404;
  1197. }
  1198. } else scode = 401; // isAuth = false
  1199. } else {
  1200. scode = 400;
  1201. }
  1202. if (responseBody.length() == 0) {
  1203. if ((res.is_object())||(res.is_array()))
  1204. responseBody = OSUtils::jsonDump(res);
  1205. else responseBody = "{}";
  1206. responseContentType = "application/json";
  1207. }
  1208. // Wrap result in jsonp function call if the user included a jsonp= url argument.
  1209. // Also double-check isAuth since forbidding this without auth feels safer.
  1210. std::map<std::string,std::string>::const_iterator jsonp(urlArgs.find("jsonp"));
  1211. if ((isAuth)&&(jsonp != urlArgs.end())&&(responseContentType == "application/json")) {
  1212. if (responseBody.length() > 0)
  1213. responseBody = jsonp->second + "(" + responseBody + ");";
  1214. else responseBody = jsonp->second + "(null);";
  1215. responseContentType = "application/javascript";
  1216. }
  1217. return scode;
  1218. }
  1219. // Must be called after _localConfig is read or modified
  1220. void applyLocalConfig()
  1221. {
  1222. Mutex::Lock _l(_localConfig_m);
  1223. json lc(_localConfig);
  1224. _v4Hints.clear();
  1225. _v6Hints.clear();
  1226. _v4Blacklists.clear();
  1227. _v6Blacklists.clear();
  1228. json &virt = lc["virtual"];
  1229. if (virt.is_object()) {
  1230. for(json::iterator v(virt.begin());v!=virt.end();++v) {
  1231. const std::string nstr = v.key();
  1232. if ((nstr.length() == ZT_ADDRESS_LENGTH_HEX)&&(v.value().is_object())) {
  1233. const Address ztaddr(Utils::hexStrToU64(nstr.c_str()));
  1234. if (ztaddr) {
  1235. const uint64_t ztaddr2 = ztaddr.toInt();
  1236. std::vector<InetAddress> &v4h = _v4Hints[ztaddr2];
  1237. std::vector<InetAddress> &v6h = _v6Hints[ztaddr2];
  1238. std::vector<InetAddress> &v4b = _v4Blacklists[ztaddr2];
  1239. std::vector<InetAddress> &v6b = _v6Blacklists[ztaddr2];
  1240. json &tryAddrs = v.value()["try"];
  1241. if (tryAddrs.is_array()) {
  1242. for(unsigned long i=0;i<tryAddrs.size();++i) {
  1243. const InetAddress ip(OSUtils::jsonString(tryAddrs[i],"").c_str());
  1244. if (ip.ss_family == AF_INET)
  1245. v4h.push_back(ip);
  1246. else if (ip.ss_family == AF_INET6)
  1247. v6h.push_back(ip);
  1248. }
  1249. }
  1250. json &blAddrs = v.value()["blacklist"];
  1251. if (blAddrs.is_array()) {
  1252. for(unsigned long i=0;i<blAddrs.size();++i) {
  1253. const InetAddress ip(OSUtils::jsonString(tryAddrs[i],"").c_str());
  1254. if (ip.ss_family == AF_INET)
  1255. v4b.push_back(ip);
  1256. else if (ip.ss_family == AF_INET6)
  1257. v6b.push_back(ip);
  1258. }
  1259. }
  1260. if (v4h.empty()) _v4Hints.erase(ztaddr2);
  1261. if (v6h.empty()) _v6Hints.erase(ztaddr2);
  1262. if (v4b.empty()) _v4Blacklists.erase(ztaddr2);
  1263. if (v6b.empty()) _v6Blacklists.erase(ztaddr2);
  1264. }
  1265. }
  1266. }
  1267. }
  1268. _globalV4Blacklist.clear();
  1269. _globalV6Blacklist.clear();
  1270. json &physical = lc["physical"];
  1271. if (physical.is_object()) {
  1272. for(json::iterator phy(physical.begin());phy!=physical.end();++phy) {
  1273. const InetAddress net(OSUtils::jsonString(phy.key(),"").c_str());
  1274. if ((net)&&(net.netmaskBits() > 0)) {
  1275. if (phy.value().is_object()) {
  1276. if (OSUtils::jsonBool(phy.value()["blacklist"],false)) {
  1277. if (net.ss_family == AF_INET)
  1278. _globalV4Blacklist.push_back(net);
  1279. else if (net.ss_family == AF_INET6)
  1280. _globalV6Blacklist.push_back(net);
  1281. }
  1282. }
  1283. }
  1284. }
  1285. }
  1286. _allowManagementFrom.clear();
  1287. _interfacePrefixBlacklist.clear();
  1288. json &settings = lc["settings"];
  1289. _primaryPort = (unsigned int)OSUtils::jsonInt(settings["primaryPort"],(uint64_t)_primaryPort) & 0xffff;
  1290. _portMappingEnabled = OSUtils::jsonBool(settings["portMappingEnabled"],true);
  1291. #ifndef ZT_SDK
  1292. const std::string up(OSUtils::jsonString(settings["softwareUpdate"],ZT_SOFTWARE_UPDATE_DEFAULT));
  1293. const bool udist = OSUtils::jsonBool(settings["softwareUpdateDist"],false);
  1294. if (((up == "apply")||(up == "download"))||(udist)) {
  1295. if (!_updater)
  1296. _updater = new SoftwareUpdater(*_node,_homePath);
  1297. _updateAutoApply = (up == "apply");
  1298. _updater->setUpdateDistribution(udist);
  1299. _updater->setChannel(OSUtils::jsonString(settings["softwareUpdateChannel"],ZT_SOFTWARE_UPDATE_DEFAULT_CHANNEL));
  1300. } else {
  1301. delete _updater;
  1302. _updater = (SoftwareUpdater *)0;
  1303. _updateAutoApply = false;
  1304. }
  1305. #endif
  1306. json &ignoreIfs = settings["interfacePrefixBlacklist"];
  1307. if (ignoreIfs.is_array()) {
  1308. for(unsigned long i=0;i<ignoreIfs.size();++i) {
  1309. const std::string tmp(OSUtils::jsonString(ignoreIfs[i],""));
  1310. if (tmp.length() > 0)
  1311. _interfacePrefixBlacklist.push_back(tmp);
  1312. }
  1313. }
  1314. json &amf = settings["allowManagementFrom"];
  1315. if (amf.is_array()) {
  1316. for(unsigned long i=0;i<amf.size();++i) {
  1317. const InetAddress nw(OSUtils::jsonString(amf[i],"").c_str());
  1318. if (nw)
  1319. _allowManagementFrom.push_back(nw);
  1320. }
  1321. }
  1322. }
  1323. // Checks if a managed IP or route target is allowed
  1324. bool checkIfManagedIsAllowed(const NetworkState &n,const InetAddress &target)
  1325. {
  1326. if (!n.settings.allowManaged)
  1327. return false;
  1328. if (n.settings.allowManagedWhitelist.size() > 0) {
  1329. bool allowed = false;
  1330. for (InetAddress addr : n.settings.allowManagedWhitelist) {
  1331. if (addr.containsAddress(target) && addr.netmaskBits() <= target.netmaskBits()) {
  1332. allowed = true;
  1333. break;
  1334. }
  1335. }
  1336. if (!allowed) return false;
  1337. }
  1338. if (target.isDefaultRoute())
  1339. return n.settings.allowDefault;
  1340. switch(target.ipScope()) {
  1341. case InetAddress::IP_SCOPE_NONE:
  1342. case InetAddress::IP_SCOPE_MULTICAST:
  1343. case InetAddress::IP_SCOPE_LOOPBACK:
  1344. case InetAddress::IP_SCOPE_LINK_LOCAL:
  1345. return false;
  1346. case InetAddress::IP_SCOPE_GLOBAL:
  1347. return n.settings.allowGlobal;
  1348. default:
  1349. return true;
  1350. }
  1351. }
  1352. // Match only an IP from a vector of IPs -- used in syncManagedStuff()
  1353. bool matchIpOnly(const std::vector<InetAddress> &ips,const InetAddress &ip) const
  1354. {
  1355. for(std::vector<InetAddress>::const_iterator i(ips.begin());i!=ips.end();++i) {
  1356. if (i->ipsEqual(ip))
  1357. return true;
  1358. }
  1359. return false;
  1360. }
  1361. // Apply or update managed IPs for a configured network (be sure n.tap exists)
  1362. void syncManagedStuff(NetworkState &n,bool syncIps,bool syncRoutes)
  1363. {
  1364. char ipbuf[64];
  1365. // assumes _nets_m is locked
  1366. if (syncIps) {
  1367. std::vector<InetAddress> newManagedIps;
  1368. newManagedIps.reserve(n.config.assignedAddressCount);
  1369. for(unsigned int i=0;i<n.config.assignedAddressCount;++i) {
  1370. const InetAddress *ii = reinterpret_cast<const InetAddress *>(&(n.config.assignedAddresses[i]));
  1371. if (checkIfManagedIsAllowed(n,*ii))
  1372. newManagedIps.push_back(*ii);
  1373. }
  1374. std::sort(newManagedIps.begin(),newManagedIps.end());
  1375. newManagedIps.erase(std::unique(newManagedIps.begin(),newManagedIps.end()),newManagedIps.end());
  1376. for(std::vector<InetAddress>::iterator ip(n.managedIps.begin());ip!=n.managedIps.end();++ip) {
  1377. if (std::find(newManagedIps.begin(),newManagedIps.end(),*ip) == newManagedIps.end()) {
  1378. if (!n.tap->removeIp(*ip))
  1379. fprintf(stderr,"ERROR: unable to remove ip address %s" ZT_EOL_S, ip->toString(ipbuf));
  1380. }
  1381. }
  1382. #ifdef __SYNOLOGY__
  1383. if (!n.tap->addIpSyn(newManagedIps))
  1384. fprintf(stderr,"ERROR: unable to add ip addresses to ifcfg" ZT_EOL_S);
  1385. #else
  1386. for(std::vector<InetAddress>::iterator ip(newManagedIps.begin());ip!=newManagedIps.end();++ip) {
  1387. if (std::find(n.managedIps.begin(),n.managedIps.end(),*ip) == n.managedIps.end()) {
  1388. if (!n.tap->addIp(*ip))
  1389. fprintf(stderr,"ERROR: unable to add ip address %s" ZT_EOL_S, ip->toString(ipbuf));
  1390. }
  1391. }
  1392. #endif
  1393. n.managedIps.swap(newManagedIps);
  1394. }
  1395. if (syncRoutes) {
  1396. char tapdev[64];
  1397. #ifdef __WINDOWS__
  1398. OSUtils::ztsnprintf(tapdev,sizeof(tapdev),"%.16llx",(unsigned long long)n.tap->luid().Value);
  1399. #else
  1400. Utils::scopy(tapdev,sizeof(tapdev),n.tap->deviceName().c_str());
  1401. #endif
  1402. std::vector<InetAddress> myIps(n.tap->ips());
  1403. // Nuke applied routes that are no longer in n.config.routes[] and/or are not allowed
  1404. for(std::list< SharedPtr<ManagedRoute> >::iterator mr(n.managedRoutes.begin());mr!=n.managedRoutes.end();) {
  1405. bool haveRoute = false;
  1406. if ( (checkIfManagedIsAllowed(n,(*mr)->target())) && (((*mr)->via().ss_family != (*mr)->target().ss_family)||(!matchIpOnly(myIps,(*mr)->via()))) ) {
  1407. for(unsigned int i=0;i<n.config.routeCount;++i) {
  1408. const InetAddress *const target = reinterpret_cast<const InetAddress *>(&(n.config.routes[i].target));
  1409. const InetAddress *const via = reinterpret_cast<const InetAddress *>(&(n.config.routes[i].via));
  1410. if ( ((*mr)->target() == *target) && ( ((via->ss_family == target->ss_family)&&((*mr)->via().ipsEqual(*via))) || (tapdev == (*mr)->device()) ) ) {
  1411. haveRoute = true;
  1412. break;
  1413. }
  1414. }
  1415. }
  1416. if (haveRoute) {
  1417. ++mr;
  1418. } else {
  1419. n.managedRoutes.erase(mr++);
  1420. }
  1421. }
  1422. // Apply routes in n.config.routes[] that we haven't applied yet, and sync those we have in case shadow routes need to change
  1423. for(unsigned int i=0;i<n.config.routeCount;++i) {
  1424. const InetAddress *const target = reinterpret_cast<const InetAddress *>(&(n.config.routes[i].target));
  1425. const InetAddress *const via = reinterpret_cast<const InetAddress *>(&(n.config.routes[i].via));
  1426. if ( (!checkIfManagedIsAllowed(n,*target)) || ((via->ss_family == target->ss_family)&&(matchIpOnly(myIps,*via))) )
  1427. continue;
  1428. bool haveRoute = false;
  1429. // Ignore routes implied by local managed IPs since adding the IP adds the route
  1430. for(std::vector<InetAddress>::iterator ip(n.managedIps.begin());ip!=n.managedIps.end();++ip) {
  1431. if ((target->netmaskBits() == ip->netmaskBits())&&(target->containsAddress(*ip))) {
  1432. haveRoute = true;
  1433. break;
  1434. }
  1435. }
  1436. if (haveRoute)
  1437. continue;
  1438. // If we've already applied this route, just sync it and continue
  1439. for(std::list< SharedPtr<ManagedRoute> >::iterator mr(n.managedRoutes.begin());mr!=n.managedRoutes.end();++mr) {
  1440. if ( ((*mr)->target() == *target) && ( ((via->ss_family == target->ss_family)&&((*mr)->via().ipsEqual(*via))) || (tapdev == (*mr)->device()) ) ) {
  1441. haveRoute = true;
  1442. (*mr)->sync();
  1443. break;
  1444. }
  1445. }
  1446. if (haveRoute)
  1447. continue;
  1448. // Add and apply new routes
  1449. n.managedRoutes.push_back(SharedPtr<ManagedRoute>(new ManagedRoute(*target,*via,tapdev)));
  1450. if (!n.managedRoutes.back()->sync())
  1451. n.managedRoutes.pop_back();
  1452. }
  1453. }
  1454. }
  1455. // =========================================================================
  1456. // Handlers for Node and Phy<> callbacks
  1457. // =========================================================================
  1458. inline void phyOnDatagram(PhySocket *sock,void **uptr,const struct sockaddr *localAddr,const struct sockaddr *from,void *data,unsigned long len)
  1459. {
  1460. if ((len >= 16)&&(reinterpret_cast<const InetAddress *>(from)->ipScope() == InetAddress::IP_SCOPE_GLOBAL))
  1461. _lastDirectReceiveFromGlobal = OSUtils::now();
  1462. const ZT_ResultCode rc = _node->processWirePacket(
  1463. (void *)0,
  1464. OSUtils::now(),
  1465. reinterpret_cast<int64_t>(sock),
  1466. reinterpret_cast<const struct sockaddr_storage *>(from), // Phy<> uses sockaddr_storage, so it'll always be that big
  1467. data,
  1468. len,
  1469. &_nextBackgroundTaskDeadline);
  1470. if (ZT_ResultCode_isFatal(rc)) {
  1471. char tmp[256];
  1472. OSUtils::ztsnprintf(tmp,sizeof(tmp),"fatal error code from processWirePacket: %d",(int)rc);
  1473. Mutex::Lock _l(_termReason_m);
  1474. _termReason = ONE_UNRECOVERABLE_ERROR;
  1475. _fatalErrorMessage = tmp;
  1476. this->terminate();
  1477. }
  1478. }
  1479. inline void phyOnTcpConnect(PhySocket *sock,void **uptr,bool success)
  1480. {
  1481. if (!success) {
  1482. phyOnTcpClose(sock,uptr);
  1483. return;
  1484. }
  1485. TcpConnection *const tc = reinterpret_cast<TcpConnection *>(*uptr);
  1486. if (!tc) { // sanity check
  1487. _phy.close(sock,true);
  1488. return;
  1489. }
  1490. tc->sock = sock;
  1491. if (tc->type == TcpConnection::TCP_TUNNEL_OUTGOING) {
  1492. if (_tcpFallbackTunnel)
  1493. _phy.close(_tcpFallbackTunnel->sock);
  1494. _tcpFallbackTunnel = tc;
  1495. _phy.streamSend(sock,ZT_TCP_TUNNEL_HELLO,sizeof(ZT_TCP_TUNNEL_HELLO));
  1496. } else {
  1497. _phy.close(sock,true);
  1498. }
  1499. }
  1500. inline void phyOnTcpAccept(PhySocket *sockL,PhySocket *sockN,void **uptrL,void **uptrN,const struct sockaddr *from)
  1501. {
  1502. if (!from) {
  1503. _phy.close(sockN,false);
  1504. return;
  1505. } else {
  1506. TcpConnection *tc = new TcpConnection();
  1507. {
  1508. Mutex::Lock _l(_tcpConnections_m);
  1509. _tcpConnections.push_back(tc);
  1510. }
  1511. tc->type = TcpConnection::TCP_UNCATEGORIZED_INCOMING;
  1512. tc->parent = this;
  1513. tc->sock = sockN;
  1514. tc->remoteAddr = from;
  1515. tc->lastReceive = OSUtils::now();
  1516. http_parser_init(&(tc->parser),HTTP_REQUEST);
  1517. tc->parser.data = (void *)tc;
  1518. tc->messageSize = 0;
  1519. *uptrN = (void *)tc;
  1520. }
  1521. }
  1522. void phyOnTcpClose(PhySocket *sock,void **uptr)
  1523. {
  1524. TcpConnection *tc = (TcpConnection *)*uptr;
  1525. if (tc) {
  1526. if (tc == _tcpFallbackTunnel) {
  1527. _tcpFallbackTunnel = (TcpConnection *)0;
  1528. }
  1529. {
  1530. Mutex::Lock _l(_tcpConnections_m);
  1531. _tcpConnections.erase(std::remove(_tcpConnections.begin(),_tcpConnections.end(),tc),_tcpConnections.end());
  1532. }
  1533. delete tc;
  1534. }
  1535. }
  1536. void phyOnTcpData(PhySocket *sock,void **uptr,void *data,unsigned long len)
  1537. {
  1538. try {
  1539. if (!len) return; // sanity check, should never happen
  1540. TcpConnection *tc = reinterpret_cast<TcpConnection *>(*uptr);
  1541. tc->lastReceive = OSUtils::now();
  1542. switch(tc->type) {
  1543. case TcpConnection::TCP_UNCATEGORIZED_INCOMING:
  1544. switch(reinterpret_cast<uint8_t *>(data)[0]) {
  1545. // HTTP: GET, PUT, POST, HEAD, DELETE
  1546. case 'G':
  1547. case 'P':
  1548. case 'D':
  1549. case 'H': {
  1550. // This is only allowed from IPs permitted to access the management
  1551. // backplane, which is just 127.0.0.1/::1 unless otherwise configured.
  1552. bool allow;
  1553. {
  1554. Mutex::Lock _l(_localConfig_m);
  1555. if (_allowManagementFrom.size() == 0) {
  1556. allow = (tc->remoteAddr.ipScope() == InetAddress::IP_SCOPE_LOOPBACK);
  1557. } else {
  1558. allow = false;
  1559. for(std::vector<InetAddress>::const_iterator i(_allowManagementFrom.begin());i!=_allowManagementFrom.end();++i) {
  1560. if (i->containsAddress(tc->remoteAddr)) {
  1561. allow = true;
  1562. break;
  1563. }
  1564. }
  1565. }
  1566. }
  1567. if (allow) {
  1568. tc->type = TcpConnection::TCP_HTTP_INCOMING;
  1569. phyOnTcpData(sock,uptr,data,len);
  1570. } else {
  1571. _phy.close(sock);
  1572. }
  1573. } break;
  1574. // Drop unknown protocols
  1575. default:
  1576. _phy.close(sock);
  1577. break;
  1578. }
  1579. return;
  1580. case TcpConnection::TCP_HTTP_INCOMING:
  1581. case TcpConnection::TCP_HTTP_OUTGOING:
  1582. http_parser_execute(&(tc->parser),&HTTP_PARSER_SETTINGS,(const char *)data,len);
  1583. if ((tc->parser.upgrade)||(tc->parser.http_errno != HPE_OK))
  1584. _phy.close(sock);
  1585. return;
  1586. case TcpConnection::TCP_TUNNEL_OUTGOING:
  1587. tc->readq.append((const char *)data,len);
  1588. while (tc->readq.length() >= 5) {
  1589. const char *data = tc->readq.data();
  1590. const unsigned long mlen = ( ((((unsigned long)data[3]) & 0xff) << 8) | (((unsigned long)data[4]) & 0xff) );
  1591. if (tc->readq.length() >= (mlen + 5)) {
  1592. InetAddress from;
  1593. unsigned long plen = mlen; // payload length, modified if there's an IP header
  1594. data += 5; // skip forward past pseudo-TLS junk and mlen
  1595. if (plen == 4) {
  1596. // Hello message, which isn't sent by proxy and would be ignored by client
  1597. } else if (plen) {
  1598. // Messages should contain IPv4 or IPv6 source IP address data
  1599. switch(data[0]) {
  1600. case 4: // IPv4
  1601. if (plen >= 7) {
  1602. from.set((const void *)(data + 1),4,((((unsigned int)data[5]) & 0xff) << 8) | (((unsigned int)data[6]) & 0xff));
  1603. data += 7; // type + 4 byte IP + 2 byte port
  1604. plen -= 7;
  1605. } else {
  1606. _phy.close(sock);
  1607. return;
  1608. }
  1609. break;
  1610. case 6: // IPv6
  1611. if (plen >= 19) {
  1612. from.set((const void *)(data + 1),16,((((unsigned int)data[17]) & 0xff) << 8) | (((unsigned int)data[18]) & 0xff));
  1613. data += 19; // type + 16 byte IP + 2 byte port
  1614. plen -= 19;
  1615. } else {
  1616. _phy.close(sock);
  1617. return;
  1618. }
  1619. break;
  1620. case 0: // none/omitted
  1621. ++data;
  1622. --plen;
  1623. break;
  1624. default: // invalid address type
  1625. _phy.close(sock);
  1626. return;
  1627. }
  1628. if (from) {
  1629. InetAddress fakeTcpLocalInterfaceAddress((uint32_t)0xffffffff,0xffff);
  1630. const ZT_ResultCode rc = _node->processWirePacket(
  1631. (void *)0,
  1632. OSUtils::now(),
  1633. -1,
  1634. reinterpret_cast<struct sockaddr_storage *>(&from),
  1635. data,
  1636. plen,
  1637. &_nextBackgroundTaskDeadline);
  1638. if (ZT_ResultCode_isFatal(rc)) {
  1639. char tmp[256];
  1640. OSUtils::ztsnprintf(tmp,sizeof(tmp),"fatal error code from processWirePacket: %d",(int)rc);
  1641. Mutex::Lock _l(_termReason_m);
  1642. _termReason = ONE_UNRECOVERABLE_ERROR;
  1643. _fatalErrorMessage = tmp;
  1644. this->terminate();
  1645. _phy.close(sock);
  1646. return;
  1647. }
  1648. }
  1649. }
  1650. if (tc->readq.length() > (mlen + 5))
  1651. tc->readq.erase(tc->readq.begin(),tc->readq.begin() + (mlen + 5));
  1652. else tc->readq.clear();
  1653. } else break;
  1654. }
  1655. return;
  1656. }
  1657. } catch ( ... ) {
  1658. _phy.close(sock);
  1659. }
  1660. }
  1661. inline void phyOnTcpWritable(PhySocket *sock,void **uptr)
  1662. {
  1663. TcpConnection *tc = reinterpret_cast<TcpConnection *>(*uptr);
  1664. bool closeit = false;
  1665. {
  1666. Mutex::Lock _l(tc->writeq_m);
  1667. if (tc->writeq.length() > 0) {
  1668. long sent = (long)_phy.streamSend(sock,tc->writeq.data(),(unsigned long)tc->writeq.length(),true);
  1669. if (sent > 0) {
  1670. if ((unsigned long)sent >= (unsigned long)tc->writeq.length()) {
  1671. tc->writeq.clear();
  1672. _phy.setNotifyWritable(sock,false);
  1673. if (tc->type == TcpConnection::TCP_HTTP_INCOMING)
  1674. closeit = true; // HTTP keep alive not supported
  1675. } else {
  1676. tc->writeq.erase(tc->writeq.begin(),tc->writeq.begin() + sent);
  1677. }
  1678. }
  1679. } else {
  1680. _phy.setNotifyWritable(sock,false);
  1681. }
  1682. }
  1683. if (closeit)
  1684. _phy.close(sock);
  1685. }
  1686. inline void phyOnFileDescriptorActivity(PhySocket *sock,void **uptr,bool readable,bool writable) {}
  1687. inline void phyOnUnixAccept(PhySocket *sockL,PhySocket *sockN,void **uptrL,void **uptrN) {}
  1688. inline void phyOnUnixClose(PhySocket *sock,void **uptr) {}
  1689. inline void phyOnUnixData(PhySocket *sock,void **uptr,void *data,unsigned long len) {}
  1690. inline void phyOnUnixWritable(PhySocket *sock,void **uptr,bool lwip_invoked) {}
  1691. inline int nodeVirtualNetworkConfigFunction(uint64_t nwid,void **nuptr,enum ZT_VirtualNetworkConfigOperation op,const ZT_VirtualNetworkConfig *nwc)
  1692. {
  1693. Mutex::Lock _l(_nets_m);
  1694. NetworkState &n = _nets[nwid];
  1695. switch(op) {
  1696. case ZT_VIRTUAL_NETWORK_CONFIG_OPERATION_UP:
  1697. if (!n.tap) {
  1698. try {
  1699. char friendlyName[128];
  1700. OSUtils::ztsnprintf(friendlyName,sizeof(friendlyName),"ZeroTier One [%.16llx]",nwid);
  1701. n.tap = new EthernetTap(
  1702. _homePath.c_str(),
  1703. MAC(nwc->mac),
  1704. nwc->mtu,
  1705. (unsigned int)ZT_IF_METRIC,
  1706. nwid,
  1707. friendlyName,
  1708. StapFrameHandler,
  1709. (void *)this);
  1710. *nuptr = (void *)&n;
  1711. char nlcpath[256];
  1712. OSUtils::ztsnprintf(nlcpath,sizeof(nlcpath),"%s" ZT_PATH_SEPARATOR_S "networks.d" ZT_PATH_SEPARATOR_S "%.16llx.local.conf",_homePath.c_str(),nwid);
  1713. std::string nlcbuf;
  1714. if (OSUtils::readFile(nlcpath,nlcbuf)) {
  1715. Dictionary<4096> nc;
  1716. nc.load(nlcbuf.c_str());
  1717. Buffer<1024> allowManaged;
  1718. if (nc.get("allowManaged", allowManaged) && allowManaged.size() != 0) {
  1719. std::string addresses (allowManaged.begin(), allowManaged.size());
  1720. if (allowManaged.size() <= 5) { // untidy parsing for backward compatibility
  1721. if (allowManaged[0] == '1' || allowManaged[0] == 't' || allowManaged[0] == 'T') {
  1722. n.settings.allowManaged = true;
  1723. } else {
  1724. n.settings.allowManaged = false;
  1725. }
  1726. } else {
  1727. // this should be a list of IP addresses
  1728. n.settings.allowManaged = true;
  1729. size_t pos = 0;
  1730. while (true) {
  1731. size_t nextPos = addresses.find(',', pos);
  1732. std::string address = addresses.substr(pos, (nextPos == std::string::npos ? addresses.size() : nextPos) - pos);
  1733. n.settings.allowManagedWhitelist.push_back(InetAddress(address.c_str()));
  1734. if (nextPos == std::string::npos) break;
  1735. pos = nextPos + 1;
  1736. }
  1737. }
  1738. } else {
  1739. n.settings.allowManaged = true;
  1740. }
  1741. n.settings.allowGlobal = nc.getB("allowGlobal", false);
  1742. n.settings.allowDefault = nc.getB("allowDefault", false);
  1743. }
  1744. } catch (std::exception &exc) {
  1745. #ifdef __WINDOWS__
  1746. FILE *tapFailLog = fopen((_homePath + ZT_PATH_SEPARATOR_S"port_error_log.txt").c_str(),"a");
  1747. if (tapFailLog) {
  1748. fprintf(tapFailLog,"%.16llx: %s" ZT_EOL_S,(unsigned long long)nwid,exc.what());
  1749. fclose(tapFailLog);
  1750. }
  1751. #else
  1752. fprintf(stderr,"ERROR: unable to configure virtual network port: %s" ZT_EOL_S,exc.what());
  1753. #endif
  1754. _nets.erase(nwid);
  1755. return -999;
  1756. } catch ( ... ) {
  1757. return -999; // tap init failed
  1758. }
  1759. }
  1760. // After setting up tap, fall through to CONFIG_UPDATE since we also want to do this...
  1761. case ZT_VIRTUAL_NETWORK_CONFIG_OPERATION_CONFIG_UPDATE:
  1762. memcpy(&(n.config),nwc,sizeof(ZT_VirtualNetworkConfig));
  1763. if (n.tap) { // sanity check
  1764. #ifdef __WINDOWS__
  1765. // wait for up to 5 seconds for the WindowsEthernetTap to actually be initialized
  1766. //
  1767. // without WindowsEthernetTap::isInitialized() returning true, the won't actually
  1768. // be online yet and setting managed routes on it will fail.
  1769. const int MAX_SLEEP_COUNT = 500;
  1770. for (int i = 0; !n.tap->isInitialized() && i < MAX_SLEEP_COUNT; i++) {
  1771. Sleep(10);
  1772. }
  1773. #endif
  1774. syncManagedStuff(n,true,true);
  1775. n.tap->setMtu(nwc->mtu);
  1776. } else {
  1777. _nets.erase(nwid);
  1778. return -999; // tap init failed
  1779. }
  1780. break;
  1781. case ZT_VIRTUAL_NETWORK_CONFIG_OPERATION_DOWN:
  1782. case ZT_VIRTUAL_NETWORK_CONFIG_OPERATION_DESTROY:
  1783. if (n.tap) { // sanity check
  1784. #ifdef __WINDOWS__
  1785. std::string winInstanceId(n.tap->instanceId());
  1786. #endif
  1787. *nuptr = (void *)0;
  1788. delete n.tap;
  1789. _nets.erase(nwid);
  1790. #if defined(__WINDOWS__) && !defined(ZT_SDK)
  1791. if ((op == ZT_VIRTUAL_NETWORK_CONFIG_OPERATION_DESTROY)&&(winInstanceId.length() > 0))
  1792. WindowsEthernetTap::deletePersistentTapDevice(winInstanceId.c_str());
  1793. #endif
  1794. if (op == ZT_VIRTUAL_NETWORK_CONFIG_OPERATION_DESTROY) {
  1795. char nlcpath[256];
  1796. OSUtils::ztsnprintf(nlcpath,sizeof(nlcpath),"%s" ZT_PATH_SEPARATOR_S "networks.d" ZT_PATH_SEPARATOR_S "%.16llx.local.conf",_homePath.c_str(),nwid);
  1797. OSUtils::rm(nlcpath);
  1798. }
  1799. } else {
  1800. _nets.erase(nwid);
  1801. }
  1802. break;
  1803. }
  1804. return 0;
  1805. }
  1806. inline void nodeEventCallback(enum ZT_Event event,const void *metaData)
  1807. {
  1808. switch(event) {
  1809. case ZT_EVENT_FATAL_ERROR_IDENTITY_COLLISION: {
  1810. Mutex::Lock _l(_termReason_m);
  1811. _termReason = ONE_IDENTITY_COLLISION;
  1812. _fatalErrorMessage = "identity/address collision";
  1813. this->terminate();
  1814. } break;
  1815. case ZT_EVENT_TRACE: {
  1816. if (metaData) {
  1817. ::fprintf(stderr,"%s" ZT_EOL_S,(const char *)metaData);
  1818. ::fflush(stderr);
  1819. }
  1820. } break;
  1821. case ZT_EVENT_USER_MESSAGE: {
  1822. const ZT_UserMessage *um = reinterpret_cast<const ZT_UserMessage *>(metaData);
  1823. if ((um->typeId == ZT_SOFTWARE_UPDATE_USER_MESSAGE_TYPE)&&(_updater)) {
  1824. _updater->handleSoftwareUpdateUserMessage(um->origin,um->data,um->length);
  1825. }
  1826. } break;
  1827. case ZT_EVENT_REMOTE_TRACE: {
  1828. const ZT_RemoteTrace *rt = reinterpret_cast<const ZT_RemoteTrace *>(metaData);
  1829. if ((rt)&&(rt->len > 0)&&(rt->len <= ZT_MAX_REMOTE_TRACE_SIZE)&&(rt->data))
  1830. _controller->handleRemoteTrace(*rt);
  1831. }
  1832. default:
  1833. break;
  1834. }
  1835. }
  1836. inline void nodeStatePutFunction(enum ZT_StateObjectType type,const uint64_t id[2],const void *data,int len)
  1837. {
  1838. char p[1024];
  1839. FILE *f;
  1840. bool secure = false;
  1841. char dirname[1024];
  1842. dirname[0] = 0;
  1843. switch(type) {
  1844. case ZT_STATE_OBJECT_IDENTITY_PUBLIC:
  1845. OSUtils::ztsnprintf(p,sizeof(p),"%s" ZT_PATH_SEPARATOR_S "identity.public",_homePath.c_str());
  1846. break;
  1847. case ZT_STATE_OBJECT_IDENTITY_SECRET:
  1848. OSUtils::ztsnprintf(p,sizeof(p),"%s" ZT_PATH_SEPARATOR_S "identity.secret",_homePath.c_str());
  1849. secure = true;
  1850. break;
  1851. case ZT_STATE_OBJECT_PLANET:
  1852. OSUtils::ztsnprintf(p,sizeof(p),"%s" ZT_PATH_SEPARATOR_S "planet",_homePath.c_str());
  1853. break;
  1854. case ZT_STATE_OBJECT_MOON:
  1855. OSUtils::ztsnprintf(dirname,sizeof(dirname),"%s" ZT_PATH_SEPARATOR_S "moons.d",_homePath.c_str());
  1856. OSUtils::ztsnprintf(p,sizeof(p),"%s" ZT_PATH_SEPARATOR_S "%.16llx.moon",dirname,(unsigned long long)id[0]);
  1857. break;
  1858. case ZT_STATE_OBJECT_NETWORK_CONFIG:
  1859. OSUtils::ztsnprintf(dirname,sizeof(dirname),"%s" ZT_PATH_SEPARATOR_S "networks.d",_homePath.c_str());
  1860. OSUtils::ztsnprintf(p,sizeof(p),"%s" ZT_PATH_SEPARATOR_S "%.16llx.conf",dirname,(unsigned long long)id[0]);
  1861. secure = true;
  1862. break;
  1863. case ZT_STATE_OBJECT_PEER:
  1864. OSUtils::ztsnprintf(dirname,sizeof(dirname),"%s" ZT_PATH_SEPARATOR_S "peers.d",_homePath.c_str());
  1865. OSUtils::ztsnprintf(p,sizeof(p),"%s" ZT_PATH_SEPARATOR_S "%.10llx.peer",dirname,(unsigned long long)id[0]);
  1866. break;
  1867. default:
  1868. return;
  1869. }
  1870. if (len >= 0) {
  1871. // Check to see if we've already written this first. This reduces
  1872. // redundant writes and I/O overhead on most platforms and has
  1873. // little effect on others.
  1874. f = fopen(p,"r");
  1875. if (f) {
  1876. char buf[65535];
  1877. long l = (long)fread(buf,1,sizeof(buf),f);
  1878. fclose(f);
  1879. if ((l == (long)len)&&(memcmp(data,buf,l) == 0))
  1880. return;
  1881. }
  1882. f = fopen(p,"w");
  1883. if ((!f)&&(dirname[0])) { // create subdirectory if it does not exist
  1884. OSUtils::mkdir(dirname);
  1885. f = fopen(p,"w");
  1886. }
  1887. if (f) {
  1888. if (fwrite(data,len,1,f) != 1)
  1889. fprintf(stderr,"WARNING: unable to write to file: %s (I/O error)" ZT_EOL_S,p);
  1890. fclose(f);
  1891. if (secure)
  1892. OSUtils::lockDownFile(p,false);
  1893. } else {
  1894. fprintf(stderr,"WARNING: unable to write to file: %s (unable to open)" ZT_EOL_S,p);
  1895. }
  1896. } else {
  1897. OSUtils::rm(p);
  1898. }
  1899. }
  1900. inline int nodeStateGetFunction(enum ZT_StateObjectType type,const uint64_t id[2],void *data,unsigned int maxlen)
  1901. {
  1902. char p[4096];
  1903. switch(type) {
  1904. case ZT_STATE_OBJECT_IDENTITY_PUBLIC:
  1905. OSUtils::ztsnprintf(p,sizeof(p),"%s" ZT_PATH_SEPARATOR_S "identity.public",_homePath.c_str());
  1906. break;
  1907. case ZT_STATE_OBJECT_IDENTITY_SECRET:
  1908. OSUtils::ztsnprintf(p,sizeof(p),"%s" ZT_PATH_SEPARATOR_S "identity.secret",_homePath.c_str());
  1909. break;
  1910. case ZT_STATE_OBJECT_PLANET:
  1911. OSUtils::ztsnprintf(p,sizeof(p),"%s" ZT_PATH_SEPARATOR_S "planet",_homePath.c_str());
  1912. break;
  1913. case ZT_STATE_OBJECT_MOON:
  1914. 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);
  1915. break;
  1916. case ZT_STATE_OBJECT_NETWORK_CONFIG:
  1917. 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);
  1918. break;
  1919. case ZT_STATE_OBJECT_PEER:
  1920. 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]);
  1921. break;
  1922. default:
  1923. return -1;
  1924. }
  1925. FILE *f = fopen(p,"r");
  1926. if (f) {
  1927. int n = (int)fread(data,1,maxlen,f);
  1928. fclose(f);
  1929. if (n >= 0)
  1930. return n;
  1931. }
  1932. return -1;
  1933. }
  1934. inline int nodeWirePacketSendFunction(const int64_t localSocket,const struct sockaddr_storage *addr,const void *data,unsigned int len,unsigned int ttl)
  1935. {
  1936. #ifdef ZT_TCP_FALLBACK_RELAY
  1937. if (addr->ss_family == AF_INET) {
  1938. // TCP fallback tunnel support, currently IPv4 only
  1939. if ((len >= 16)&&(reinterpret_cast<const InetAddress *>(addr)->ipScope() == InetAddress::IP_SCOPE_GLOBAL)) {
  1940. // Engage TCP tunnel fallback if we haven't received anything valid from a global
  1941. // IP address in ZT_TCP_FALLBACK_AFTER milliseconds. If we do start getting
  1942. // valid direct traffic we'll stop using it and close the socket after a while.
  1943. const int64_t now = OSUtils::now();
  1944. if (((now - _lastDirectReceiveFromGlobal) > ZT_TCP_FALLBACK_AFTER)&&((now - _lastRestart) > ZT_TCP_FALLBACK_AFTER)) {
  1945. if (_tcpFallbackTunnel) {
  1946. bool flushNow = false;
  1947. {
  1948. Mutex::Lock _l(_tcpFallbackTunnel->writeq_m);
  1949. if (_tcpFallbackTunnel->writeq.size() < (1024 * 64)) {
  1950. if (_tcpFallbackTunnel->writeq.length() == 0) {
  1951. _phy.setNotifyWritable(_tcpFallbackTunnel->sock,true);
  1952. flushNow = true;
  1953. }
  1954. const unsigned long mlen = len + 7;
  1955. _tcpFallbackTunnel->writeq.push_back((char)0x17);
  1956. _tcpFallbackTunnel->writeq.push_back((char)0x03);
  1957. _tcpFallbackTunnel->writeq.push_back((char)0x03); // fake TLS 1.2 header
  1958. _tcpFallbackTunnel->writeq.push_back((char)((mlen >> 8) & 0xff));
  1959. _tcpFallbackTunnel->writeq.push_back((char)(mlen & 0xff));
  1960. _tcpFallbackTunnel->writeq.push_back((char)4); // IPv4
  1961. _tcpFallbackTunnel->writeq.append(reinterpret_cast<const char *>(reinterpret_cast<const void *>(&(reinterpret_cast<const struct sockaddr_in *>(addr)->sin_addr.s_addr))),4);
  1962. _tcpFallbackTunnel->writeq.append(reinterpret_cast<const char *>(reinterpret_cast<const void *>(&(reinterpret_cast<const struct sockaddr_in *>(addr)->sin_port))),2);
  1963. _tcpFallbackTunnel->writeq.append((const char *)data,len);
  1964. }
  1965. }
  1966. if (flushNow) {
  1967. void *tmpptr = (void *)_tcpFallbackTunnel;
  1968. phyOnTcpWritable(_tcpFallbackTunnel->sock,&tmpptr);
  1969. }
  1970. } else if (((now - _lastSendToGlobalV4) < ZT_TCP_FALLBACK_AFTER)&&((now - _lastSendToGlobalV4) > (ZT_PING_CHECK_INVERVAL / 2))) {
  1971. const InetAddress addr(ZT_TCP_FALLBACK_RELAY);
  1972. TcpConnection *tc = new TcpConnection();
  1973. {
  1974. Mutex::Lock _l(_tcpConnections_m);
  1975. _tcpConnections.push_back(tc);
  1976. }
  1977. tc->type = TcpConnection::TCP_TUNNEL_OUTGOING;
  1978. tc->remoteAddr = addr;
  1979. tc->lastReceive = OSUtils::now();
  1980. tc->parent = this;
  1981. tc->sock = (PhySocket *)0; // set in connect handler
  1982. tc->messageSize = 0;
  1983. bool connected = false;
  1984. _phy.tcpConnect(reinterpret_cast<const struct sockaddr *>(&addr),connected,(void *)tc,true);
  1985. }
  1986. }
  1987. _lastSendToGlobalV4 = now;
  1988. }
  1989. }
  1990. // Even when relaying we still send via UDP. This way if UDP starts
  1991. // working we can instantly "fail forward" to it and stop using TCP
  1992. // proxy fallback, which is slow.
  1993. #endif // ZT_TCP_FALLBACK_RELAY
  1994. if ((localSocket != -1)&&(localSocket != 0)&&(_binder.isUdpSocketValid((PhySocket *)((uintptr_t)localSocket)))) {
  1995. if ((ttl)&&(addr->ss_family == AF_INET)) _phy.setIp4UdpTtl((PhySocket *)((uintptr_t)localSocket),ttl);
  1996. const bool r = _phy.udpSend((PhySocket *)((uintptr_t)localSocket),(const struct sockaddr *)addr,data,len);
  1997. if ((ttl)&&(addr->ss_family == AF_INET)) _phy.setIp4UdpTtl((PhySocket *)((uintptr_t)localSocket),255);
  1998. return ((r) ? 0 : -1);
  1999. } else {
  2000. return ((_binder.udpSendAll(_phy,addr,data,len,ttl)) ? 0 : -1);
  2001. }
  2002. }
  2003. 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)
  2004. {
  2005. NetworkState *n = reinterpret_cast<NetworkState *>(*nuptr);
  2006. if ((!n)||(!n->tap))
  2007. return;
  2008. n->tap->put(MAC(sourceMac),MAC(destMac),etherType,data,len);
  2009. }
  2010. inline int nodePathCheckFunction(uint64_t ztaddr,const int64_t localSocket,const struct sockaddr_storage *remoteAddr)
  2011. {
  2012. // Make sure we're not trying to do ZeroTier-over-ZeroTier
  2013. {
  2014. Mutex::Lock _l(_nets_m);
  2015. for(std::map<uint64_t,NetworkState>::const_iterator n(_nets.begin());n!=_nets.end();++n) {
  2016. if (n->second.tap) {
  2017. std::vector<InetAddress> ips(n->second.tap->ips());
  2018. for(std::vector<InetAddress>::const_iterator i(ips.begin());i!=ips.end();++i) {
  2019. if (i->containsAddress(*(reinterpret_cast<const InetAddress *>(remoteAddr)))) {
  2020. return 0;
  2021. }
  2022. }
  2023. }
  2024. }
  2025. }
  2026. /* Note: I do not think we need to scan for overlap with managed routes
  2027. * because of the "route forking" and interface binding that we do. This
  2028. * ensures (we hope) that ZeroTier traffic will still take the physical
  2029. * path even if its managed routes override this for other traffic. Will
  2030. * revisit if we see recursion problems. */
  2031. // Check blacklists
  2032. const Hashtable< uint64_t,std::vector<InetAddress> > *blh = (const Hashtable< uint64_t,std::vector<InetAddress> > *)0;
  2033. const std::vector<InetAddress> *gbl = (const std::vector<InetAddress> *)0;
  2034. if (remoteAddr->ss_family == AF_INET) {
  2035. blh = &_v4Blacklists;
  2036. gbl = &_globalV4Blacklist;
  2037. } else if (remoteAddr->ss_family == AF_INET6) {
  2038. blh = &_v6Blacklists;
  2039. gbl = &_globalV6Blacklist;
  2040. }
  2041. if (blh) {
  2042. Mutex::Lock _l(_localConfig_m);
  2043. const std::vector<InetAddress> *l = blh->get(ztaddr);
  2044. if (l) {
  2045. for(std::vector<InetAddress>::const_iterator a(l->begin());a!=l->end();++a) {
  2046. if (a->containsAddress(*reinterpret_cast<const InetAddress *>(remoteAddr)))
  2047. return 0;
  2048. }
  2049. }
  2050. for(std::vector<InetAddress>::const_iterator a(gbl->begin());a!=gbl->end();++a) {
  2051. if (a->containsAddress(*reinterpret_cast<const InetAddress *>(remoteAddr)))
  2052. return 0;
  2053. }
  2054. }
  2055. return 1;
  2056. }
  2057. inline int nodePathLookupFunction(uint64_t ztaddr,int family,struct sockaddr_storage *result)
  2058. {
  2059. const Hashtable< uint64_t,std::vector<InetAddress> > *lh = (const Hashtable< uint64_t,std::vector<InetAddress> > *)0;
  2060. if (family < 0)
  2061. lh = (_node->prng() & 1) ? &_v4Hints : &_v6Hints;
  2062. else if (family == AF_INET)
  2063. lh = &_v4Hints;
  2064. else if (family == AF_INET6)
  2065. lh = &_v6Hints;
  2066. else return 0;
  2067. const std::vector<InetAddress> *l = lh->get(ztaddr);
  2068. if ((l)&&(l->size() > 0)) {
  2069. memcpy(result,&((*l)[(unsigned long)_node->prng() % l->size()]),sizeof(struct sockaddr_storage));
  2070. return 1;
  2071. } else return 0;
  2072. }
  2073. inline void tapFrameHandler(uint64_t nwid,const MAC &from,const MAC &to,unsigned int etherType,unsigned int vlanId,const void *data,unsigned int len)
  2074. {
  2075. _node->processVirtualNetworkFrame((void *)0,OSUtils::now(),nwid,from.toInt(),to.toInt(),etherType,vlanId,data,len,&_nextBackgroundTaskDeadline);
  2076. }
  2077. inline void onHttpRequestToServer(TcpConnection *tc)
  2078. {
  2079. char tmpn[4096];
  2080. std::string data;
  2081. std::string contentType("text/plain"); // default if not changed in handleRequest()
  2082. unsigned int scode = 404;
  2083. // Note that we check allowed IP ranges when HTTP connections are first detected in
  2084. // phyOnTcpData(). If we made it here the source IP is okay.
  2085. try {
  2086. scode = handleControlPlaneHttpRequest(tc->remoteAddr,tc->parser.method,tc->url,tc->headers,tc->readq,data,contentType);
  2087. } catch (std::exception &exc) {
  2088. fprintf(stderr,"WARNING: unexpected exception processing control HTTP request: %s" ZT_EOL_S,exc.what());
  2089. scode = 500;
  2090. } catch ( ... ) {
  2091. fprintf(stderr,"WARNING: unexpected exception processing control HTTP request: unknown exception" ZT_EOL_S);
  2092. scode = 500;
  2093. }
  2094. const char *scodestr;
  2095. switch(scode) {
  2096. case 200: scodestr = "OK"; break;
  2097. case 400: scodestr = "Bad Request"; break;
  2098. case 401: scodestr = "Unauthorized"; break;
  2099. case 403: scodestr = "Forbidden"; break;
  2100. case 404: scodestr = "Not Found"; break;
  2101. case 500: scodestr = "Internal Server Error"; break;
  2102. case 501: scodestr = "Not Implemented"; break;
  2103. case 503: scodestr = "Service Unavailable"; break;
  2104. default: scodestr = "Error"; break;
  2105. }
  2106. 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",
  2107. scode,
  2108. scodestr,
  2109. contentType.c_str(),
  2110. (unsigned long)data.length());
  2111. {
  2112. Mutex::Lock _l(tc->writeq_m);
  2113. tc->writeq = tmpn;
  2114. if (tc->parser.method != HTTP_HEAD)
  2115. tc->writeq.append(data);
  2116. }
  2117. _phy.setNotifyWritable(tc->sock,true);
  2118. }
  2119. inline void onHttpResponseFromClient(TcpConnection *tc)
  2120. {
  2121. _phy.close(tc->sock);
  2122. }
  2123. bool shouldBindInterface(const char *ifname,const InetAddress &ifaddr)
  2124. {
  2125. #if defined(__linux__) || defined(linux) || defined(__LINUX__) || defined(__linux)
  2126. if ((ifname[0] == 'l')&&(ifname[1] == 'o')) return false; // loopback
  2127. if ((ifname[0] == 'z')&&(ifname[1] == 't')) return false; // sanity check: zt#
  2128. if ((ifname[0] == 't')&&(ifname[1] == 'u')&&(ifname[2] == 'n')) return false; // tun# is probably an OpenVPN tunnel or similar
  2129. if ((ifname[0] == 't')&&(ifname[1] == 'a')&&(ifname[2] == 'p')) return false; // tap# is probably an OpenVPN tunnel or similar
  2130. #endif
  2131. #ifdef __APPLE__
  2132. if ((ifname[0] == 'l')&&(ifname[1] == 'o')) return false; // loopback
  2133. if ((ifname[0] == 'z')&&(ifname[1] == 't')) return false; // sanity check: zt#
  2134. if ((ifname[0] == 't')&&(ifname[1] == 'u')&&(ifname[2] == 'n')) return false; // tun# is probably an OpenVPN tunnel or similar
  2135. if ((ifname[0] == 't')&&(ifname[1] == 'a')&&(ifname[2] == 'p')) return false; // tap# is probably an OpenVPN tunnel or similar
  2136. if ((ifname[0] == 'u')&&(ifname[1] == 't')&&(ifname[2] == 'u')&&(ifname[3] == 'n')) return false; // ... as is utun#
  2137. #endif
  2138. {
  2139. Mutex::Lock _l(_localConfig_m);
  2140. for(std::vector<std::string>::const_iterator p(_interfacePrefixBlacklist.begin());p!=_interfacePrefixBlacklist.end();++p) {
  2141. if (!strncmp(p->c_str(),ifname,p->length()))
  2142. return false;
  2143. }
  2144. }
  2145. {
  2146. Mutex::Lock _l(_nets_m);
  2147. for(std::map<uint64_t,NetworkState>::const_iterator n(_nets.begin());n!=_nets.end();++n) {
  2148. if (n->second.tap) {
  2149. std::vector<InetAddress> ips(n->second.tap->ips());
  2150. for(std::vector<InetAddress>::const_iterator i(ips.begin());i!=ips.end();++i) {
  2151. if (i->ipsEqual(ifaddr))
  2152. return false;
  2153. }
  2154. }
  2155. }
  2156. }
  2157. return true;
  2158. }
  2159. bool _trialBind(unsigned int port)
  2160. {
  2161. struct sockaddr_in in4;
  2162. struct sockaddr_in6 in6;
  2163. PhySocket *tb;
  2164. memset(&in4,0,sizeof(in4));
  2165. in4.sin_family = AF_INET;
  2166. in4.sin_port = Utils::hton((uint16_t)port);
  2167. tb = _phy.udpBind(reinterpret_cast<const struct sockaddr *>(&in4),(void *)0,0);
  2168. if (tb) {
  2169. _phy.close(tb,false);
  2170. tb = _phy.tcpListen(reinterpret_cast<const struct sockaddr *>(&in4),(void *)0);
  2171. if (tb) {
  2172. _phy.close(tb,false);
  2173. return true;
  2174. }
  2175. }
  2176. memset(&in6,0,sizeof(in6));
  2177. in6.sin6_family = AF_INET6;
  2178. in6.sin6_port = Utils::hton((uint16_t)port);
  2179. tb = _phy.udpBind(reinterpret_cast<const struct sockaddr *>(&in6),(void *)0,0);
  2180. if (tb) {
  2181. _phy.close(tb,false);
  2182. tb = _phy.tcpListen(reinterpret_cast<const struct sockaddr *>(&in6),(void *)0);
  2183. if (tb) {
  2184. _phy.close(tb,false);
  2185. return true;
  2186. }
  2187. }
  2188. return false;
  2189. }
  2190. };
  2191. static int SnodeVirtualNetworkConfigFunction(ZT_Node *node,void *uptr,void *tptr,uint64_t nwid,void **nuptr,enum ZT_VirtualNetworkConfigOperation op,const ZT_VirtualNetworkConfig *nwconf)
  2192. { return reinterpret_cast<OneServiceImpl *>(uptr)->nodeVirtualNetworkConfigFunction(nwid,nuptr,op,nwconf); }
  2193. static void SnodeEventCallback(ZT_Node *node,void *uptr,void *tptr,enum ZT_Event event,const void *metaData)
  2194. { reinterpret_cast<OneServiceImpl *>(uptr)->nodeEventCallback(event,metaData); }
  2195. static void SnodeStatePutFunction(ZT_Node *node,void *uptr,void *tptr,enum ZT_StateObjectType type,const uint64_t id[2],const void *data,int len)
  2196. { reinterpret_cast<OneServiceImpl *>(uptr)->nodeStatePutFunction(type,id,data,len); }
  2197. static int SnodeStateGetFunction(ZT_Node *node,void *uptr,void *tptr,enum ZT_StateObjectType type,const uint64_t id[2],void *data,unsigned int maxlen)
  2198. { return reinterpret_cast<OneServiceImpl *>(uptr)->nodeStateGetFunction(type,id,data,maxlen); }
  2199. 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)
  2200. { return reinterpret_cast<OneServiceImpl *>(uptr)->nodeWirePacketSendFunction(localSocket,addr,data,len,ttl); }
  2201. 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)
  2202. { reinterpret_cast<OneServiceImpl *>(uptr)->nodeVirtualNetworkFrameFunction(nwid,nuptr,sourceMac,destMac,etherType,vlanId,data,len); }
  2203. static int SnodePathCheckFunction(ZT_Node *node,void *uptr,void *tptr,uint64_t ztaddr,int64_t localSocket,const struct sockaddr_storage *remoteAddr)
  2204. { return reinterpret_cast<OneServiceImpl *>(uptr)->nodePathCheckFunction(ztaddr,localSocket,remoteAddr); }
  2205. static int SnodePathLookupFunction(ZT_Node *node,void *uptr,void *tptr,uint64_t ztaddr,int family,struct sockaddr_storage *result)
  2206. { return reinterpret_cast<OneServiceImpl *>(uptr)->nodePathLookupFunction(ztaddr,family,result); }
  2207. 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)
  2208. { reinterpret_cast<OneServiceImpl *>(uptr)->tapFrameHandler(nwid,from,to,etherType,vlanId,data,len); }
  2209. static int ShttpOnMessageBegin(http_parser *parser)
  2210. {
  2211. TcpConnection *tc = reinterpret_cast<TcpConnection *>(parser->data);
  2212. tc->currentHeaderField = "";
  2213. tc->currentHeaderValue = "";
  2214. tc->messageSize = 0;
  2215. tc->url.clear();
  2216. tc->status.clear();
  2217. tc->headers.clear();
  2218. tc->readq.clear();
  2219. return 0;
  2220. }
  2221. static int ShttpOnUrl(http_parser *parser,const char *ptr,size_t length)
  2222. {
  2223. TcpConnection *tc = reinterpret_cast<TcpConnection *>(parser->data);
  2224. tc->messageSize += (unsigned long)length;
  2225. if (tc->messageSize > ZT_MAX_HTTP_MESSAGE_SIZE)
  2226. return -1;
  2227. tc->url.append(ptr,length);
  2228. return 0;
  2229. }
  2230. #if (HTTP_PARSER_VERSION_MAJOR >= 2) && (HTTP_PARSER_VERSION_MINOR >= 2)
  2231. static int ShttpOnStatus(http_parser *parser,const char *ptr,size_t length)
  2232. #else
  2233. static int ShttpOnStatus(http_parser *parser)
  2234. #endif
  2235. { return 0; }
  2236. static int ShttpOnHeaderField(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. if ((tc->currentHeaderField.length())&&(tc->currentHeaderValue.length())) {
  2243. tc->headers[tc->currentHeaderField] = tc->currentHeaderValue;
  2244. tc->currentHeaderField = "";
  2245. tc->currentHeaderValue = "";
  2246. }
  2247. for(size_t i=0;i<length;++i)
  2248. tc->currentHeaderField.push_back(OSUtils::toLower(ptr[i]));
  2249. return 0;
  2250. }
  2251. static int ShttpOnValue(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. tc->currentHeaderValue.append(ptr,length);
  2258. return 0;
  2259. }
  2260. static int ShttpOnHeadersComplete(http_parser *parser)
  2261. {
  2262. TcpConnection *tc = reinterpret_cast<TcpConnection *>(parser->data);
  2263. if ((tc->currentHeaderField.length())&&(tc->currentHeaderValue.length()))
  2264. tc->headers[tc->currentHeaderField] = tc->currentHeaderValue;
  2265. return 0;
  2266. }
  2267. static int ShttpOnBody(http_parser *parser,const char *ptr,size_t length)
  2268. {
  2269. TcpConnection *tc = reinterpret_cast<TcpConnection *>(parser->data);
  2270. tc->messageSize += (unsigned long)length;
  2271. if (tc->messageSize > ZT_MAX_HTTP_MESSAGE_SIZE)
  2272. return -1;
  2273. tc->readq.append(ptr,length);
  2274. return 0;
  2275. }
  2276. static int ShttpOnMessageComplete(http_parser *parser)
  2277. {
  2278. TcpConnection *tc = reinterpret_cast<TcpConnection *>(parser->data);
  2279. if (tc->type == TcpConnection::TCP_HTTP_INCOMING) {
  2280. tc->parent->onHttpRequestToServer(tc);
  2281. } else {
  2282. tc->parent->onHttpResponseFromClient(tc);
  2283. }
  2284. return 0;
  2285. }
  2286. } // anonymous namespace
  2287. std::string OneService::platformDefaultHomePath()
  2288. {
  2289. return OSUtils::platformDefaultHomePath();
  2290. }
  2291. OneService *OneService::newInstance(const char *hp,unsigned int port) { return new OneServiceImpl(hp,port); }
  2292. OneService::~OneService() {}
  2293. } // namespace ZeroTier