OneService.cpp 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922
  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);
  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;
  390. if (mlen == 4) {
  391. // Hello message, which isn't sent by proxy and would be ignored by client
  392. } else if (mlen) {
  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. }
  401. break;
  402. case 6: // IPv6
  403. if (plen >= 19) {
  404. from.set((const void *)(data + 1),16,((((unsigned int)data[17]) & 0xff) << 8) | (((unsigned int)data[18]) & 0xff));
  405. data += 19; // type + 16 byte IP + 2 byte port
  406. plen -= 19;
  407. }
  408. break;
  409. case 0: // none/omitted
  410. break;
  411. default: // invalid
  412. _phy.close(sock);
  413. return;
  414. }
  415. if (!from) { // missing IP header
  416. _phy.close(sock);
  417. return;
  418. }
  419. }
  420. ZT1_ResultCode rc = _node->processWirePacket(
  421. OSUtils::now(),
  422. (const struct sockaddr_storage *)&from, // Phy<> uses sockaddr_storage, so it'll always be that big
  423. 1, // desperation == 1, TCP tunnel proxy
  424. data,
  425. plen,
  426. &_nextBackgroundTaskDeadline);
  427. if (ZT1_ResultCode_isFatal(rc)) {
  428. char tmp[256];
  429. Utils::snprintf(tmp,sizeof(tmp),"fatal error code from processWirePacket: %d",(int)rc);
  430. Mutex::Lock _l(_termReason_m);
  431. _termReason = ONE_UNRECOVERABLE_ERROR;
  432. _fatalErrorMessage = tmp;
  433. this->terminate();
  434. _phy.close(sock);
  435. return;
  436. }
  437. if (tc->body.length() > (mlen + 5))
  438. tc->body = tc->body.substr(mlen + 5);
  439. else tc->body = "";
  440. }
  441. }
  442. break;
  443. }
  444. }
  445. inline void phyOnTcpWritable(PhySocket *sock,void **uptr)
  446. {
  447. TcpConnection *tc = reinterpret_cast<TcpConnection *>(*uptr);
  448. if (tc->writeBuf.length()) {
  449. long sent = _phy.tcpSend(sock,tc->writeBuf.data(),tc->writeBuf.length(),true);
  450. if (sent > 0) {
  451. tc->lastActivity = OSUtils::now();
  452. if (sent == tc->writeBuf.length()) {
  453. tc->writeBuf = "";
  454. _phy.tcpSetNotifyWritable(sock,false);
  455. if (!tc->shouldKeepAlive)
  456. _phy.close(sock); // will call close handler to delete from _tcpConections
  457. } else tc->writeBuf = tc->writeBuf.substr(sent);
  458. }
  459. } else _phy.tcpSetNotifyWritable(sock,false); // sanity check... shouldn't happen
  460. }
  461. inline int nodeVirtualNetworkConfigFunction(uint64_t nwid,enum ZT1_VirtualNetworkConfigOperation op,const ZT1_VirtualNetworkConfig *nwc)
  462. {
  463. Mutex::Lock _l(_taps_m);
  464. std::map< uint64_t,EthernetTap * >::iterator t(_taps.find(nwid));
  465. switch(op) {
  466. case ZT1_VIRTUAL_NETWORK_CONFIG_OPERATION_UP:
  467. if (t == _taps.end()) {
  468. try {
  469. char friendlyName[1024];
  470. Utils::snprintf(friendlyName,sizeof(friendlyName),"ZeroTier One [%.16llx]",nwid);
  471. t = _taps.insert(std::pair< uint64_t,EthernetTap *>(nwid,new EthernetTap(
  472. _homePath.c_str(),
  473. MAC(nwc->mac),
  474. nwc->mtu,
  475. (unsigned int)ZT_IF_METRIC,
  476. nwid,
  477. friendlyName,
  478. StapFrameHandler,
  479. (void *)this))).first;
  480. } catch ( ... ) {
  481. return -999; // tap init failed
  482. }
  483. }
  484. // fall through...
  485. case ZT1_VIRTUAL_NETWORK_CONFIG_OPERATION_CONFIG_UPDATE:
  486. if (t != _taps.end()) {
  487. t->second->setEnabled(nwc->enabled != 0);
  488. std::vector<InetAddress> &assignedIps = _tapAssignedIps[nwid];
  489. std::vector<InetAddress> newAssignedIps;
  490. for(unsigned int i=0;i<nwc->assignedAddressCount;++i)
  491. newAssignedIps.push_back(InetAddress(nwc->assignedAddresses[i]));
  492. std::sort(newAssignedIps.begin(),newAssignedIps.end());
  493. std::unique(newAssignedIps.begin(),newAssignedIps.end());
  494. for(std::vector<InetAddress>::iterator ip(newAssignedIps.begin());ip!=newAssignedIps.end();++ip) {
  495. if (!std::binary_search(assignedIps.begin(),assignedIps.end(),*ip))
  496. t->second->addIp(*ip);
  497. }
  498. for(std::vector<InetAddress>::iterator ip(assignedIps.begin());ip!=assignedIps.end();++ip) {
  499. if (!std::binary_search(newAssignedIps.begin(),newAssignedIps.end(),*ip))
  500. t->second->removeIp(*ip);
  501. }
  502. assignedIps.swap(newAssignedIps);
  503. } else {
  504. return -999; // tap init failed
  505. }
  506. break;
  507. case ZT1_VIRTUAL_NETWORK_CONFIG_OPERATION_DOWN:
  508. case ZT1_VIRTUAL_NETWORK_CONFIG_OPERATION_DESTROY:
  509. if (t != _taps.end()) {
  510. #ifdef __WINDOWS__
  511. std::string winInstanceId(t->second->instanceId());
  512. #endif
  513. delete t->second;
  514. _taps.erase(t);
  515. _tapAssignedIps.erase(nwid);
  516. #ifdef __WINDOWS__
  517. if ((op == ZT1_VIRTUAL_NETWORK_CONFIG_OPERATION_DESTROY)&&(winInstanceId.length() > 0))
  518. WindowsEthernetTap::deletePersistentTapDevice(_homePath.c_str(),winInstanceId.c_str());
  519. #endif
  520. }
  521. break;
  522. }
  523. return 0;
  524. }
  525. inline void nodeEventCallback(enum ZT1_Event event,const void *metaData)
  526. {
  527. switch(event) {
  528. case ZT1_EVENT_FATAL_ERROR_IDENTITY_COLLISION: {
  529. Mutex::Lock _l(_termReason_m);
  530. _termReason = ONE_IDENTITY_COLLISION;
  531. _fatalErrorMessage = "identity/address collision";
  532. this->terminate();
  533. } break;
  534. case ZT1_EVENT_SAW_MORE_RECENT_VERSION: {
  535. } break;
  536. case ZT1_EVENT_TRACE: {
  537. if (metaData) {
  538. ::fprintf(stderr,"%s"ZT_EOL_S,(const char *)metaData);
  539. ::fflush(stderr);
  540. }
  541. } break;
  542. default:
  543. break;
  544. }
  545. }
  546. inline long nodeDataStoreGetFunction(const char *name,void *buf,unsigned long bufSize,unsigned long readIndex,unsigned long *totalSize)
  547. {
  548. std::string p(_dataStorePrepPath(name));
  549. if (!p.length())
  550. return -2;
  551. FILE *f = fopen(p.c_str(),"rb");
  552. if (!f)
  553. return -1;
  554. if (fseek(f,0,SEEK_END) != 0) {
  555. fclose(f);
  556. return -2;
  557. }
  558. long ts = ftell(f);
  559. if (ts < 0) {
  560. fclose(f);
  561. return -2;
  562. }
  563. *totalSize = (unsigned long)ts;
  564. if (fseek(f,(long)readIndex,SEEK_SET) != 0) {
  565. fclose(f);
  566. return -2;
  567. }
  568. long n = (long)fread(buf,1,bufSize,f);
  569. fclose(f);
  570. return n;
  571. }
  572. inline int nodeDataStorePutFunction(const char *name,const void *data,unsigned long len,int secure)
  573. {
  574. std::string p(_dataStorePrepPath(name));
  575. if (!p.length())
  576. return -2;
  577. if (!data) {
  578. OSUtils::rm(p.c_str());
  579. return 0;
  580. }
  581. FILE *f = fopen(p.c_str(),"wb");
  582. if (!f)
  583. return -1;
  584. if (fwrite(data,len,1,f) == 1) {
  585. fclose(f);
  586. if (secure)
  587. OSUtils::lockDownFile(p.c_str(),false);
  588. return 0;
  589. } else {
  590. fclose(f);
  591. OSUtils::rm(p.c_str());
  592. return -1;
  593. }
  594. }
  595. inline int nodeWirePacketSendFunction(const struct sockaddr_storage *addr,unsigned int desperation,const void *data,unsigned int len)
  596. {
  597. switch(addr->ss_family) {
  598. case AF_INET:
  599. if (_v4UdpSocket)
  600. return (_phy.udpSend(_v4UdpSocket,(const struct sockaddr *)addr,data,len) ? 0 : -1);
  601. break;
  602. case AF_INET6:
  603. if (_v6UdpSocket)
  604. return (_phy.udpSend(_v6UdpSocket,(const struct sockaddr *)addr,data,len) ? 0 : -1);
  605. break;
  606. }
  607. return -1;
  608. }
  609. inline void nodeVirtualNetworkFrameFunction(uint64_t nwid,uint64_t sourceMac,uint64_t destMac,unsigned int etherType,unsigned int vlanId,const void *data,unsigned int len)
  610. {
  611. Mutex::Lock _l(_taps_m);
  612. std::map< uint64_t,EthernetTap * >::const_iterator t(_taps.find(nwid));
  613. if (t != _taps.end())
  614. t->second->put(MAC(sourceMac),MAC(destMac),etherType,data,len);
  615. }
  616. inline void tapFrameHandler(uint64_t nwid,const MAC &from,const MAC &to,unsigned int etherType,unsigned int vlanId,const void *data,unsigned int len)
  617. {
  618. _node->processVirtualNetworkFrame(OSUtils::now(),nwid,from.toInt(),to.toInt(),etherType,vlanId,data,len,&_nextBackgroundTaskDeadline);
  619. }
  620. inline void onHttpRequestToServer(TcpConnection *tc)
  621. {
  622. char tmpn[256];
  623. std::string data;
  624. std::string contentType("text/plain"); // default if not changed in handleRequest()
  625. unsigned int scode = 404;
  626. try {
  627. if (_controlPlane)
  628. scode = _controlPlane->handleRequest(tc->from,tc->parser.method,tc->url,tc->headers,tc->body,data,contentType);
  629. else scode = 500;
  630. } catch ( ... ) {
  631. scode = 500;
  632. }
  633. const char *scodestr;
  634. switch(scode) {
  635. case 200: scodestr = "OK"; break;
  636. case 400: scodestr = "Bad Request"; break;
  637. case 401: scodestr = "Unauthorized"; break;
  638. case 403: scodestr = "Forbidden"; break;
  639. case 404: scodestr = "Not Found"; break;
  640. case 500: scodestr = "Internal Server Error"; break;
  641. case 501: scodestr = "Not Implemented"; break;
  642. case 503: scodestr = "Service Unavailable"; break;
  643. default: scodestr = "Error"; break;
  644. }
  645. Utils::snprintf(tmpn,sizeof(tmpn),"HTTP/1.1 %.3u %s\r\nCache-Control: no-cache\r\nPragma: no-cache\r\n",scode,scodestr);
  646. tc->writeBuf.assign(tmpn);
  647. tc->writeBuf.append("Content-Type: ");
  648. tc->writeBuf.append(contentType);
  649. Utils::snprintf(tmpn,sizeof(tmpn),"\r\nContent-Length: %lu\r\n",(unsigned long)data.length());
  650. tc->writeBuf.append(tmpn);
  651. if (!tc->shouldKeepAlive)
  652. tc->writeBuf.append("Connection: close\r\n");
  653. tc->writeBuf.append("\r\n");
  654. if (tc->parser.method != HTTP_HEAD)
  655. tc->writeBuf.append(data);
  656. _phy.tcpSetNotifyWritable(tc->sock,true);
  657. }
  658. inline void onHttpResponseFromClient(TcpConnection *tc)
  659. {
  660. if (!tc->shouldKeepAlive)
  661. _phy.close(tc->sock); // will call close handler, which deletes from _tcpConections
  662. }
  663. private:
  664. std::string _dataStorePrepPath(const char *name) const
  665. {
  666. std::string p(_homePath);
  667. p.push_back(ZT_PATH_SEPARATOR);
  668. char lastc = (char)0;
  669. for(const char *n=name;(*n);++n) {
  670. if ((*n == '.')&&(lastc == '.'))
  671. return std::string(); // don't allow ../../ stuff as a precaution
  672. if (*n == '/') {
  673. OSUtils::mkdir(p.c_str());
  674. p.push_back(ZT_PATH_SEPARATOR);
  675. } else p.push_back(*n);
  676. lastc = *n;
  677. }
  678. return p;
  679. }
  680. const std::string _homePath;
  681. Phy<OneServiceImpl *> _phy;
  682. NetworkController *_master;
  683. std::string _overrideRootTopology;
  684. Node *_node;
  685. PhySocket *_v4UdpSocket;
  686. PhySocket *_v6UdpSocket;
  687. PhySocket *_v4TcpListenSocket;
  688. PhySocket *_v6TcpListenSocket;
  689. ControlPlane *_controlPlane;
  690. volatile uint64_t _nextBackgroundTaskDeadline;
  691. std::map< uint64_t,EthernetTap * > _taps;
  692. std::map< uint64_t,std::vector<InetAddress> > _tapAssignedIps; // ZeroTier assigned IPs, not user or dhcp assigned
  693. Mutex _taps_m;
  694. std::map< PhySocket *,TcpConnection > _tcpConections; // no mutex for this since it's done in the main loop thread only
  695. ReasonForTermination _termReason;
  696. std::string _fatalErrorMessage;
  697. Mutex _termReason_m;
  698. bool _run;
  699. Mutex _run_m;
  700. };
  701. static int SnodeVirtualNetworkConfigFunction(ZT1_Node *node,void *uptr,uint64_t nwid,enum ZT1_VirtualNetworkConfigOperation op,const ZT1_VirtualNetworkConfig *nwconf)
  702. { return reinterpret_cast<OneServiceImpl *>(uptr)->nodeVirtualNetworkConfigFunction(nwid,op,nwconf); }
  703. static void SnodeEventCallback(ZT1_Node *node,void *uptr,enum ZT1_Event event,const void *metaData)
  704. { reinterpret_cast<OneServiceImpl *>(uptr)->nodeEventCallback(event,metaData); }
  705. static long SnodeDataStoreGetFunction(ZT1_Node *node,void *uptr,const char *name,void *buf,unsigned long bufSize,unsigned long readIndex,unsigned long *totalSize)
  706. { return reinterpret_cast<OneServiceImpl *>(uptr)->nodeDataStoreGetFunction(name,buf,bufSize,readIndex,totalSize); }
  707. static int SnodeDataStorePutFunction(ZT1_Node *node,void *uptr,const char *name,const void *data,unsigned long len,int secure)
  708. { return reinterpret_cast<OneServiceImpl *>(uptr)->nodeDataStorePutFunction(name,data,len,secure); }
  709. static int SnodeWirePacketSendFunction(ZT1_Node *node,void *uptr,const struct sockaddr_storage *addr,unsigned int desperation,const void *data,unsigned int len)
  710. { return reinterpret_cast<OneServiceImpl *>(uptr)->nodeWirePacketSendFunction(addr,desperation,data,len); }
  711. 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)
  712. { reinterpret_cast<OneServiceImpl *>(uptr)->nodeVirtualNetworkFrameFunction(nwid,sourceMac,destMac,etherType,vlanId,data,len); }
  713. 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)
  714. { reinterpret_cast<OneServiceImpl *>(uptr)->tapFrameHandler(nwid,from,to,etherType,vlanId,data,len); }
  715. static int ShttpOnMessageBegin(http_parser *parser)
  716. {
  717. TcpConnection *tc = reinterpret_cast<TcpConnection *>(parser->data);
  718. tc->currentHeaderField = "";
  719. tc->currentHeaderValue = "";
  720. tc->messageSize = 0;
  721. tc->url = "";
  722. tc->status = "";
  723. tc->headers.clear();
  724. tc->body = "";
  725. return 0;
  726. }
  727. static int ShttpOnUrl(http_parser *parser,const char *ptr,size_t length)
  728. {
  729. TcpConnection *tc = reinterpret_cast<TcpConnection *>(parser->data);
  730. tc->messageSize += (unsigned long)length;
  731. if (tc->messageSize > ZT_MAX_HTTP_MESSAGE_SIZE)
  732. return -1;
  733. tc->url.append(ptr,length);
  734. return 0;
  735. }
  736. static int ShttpOnStatus(http_parser *parser,const char *ptr,size_t length)
  737. {
  738. TcpConnection *tc = reinterpret_cast<TcpConnection *>(parser->data);
  739. tc->messageSize += (unsigned long)length;
  740. if (tc->messageSize > ZT_MAX_HTTP_MESSAGE_SIZE)
  741. return -1;
  742. tc->status.append(ptr,length);
  743. return 0;
  744. }
  745. static int ShttpOnHeaderField(http_parser *parser,const char *ptr,size_t length)
  746. {
  747. TcpConnection *tc = reinterpret_cast<TcpConnection *>(parser->data);
  748. tc->messageSize += (unsigned long)length;
  749. if (tc->messageSize > ZT_MAX_HTTP_MESSAGE_SIZE)
  750. return -1;
  751. if ((tc->currentHeaderField.length())&&(tc->currentHeaderValue.length())) {
  752. tc->headers[tc->currentHeaderField] = tc->currentHeaderValue;
  753. tc->currentHeaderField = "";
  754. tc->currentHeaderValue = "";
  755. }
  756. for(size_t i=0;i<length;++i)
  757. tc->currentHeaderField.push_back(OSUtils::toLower(ptr[i]));
  758. return 0;
  759. }
  760. static int ShttpOnValue(http_parser *parser,const char *ptr,size_t length)
  761. {
  762. TcpConnection *tc = reinterpret_cast<TcpConnection *>(parser->data);
  763. tc->messageSize += (unsigned long)length;
  764. if (tc->messageSize > ZT_MAX_HTTP_MESSAGE_SIZE)
  765. return -1;
  766. tc->currentHeaderValue.append(ptr,length);
  767. return 0;
  768. }
  769. static int ShttpOnHeadersComplete(http_parser *parser)
  770. {
  771. TcpConnection *tc = reinterpret_cast<TcpConnection *>(parser->data);
  772. if ((tc->currentHeaderField.length())&&(tc->currentHeaderValue.length()))
  773. tc->headers[tc->currentHeaderField] = tc->currentHeaderValue;
  774. return 0;
  775. }
  776. static int ShttpOnBody(http_parser *parser,const char *ptr,size_t length)
  777. {
  778. TcpConnection *tc = reinterpret_cast<TcpConnection *>(parser->data);
  779. tc->messageSize += (unsigned long)length;
  780. if (tc->messageSize > ZT_MAX_HTTP_MESSAGE_SIZE)
  781. return -1;
  782. tc->body.append(ptr,length);
  783. return 0;
  784. }
  785. static int ShttpOnMessageComplete(http_parser *parser)
  786. {
  787. TcpConnection *tc = reinterpret_cast<TcpConnection *>(parser->data);
  788. tc->shouldKeepAlive = (http_should_keep_alive(parser) != 0);
  789. tc->lastActivity = OSUtils::now();
  790. if (tc->type == TcpConnection::TCP_HTTP_INCOMING) {
  791. tc->parent->onHttpRequestToServer(tc);
  792. } else {
  793. tc->parent->onHttpResponseFromClient(tc);
  794. }
  795. return 0;
  796. }
  797. std::string OneService::platformDefaultHomePath()
  798. {
  799. #ifdef __UNIX_LIKE__
  800. #ifdef __APPLE__
  801. // /Library/... on Apple
  802. return std::string("/Library/Application Support/ZeroTier/One");
  803. #else
  804. #ifdef __FreeBSD__
  805. // FreeBSD likes /var/db instead of /var/lib
  806. return std::string("/var/db/zerotier-one");
  807. #else
  808. // Use /var/lib for Linux and other *nix
  809. return std::string("/var/lib/zerotier-one");
  810. #endif
  811. #endif
  812. #else // not __UNIX_LIKE__
  813. #ifdef __WINDOWS__
  814. // Look up app data folder on Windows, e.g. C:\ProgramData\...
  815. char buf[16384];
  816. if (SUCCEEDED(SHGetFolderPathA(NULL,CSIDL_COMMON_APPDATA,NULL,0,buf)))
  817. return (std::string(buf) + "\\ZeroTier\\One");
  818. else return std::string("C:\\ZeroTier\\One");
  819. #else
  820. return std::string(); // UNKNOWN PLATFORM
  821. #endif
  822. #endif // __UNIX_LIKE__ or not...
  823. }
  824. OneService *OneService::newInstance(const char *hp,unsigned int port,NetworkController *master,const char *overrideRootTopology) { return new OneServiceImpl(hp,port,master,overrideRootTopology); }
  825. OneService::~OneService() {}
  826. } // namespace ZeroTier