OneService.cpp 70 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022
  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. bool _updateAutoApply;
  226. unsigned int _primaryPort;
  227. // Local configuration and memo-ized static path definitions
  228. json _localConfig;
  229. Hashtable< uint64_t,std::vector<InetAddress> > _v4Hints;
  230. Hashtable< uint64_t,std::vector<InetAddress> > _v6Hints;
  231. Hashtable< uint64_t,std::vector<InetAddress> > _v4Blacklists;
  232. Hashtable< uint64_t,std::vector<InetAddress> > _v6Blacklists;
  233. std::vector< InetAddress > _globalV4Blacklist;
  234. std::vector< InetAddress > _globalV6Blacklist;
  235. std::vector< InetAddress > _allowManagementFrom;
  236. std::vector< std::string > _interfacePrefixBlacklist;
  237. Mutex _localConfig_m;
  238. /*
  239. * To attempt to handle NAT/gateway craziness we use three local UDP ports:
  240. *
  241. * [0] is the normal/default port, usually 9993
  242. * [1] is a port dervied from our ZeroTier address
  243. * [2] is a port computed from the normal/default for use with uPnP/NAT-PMP mappings
  244. *
  245. * [2] exists because on some gateways trying to do regular NAT-t interferes
  246. * destructively with uPnP port mapping behavior in very weird buggy ways.
  247. * It's only used if uPnP/NAT-PMP is enabled in this build.
  248. */
  249. Binder _bindings[3];
  250. unsigned int _ports[3];
  251. uint16_t _portsBE[3]; // ports in big-endian network byte order as in sockaddr
  252. // Sockets for JSON API -- bound only to V4 and V6 localhost
  253. PhySocket *_v4TcpControlSocket;
  254. PhySocket *_v6TcpControlSocket;
  255. // JSON API handler
  256. ControlPlane *_controlPlane;
  257. // Time we last received a packet from a global address
  258. uint64_t _lastDirectReceiveFromGlobal;
  259. #ifdef ZT_TCP_FALLBACK_RELAY
  260. uint64_t _lastSendToGlobalV4;
  261. #endif
  262. // Last potential sleep/wake event
  263. uint64_t _lastRestart;
  264. // Deadline for the next background task service function
  265. volatile uint64_t _nextBackgroundTaskDeadline;
  266. // Configured networks
  267. struct NetworkState
  268. {
  269. NetworkState() :
  270. tap((EthernetTap *)0)
  271. {
  272. // Real defaults are in network 'up' code in network event handler
  273. settings.allowManaged = true;
  274. settings.allowGlobal = false;
  275. settings.allowDefault = false;
  276. }
  277. EthernetTap *tap;
  278. ZT_VirtualNetworkConfig config; // memcpy() of raw config from core
  279. std::vector<InetAddress> managedIps;
  280. std::list< SharedPtr<ManagedRoute> > managedRoutes;
  281. NetworkSettings settings;
  282. };
  283. std::map<uint64_t,NetworkState> _nets;
  284. Mutex _nets_m;
  285. // Active TCP/IP connections
  286. std::set< TcpConnection * > _tcpConnections; // no mutex for this since it's done in the main loop thread only
  287. TcpConnection *_tcpFallbackTunnel;
  288. // Termination status information
  289. ReasonForTermination _termReason;
  290. std::string _fatalErrorMessage;
  291. Mutex _termReason_m;
  292. // uPnP/NAT-PMP port mapper if enabled
  293. #ifdef ZT_USE_MINIUPNPC
  294. PortMapper *_portMapper;
  295. #endif
  296. // Cluster management instance if enabled
  297. #ifdef ZT_ENABLE_CLUSTER
  298. PhySocket *_clusterMessageSocket;
  299. ClusterDefinition *_clusterDefinition;
  300. unsigned int _clusterMemberId;
  301. #endif
  302. // Set to false to force service to stop
  303. volatile bool _run;
  304. Mutex _run_m;
  305. // end member variables ----------------------------------------------------
  306. OneServiceImpl(const char *hp,unsigned int port) :
  307. _homePath((hp) ? hp : ".")
  308. ,_tcpFallbackResolver(ZT_TCP_FALLBACK_RELAY)
  309. ,_controller((EmbeddedNetworkController *)0)
  310. ,_phy(this,false,true)
  311. ,_node((Node *)0)
  312. ,_updater((SoftwareUpdater *)0)
  313. ,_updateAutoApply(false)
  314. ,_primaryPort(port)
  315. ,_controlPlane((ControlPlane *)0)
  316. ,_lastDirectReceiveFromGlobal(0)
  317. #ifdef ZT_TCP_FALLBACK_RELAY
  318. ,_lastSendToGlobalV4(0)
  319. #endif
  320. ,_lastRestart(0)
  321. ,_nextBackgroundTaskDeadline(0)
  322. ,_tcpFallbackTunnel((TcpConnection *)0)
  323. ,_termReason(ONE_STILL_RUNNING)
  324. #ifdef ZT_USE_MINIUPNPC
  325. ,_portMapper((PortMapper *)0)
  326. #endif
  327. #ifdef ZT_ENABLE_CLUSTER
  328. ,_clusterMessageSocket((PhySocket *)0)
  329. ,_clusterDefinition((ClusterDefinition *)0)
  330. ,_clusterMemberId(0)
  331. #endif
  332. ,_run(true)
  333. {
  334. _ports[0] = 0;
  335. _ports[1] = 0;
  336. _ports[2] = 0;
  337. }
  338. virtual ~OneServiceImpl()
  339. {
  340. for(int i=0;i<3;++i)
  341. _bindings[i].closeAll(_phy);
  342. _phy.close(_v4TcpControlSocket);
  343. _phy.close(_v6TcpControlSocket);
  344. #ifdef ZT_ENABLE_CLUSTER
  345. _phy.close(_clusterMessageSocket);
  346. #endif
  347. #ifdef ZT_USE_MINIUPNPC
  348. delete _portMapper;
  349. #endif
  350. delete _controller;
  351. #ifdef ZT_ENABLE_CLUSTER
  352. delete _clusterDefinition;
  353. #endif
  354. }
  355. virtual ReasonForTermination run()
  356. {
  357. try {
  358. std::string authToken;
  359. {
  360. std::string authTokenPath(_homePath + ZT_PATH_SEPARATOR_S + "authtoken.secret");
  361. if (!OSUtils::readFile(authTokenPath.c_str(),authToken)) {
  362. unsigned char foo[24];
  363. Utils::getSecureRandom(foo,sizeof(foo));
  364. authToken = "";
  365. for(unsigned int i=0;i<sizeof(foo);++i)
  366. authToken.push_back("abcdefghijklmnopqrstuvwxyz0123456789"[(unsigned long)foo[i] % 36]);
  367. if (!OSUtils::writeFile(authTokenPath.c_str(),authToken)) {
  368. Mutex::Lock _l(_termReason_m);
  369. _termReason = ONE_UNRECOVERABLE_ERROR;
  370. _fatalErrorMessage = "authtoken.secret could not be written";
  371. return _termReason;
  372. } else {
  373. OSUtils::lockDownFile(authTokenPath.c_str(),false);
  374. }
  375. }
  376. }
  377. authToken = _trimString(authToken);
  378. // Clean up any legacy files if present
  379. OSUtils::rm((_homePath + ZT_PATH_SEPARATOR_S + "peers.save").c_str());
  380. {
  381. struct ZT_Node_Callbacks cb;
  382. cb.version = 0;
  383. cb.dataStoreGetFunction = SnodeDataStoreGetFunction;
  384. cb.dataStorePutFunction = SnodeDataStorePutFunction;
  385. cb.wirePacketSendFunction = SnodeWirePacketSendFunction;
  386. cb.virtualNetworkFrameFunction = SnodeVirtualNetworkFrameFunction;
  387. cb.virtualNetworkConfigFunction = SnodeVirtualNetworkConfigFunction;
  388. cb.eventCallback = SnodeEventCallback;
  389. cb.pathCheckFunction = SnodePathCheckFunction;
  390. cb.pathLookupFunction = SnodePathLookupFunction;
  391. _node = new Node(this,&cb,OSUtils::now());
  392. }
  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. if (_updater->check(now) && _updateAutoApply)
  636. _updater->apply();
  637. }
  638. // Refresh bindings in case device's interfaces have changed, and also sync routes to update any shadow routes (e.g. shadow default)
  639. if (((now - lastBindRefresh) >= ZT_BINDER_REFRESH_PERIOD)||(restarted)) {
  640. lastBindRefresh = now;
  641. for(int i=0;i<3;++i) {
  642. if (_ports[i]) {
  643. _bindings[i].refresh(_phy,_ports[i],*this);
  644. }
  645. }
  646. {
  647. Mutex::Lock _l(_nets_m);
  648. for(std::map<uint64_t,NetworkState>::iterator n(_nets.begin());n!=_nets.end();++n) {
  649. if (n->second.tap)
  650. syncManagedStuff(n->second,false,true);
  651. }
  652. }
  653. }
  654. uint64_t dl = _nextBackgroundTaskDeadline;
  655. if (dl <= now) {
  656. _node->processBackgroundTasks(now,&_nextBackgroundTaskDeadline);
  657. dl = _nextBackgroundTaskDeadline;
  658. }
  659. if ((now - lastTcpFallbackResolve) >= ZT_TCP_FALLBACK_RERESOLVE_DELAY) {
  660. lastTcpFallbackResolve = now;
  661. _tcpFallbackResolver.resolveNow();
  662. }
  663. if ((_tcpFallbackTunnel)&&((now - _lastDirectReceiveFromGlobal) < (ZT_TCP_FALLBACK_AFTER / 2)))
  664. _phy.close(_tcpFallbackTunnel->sock);
  665. if ((now - lastTapMulticastGroupCheck) >= ZT_TAP_CHECK_MULTICAST_INTERVAL) {
  666. lastTapMulticastGroupCheck = now;
  667. Mutex::Lock _l(_nets_m);
  668. for(std::map<uint64_t,NetworkState>::const_iterator n(_nets.begin());n!=_nets.end();++n) {
  669. if (n->second.tap) {
  670. std::vector<MulticastGroup> added,removed;
  671. n->second.tap->scanMulticastGroups(added,removed);
  672. for(std::vector<MulticastGroup>::iterator m(added.begin());m!=added.end();++m)
  673. _node->multicastSubscribe(n->first,m->mac().toInt(),m->adi());
  674. for(std::vector<MulticastGroup>::iterator m(removed.begin());m!=removed.end();++m)
  675. _node->multicastUnsubscribe(n->first,m->mac().toInt(),m->adi());
  676. }
  677. }
  678. }
  679. if ((now - lastLocalInterfaceAddressCheck) >= ZT_LOCAL_INTERFACE_CHECK_INTERVAL) {
  680. lastLocalInterfaceAddressCheck = now;
  681. _node->clearLocalInterfaceAddresses();
  682. #ifdef ZT_USE_MINIUPNPC
  683. if (_portMapper) {
  684. std::vector<InetAddress> mappedAddresses(_portMapper->get());
  685. for(std::vector<InetAddress>::const_iterator ext(mappedAddresses.begin());ext!=mappedAddresses.end();++ext)
  686. _node->addLocalInterfaceAddress(reinterpret_cast<const struct sockaddr_storage *>(&(*ext)));
  687. }
  688. #endif
  689. std::vector<InetAddress> boundAddrs(_bindings[0].allBoundLocalInterfaceAddresses());
  690. for(std::vector<InetAddress>::const_iterator i(boundAddrs.begin());i!=boundAddrs.end();++i)
  691. _node->addLocalInterfaceAddress(reinterpret_cast<const struct sockaddr_storage *>(&(*i)));
  692. }
  693. const unsigned long delay = (dl > now) ? (unsigned long)(dl - now) : 100;
  694. clockShouldBe = now + (uint64_t)delay;
  695. _phy.poll(delay);
  696. }
  697. } catch (std::exception &exc) {
  698. Mutex::Lock _l(_termReason_m);
  699. _termReason = ONE_UNRECOVERABLE_ERROR;
  700. _fatalErrorMessage = exc.what();
  701. } catch ( ... ) {
  702. Mutex::Lock _l(_termReason_m);
  703. _termReason = ONE_UNRECOVERABLE_ERROR;
  704. _fatalErrorMessage = "unexpected exception in main thread";
  705. }
  706. try {
  707. while (!_tcpConnections.empty())
  708. _phy.close((*_tcpConnections.begin())->sock);
  709. } catch ( ... ) {}
  710. {
  711. Mutex::Lock _l(_nets_m);
  712. for(std::map<uint64_t,NetworkState>::iterator n(_nets.begin());n!=_nets.end();++n)
  713. delete n->second.tap;
  714. _nets.clear();
  715. }
  716. delete _controlPlane;
  717. _controlPlane = (ControlPlane *)0;
  718. delete _updater;
  719. _updater = (SoftwareUpdater *)0;
  720. delete _node;
  721. _node = (Node *)0;
  722. return _termReason;
  723. }
  724. virtual ReasonForTermination reasonForTermination() const
  725. {
  726. Mutex::Lock _l(_termReason_m);
  727. return _termReason;
  728. }
  729. virtual std::string fatalErrorMessage() const
  730. {
  731. Mutex::Lock _l(_termReason_m);
  732. return _fatalErrorMessage;
  733. }
  734. virtual std::string portDeviceName(uint64_t nwid) const
  735. {
  736. Mutex::Lock _l(_nets_m);
  737. std::map<uint64_t,NetworkState>::const_iterator n(_nets.find(nwid));
  738. if ((n != _nets.end())&&(n->second.tap))
  739. return n->second.tap->deviceName();
  740. else return std::string();
  741. }
  742. virtual bool tcpFallbackActive() const
  743. {
  744. return (_tcpFallbackTunnel != (TcpConnection *)0);
  745. }
  746. virtual void terminate()
  747. {
  748. _run_m.lock();
  749. _run = false;
  750. _run_m.unlock();
  751. _phy.whack();
  752. }
  753. virtual bool getNetworkSettings(const uint64_t nwid,NetworkSettings &settings) const
  754. {
  755. Mutex::Lock _l(_nets_m);
  756. std::map<uint64_t,NetworkState>::const_iterator n(_nets.find(nwid));
  757. if (n == _nets.end())
  758. return false;
  759. memcpy(&settings,&(n->second.settings),sizeof(NetworkSettings));
  760. return true;
  761. }
  762. virtual bool setNetworkSettings(const uint64_t nwid,const NetworkSettings &settings)
  763. {
  764. Mutex::Lock _l(_nets_m);
  765. std::map<uint64_t,NetworkState>::iterator n(_nets.find(nwid));
  766. if (n == _nets.end())
  767. return false;
  768. memcpy(&(n->second.settings),&settings,sizeof(NetworkSettings));
  769. char nlcpath[256];
  770. Utils::snprintf(nlcpath,sizeof(nlcpath),"%s" ZT_PATH_SEPARATOR_S "networks.d" ZT_PATH_SEPARATOR_S "%.16llx.local.conf",_homePath.c_str(),nwid);
  771. FILE *out = fopen(nlcpath,"w");
  772. if (out) {
  773. fprintf(out,"allowManaged=%d\n",(int)n->second.settings.allowManaged);
  774. fprintf(out,"allowGlobal=%d\n",(int)n->second.settings.allowGlobal);
  775. fprintf(out,"allowDefault=%d\n",(int)n->second.settings.allowDefault);
  776. fclose(out);
  777. }
  778. if (n->second.tap)
  779. syncManagedStuff(n->second,true,true);
  780. return true;
  781. }
  782. // Internal implementation methods -----------------------------------------
  783. // Must be called after _localConfig is read or modified
  784. void applyLocalConfig()
  785. {
  786. Mutex::Lock _l(_localConfig_m);
  787. _v4Hints.clear();
  788. _v6Hints.clear();
  789. _v4Blacklists.clear();
  790. _v6Blacklists.clear();
  791. json &virt = _localConfig["virtual"];
  792. if (virt.is_object()) {
  793. for(json::iterator v(virt.begin());v!=virt.end();++v) {
  794. const std::string nstr = v.key();
  795. if ((nstr.length() == ZT_ADDRESS_LENGTH_HEX)&&(v.value().is_object())) {
  796. const Address ztaddr(nstr.c_str());
  797. if (ztaddr) {
  798. const std::string rstr(OSUtils::jsonString(v.value()["role"],""));
  799. _node->setRole(ztaddr.toInt(),((rstr == "upstream")||(rstr == "UPSTREAM")) ? ZT_PEER_ROLE_UPSTREAM : ZT_PEER_ROLE_LEAF);
  800. const uint64_t ztaddr2 = ztaddr.toInt();
  801. std::vector<InetAddress> &v4h = _v4Hints[ztaddr2];
  802. std::vector<InetAddress> &v6h = _v6Hints[ztaddr2];
  803. std::vector<InetAddress> &v4b = _v4Blacklists[ztaddr2];
  804. std::vector<InetAddress> &v6b = _v6Blacklists[ztaddr2];
  805. json &tryAddrs = v.value()["try"];
  806. if (tryAddrs.is_array()) {
  807. for(unsigned long i=0;i<tryAddrs.size();++i) {
  808. const InetAddress ip(OSUtils::jsonString(tryAddrs[i],""));
  809. if (ip.ss_family == AF_INET)
  810. v4h.push_back(ip);
  811. else if (ip.ss_family == AF_INET6)
  812. v6h.push_back(ip);
  813. }
  814. }
  815. json &blAddrs = v.value()["blacklist"];
  816. if (blAddrs.is_array()) {
  817. for(unsigned long i=0;i<blAddrs.size();++i) {
  818. const InetAddress ip(OSUtils::jsonString(tryAddrs[i],""));
  819. if (ip.ss_family == AF_INET)
  820. v4b.push_back(ip);
  821. else if (ip.ss_family == AF_INET6)
  822. v6b.push_back(ip);
  823. }
  824. }
  825. if (v4h.empty()) _v4Hints.erase(ztaddr2);
  826. if (v6h.empty()) _v6Hints.erase(ztaddr2);
  827. if (v4b.empty()) _v4Blacklists.erase(ztaddr2);
  828. if (v6b.empty()) _v6Blacklists.erase(ztaddr2);
  829. }
  830. }
  831. }
  832. }
  833. _globalV4Blacklist.clear();
  834. _globalV6Blacklist.clear();
  835. json &physical = _localConfig["physical"];
  836. if (physical.is_object()) {
  837. for(json::iterator phy(physical.begin());phy!=physical.end();++phy) {
  838. const InetAddress net(OSUtils::jsonString(phy.key(),""));
  839. if ((net)&&(net.netmaskBits() > 0)) {
  840. if (phy.value().is_object()) {
  841. if (OSUtils::jsonBool(phy.value()["blacklist"],false)) {
  842. if (net.ss_family == AF_INET)
  843. _globalV4Blacklist.push_back(net);
  844. else if (net.ss_family == AF_INET6)
  845. _globalV6Blacklist.push_back(net);
  846. }
  847. }
  848. }
  849. }
  850. }
  851. _allowManagementFrom.clear();
  852. _interfacePrefixBlacklist.clear();
  853. json &settings = _localConfig["settings"];
  854. if (settings.is_object()) {
  855. const std::string rp(OSUtils::jsonString(settings["relayPolicy"],""));
  856. if ((rp == "always")||(rp == "ALWAYS"))
  857. _node->setRelayPolicy(ZT_RELAY_POLICY_ALWAYS);
  858. else if ((rp == "never")||(rp == "NEVER"))
  859. _node->setRelayPolicy(ZT_RELAY_POLICY_NEVER);
  860. else _node->setRelayPolicy(ZT_RELAY_POLICY_TRUSTED);
  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. std::vector<InetAddress> tunnelIps(_tcpFallbackResolver.get());
  1422. if (tunnelIps.empty()) {
  1423. if (!_tcpFallbackResolver.running())
  1424. _tcpFallbackResolver.resolveNow();
  1425. } else {
  1426. bool connected = false;
  1427. InetAddress addr(tunnelIps[(unsigned long)now % tunnelIps.size()]);
  1428. addr.setPort(ZT_TCP_FALLBACK_RELAY_PORT);
  1429. _phy.tcpConnect(reinterpret_cast<const struct sockaddr *>(&addr),connected);
  1430. }
  1431. }
  1432. }
  1433. _lastSendToGlobalV4 = now;
  1434. }
  1435. #endif // ZT_TCP_FALLBACK_RELAY
  1436. } else if (addr->ss_family == AF_INET6) {
  1437. if (reinterpret_cast<const struct sockaddr_in6 *>(localAddr)->sin6_port != 0) {
  1438. const uint16_t lp = reinterpret_cast<const struct sockaddr_in6 *>(localAddr)->sin6_port;
  1439. if (lp == _portsBE[1])
  1440. fromBindingNo = 1;
  1441. else if (lp == _portsBE[2])
  1442. fromBindingNo = 2;
  1443. }
  1444. } else {
  1445. return -1;
  1446. }
  1447. #ifdef ZT_BREAK_UDP
  1448. if (OSUtils::fileExists("/tmp/ZT_BREAK_UDP"))
  1449. return 0; // silently break UDP
  1450. #endif
  1451. return (_bindings[fromBindingNo].udpSend(_phy,*(reinterpret_cast<const InetAddress *>(localAddr)),*(reinterpret_cast<const InetAddress *>(addr)),data,len,ttl)) ? 0 : -1;
  1452. }
  1453. 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)
  1454. {
  1455. NetworkState *n = reinterpret_cast<NetworkState *>(*nuptr);
  1456. if ((!n)||(!n->tap))
  1457. return;
  1458. n->tap->put(MAC(sourceMac),MAC(destMac),etherType,data,len);
  1459. }
  1460. inline int nodePathCheckFunction(uint64_t ztaddr,const struct sockaddr_storage *localAddr,const struct sockaddr_storage *remoteAddr)
  1461. {
  1462. // Make sure we're not trying to do ZeroTier-over-ZeroTier
  1463. {
  1464. Mutex::Lock _l(_nets_m);
  1465. for(std::map<uint64_t,NetworkState>::const_iterator n(_nets.begin());n!=_nets.end();++n) {
  1466. if (n->second.tap) {
  1467. std::vector<InetAddress> ips(n->second.tap->ips());
  1468. for(std::vector<InetAddress>::const_iterator i(ips.begin());i!=ips.end();++i) {
  1469. if (i->containsAddress(*(reinterpret_cast<const InetAddress *>(remoteAddr)))) {
  1470. return 0;
  1471. }
  1472. }
  1473. }
  1474. }
  1475. }
  1476. /* Note: I do not think we need to scan for overlap with managed routes
  1477. * because of the "route forking" and interface binding that we do. This
  1478. * ensures (we hope) that ZeroTier traffic will still take the physical
  1479. * path even if its managed routes override this for other traffic. Will
  1480. * revisit if we see recursion problems. */
  1481. // Check blacklists
  1482. const Hashtable< uint64_t,std::vector<InetAddress> > *blh = (const Hashtable< uint64_t,std::vector<InetAddress> > *)0;
  1483. const std::vector<InetAddress> *gbl = (const std::vector<InetAddress> *)0;
  1484. if (remoteAddr->ss_family == AF_INET) {
  1485. blh = &_v4Blacklists;
  1486. gbl = &_globalV4Blacklist;
  1487. } else if (remoteAddr->ss_family == AF_INET6) {
  1488. blh = &_v6Blacklists;
  1489. gbl = &_globalV6Blacklist;
  1490. }
  1491. if (blh) {
  1492. Mutex::Lock _l(_localConfig_m);
  1493. const std::vector<InetAddress> *l = blh->get(ztaddr);
  1494. if (l) {
  1495. for(std::vector<InetAddress>::const_iterator a(l->begin());a!=l->end();++a) {
  1496. if (a->containsAddress(*reinterpret_cast<const InetAddress *>(remoteAddr)))
  1497. return 0;
  1498. }
  1499. }
  1500. for(std::vector<InetAddress>::const_iterator a(gbl->begin());a!=gbl->end();++a) {
  1501. if (a->containsAddress(*reinterpret_cast<const InetAddress *>(remoteAddr)))
  1502. return 0;
  1503. }
  1504. }
  1505. return 1;
  1506. }
  1507. inline int nodePathLookupFunction(uint64_t ztaddr,int family,struct sockaddr_storage *result)
  1508. {
  1509. const Hashtable< uint64_t,std::vector<InetAddress> > *lh = (const Hashtable< uint64_t,std::vector<InetAddress> > *)0;
  1510. if (family < 0)
  1511. lh = (_node->prng() & 1) ? &_v4Hints : &_v6Hints;
  1512. else if (family == AF_INET)
  1513. lh = &_v4Hints;
  1514. else if (family == AF_INET6)
  1515. lh = &_v6Hints;
  1516. else return 0;
  1517. const std::vector<InetAddress> *l = lh->get(ztaddr);
  1518. if ((l)&&(l->size() > 0)) {
  1519. memcpy(result,&((*l)[(unsigned long)_node->prng() % l->size()]),sizeof(struct sockaddr_storage));
  1520. return 1;
  1521. } else return 0;
  1522. }
  1523. inline void tapFrameHandler(uint64_t nwid,const MAC &from,const MAC &to,unsigned int etherType,unsigned int vlanId,const void *data,unsigned int len)
  1524. {
  1525. _node->processVirtualNetworkFrame(OSUtils::now(),nwid,from.toInt(),to.toInt(),etherType,vlanId,data,len,&_nextBackgroundTaskDeadline);
  1526. }
  1527. inline void onHttpRequestToServer(TcpConnection *tc)
  1528. {
  1529. char tmpn[256];
  1530. std::string data;
  1531. std::string contentType("text/plain"); // default if not changed in handleRequest()
  1532. unsigned int scode = 404;
  1533. bool allow;
  1534. {
  1535. Mutex::Lock _l(_localConfig_m);
  1536. if (_allowManagementFrom.size() == 0) {
  1537. allow = (tc->from.ipScope() == InetAddress::IP_SCOPE_LOOPBACK);
  1538. } else {
  1539. allow = false;
  1540. for(std::vector<InetAddress>::const_iterator i(_allowManagementFrom.begin());i!=_allowManagementFrom.end();++i) {
  1541. if (i->containsAddress(tc->from)) {
  1542. allow = true;
  1543. break;
  1544. }
  1545. }
  1546. }
  1547. }
  1548. if (allow) {
  1549. try {
  1550. if (_controlPlane)
  1551. scode = _controlPlane->handleRequest(tc->from,tc->parser.method,tc->url,tc->headers,tc->body,data,contentType);
  1552. else scode = 500;
  1553. } catch (std::exception &exc) {
  1554. fprintf(stderr,"WARNING: unexpected exception processing control HTTP request: %s" ZT_EOL_S,exc.what());
  1555. scode = 500;
  1556. } catch ( ... ) {
  1557. fprintf(stderr,"WARNING: unexpected exception processing control HTTP request: unknown exceptino" ZT_EOL_S);
  1558. scode = 500;
  1559. }
  1560. } else {
  1561. scode = 401;
  1562. }
  1563. const char *scodestr;
  1564. switch(scode) {
  1565. case 200: scodestr = "OK"; break;
  1566. case 400: scodestr = "Bad Request"; break;
  1567. case 401: scodestr = "Unauthorized"; break;
  1568. case 403: scodestr = "Forbidden"; break;
  1569. case 404: scodestr = "Not Found"; break;
  1570. case 500: scodestr = "Internal Server Error"; break;
  1571. case 501: scodestr = "Not Implemented"; break;
  1572. case 503: scodestr = "Service Unavailable"; break;
  1573. default: scodestr = "Error"; break;
  1574. }
  1575. Utils::snprintf(tmpn,sizeof(tmpn),"HTTP/1.1 %.3u %s\r\nCache-Control: no-cache\r\nPragma: no-cache\r\n",scode,scodestr);
  1576. {
  1577. Mutex::Lock _l(tc->writeBuf_m);
  1578. tc->writeBuf.assign(tmpn);
  1579. tc->writeBuf.append("Content-Type: ");
  1580. tc->writeBuf.append(contentType);
  1581. Utils::snprintf(tmpn,sizeof(tmpn),"\r\nContent-Length: %lu\r\n",(unsigned long)data.length());
  1582. tc->writeBuf.append(tmpn);
  1583. if (!tc->shouldKeepAlive)
  1584. tc->writeBuf.append("Connection: close\r\n");
  1585. tc->writeBuf.append("\r\n");
  1586. if (tc->parser.method != HTTP_HEAD)
  1587. tc->writeBuf.append(data);
  1588. }
  1589. _phy.setNotifyWritable(tc->sock,true);
  1590. }
  1591. inline void onHttpResponseFromClient(TcpConnection *tc)
  1592. {
  1593. if (!tc->shouldKeepAlive)
  1594. _phy.close(tc->sock); // will call close handler, which deletes from _tcpConnections
  1595. }
  1596. bool shouldBindInterface(const char *ifname,const InetAddress &ifaddr)
  1597. {
  1598. #if defined(__linux__) || defined(linux) || defined(__LINUX__) || defined(__linux)
  1599. if ((ifname[0] == 'l')&&(ifname[1] == 'o')) return false; // loopback
  1600. if ((ifname[0] == 'z')&&(ifname[1] == 't')) return false; // sanity check: zt#
  1601. if ((ifname[0] == 't')&&(ifname[1] == 'u')&&(ifname[2] == 'n')) return false; // tun# is probably an OpenVPN tunnel or similar
  1602. if ((ifname[0] == 't')&&(ifname[1] == 'a')&&(ifname[2] == 'p')) return false; // tap# is probably an OpenVPN tunnel or similar
  1603. #endif
  1604. #ifdef __APPLE__
  1605. if ((ifname[0] == 'l')&&(ifname[1] == 'o')) return false; // loopback
  1606. if ((ifname[0] == 'z')&&(ifname[1] == 't')) return false; // sanity check: zt#
  1607. if ((ifname[0] == 't')&&(ifname[1] == 'u')&&(ifname[2] == 'n')) return false; // tun# is probably an OpenVPN tunnel or similar
  1608. if ((ifname[0] == 't')&&(ifname[1] == 'a')&&(ifname[2] == 'p')) return false; // tap# is probably an OpenVPN tunnel or similar
  1609. if ((ifname[0] == 'u')&&(ifname[1] == 't')&&(ifname[2] == 'u')&&(ifname[3] == 'n')) return false; // ... as is utun#
  1610. #endif
  1611. {
  1612. Mutex::Lock _l(_localConfig_m);
  1613. for(std::vector<std::string>::const_iterator p(_interfacePrefixBlacklist.begin());p!=_interfacePrefixBlacklist.end();++p) {
  1614. if (!strncmp(p->c_str(),ifname,p->length()))
  1615. return false;
  1616. }
  1617. }
  1618. {
  1619. Mutex::Lock _l(_nets_m);
  1620. for(std::map<uint64_t,NetworkState>::const_iterator n(_nets.begin());n!=_nets.end();++n) {
  1621. if (n->second.tap) {
  1622. std::vector<InetAddress> ips(n->second.tap->ips());
  1623. for(std::vector<InetAddress>::const_iterator i(ips.begin());i!=ips.end();++i) {
  1624. if (i->ipsEqual(ifaddr))
  1625. return false;
  1626. }
  1627. }
  1628. }
  1629. }
  1630. return true;
  1631. }
  1632. std::string _dataStorePrepPath(const char *name) const
  1633. {
  1634. std::string p(_homePath);
  1635. p.push_back(ZT_PATH_SEPARATOR);
  1636. char lastc = (char)0;
  1637. for(const char *n=name;(*n);++n) {
  1638. if ((*n == '.')&&(lastc == '.'))
  1639. return std::string(); // don't allow ../../ stuff as a precaution
  1640. if (*n == '/') {
  1641. OSUtils::mkdir(p.c_str());
  1642. p.push_back(ZT_PATH_SEPARATOR);
  1643. } else p.push_back(*n);
  1644. lastc = *n;
  1645. }
  1646. return p;
  1647. }
  1648. bool _trialBind(unsigned int port)
  1649. {
  1650. struct sockaddr_in in4;
  1651. struct sockaddr_in6 in6;
  1652. PhySocket *tb;
  1653. memset(&in4,0,sizeof(in4));
  1654. in4.sin_family = AF_INET;
  1655. in4.sin_port = Utils::hton((uint16_t)port);
  1656. tb = _phy.udpBind(reinterpret_cast<const struct sockaddr *>(&in4),(void *)0,0);
  1657. if (tb) {
  1658. _phy.close(tb,false);
  1659. tb = _phy.tcpListen(reinterpret_cast<const struct sockaddr *>(&in4),(void *)0);
  1660. if (tb) {
  1661. _phy.close(tb,false);
  1662. return true;
  1663. }
  1664. }
  1665. memset(&in6,0,sizeof(in6));
  1666. in6.sin6_family = AF_INET6;
  1667. in6.sin6_port = Utils::hton((uint16_t)port);
  1668. tb = _phy.udpBind(reinterpret_cast<const struct sockaddr *>(&in6),(void *)0,0);
  1669. if (tb) {
  1670. _phy.close(tb,false);
  1671. tb = _phy.tcpListen(reinterpret_cast<const struct sockaddr *>(&in6),(void *)0);
  1672. if (tb) {
  1673. _phy.close(tb,false);
  1674. return true;
  1675. }
  1676. }
  1677. return false;
  1678. }
  1679. };
  1680. static int SnodeVirtualNetworkConfigFunction(ZT_Node *node,void *uptr,uint64_t nwid,void **nuptr,enum ZT_VirtualNetworkConfigOperation op,const ZT_VirtualNetworkConfig *nwconf)
  1681. { return reinterpret_cast<OneServiceImpl *>(uptr)->nodeVirtualNetworkConfigFunction(nwid,nuptr,op,nwconf); }
  1682. static void SnodeEventCallback(ZT_Node *node,void *uptr,enum ZT_Event event,const void *metaData)
  1683. { reinterpret_cast<OneServiceImpl *>(uptr)->nodeEventCallback(event,metaData); }
  1684. static long SnodeDataStoreGetFunction(ZT_Node *node,void *uptr,const char *name,void *buf,unsigned long bufSize,unsigned long readIndex,unsigned long *totalSize)
  1685. { return reinterpret_cast<OneServiceImpl *>(uptr)->nodeDataStoreGetFunction(name,buf,bufSize,readIndex,totalSize); }
  1686. static int SnodeDataStorePutFunction(ZT_Node *node,void *uptr,const char *name,const void *data,unsigned long len,int secure)
  1687. { return reinterpret_cast<OneServiceImpl *>(uptr)->nodeDataStorePutFunction(name,data,len,secure); }
  1688. 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)
  1689. { return reinterpret_cast<OneServiceImpl *>(uptr)->nodeWirePacketSendFunction(localAddr,addr,data,len,ttl); }
  1690. 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)
  1691. { reinterpret_cast<OneServiceImpl *>(uptr)->nodeVirtualNetworkFrameFunction(nwid,nuptr,sourceMac,destMac,etherType,vlanId,data,len); }
  1692. static int SnodePathCheckFunction(ZT_Node *node,void *uptr,uint64_t ztaddr,const struct sockaddr_storage *localAddr,const struct sockaddr_storage *remoteAddr)
  1693. { return reinterpret_cast<OneServiceImpl *>(uptr)->nodePathCheckFunction(ztaddr,localAddr,remoteAddr); }
  1694. static int SnodePathLookupFunction(ZT_Node *node,void *uptr,uint64_t ztaddr,int family,struct sockaddr_storage *result)
  1695. { return reinterpret_cast<OneServiceImpl *>(uptr)->nodePathLookupFunction(ztaddr,family,result); }
  1696. #ifdef ZT_ENABLE_CLUSTER
  1697. static void SclusterSendFunction(void *uptr,unsigned int toMemberId,const void *data,unsigned int len)
  1698. {
  1699. OneServiceImpl *const impl = reinterpret_cast<OneServiceImpl *>(uptr);
  1700. const ClusterDefinition::MemberDefinition &md = (*(impl->_clusterDefinition))[toMemberId];
  1701. if (md.clusterEndpoint)
  1702. impl->_phy.udpSend(impl->_clusterMessageSocket,reinterpret_cast<const struct sockaddr *>(&(md.clusterEndpoint)),data,len);
  1703. }
  1704. static int SclusterGeoIpFunction(void *uptr,const struct sockaddr_storage *addr,int *x,int *y,int *z)
  1705. {
  1706. OneServiceImpl *const impl = reinterpret_cast<OneServiceImpl *>(uptr);
  1707. return (int)(impl->_clusterDefinition->geo().locate(*(reinterpret_cast<const InetAddress *>(addr)),*x,*y,*z));
  1708. }
  1709. #endif
  1710. 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)
  1711. { reinterpret_cast<OneServiceImpl *>(uptr)->tapFrameHandler(nwid,from,to,etherType,vlanId,data,len); }
  1712. static int ShttpOnMessageBegin(http_parser *parser)
  1713. {
  1714. TcpConnection *tc = reinterpret_cast<TcpConnection *>(parser->data);
  1715. tc->currentHeaderField = "";
  1716. tc->currentHeaderValue = "";
  1717. tc->messageSize = 0;
  1718. tc->url = "";
  1719. tc->status = "";
  1720. tc->headers.clear();
  1721. tc->body = "";
  1722. return 0;
  1723. }
  1724. static int ShttpOnUrl(http_parser *parser,const char *ptr,size_t length)
  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->url.append(ptr,length);
  1731. return 0;
  1732. }
  1733. #if (HTTP_PARSER_VERSION_MAJOR >= 2) && (HTTP_PARSER_VERSION_MINOR >= 2)
  1734. static int ShttpOnStatus(http_parser *parser,const char *ptr,size_t length)
  1735. #else
  1736. static int ShttpOnStatus(http_parser *parser)
  1737. #endif
  1738. {
  1739. /*
  1740. TcpConnection *tc = reinterpret_cast<TcpConnection *>(parser->data);
  1741. tc->messageSize += (unsigned long)length;
  1742. if (tc->messageSize > ZT_MAX_HTTP_MESSAGE_SIZE)
  1743. return -1;
  1744. tc->status.append(ptr,length);
  1745. */
  1746. return 0;
  1747. }
  1748. static int ShttpOnHeaderField(http_parser *parser,const char *ptr,size_t length)
  1749. {
  1750. TcpConnection *tc = reinterpret_cast<TcpConnection *>(parser->data);
  1751. tc->messageSize += (unsigned long)length;
  1752. if (tc->messageSize > ZT_MAX_HTTP_MESSAGE_SIZE)
  1753. return -1;
  1754. if ((tc->currentHeaderField.length())&&(tc->currentHeaderValue.length())) {
  1755. tc->headers[tc->currentHeaderField] = tc->currentHeaderValue;
  1756. tc->currentHeaderField = "";
  1757. tc->currentHeaderValue = "";
  1758. }
  1759. for(size_t i=0;i<length;++i)
  1760. tc->currentHeaderField.push_back(OSUtils::toLower(ptr[i]));
  1761. return 0;
  1762. }
  1763. static int ShttpOnValue(http_parser *parser,const char *ptr,size_t length)
  1764. {
  1765. TcpConnection *tc = reinterpret_cast<TcpConnection *>(parser->data);
  1766. tc->messageSize += (unsigned long)length;
  1767. if (tc->messageSize > ZT_MAX_HTTP_MESSAGE_SIZE)
  1768. return -1;
  1769. tc->currentHeaderValue.append(ptr,length);
  1770. return 0;
  1771. }
  1772. static int ShttpOnHeadersComplete(http_parser *parser)
  1773. {
  1774. TcpConnection *tc = reinterpret_cast<TcpConnection *>(parser->data);
  1775. if ((tc->currentHeaderField.length())&&(tc->currentHeaderValue.length()))
  1776. tc->headers[tc->currentHeaderField] = tc->currentHeaderValue;
  1777. return 0;
  1778. }
  1779. static int ShttpOnBody(http_parser *parser,const char *ptr,size_t length)
  1780. {
  1781. TcpConnection *tc = reinterpret_cast<TcpConnection *>(parser->data);
  1782. tc->messageSize += (unsigned long)length;
  1783. if (tc->messageSize > ZT_MAX_HTTP_MESSAGE_SIZE)
  1784. return -1;
  1785. tc->body.append(ptr,length);
  1786. return 0;
  1787. }
  1788. static int ShttpOnMessageComplete(http_parser *parser)
  1789. {
  1790. TcpConnection *tc = reinterpret_cast<TcpConnection *>(parser->data);
  1791. tc->shouldKeepAlive = (http_should_keep_alive(parser) != 0);
  1792. tc->lastActivity = OSUtils::now();
  1793. if (tc->type == TcpConnection::TCP_HTTP_INCOMING) {
  1794. tc->parent->onHttpRequestToServer(tc);
  1795. } else {
  1796. tc->parent->onHttpResponseFromClient(tc);
  1797. }
  1798. return 0;
  1799. }
  1800. } // anonymous namespace
  1801. std::string OneService::platformDefaultHomePath()
  1802. {
  1803. return OSUtils::platformDefaultHomePath();
  1804. }
  1805. OneService *OneService::newInstance(const char *hp,unsigned int port) { return new OneServiceImpl(hp,port); }
  1806. OneService::~OneService() {}
  1807. } // namespace ZeroTier