OneService.cpp 92 KB

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