OneService.cpp 97 KB

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