OneService.cpp 102 KB

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