OneService.cpp 96 KB

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