OneService.cpp 105 KB

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