OneService.cpp 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973
  1. /*
  2. * ZeroTier One - Network Virtualization Everywhere
  3. * Copyright (C) 2011-2015 ZeroTier, Inc.
  4. *
  5. * This program is free software: you can redistribute it and/or modify
  6. * it under the terms of the GNU General Public License as published by
  7. * the Free Software Foundation, either version 3 of the License, or
  8. * (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU General Public License
  16. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  17. *
  18. * --
  19. *
  20. * ZeroTier may be used and distributed under the terms of the GPLv3, which
  21. * are available at: http://www.gnu.org/licenses/gpl-3.0.html
  22. *
  23. * If you would like to embed ZeroTier into a commercial application or
  24. * redistribute it in a modified binary form, please contact ZeroTier Networks
  25. * LLC. Start here: http://www.zerotier.com/
  26. */
  27. #include <stdio.h>
  28. #include <stdlib.h>
  29. #include <string.h>
  30. #include <string>
  31. #include <map>
  32. #include <set>
  33. #include <vector>
  34. #include <algorithm>
  35. #include "../version.h"
  36. #include "../include/ZeroTierOne.h"
  37. #include "../ext/http-parser/http_parser.h"
  38. #include "../node/Constants.hpp"
  39. #include "../node/Mutex.hpp"
  40. #include "../node/Node.hpp"
  41. #include "../node/Utils.hpp"
  42. #include "../node/InetAddress.hpp"
  43. #include "../node/MAC.hpp"
  44. #include "../osdep/Phy.hpp"
  45. #include "../osdep/OSUtils.hpp"
  46. #include "OneService.hpp"
  47. #include "ControlPlane.hpp"
  48. #ifdef ZT_ENABLE_NETWORK_CONTROLLER
  49. #include "../controller/SqliteNetworkController.hpp"
  50. #else
  51. class SqliteNetworkController;
  52. #endif
  53. #ifdef __WINDOWS__
  54. #include <ShlObj.h>
  55. #endif
  56. // Include the right tap device driver for this platform -- add new platforms here
  57. #ifdef __APPLE__
  58. #include "../osdep/OSXEthernetTap.hpp"
  59. namespace ZeroTier { typedef OSXEthernetTap EthernetTap; }
  60. #endif
  61. #ifdef __LINUX__
  62. #include "../osdep/LinuxEthernetTap.hpp"
  63. namespace ZeroTier { typedef LinuxEthernetTap EthernetTap; }
  64. #endif
  65. #ifdef __WINDOWS__
  66. #include "../osdep/WindowsEthernetTap.hpp"
  67. namespace ZeroTier { typedef WindowsEthernetTap EthernetTap; }
  68. #endif
  69. #if defined(__BSD__) && (!defined(__APPLE__))
  70. #include "../osdep/BSDEthernetTap.hpp"
  71. namespace ZeroTier { typedef BSDEthernetTap EthernetTap; }
  72. #endif
  73. // Sanity limits for HTTP
  74. #define ZT_MAX_HTTP_MESSAGE_SIZE (1024 * 1024 * 8)
  75. #define ZT_MAX_HTTP_CONNECTIONS 64
  76. // Interface metric for ZeroTier taps
  77. #define ZT_IF_METRIC 32768
  78. // How often to check for new multicast subscriptions on a tap device
  79. #define ZT_TAP_CHECK_MULTICAST_INTERVAL 30000
  80. // Path under ZT1 home for controller database if controller is enabled
  81. #define ZT1_CONTROLLER_DB_PATH "controller.db"
  82. namespace ZeroTier {
  83. namespace {
  84. class OneServiceImpl;
  85. static int SnodeVirtualNetworkConfigFunction(ZT1_Node *node,void *uptr,uint64_t nwid,enum ZT1_VirtualNetworkConfigOperation op,const ZT1_VirtualNetworkConfig *nwconf);
  86. static void SnodeEventCallback(ZT1_Node *node,void *uptr,enum ZT1_Event event,const void *metaData);
  87. static long SnodeDataStoreGetFunction(ZT1_Node *node,void *uptr,const char *name,void *buf,unsigned long bufSize,unsigned long readIndex,unsigned long *totalSize);
  88. static int SnodeDataStorePutFunction(ZT1_Node *node,void *uptr,const char *name,const void *data,unsigned long len,int secure);
  89. static int SnodeWirePacketSendFunction(ZT1_Node *node,void *uptr,const struct sockaddr_storage *addr,unsigned int desperation,const void *data,unsigned int len);
  90. static void SnodeVirtualNetworkFrameFunction(ZT1_Node *node,void *uptr,uint64_t nwid,uint64_t sourceMac,uint64_t destMac,unsigned int etherType,unsigned int vlanId,const void *data,unsigned int len);
  91. 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);
  92. static int ShttpOnMessageBegin(http_parser *parser);
  93. static int ShttpOnUrl(http_parser *parser,const char *ptr,size_t length);
  94. static int ShttpOnStatus(http_parser *parser,const char *ptr,size_t length);
  95. static int ShttpOnHeaderField(http_parser *parser,const char *ptr,size_t length);
  96. static int ShttpOnValue(http_parser *parser,const char *ptr,size_t length);
  97. static int ShttpOnHeadersComplete(http_parser *parser);
  98. static int ShttpOnBody(http_parser *parser,const char *ptr,size_t length);
  99. static int ShttpOnMessageComplete(http_parser *parser);
  100. static const struct http_parser_settings HTTP_PARSER_SETTINGS = {
  101. ShttpOnMessageBegin,
  102. ShttpOnUrl,
  103. ShttpOnStatus,
  104. ShttpOnHeaderField,
  105. ShttpOnValue,
  106. ShttpOnHeadersComplete,
  107. ShttpOnBody,
  108. ShttpOnMessageComplete
  109. };
  110. struct TcpConnection
  111. {
  112. enum {
  113. TCP_HTTP_INCOMING,
  114. TCP_HTTP_OUTGOING, // not currently used
  115. TCP_TUNNEL_OUTGOING // fale-SSL outgoing tunnel -- HTTP-related fields are not used
  116. } type;
  117. bool shouldKeepAlive;
  118. OneServiceImpl *parent;
  119. PhySocket *sock;
  120. InetAddress from;
  121. http_parser parser;
  122. unsigned long messageSize;
  123. uint64_t lastActivity;
  124. std::string currentHeaderField;
  125. std::string currentHeaderValue;
  126. std::string url;
  127. std::string status;
  128. std::map< std::string,std::string > headers;
  129. std::string body;
  130. std::string writeBuf;
  131. };
  132. class OneServiceImpl : public OneService
  133. {
  134. public:
  135. OneServiceImpl(const char *hp,unsigned int port,const char *overrideRootTopology) :
  136. _homePath((hp) ? hp : "."),
  137. #ifdef ZT_ENABLE_NETWORK_CONTROLLER
  138. _controller((_homePath + ZT_PATH_SEPARATOR_S + ZT1_CONTROLLER_DB_PATH).c_str()),
  139. #endif
  140. _phy(this,true),
  141. _overrideRootTopology((overrideRootTopology) ? overrideRootTopology : ""),
  142. _node((Node *)0),
  143. _controlPlane((ControlPlane *)0),
  144. _nextBackgroundTaskDeadline(0),
  145. _termReason(ONE_STILL_RUNNING),
  146. _run(true)
  147. {
  148. struct sockaddr_in in4;
  149. struct sockaddr_in6 in6;
  150. ::memset((void *)&in4,0,sizeof(in4));
  151. in4.sin_family = AF_INET;
  152. in4.sin_port = Utils::hton((uint16_t)port);
  153. _v4UdpSocket = _phy.udpBind((const struct sockaddr *)&in4,this,131072);
  154. if (!_v4UdpSocket)
  155. throw std::runtime_error("cannot bind to port (UDP/IPv4)");
  156. in4.sin_addr.s_addr = Utils::hton((uint32_t)0x7f000001); // right now we just listen for TCP @localhost
  157. _v4TcpListenSocket = _phy.tcpListen((const struct sockaddr *)&in4,this);
  158. if (!_v4TcpListenSocket) {
  159. _phy.close(_v4UdpSocket);
  160. throw std::runtime_error("cannot bind to port (TCP/IPv4)");
  161. }
  162. ::memset((void *)&in6,0,sizeof(in6));
  163. in6.sin6_family = AF_INET6;
  164. in6.sin6_port = in4.sin_port;
  165. _v6UdpSocket = _phy.udpBind((const struct sockaddr *)&in6,this,131072);
  166. in6.sin6_addr.s6_addr[15] = 1; // listen for TCP only at localhost
  167. _v6TcpListenSocket = _phy.tcpListen((const struct sockaddr *)&in6,this);
  168. char portstr[64];
  169. Utils::snprintf(portstr,sizeof(portstr),"%u",port);
  170. OSUtils::writeFile((_homePath + ZT_PATH_SEPARATOR_S + "zerotier-one.port").c_str(),std::string(portstr));
  171. }
  172. virtual ~OneServiceImpl()
  173. {
  174. _phy.close(_v4UdpSocket);
  175. _phy.close(_v6UdpSocket);
  176. _phy.close(_v4TcpListenSocket);
  177. _phy.close(_v6TcpListenSocket);
  178. }
  179. virtual ReasonForTermination run()
  180. {
  181. try {
  182. std::string authToken;
  183. {
  184. std::string authTokenPath(_homePath + ZT_PATH_SEPARATOR_S + "authtoken.secret");
  185. if (!OSUtils::readFile(authTokenPath.c_str(),authToken)) {
  186. unsigned char foo[24];
  187. Utils::getSecureRandom(foo,sizeof(foo));
  188. authToken = "";
  189. for(unsigned int i=0;i<sizeof(foo);++i)
  190. authToken.push_back("abcdefghijklmnopqrstuvwxyz0123456789"[(unsigned long)foo[i] % 36]);
  191. if (!OSUtils::writeFile(authTokenPath.c_str(),authToken)) {
  192. Mutex::Lock _l(_termReason_m);
  193. _termReason = ONE_UNRECOVERABLE_ERROR;
  194. _fatalErrorMessage = "authtoken.secret could not be written";
  195. return _termReason;
  196. } else OSUtils::lockDownFile(authTokenPath.c_str(),false);
  197. }
  198. }
  199. authToken = Utils::trim(authToken);
  200. _node = new Node(
  201. OSUtils::now(),
  202. this,
  203. SnodeDataStoreGetFunction,
  204. SnodeDataStorePutFunction,
  205. SnodeWirePacketSendFunction,
  206. SnodeVirtualNetworkFrameFunction,
  207. SnodeVirtualNetworkConfigFunction,
  208. SnodeEventCallback,
  209. ((_overrideRootTopology.length() > 0) ? _overrideRootTopology.c_str() : (const char *)0));
  210. #ifdef ZT_ENABLE_NETWORK_CONTROLLER
  211. _node->setNetconfMaster((void *)&_controller);
  212. #endif
  213. _controlPlane = new ControlPlane(this,_node,(_homePath + ZT_PATH_SEPARATOR_S + "ui").c_str());
  214. _controlPlane->addAuthToken(authToken.c_str());
  215. #ifdef ZT_ENABLE_NETWORK_CONTROLLER
  216. _controlPlane->setController(&_controller);
  217. #endif
  218. { // Remember networks from previous session
  219. std::vector<std::string> networksDotD(OSUtils::listDirectory((_homePath + ZT_PATH_SEPARATOR_S + "networks.d").c_str()));
  220. for(std::vector<std::string>::iterator f(networksDotD.begin());f!=networksDotD.end();++f) {
  221. std::size_t dot = f->find_last_of('.');
  222. if ((dot == 16)&&(f->substr(16) == ".conf"))
  223. _node->join(Utils::hexStrToU64(f->substr(0,dot).c_str()));
  224. }
  225. }
  226. _nextBackgroundTaskDeadline = 0;
  227. uint64_t lastTapMulticastGroupCheck = 0;
  228. for(;;) {
  229. _run_m.lock();
  230. if (!_run) {
  231. _run_m.unlock();
  232. _termReason_m.lock();
  233. _termReason = ONE_NORMAL_TERMINATION;
  234. _termReason_m.unlock();
  235. break;
  236. } else _run_m.unlock();
  237. uint64_t dl = _nextBackgroundTaskDeadline;
  238. uint64_t now = OSUtils::now();
  239. if (dl <= now) {
  240. _node->processBackgroundTasks(now,&_nextBackgroundTaskDeadline);
  241. dl = _nextBackgroundTaskDeadline;
  242. }
  243. if ((now - lastTapMulticastGroupCheck) >= ZT_TAP_CHECK_MULTICAST_INTERVAL) {
  244. lastTapMulticastGroupCheck = now;
  245. Mutex::Lock _l(_taps_m);
  246. for(std::map< uint64_t,EthernetTap *>::const_iterator t(_taps.begin());t!=_taps.end();++t) {
  247. std::vector<MulticastGroup> added,removed;
  248. t->second->scanMulticastGroups(added,removed);
  249. for(std::vector<MulticastGroup>::iterator m(added.begin());m!=added.end();++m)
  250. _node->multicastSubscribe(t->first,m->mac().toInt(),m->adi());
  251. for(std::vector<MulticastGroup>::iterator m(removed.begin());m!=removed.end();++m)
  252. _node->multicastUnsubscribe(t->first,m->mac().toInt(),m->adi());
  253. }
  254. }
  255. const unsigned long delay = (dl > now) ? (unsigned long)(dl - now) : 100;
  256. _phy.poll(delay);
  257. }
  258. } catch (std::exception &exc) {
  259. Mutex::Lock _l(_termReason_m);
  260. _termReason = ONE_UNRECOVERABLE_ERROR;
  261. _fatalErrorMessage = exc.what();
  262. } catch ( ... ) {
  263. Mutex::Lock _l(_termReason_m);
  264. _termReason = ONE_UNRECOVERABLE_ERROR;
  265. _fatalErrorMessage = "unexpected exception in main thread";
  266. }
  267. try {
  268. while (!_tcpConections.empty())
  269. _phy.close(_tcpConections.begin()->first);
  270. } catch ( ... ) {}
  271. {
  272. Mutex::Lock _l(_taps_m);
  273. for(std::map< uint64_t,EthernetTap * >::iterator t(_taps.begin());t!=_taps.end();++t)
  274. delete t->second;
  275. _taps.clear();
  276. }
  277. delete _controlPlane;
  278. _controlPlane = (ControlPlane *)0;
  279. delete _node;
  280. _node = (Node *)0;
  281. return _termReason;
  282. }
  283. virtual ReasonForTermination reasonForTermination() const
  284. {
  285. Mutex::Lock _l(_termReason_m);
  286. return _termReason;
  287. }
  288. virtual std::string fatalErrorMessage() const
  289. {
  290. Mutex::Lock _l(_termReason_m);
  291. return _fatalErrorMessage;
  292. }
  293. virtual std::string portDeviceName(uint64_t nwid) const
  294. {
  295. Mutex::Lock _l(_taps_m);
  296. std::map< uint64_t,EthernetTap * >::const_iterator t(_taps.find(nwid));
  297. if (t != _taps.end())
  298. return t->second->deviceName();
  299. return std::string();
  300. }
  301. virtual void terminate()
  302. {
  303. _run_m.lock();
  304. _run = false;
  305. _run_m.unlock();
  306. _phy.whack();
  307. }
  308. // Begin private implementation methods
  309. inline void phyOnDatagram(PhySocket *sock,void **uptr,const struct sockaddr *from,void *data,unsigned long len)
  310. {
  311. ZT1_ResultCode rc = _node->processWirePacket(
  312. OSUtils::now(),
  313. (const struct sockaddr_storage *)from, // Phy<> uses sockaddr_storage, so it'll always be that big
  314. 0, // desperation == 0, direct UDP
  315. data,
  316. len,
  317. &_nextBackgroundTaskDeadline);
  318. if (ZT1_ResultCode_isFatal(rc)) {
  319. char tmp[256];
  320. Utils::snprintf(tmp,sizeof(tmp),"fatal error code from processWirePacket: %d",(int)rc);
  321. Mutex::Lock _l(_termReason_m);
  322. _termReason = ONE_UNRECOVERABLE_ERROR;
  323. _fatalErrorMessage = tmp;
  324. this->terminate();
  325. }
  326. }
  327. inline void phyOnTcpConnect(PhySocket *sock,void **uptr,bool success)
  328. {
  329. if (!success)
  330. return;
  331. // Outgoing connections are right now only tunnel connections
  332. TcpConnection *tc = &(_tcpConections[sock]);
  333. tc->type = TcpConnection::TCP_TUNNEL_OUTGOING;
  334. tc->shouldKeepAlive = true; // unused
  335. tc->parent = this;
  336. tc->sock = sock;
  337. // from and parser are not used
  338. tc->messageSize = 0; // unused
  339. tc->lastActivity = OSUtils::now();
  340. // HTTP stuff is not used
  341. tc->writeBuf = "";
  342. *uptr = (void *)tc;
  343. // Send "hello" message
  344. tc->writeBuf.push_back((char)0x17);
  345. tc->writeBuf.push_back((char)0x03);
  346. tc->writeBuf.push_back((char)0x03); // fake TLS 1.2 header
  347. tc->writeBuf.push_back((char)0x00);
  348. tc->writeBuf.push_back((char)0x04); // mlen == 4
  349. tc->writeBuf.push_back((char)ZEROTIER_ONE_VERSION_MAJOR);
  350. tc->writeBuf.push_back((char)ZEROTIER_ONE_VERSION_MINOR);
  351. tc->writeBuf.push_back((char)((ZEROTIER_ONE_VERSION_REVISION >> 8) & 0xff));
  352. tc->writeBuf.push_back((char)(ZEROTIER_ONE_VERSION_REVISION & 0xff));
  353. _phy.tcpSetNotifyWritable(sock,true);
  354. }
  355. inline void phyOnTcpAccept(PhySocket *sockL,PhySocket *sockN,void **uptrL,void **uptrN,const struct sockaddr *from)
  356. {
  357. // Incoming connections are TCP HTTP requests
  358. TcpConnection *tc = &(_tcpConections[sockN]);
  359. tc->type = TcpConnection::TCP_HTTP_INCOMING;
  360. tc->shouldKeepAlive = true;
  361. tc->parent = this;
  362. tc->sock = sockN;
  363. tc->from = from;
  364. http_parser_init(&(tc->parser),HTTP_REQUEST);
  365. tc->parser.data = (void *)tc;
  366. tc->messageSize = 0;
  367. tc->lastActivity = OSUtils::now();
  368. tc->currentHeaderField = "";
  369. tc->currentHeaderValue = "";
  370. tc->url = "";
  371. tc->status = "";
  372. tc->headers.clear();
  373. tc->body = "";
  374. tc->writeBuf = "";
  375. *uptrN = (void *)tc;
  376. }
  377. inline void phyOnTcpClose(PhySocket *sock,void **uptr)
  378. {
  379. _tcpConections.erase(sock);
  380. }
  381. inline void phyOnTcpData(PhySocket *sock,void **uptr,void *data,unsigned long len)
  382. {
  383. TcpConnection *tc = reinterpret_cast<TcpConnection *>(*uptr);
  384. switch(tc->type) {
  385. case TcpConnection::TCP_HTTP_INCOMING:
  386. case TcpConnection::TCP_HTTP_OUTGOING:
  387. http_parser_execute(&(tc->parser),&HTTP_PARSER_SETTINGS,(const char *)data,len);
  388. if ((tc->parser.upgrade)||(tc->parser.http_errno != HPE_OK)) {
  389. _phy.close(sock);
  390. return;
  391. }
  392. break;
  393. case TcpConnection::TCP_TUNNEL_OUTGOING:
  394. tc->body.append((const char *)data,len);
  395. if (tc->body.length() > 65535) {
  396. // sanity limit -- a message will never be this big since mlen is 16-bit
  397. _phy.close(sock);
  398. return;
  399. } else if (tc->body.length() >= 5) {
  400. const char *data = tc->body.data();
  401. const unsigned long mlen = ( ((((unsigned long)data[3]) & 0xff) << 8) | (((unsigned long)data[4]) & 0xff) );
  402. if (tc->body.length() >= (mlen + 5)) {
  403. InetAddress from;
  404. unsigned long plen = mlen; // payload length, modified if there's an IP header
  405. data += 5; // skip forward past pseudo-TLS junk and mlen
  406. if (plen == 4) {
  407. // Hello message, which isn't sent by proxy and would be ignored by client
  408. } else if (plen) {
  409. // Messages should contain IPv4 or IPv6 source IP address data
  410. switch(data[0]) {
  411. case 4: // IPv4
  412. if (plen >= 7) {
  413. from.set((const void *)(data + 1),4,((((unsigned int)data[5]) & 0xff) << 8) | (((unsigned int)data[6]) & 0xff));
  414. data += 7; // type + 4 byte IP + 2 byte port
  415. plen -= 7;
  416. } else {
  417. _phy.close(sock);
  418. return;
  419. }
  420. break;
  421. case 6: // IPv6
  422. if (plen >= 19) {
  423. from.set((const void *)(data + 1),16,((((unsigned int)data[17]) & 0xff) << 8) | (((unsigned int)data[18]) & 0xff));
  424. data += 19; // type + 16 byte IP + 2 byte port
  425. plen -= 19;
  426. } else {
  427. _phy.close(sock);
  428. return;
  429. }
  430. break;
  431. case 0: // none/omitted
  432. ++data;
  433. --plen;
  434. break;
  435. default: // invalid address type
  436. _phy.close(sock);
  437. return;
  438. }
  439. ZT1_ResultCode rc = _node->processWirePacket(
  440. OSUtils::now(),
  441. (const struct sockaddr_storage *)&from, // Phy<> uses sockaddr_storage, so it'll always be that big
  442. 1, // desperation == 1, TCP tunnel proxy
  443. data,
  444. plen,
  445. &_nextBackgroundTaskDeadline);
  446. if (ZT1_ResultCode_isFatal(rc)) {
  447. char tmp[256];
  448. Utils::snprintf(tmp,sizeof(tmp),"fatal error code from processWirePacket: %d",(int)rc);
  449. Mutex::Lock _l(_termReason_m);
  450. _termReason = ONE_UNRECOVERABLE_ERROR;
  451. _fatalErrorMessage = tmp;
  452. this->terminate();
  453. _phy.close(sock);
  454. return;
  455. }
  456. }
  457. if (tc->body.length() > (mlen + 5))
  458. tc->body = tc->body.substr(mlen + 5);
  459. else tc->body = "";
  460. }
  461. }
  462. break;
  463. }
  464. }
  465. inline void phyOnTcpWritable(PhySocket *sock,void **uptr)
  466. {
  467. TcpConnection *tc = reinterpret_cast<TcpConnection *>(*uptr);
  468. if (tc->writeBuf.length()) {
  469. long sent = (long)_phy.tcpSend(sock,tc->writeBuf.data(),(unsigned long)tc->writeBuf.length(),true);
  470. if (sent > 0) {
  471. tc->lastActivity = OSUtils::now();
  472. if ((unsigned long)sent == (unsigned long)tc->writeBuf.length()) {
  473. tc->writeBuf = "";
  474. _phy.tcpSetNotifyWritable(sock,false);
  475. if (!tc->shouldKeepAlive)
  476. _phy.close(sock); // will call close handler to delete from _tcpConections
  477. } else tc->writeBuf = tc->writeBuf.substr(sent);
  478. }
  479. } else _phy.tcpSetNotifyWritable(sock,false); // sanity check... shouldn't happen
  480. }
  481. inline int nodeVirtualNetworkConfigFunction(uint64_t nwid,enum ZT1_VirtualNetworkConfigOperation op,const ZT1_VirtualNetworkConfig *nwc)
  482. {
  483. Mutex::Lock _l(_taps_m);
  484. std::map< uint64_t,EthernetTap * >::iterator t(_taps.find(nwid));
  485. switch(op) {
  486. case ZT1_VIRTUAL_NETWORK_CONFIG_OPERATION_UP:
  487. if (t == _taps.end()) {
  488. try {
  489. char friendlyName[1024];
  490. Utils::snprintf(friendlyName,sizeof(friendlyName),"ZeroTier One [%.16llx]",nwid);
  491. t = _taps.insert(std::pair< uint64_t,EthernetTap *>(nwid,new EthernetTap(
  492. _homePath.c_str(),
  493. MAC(nwc->mac),
  494. nwc->mtu,
  495. (unsigned int)ZT_IF_METRIC,
  496. nwid,
  497. friendlyName,
  498. StapFrameHandler,
  499. (void *)this))).first;
  500. } catch ( ... ) {
  501. return -999; // tap init failed
  502. }
  503. }
  504. // fall through...
  505. case ZT1_VIRTUAL_NETWORK_CONFIG_OPERATION_CONFIG_UPDATE:
  506. if (t != _taps.end()) {
  507. t->second->setEnabled(nwc->enabled != 0);
  508. std::vector<InetAddress> &assignedIps = _tapAssignedIps[nwid];
  509. std::vector<InetAddress> newAssignedIps;
  510. for(unsigned int i=0;i<nwc->assignedAddressCount;++i)
  511. newAssignedIps.push_back(InetAddress(nwc->assignedAddresses[i]));
  512. std::sort(newAssignedIps.begin(),newAssignedIps.end());
  513. std::unique(newAssignedIps.begin(),newAssignedIps.end());
  514. for(std::vector<InetAddress>::iterator ip(newAssignedIps.begin());ip!=newAssignedIps.end();++ip) {
  515. if (!std::binary_search(assignedIps.begin(),assignedIps.end(),*ip))
  516. t->second->addIp(*ip);
  517. }
  518. for(std::vector<InetAddress>::iterator ip(assignedIps.begin());ip!=assignedIps.end();++ip) {
  519. if (!std::binary_search(newAssignedIps.begin(),newAssignedIps.end(),*ip))
  520. t->second->removeIp(*ip);
  521. }
  522. assignedIps.swap(newAssignedIps);
  523. } else {
  524. return -999; // tap init failed
  525. }
  526. break;
  527. case ZT1_VIRTUAL_NETWORK_CONFIG_OPERATION_DOWN:
  528. case ZT1_VIRTUAL_NETWORK_CONFIG_OPERATION_DESTROY:
  529. if (t != _taps.end()) {
  530. #ifdef __WINDOWS__
  531. std::string winInstanceId(t->second->instanceId());
  532. #endif
  533. delete t->second;
  534. _taps.erase(t);
  535. _tapAssignedIps.erase(nwid);
  536. #ifdef __WINDOWS__
  537. if ((op == ZT1_VIRTUAL_NETWORK_CONFIG_OPERATION_DESTROY)&&(winInstanceId.length() > 0))
  538. WindowsEthernetTap::deletePersistentTapDevice(_homePath.c_str(),winInstanceId.c_str());
  539. #endif
  540. }
  541. break;
  542. }
  543. return 0;
  544. }
  545. inline void nodeEventCallback(enum ZT1_Event event,const void *metaData)
  546. {
  547. switch(event) {
  548. case ZT1_EVENT_FATAL_ERROR_IDENTITY_COLLISION: {
  549. Mutex::Lock _l(_termReason_m);
  550. _termReason = ONE_IDENTITY_COLLISION;
  551. _fatalErrorMessage = "identity/address collision";
  552. this->terminate();
  553. } break;
  554. case ZT1_EVENT_SAW_MORE_RECENT_VERSION: {
  555. } break;
  556. case ZT1_EVENT_TRACE: {
  557. if (metaData) {
  558. ::fprintf(stderr,"%s"ZT_EOL_S,(const char *)metaData);
  559. ::fflush(stderr);
  560. }
  561. } break;
  562. default:
  563. break;
  564. }
  565. }
  566. inline long nodeDataStoreGetFunction(const char *name,void *buf,unsigned long bufSize,unsigned long readIndex,unsigned long *totalSize)
  567. {
  568. std::string p(_dataStorePrepPath(name));
  569. if (!p.length())
  570. return -2;
  571. FILE *f = fopen(p.c_str(),"rb");
  572. if (!f)
  573. return -1;
  574. if (fseek(f,0,SEEK_END) != 0) {
  575. fclose(f);
  576. return -2;
  577. }
  578. long ts = ftell(f);
  579. if (ts < 0) {
  580. fclose(f);
  581. return -2;
  582. }
  583. *totalSize = (unsigned long)ts;
  584. if (fseek(f,(long)readIndex,SEEK_SET) != 0) {
  585. fclose(f);
  586. return -2;
  587. }
  588. long n = (long)fread(buf,1,bufSize,f);
  589. fclose(f);
  590. return n;
  591. }
  592. inline int nodeDataStorePutFunction(const char *name,const void *data,unsigned long len,int secure)
  593. {
  594. std::string p(_dataStorePrepPath(name));
  595. if (!p.length())
  596. return -2;
  597. if (!data) {
  598. OSUtils::rm(p.c_str());
  599. return 0;
  600. }
  601. FILE *f = fopen(p.c_str(),"wb");
  602. if (!f)
  603. return -1;
  604. if (fwrite(data,len,1,f) == 1) {
  605. fclose(f);
  606. if (secure)
  607. OSUtils::lockDownFile(p.c_str(),false);
  608. return 0;
  609. } else {
  610. fclose(f);
  611. OSUtils::rm(p.c_str());
  612. return -1;
  613. }
  614. }
  615. inline int nodeWirePacketSendFunction(const struct sockaddr_storage *addr,unsigned int desperation,const void *data,unsigned int len)
  616. {
  617. switch(addr->ss_family) {
  618. case AF_INET:
  619. if (_v4UdpSocket)
  620. return (_phy.udpSend(_v4UdpSocket,(const struct sockaddr *)addr,data,len) ? 0 : -1);
  621. break;
  622. case AF_INET6:
  623. if (_v6UdpSocket)
  624. return (_phy.udpSend(_v6UdpSocket,(const struct sockaddr *)addr,data,len) ? 0 : -1);
  625. break;
  626. }
  627. return -1;
  628. }
  629. inline void nodeVirtualNetworkFrameFunction(uint64_t nwid,uint64_t sourceMac,uint64_t destMac,unsigned int etherType,unsigned int vlanId,const void *data,unsigned int len)
  630. {
  631. Mutex::Lock _l(_taps_m);
  632. std::map< uint64_t,EthernetTap * >::const_iterator t(_taps.find(nwid));
  633. if (t != _taps.end())
  634. t->second->put(MAC(sourceMac),MAC(destMac),etherType,data,len);
  635. }
  636. inline void tapFrameHandler(uint64_t nwid,const MAC &from,const MAC &to,unsigned int etherType,unsigned int vlanId,const void *data,unsigned int len)
  637. {
  638. _node->processVirtualNetworkFrame(OSUtils::now(),nwid,from.toInt(),to.toInt(),etherType,vlanId,data,len,&_nextBackgroundTaskDeadline);
  639. }
  640. inline void onHttpRequestToServer(TcpConnection *tc)
  641. {
  642. char tmpn[256];
  643. std::string data;
  644. std::string contentType("text/plain"); // default if not changed in handleRequest()
  645. unsigned int scode = 404;
  646. try {
  647. if (_controlPlane)
  648. scode = _controlPlane->handleRequest(tc->from,tc->parser.method,tc->url,tc->headers,tc->body,data,contentType);
  649. else scode = 500;
  650. } catch ( ... ) {
  651. scode = 500;
  652. }
  653. const char *scodestr;
  654. switch(scode) {
  655. case 200: scodestr = "OK"; break;
  656. case 400: scodestr = "Bad Request"; break;
  657. case 401: scodestr = "Unauthorized"; break;
  658. case 403: scodestr = "Forbidden"; break;
  659. case 404: scodestr = "Not Found"; break;
  660. case 500: scodestr = "Internal Server Error"; break;
  661. case 501: scodestr = "Not Implemented"; break;
  662. case 503: scodestr = "Service Unavailable"; break;
  663. default: scodestr = "Error"; break;
  664. }
  665. Utils::snprintf(tmpn,sizeof(tmpn),"HTTP/1.1 %.3u %s\r\nCache-Control: no-cache\r\nPragma: no-cache\r\n",scode,scodestr);
  666. tc->writeBuf.assign(tmpn);
  667. tc->writeBuf.append("Content-Type: ");
  668. tc->writeBuf.append(contentType);
  669. Utils::snprintf(tmpn,sizeof(tmpn),"\r\nContent-Length: %lu\r\n",(unsigned long)data.length());
  670. tc->writeBuf.append(tmpn);
  671. if (!tc->shouldKeepAlive)
  672. tc->writeBuf.append("Connection: close\r\n");
  673. tc->writeBuf.append("\r\n");
  674. if (tc->parser.method != HTTP_HEAD)
  675. tc->writeBuf.append(data);
  676. _phy.tcpSetNotifyWritable(tc->sock,true);
  677. }
  678. inline void onHttpResponseFromClient(TcpConnection *tc)
  679. {
  680. if (!tc->shouldKeepAlive)
  681. _phy.close(tc->sock); // will call close handler, which deletes from _tcpConections
  682. }
  683. private:
  684. std::string _dataStorePrepPath(const char *name) const
  685. {
  686. std::string p(_homePath);
  687. p.push_back(ZT_PATH_SEPARATOR);
  688. char lastc = (char)0;
  689. for(const char *n=name;(*n);++n) {
  690. if ((*n == '.')&&(lastc == '.'))
  691. return std::string(); // don't allow ../../ stuff as a precaution
  692. if (*n == '/') {
  693. OSUtils::mkdir(p.c_str());
  694. p.push_back(ZT_PATH_SEPARATOR);
  695. } else p.push_back(*n);
  696. lastc = *n;
  697. }
  698. return p;
  699. }
  700. const std::string _homePath;
  701. #ifdef ZT_ENABLE_NETWORK_CONTROLLER
  702. SqliteNetworkController _controller;
  703. #endif
  704. Phy<OneServiceImpl *> _phy;
  705. std::string _overrideRootTopology;
  706. Node *_node;
  707. PhySocket *_v4UdpSocket;
  708. PhySocket *_v6UdpSocket;
  709. PhySocket *_v4TcpListenSocket;
  710. PhySocket *_v6TcpListenSocket;
  711. ControlPlane *_controlPlane;
  712. volatile uint64_t _nextBackgroundTaskDeadline;
  713. std::map< uint64_t,EthernetTap * > _taps;
  714. std::map< uint64_t,std::vector<InetAddress> > _tapAssignedIps; // ZeroTier assigned IPs, not user or dhcp assigned
  715. Mutex _taps_m;
  716. std::map< PhySocket *,TcpConnection > _tcpConections; // no mutex for this since it's done in the main loop thread only
  717. ReasonForTermination _termReason;
  718. std::string _fatalErrorMessage;
  719. Mutex _termReason_m;
  720. bool _run;
  721. Mutex _run_m;
  722. };
  723. static int SnodeVirtualNetworkConfigFunction(ZT1_Node *node,void *uptr,uint64_t nwid,enum ZT1_VirtualNetworkConfigOperation op,const ZT1_VirtualNetworkConfig *nwconf)
  724. { return reinterpret_cast<OneServiceImpl *>(uptr)->nodeVirtualNetworkConfigFunction(nwid,op,nwconf); }
  725. static void SnodeEventCallback(ZT1_Node *node,void *uptr,enum ZT1_Event event,const void *metaData)
  726. { reinterpret_cast<OneServiceImpl *>(uptr)->nodeEventCallback(event,metaData); }
  727. static long SnodeDataStoreGetFunction(ZT1_Node *node,void *uptr,const char *name,void *buf,unsigned long bufSize,unsigned long readIndex,unsigned long *totalSize)
  728. { return reinterpret_cast<OneServiceImpl *>(uptr)->nodeDataStoreGetFunction(name,buf,bufSize,readIndex,totalSize); }
  729. static int SnodeDataStorePutFunction(ZT1_Node *node,void *uptr,const char *name,const void *data,unsigned long len,int secure)
  730. { return reinterpret_cast<OneServiceImpl *>(uptr)->nodeDataStorePutFunction(name,data,len,secure); }
  731. static int SnodeWirePacketSendFunction(ZT1_Node *node,void *uptr,const struct sockaddr_storage *addr,unsigned int desperation,const void *data,unsigned int len)
  732. { return reinterpret_cast<OneServiceImpl *>(uptr)->nodeWirePacketSendFunction(addr,desperation,data,len); }
  733. static void SnodeVirtualNetworkFrameFunction(ZT1_Node *node,void *uptr,uint64_t nwid,uint64_t sourceMac,uint64_t destMac,unsigned int etherType,unsigned int vlanId,const void *data,unsigned int len)
  734. { reinterpret_cast<OneServiceImpl *>(uptr)->nodeVirtualNetworkFrameFunction(nwid,sourceMac,destMac,etherType,vlanId,data,len); }
  735. 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)
  736. { reinterpret_cast<OneServiceImpl *>(uptr)->tapFrameHandler(nwid,from,to,etherType,vlanId,data,len); }
  737. static int ShttpOnMessageBegin(http_parser *parser)
  738. {
  739. TcpConnection *tc = reinterpret_cast<TcpConnection *>(parser->data);
  740. tc->currentHeaderField = "";
  741. tc->currentHeaderValue = "";
  742. tc->messageSize = 0;
  743. tc->url = "";
  744. tc->status = "";
  745. tc->headers.clear();
  746. tc->body = "";
  747. return 0;
  748. }
  749. static int ShttpOnUrl(http_parser *parser,const char *ptr,size_t length)
  750. {
  751. TcpConnection *tc = reinterpret_cast<TcpConnection *>(parser->data);
  752. tc->messageSize += (unsigned long)length;
  753. if (tc->messageSize > ZT_MAX_HTTP_MESSAGE_SIZE)
  754. return -1;
  755. tc->url.append(ptr,length);
  756. return 0;
  757. }
  758. static int ShttpOnStatus(http_parser *parser,const char *ptr,size_t length)
  759. {
  760. TcpConnection *tc = reinterpret_cast<TcpConnection *>(parser->data);
  761. tc->messageSize += (unsigned long)length;
  762. if (tc->messageSize > ZT_MAX_HTTP_MESSAGE_SIZE)
  763. return -1;
  764. tc->status.append(ptr,length);
  765. return 0;
  766. }
  767. static int ShttpOnHeaderField(http_parser *parser,const char *ptr,size_t length)
  768. {
  769. TcpConnection *tc = reinterpret_cast<TcpConnection *>(parser->data);
  770. tc->messageSize += (unsigned long)length;
  771. if (tc->messageSize > ZT_MAX_HTTP_MESSAGE_SIZE)
  772. return -1;
  773. if ((tc->currentHeaderField.length())&&(tc->currentHeaderValue.length())) {
  774. tc->headers[tc->currentHeaderField] = tc->currentHeaderValue;
  775. tc->currentHeaderField = "";
  776. tc->currentHeaderValue = "";
  777. }
  778. for(size_t i=0;i<length;++i)
  779. tc->currentHeaderField.push_back(OSUtils::toLower(ptr[i]));
  780. return 0;
  781. }
  782. static int ShttpOnValue(http_parser *parser,const char *ptr,size_t length)
  783. {
  784. TcpConnection *tc = reinterpret_cast<TcpConnection *>(parser->data);
  785. tc->messageSize += (unsigned long)length;
  786. if (tc->messageSize > ZT_MAX_HTTP_MESSAGE_SIZE)
  787. return -1;
  788. tc->currentHeaderValue.append(ptr,length);
  789. return 0;
  790. }
  791. static int ShttpOnHeadersComplete(http_parser *parser)
  792. {
  793. TcpConnection *tc = reinterpret_cast<TcpConnection *>(parser->data);
  794. if ((tc->currentHeaderField.length())&&(tc->currentHeaderValue.length()))
  795. tc->headers[tc->currentHeaderField] = tc->currentHeaderValue;
  796. return 0;
  797. }
  798. static int ShttpOnBody(http_parser *parser,const char *ptr,size_t length)
  799. {
  800. TcpConnection *tc = reinterpret_cast<TcpConnection *>(parser->data);
  801. tc->messageSize += (unsigned long)length;
  802. if (tc->messageSize > ZT_MAX_HTTP_MESSAGE_SIZE)
  803. return -1;
  804. tc->body.append(ptr,length);
  805. return 0;
  806. }
  807. static int ShttpOnMessageComplete(http_parser *parser)
  808. {
  809. TcpConnection *tc = reinterpret_cast<TcpConnection *>(parser->data);
  810. tc->shouldKeepAlive = (http_should_keep_alive(parser) != 0);
  811. tc->lastActivity = OSUtils::now();
  812. if (tc->type == TcpConnection::TCP_HTTP_INCOMING) {
  813. tc->parent->onHttpRequestToServer(tc);
  814. } else {
  815. tc->parent->onHttpResponseFromClient(tc);
  816. }
  817. return 0;
  818. }
  819. } // anonymous namespace
  820. std::string OneService::platformDefaultHomePath()
  821. {
  822. #ifdef __UNIX_LIKE__
  823. #ifdef __APPLE__
  824. // /Library/... on Apple
  825. return std::string("/Library/Application Support/ZeroTier/One");
  826. #else
  827. #ifdef __BSD__
  828. // BSD likes /var/db instead of /var/lib
  829. return std::string("/var/db/zerotier-one");
  830. #else
  831. // Use /var/lib for Linux and other *nix
  832. return std::string("/var/lib/zerotier-one");
  833. #endif
  834. #endif
  835. #else // not __UNIX_LIKE__
  836. #ifdef __WINDOWS__
  837. // Look up app data folder on Windows, e.g. C:\ProgramData\...
  838. char buf[16384];
  839. if (SUCCEEDED(SHGetFolderPathA(NULL,CSIDL_COMMON_APPDATA,NULL,0,buf)))
  840. return (std::string(buf) + "\\ZeroTier\\One");
  841. else return std::string("C:\\ZeroTier\\One");
  842. #else
  843. return std::string(); // UNKNOWN PLATFORM
  844. #endif
  845. #endif // __UNIX_LIKE__ or not...
  846. }
  847. std::string OneService::autoUpdateUrl()
  848. {
  849. #ifdef ZT_AUTO_UPDATE
  850. /*
  851. #if defined(__LINUX__) && ( defined(__i386__) || defined(__x86_64) || defined(__x86_64__) || defined(__amd64) || defined(__i386) )
  852. if (sizeof(void *) == 8)
  853. return "http://download.zerotier.com/ZeroTierOneInstaller-linux-x64-LATEST.nfo";
  854. else return "http://download.zerotier.com/ZeroTierOneInstaller-linux-x86-LATEST.nfo";
  855. #endif
  856. */
  857. #if defined(__APPLE__) && ( defined(__i386__) || defined(__x86_64) || defined(__x86_64__) || defined(__amd64) || defined(__i386) )
  858. return "http://download.zerotier.com/update/mac_intel/LATEST.nfo";
  859. #endif
  860. #ifdef __WINDOWS__
  861. return "http://download.zerotier.com/update/win_intel/LATEST.nfo";
  862. #endif
  863. #endif // ZT_AUTO_UPDATE
  864. return std::string();
  865. }
  866. OneService *OneService::newInstance(const char *hp,unsigned int port,const char *overrideRootTopology) { return new OneServiceImpl(hp,port,overrideRootTopology); }
  867. OneService::~OneService() {}
  868. } // namespace ZeroTier