OneService.cpp 30 KB

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