OneService.cpp 27 KB

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