OneService.cpp 88 KB

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