SqliteNetworkController.cpp 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481
  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 <stdint.h>
  28. #include <stdio.h>
  29. #include <stdlib.h>
  30. #include <string.h>
  31. #include <time.h>
  32. #include <sys/time.h>
  33. #include <sys/types.h>
  34. #include <algorithm>
  35. #include <utility>
  36. #include <stdexcept>
  37. #include "SqliteNetworkController.hpp"
  38. #include "../node/Utils.hpp"
  39. #include "../node/CertificateOfMembership.hpp"
  40. #include "../node/NetworkConfig.hpp"
  41. #include "../osdep/OSUtils.hpp"
  42. // Include ZT_NETCONF_SCHEMA_SQL constant to init database
  43. #include "schema.sql.c"
  44. // Stored in database as schemaVersion key in Config.
  45. // If not present, database is assumed to be empty and at the current schema version
  46. // and this key/value is added automatically.
  47. #define ZT_NETCONF_SQLITE_SCHEMA_VERSION 1
  48. #define ZT_NETCONF_SQLITE_SCHEMA_VERSION_STR "1"
  49. namespace ZeroTier {
  50. SqliteNetworkController::SqliteNetworkController(const char *dbPath) :
  51. _dbPath(dbPath),
  52. _db((sqlite3 *)0)
  53. {
  54. if (sqlite3_open_v2(dbPath,&_db,SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE,(const char *)0) != SQLITE_OK)
  55. throw std::runtime_error("SqliteNetworkController cannot open database file");
  56. sqlite3_busy_timeout(_db,10000);
  57. sqlite3_stmt *s = (sqlite3_stmt *)0;
  58. if ((sqlite3_prepare_v2(_db,"SELECT 'v' FROM Config WHERE 'k' = 'schemaVersion';",-1,&s,(const char **)0) == SQLITE_OK)&&(s)) {
  59. int schemaVersion = -1234;
  60. if (sqlite3_step(s) == SQLITE_ROW)
  61. schemaVersion = sqlite3_column_int(s,0);
  62. sqlite3_finalize(s);
  63. if (schemaVersion == -1234) {
  64. sqlite3_close(_db);
  65. throw std::runtime_error("SqliteNetworkController schemaVersion not found in Config table (init failure?)");
  66. } else if (schemaVersion != ZT_NETCONF_SQLITE_SCHEMA_VERSION) {
  67. // Note -- this will eventually run auto-upgrades so this isn't how it'll work going forward
  68. sqlite3_close(_db);
  69. throw std::runtime_error("SqliteNetworkController database schema version mismatch");
  70. }
  71. } else {
  72. // Prepare statement will fail if Config table doesn't exist, which means our DB
  73. // needs to be initialized.
  74. if (sqlite3_exec(_db,ZT_NETCONF_SCHEMA_SQL"INSERT INTO Config (k,v) VALUES ('schemaVersion',"ZT_NETCONF_SQLITE_SCHEMA_VERSION_STR");",0,0,0) != SQLITE_OK) {
  75. sqlite3_close(_db);
  76. throw std::runtime_error("SqliteNetworkController cannot initialize database and/or insert schemaVersion into Config table");
  77. }
  78. }
  79. if (
  80. (sqlite3_prepare_v2(_db,"SELECT 'name','private','enableBroadcast','allowPassiveBridging','v4AssignMode','v6AssignMode','multicastLimit','revision' FROM Network WHERE 'id' = ?",-1,&_sGetNetworkById,(const char **)0) != SQLITE_OK)
  81. ||(sqlite3_prepare_v2(_db,"SELECT rowid,'cachedNetconf','cachedNetconfRevision','clientReportedRevision','authorized','activeBridge' FROM Member WHERE 'networkId' = ? AND 'nodeId' = ?",-1,&_sGetMemberByNetworkAndNodeId,(const char **)0) != SQLITE_OK)
  82. ||(sqlite3_prepare_v2(_db,"INSERT INTO Member ('networkId','nodeId','cachedNetconfRevision','clientReportedRevision','authorized','activeBridge') VALUES (?,?,0,0,?,0)",-1,&_sCreateMember,(const char **)0) != SQLITE_OK)
  83. ||(sqlite3_prepare_v2(_db,"SELECT 'identity' FROM Node WHERE 'id' = ?",-1,&_sGetNodeIdentity,(const char **)0) != SQLITE_OK)
  84. ||(sqlite3_prepare_v2(_db,"INSERT INTO Node ('id','identity','lastAt','lastSeen','firstSeen') VALUES (?,?,?,?,?)",-1,&_sCreateNode,(const char **)0) != SQLITE_OK)
  85. ||(sqlite3_prepare_v2(_db,"UPDATE Node SET 'lastAt' = ?,'lastSeen' = ? WHERE 'id' = ?",-1,&_sUpdateNode,(const char **)0) != SQLITE_OK)
  86. ||(sqlite3_prepare_v2(_db,"UPDATE Node SET 'lastSeen' = ? WHERE 'id' = ?",-1,&_sUpdateNode2,(const char **)0) != SQLITE_OK)
  87. ||(sqlite3_prepare_v2(_db,"UPDATE Member SET 'clientReportedRevision' = ? WHERE rowid = ?",-1,&_sUpdateMemberClientReportedRevision,(const char **)0) != SQLITE_OK)
  88. ||(sqlite3_prepare_v2(_db,"SELECT 'etherType' FROM Rule WHERE 'networkId' = ? AND 'action' = 'accept'",-1,&_sGetEtherTypesFromRuleTable,(const char **)0) != SQLITE_OK)
  89. ||(sqlite3_prepare_v2(_db,"SELECT 'mgMac','mgAdi','preload','maxBalance','accrual' FROM MulticastRate WHERE 'networkId' = ?",-1,&_sGetMulticastRates,(const char **)0) != SQLITE_OK)
  90. ||(sqlite3_prepare_v2(_db,"SELECT 'nodeId' FROM Member WHERE 'networkId' = ? AND 'authorized' > 0 AND 'activeBridge' > 0",-1,&_sGetActiveBridges,(const char **)0) != SQLITE_OK)
  91. ||(sqlite3_prepare_v2(_db,"SELECT DISTINCT 'ip','ipNetmaskBits' FROM IpAssignment WHERE 'networkId' = ? AND 'nodeId' = ? AND 'ipVersion' = ?",-1,&_sGetIpAssignmentsForNode,(const char **)0) != SQLITE_OK)
  92. ||(sqlite3_prepare_v2(_db,"SELECT DISTINCT 'ipNetwork','ipNetmaskBits' FROM IpAssignmentPool WHERE 'networkId' = ? AND 'ipVersion' = ? AND 'active' > 0",-1,&_sGetIpAssignmentPools,(const char **)0) != SQLITE_OK)
  93. ||(sqlite3_prepare_v2(_db,"SELECT 1 FROM IpAssignment WHERE 'networkId' = ? AND 'ip' = ? AND 'ipVersion' = ?",-1,&_sCheckIfIpIsAllocated,(const char **)0) != SQLITE_OK)
  94. ||(sqlite3_prepare_v2(_db,"INSERT INTO IpAssignment ('networkId','nodeId','ip','ipNetmaskBits','ipVersion') VALUES (?,?,?,?,?)",-1,&_sAllocateIp,(const char **)0) != SQLITE_OK)
  95. ||(sqlite3_prepare_v2(_db,"UPDATE Member SET 'cachedNetconf' = ?,'cachedNetconfRevision' = ? WHERE rowid = ?",-1,&_sCacheNetconf,(const char **)0) != SQLITE_OK)
  96. ) {
  97. sqlite3_close(_db);
  98. throw std::runtime_error("SqliteNetworkController unable to initialize one or more prepared statements");
  99. }
  100. }
  101. SqliteNetworkController::~SqliteNetworkController()
  102. {
  103. Mutex::Lock _l(_lock);
  104. if (_db) {
  105. sqlite3_finalize(_sGetNetworkById);
  106. sqlite3_finalize(_sGetMemberByNetworkAndNodeId);
  107. sqlite3_finalize(_sCreateMember);
  108. sqlite3_finalize(_sGetNodeIdentity);
  109. sqlite3_finalize(_sCreateNode);
  110. sqlite3_finalize(_sUpdateNode);
  111. sqlite3_finalize(_sUpdateNode2);
  112. sqlite3_finalize(_sUpdateMemberClientReportedRevision);
  113. sqlite3_finalize(_sGetEtherTypesFromRuleTable);
  114. sqlite3_finalize(_sGetMulticastRates);
  115. sqlite3_finalize(_sGetActiveBridges);
  116. sqlite3_finalize(_sGetIpAssignmentsForNode);
  117. sqlite3_finalize(_sGetIpAssignmentPools);
  118. sqlite3_finalize(_sCheckIfIpIsAllocated);
  119. sqlite3_finalize(_sAllocateIp);
  120. sqlite3_finalize(_sCacheNetconf);
  121. sqlite3_close(_db);
  122. }
  123. }
  124. NetworkController::ResultCode SqliteNetworkController::doNetworkConfigRequest(const InetAddress &fromAddr,const Identity &signingId,const Identity &identity,uint64_t nwid,const Dictionary &metaData,uint64_t haveRevision,Dictionary &netconf)
  125. {
  126. Mutex::Lock _l(_lock);
  127. // Note: we can't reuse prepared statements that return const char * pointers without
  128. // making our own copy in e.g. a std::string first.
  129. if ((!signingId)||(!signingId.hasPrivate())) {
  130. netconf["error"] = "signing identity invalid or lacks private key";
  131. return NetworkController::NETCONF_QUERY_INTERNAL_SERVER_ERROR;
  132. }
  133. struct {
  134. char id[24];
  135. const char *name;
  136. const char *v4AssignMode;
  137. const char *v6AssignMode;
  138. bool isPrivate;
  139. bool enableBroadcast;
  140. bool allowPassiveBridging;
  141. int multicastLimit;
  142. uint64_t revision;
  143. } network;
  144. memset(&network,0,sizeof(network));
  145. Utils::snprintf(network.id,sizeof(network.id),"%.16llx",(unsigned long long)nwid);
  146. struct {
  147. int64_t rowid;
  148. char nodeId[16];
  149. int cachedNetconfBytes;
  150. const void *cachedNetconf;
  151. uint64_t cachedNetconfRevision;
  152. uint64_t clientReportedRevision;
  153. bool authorized;
  154. bool activeBridge;
  155. } member;
  156. memset(&member,0,sizeof(member));
  157. Utils::snprintf(member.nodeId,sizeof(member.nodeId),"%.10llx",(unsigned long long)identity.address().toInt());
  158. // Create/update Node record and check identity fully -- identities are first-come-first-claim
  159. sqlite3_reset(_sGetNodeIdentity);
  160. sqlite3_bind_text(_sGetNodeIdentity,1,member.nodeId,10,SQLITE_STATIC);
  161. if (sqlite3_step(_sGetNodeIdentity) == SQLITE_ROW) {
  162. try {
  163. Identity alreadyKnownIdentity((const char *)sqlite3_column_text(_sGetNodeIdentity,0));
  164. if (alreadyKnownIdentity == identity) {
  165. char lastSeen[64];
  166. Utils::snprintf(lastSeen,sizeof(lastSeen),"%llu",(unsigned long long)OSUtils::now());
  167. if (fromAddr) {
  168. std::string lastAt(fromAddr.toString());
  169. sqlite3_reset(_sUpdateNode);
  170. sqlite3_bind_text(_sUpdateNode,1,lastAt.c_str(),-1,SQLITE_STATIC);
  171. sqlite3_bind_text(_sUpdateNode,2,lastSeen,-1,SQLITE_STATIC);
  172. sqlite3_bind_text(_sUpdateNode,3,member.nodeId,10,SQLITE_STATIC);
  173. sqlite3_step(_sUpdateNode);
  174. } else { // fromAddr is empty, which means this was a relayed packet -- so don't update lastAt
  175. sqlite3_reset(_sUpdateNode2);
  176. sqlite3_bind_text(_sUpdateNode2,1,lastSeen,-1,SQLITE_STATIC);
  177. sqlite3_bind_text(_sUpdateNode2,2,member.nodeId,10,SQLITE_STATIC);
  178. sqlite3_step(_sUpdateNode2);
  179. }
  180. } else {
  181. return NetworkController::NETCONF_QUERY_ACCESS_DENIED;
  182. }
  183. } catch ( ... ) { // identity stored in database is not valid or is NULL
  184. return NetworkController::NETCONF_QUERY_ACCESS_DENIED;
  185. }
  186. } else {
  187. std::string idstr(identity.toString(false));
  188. std::string lastAt;
  189. if (fromAddr)
  190. lastAt = fromAddr.toString();
  191. char lastSeen[64];
  192. Utils::snprintf(lastSeen,sizeof(lastSeen),"%llu",(unsigned long long)OSUtils::now());
  193. sqlite3_reset(_sCreateNode);
  194. sqlite3_bind_text(_sCreateNode,1,member.nodeId,10,SQLITE_STATIC);
  195. sqlite3_bind_text(_sCreateNode,2,idstr.c_str(),-1,SQLITE_STATIC);
  196. sqlite3_bind_text(_sCreateNode,3,lastAt.c_str(),-1,SQLITE_STATIC);
  197. sqlite3_bind_text(_sCreateNode,4,lastSeen,-1,SQLITE_STATIC);
  198. sqlite3_bind_text(_sCreateNode,5,lastSeen,-1,SQLITE_STATIC);
  199. if (sqlite3_step(_sCreateNode) != SQLITE_DONE) {
  200. netconf["error"] = "unable to create new node record";
  201. return NetworkController::NETCONF_QUERY_INTERNAL_SERVER_ERROR;
  202. }
  203. }
  204. // Fetch Network record
  205. bool foundNetwork = false;
  206. sqlite3_reset(_sGetNetworkById);
  207. sqlite3_bind_text(_sGetNetworkById,1,network.id,16,SQLITE_STATIC);
  208. if (sqlite3_step(_sGetNetworkById) == SQLITE_ROW) {
  209. foundNetwork = true;
  210. network.name = (const char *)sqlite3_column_text(_sGetNetworkById,0);
  211. network.isPrivate = (sqlite3_column_int(_sGetNetworkById,1) > 0);
  212. network.enableBroadcast = (sqlite3_column_int(_sGetNetworkById,2) > 0);
  213. network.allowPassiveBridging = (sqlite3_column_int(_sGetNetworkById,3) > 0);
  214. network.v4AssignMode = (const char *)sqlite3_column_text(_sGetNetworkById,4);
  215. network.v6AssignMode = (const char *)sqlite3_column_text(_sGetNetworkById,5);
  216. network.multicastLimit = sqlite3_column_int(_sGetNetworkById,6);
  217. network.revision = (uint64_t)sqlite3_column_int64(_sGetNetworkById,7);
  218. }
  219. if (!foundNetwork)
  220. return NetworkController::NETCONF_QUERY_OBJECT_NOT_FOUND;
  221. // Fetch Member record
  222. bool foundMember = false;
  223. sqlite3_reset(_sGetMemberByNetworkAndNodeId);
  224. sqlite3_bind_text(_sGetMemberByNetworkAndNodeId,1,network.id,16,SQLITE_STATIC);
  225. sqlite3_bind_text(_sGetMemberByNetworkAndNodeId,2,member.nodeId,10,SQLITE_STATIC);
  226. if (sqlite3_step(_sGetMemberByNetworkAndNodeId) == SQLITE_ROW) {
  227. foundMember = true;
  228. member.rowid = (int64_t)sqlite3_column_int64(_sGetMemberByNetworkAndNodeId,0);
  229. member.cachedNetconfBytes = sqlite3_column_bytes(_sGetMemberByNetworkAndNodeId,1);
  230. member.cachedNetconf = sqlite3_column_blob(_sGetMemberByNetworkAndNodeId,1);
  231. member.cachedNetconfRevision = (uint64_t)sqlite3_column_int64(_sGetMemberByNetworkAndNodeId,2);
  232. member.clientReportedRevision = (uint64_t)sqlite3_column_int64(_sGetMemberByNetworkAndNodeId,3);
  233. member.authorized = (sqlite3_column_int(_sGetMemberByNetworkAndNodeId,4) > 0);
  234. member.activeBridge = (sqlite3_column_int(_sGetMemberByNetworkAndNodeId,5) > 0);
  235. }
  236. // Create Member record for unknown nodes, auto-authorizing if network is public
  237. if (!foundMember) {
  238. member.cachedNetconfBytes = 0;
  239. member.cachedNetconfRevision = 0;
  240. member.clientReportedRevision = 0;
  241. member.authorized = (network.isPrivate ? false : true);
  242. member.activeBridge = false;
  243. sqlite3_reset(_sCreateMember);
  244. sqlite3_bind_text(_sCreateMember,1,network.id,16,SQLITE_STATIC);
  245. sqlite3_bind_text(_sCreateMember,2,member.nodeId,10,SQLITE_STATIC);
  246. sqlite3_bind_int(_sCreateMember,3,(member.authorized ? 0 : 1));
  247. if ( (sqlite3_step(_sCreateMember) != SQLITE_DONE) && ((member.rowid = (int64_t)sqlite3_last_insert_rowid(_db)) > 0) ) {
  248. netconf["error"] = "unable to create new member record";
  249. return NetworkController::NETCONF_QUERY_INTERNAL_SERVER_ERROR;
  250. }
  251. }
  252. // Check member authorization
  253. if (!member.authorized)
  254. return NetworkController::NETCONF_QUERY_ACCESS_DENIED;
  255. // Update client's currently reported haveRevision in Member record
  256. if (member.rowid > 0) {
  257. sqlite3_reset(_sUpdateMemberClientReportedRevision);
  258. sqlite3_bind_int64(_sUpdateMemberClientReportedRevision,1,(sqlite3_int64)haveRevision);
  259. sqlite3_bind_int64(_sUpdateMemberClientReportedRevision,2,member.rowid);
  260. sqlite3_step(_sUpdateMemberClientReportedRevision);
  261. }
  262. // If netconf is unchanged from client reported revision, just tell client they're up to date
  263. if ((haveRevision > 0)&&(haveRevision == network.revision))
  264. return NetworkController::NETCONF_QUERY_OK_BUT_NOT_NEWER;
  265. // Generate or retrieve cached netconf
  266. netconf.clear();
  267. if ((member.cachedNetconfRevision == network.revision)&&(member.cachedNetconfBytes > 0)) {
  268. // Use cached copy
  269. std::string tmp((const char *)member.cachedNetconf,member.cachedNetconfBytes);
  270. netconf.fromString(tmp);
  271. } else {
  272. // Create and sign a new netconf, and save in database to re-use in the future
  273. char tss[24],rs[24];
  274. Utils::snprintf(tss,sizeof(tss),"%.16llx",(unsigned long long)OSUtils::now());
  275. Utils::snprintf(rs,sizeof(rs),"%.16llx",(unsigned long long)network.revision);
  276. netconf[ZT_NETWORKCONFIG_DICT_KEY_TIMESTAMP] = tss;
  277. netconf[ZT_NETWORKCONFIG_DICT_KEY_REVISION] = rs;
  278. netconf[ZT_NETWORKCONFIG_DICT_KEY_NETWORK_ID] = network.id;
  279. netconf[ZT_NETWORKCONFIG_DICT_KEY_ISSUED_TO] = member.nodeId;
  280. netconf[ZT_NETWORKCONFIG_DICT_KEY_PRIVATE] = network.isPrivate ? "1" : "0";
  281. netconf[ZT_NETWORKCONFIG_DICT_KEY_NAME] = (network.name) ? network.name : "";
  282. netconf[ZT_NETWORKCONFIG_DICT_KEY_ENABLE_BROADCAST] = network.enableBroadcast ? "1" : "0";
  283. netconf[ZT_NETWORKCONFIG_DICT_KEY_ALLOW_PASSIVE_BRIDGING] = network.allowPassiveBridging ? "1" : "0";
  284. {
  285. std::vector<int> allowedEtherTypes;
  286. sqlite3_reset(_sGetEtherTypesFromRuleTable);
  287. sqlite3_bind_text(_sGetEtherTypesFromRuleTable,1,network.id,16,SQLITE_STATIC);
  288. while (sqlite3_step(_sGetEtherTypesFromRuleTable) == SQLITE_ROW) {
  289. int et = sqlite3_column_int(_sGetEtherTypesFromRuleTable,0);
  290. if ((et >= 0)&&(et <= 0xffff))
  291. allowedEtherTypes.push_back(et);
  292. }
  293. std::sort(allowedEtherTypes.begin(),allowedEtherTypes.end());
  294. std::unique(allowedEtherTypes.begin(),allowedEtherTypes.end());
  295. std::string allowedEtherTypesCsv;
  296. for(std::vector<int>::const_iterator i(allowedEtherTypes.begin());i!=allowedEtherTypes.end();++i) {
  297. if (allowedEtherTypesCsv.length())
  298. allowedEtherTypesCsv.push_back(',');
  299. char tmp[16];
  300. Utils::snprintf(tmp,sizeof(tmp),"%.4x",(unsigned int)*i);
  301. allowedEtherTypesCsv.append(tmp);
  302. }
  303. netconf[ZT_NETWORKCONFIG_DICT_KEY_ALLOWED_ETHERNET_TYPES] = allowedEtherTypesCsv;
  304. }
  305. {
  306. std::string multicastRates;
  307. sqlite3_reset(_sGetMulticastRates);
  308. sqlite3_bind_text(_sGetMulticastRates,1,network.id,16,SQLITE_STATIC);
  309. while (sqlite3_step(_sGetMulticastRates) == SQLITE_ROW) {
  310. const char *mac = (const char *)sqlite3_column_text(_sGetMulticastRates,0);
  311. if ((mac)&&(strlen(mac) == 12)) {
  312. unsigned long adi = ((unsigned long)sqlite3_column_int64(_sGetMulticastRates,1)) & 0xffffffff;
  313. char tmp[256];
  314. Utils::snprintf(tmp,sizeof(tmp),"%s/%.4lx=%x,%x,%x\n",mac,adi,sqlite3_column_int(_sGetMulticastRates,2),sqlite3_column_int(_sGetMulticastRates,3),sqlite3_column_int(_sGetMulticastRates,4));
  315. multicastRates.append(tmp);
  316. }
  317. }
  318. if (multicastRates.length() > 0)
  319. netconf[ZT_NETWORKCONFIG_DICT_KEY_MULTICAST_RATES] = multicastRates;
  320. if (network.multicastLimit > 0) {
  321. char ml[16];
  322. Utils::snprintf(ml,sizeof(ml),"%lx",(unsigned long)network.multicastLimit);
  323. netconf[ZT_NETWORKCONFIG_DICT_KEY_MULTICAST_LIMIT] = ml;
  324. }
  325. }
  326. {
  327. std::string activeBridges;
  328. sqlite3_reset(_sGetActiveBridges);
  329. sqlite3_bind_text(_sGetActiveBridges,1,network.id,16,SQLITE_STATIC);
  330. while (sqlite3_step(_sGetActiveBridges) == SQLITE_ROW) {
  331. const char *ab = (const char *)sqlite3_column_text(_sGetActiveBridges,0);
  332. if ((ab)&&(strlen(ab) == 10)) {
  333. if (activeBridges.length())
  334. activeBridges.push_back(',');
  335. activeBridges.append(ab);
  336. }
  337. if (activeBridges.length() > 1024) // sanity check -- you can't have too many active bridges at the moment
  338. break;
  339. }
  340. if (activeBridges.length())
  341. netconf[ZT_NETWORKCONFIG_DICT_KEY_ACTIVE_BRIDGES] = activeBridges;
  342. }
  343. if ((network.v4AssignMode)&&(!strcmp(network.v4AssignMode,"zt"))) {
  344. std::string v4s;
  345. sqlite3_reset(_sGetIpAssignmentsForNode);
  346. sqlite3_bind_text(_sGetIpAssignmentsForNode,1,network.id,16,SQLITE_STATIC);
  347. sqlite3_bind_text(_sGetIpAssignmentsForNode,2,member.nodeId,10,SQLITE_STATIC);
  348. sqlite3_bind_int(_sGetIpAssignmentsForNode,3,4); // 4 == IPv4
  349. while (sqlite3_step(_sGetIpAssignmentsForNode) == SQLITE_ROW) {
  350. const unsigned char *ip = (const unsigned char *)sqlite3_column_blob(_sGetIpAssignmentsForNode,0);
  351. int ipNetmaskBits = sqlite3_column_int(_sGetIpAssignmentsForNode,1);
  352. if ((ip)&&(sqlite3_column_bytes(_sGetIpAssignmentsForNode,0) >= 4)&&(ipNetmaskBits > 0)&&(ipNetmaskBits <= 32)) {
  353. char tmp[32];
  354. Utils::snprintf(tmp,sizeof(tmp),"%d.%d.%d.%d/%d",(int)ip[0],(int)ip[1],(int)ip[2],(int)ip[3],ipNetmaskBits);
  355. if (v4s.length())
  356. v4s.push_back(',');
  357. v4s.append(tmp);
  358. }
  359. }
  360. if (!v4s.length()) {
  361. // Attempt to auto-assign an IPv4 address from an available pool if one isn't assigned already
  362. sqlite3_reset(_sGetIpAssignmentPools);
  363. sqlite3_bind_text(_sGetIpAssignmentPools,1,network.id,16,SQLITE_STATIC);
  364. sqlite3_bind_int(_sGetIpAssignmentPools,2,4); // 4 == IPv4
  365. while ((!v4s.length())&&(sqlite3_step(_sGetIpAssignmentPools) == SQLITE_ROW)) {
  366. const void *ipNetwork = sqlite3_column_blob(_sGetIpAssignmentPools,0);
  367. int ipNetmaskBits = sqlite3_column_int(_sGetIpAssignmentPools,1);
  368. if ((ipNetwork)&&(sqlite3_column_bytes(_sGetIpAssignmentPools,0) >= 4)&&(ipNetmaskBits > 0)&&(ipNetmaskBits < 32)) {
  369. uint32_t n = Utils::ntoh(*((const uint32_t *)ipNetwork)); // network in host byte order e.g. 192.168.0.0
  370. uint32_t m = 0xffffffff << (32 - ipNetmaskBits); // netmask e.g. 0xffffff00 for '24' since 32 - 24 == 8
  371. uint32_t im = ~m; // inverse mask, e.g. 0x000000ff for a netmask of 0xffffff00
  372. uint32_t abits = (uint32_t)(identity.address().toInt() & 0xffffffff); // least significant bits of member ZT address
  373. for(uint32_t k=0;k<=im;++k) { // try up to the number of IPs possible in this network
  374. uint32_t ip = ( ((abits + k) & im) | (n & m) ); // build IP using bits from ZT address of member + k
  375. if ((ip & 0x000000ff) == 0x00) continue; // no IPs ending in .0 allowed
  376. if ((ip & 0x000000ff) == 0xff) continue; // no IPs ending in .255 allowed
  377. uint32_t nip = Utils::hton(ip); // IP in big-endian "network" byte order
  378. sqlite3_reset(_sCheckIfIpIsAllocated);
  379. sqlite3_bind_text(_sCheckIfIpIsAllocated,1,network.id,16,SQLITE_STATIC);
  380. sqlite3_bind_blob(_sCheckIfIpIsAllocated,2,(const void *)&nip,4,SQLITE_STATIC);
  381. sqlite3_bind_int(_sCheckIfIpIsAllocated,3,4); // 4 == IPv4
  382. if (sqlite3_step(_sCheckIfIpIsAllocated) != SQLITE_ROW) {
  383. // No rows returned, so the IP is available
  384. sqlite3_reset(_sAllocateIp);
  385. sqlite3_bind_text(_sAllocateIp,1,network.id,16,SQLITE_STATIC);
  386. sqlite3_bind_text(_sAllocateIp,2,member.nodeId,10,SQLITE_STATIC);
  387. sqlite3_bind_blob(_sAllocateIp,3,(const void *)&nip,4,SQLITE_STATIC);
  388. sqlite3_bind_int(_sAllocateIp,4,ipNetmaskBits);
  389. sqlite3_bind_int(_sAllocateIp,5,4); // 4 == IPv4
  390. if (sqlite3_step(_sAllocateIp) == SQLITE_DONE) {
  391. char tmp[32];
  392. Utils::snprintf(tmp,sizeof(tmp),"%d.%d.%d.%d/%d",(int)((ip >> 24) & 0xff),(int)((ip >> 16) & 0xff),(int)((ip >> 8) & 0xff),(int)(ip & 0xff),ipNetmaskBits);
  393. if (v4s.length())
  394. v4s.push_back(',');
  395. v4s.append(tmp);
  396. break; // IP found and reserved! v4s containing something will cause outer while() to break.
  397. }
  398. }
  399. }
  400. }
  401. }
  402. }
  403. if (v4s.length())
  404. netconf[ZT_NETWORKCONFIG_DICT_KEY_IPV4_STATIC] = v4s;
  405. }
  406. // TODO: IPv6 auto-assign once it's supported in UI
  407. if (network.isPrivate) {
  408. CertificateOfMembership com(network.revision,16,nwid,identity.address());
  409. if (com.sign(signingId)) // basically can't fail unless our identity is invalid
  410. netconf[ZT_NETWORKCONFIG_DICT_KEY_CERTIFICATE_OF_MEMBERSHIP] = com.toString();
  411. else {
  412. netconf["error"] = "unable to sign COM";
  413. return NETCONF_QUERY_INTERNAL_SERVER_ERROR;
  414. }
  415. }
  416. if (!netconf.sign(signingId,OSUtils::now())) {
  417. netconf["error"] = "unable to sign netconf dictionary";
  418. return NETCONF_QUERY_INTERNAL_SERVER_ERROR;
  419. }
  420. // Save serialized netconf for future re-use
  421. std::string netconfSerialized(netconf.toString());
  422. if (netconfSerialized.length() < 4096) { // sanity check
  423. sqlite3_reset(_sCacheNetconf);
  424. sqlite3_bind_blob(_sCacheNetconf,1,(const void *)netconfSerialized.data(),netconfSerialized.length(),SQLITE_STATIC);
  425. sqlite3_bind_int64(_sCacheNetconf,2,(sqlite3_int64)network.revision);
  426. sqlite3_bind_int64(_sCacheNetconf,3,member.rowid);
  427. sqlite3_step(_sCacheNetconf);
  428. }
  429. }
  430. return NetworkController::NETCONF_QUERY_OK;
  431. }
  432. } // namespace ZeroTier