OneService.cpp 30 KB

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