SqliteNetworkConfigMaster.cpp 22 KB

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