OneService.cpp 89 KB

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