OneService.cpp 69 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008
  1. /*
  2. * ZeroTier One - Network Virtualization Everywhere
  3. * Copyright (C) 2011-2016 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. #include <stdio.h>
  19. #include <stdlib.h>
  20. #include <string.h>
  21. #include <stdint.h>
  22. #include <string>
  23. #include <map>
  24. #include <set>
  25. #include <vector>
  26. #include <algorithm>
  27. #include <list>
  28. #include "../version.h"
  29. #include "../include/ZeroTierOne.h"
  30. #include "../node/Constants.hpp"
  31. #include "../node/Mutex.hpp"
  32. #include "../node/Node.hpp"
  33. #include "../node/Utils.hpp"
  34. #include "../node/InetAddress.hpp"
  35. #include "../node/MAC.hpp"
  36. #include "../node/Identity.hpp"
  37. #include "../osdep/Phy.hpp"
  38. #include "../osdep/Thread.hpp"
  39. #include "../osdep/OSUtils.hpp"
  40. #include "../osdep/Http.hpp"
  41. #include "../osdep/BackgroundResolver.hpp"
  42. #include "../osdep/PortMapper.hpp"
  43. #include "../osdep/Binder.hpp"
  44. #include "../osdep/ManagedRoute.hpp"
  45. #include "OneService.hpp"
  46. #include "ControlPlane.hpp"
  47. #include "ClusterGeoIpService.hpp"
  48. #include "ClusterDefinition.hpp"
  49. #include "SoftwareUpdater.hpp"
  50. #ifdef ZT_USE_SYSTEM_HTTP_PARSER
  51. #include <http_parser.h>
  52. #else
  53. #include "../ext/http-parser/http_parser.h"
  54. #endif
  55. #include "../ext/json/json.hpp"
  56. using json = nlohmann::json;
  57. /**
  58. * Uncomment to enable UDP breakage switch
  59. *
  60. * If this is defined, the presence of a file called /tmp/ZT_BREAK_UDP
  61. * will cause direct UDP TX/RX to stop working. This can be used to
  62. * test TCP tunneling fallback and other robustness features. Deleting
  63. * this file will cause it to start working again.
  64. */
  65. //#define ZT_BREAK_UDP
  66. #include "../controller/EmbeddedNetworkController.hpp"
  67. #ifdef __WINDOWS__
  68. #include <WinSock2.h>
  69. #include <Windows.h>
  70. #include <ShlObj.h>
  71. #include <netioapi.h>
  72. #include <iphlpapi.h>
  73. #else
  74. #include <sys/types.h>
  75. #include <sys/socket.h>
  76. #include <sys/wait.h>
  77. #include <unistd.h>
  78. #include <ifaddrs.h>
  79. #endif
  80. // Include the right tap device driver for this platform -- add new platforms here
  81. #ifdef ZT_SERVICE_NETCON
  82. // In network containers builds, use the virtual netcon endpoint instead of a tun/tap port driver
  83. #include "../netcon/NetconEthernetTap.hpp"
  84. namespace ZeroTier { typedef NetconEthernetTap EthernetTap; }
  85. #else // not ZT_SERVICE_NETCON so pick a tap driver
  86. #ifdef __APPLE__
  87. #include "../osdep/OSXEthernetTap.hpp"
  88. namespace ZeroTier { typedef OSXEthernetTap EthernetTap; }
  89. #endif // __APPLE__
  90. #ifdef __LINUX__
  91. #include "../osdep/LinuxEthernetTap.hpp"
  92. namespace ZeroTier { typedef LinuxEthernetTap EthernetTap; }
  93. #endif // __LINUX__
  94. #ifdef __WINDOWS__
  95. #include "../osdep/WindowsEthernetTap.hpp"
  96. namespace ZeroTier { typedef WindowsEthernetTap EthernetTap; }
  97. #endif // __WINDOWS__
  98. #ifdef __FreeBSD__
  99. #include "../osdep/BSDEthernetTap.hpp"
  100. namespace ZeroTier { typedef BSDEthernetTap EthernetTap; }
  101. #endif // __FreeBSD__
  102. #endif // ZT_SERVICE_NETCON
  103. // Sanity limits for HTTP
  104. #define ZT_MAX_HTTP_MESSAGE_SIZE (1024 * 1024 * 64)
  105. #define ZT_MAX_HTTP_CONNECTIONS 64
  106. // Interface metric for ZeroTier taps -- this ensures that if we are on WiFi and also
  107. // bridged via ZeroTier to the same LAN traffic will (if the OS is sane) prefer WiFi.
  108. #define ZT_IF_METRIC 5000
  109. // How often to check for new multicast subscriptions on a tap device
  110. #define ZT_TAP_CHECK_MULTICAST_INTERVAL 5000
  111. // Path under ZT1 home for controller database if controller is enabled
  112. #define ZT_CONTROLLER_DB_PATH "controller.d"
  113. // TCP fallback relay host -- geo-distributed using Amazon Route53 geo-aware DNS
  114. #define ZT_TCP_FALLBACK_RELAY "tcp-fallback.zerotier.com"
  115. #define ZT_TCP_FALLBACK_RELAY_PORT 443
  116. // Frequency at which we re-resolve the TCP fallback relay
  117. #define ZT_TCP_FALLBACK_RERESOLVE_DELAY 86400000
  118. // Attempt to engage TCP fallback after this many ms of no reply to packets sent to global-scope IPs
  119. #define ZT_TCP_FALLBACK_AFTER 60000
  120. // How often to check for local interface addresses
  121. #define ZT_LOCAL_INTERFACE_CHECK_INTERVAL 60000
  122. namespace ZeroTier {
  123. namespace {
  124. static std::string _trimString(const std::string &s)
  125. {
  126. unsigned long end = (unsigned long)s.length();
  127. while (end) {
  128. char c = s[end - 1];
  129. if ((c == ' ')||(c == '\r')||(c == '\n')||(!c)||(c == '\t'))
  130. --end;
  131. else break;
  132. }
  133. unsigned long start = 0;
  134. while (start < end) {
  135. char c = s[start];
  136. if ((c == ' ')||(c == '\r')||(c == '\n')||(!c)||(c == '\t'))
  137. ++start;
  138. else break;
  139. }
  140. return s.substr(start,end - start);
  141. }
  142. class OneServiceImpl;
  143. static int SnodeVirtualNetworkConfigFunction(ZT_Node *node,void *uptr,uint64_t nwid,void **nuptr,enum ZT_VirtualNetworkConfigOperation op,const ZT_VirtualNetworkConfig *nwconf);
  144. static void SnodeEventCallback(ZT_Node *node,void *uptr,enum ZT_Event event,const void *metaData);
  145. static long SnodeDataStoreGetFunction(ZT_Node *node,void *uptr,const char *name,void *buf,unsigned long bufSize,unsigned long readIndex,unsigned long *totalSize);
  146. static int SnodeDataStorePutFunction(ZT_Node *node,void *uptr,const char *name,const void *data,unsigned long len,int secure);
  147. static int SnodeWirePacketSendFunction(ZT_Node *node,void *uptr,const struct sockaddr_storage *localAddr,const struct sockaddr_storage *addr,const void *data,unsigned int len,unsigned int ttl);
  148. static void SnodeVirtualNetworkFrameFunction(ZT_Node *node,void *uptr,uint64_t nwid,void **nuptr,uint64_t sourceMac,uint64_t destMac,unsigned int etherType,unsigned int vlanId,const void *data,unsigned int len);
  149. static int SnodePathCheckFunction(ZT_Node *node,void *uptr,uint64_t ztaddr,const struct sockaddr_storage *localAddr,const struct sockaddr_storage *remoteAddr);
  150. static int SnodePathLookupFunction(ZT_Node *node,void *uptr,uint64_t ztaddr,int family,struct sockaddr_storage *result);
  151. #ifdef ZT_ENABLE_CLUSTER
  152. static void SclusterSendFunction(void *uptr,unsigned int toMemberId,const void *data,unsigned int len);
  153. static int SclusterGeoIpFunction(void *uptr,const struct sockaddr_storage *addr,int *x,int *y,int *z);
  154. #endif
  155. static void StapFrameHandler(void *uptr,uint64_t nwid,const MAC &from,const MAC &to,unsigned int etherType,unsigned int vlanId,const void *data,unsigned int len);
  156. static int ShttpOnMessageBegin(http_parser *parser);
  157. static int ShttpOnUrl(http_parser *parser,const char *ptr,size_t length);
  158. #if (HTTP_PARSER_VERSION_MAJOR >= 2) && (HTTP_PARSER_VERSION_MINOR >= 2)
  159. static int ShttpOnStatus(http_parser *parser,const char *ptr,size_t length);
  160. #else
  161. static int ShttpOnStatus(http_parser *parser);
  162. #endif
  163. static int ShttpOnHeaderField(http_parser *parser,const char *ptr,size_t length);
  164. static int ShttpOnValue(http_parser *parser,const char *ptr,size_t length);
  165. static int ShttpOnHeadersComplete(http_parser *parser);
  166. static int ShttpOnBody(http_parser *parser,const char *ptr,size_t length);
  167. static int ShttpOnMessageComplete(http_parser *parser);
  168. #if (HTTP_PARSER_VERSION_MAJOR >= 2) && (HTTP_PARSER_VERSION_MINOR >= 1)
  169. static const struct http_parser_settings HTTP_PARSER_SETTINGS = {
  170. ShttpOnMessageBegin,
  171. ShttpOnUrl,
  172. ShttpOnStatus,
  173. ShttpOnHeaderField,
  174. ShttpOnValue,
  175. ShttpOnHeadersComplete,
  176. ShttpOnBody,
  177. ShttpOnMessageComplete
  178. };
  179. #else
  180. static const struct http_parser_settings HTTP_PARSER_SETTINGS = {
  181. ShttpOnMessageBegin,
  182. ShttpOnUrl,
  183. ShttpOnHeaderField,
  184. ShttpOnValue,
  185. ShttpOnHeadersComplete,
  186. ShttpOnBody,
  187. ShttpOnMessageComplete
  188. };
  189. #endif
  190. struct TcpConnection
  191. {
  192. enum {
  193. TCP_HTTP_INCOMING,
  194. TCP_HTTP_OUTGOING, // not currently used
  195. TCP_TUNNEL_OUTGOING // fale-SSL outgoing tunnel -- HTTP-related fields are not used
  196. } type;
  197. bool shouldKeepAlive;
  198. OneServiceImpl *parent;
  199. PhySocket *sock;
  200. InetAddress from;
  201. http_parser parser;
  202. unsigned long messageSize;
  203. uint64_t lastActivity;
  204. std::string currentHeaderField;
  205. std::string currentHeaderValue;
  206. std::string url;
  207. std::string status;
  208. std::map< std::string,std::string > headers;
  209. std::string body;
  210. std::string writeBuf;
  211. Mutex writeBuf_m;
  212. };
  213. // Used to pseudo-randomize local source port picking
  214. static volatile unsigned int _udpPortPickerCounter = 0;
  215. class OneServiceImpl : public OneService
  216. {
  217. public:
  218. // begin member variables --------------------------------------------------
  219. const std::string _homePath;
  220. BackgroundResolver _tcpFallbackResolver;
  221. EmbeddedNetworkController *_controller;
  222. Phy<OneServiceImpl *> _phy;
  223. Node *_node;
  224. SoftwareUpdater *_updater;
  225. unsigned int _primaryPort;
  226. // Local configuration and memo-ized static path definitions
  227. json _localConfig;
  228. Hashtable< uint64_t,std::vector<InetAddress> > _v4Hints;
  229. Hashtable< uint64_t,std::vector<InetAddress> > _v6Hints;
  230. Hashtable< uint64_t,std::vector<InetAddress> > _v4Blacklists;
  231. Hashtable< uint64_t,std::vector<InetAddress> > _v6Blacklists;
  232. std::vector< InetAddress > _globalV4Blacklist;
  233. std::vector< InetAddress > _globalV6Blacklist;
  234. std::vector< InetAddress > _allowManagementFrom;
  235. std::vector< std::string > _interfacePrefixBlacklist;
  236. Mutex _localConfig_m;
  237. /*
  238. * To attempt to handle NAT/gateway craziness we use three local UDP ports:
  239. *
  240. * [0] is the normal/default port, usually 9993
  241. * [1] is a port dervied from our ZeroTier address
  242. * [2] is a port computed from the normal/default for use with uPnP/NAT-PMP mappings
  243. *
  244. * [2] exists because on some gateways trying to do regular NAT-t interferes
  245. * destructively with uPnP port mapping behavior in very weird buggy ways.
  246. * It's only used if uPnP/NAT-PMP is enabled in this build.
  247. */
  248. Binder _bindings[3];
  249. unsigned int _ports[3];
  250. uint16_t _portsBE[3]; // ports in big-endian network byte order as in sockaddr
  251. // Sockets for JSON API -- bound only to V4 and V6 localhost
  252. PhySocket *_v4TcpControlSocket;
  253. PhySocket *_v6TcpControlSocket;
  254. // JSON API handler
  255. ControlPlane *_controlPlane;
  256. // Time we last received a packet from a global address
  257. uint64_t _lastDirectReceiveFromGlobal;
  258. #ifdef ZT_TCP_FALLBACK_RELAY
  259. uint64_t _lastSendToGlobalV4;
  260. #endif
  261. // Last potential sleep/wake event
  262. uint64_t _lastRestart;
  263. // Deadline for the next background task service function
  264. volatile uint64_t _nextBackgroundTaskDeadline;
  265. // Configured networks
  266. struct NetworkState
  267. {
  268. NetworkState() :
  269. tap((EthernetTap *)0)
  270. {
  271. // Real defaults are in network 'up' code in network event handler
  272. settings.allowManaged = true;
  273. settings.allowGlobal = false;
  274. settings.allowDefault = false;
  275. }
  276. EthernetTap *tap;
  277. ZT_VirtualNetworkConfig config; // memcpy() of raw config from core
  278. std::vector<InetAddress> managedIps;
  279. std::list< SharedPtr<ManagedRoute> > managedRoutes;
  280. NetworkSettings settings;
  281. };
  282. std::map<uint64_t,NetworkState> _nets;
  283. Mutex _nets_m;
  284. // Active TCP/IP connections
  285. std::set< TcpConnection * > _tcpConnections; // no mutex for this since it's done in the main loop thread only
  286. TcpConnection *_tcpFallbackTunnel;
  287. // Termination status information
  288. ReasonForTermination _termReason;
  289. std::string _fatalErrorMessage;
  290. Mutex _termReason_m;
  291. // uPnP/NAT-PMP port mapper if enabled
  292. #ifdef ZT_USE_MINIUPNPC
  293. PortMapper *_portMapper;
  294. #endif
  295. // Cluster management instance if enabled
  296. #ifdef ZT_ENABLE_CLUSTER
  297. PhySocket *_clusterMessageSocket;
  298. ClusterDefinition *_clusterDefinition;
  299. unsigned int _clusterMemberId;
  300. #endif
  301. // Set to false to force service to stop
  302. volatile bool _run;
  303. Mutex _run_m;
  304. // end member variables ----------------------------------------------------
  305. OneServiceImpl(const char *hp,unsigned int port) :
  306. _homePath((hp) ? hp : ".")
  307. ,_tcpFallbackResolver(ZT_TCP_FALLBACK_RELAY)
  308. ,_controller((EmbeddedNetworkController *)0)
  309. ,_phy(this,false,true)
  310. ,_node((Node *)0)
  311. ,_updater((SoftwareUpdater *)0)
  312. ,_primaryPort(port)
  313. ,_controlPlane((ControlPlane *)0)
  314. ,_lastDirectReceiveFromGlobal(0)
  315. #ifdef ZT_TCP_FALLBACK_RELAY
  316. ,_lastSendToGlobalV4(0)
  317. #endif
  318. ,_lastRestart(0)
  319. ,_nextBackgroundTaskDeadline(0)
  320. ,_tcpFallbackTunnel((TcpConnection *)0)
  321. ,_termReason(ONE_STILL_RUNNING)
  322. #ifdef ZT_USE_MINIUPNPC
  323. ,_portMapper((PortMapper *)0)
  324. #endif
  325. #ifdef ZT_ENABLE_CLUSTER
  326. ,_clusterMessageSocket((PhySocket *)0)
  327. ,_clusterDefinition((ClusterDefinition *)0)
  328. ,_clusterMemberId(0)
  329. #endif
  330. ,_run(true)
  331. {
  332. _ports[0] = 0;
  333. _ports[1] = 0;
  334. _ports[2] = 0;
  335. }
  336. virtual ~OneServiceImpl()
  337. {
  338. for(int i=0;i<3;++i)
  339. _bindings[i].closeAll(_phy);
  340. _phy.close(_v4TcpControlSocket);
  341. _phy.close(_v6TcpControlSocket);
  342. #ifdef ZT_ENABLE_CLUSTER
  343. _phy.close(_clusterMessageSocket);
  344. #endif
  345. #ifdef ZT_USE_MINIUPNPC
  346. delete _portMapper;
  347. #endif
  348. delete _controller;
  349. #ifdef ZT_ENABLE_CLUSTER
  350. delete _clusterDefinition;
  351. #endif
  352. }
  353. virtual ReasonForTermination run()
  354. {
  355. try {
  356. std::string authToken;
  357. {
  358. std::string authTokenPath(_homePath + ZT_PATH_SEPARATOR_S + "authtoken.secret");
  359. if (!OSUtils::readFile(authTokenPath.c_str(),authToken)) {
  360. unsigned char foo[24];
  361. Utils::getSecureRandom(foo,sizeof(foo));
  362. authToken = "";
  363. for(unsigned int i=0;i<sizeof(foo);++i)
  364. authToken.push_back("abcdefghijklmnopqrstuvwxyz0123456789"[(unsigned long)foo[i] % 36]);
  365. if (!OSUtils::writeFile(authTokenPath.c_str(),authToken)) {
  366. Mutex::Lock _l(_termReason_m);
  367. _termReason = ONE_UNRECOVERABLE_ERROR;
  368. _fatalErrorMessage = "authtoken.secret could not be written";
  369. return _termReason;
  370. } else {
  371. OSUtils::lockDownFile(authTokenPath.c_str(),false);
  372. }
  373. }
  374. }
  375. authToken = _trimString(authToken);
  376. // Clean up any legacy files if present
  377. OSUtils::rm((_homePath + ZT_PATH_SEPARATOR_S + "peers.save").c_str());
  378. {
  379. struct ZT_Node_Callbacks cb;
  380. cb.version = 0;
  381. cb.dataStoreGetFunction = SnodeDataStoreGetFunction;
  382. cb.dataStorePutFunction = SnodeDataStorePutFunction;
  383. cb.wirePacketSendFunction = SnodeWirePacketSendFunction;
  384. cb.virtualNetworkFrameFunction = SnodeVirtualNetworkFrameFunction;
  385. cb.virtualNetworkConfigFunction = SnodeVirtualNetworkConfigFunction;
  386. cb.eventCallback = SnodeEventCallback;
  387. cb.pathCheckFunction = SnodePathCheckFunction;
  388. cb.pathLookupFunction = SnodePathLookupFunction;
  389. _node = new Node(this,&cb,OSUtils::now());
  390. }
  391. _updater = new SoftwareUpdater(*_node,_homePath);
  392. _updater->loadUpdatesToDistribute();
  393. // Read local configuration
  394. {
  395. uint64_t trustedPathIds[ZT_MAX_TRUSTED_PATHS];
  396. InetAddress trustedPathNetworks[ZT_MAX_TRUSTED_PATHS];
  397. unsigned int trustedPathCount = 0;
  398. // Old style "trustedpaths" flat file -- will eventually go away
  399. FILE *trustpaths = fopen((_homePath + ZT_PATH_SEPARATOR_S + "trustedpaths").c_str(),"r");
  400. if (trustpaths) {
  401. char buf[1024];
  402. while ((fgets(buf,sizeof(buf),trustpaths))&&(trustedPathCount < ZT_MAX_TRUSTED_PATHS)) {
  403. int fno = 0;
  404. char *saveptr = (char *)0;
  405. uint64_t trustedPathId = 0;
  406. InetAddress trustedPathNetwork;
  407. for(char *f=Utils::stok(buf,"=\r\n \t",&saveptr);(f);f=Utils::stok((char *)0,"=\r\n \t",&saveptr)) {
  408. if (fno == 0) {
  409. trustedPathId = Utils::hexStrToU64(f);
  410. } else if (fno == 1) {
  411. trustedPathNetwork = InetAddress(f);
  412. } else break;
  413. ++fno;
  414. }
  415. if ( (trustedPathId != 0) && ((trustedPathNetwork.ss_family == AF_INET)||(trustedPathNetwork.ss_family == AF_INET6)) && (trustedPathNetwork.ipScope() != InetAddress::IP_SCOPE_GLOBAL) && (trustedPathNetwork.netmaskBits() > 0) ) {
  416. trustedPathIds[trustedPathCount] = trustedPathId;
  417. trustedPathNetworks[trustedPathCount] = trustedPathNetwork;
  418. ++trustedPathCount;
  419. }
  420. }
  421. fclose(trustpaths);
  422. }
  423. // Read local config file
  424. Mutex::Lock _l2(_localConfig_m);
  425. std::string lcbuf;
  426. if (OSUtils::readFile((_homePath + ZT_PATH_SEPARATOR_S + "local.conf").c_str(),lcbuf)) {
  427. try {
  428. _localConfig = OSUtils::jsonParse(lcbuf);
  429. if (!_localConfig.is_object()) {
  430. fprintf(stderr,"WARNING: unable to parse local.conf (root element is not a JSON object)" ZT_EOL_S);
  431. }
  432. } catch ( ... ) {
  433. fprintf(stderr,"WARNING: unable to parse local.conf (invalid JSON)" ZT_EOL_S);
  434. }
  435. }
  436. // Get any trusted paths in local.conf (we'll parse the rest of physical[] elsewhere)
  437. json &physical = _localConfig["physical"];
  438. if (physical.is_object()) {
  439. for(json::iterator phy(physical.begin());phy!=physical.end();++phy) {
  440. InetAddress net(OSUtils::jsonString(phy.key(),""));
  441. if (net) {
  442. if (phy.value().is_object()) {
  443. uint64_t tpid;
  444. if ((tpid = OSUtils::jsonInt(phy.value()["trustedPathId"],0ULL)) != 0ULL) {
  445. 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) ) {
  446. trustedPathIds[trustedPathCount] = tpid;
  447. trustedPathNetworks[trustedPathCount] = net;
  448. ++trustedPathCount;
  449. }
  450. }
  451. }
  452. }
  453. }
  454. }
  455. // Set trusted paths if there are any
  456. if (trustedPathCount)
  457. _node->setTrustedPaths(reinterpret_cast<const struct sockaddr_storage *>(trustedPathNetworks),trustedPathIds,trustedPathCount);
  458. }
  459. applyLocalConfig();
  460. // Bind TCP control socket
  461. const int portTrials = (_primaryPort == 0) ? 256 : 1; // if port is 0, pick random
  462. for(int k=0;k<portTrials;++k) {
  463. if (_primaryPort == 0) {
  464. unsigned int randp = 0;
  465. Utils::getSecureRandom(&randp,sizeof(randp));
  466. _primaryPort = 20000 + (randp % 45500);
  467. }
  468. if (_trialBind(_primaryPort)) {
  469. struct sockaddr_in in4;
  470. memset(&in4,0,sizeof(in4));
  471. in4.sin_family = AF_INET;
  472. in4.sin_addr.s_addr = Utils::hton((uint32_t)((_allowManagementFrom.size() > 0) ? 0 : 0x7f000001)); // right now we just listen for TCP @127.0.0.1
  473. in4.sin_port = Utils::hton((uint16_t)_primaryPort);
  474. _v4TcpControlSocket = _phy.tcpListen((const struct sockaddr *)&in4,this);
  475. struct sockaddr_in6 in6;
  476. memset((void *)&in6,0,sizeof(in6));
  477. in6.sin6_family = AF_INET6;
  478. in6.sin6_port = in4.sin_port;
  479. if (_allowManagementFrom.size() == 0)
  480. in6.sin6_addr.s6_addr[15] = 1; // IPv6 localhost == ::1
  481. _v6TcpControlSocket = _phy.tcpListen((const struct sockaddr *)&in6,this);
  482. // We must bind one of IPv4 or IPv6 -- support either failing to support hosts that
  483. // have only IPv4 or only IPv6 stacks.
  484. if ((_v4TcpControlSocket)||(_v6TcpControlSocket)) {
  485. _ports[0] = _primaryPort;
  486. break;
  487. } else {
  488. if (_v4TcpControlSocket)
  489. _phy.close(_v4TcpControlSocket,false);
  490. if (_v6TcpControlSocket)
  491. _phy.close(_v6TcpControlSocket,false);
  492. _primaryPort = 0;
  493. }
  494. } else {
  495. _primaryPort = 0;
  496. }
  497. }
  498. if (_ports[0] == 0) {
  499. Mutex::Lock _l(_termReason_m);
  500. _termReason = ONE_UNRECOVERABLE_ERROR;
  501. _fatalErrorMessage = "cannot bind to local control interface port";
  502. return _termReason;
  503. }
  504. // Write file containing primary port to be read by CLIs, etc.
  505. char portstr[64];
  506. Utils::snprintf(portstr,sizeof(portstr),"%u",_ports[0]);
  507. OSUtils::writeFile((_homePath + ZT_PATH_SEPARATOR_S + "zerotier-one.port").c_str(),std::string(portstr));
  508. // Attempt to bind to a secondary port chosen from our ZeroTier address.
  509. // This exists because there are buggy NATs out there that fail if more
  510. // than one device behind the same NAT tries to use the same internal
  511. // private address port number.
  512. _ports[1] = 20000 + ((unsigned int)_node->address() % 45500);
  513. for(int i=0;;++i) {
  514. if (i > 1000) {
  515. _ports[1] = 0;
  516. break;
  517. } else if (++_ports[1] >= 65536) {
  518. _ports[1] = 20000;
  519. }
  520. if (_trialBind(_ports[1]))
  521. break;
  522. }
  523. #ifdef ZT_USE_MINIUPNPC
  524. // If we're running uPnP/NAT-PMP, bind a *third* port for that. We can't
  525. // use the other two ports for that because some NATs do really funky
  526. // stuff with ports that are explicitly mapped that breaks things.
  527. if (_ports[1]) {
  528. _ports[2] = _ports[1];
  529. for(int i=0;;++i) {
  530. if (i > 1000) {
  531. _ports[2] = 0;
  532. break;
  533. } else if (++_ports[2] >= 65536) {
  534. _ports[2] = 20000;
  535. }
  536. if (_trialBind(_ports[2]))
  537. break;
  538. }
  539. if (_ports[2]) {
  540. char uniqueName[64];
  541. Utils::snprintf(uniqueName,sizeof(uniqueName),"ZeroTier/%.10llx@%u",_node->address(),_ports[2]);
  542. _portMapper = new PortMapper(_ports[2],uniqueName);
  543. }
  544. }
  545. #endif
  546. // Populate ports in big-endian format for quick compare
  547. for(int i=0;i<3;++i)
  548. _portsBE[i] = Utils::hton((uint16_t)_ports[i]);
  549. _controller = new EmbeddedNetworkController(_node,(_homePath + ZT_PATH_SEPARATOR_S + ZT_CONTROLLER_DB_PATH).c_str(),(FILE *)0);
  550. _node->setNetconfMaster((void *)_controller);
  551. #ifdef ZT_ENABLE_CLUSTER
  552. if (OSUtils::fileExists((_homePath + ZT_PATH_SEPARATOR_S + "cluster").c_str())) {
  553. _clusterDefinition = new ClusterDefinition(_node->address(),(_homePath + ZT_PATH_SEPARATOR_S + "cluster").c_str());
  554. if (_clusterDefinition->size() > 0) {
  555. std::vector<ClusterDefinition::MemberDefinition> members(_clusterDefinition->members());
  556. for(std::vector<ClusterDefinition::MemberDefinition>::iterator m(members.begin());m!=members.end();++m) {
  557. PhySocket *cs = _phy.udpBind(reinterpret_cast<const struct sockaddr *>(&(m->clusterEndpoint)));
  558. if (cs) {
  559. if (_clusterMessageSocket) {
  560. _phy.close(_clusterMessageSocket,false);
  561. _phy.close(cs,false);
  562. Mutex::Lock _l(_termReason_m);
  563. _termReason = ONE_UNRECOVERABLE_ERROR;
  564. _fatalErrorMessage = "cluster: can't determine my cluster member ID: able to bind more than one cluster message socket IP/port!";
  565. return _termReason;
  566. }
  567. _clusterMessageSocket = cs;
  568. _clusterMemberId = m->id;
  569. }
  570. }
  571. if (!_clusterMessageSocket) {
  572. Mutex::Lock _l(_termReason_m);
  573. _termReason = ONE_UNRECOVERABLE_ERROR;
  574. _fatalErrorMessage = "cluster: can't determine my cluster member ID: unable to bind to any cluster message socket IP/port.";
  575. return _termReason;
  576. }
  577. const ClusterDefinition::MemberDefinition &me = (*_clusterDefinition)[_clusterMemberId];
  578. InetAddress endpoints[255];
  579. unsigned int numEndpoints = 0;
  580. for(std::vector<InetAddress>::const_iterator i(me.zeroTierEndpoints.begin());i!=me.zeroTierEndpoints.end();++i)
  581. endpoints[numEndpoints++] = *i;
  582. if (_node->clusterInit(_clusterMemberId,reinterpret_cast<const struct sockaddr_storage *>(endpoints),numEndpoints,me.x,me.y,me.z,&SclusterSendFunction,this,_clusterDefinition->geo().available() ? &SclusterGeoIpFunction : 0,this) == ZT_RESULT_OK) {
  583. std::vector<ClusterDefinition::MemberDefinition> members(_clusterDefinition->members());
  584. for(std::vector<ClusterDefinition::MemberDefinition>::iterator m(members.begin());m!=members.end();++m) {
  585. if (m->id != _clusterMemberId)
  586. _node->clusterAddMember(m->id);
  587. }
  588. }
  589. } else {
  590. delete _clusterDefinition;
  591. _clusterDefinition = (ClusterDefinition *)0;
  592. }
  593. }
  594. #endif
  595. _controlPlane = new ControlPlane(this,_node,(_homePath + ZT_PATH_SEPARATOR_S + "ui").c_str());
  596. _controlPlane->addAuthToken(authToken.c_str());
  597. _controlPlane->setController(_controller);
  598. { // Remember networks from previous session
  599. std::vector<std::string> networksDotD(OSUtils::listDirectory((_homePath + ZT_PATH_SEPARATOR_S + "networks.d").c_str()));
  600. for(std::vector<std::string>::iterator f(networksDotD.begin());f!=networksDotD.end();++f) {
  601. std::size_t dot = f->find_last_of('.');
  602. if ((dot == 16)&&(f->substr(16) == ".conf"))
  603. _node->join(Utils::hexStrToU64(f->substr(0,dot).c_str()),(void *)0);
  604. }
  605. }
  606. _nextBackgroundTaskDeadline = 0;
  607. uint64_t clockShouldBe = OSUtils::now();
  608. _lastRestart = clockShouldBe;
  609. uint64_t lastTapMulticastGroupCheck = 0;
  610. uint64_t lastTcpFallbackResolve = 0;
  611. uint64_t lastBindRefresh = 0;
  612. uint64_t lastUpdateCheck = clockShouldBe;
  613. 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
  614. for(;;) {
  615. _run_m.lock();
  616. if (!_run) {
  617. _run_m.unlock();
  618. _termReason_m.lock();
  619. _termReason = ONE_NORMAL_TERMINATION;
  620. _termReason_m.unlock();
  621. break;
  622. } else {
  623. _run_m.unlock();
  624. }
  625. const uint64_t now = OSUtils::now();
  626. // Attempt to detect sleep/wake events by detecting delay overruns
  627. bool restarted = false;
  628. if ((now > clockShouldBe)&&((now - clockShouldBe) > 10000)) {
  629. _lastRestart = now;
  630. restarted = true;
  631. }
  632. // Check for updates (if enabled)
  633. if ((_updater)&&((now - lastUpdateCheck) > 10000)) {
  634. lastUpdateCheck = now;
  635. _updater->check(now);
  636. }
  637. // Refresh bindings in case device's interfaces have changed, and also sync routes to update any shadow routes (e.g. shadow default)
  638. if (((now - lastBindRefresh) >= ZT_BINDER_REFRESH_PERIOD)||(restarted)) {
  639. lastBindRefresh = now;
  640. for(int i=0;i<3;++i) {
  641. if (_ports[i]) {
  642. _bindings[i].refresh(_phy,_ports[i],*this);
  643. }
  644. }
  645. {
  646. Mutex::Lock _l(_nets_m);
  647. for(std::map<uint64_t,NetworkState>::iterator n(_nets.begin());n!=_nets.end();++n) {
  648. if (n->second.tap)
  649. syncManagedStuff(n->second,false,true);
  650. }
  651. }
  652. }
  653. uint64_t dl = _nextBackgroundTaskDeadline;
  654. if (dl <= now) {
  655. _node->processBackgroundTasks(now,&_nextBackgroundTaskDeadline);
  656. dl = _nextBackgroundTaskDeadline;
  657. }
  658. if ((now - lastTcpFallbackResolve) >= ZT_TCP_FALLBACK_RERESOLVE_DELAY) {
  659. lastTcpFallbackResolve = now;
  660. _tcpFallbackResolver.resolveNow();
  661. }
  662. if ((_tcpFallbackTunnel)&&((now - _lastDirectReceiveFromGlobal) < (ZT_TCP_FALLBACK_AFTER / 2)))
  663. _phy.close(_tcpFallbackTunnel->sock);
  664. if ((now - lastTapMulticastGroupCheck) >= ZT_TAP_CHECK_MULTICAST_INTERVAL) {
  665. lastTapMulticastGroupCheck = now;
  666. Mutex::Lock _l(_nets_m);
  667. for(std::map<uint64_t,NetworkState>::const_iterator n(_nets.begin());n!=_nets.end();++n) {
  668. if (n->second.tap) {
  669. std::vector<MulticastGroup> added,removed;
  670. n->second.tap->scanMulticastGroups(added,removed);
  671. for(std::vector<MulticastGroup>::iterator m(added.begin());m!=added.end();++m)
  672. _node->multicastSubscribe(n->first,m->mac().toInt(),m->adi());
  673. for(std::vector<MulticastGroup>::iterator m(removed.begin());m!=removed.end();++m)
  674. _node->multicastUnsubscribe(n->first,m->mac().toInt(),m->adi());
  675. }
  676. }
  677. }
  678. if ((now - lastLocalInterfaceAddressCheck) >= ZT_LOCAL_INTERFACE_CHECK_INTERVAL) {
  679. lastLocalInterfaceAddressCheck = now;
  680. _node->clearLocalInterfaceAddresses();
  681. #ifdef ZT_USE_MINIUPNPC
  682. if (_portMapper) {
  683. std::vector<InetAddress> mappedAddresses(_portMapper->get());
  684. for(std::vector<InetAddress>::const_iterator ext(mappedAddresses.begin());ext!=mappedAddresses.end();++ext)
  685. _node->addLocalInterfaceAddress(reinterpret_cast<const struct sockaddr_storage *>(&(*ext)));
  686. }
  687. #endif
  688. std::vector<InetAddress> boundAddrs(_bindings[0].allBoundLocalInterfaceAddresses());
  689. for(std::vector<InetAddress>::const_iterator i(boundAddrs.begin());i!=boundAddrs.end();++i)
  690. _node->addLocalInterfaceAddress(reinterpret_cast<const struct sockaddr_storage *>(&(*i)));
  691. }
  692. const unsigned long delay = (dl > now) ? (unsigned long)(dl - now) : 100;
  693. clockShouldBe = now + (uint64_t)delay;
  694. _phy.poll(delay);
  695. }
  696. } catch (std::exception &exc) {
  697. Mutex::Lock _l(_termReason_m);
  698. _termReason = ONE_UNRECOVERABLE_ERROR;
  699. _fatalErrorMessage = exc.what();
  700. } catch ( ... ) {
  701. Mutex::Lock _l(_termReason_m);
  702. _termReason = ONE_UNRECOVERABLE_ERROR;
  703. _fatalErrorMessage = "unexpected exception in main thread";
  704. }
  705. try {
  706. while (!_tcpConnections.empty())
  707. _phy.close((*_tcpConnections.begin())->sock);
  708. } catch ( ... ) {}
  709. {
  710. Mutex::Lock _l(_nets_m);
  711. for(std::map<uint64_t,NetworkState>::iterator n(_nets.begin());n!=_nets.end();++n)
  712. delete n->second.tap;
  713. _nets.clear();
  714. }
  715. delete _controlPlane;
  716. _controlPlane = (ControlPlane *)0;
  717. delete _updater;
  718. _updater = (SoftwareUpdater *)0;
  719. delete _node;
  720. _node = (Node *)0;
  721. return _termReason;
  722. }
  723. virtual ReasonForTermination reasonForTermination() const
  724. {
  725. Mutex::Lock _l(_termReason_m);
  726. return _termReason;
  727. }
  728. virtual std::string fatalErrorMessage() const
  729. {
  730. Mutex::Lock _l(_termReason_m);
  731. return _fatalErrorMessage;
  732. }
  733. virtual std::string portDeviceName(uint64_t nwid) const
  734. {
  735. Mutex::Lock _l(_nets_m);
  736. std::map<uint64_t,NetworkState>::const_iterator n(_nets.find(nwid));
  737. if ((n != _nets.end())&&(n->second.tap))
  738. return n->second.tap->deviceName();
  739. else return std::string();
  740. }
  741. virtual bool tcpFallbackActive() const
  742. {
  743. return (_tcpFallbackTunnel != (TcpConnection *)0);
  744. }
  745. virtual void terminate()
  746. {
  747. _run_m.lock();
  748. _run = false;
  749. _run_m.unlock();
  750. _phy.whack();
  751. }
  752. virtual bool getNetworkSettings(const uint64_t nwid,NetworkSettings &settings) const
  753. {
  754. Mutex::Lock _l(_nets_m);
  755. std::map<uint64_t,NetworkState>::const_iterator n(_nets.find(nwid));
  756. if (n == _nets.end())
  757. return false;
  758. memcpy(&settings,&(n->second.settings),sizeof(NetworkSettings));
  759. return true;
  760. }
  761. virtual bool setNetworkSettings(const uint64_t nwid,const NetworkSettings &settings)
  762. {
  763. Mutex::Lock _l(_nets_m);
  764. std::map<uint64_t,NetworkState>::iterator n(_nets.find(nwid));
  765. if (n == _nets.end())
  766. return false;
  767. memcpy(&(n->second.settings),&settings,sizeof(NetworkSettings));
  768. char nlcpath[256];
  769. Utils::snprintf(nlcpath,sizeof(nlcpath),"%s" ZT_PATH_SEPARATOR_S "networks.d" ZT_PATH_SEPARATOR_S "%.16llx.local.conf",_homePath.c_str(),nwid);
  770. FILE *out = fopen(nlcpath,"w");
  771. if (out) {
  772. fprintf(out,"allowManaged=%d\n",(int)n->second.settings.allowManaged);
  773. fprintf(out,"allowGlobal=%d\n",(int)n->second.settings.allowGlobal);
  774. fprintf(out,"allowDefault=%d\n",(int)n->second.settings.allowDefault);
  775. fclose(out);
  776. }
  777. if (n->second.tap)
  778. syncManagedStuff(n->second,true,true);
  779. return true;
  780. }
  781. // Internal implementation methods -----------------------------------------
  782. // Must be called after _localConfig is read or modified
  783. void applyLocalConfig()
  784. {
  785. Mutex::Lock _l(_localConfig_m);
  786. _v4Hints.clear();
  787. _v6Hints.clear();
  788. _v4Blacklists.clear();
  789. _v6Blacklists.clear();
  790. json &virt = _localConfig["virtual"];
  791. if (virt.is_object()) {
  792. for(json::iterator v(virt.begin());v!=virt.end();++v) {
  793. const std::string nstr = v.key();
  794. if ((nstr.length() == ZT_ADDRESS_LENGTH_HEX)&&(v.value().is_object())) {
  795. const Address ztaddr(nstr.c_str());
  796. if (ztaddr) {
  797. const std::string rstr(OSUtils::jsonString(v.value()["role"],""));
  798. _node->setRole(ztaddr.toInt(),((rstr == "upstream")||(rstr == "UPSTREAM")) ? ZT_PEER_ROLE_UPSTREAM : ZT_PEER_ROLE_LEAF);
  799. const uint64_t ztaddr2 = ztaddr.toInt();
  800. std::vector<InetAddress> &v4h = _v4Hints[ztaddr2];
  801. std::vector<InetAddress> &v6h = _v6Hints[ztaddr2];
  802. std::vector<InetAddress> &v4b = _v4Blacklists[ztaddr2];
  803. std::vector<InetAddress> &v6b = _v6Blacklists[ztaddr2];
  804. json &tryAddrs = v.value()["try"];
  805. if (tryAddrs.is_array()) {
  806. for(unsigned long i=0;i<tryAddrs.size();++i) {
  807. const InetAddress ip(OSUtils::jsonString(tryAddrs[i],""));
  808. if (ip.ss_family == AF_INET)
  809. v4h.push_back(ip);
  810. else if (ip.ss_family == AF_INET6)
  811. v6h.push_back(ip);
  812. }
  813. }
  814. json &blAddrs = v.value()["blacklist"];
  815. if (blAddrs.is_array()) {
  816. for(unsigned long i=0;i<blAddrs.size();++i) {
  817. const InetAddress ip(OSUtils::jsonString(tryAddrs[i],""));
  818. if (ip.ss_family == AF_INET)
  819. v4b.push_back(ip);
  820. else if (ip.ss_family == AF_INET6)
  821. v6b.push_back(ip);
  822. }
  823. }
  824. if (v4h.empty()) _v4Hints.erase(ztaddr2);
  825. if (v6h.empty()) _v6Hints.erase(ztaddr2);
  826. if (v4b.empty()) _v4Blacklists.erase(ztaddr2);
  827. if (v6b.empty()) _v6Blacklists.erase(ztaddr2);
  828. }
  829. }
  830. }
  831. }
  832. _globalV4Blacklist.clear();
  833. _globalV6Blacklist.clear();
  834. json &physical = _localConfig["physical"];
  835. if (physical.is_object()) {
  836. for(json::iterator phy(physical.begin());phy!=physical.end();++phy) {
  837. const InetAddress net(OSUtils::jsonString(phy.key(),""));
  838. if ((net)&&(net.netmaskBits() > 0)) {
  839. if (phy.value().is_object()) {
  840. if (OSUtils::jsonBool(phy.value()["blacklist"],false)) {
  841. if (net.ss_family == AF_INET)
  842. _globalV4Blacklist.push_back(net);
  843. else if (net.ss_family == AF_INET6)
  844. _globalV6Blacklist.push_back(net);
  845. }
  846. }
  847. }
  848. }
  849. }
  850. _allowManagementFrom.clear();
  851. _interfacePrefixBlacklist.clear();
  852. json &settings = _localConfig["settings"];
  853. if (settings.is_object()) {
  854. const std::string rp(OSUtils::jsonString(settings["relayPolicy"],""));
  855. if ((rp == "always")||(rp == "ALWAYS"))
  856. _node->setRelayPolicy(ZT_RELAY_POLICY_ALWAYS);
  857. else if ((rp == "never")||(rp == "NEVER"))
  858. _node->setRelayPolicy(ZT_RELAY_POLICY_NEVER);
  859. else _node->setRelayPolicy(ZT_RELAY_POLICY_TRUSTED);
  860. json &ignoreIfs = settings["interfacePrefixBlacklist"];
  861. if (ignoreIfs.is_array()) {
  862. for(unsigned long i=0;i<ignoreIfs.size();++i) {
  863. const std::string tmp(OSUtils::jsonString(ignoreIfs[i],""));
  864. if (tmp.length() > 0)
  865. _interfacePrefixBlacklist.push_back(tmp);
  866. }
  867. }
  868. json &amf = settings["allowManagementFrom"];
  869. if (amf.is_array()) {
  870. for(unsigned long i=0;i<amf.size();++i) {
  871. const InetAddress nw(OSUtils::jsonString(amf[i],""));
  872. if (nw)
  873. _allowManagementFrom.push_back(nw);
  874. }
  875. }
  876. }
  877. }
  878. // Checks if a managed IP or route target is allowed
  879. bool checkIfManagedIsAllowed(const NetworkState &n,const InetAddress &target)
  880. {
  881. if (!n.settings.allowManaged)
  882. return false;
  883. if (target.isDefaultRoute())
  884. return n.settings.allowDefault;
  885. switch(target.ipScope()) {
  886. case InetAddress::IP_SCOPE_NONE:
  887. case InetAddress::IP_SCOPE_MULTICAST:
  888. case InetAddress::IP_SCOPE_LOOPBACK:
  889. case InetAddress::IP_SCOPE_LINK_LOCAL:
  890. return false;
  891. case InetAddress::IP_SCOPE_GLOBAL:
  892. return n.settings.allowGlobal;
  893. default:
  894. return true;
  895. }
  896. }
  897. // Match only an IP from a vector of IPs -- used in syncManagedStuff()
  898. bool matchIpOnly(const std::vector<InetAddress> &ips,const InetAddress &ip) const
  899. {
  900. for(std::vector<InetAddress>::const_iterator i(ips.begin());i!=ips.end();++i) {
  901. if (i->ipsEqual(ip))
  902. return true;
  903. }
  904. return false;
  905. }
  906. // Apply or update managed IPs for a configured network (be sure n.tap exists)
  907. void syncManagedStuff(NetworkState &n,bool syncIps,bool syncRoutes)
  908. {
  909. // assumes _nets_m is locked
  910. if (syncIps) {
  911. std::vector<InetAddress> newManagedIps;
  912. newManagedIps.reserve(n.config.assignedAddressCount);
  913. for(unsigned int i=0;i<n.config.assignedAddressCount;++i) {
  914. const InetAddress *ii = reinterpret_cast<const InetAddress *>(&(n.config.assignedAddresses[i]));
  915. if (checkIfManagedIsAllowed(n,*ii))
  916. newManagedIps.push_back(*ii);
  917. }
  918. std::sort(newManagedIps.begin(),newManagedIps.end());
  919. newManagedIps.erase(std::unique(newManagedIps.begin(),newManagedIps.end()),newManagedIps.end());
  920. for(std::vector<InetAddress>::iterator ip(n.managedIps.begin());ip!=n.managedIps.end();++ip) {
  921. if (std::find(newManagedIps.begin(),newManagedIps.end(),*ip) == newManagedIps.end()) {
  922. if (!n.tap->removeIp(*ip))
  923. fprintf(stderr,"ERROR: unable to remove ip address %s" ZT_EOL_S, ip->toString().c_str());
  924. }
  925. }
  926. for(std::vector<InetAddress>::iterator ip(newManagedIps.begin());ip!=newManagedIps.end();++ip) {
  927. if (std::find(n.managedIps.begin(),n.managedIps.end(),*ip) == n.managedIps.end()) {
  928. if (!n.tap->addIp(*ip))
  929. fprintf(stderr,"ERROR: unable to add ip address %s" ZT_EOL_S, ip->toString().c_str());
  930. }
  931. }
  932. n.managedIps.swap(newManagedIps);
  933. }
  934. if (syncRoutes) {
  935. char tapdev[64];
  936. #ifdef __WINDOWS__
  937. Utils::snprintf(tapdev,sizeof(tapdev),"%.16llx",(unsigned long long)n.tap->luid().Value);
  938. #else
  939. Utils::scopy(tapdev,sizeof(tapdev),n.tap->deviceName().c_str());
  940. #endif
  941. std::vector<InetAddress> myIps(n.tap->ips());
  942. // Nuke applied routes that are no longer in n.config.routes[] and/or are not allowed
  943. for(std::list< SharedPtr<ManagedRoute> >::iterator mr(n.managedRoutes.begin());mr!=n.managedRoutes.end();) {
  944. bool haveRoute = false;
  945. if ( (checkIfManagedIsAllowed(n,(*mr)->target())) && (((*mr)->via().ss_family != (*mr)->target().ss_family)||(!matchIpOnly(myIps,(*mr)->via()))) ) {
  946. for(unsigned int i=0;i<n.config.routeCount;++i) {
  947. const InetAddress *const target = reinterpret_cast<const InetAddress *>(&(n.config.routes[i].target));
  948. const InetAddress *const via = reinterpret_cast<const InetAddress *>(&(n.config.routes[i].via));
  949. if ( ((*mr)->target() == *target) && ( ((via->ss_family == target->ss_family)&&((*mr)->via().ipsEqual(*via))) || (tapdev == (*mr)->device()) ) ) {
  950. haveRoute = true;
  951. break;
  952. }
  953. }
  954. }
  955. if (haveRoute) {
  956. ++mr;
  957. } else {
  958. n.managedRoutes.erase(mr++);
  959. }
  960. }
  961. // Apply routes in n.config.routes[] that we haven't applied yet, and sync those we have in case shadow routes need to change
  962. for(unsigned int i=0;i<n.config.routeCount;++i) {
  963. const InetAddress *const target = reinterpret_cast<const InetAddress *>(&(n.config.routes[i].target));
  964. const InetAddress *const via = reinterpret_cast<const InetAddress *>(&(n.config.routes[i].via));
  965. if ( (!checkIfManagedIsAllowed(n,*target)) || ((via->ss_family == target->ss_family)&&(matchIpOnly(myIps,*via))) )
  966. continue;
  967. bool haveRoute = false;
  968. // Ignore routes implied by local managed IPs since adding the IP adds the route
  969. for(std::vector<InetAddress>::iterator ip(n.managedIps.begin());ip!=n.managedIps.end();++ip) {
  970. if ((target->netmaskBits() == ip->netmaskBits())&&(target->containsAddress(*ip))) {
  971. haveRoute = true;
  972. break;
  973. }
  974. }
  975. if (haveRoute)
  976. continue;
  977. // If we've already applied this route, just sync it and continue
  978. for(std::list< SharedPtr<ManagedRoute> >::iterator mr(n.managedRoutes.begin());mr!=n.managedRoutes.end();++mr) {
  979. if ( ((*mr)->target() == *target) && ( ((via->ss_family == target->ss_family)&&((*mr)->via().ipsEqual(*via))) || (tapdev == (*mr)->device()) ) ) {
  980. haveRoute = true;
  981. (*mr)->sync();
  982. break;
  983. }
  984. }
  985. if (haveRoute)
  986. continue;
  987. // Add and apply new routes
  988. n.managedRoutes.push_back(SharedPtr<ManagedRoute>(new ManagedRoute(*target,*via,tapdev)));
  989. if (!n.managedRoutes.back()->sync())
  990. n.managedRoutes.pop_back();
  991. }
  992. }
  993. }
  994. // Handlers for Node and Phy<> callbacks -----------------------------------
  995. inline void phyOnDatagram(PhySocket *sock,void **uptr,const struct sockaddr *localAddr,const struct sockaddr *from,void *data,unsigned long len)
  996. {
  997. #ifdef ZT_ENABLE_CLUSTER
  998. if (sock == _clusterMessageSocket) {
  999. _lastDirectReceiveFromGlobal = OSUtils::now();
  1000. _node->clusterHandleIncomingMessage(data,len);
  1001. return;
  1002. }
  1003. #endif
  1004. #ifdef ZT_BREAK_UDP
  1005. if (OSUtils::fileExists("/tmp/ZT_BREAK_UDP"))
  1006. return;
  1007. #endif
  1008. if ((len >= 16)&&(reinterpret_cast<const InetAddress *>(from)->ipScope() == InetAddress::IP_SCOPE_GLOBAL))
  1009. _lastDirectReceiveFromGlobal = OSUtils::now();
  1010. const ZT_ResultCode rc = _node->processWirePacket(
  1011. OSUtils::now(),
  1012. reinterpret_cast<const struct sockaddr_storage *>(localAddr),
  1013. (const struct sockaddr_storage *)from, // Phy<> uses sockaddr_storage, so it'll always be that big
  1014. data,
  1015. len,
  1016. &_nextBackgroundTaskDeadline);
  1017. if (ZT_ResultCode_isFatal(rc)) {
  1018. char tmp[256];
  1019. Utils::snprintf(tmp,sizeof(tmp),"fatal error code from processWirePacket: %d",(int)rc);
  1020. Mutex::Lock _l(_termReason_m);
  1021. _termReason = ONE_UNRECOVERABLE_ERROR;
  1022. _fatalErrorMessage = tmp;
  1023. this->terminate();
  1024. }
  1025. }
  1026. inline void phyOnTcpConnect(PhySocket *sock,void **uptr,bool success)
  1027. {
  1028. if (!success)
  1029. return;
  1030. // Outgoing TCP connections are always TCP fallback tunnel connections.
  1031. TcpConnection *tc = new TcpConnection();
  1032. _tcpConnections.insert(tc);
  1033. tc->type = TcpConnection::TCP_TUNNEL_OUTGOING;
  1034. tc->shouldKeepAlive = true;
  1035. tc->parent = this;
  1036. tc->sock = sock;
  1037. // from and parser are not used
  1038. tc->messageSize = 0; // unused
  1039. tc->lastActivity = OSUtils::now();
  1040. // HTTP stuff is not used
  1041. tc->writeBuf = "";
  1042. *uptr = (void *)tc;
  1043. // Send "hello" message
  1044. tc->writeBuf.push_back((char)0x17);
  1045. tc->writeBuf.push_back((char)0x03);
  1046. tc->writeBuf.push_back((char)0x03); // fake TLS 1.2 header
  1047. tc->writeBuf.push_back((char)0x00);
  1048. tc->writeBuf.push_back((char)0x04); // mlen == 4
  1049. tc->writeBuf.push_back((char)ZEROTIER_ONE_VERSION_MAJOR);
  1050. tc->writeBuf.push_back((char)ZEROTIER_ONE_VERSION_MINOR);
  1051. tc->writeBuf.push_back((char)((ZEROTIER_ONE_VERSION_REVISION >> 8) & 0xff));
  1052. tc->writeBuf.push_back((char)(ZEROTIER_ONE_VERSION_REVISION & 0xff));
  1053. _phy.setNotifyWritable(sock,true);
  1054. _tcpFallbackTunnel = tc;
  1055. }
  1056. inline void phyOnTcpAccept(PhySocket *sockL,PhySocket *sockN,void **uptrL,void **uptrN,const struct sockaddr *from)
  1057. {
  1058. if (!from) {
  1059. _phy.close(sockN,false);
  1060. return;
  1061. } else {
  1062. TcpConnection *tc = new TcpConnection();
  1063. _tcpConnections.insert(tc);
  1064. tc->type = TcpConnection::TCP_HTTP_INCOMING;
  1065. tc->shouldKeepAlive = true;
  1066. tc->parent = this;
  1067. tc->sock = sockN;
  1068. tc->from = from;
  1069. http_parser_init(&(tc->parser),HTTP_REQUEST);
  1070. tc->parser.data = (void *)tc;
  1071. tc->messageSize = 0;
  1072. tc->lastActivity = OSUtils::now();
  1073. tc->currentHeaderField = "";
  1074. tc->currentHeaderValue = "";
  1075. tc->url = "";
  1076. tc->status = "";
  1077. tc->headers.clear();
  1078. tc->body = "";
  1079. tc->writeBuf = "";
  1080. *uptrN = (void *)tc;
  1081. }
  1082. }
  1083. inline void phyOnTcpClose(PhySocket *sock,void **uptr)
  1084. {
  1085. TcpConnection *tc = (TcpConnection *)*uptr;
  1086. if (tc) {
  1087. if (tc == _tcpFallbackTunnel)
  1088. _tcpFallbackTunnel = (TcpConnection *)0;
  1089. _tcpConnections.erase(tc);
  1090. delete tc;
  1091. }
  1092. }
  1093. inline void phyOnTcpData(PhySocket *sock,void **uptr,void *data,unsigned long len)
  1094. {
  1095. TcpConnection *tc = reinterpret_cast<TcpConnection *>(*uptr);
  1096. switch(tc->type) {
  1097. case TcpConnection::TCP_HTTP_INCOMING:
  1098. case TcpConnection::TCP_HTTP_OUTGOING:
  1099. http_parser_execute(&(tc->parser),&HTTP_PARSER_SETTINGS,(const char *)data,len);
  1100. if ((tc->parser.upgrade)||(tc->parser.http_errno != HPE_OK)) {
  1101. _phy.close(sock);
  1102. return;
  1103. }
  1104. break;
  1105. case TcpConnection::TCP_TUNNEL_OUTGOING:
  1106. tc->body.append((const char *)data,len);
  1107. while (tc->body.length() >= 5) {
  1108. const char *data = tc->body.data();
  1109. const unsigned long mlen = ( ((((unsigned long)data[3]) & 0xff) << 8) | (((unsigned long)data[4]) & 0xff) );
  1110. if (tc->body.length() >= (mlen + 5)) {
  1111. InetAddress from;
  1112. unsigned long plen = mlen; // payload length, modified if there's an IP header
  1113. data += 5; // skip forward past pseudo-TLS junk and mlen
  1114. if (plen == 4) {
  1115. // Hello message, which isn't sent by proxy and would be ignored by client
  1116. } else if (plen) {
  1117. // Messages should contain IPv4 or IPv6 source IP address data
  1118. switch(data[0]) {
  1119. case 4: // IPv4
  1120. if (plen >= 7) {
  1121. from.set((const void *)(data + 1),4,((((unsigned int)data[5]) & 0xff) << 8) | (((unsigned int)data[6]) & 0xff));
  1122. data += 7; // type + 4 byte IP + 2 byte port
  1123. plen -= 7;
  1124. } else {
  1125. _phy.close(sock);
  1126. return;
  1127. }
  1128. break;
  1129. case 6: // IPv6
  1130. if (plen >= 19) {
  1131. from.set((const void *)(data + 1),16,((((unsigned int)data[17]) & 0xff) << 8) | (((unsigned int)data[18]) & 0xff));
  1132. data += 19; // type + 16 byte IP + 2 byte port
  1133. plen -= 19;
  1134. } else {
  1135. _phy.close(sock);
  1136. return;
  1137. }
  1138. break;
  1139. case 0: // none/omitted
  1140. ++data;
  1141. --plen;
  1142. break;
  1143. default: // invalid address type
  1144. _phy.close(sock);
  1145. return;
  1146. }
  1147. if (from) {
  1148. InetAddress fakeTcpLocalInterfaceAddress((uint32_t)0xffffffff,0xffff);
  1149. const ZT_ResultCode rc = _node->processWirePacket(
  1150. OSUtils::now(),
  1151. reinterpret_cast<struct sockaddr_storage *>(&fakeTcpLocalInterfaceAddress),
  1152. reinterpret_cast<struct sockaddr_storage *>(&from),
  1153. data,
  1154. plen,
  1155. &_nextBackgroundTaskDeadline);
  1156. if (ZT_ResultCode_isFatal(rc)) {
  1157. char tmp[256];
  1158. Utils::snprintf(tmp,sizeof(tmp),"fatal error code from processWirePacket: %d",(int)rc);
  1159. Mutex::Lock _l(_termReason_m);
  1160. _termReason = ONE_UNRECOVERABLE_ERROR;
  1161. _fatalErrorMessage = tmp;
  1162. this->terminate();
  1163. _phy.close(sock);
  1164. return;
  1165. }
  1166. }
  1167. }
  1168. if (tc->body.length() > (mlen + 5))
  1169. tc->body = tc->body.substr(mlen + 5);
  1170. else tc->body = "";
  1171. } else break;
  1172. }
  1173. break;
  1174. }
  1175. }
  1176. inline void phyOnTcpWritable(PhySocket *sock,void **uptr)
  1177. {
  1178. TcpConnection *tc = reinterpret_cast<TcpConnection *>(*uptr);
  1179. Mutex::Lock _l(tc->writeBuf_m);
  1180. if (tc->writeBuf.length() > 0) {
  1181. long sent = (long)_phy.streamSend(sock,tc->writeBuf.data(),(unsigned long)tc->writeBuf.length(),true);
  1182. if (sent > 0) {
  1183. tc->lastActivity = OSUtils::now();
  1184. if ((unsigned long)sent >= (unsigned long)tc->writeBuf.length()) {
  1185. tc->writeBuf = "";
  1186. _phy.setNotifyWritable(sock,false);
  1187. if (!tc->shouldKeepAlive)
  1188. _phy.close(sock); // will call close handler to delete from _tcpConnections
  1189. } else {
  1190. tc->writeBuf = tc->writeBuf.substr(sent);
  1191. }
  1192. }
  1193. } else {
  1194. _phy.setNotifyWritable(sock,false);
  1195. }
  1196. }
  1197. inline void phyOnFileDescriptorActivity(PhySocket *sock,void **uptr,bool readable,bool writable) {}
  1198. inline void phyOnUnixAccept(PhySocket *sockL,PhySocket *sockN,void **uptrL,void **uptrN) {}
  1199. inline void phyOnUnixClose(PhySocket *sock,void **uptr) {}
  1200. inline void phyOnUnixData(PhySocket *sock,void **uptr,void *data,unsigned long len) {}
  1201. inline void phyOnUnixWritable(PhySocket *sock,void **uptr,bool lwip_invoked) {}
  1202. inline int nodeVirtualNetworkConfigFunction(uint64_t nwid,void **nuptr,enum ZT_VirtualNetworkConfigOperation op,const ZT_VirtualNetworkConfig *nwc)
  1203. {
  1204. Mutex::Lock _l(_nets_m);
  1205. NetworkState &n = _nets[nwid];
  1206. switch(op) {
  1207. case ZT_VIRTUAL_NETWORK_CONFIG_OPERATION_UP:
  1208. if (!n.tap) {
  1209. try {
  1210. char friendlyName[128];
  1211. Utils::snprintf(friendlyName,sizeof(friendlyName),"ZeroTier One [%.16llx]",nwid);
  1212. n.tap = new EthernetTap(
  1213. _homePath.c_str(),
  1214. MAC(nwc->mac),
  1215. nwc->mtu,
  1216. (unsigned int)ZT_IF_METRIC,
  1217. nwid,
  1218. friendlyName,
  1219. StapFrameHandler,
  1220. (void *)this);
  1221. *nuptr = (void *)&n;
  1222. char nlcpath[256];
  1223. Utils::snprintf(nlcpath,sizeof(nlcpath),"%s" ZT_PATH_SEPARATOR_S "networks.d" ZT_PATH_SEPARATOR_S "%.16llx.local.conf",_homePath.c_str(),nwid);
  1224. std::string nlcbuf;
  1225. if (OSUtils::readFile(nlcpath,nlcbuf)) {
  1226. Dictionary<4096> nc;
  1227. nc.load(nlcbuf.c_str());
  1228. n.settings.allowManaged = nc.getB("allowManaged",true);
  1229. n.settings.allowGlobal = nc.getB("allowGlobal",false);
  1230. n.settings.allowDefault = nc.getB("allowDefault",false);
  1231. }
  1232. } catch (std::exception &exc) {
  1233. #ifdef __WINDOWS__
  1234. FILE *tapFailLog = fopen((_homePath + ZT_PATH_SEPARATOR_S"port_error_log.txt").c_str(),"a");
  1235. if (tapFailLog) {
  1236. fprintf(tapFailLog,"%.16llx: %s" ZT_EOL_S,(unsigned long long)nwid,exc.what());
  1237. fclose(tapFailLog);
  1238. }
  1239. #else
  1240. fprintf(stderr,"ERROR: unable to configure virtual network port: %s" ZT_EOL_S,exc.what());
  1241. #endif
  1242. _nets.erase(nwid);
  1243. return -999;
  1244. } catch ( ... ) {
  1245. return -999; // tap init failed
  1246. }
  1247. }
  1248. // After setting up tap, fall through to CONFIG_UPDATE since we also want to do this...
  1249. case ZT_VIRTUAL_NETWORK_CONFIG_OPERATION_CONFIG_UPDATE:
  1250. memcpy(&(n.config),nwc,sizeof(ZT_VirtualNetworkConfig));
  1251. if (n.tap) { // sanity check
  1252. #ifdef __WINDOWS__
  1253. // wait for up to 5 seconds for the WindowsEthernetTap to actually be initialized
  1254. //
  1255. // without WindowsEthernetTap::isInitialized() returning true, the won't actually
  1256. // be online yet and setting managed routes on it will fail.
  1257. const int MAX_SLEEP_COUNT = 500;
  1258. for (int i = 0; !n.tap->isInitialized() && i < MAX_SLEEP_COUNT; i++) {
  1259. Sleep(10);
  1260. }
  1261. #endif
  1262. syncManagedStuff(n,true,true);
  1263. } else {
  1264. _nets.erase(nwid);
  1265. return -999; // tap init failed
  1266. }
  1267. break;
  1268. case ZT_VIRTUAL_NETWORK_CONFIG_OPERATION_DOWN:
  1269. case ZT_VIRTUAL_NETWORK_CONFIG_OPERATION_DESTROY:
  1270. if (n.tap) { // sanity check
  1271. #ifdef __WINDOWS__
  1272. std::string winInstanceId(n.tap->instanceId());
  1273. #endif
  1274. *nuptr = (void *)0;
  1275. delete n.tap;
  1276. _nets.erase(nwid);
  1277. #ifdef __WINDOWS__
  1278. if ((op == ZT_VIRTUAL_NETWORK_CONFIG_OPERATION_DESTROY)&&(winInstanceId.length() > 0))
  1279. WindowsEthernetTap::deletePersistentTapDevice(winInstanceId.c_str());
  1280. #endif
  1281. if (op == ZT_VIRTUAL_NETWORK_CONFIG_OPERATION_DESTROY) {
  1282. char nlcpath[256];
  1283. Utils::snprintf(nlcpath,sizeof(nlcpath),"%s" ZT_PATH_SEPARATOR_S "networks.d" ZT_PATH_SEPARATOR_S "%.16llx.local.conf",_homePath.c_str(),nwid);
  1284. OSUtils::rm(nlcpath);
  1285. }
  1286. } else {
  1287. _nets.erase(nwid);
  1288. }
  1289. break;
  1290. }
  1291. return 0;
  1292. }
  1293. inline void nodeEventCallback(enum ZT_Event event,const void *metaData)
  1294. {
  1295. switch(event) {
  1296. case ZT_EVENT_FATAL_ERROR_IDENTITY_COLLISION: {
  1297. Mutex::Lock _l(_termReason_m);
  1298. _termReason = ONE_IDENTITY_COLLISION;
  1299. _fatalErrorMessage = "identity/address collision";
  1300. this->terminate();
  1301. } break;
  1302. case ZT_EVENT_TRACE: {
  1303. if (metaData) {
  1304. ::fprintf(stderr,"%s" ZT_EOL_S,(const char *)metaData);
  1305. ::fflush(stderr);
  1306. }
  1307. } break;
  1308. case ZT_EVENT_USER_MESSAGE: {
  1309. const ZT_UserMessage *um = reinterpret_cast<const ZT_UserMessage *>(metaData);
  1310. if ((um->typeId == ZT_SOFTWARE_UPDATE_USER_MESSAGE_TYPE)&&(_updater)) {
  1311. _updater->handleSoftwareUpdateUserMessage(um->origin,um->data,um->length);
  1312. }
  1313. } break;
  1314. default:
  1315. break;
  1316. }
  1317. }
  1318. inline long nodeDataStoreGetFunction(const char *name,void *buf,unsigned long bufSize,unsigned long readIndex,unsigned long *totalSize)
  1319. {
  1320. std::string p(_dataStorePrepPath(name));
  1321. if (!p.length())
  1322. return -2;
  1323. FILE *f = fopen(p.c_str(),"rb");
  1324. if (!f)
  1325. return -1;
  1326. if (fseek(f,0,SEEK_END) != 0) {
  1327. fclose(f);
  1328. return -2;
  1329. }
  1330. long ts = ftell(f);
  1331. if (ts < 0) {
  1332. fclose(f);
  1333. return -2;
  1334. }
  1335. *totalSize = (unsigned long)ts;
  1336. if (fseek(f,(long)readIndex,SEEK_SET) != 0) {
  1337. fclose(f);
  1338. return -2;
  1339. }
  1340. long n = (long)fread(buf,1,bufSize,f);
  1341. fclose(f);
  1342. return n;
  1343. }
  1344. inline int nodeDataStorePutFunction(const char *name,const void *data,unsigned long len,int secure)
  1345. {
  1346. std::string p(_dataStorePrepPath(name));
  1347. if (!p.length())
  1348. return -2;
  1349. if (!data) {
  1350. OSUtils::rm(p.c_str());
  1351. return 0;
  1352. }
  1353. FILE *f = fopen(p.c_str(),"wb");
  1354. if (!f)
  1355. return -1;
  1356. if (fwrite(data,len,1,f) == 1) {
  1357. fclose(f);
  1358. if (secure)
  1359. OSUtils::lockDownFile(p.c_str(),false);
  1360. return 0;
  1361. } else {
  1362. fclose(f);
  1363. OSUtils::rm(p.c_str());
  1364. return -1;
  1365. }
  1366. }
  1367. inline int nodeWirePacketSendFunction(const struct sockaddr_storage *localAddr,const struct sockaddr_storage *addr,const void *data,unsigned int len,unsigned int ttl)
  1368. {
  1369. unsigned int fromBindingNo = 0;
  1370. if (addr->ss_family == AF_INET) {
  1371. if (reinterpret_cast<const struct sockaddr_in *>(localAddr)->sin_port == 0) {
  1372. // If sender is sending from wildcard (null address), choose the secondary backup
  1373. // port 1/4 of the time. (but only for IPv4)
  1374. fromBindingNo = (++_udpPortPickerCounter & 0x4) >> 2;
  1375. if (!_ports[fromBindingNo])
  1376. fromBindingNo = 0;
  1377. } else {
  1378. const uint16_t lp = reinterpret_cast<const struct sockaddr_in *>(localAddr)->sin_port;
  1379. if (lp == _portsBE[1])
  1380. fromBindingNo = 1;
  1381. else if (lp == _portsBE[2])
  1382. fromBindingNo = 2;
  1383. }
  1384. #ifdef ZT_TCP_FALLBACK_RELAY
  1385. // TCP fallback tunnel support, currently IPv4 only
  1386. if ((len >= 16)&&(reinterpret_cast<const InetAddress *>(addr)->ipScope() == InetAddress::IP_SCOPE_GLOBAL)) {
  1387. // Engage TCP tunnel fallback if we haven't received anything valid from a global
  1388. // IP address in ZT_TCP_FALLBACK_AFTER milliseconds. If we do start getting
  1389. // valid direct traffic we'll stop using it and close the socket after a while.
  1390. const uint64_t now = OSUtils::now();
  1391. if (((now - _lastDirectReceiveFromGlobal) > ZT_TCP_FALLBACK_AFTER)&&((now - _lastRestart) > ZT_TCP_FALLBACK_AFTER)) {
  1392. if (_tcpFallbackTunnel) {
  1393. Mutex::Lock _l(_tcpFallbackTunnel->writeBuf_m);
  1394. if (!_tcpFallbackTunnel->writeBuf.length())
  1395. _phy.setNotifyWritable(_tcpFallbackTunnel->sock,true);
  1396. unsigned long mlen = len + 7;
  1397. _tcpFallbackTunnel->writeBuf.push_back((char)0x17);
  1398. _tcpFallbackTunnel->writeBuf.push_back((char)0x03);
  1399. _tcpFallbackTunnel->writeBuf.push_back((char)0x03); // fake TLS 1.2 header
  1400. _tcpFallbackTunnel->writeBuf.push_back((char)((mlen >> 8) & 0xff));
  1401. _tcpFallbackTunnel->writeBuf.push_back((char)(mlen & 0xff));
  1402. _tcpFallbackTunnel->writeBuf.push_back((char)4); // IPv4
  1403. _tcpFallbackTunnel->writeBuf.append(reinterpret_cast<const char *>(reinterpret_cast<const void *>(&(reinterpret_cast<const struct sockaddr_in *>(addr)->sin_addr.s_addr))),4);
  1404. _tcpFallbackTunnel->writeBuf.append(reinterpret_cast<const char *>(reinterpret_cast<const void *>(&(reinterpret_cast<const struct sockaddr_in *>(addr)->sin_port))),2);
  1405. _tcpFallbackTunnel->writeBuf.append((const char *)data,len);
  1406. } else if (((now - _lastSendToGlobalV4) < ZT_TCP_FALLBACK_AFTER)&&((now - _lastSendToGlobalV4) > (ZT_PING_CHECK_INVERVAL / 2))) {
  1407. std::vector<InetAddress> tunnelIps(_tcpFallbackResolver.get());
  1408. if (tunnelIps.empty()) {
  1409. if (!_tcpFallbackResolver.running())
  1410. _tcpFallbackResolver.resolveNow();
  1411. } else {
  1412. bool connected = false;
  1413. InetAddress addr(tunnelIps[(unsigned long)now % tunnelIps.size()]);
  1414. addr.setPort(ZT_TCP_FALLBACK_RELAY_PORT);
  1415. _phy.tcpConnect(reinterpret_cast<const struct sockaddr *>(&addr),connected);
  1416. }
  1417. }
  1418. }
  1419. _lastSendToGlobalV4 = now;
  1420. }
  1421. #endif // ZT_TCP_FALLBACK_RELAY
  1422. } else if (addr->ss_family == AF_INET6) {
  1423. if (reinterpret_cast<const struct sockaddr_in6 *>(localAddr)->sin6_port != 0) {
  1424. const uint16_t lp = reinterpret_cast<const struct sockaddr_in6 *>(localAddr)->sin6_port;
  1425. if (lp == _portsBE[1])
  1426. fromBindingNo = 1;
  1427. else if (lp == _portsBE[2])
  1428. fromBindingNo = 2;
  1429. }
  1430. } else {
  1431. return -1;
  1432. }
  1433. #ifdef ZT_BREAK_UDP
  1434. if (OSUtils::fileExists("/tmp/ZT_BREAK_UDP"))
  1435. return 0; // silently break UDP
  1436. #endif
  1437. return (_bindings[fromBindingNo].udpSend(_phy,*(reinterpret_cast<const InetAddress *>(localAddr)),*(reinterpret_cast<const InetAddress *>(addr)),data,len,ttl)) ? 0 : -1;
  1438. }
  1439. 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)
  1440. {
  1441. NetworkState *n = reinterpret_cast<NetworkState *>(*nuptr);
  1442. if ((!n)||(!n->tap))
  1443. return;
  1444. n->tap->put(MAC(sourceMac),MAC(destMac),etherType,data,len);
  1445. }
  1446. inline int nodePathCheckFunction(uint64_t ztaddr,const struct sockaddr_storage *localAddr,const struct sockaddr_storage *remoteAddr)
  1447. {
  1448. // Make sure we're not trying to do ZeroTier-over-ZeroTier
  1449. {
  1450. Mutex::Lock _l(_nets_m);
  1451. for(std::map<uint64_t,NetworkState>::const_iterator n(_nets.begin());n!=_nets.end();++n) {
  1452. if (n->second.tap) {
  1453. std::vector<InetAddress> ips(n->second.tap->ips());
  1454. for(std::vector<InetAddress>::const_iterator i(ips.begin());i!=ips.end();++i) {
  1455. if (i->containsAddress(*(reinterpret_cast<const InetAddress *>(remoteAddr)))) {
  1456. return 0;
  1457. }
  1458. }
  1459. }
  1460. }
  1461. }
  1462. /* Note: I do not think we need to scan for overlap with managed routes
  1463. * because of the "route forking" and interface binding that we do. This
  1464. * ensures (we hope) that ZeroTier traffic will still take the physical
  1465. * path even if its managed routes override this for other traffic. Will
  1466. * revisit if we see recursion problems. */
  1467. // Check blacklists
  1468. const Hashtable< uint64_t,std::vector<InetAddress> > *blh = (const Hashtable< uint64_t,std::vector<InetAddress> > *)0;
  1469. const std::vector<InetAddress> *gbl = (const std::vector<InetAddress> *)0;
  1470. if (remoteAddr->ss_family == AF_INET) {
  1471. blh = &_v4Blacklists;
  1472. gbl = &_globalV4Blacklist;
  1473. } else if (remoteAddr->ss_family == AF_INET6) {
  1474. blh = &_v6Blacklists;
  1475. gbl = &_globalV6Blacklist;
  1476. }
  1477. if (blh) {
  1478. Mutex::Lock _l(_localConfig_m);
  1479. const std::vector<InetAddress> *l = blh->get(ztaddr);
  1480. if (l) {
  1481. for(std::vector<InetAddress>::const_iterator a(l->begin());a!=l->end();++a) {
  1482. if (a->containsAddress(*reinterpret_cast<const InetAddress *>(remoteAddr)))
  1483. return 0;
  1484. }
  1485. }
  1486. for(std::vector<InetAddress>::const_iterator a(gbl->begin());a!=gbl->end();++a) {
  1487. if (a->containsAddress(*reinterpret_cast<const InetAddress *>(remoteAddr)))
  1488. return 0;
  1489. }
  1490. }
  1491. return 1;
  1492. }
  1493. inline int nodePathLookupFunction(uint64_t ztaddr,int family,struct sockaddr_storage *result)
  1494. {
  1495. const Hashtable< uint64_t,std::vector<InetAddress> > *lh = (const Hashtable< uint64_t,std::vector<InetAddress> > *)0;
  1496. if (family < 0)
  1497. lh = (_node->prng() & 1) ? &_v4Hints : &_v6Hints;
  1498. else if (family == AF_INET)
  1499. lh = &_v4Hints;
  1500. else if (family == AF_INET6)
  1501. lh = &_v6Hints;
  1502. else return 0;
  1503. const std::vector<InetAddress> *l = lh->get(ztaddr);
  1504. if ((l)&&(l->size() > 0)) {
  1505. memcpy(result,&((*l)[(unsigned long)_node->prng() % l->size()]),sizeof(struct sockaddr_storage));
  1506. return 1;
  1507. } else return 0;
  1508. }
  1509. inline void tapFrameHandler(uint64_t nwid,const MAC &from,const MAC &to,unsigned int etherType,unsigned int vlanId,const void *data,unsigned int len)
  1510. {
  1511. _node->processVirtualNetworkFrame(OSUtils::now(),nwid,from.toInt(),to.toInt(),etherType,vlanId,data,len,&_nextBackgroundTaskDeadline);
  1512. }
  1513. inline void onHttpRequestToServer(TcpConnection *tc)
  1514. {
  1515. char tmpn[256];
  1516. std::string data;
  1517. std::string contentType("text/plain"); // default if not changed in handleRequest()
  1518. unsigned int scode = 404;
  1519. bool allow;
  1520. {
  1521. Mutex::Lock _l(_localConfig_m);
  1522. if (_allowManagementFrom.size() == 0) {
  1523. allow = (tc->from.ipScope() == InetAddress::IP_SCOPE_LOOPBACK);
  1524. } else {
  1525. allow = false;
  1526. for(std::vector<InetAddress>::const_iterator i(_allowManagementFrom.begin());i!=_allowManagementFrom.end();++i) {
  1527. if (i->containsAddress(tc->from)) {
  1528. allow = true;
  1529. break;
  1530. }
  1531. }
  1532. }
  1533. }
  1534. if (allow) {
  1535. try {
  1536. if (_controlPlane)
  1537. scode = _controlPlane->handleRequest(tc->from,tc->parser.method,tc->url,tc->headers,tc->body,data,contentType);
  1538. else scode = 500;
  1539. } catch (std::exception &exc) {
  1540. fprintf(stderr,"WARNING: unexpected exception processing control HTTP request: %s" ZT_EOL_S,exc.what());
  1541. scode = 500;
  1542. } catch ( ... ) {
  1543. fprintf(stderr,"WARNING: unexpected exception processing control HTTP request: unknown exceptino" ZT_EOL_S);
  1544. scode = 500;
  1545. }
  1546. } else {
  1547. scode = 401;
  1548. }
  1549. const char *scodestr;
  1550. switch(scode) {
  1551. case 200: scodestr = "OK"; break;
  1552. case 400: scodestr = "Bad Request"; break;
  1553. case 401: scodestr = "Unauthorized"; break;
  1554. case 403: scodestr = "Forbidden"; break;
  1555. case 404: scodestr = "Not Found"; break;
  1556. case 500: scodestr = "Internal Server Error"; break;
  1557. case 501: scodestr = "Not Implemented"; break;
  1558. case 503: scodestr = "Service Unavailable"; break;
  1559. default: scodestr = "Error"; break;
  1560. }
  1561. Utils::snprintf(tmpn,sizeof(tmpn),"HTTP/1.1 %.3u %s\r\nCache-Control: no-cache\r\nPragma: no-cache\r\n",scode,scodestr);
  1562. {
  1563. Mutex::Lock _l(tc->writeBuf_m);
  1564. tc->writeBuf.assign(tmpn);
  1565. tc->writeBuf.append("Content-Type: ");
  1566. tc->writeBuf.append(contentType);
  1567. Utils::snprintf(tmpn,sizeof(tmpn),"\r\nContent-Length: %lu\r\n",(unsigned long)data.length());
  1568. tc->writeBuf.append(tmpn);
  1569. if (!tc->shouldKeepAlive)
  1570. tc->writeBuf.append("Connection: close\r\n");
  1571. tc->writeBuf.append("\r\n");
  1572. if (tc->parser.method != HTTP_HEAD)
  1573. tc->writeBuf.append(data);
  1574. }
  1575. _phy.setNotifyWritable(tc->sock,true);
  1576. }
  1577. inline void onHttpResponseFromClient(TcpConnection *tc)
  1578. {
  1579. if (!tc->shouldKeepAlive)
  1580. _phy.close(tc->sock); // will call close handler, which deletes from _tcpConnections
  1581. }
  1582. bool shouldBindInterface(const char *ifname,const InetAddress &ifaddr)
  1583. {
  1584. #if defined(__linux__) || defined(linux) || defined(__LINUX__) || defined(__linux)
  1585. if ((ifname[0] == 'l')&&(ifname[1] == 'o')) return false; // loopback
  1586. if ((ifname[0] == 'z')&&(ifname[1] == 't')) return false; // sanity check: zt#
  1587. if ((ifname[0] == 't')&&(ifname[1] == 'u')&&(ifname[2] == 'n')) return false; // tun# is probably an OpenVPN tunnel or similar
  1588. if ((ifname[0] == 't')&&(ifname[1] == 'a')&&(ifname[2] == 'p')) return false; // tap# is probably an OpenVPN tunnel or similar
  1589. #endif
  1590. #ifdef __APPLE__
  1591. if ((ifname[0] == 'l')&&(ifname[1] == 'o')) return false; // loopback
  1592. if ((ifname[0] == 'z')&&(ifname[1] == 't')) return false; // sanity check: zt#
  1593. if ((ifname[0] == 't')&&(ifname[1] == 'u')&&(ifname[2] == 'n')) return false; // tun# is probably an OpenVPN tunnel or similar
  1594. if ((ifname[0] == 't')&&(ifname[1] == 'a')&&(ifname[2] == 'p')) return false; // tap# is probably an OpenVPN tunnel or similar
  1595. if ((ifname[0] == 'u')&&(ifname[1] == 't')&&(ifname[2] == 'u')&&(ifname[3] == 'n')) return false; // ... as is utun#
  1596. #endif
  1597. {
  1598. Mutex::Lock _l(_localConfig_m);
  1599. for(std::vector<std::string>::const_iterator p(_interfacePrefixBlacklist.begin());p!=_interfacePrefixBlacklist.end();++p) {
  1600. if (!strncmp(p->c_str(),ifname,p->length()))
  1601. return false;
  1602. }
  1603. }
  1604. {
  1605. Mutex::Lock _l(_nets_m);
  1606. for(std::map<uint64_t,NetworkState>::const_iterator n(_nets.begin());n!=_nets.end();++n) {
  1607. if (n->second.tap) {
  1608. std::vector<InetAddress> ips(n->second.tap->ips());
  1609. for(std::vector<InetAddress>::const_iterator i(ips.begin());i!=ips.end();++i) {
  1610. if (i->ipsEqual(ifaddr))
  1611. return false;
  1612. }
  1613. }
  1614. }
  1615. }
  1616. return true;
  1617. }
  1618. std::string _dataStorePrepPath(const char *name) const
  1619. {
  1620. std::string p(_homePath);
  1621. p.push_back(ZT_PATH_SEPARATOR);
  1622. char lastc = (char)0;
  1623. for(const char *n=name;(*n);++n) {
  1624. if ((*n == '.')&&(lastc == '.'))
  1625. return std::string(); // don't allow ../../ stuff as a precaution
  1626. if (*n == '/') {
  1627. OSUtils::mkdir(p.c_str());
  1628. p.push_back(ZT_PATH_SEPARATOR);
  1629. } else p.push_back(*n);
  1630. lastc = *n;
  1631. }
  1632. return p;
  1633. }
  1634. bool _trialBind(unsigned int port)
  1635. {
  1636. struct sockaddr_in in4;
  1637. struct sockaddr_in6 in6;
  1638. PhySocket *tb;
  1639. memset(&in4,0,sizeof(in4));
  1640. in4.sin_family = AF_INET;
  1641. in4.sin_port = Utils::hton((uint16_t)port);
  1642. tb = _phy.udpBind(reinterpret_cast<const struct sockaddr *>(&in4),(void *)0,0);
  1643. if (tb) {
  1644. _phy.close(tb,false);
  1645. tb = _phy.tcpListen(reinterpret_cast<const struct sockaddr *>(&in4),(void *)0);
  1646. if (tb) {
  1647. _phy.close(tb,false);
  1648. return true;
  1649. }
  1650. }
  1651. memset(&in6,0,sizeof(in6));
  1652. in6.sin6_family = AF_INET6;
  1653. in6.sin6_port = Utils::hton((uint16_t)port);
  1654. tb = _phy.udpBind(reinterpret_cast<const struct sockaddr *>(&in6),(void *)0,0);
  1655. if (tb) {
  1656. _phy.close(tb,false);
  1657. tb = _phy.tcpListen(reinterpret_cast<const struct sockaddr *>(&in6),(void *)0);
  1658. if (tb) {
  1659. _phy.close(tb,false);
  1660. return true;
  1661. }
  1662. }
  1663. return false;
  1664. }
  1665. };
  1666. static int SnodeVirtualNetworkConfigFunction(ZT_Node *node,void *uptr,uint64_t nwid,void **nuptr,enum ZT_VirtualNetworkConfigOperation op,const ZT_VirtualNetworkConfig *nwconf)
  1667. { return reinterpret_cast<OneServiceImpl *>(uptr)->nodeVirtualNetworkConfigFunction(nwid,nuptr,op,nwconf); }
  1668. static void SnodeEventCallback(ZT_Node *node,void *uptr,enum ZT_Event event,const void *metaData)
  1669. { reinterpret_cast<OneServiceImpl *>(uptr)->nodeEventCallback(event,metaData); }
  1670. static long SnodeDataStoreGetFunction(ZT_Node *node,void *uptr,const char *name,void *buf,unsigned long bufSize,unsigned long readIndex,unsigned long *totalSize)
  1671. { return reinterpret_cast<OneServiceImpl *>(uptr)->nodeDataStoreGetFunction(name,buf,bufSize,readIndex,totalSize); }
  1672. static int SnodeDataStorePutFunction(ZT_Node *node,void *uptr,const char *name,const void *data,unsigned long len,int secure)
  1673. { return reinterpret_cast<OneServiceImpl *>(uptr)->nodeDataStorePutFunction(name,data,len,secure); }
  1674. static int SnodeWirePacketSendFunction(ZT_Node *node,void *uptr,const struct sockaddr_storage *localAddr,const struct sockaddr_storage *addr,const void *data,unsigned int len,unsigned int ttl)
  1675. { return reinterpret_cast<OneServiceImpl *>(uptr)->nodeWirePacketSendFunction(localAddr,addr,data,len,ttl); }
  1676. static void SnodeVirtualNetworkFrameFunction(ZT_Node *node,void *uptr,uint64_t nwid,void **nuptr,uint64_t sourceMac,uint64_t destMac,unsigned int etherType,unsigned int vlanId,const void *data,unsigned int len)
  1677. { reinterpret_cast<OneServiceImpl *>(uptr)->nodeVirtualNetworkFrameFunction(nwid,nuptr,sourceMac,destMac,etherType,vlanId,data,len); }
  1678. static int SnodePathCheckFunction(ZT_Node *node,void *uptr,uint64_t ztaddr,const struct sockaddr_storage *localAddr,const struct sockaddr_storage *remoteAddr)
  1679. { return reinterpret_cast<OneServiceImpl *>(uptr)->nodePathCheckFunction(ztaddr,localAddr,remoteAddr); }
  1680. static int SnodePathLookupFunction(ZT_Node *node,void *uptr,uint64_t ztaddr,int family,struct sockaddr_storage *result)
  1681. { return reinterpret_cast<OneServiceImpl *>(uptr)->nodePathLookupFunction(ztaddr,family,result); }
  1682. #ifdef ZT_ENABLE_CLUSTER
  1683. static void SclusterSendFunction(void *uptr,unsigned int toMemberId,const void *data,unsigned int len)
  1684. {
  1685. OneServiceImpl *const impl = reinterpret_cast<OneServiceImpl *>(uptr);
  1686. const ClusterDefinition::MemberDefinition &md = (*(impl->_clusterDefinition))[toMemberId];
  1687. if (md.clusterEndpoint)
  1688. impl->_phy.udpSend(impl->_clusterMessageSocket,reinterpret_cast<const struct sockaddr *>(&(md.clusterEndpoint)),data,len);
  1689. }
  1690. static int SclusterGeoIpFunction(void *uptr,const struct sockaddr_storage *addr,int *x,int *y,int *z)
  1691. {
  1692. OneServiceImpl *const impl = reinterpret_cast<OneServiceImpl *>(uptr);
  1693. return (int)(impl->_clusterDefinition->geo().locate(*(reinterpret_cast<const InetAddress *>(addr)),*x,*y,*z));
  1694. }
  1695. #endif
  1696. static void StapFrameHandler(void *uptr,uint64_t nwid,const MAC &from,const MAC &to,unsigned int etherType,unsigned int vlanId,const void *data,unsigned int len)
  1697. { reinterpret_cast<OneServiceImpl *>(uptr)->tapFrameHandler(nwid,from,to,etherType,vlanId,data,len); }
  1698. static int ShttpOnMessageBegin(http_parser *parser)
  1699. {
  1700. TcpConnection *tc = reinterpret_cast<TcpConnection *>(parser->data);
  1701. tc->currentHeaderField = "";
  1702. tc->currentHeaderValue = "";
  1703. tc->messageSize = 0;
  1704. tc->url = "";
  1705. tc->status = "";
  1706. tc->headers.clear();
  1707. tc->body = "";
  1708. return 0;
  1709. }
  1710. static int ShttpOnUrl(http_parser *parser,const char *ptr,size_t length)
  1711. {
  1712. TcpConnection *tc = reinterpret_cast<TcpConnection *>(parser->data);
  1713. tc->messageSize += (unsigned long)length;
  1714. if (tc->messageSize > ZT_MAX_HTTP_MESSAGE_SIZE)
  1715. return -1;
  1716. tc->url.append(ptr,length);
  1717. return 0;
  1718. }
  1719. #if (HTTP_PARSER_VERSION_MAJOR >= 2) && (HTTP_PARSER_VERSION_MINOR >= 2)
  1720. static int ShttpOnStatus(http_parser *parser,const char *ptr,size_t length)
  1721. #else
  1722. static int ShttpOnStatus(http_parser *parser)
  1723. #endif
  1724. {
  1725. /*
  1726. TcpConnection *tc = reinterpret_cast<TcpConnection *>(parser->data);
  1727. tc->messageSize += (unsigned long)length;
  1728. if (tc->messageSize > ZT_MAX_HTTP_MESSAGE_SIZE)
  1729. return -1;
  1730. tc->status.append(ptr,length);
  1731. */
  1732. return 0;
  1733. }
  1734. static int ShttpOnHeaderField(http_parser *parser,const char *ptr,size_t length)
  1735. {
  1736. TcpConnection *tc = reinterpret_cast<TcpConnection *>(parser->data);
  1737. tc->messageSize += (unsigned long)length;
  1738. if (tc->messageSize > ZT_MAX_HTTP_MESSAGE_SIZE)
  1739. return -1;
  1740. if ((tc->currentHeaderField.length())&&(tc->currentHeaderValue.length())) {
  1741. tc->headers[tc->currentHeaderField] = tc->currentHeaderValue;
  1742. tc->currentHeaderField = "";
  1743. tc->currentHeaderValue = "";
  1744. }
  1745. for(size_t i=0;i<length;++i)
  1746. tc->currentHeaderField.push_back(OSUtils::toLower(ptr[i]));
  1747. return 0;
  1748. }
  1749. static int ShttpOnValue(http_parser *parser,const char *ptr,size_t length)
  1750. {
  1751. TcpConnection *tc = reinterpret_cast<TcpConnection *>(parser->data);
  1752. tc->messageSize += (unsigned long)length;
  1753. if (tc->messageSize > ZT_MAX_HTTP_MESSAGE_SIZE)
  1754. return -1;
  1755. tc->currentHeaderValue.append(ptr,length);
  1756. return 0;
  1757. }
  1758. static int ShttpOnHeadersComplete(http_parser *parser)
  1759. {
  1760. TcpConnection *tc = reinterpret_cast<TcpConnection *>(parser->data);
  1761. if ((tc->currentHeaderField.length())&&(tc->currentHeaderValue.length()))
  1762. tc->headers[tc->currentHeaderField] = tc->currentHeaderValue;
  1763. return 0;
  1764. }
  1765. static int ShttpOnBody(http_parser *parser,const char *ptr,size_t length)
  1766. {
  1767. TcpConnection *tc = reinterpret_cast<TcpConnection *>(parser->data);
  1768. tc->messageSize += (unsigned long)length;
  1769. if (tc->messageSize > ZT_MAX_HTTP_MESSAGE_SIZE)
  1770. return -1;
  1771. tc->body.append(ptr,length);
  1772. return 0;
  1773. }
  1774. static int ShttpOnMessageComplete(http_parser *parser)
  1775. {
  1776. TcpConnection *tc = reinterpret_cast<TcpConnection *>(parser->data);
  1777. tc->shouldKeepAlive = (http_should_keep_alive(parser) != 0);
  1778. tc->lastActivity = OSUtils::now();
  1779. if (tc->type == TcpConnection::TCP_HTTP_INCOMING) {
  1780. tc->parent->onHttpRequestToServer(tc);
  1781. } else {
  1782. tc->parent->onHttpResponseFromClient(tc);
  1783. }
  1784. return 0;
  1785. }
  1786. } // anonymous namespace
  1787. std::string OneService::platformDefaultHomePath()
  1788. {
  1789. return OSUtils::platformDefaultHomePath();
  1790. }
  1791. OneService *OneService::newInstance(const char *hp,unsigned int port) { return new OneServiceImpl(hp,port); }
  1792. OneService::~OneService() {}
  1793. } // namespace ZeroTier