OneService.cpp 27 KB

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