OneService.cpp 96 KB

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