OneService.cpp 100 KB

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