One.cpp 22 KB

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