OneService.cpp 103 KB

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