OneService.cpp 101 KB

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