SqliteNetworkController.cpp 23 KB

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