OneService.cpp 101 KB

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