OneService.cpp 96 KB

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