OneService.cpp 88 KB

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