OneService.cpp 90 KB

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