netconf.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477
  1. /*
  2. * ZeroTier One - Global Peer to Peer Ethernet
  3. * Copyright (C) 2012-2013 ZeroTier Networks LLC
  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. /*
  28. * This is the netconf service. It's currently used only by netconf nodes that
  29. * are run by ZeroTier itself. There is nothing to prevent you from running
  30. * your own if you wanted to create your own networks outside our system.
  31. *
  32. * That being said, we'd like to charge for private networks to support
  33. * ZeroTier One and future development efforts. So while this software is
  34. * open source and we're not going to stop you from sidestepping this, we
  35. * do ask -- honor system here -- that you pay for private networks if you
  36. * are going to use them for any commercial purpose such as a business VPN
  37. * alternative.
  38. *
  39. * This will at the moment only build on Linux and requires the mysql++
  40. * library, which is available here:
  41. *
  42. * http://tangentsoft.net/mysql++/
  43. *
  44. * (Packages are available for CentOS via EPEL and for any Debian distro.)
  45. *
  46. * This program must be built and installed in the services.d subfolder of
  47. * the ZeroTier One home folder of the node designated to act as a master
  48. * for networks. Doing so will enable the NETWORK_CONFIG_REQUEST protocol
  49. * verb.
  50. */
  51. #include <stdio.h>
  52. #include <stdlib.h>
  53. #include <string.h>
  54. #include <stdint.h>
  55. #include <unistd.h>
  56. #include <errno.h>
  57. #include <sys/stat.h>
  58. #include <sys/types.h>
  59. #include <arpa/inet.h>
  60. #include <iostream>
  61. #include <string>
  62. #include <map>
  63. #include <list>
  64. #include <vector>
  65. #include <algorithm>
  66. #include <mysql++/mysql++.h>
  67. #include "../node/Dictionary.hpp"
  68. #include "../node/Identity.hpp"
  69. #include "../node/Utils.hpp"
  70. #include "../node/Mutex.hpp"
  71. #include "../node/NetworkConfig.hpp"
  72. using namespace ZeroTier;
  73. using namespace mysqlpp;
  74. static Mutex stdoutWriteLock;
  75. static Connection *dbCon = (Connection *)0;
  76. static char mysqlHost[64],mysqlPort[64],mysqlDatabase[64],mysqlUser[64],mysqlPassword[64];
  77. int main(int argc,char **argv)
  78. {
  79. {
  80. char *ee = getenv("ZT_NETCONF_MYSQL_HOST");
  81. if (!ee) {
  82. fprintf(stderr,"missing environment variable: ZT_NETCONF_MYSQL_HOST\n");
  83. return -1;
  84. }
  85. strcpy(mysqlHost,ee);
  86. ee = getenv("ZT_NETCONF_MYSQL_PORT");
  87. if (!ee)
  88. strcpy(mysqlPort,"3306");
  89. else strcpy(mysqlPort,ee);
  90. ee = getenv("ZT_NETCONF_MYSQL_DATABASE");
  91. if (!ee) {
  92. fprintf(stderr,"missing environment variable: ZT_NETCONF_MYSQL_DATABASE\n");
  93. return -1;
  94. }
  95. strcpy(mysqlDatabase,ee);
  96. ee = getenv("ZT_NETCONF_MYSQL_USER");
  97. if (!ee) {
  98. fprintf(stderr,"missing environment variable: ZT_NETCONF_MYSQL_USER\n");
  99. return -1;
  100. }
  101. strcpy(mysqlUser,ee);
  102. ee = getenv("ZT_NETCONF_MYSQL_PASSWORD");
  103. if (!ee) {
  104. fprintf(stderr,"missing environment variable: ZT_NETCONF_MYSQL_PASSWORD\n");
  105. return -1;
  106. }
  107. strcpy(mysqlPassword,ee);
  108. }
  109. char buf[131072],buf2[131072];
  110. std::string dictBuf;
  111. try {
  112. dbCon = new Connection(mysqlDatabase,mysqlHost,mysqlUser,mysqlPassword,(unsigned int)strtol(mysqlPort,(char **)0,10));
  113. if (dbCon->connected()) {
  114. fprintf(stderr,"connected to mysql server successfully\n");
  115. } else {
  116. fprintf(stderr,"unable to connect to database server\n");
  117. return -1;
  118. }
  119. } catch (std::exception &exc) {
  120. fprintf(stderr,"unable to connect to database server: %s\n",exc.what());
  121. return -1;
  122. }
  123. for(;;) {
  124. for(int l=0;l<4;) {
  125. int n = (int)read(STDIN_FILENO,buf + l,4 - l);
  126. if (n < 0) {
  127. fprintf(stderr,"error reading frame size from stdin: %s\n",strerror(errno));
  128. return -1;
  129. }
  130. l += n;
  131. }
  132. unsigned int fsize = (unsigned int)ntohl(*((const uint32_t *)buf));
  133. while (dictBuf.length() < fsize) {
  134. int n = (int)read(STDIN_FILENO,buf,std::min((int)sizeof(buf),(int)(fsize - dictBuf.length())));
  135. if (n < 0) {
  136. fprintf(stderr,"error reading frame from stdin: %s\n",strerror(errno));
  137. return -1;
  138. }
  139. for(int i=0;i<n;++i)
  140. dictBuf.push_back(buf[i]);
  141. }
  142. Dictionary request(dictBuf);
  143. dictBuf = "";
  144. if (!dbCon->connected()) {
  145. fprintf(stderr,"connection to database server lost\n");
  146. return -1;
  147. }
  148. // Check QNetworkConfigRefresh (MEMORY table) and push network
  149. // config refreshes to queued peer/network pairs.
  150. try {
  151. Dictionary to;
  152. {
  153. Query q = dbCon->query();
  154. q << "SELECT DISTINCT LOWER(HEX(Node_id)) AS Node_id,LOWER(HEX(Network_id)) AS Network_id FROM QNetworkConfigRefresh";
  155. StoreQueryResult rs = q.store();
  156. for(unsigned long i=0;i<rs.num_rows();++i) {
  157. std::string &nwids = to[rs[i]["Node_id"].c_str()];
  158. if (nwids.length())
  159. nwids.push_back(',');
  160. nwids.append(rs[i]["Network_id"]);
  161. }
  162. }
  163. {
  164. Query q = dbCon->query();
  165. q << "DELETE FROM QNetworkConfigRefresh";
  166. q.exec();
  167. }
  168. Dictionary response;
  169. response["type"] = "netconf-push";
  170. response["to"] = to.toString();
  171. std::string respm = response.toString();
  172. uint32_t respml = (uint32_t)htonl((uint32_t)respm.length());
  173. stdoutWriteLock.lock();
  174. write(STDOUT_FILENO,&respml,4);
  175. write(STDOUT_FILENO,respm.data(),respm.length());
  176. stdoutWriteLock.unlock();
  177. } catch ( ... ) {}
  178. try {
  179. const std::string &reqType = request.get("type");
  180. if (reqType == "netconf-request") { // NETWORK_CONFIG_REQUEST packet
  181. // Deserialize querying peer identity and network ID
  182. Identity peerIdentity(request.get("peerId"));
  183. uint64_t nwid = strtoull(request.get("nwid").c_str(),(char **)0,16);
  184. std::string fromAddr(request.get("from",""));
  185. // Meta-information from node, such as (future) geo-location stuff
  186. Dictionary meta;
  187. if (request.contains("meta"))
  188. meta.fromString(request.get("meta"));
  189. // Check validity of node's identity, ignore request on failure
  190. if (!peerIdentity.locallyValidate()) {
  191. fprintf(stderr,"identity failed validity check: %s\n",peerIdentity.toString(false).c_str());
  192. continue;
  193. }
  194. // Save node's identity if unknown
  195. {
  196. Query q = dbCon->query();
  197. q << "SELECT identity FROM Node WHERE id = " << peerIdentity.address().toInt();
  198. StoreQueryResult rs = q.store();
  199. if (rs.num_rows() > 0) {
  200. if (rs[0]["identity"] != peerIdentity.toString(false)) {
  201. // TODO: handle collisions...
  202. continue;
  203. }
  204. } else {
  205. q = dbCon->query();
  206. q << "INSERT INTO Node (id,creationTime,lastSeen,identity) VALUES (" << peerIdentity.address().toInt() << "," << Utils::now() << ",0," << quote << peerIdentity.toString(false) << ")";
  207. if (!q.exec()) {
  208. fprintf(stderr,"error inserting Node row for peer %s, aborting netconf request\n",peerIdentity.address().toString().c_str());
  209. continue;
  210. }
  211. // TODO: launch background validation
  212. }
  213. }
  214. // Update lastSeen for Node, which is always updated on a netconf request
  215. {
  216. Query q = dbCon->query();
  217. q << "UPDATE Node SET lastSeen = " << Utils::now() << " WHERE id = " << peerIdentity.address().toInt();
  218. q.exec();
  219. }
  220. // Look up core network information
  221. bool isOpen = false;
  222. unsigned int multicastPrefixBits = 0;
  223. unsigned int multicastDepth = 0;
  224. bool emulateArp = false;
  225. bool emulateNdp = false;
  226. unsigned int arpCacheTtl = 0;
  227. unsigned int ndpCacheTtl = 0;
  228. std::string name;
  229. std::string desc;
  230. {
  231. Query q = dbCon->query();
  232. q << "SELECT name,`desc`,isOpen,multicastPrefixBits,multicastDepth,emulateArp,emulateNdp,arpCacheTtl,ndpCacheTtl FROM Network WHERE id = " << nwid;
  233. StoreQueryResult rs = q.store();
  234. if (rs.num_rows() > 0) {
  235. name = rs[0]["name"].c_str();
  236. desc = rs[0]["desc"].c_str();
  237. isOpen = ((int)rs[0]["isOpen"] > 0);
  238. emulateArp = ((int)rs[0]["emulateArp"] > 0);
  239. emulateNdp = ((int)rs[0]["emulateNdp"] > 0);
  240. arpCacheTtl = (unsigned int)rs[0]["arpCacheTtl"];
  241. ndpCacheTtl = (unsigned int)rs[0]["ndpCacheTtl"];
  242. multicastPrefixBits = (unsigned int)rs[0]["multicastPrefixBits"];
  243. multicastDepth = (unsigned int)rs[0]["multicastDepth"];
  244. } else {
  245. Dictionary response;
  246. response["peer"] = peerIdentity.address().toString();
  247. response["nwid"] = request.get("nwid");
  248. response["type"] = "netconf-response";
  249. response["requestId"] = request.get("requestId");
  250. response["error"] = "OBJ_NOT_FOUND";
  251. std::string respm = response.toString();
  252. uint32_t respml = (uint32_t)htonl((uint32_t)respm.length());
  253. stdoutWriteLock.lock();
  254. write(STDOUT_FILENO,&respml,4);
  255. write(STDOUT_FILENO,respm.data(),respm.length());
  256. stdoutWriteLock.unlock();
  257. continue; // ABORT, wait for next request
  258. }
  259. }
  260. // Check membership if this is a closed network
  261. if (!isOpen) {
  262. Query q = dbCon->query();
  263. q << "SELECT Node_id FROM NetworkNodes WHERE Network_id = " << nwid << " AND Node_id = " << peerIdentity.address().toInt();
  264. StoreQueryResult rs = q.store();
  265. if (!rs.num_rows()) {
  266. Dictionary response;
  267. response["peer"] = peerIdentity.address().toString();
  268. response["nwid"] = request.get("nwid");
  269. response["type"] = "netconf-response";
  270. response["requestId"] = request.get("requestId");
  271. response["error"] = "ACCESS_DENIED";
  272. std::string respm = response.toString();
  273. uint32_t respml = (uint32_t)htonl((uint32_t)respm.length());
  274. stdoutWriteLock.lock();
  275. write(STDOUT_FILENO,&respml,4);
  276. write(STDOUT_FILENO,respm.data(),respm.length());
  277. stdoutWriteLock.unlock();
  278. continue; // ABORT, wait for next request
  279. }
  280. }
  281. // Get list of etherTypes in comma-delimited hex format
  282. std::string etherTypeWhitelist;
  283. {
  284. Query q = dbCon->query();
  285. q << "SELECT DISTINCT LOWER(HEX(etherType)) AS etherType FROM NetworkEthertypes WHERE Network_id = " << nwid;
  286. StoreQueryResult rs = q.store();
  287. for(unsigned long i=0;i<rs.num_rows();++i) {
  288. if (etherTypeWhitelist.length() > 0)
  289. etherTypeWhitelist.push_back(',');
  290. etherTypeWhitelist.append(rs[i]["etherType"].c_str());
  291. }
  292. }
  293. // Get multicast group rates in dictionary format
  294. Dictionary multicastRates;
  295. {
  296. Query q = dbCon->query();
  297. q << "SELECT DISTINCT multicastGroupMac,multicastGroupAdi,preload,maxBalance,accrual FROM NetworkMulticastRates WHERE Network_id = " << nwid;
  298. StoreQueryResult rs = q.store();
  299. for(unsigned long i=0;i<rs.num_rows();++i) {
  300. unsigned long preload = (unsigned long)rs[i]["preload"];
  301. unsigned long maxBalance = (unsigned long)rs[i]["maxBalance"];
  302. unsigned long accrual = (unsigned long)rs[i]["accrual"];
  303. unsigned long long mac = (unsigned long long)rs[i]["multicastGroupMac"];
  304. sprintf(buf,"%.12llx/%lx",(mac & 0xffffffffffffULL),(unsigned long)rs[i]["multicastGroupAdi"]);
  305. sprintf(buf2,"%lx,%lx,%lx",preload,maxBalance,accrual);
  306. multicastRates[buf] = buf2;
  307. }
  308. }
  309. // Check for (or assign?) static IP address assignments
  310. std::string ipv4Static;
  311. std::string ipv6Static;
  312. {
  313. Query q = dbCon->query();
  314. q << "SELECT INET_NTOA(ip) AS ip,netmaskBits FROM IPv4Static WHERE Node_id = " << peerIdentity.address().toInt() << " AND Network_id = " << nwid;
  315. StoreQueryResult rs = q.store();
  316. if (rs.num_rows() > 0) {
  317. for(int i=0;i<rs.num_rows();++i) {
  318. if (ipv4Static.length())
  319. ipv4Static.push_back(',');
  320. ipv4Static.append(rs[i]["ip"].c_str());
  321. ipv4Static.push_back('/');
  322. ipv4Static.append(rs[i]["netmaskBits"].c_str());
  323. }
  324. }
  325. // Try to auto-assign if there's any auto-assign networks with space
  326. // available.
  327. if (!ipv4Static.length()) {
  328. unsigned char addressBytes[5];
  329. peerIdentity.address().copyTo(addressBytes,5);
  330. q = dbCon->query();
  331. q << "SELECT ipNet,netmaskBits FROM IPv4AutoAssign WHERE Network_id = " << nwid;
  332. rs = q.store();
  333. if (rs.num_rows() > 0) {
  334. for(int aaRow=0;aaRow<rs.num_rows();++aaRow) {
  335. uint32_t ipNet = (uint32_t)((unsigned long)rs[aaRow]["ipNet"]);
  336. unsigned int netmaskBits = (unsigned int)rs[aaRow]["netmaskBits"];
  337. uint32_t tryIp = (((uint32_t)addressBytes[1]) << 24) |
  338. (((uint32_t)addressBytes[2]) << 16) |
  339. (((uint32_t)addressBytes[3]) << 8) |
  340. ((((uint32_t)addressBytes[4]) % 254) + 1);
  341. tryIp &= (0xffffffff >> netmaskBits);
  342. tryIp |= ipNet;
  343. for(int k=0;k<100000;++k) {
  344. Query q2 = dbCon->query();
  345. q2 << "INSERT INTO IPv4Static (Network_id,Node_id,ip,netmaskBits) VALUES (" << nwid << "," << peerIdentity.address().toInt() << "," << tryIp << "," << netmaskBits << ")";
  346. if (q2.exec()) {
  347. sprintf(buf,"%u.%u.%u.%u",(unsigned int)((tryIp >> 24) & 0xff),(unsigned int)((tryIp >> 16) & 0xff),(unsigned int)((tryIp >> 8) & 0xff),(unsigned int)(tryIp & 0xff));
  348. if (ipv4Static.length())
  349. ipv4Static.push_back(',');
  350. ipv4Static.append(buf);
  351. ipv4Static.push_back('/');
  352. sprintf(buf,"%u",netmaskBits);
  353. ipv4Static.append(buf);
  354. break;
  355. } else { // insert will fail if IP is in use due to uniqueness constraints in DB
  356. ++tryIp;
  357. if ((tryIp & 0xff) == 0)
  358. tryIp |= 1;
  359. tryIp &= (0xffffffff >> netmaskBits);
  360. tryIp |= ipNet;
  361. }
  362. }
  363. if (ipv4Static.length())
  364. break;
  365. }
  366. }
  367. }
  368. }
  369. // Update activity table for this network to indicate peer's participation
  370. {
  371. if (fromAddr.length()) {
  372. Query q = dbCon->query();
  373. q << "INSERT INTO NetworkActivity (Network_id,Node_id,lastActivityTime,lastActivityFrom) VALUES (" << nwid << "," << peerIdentity.address().toInt() << "," << Utils::now() << "," << quote << fromAddr << ") ON DUPLICATE KEY UPDATE lastActivityTime = VALUES(lastActivityTime),lastActivityFrom = VALUES(lastActivityFrom)";
  374. q.exec();
  375. } else {
  376. Query q = dbCon->query();
  377. q << "INSERT INTO NetworkActivity (Network_id,Node_id,lastActivityTime) VALUES (" << nwid << "," << peerIdentity.address().toInt() << "," << Utils::now() << ") ON DUPLICATE KEY UPDATE lastActivityTime = VALUES(lastActivityTime)";
  378. q.exec();
  379. }
  380. }
  381. // Assemble response dictionary to send to peer
  382. Dictionary netconf;
  383. sprintf(buf,"%.16llx",(unsigned long long)nwid);
  384. netconf[ZT_NETWORKCONFIG_DICT_KEY_NETWORK_ID] = buf;
  385. netconf[ZT_NETWORKCONFIG_DICT_KEY_ISSUED_TO] = peerIdentity.address().toString();
  386. netconf[ZT_NETWORKCONFIG_DICT_KEY_NAME] = name;
  387. netconf[ZT_NETWORKCONFIG_DICT_KEY_DESC] = desc;
  388. netconf[ZT_NETWORKCONFIG_DICT_KEY_IS_OPEN] = (isOpen ? "1" : "0");
  389. netconf[ZT_NETWORKCONFIG_DICT_KEY_ALLOWED_ETHERNET_TYPES] = etherTypeWhitelist;
  390. netconf[ZT_NETWORKCONFIG_DICT_KEY_MULTICAST_RATES] = multicastRates.toString();
  391. sprintf(buf,"%llx",(unsigned long long)Utils::now());
  392. netconf[ZT_NETWORKCONFIG_DICT_KEY_TIMESTAMP] = buf;
  393. netconf[ZT_NETWORKCONFIG_DICT_KEY_EMULATE_ARP] = (emulateArp ? "1" : "0");
  394. netconf[ZT_NETWORKCONFIG_DICT_KEY_EMULATE_NDP] = (emulateNdp ? "1" : "0");
  395. if (arpCacheTtl) {
  396. sprintf(buf,"%x",arpCacheTtl);
  397. netconf[ZT_NETWORKCONFIG_DICT_KEY_ARP_CACHE_TTL] = buf;
  398. }
  399. if (ndpCachettl) {
  400. sprintf(buf,"%x",ndpCacheTtl);
  401. netconf[ZT_NETWORKCONFIG_DICT_KEY_NDP_CACHE_TTL] = buf;
  402. }
  403. if (multicastPrefixBits) {
  404. sprintf(buf,"%x",multicastPrefixBits);
  405. netconf[ZT_NETWORKCONFIG_DICT_KEY_MULTICAST_PREFIX_BITS] = buf;
  406. }
  407. if (multicastDepth) {
  408. sprintf(buf,"%x",multicastDepth);
  409. netconf[ZT_NETWORKCONFIG_DICT_KEY_MULTICAST_DEPTH] = buf;
  410. }
  411. if (ipv4Static.length())
  412. netconf[ZT_NETWORKCONFIG_DICT_KEY_IPV4_STATIC] = ipv4Static;
  413. if (ipv6Static.length())
  414. netconf[ZT_NETWORKCONFIG_DICT_KEY_IPV6_STATIC] = ipv6Static;
  415. // Send netconf as service bus response
  416. {
  417. Dictionary response;
  418. response["peer"] = peerIdentity.address().toString();
  419. response["nwid"] = request.get("nwid");
  420. response["type"] = "netconf-response";
  421. response["requestId"] = request.get("requestId");
  422. response["netconf"] = netconf.toString();
  423. std::string respm = response.toString();
  424. uint32_t respml = (uint32_t)htonl((uint32_t)respm.length());
  425. stdoutWriteLock.lock();
  426. write(STDOUT_FILENO,&respml,4);
  427. write(STDOUT_FILENO,respm.data(),respm.length());
  428. stdoutWriteLock.unlock();
  429. // LOOP, wait for next request
  430. }
  431. }
  432. } catch (std::exception &exc) {
  433. fprintf(stderr,"unexpected exception handling message: %s\n",exc.what());
  434. } catch ( ... ) {
  435. fprintf(stderr,"unexpected exception handling message: unknown exception\n");
  436. }
  437. }
  438. }