2
0

OneService.cpp 27 KB

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