OneService.cpp 26 KB

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