One.cpp 22 KB

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