OneService.cpp 69 KB

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