OneService.cpp 103 KB

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