OneService.cpp 27 KB

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