OneService.cpp 31 KB

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