OneService.cpp 103 KB

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