OneService.cpp 26 KB

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