netconf.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344
  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. using namespace ZeroTier;
  72. using namespace mysqlpp;
  73. static Mutex stdoutWriteLock;
  74. static Connection *dbCon = (Connection *)0;
  75. static char mysqlHost[64],mysqlPort[64],mysqlDatabase[64],mysqlUser[64],mysqlPassword[64];
  76. int main(int argc,char **argv)
  77. {
  78. {
  79. char *ee = getenv("ZT_NETCONF_MYSQL_HOST");
  80. if (!ee) {
  81. fprintf(stderr,"missing environment variable: ZT_NETCONF_MYSQL_HOST\n");
  82. return -1;
  83. }
  84. strcpy(mysqlHost,ee);
  85. ee = getenv("ZT_NETCONF_MYSQL_PORT");
  86. if (!ee)
  87. strcpy(mysqlPort,"3306");
  88. else strcpy(mysqlPort,ee);
  89. ee = getenv("ZT_NETCONF_MYSQL_DATABASE");
  90. if (!ee) {
  91. fprintf(stderr,"missing environment variable: ZT_NETCONF_MYSQL_DATABASE\n");
  92. return -1;
  93. }
  94. strcpy(mysqlDatabase,ee);
  95. ee = getenv("ZT_NETCONF_MYSQL_USER");
  96. if (!ee) {
  97. fprintf(stderr,"missing environment variable: ZT_NETCONF_MYSQL_USER\n");
  98. return -1;
  99. }
  100. strcpy(mysqlUser,ee);
  101. ee = getenv("ZT_NETCONF_MYSQL_PASSWORD");
  102. if (!ee) {
  103. fprintf(stderr,"missing environment variable: ZT_NETCONF_MYSQL_PASSWORD\n");
  104. return -1;
  105. }
  106. strcpy(mysqlPassword,ee);
  107. }
  108. char buf[131072];
  109. std::string dictBuf;
  110. try {
  111. dbCon = new Connection(mysqlDatabase,mysqlHost,mysqlUser,mysqlPassword,(unsigned int)strtol(mysqlPort,(char **)0,10));
  112. if (dbCon->connected()) {
  113. fprintf(stderr,"connected to mysql server successfully\n");
  114. break;
  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. try {
  149. const std::string &reqType = request.get("type");
  150. if (reqType == "netconf-request") { // NETWORK_CONFIG_REQUEST packet
  151. Identity peerIdentity(request.get("peerId"));
  152. uint64_t nwid = strtoull(request.get("nwid").c_str(),(char **)0,16);
  153. Dictionary meta;
  154. if (request.contains("meta"))
  155. meta.fromString(request.get("meta"));
  156. // Do quick signature check / sanity check
  157. if (!peerIdentity.locallyValidate(false)) {
  158. fprintf(stderr,"identity failed signature check: %s\n",peerIdentity.toString(false).c_str());
  159. continue;
  160. }
  161. // Save identity if unknown
  162. {
  163. Query q = dbCon->query();
  164. q << "SELECT identity,identityValidated FROM Node WHERE id = " << peerIdentity.address().toInt();
  165. StoreQueryResult rs = q.store();
  166. if (rs.num_rows() > 0) {
  167. if (rs[0]["identity"] != peerIdentity.toString(false)) {
  168. // TODO: handle collisions...
  169. continue;
  170. } else if ((int)rs[0]["identityValidated"] == 0) {
  171. // TODO: launch background validation
  172. }
  173. } else {
  174. q = dbCon->query();
  175. q << "INSERT INTO Node (id,creationTime,lastSeen,identity) VALUES (" << peerIdentity.address().toInt() << "," << Utils::now() << ",0," << quote << peerIdentity.toString(false) << ")";
  176. if (!q.exec()) {
  177. fprintf(stderr,"error inserting Node row for peer %s, aborting netconf request\n",peerIdentity.address().toString().c_str());
  178. continue;
  179. }
  180. // TODO: launch background validation
  181. }
  182. }
  183. // Update lastSeen
  184. {
  185. Query q = dbCon->query();
  186. q << "UPDATE Node SET lastSeen = " << Utils::now() << " WHERE id = " << peerIdentity.address().toInt();
  187. q.exec();
  188. }
  189. bool isOpen = false;
  190. std::string name,desc;
  191. {
  192. Query q = dbCon->query();
  193. q << "SELECT name,desc,isOpen FROM Network WHERE id = " << nwid;
  194. StoreQueryResult rs = q.store();
  195. if (rs.num_rows() > 0) {
  196. name = rs[0]["name"].c_str();
  197. desc = rs[0]["desc"].c_str();
  198. isOpen = ((int)rs[0]["isOpen"] > 0);
  199. } else {
  200. Dictionary response;
  201. response["peer"] = peerIdentity.address().toString();
  202. response["nwid"] = request.get("nwid");
  203. response["type"] = "netconf-response";
  204. response["requestId"] = request.get("requestId");
  205. response["error"] = "OBJ_NOT_FOUND";
  206. std::string respm = response.toString();
  207. uint32_t respml = (uint32_t)htonl((uint32_t)respm.length());
  208. stdoutWriteLock.lock();
  209. write(STDOUT_FILENO,&respml,4);
  210. write(STDOUT_FILENO,respm.data(),respm.length());
  211. stdoutWriteLock.unlock();
  212. continue;
  213. }
  214. }
  215. Dictionary netconf;
  216. netconf["peer"] = peerIdentity.address().toString();
  217. sprintf(buf,"%.16llx",(unsigned long long)nwid);
  218. netconf["nwid"] = buf;
  219. netconf["isOpen"] = (isOpen ? "1" : "0");
  220. netconf["name"] = name;
  221. netconf["desc"] = desc;
  222. sprintf(buf,"%llx",(unsigned long long)Utils::now());
  223. netconf["ts"] = buf;
  224. if (!isOpen) {
  225. // TODO: handle closed networks, look up private membership,
  226. // generate signed cert.
  227. }
  228. std::string ipv4Static,ipv6Static;
  229. {
  230. // Check for IPv4 static assignments
  231. Query q = dbCon->query();
  232. q << "SELECT INET_NTOA(ip) AS ip,netmaskBits FROM IPv4Static WHERE Node_id = " << peerIdentity.address().toInt() << " AND Network_id = " << nwid;
  233. StoreQueryResult rs = q.store();
  234. if (rs.num_rows() > 0) {
  235. for(int i=0;i<rs.num_rows();++i) {
  236. if (ipv4Static.length())
  237. ipv4Static.push_back(',');
  238. ipv4Static.append(rs[i]["ip"].c_str());
  239. ipv4Static.push_back('/');
  240. ipv4Static.append(rs[i]["netmaskBits"].c_str());
  241. }
  242. }
  243. // Try to auto-assign if there's any auto-assign networks with space
  244. // available.
  245. if (!ipv4Static.length()) {
  246. unsigned char addressBytes[5];
  247. peerIdentity.address().copyTo(addressBytes,5);
  248. q = dbCon->query();
  249. q << "SELECT ipNet,netmaskBits FROM IPv4AutoAssign WHERE Network_id = " << nwid;
  250. rs = q.store();
  251. if (rs.num_rows() > 0) {
  252. for(int aaRow=0;aaRow<rs.num_rows();++aaRow) {
  253. uint32_t ipNet = (uint32_t)((unsigned long)rs[aaRow]["ipNet"]);
  254. unsigned int netmaskBits = (unsigned int)rs[aaRow]["netmaskBits"];
  255. uint32_t tryIp = (((uint32_t)addressBytes[1]) << 24) |
  256. (((uint32_t)addressBytes[2]) << 16) |
  257. (((uint32_t)addressBytes[3]) << 8) |
  258. ((((uint32_t)addressBytes[4]) % 254) + 1);
  259. tryIp &= (0xffffffff >> netmaskBits);
  260. tryIp |= ipNet;
  261. for(int k=0;k<100000;++k) {
  262. Query q2 = dbCon->query();
  263. q2 << "INSERT INTO IPv4Static (Network_id,Node_id,ip,netmaskBits) VALUES (" << nwid << "," << peerIdentity.address().toInt() << "," << tryIp << "," << netmaskBits << ")";
  264. if (q2.exec()) {
  265. 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));
  266. if (ipv4Static.length())
  267. ipv4Static.push_back(',');
  268. ipv4Static.append(buf);
  269. ipv4Static.push_back('/');
  270. sprintf(buf,"%u",netmaskBits);
  271. ipv4Static.append(buf);
  272. break;
  273. } else { // insert will fail if IP is in use due to uniqueness constraints in DB
  274. ++tryIp;
  275. if ((tryIp & 0xff) == 0)
  276. tryIp |= 1;
  277. tryIp &= (0xffffffff >> netmaskBits);
  278. tryIp |= ipNet;
  279. }
  280. }
  281. if (ipv4Static.length())
  282. break;
  283. }
  284. }
  285. }
  286. }
  287. if (ipv4Static.length())
  288. netconf["ipv4Static"] = ipv4Static;
  289. if (ipv6Static.length())
  290. netconf["ipv6Static"] = ipv6Static;
  291. {
  292. Dictionary response;
  293. response["peer"] = peerIdentity.address().toString();
  294. response["nwid"] = request.get("nwid");
  295. response["type"] = "netconf-response";
  296. response["requestId"] = request.get("requestId");
  297. response["netconf"] = netconf.toString();
  298. std::string respm = response.toString();
  299. uint32_t respml = (uint32_t)htonl((uint32_t)respm.length());
  300. stdoutWriteLock.lock();
  301. write(STDOUT_FILENO,&respml,4);
  302. write(STDOUT_FILENO,respm.data(),respm.length());
  303. stdoutWriteLock.unlock();
  304. }
  305. }
  306. } catch (std::exception &exc) {
  307. fprintf(stderr,"unexpected exception handling message: %s\n",exc.what());
  308. } catch ( ... ) {
  309. fprintf(stderr,"unexpected exception handling message: unknown exception\n");
  310. }
  311. }
  312. }