OneService.cpp 100 KB

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