One.cpp 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652
  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 <vector>
  33. #include <algorithm>
  34. #include "../version.h"
  35. #include "../include/ZeroTierOne.h"
  36. #include "../ext/http-parser/http_parser.h"
  37. #include "../node/Constants.hpp"
  38. #include "../node/Mutex.hpp"
  39. #include "../node/Node.hpp"
  40. #include "../node/Utils.hpp"
  41. #include "../node/InetAddress.hpp"
  42. #include "../osdep/Phy.hpp"
  43. #include "../osdep/OSUtils.hpp"
  44. #include "One.hpp"
  45. // Sanity limits for HTTP
  46. #define ZT_MAX_HTTP_MESSAGE_SIZE (1024 * 1024 * 8)
  47. #define ZT_MAX_HTTP_CONNECTIONS 64
  48. namespace ZeroTier {
  49. // Used to convert HTTP header names to ASCII lower case
  50. 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 };
  51. class OneImpl;
  52. static int SnodeVirtualNetworkConfigFunction(ZT1_Node *node,void *uptr,uint64_t nwid,enum ZT1_VirtualNetworkConfigOperation op,const ZT1_VirtualNetworkConfig *nwconf);
  53. static void SnodeEventCallback(ZT1_Node *node,void *uptr,enum ZT1_Event event,const void *metaData);
  54. static long SnodeDataStoreGetFunction(ZT1_Node *node,void *uptr,const char *name,void *buf,unsigned long bufSize,unsigned long readIndex,unsigned long *totalSize);
  55. static int SnodeDataStorePutFunction(ZT1_Node *node,void *uptr,const char *name,const void *data,unsigned long len,int secure);
  56. static int SnodeWirePacketSendFunction(ZT1_Node *node,void *uptr,const struct sockaddr_storage *addr,unsigned int desperation,const void *data,unsigned int len);
  57. 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);
  58. static int ShttpOnMessageBegin(http_parser *parser);
  59. static int ShttpOnUrl(http_parser *parser,const char *ptr,size_t length);
  60. static int ShttpOnStatus(http_parser *parser,const char *ptr,size_t length);
  61. static int ShttpOnHeaderField(http_parser *parser,const char *ptr,size_t length);
  62. static int ShttpOnValue(http_parser *parser,const char *ptr,size_t length);
  63. static int ShttpOnHeadersComplete(http_parser *parser);
  64. static int ShttpOnBody(http_parser *parser,const char *ptr,size_t length);
  65. static int ShttpOnMessageComplete(http_parser *parser);
  66. const struct http_parser_settings HTTP_PARSER_SETTINGS = {
  67. ShttpOnMessageBegin,
  68. ShttpOnUrl,
  69. ShttpOnStatus,
  70. ShttpOnHeaderField,
  71. ShttpOnValue,
  72. ShttpOnHeadersComplete,
  73. ShttpOnBody,
  74. ShttpOnMessageComplete
  75. };
  76. struct HttpConnection
  77. {
  78. bool server;
  79. bool writing;
  80. bool shouldKeepAlive;
  81. OneImpl *parent;
  82. PhySocket *sock;
  83. http_parser parser;
  84. unsigned long messageSize;
  85. unsigned long writePtr;
  86. uint64_t lastActivity;
  87. std::string currentHeaderField;
  88. std::string currentHeaderValue;
  89. std::string url;
  90. std::string status;
  91. std::map< std::string,std::string > headers;
  92. std::string body; // also doubles as send queue for writes out to the socket
  93. };
  94. class OneImpl : public One
  95. {
  96. public:
  97. OneImpl(const char *hp,unsigned int port,NetworkConfigMaster *master,const char *overrideRootTopology) :
  98. _homePath((hp) ? hp : "."),
  99. _phy(this,true),
  100. _master(master),
  101. _overrideRootTopology((overrideRootTopology) ? overrideRootTopology : ""),
  102. _node((Node *)0),
  103. _nextBackgroundTaskDeadline(0),
  104. _termReason(ONE_STILL_RUNNING),
  105. _run(true)
  106. {
  107. struct sockaddr_in in4;
  108. struct sockaddr_in6 in6;
  109. if (*hp) {
  110. std::vector<std::string> hpsp(Utils::split(hp,ZT_PATH_SEPARATOR_S,"",""));
  111. std::string ptmp;
  112. if (*hp == '/')
  113. ptmp.push_back('/');
  114. for(std::vector<std::string>::iterator pi(hpsp.begin());pi!=hpsp.end();++pi) {
  115. if (ptmp.length() > 0)
  116. ptmp.push_back(ZT_PATH_SEPARATOR);
  117. ptmp.append(*pi);
  118. if ((*pi != ".")&&(*pi != "..")) {
  119. if (!OSUtils::mkdir(ptmp))
  120. throw std::runtime_error("home path does not exist, and could not create");
  121. }
  122. }
  123. }
  124. ::memset((void *)&in4,0,sizeof(in4));
  125. in4.sin_family = AF_INET;
  126. in4.sin_port = Utils::hton((uint16_t)port);
  127. _v4UdpSocket = _phy.udpBind((const struct sockaddr *)&in4,this,131072);
  128. if (!_v4UdpSocket)
  129. throw std::runtime_error("cannot bind to port (UDP/IPv4)");
  130. _v4TcpListenSocket = _phy.tcpListen((const struct sockaddr *)&in4,this);
  131. if (!_v4TcpListenSocket) {
  132. _phy.close(_v4UdpSocket);
  133. throw std::runtime_error("cannot bind to port (TCP/IPv4)");
  134. }
  135. ::memset((void *)&in6,0,sizeof(in6));
  136. in6.sin6_family = AF_INET6;
  137. in6.sin6_port = in4.sin_port;
  138. _v6UdpSocket = _phy.udpBind((const struct sockaddr *)&in6,this,131072);
  139. _v6TcpListenSocket = _phy.tcpListen((const struct sockaddr *)&in6,this);
  140. }
  141. virtual ~OneImpl()
  142. {
  143. _phy.close(_v4UdpSocket);
  144. _phy.close(_v6UdpSocket);
  145. _phy.close(_v4TcpListenSocket);
  146. _phy.close(_v6TcpListenSocket);
  147. }
  148. virtual ReasonForTermination run()
  149. {
  150. try {
  151. _node = new Node(
  152. OSUtils::now(),
  153. this,
  154. SnodeDataStoreGetFunction,
  155. SnodeDataStorePutFunction,
  156. SnodeWirePacketSendFunction,
  157. SnodeVirtualNetworkFrameFunction,
  158. SnodeVirtualNetworkConfigFunction,
  159. SnodeEventCallback,
  160. ((_overrideRootTopology.length() > 0) ? _overrideRootTopology.c_str() : (const char *)0));
  161. if (_master)
  162. _node->setNetconfMaster((void *)_master);
  163. _nextBackgroundTaskDeadline = 0;
  164. for(;;) {
  165. _run_m.lock();
  166. if (!_run) {
  167. _run_m.unlock();
  168. _termReason_m.lock();
  169. _termReason = ONE_NORMAL_TERMINATION;
  170. _termReason_m.unlock();
  171. break;
  172. } else _run_m.unlock();
  173. uint64_t dl = _nextBackgroundTaskDeadline;
  174. uint64_t now = OSUtils::now();
  175. if (dl <= now) {
  176. _node->processBackgroundTasks(now,&_nextBackgroundTaskDeadline);
  177. dl = _nextBackgroundTaskDeadline;
  178. now = OSUtils::now();
  179. }
  180. const unsigned long delay = (dl > now) ? (unsigned long)(dl - now) : 100;
  181. //printf("polling: %lums timeout\n",delay);
  182. _phy.poll(delay);
  183. }
  184. } catch (std::exception &exc) {
  185. Mutex::Lock _l(_termReason_m);
  186. _termReason = ONE_UNRECOVERABLE_ERROR;
  187. _fatalErrorMessage = exc.what();
  188. } catch ( ... ) {
  189. Mutex::Lock _l(_termReason_m);
  190. _termReason = ONE_UNRECOVERABLE_ERROR;
  191. _fatalErrorMessage = "unexpected exception in main thread";
  192. }
  193. delete _node;
  194. _node = (Node *)0;
  195. return _termReason;
  196. }
  197. virtual ReasonForTermination reasonForTermination() const
  198. {
  199. Mutex::Lock _l(_termReason_m);
  200. return _termReason;
  201. }
  202. virtual std::string fatalErrorMessage() const
  203. {
  204. Mutex::Lock _l(_termReason_m);
  205. return _fatalErrorMessage;
  206. }
  207. virtual void terminate()
  208. {
  209. _run_m.lock();
  210. _run = false;
  211. _run_m.unlock();
  212. _phy.whack();
  213. }
  214. // Begin private implementation methods
  215. inline void phyOnDatagram(PhySocket *sock,void **uptr,const struct sockaddr *from,void *data,unsigned long len)
  216. {
  217. ZT1_ResultCode rc = _node->processWirePacket(
  218. OSUtils::now(),
  219. (const struct sockaddr_storage *)from, // Phy<> uses sockaddr_storage, so it'll always be that big
  220. 0,
  221. data,
  222. len,
  223. &_nextBackgroundTaskDeadline);
  224. if (ZT1_ResultCode_isFatal(rc)) {
  225. char tmp[256];
  226. Utils::snprintf(tmp,sizeof(tmp),"fatal error code from processWirePacket(%d)",(int)rc);
  227. Mutex::Lock _l(_termReason_m);
  228. _termReason = ONE_UNRECOVERABLE_ERROR;
  229. _fatalErrorMessage = tmp;
  230. this->terminate();
  231. }
  232. }
  233. inline void phyOnTcpConnect(PhySocket *sock,void **uptr,bool success)
  234. {
  235. // TODO: outgoing HTTP connection success/failure
  236. }
  237. inline void phyOnTcpAccept(PhySocket *sockL,PhySocket *sockN,void **uptrL,void **uptrN,const struct sockaddr *from)
  238. {
  239. HttpConnection *htc = &(_httpConnections[sockN]);
  240. htc->server = true;
  241. htc->writing = false;
  242. htc->shouldKeepAlive = true;
  243. htc->parent = this;
  244. htc->sock = sockN;
  245. http_parser_init(&(htc->parser),HTTP_REQUEST);
  246. htc->parser.data = (void *)htc;
  247. htc->messageSize = 0;
  248. htc->writePtr = 0;
  249. htc->lastActivity = OSUtils::now();
  250. htc->currentHeaderField = "";
  251. htc->currentHeaderValue = "";
  252. htc->url = "";
  253. htc->status = "";
  254. htc->headers.clear();
  255. htc->body = "";
  256. *uptrN = (void *)htc;
  257. }
  258. inline void phyOnTcpClose(PhySocket *sock,void **uptr)
  259. {
  260. _httpConnections.erase(sock);
  261. }
  262. inline void phyOnTcpData(PhySocket *sock,void **uptr,void *data,unsigned long len)
  263. {
  264. HttpConnection *htc = reinterpret_cast<HttpConnection *>(*uptr);
  265. http_parser_execute(&(htc->parser),&HTTP_PARSER_SETTINGS,(const char *)data,len);
  266. if ((htc->parser.upgrade)||(htc->parser.http_errno != HPE_OK))
  267. _phy.close(sock);
  268. }
  269. inline void phyOnTcpWritable(PhySocket *sock,void **uptr)
  270. {
  271. HttpConnection *htc = reinterpret_cast<HttpConnection *>(*uptr);
  272. long sent = _phy.tcpSend(sock,htc->body.data() + htc->writePtr,htc->body.length() - htc->writePtr,true);
  273. if (sent < 0) {
  274. return; // close handler will have been called, so everything's dead
  275. } else {
  276. htc->lastActivity = OSUtils::now();
  277. htc->writePtr += sent;
  278. if (htc->writePtr >= htc->body.length()) {
  279. _phy.tcpSetNotifyWritable(sock,false);
  280. if (htc->shouldKeepAlive) {
  281. htc->writing = false;
  282. htc->writePtr = 0;
  283. htc->body.assign("",0);
  284. } else {
  285. _phy.close(sock); // will call close handler to delete from _httpConnections
  286. }
  287. }
  288. }
  289. }
  290. inline int nodeVirtualNetworkConfigFunction(uint64_t nwid,enum ZT1_VirtualNetworkConfigOperation op,const ZT1_VirtualNetworkConfig *nwconf)
  291. {
  292. return 0;
  293. }
  294. inline void nodeEventCallback(enum ZT1_Event event,const void *metaData)
  295. {
  296. switch(event) {
  297. case ZT1_EVENT_FATAL_ERROR_IDENTITY_COLLISION: {
  298. Mutex::Lock _l(_termReason_m);
  299. _termReason = ONE_IDENTITY_COLLISION;
  300. _fatalErrorMessage = "identity/address collision";
  301. this->terminate();
  302. } break;
  303. case ZT1_EVENT_SAW_MORE_RECENT_VERSION: {
  304. } break;
  305. case ZT1_EVENT_TRACE: {
  306. if (metaData) {
  307. ::fprintf(stderr,"%s"ZT_EOL_S,(const char *)metaData);
  308. ::fflush(stderr);
  309. }
  310. } break;
  311. default:
  312. break;
  313. }
  314. }
  315. inline long nodeDataStoreGetFunction(const char *name,void *buf,unsigned long bufSize,unsigned long readIndex,unsigned long *totalSize)
  316. {
  317. std::string p(_dataStorePrepPath(name));
  318. if (!p.length())
  319. return -2;
  320. FILE *f = fopen(p.c_str(),"rb");
  321. if (!f)
  322. return -1;
  323. if (fseek(f,0,SEEK_END) != 0) {
  324. fclose(f);
  325. return -2;
  326. }
  327. long ts = ftell(f);
  328. if (ts < 0) {
  329. fclose(f);
  330. return -2;
  331. }
  332. *totalSize = (unsigned long)ts;
  333. if (fseek(f,(long)readIndex,SEEK_SET) != 0) {
  334. fclose(f);
  335. return -2;
  336. }
  337. long n = (long)fread(buf,1,bufSize,f);
  338. fclose(f);
  339. return n;
  340. }
  341. inline int nodeDataStorePutFunction(const char *name,const void *data,unsigned long len,int secure)
  342. {
  343. std::string p(_dataStorePrepPath(name));
  344. if (!p.length())
  345. return -2;
  346. if (!data) {
  347. OSUtils::rm(p.c_str());
  348. return 0;
  349. }
  350. FILE *f = fopen(p.c_str(),"wb");
  351. if (!f)
  352. return -1;
  353. if (fwrite(data,len,1,f) == 1) {
  354. fclose(f);
  355. if (secure)
  356. OSUtils::lockDownFile(p.c_str(),false);
  357. return 0;
  358. } else {
  359. fclose(f);
  360. OSUtils::rm(p.c_str());
  361. return -1;
  362. }
  363. }
  364. inline int nodeWirePacketSendFunction(const struct sockaddr_storage *addr,unsigned int desperation,const void *data,unsigned int len)
  365. {
  366. switch(addr->ss_family) {
  367. case AF_INET:
  368. if (_v4UdpSocket)
  369. return (_phy.udpSend(_v4UdpSocket,(const struct sockaddr *)addr,data,len) ? 0 : -1);
  370. break;
  371. case AF_INET6:
  372. if (_v6UdpSocket)
  373. return (_phy.udpSend(_v6UdpSocket,(const struct sockaddr *)addr,data,len) ? 0 : -1);
  374. break;
  375. }
  376. return -1;
  377. }
  378. inline void nodeVirtualNetworkFrameFunction(uint64_t nwid,uint64_t sourceMac,uint64_t destMac,unsigned int etherType,unsigned int vlanId,const void *data,unsigned int len)
  379. {
  380. fprintf(stderr,"VIRTUAL NETWORK FRAME from %.16llx : %.12llx -> %.12llx %.4x %u bytes\n",nwid,sourceMac,destMac,etherType,len);
  381. fflush(stderr);
  382. }
  383. inline void onHttpRequestToServer(HttpConnection *htc)
  384. {
  385. char tmpn[256];
  386. /*
  387. printf("HTTP request:\n");
  388. printf(" url: %s\n",htc->url.c_str());
  389. printf(" status: %s\n",htc->status.c_str());
  390. printf(" headers:\n");
  391. for(std::map<std::string,std::string>::iterator h(htc->headers.begin());h!=htc->headers.end();++h)
  392. printf(" %s: %s\n",h->first.c_str(),h->second.c_str());
  393. printf(" body:\n----\n%s\n----\n",htc->body.c_str());
  394. */
  395. std::string data = "123456";
  396. std::string contentType = "text/plain";
  397. //unsigned int scode = _nodeHttpControlPlane.handleRequest(htc->parser.method,htc->url,htc->headers,htc->body,data,contentType);
  398. unsigned int scode = 200;
  399. Utils::snprintf(tmpn,sizeof(tmpn),"HTTP/1.1 %.3u %s\r\nServer: ZeroTier One\r\nCache-Control: no-cache\r\nPragma: no-cache\r\n",scode,((scode == 200) ? "OK" : ((scode == 404) ? "Not Found" : "Error")));
  400. htc->body.assign(tmpn);
  401. htc->body.append("Content-Type: ");
  402. htc->body.append(contentType);
  403. Utils::snprintf(tmpn,sizeof(tmpn),"\r\nContent-Length: %lu\r\n",(unsigned long)data.length());
  404. htc->body.append(tmpn);
  405. if (!htc->shouldKeepAlive)
  406. htc->body.append("Connection: close\r\n");
  407. htc->body.append("\r\n");
  408. if (htc->parser.method != HTTP_HEAD)
  409. htc->body.append(data);
  410. htc->writing = true;
  411. htc->writePtr = 0;
  412. _phy.tcpSetNotifyWritable(htc->sock,true);
  413. }
  414. inline void onHttpResponseFromClient(HttpConnection *htc)
  415. {
  416. if (!htc->shouldKeepAlive)
  417. _phy.close(htc->sock); // will call close handler, which deletes from _httpConnections
  418. }
  419. private:
  420. std::string _dataStorePrepPath(const char *name) const
  421. {
  422. std::string p(_homePath);
  423. p.push_back(ZT_PATH_SEPARATOR);
  424. char lastc = (char)0;
  425. for(const char *n=name;(*n);++n) {
  426. if ((*n == '.')&&(lastc == '.'))
  427. return std::string(); // don't allow ../../ stuff as a precaution
  428. if (*n == '/') {
  429. OSUtils::mkdir(p.c_str());
  430. p.push_back(ZT_PATH_SEPARATOR);
  431. } else p.push_back(*n);
  432. lastc = *n;
  433. }
  434. return p;
  435. }
  436. const std::string _homePath;
  437. Phy<OneImpl *> _phy;
  438. NetworkConfigMaster *_master;
  439. std::string _overrideRootTopology;
  440. Node *_node;
  441. PhySocket *_v4UdpSocket;
  442. PhySocket *_v6UdpSocket;
  443. PhySocket *_v4TcpListenSocket;
  444. PhySocket *_v6TcpListenSocket;
  445. uint64_t _nextBackgroundTaskDeadline;
  446. std::map< PhySocket *,HttpConnection > _httpConnections; // no mutex for this since it's done in the main loop thread only
  447. ReasonForTermination _termReason;
  448. std::string _fatalErrorMessage;
  449. Mutex _termReason_m;
  450. bool _run;
  451. Mutex _run_m;
  452. };
  453. static int SnodeVirtualNetworkConfigFunction(ZT1_Node *node,void *uptr,uint64_t nwid,enum ZT1_VirtualNetworkConfigOperation op,const ZT1_VirtualNetworkConfig *nwconf)
  454. { return reinterpret_cast<OneImpl *>(uptr)->nodeVirtualNetworkConfigFunction(nwid,op,nwconf); }
  455. static void SnodeEventCallback(ZT1_Node *node,void *uptr,enum ZT1_Event event,const void *metaData)
  456. { reinterpret_cast<OneImpl *>(uptr)->nodeEventCallback(event,metaData); }
  457. static long SnodeDataStoreGetFunction(ZT1_Node *node,void *uptr,const char *name,void *buf,unsigned long bufSize,unsigned long readIndex,unsigned long *totalSize)
  458. { return reinterpret_cast<OneImpl *>(uptr)->nodeDataStoreGetFunction(name,buf,bufSize,readIndex,totalSize); }
  459. static int SnodeDataStorePutFunction(ZT1_Node *node,void *uptr,const char *name,const void *data,unsigned long len,int secure)
  460. { return reinterpret_cast<OneImpl *>(uptr)->nodeDataStorePutFunction(name,data,len,secure); }
  461. static int SnodeWirePacketSendFunction(ZT1_Node *node,void *uptr,const struct sockaddr_storage *addr,unsigned int desperation,const void *data,unsigned int len)
  462. { return reinterpret_cast<OneImpl *>(uptr)->nodeWirePacketSendFunction(addr,desperation,data,len); }
  463. 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)
  464. { reinterpret_cast<OneImpl *>(uptr)->nodeVirtualNetworkFrameFunction(nwid,sourceMac,destMac,etherType,vlanId,data,len); }
  465. static int ShttpOnMessageBegin(http_parser *parser)
  466. {
  467. HttpConnection *htc = reinterpret_cast<HttpConnection *>(parser->data);
  468. htc->currentHeaderField.assign("",0);
  469. htc->currentHeaderValue.assign("",0);
  470. htc->messageSize = 0;
  471. htc->url.assign("",0);
  472. htc->status.assign("",0);
  473. htc->headers.clear();
  474. htc->body.assign("",0);
  475. return 0;
  476. }
  477. static int ShttpOnUrl(http_parser *parser,const char *ptr,size_t length)
  478. {
  479. HttpConnection *htc = reinterpret_cast<HttpConnection *>(parser->data);
  480. htc->messageSize += length;
  481. if (htc->messageSize > ZT_MAX_HTTP_MESSAGE_SIZE)
  482. return -1;
  483. htc->url.append(ptr,length);
  484. return 0;
  485. }
  486. static int ShttpOnStatus(http_parser *parser,const char *ptr,size_t length)
  487. {
  488. HttpConnection *htc = reinterpret_cast<HttpConnection *>(parser->data);
  489. htc->messageSize += length;
  490. if (htc->messageSize > ZT_MAX_HTTP_MESSAGE_SIZE)
  491. return -1;
  492. htc->status.append(ptr,length);
  493. return 0;
  494. }
  495. static int ShttpOnHeaderField(http_parser *parser,const char *ptr,size_t length)
  496. {
  497. HttpConnection *htc = reinterpret_cast<HttpConnection *>(parser->data);
  498. htc->messageSize += length;
  499. if (htc->messageSize > ZT_MAX_HTTP_MESSAGE_SIZE)
  500. return -1;
  501. if ((htc->currentHeaderField.length())&&(htc->currentHeaderValue.length())) {
  502. htc->headers[htc->currentHeaderField] = htc->currentHeaderValue;
  503. htc->currentHeaderField.assign("",0);
  504. htc->currentHeaderValue.assign("",0);
  505. }
  506. for(size_t i=0;i<length;++i)
  507. htc->currentHeaderField.push_back((char)ZT_TOLOWER_TABLE[(unsigned int)ptr[i]]);
  508. return 0;
  509. }
  510. static int ShttpOnValue(http_parser *parser,const char *ptr,size_t length)
  511. {
  512. HttpConnection *htc = reinterpret_cast<HttpConnection *>(parser->data);
  513. htc->messageSize += length;
  514. if (htc->messageSize > ZT_MAX_HTTP_MESSAGE_SIZE)
  515. return -1;
  516. htc->currentHeaderValue.append(ptr,length);
  517. return 0;
  518. }
  519. static int ShttpOnHeadersComplete(http_parser *parser)
  520. {
  521. HttpConnection *htc = reinterpret_cast<HttpConnection *>(parser->data);
  522. if ((htc->currentHeaderField.length())&&(htc->currentHeaderValue.length()))
  523. htc->headers[htc->currentHeaderField] = htc->currentHeaderValue;
  524. return 0;
  525. }
  526. static int ShttpOnBody(http_parser *parser,const char *ptr,size_t length)
  527. {
  528. HttpConnection *htc = reinterpret_cast<HttpConnection *>(parser->data);
  529. htc->messageSize += length;
  530. if (htc->messageSize > ZT_MAX_HTTP_MESSAGE_SIZE)
  531. return -1;
  532. htc->body.append(ptr,length);
  533. return 0;
  534. }
  535. static int ShttpOnMessageComplete(http_parser *parser)
  536. {
  537. HttpConnection *htc = reinterpret_cast<HttpConnection *>(parser->data);
  538. htc->shouldKeepAlive = (http_should_keep_alive(parser) != 0);
  539. htc->lastActivity = OSUtils::now();
  540. if (htc->server) {
  541. htc->parent->onHttpRequestToServer(htc);
  542. } else {
  543. htc->parent->onHttpResponseFromClient(htc);
  544. }
  545. return 0;
  546. }
  547. std::string One::platformDefaultHomePath()
  548. {
  549. #ifdef __UNIX_LIKE__
  550. #ifdef __APPLE__
  551. // /Library/... on Apple
  552. return std::string("/Library/Application Support/ZeroTier/One");
  553. #else
  554. #ifdef __FreeBSD__
  555. // FreeBSD likes /var/db instead of /var/lib
  556. return std::string("/var/db/zerotier-one");
  557. #else
  558. // Use /var/lib for Linux and other *nix
  559. return std::string("/var/lib/zerotier-one");
  560. #endif
  561. #endif
  562. #else // not __UNIX_LIKE__
  563. #ifdef __WINDOWS__
  564. // Look up app data folder on Windows, e.g. C:\ProgramData\...
  565. char buf[16384];
  566. if (SUCCEEDED(SHGetFolderPathA(NULL,CSIDL_COMMON_APPDATA,NULL,0,buf)))
  567. return (std::string(buf) + "\\ZeroTier\\One");
  568. else return std::string("C:\\ZeroTier\\One");
  569. #else
  570. return std::string(); // UNKNOWN PLATFORM
  571. #endif
  572. #endif // __UNIX_LIKE__ or not...
  573. }
  574. One *One::newInstance(const char *hp,unsigned int port,NetworkConfigMaster *master,const char *overrideRootTopology) { return new OneImpl(hp,port,master,overrideRootTopology); }
  575. One::~One() {}
  576. } // namespace ZeroTier