OneService.cpp 26 KB

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