OneService.cpp 98 KB

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