OneService.cpp 88 KB

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