OneService.cpp 86 KB

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