SqliteNetworkController.cpp 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517
  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 activeBridge > 0 AND authorized > 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. ||(sqlite3_prepare_v2(_db,"SELECT DISTINCT nodeId,address FROM Relay WHERE networkId = ?",-1,&_sGetRelays,(const char **)0) != SQLITE_OK)
  102. ) {
  103. sqlite3_close(_db);
  104. throw std::runtime_error("SqliteNetworkController unable to initialize one or more prepared statements");
  105. }
  106. }
  107. SqliteNetworkController::~SqliteNetworkController()
  108. {
  109. Mutex::Lock _l(_lock);
  110. if (_db) {
  111. sqlite3_finalize(_sGetNetworkById);
  112. sqlite3_finalize(_sGetMemberByNetworkAndNodeId);
  113. sqlite3_finalize(_sCreateMember);
  114. sqlite3_finalize(_sGetNodeIdentity);
  115. sqlite3_finalize(_sCreateNode);
  116. sqlite3_finalize(_sUpdateNode);
  117. sqlite3_finalize(_sUpdateNode2);
  118. sqlite3_finalize(_sUpdateMemberClientReportedRevision);
  119. sqlite3_finalize(_sGetEtherTypesFromRuleTable);
  120. sqlite3_finalize(_sGetMulticastRates);
  121. sqlite3_finalize(_sGetActiveBridges);
  122. sqlite3_finalize(_sGetIpAssignmentsForNode);
  123. sqlite3_finalize(_sGetIpAssignmentPools);
  124. sqlite3_finalize(_sCheckIfIpIsAllocated);
  125. sqlite3_finalize(_sAllocateIp);
  126. sqlite3_finalize(_sCacheNetconf);
  127. sqlite3_finalize(_sGetRelays);
  128. sqlite3_close(_db);
  129. }
  130. }
  131. NetworkController::ResultCode SqliteNetworkController::doNetworkConfigRequest(const InetAddress &fromAddr,const Identity &signingId,const Identity &identity,uint64_t nwid,const Dictionary &metaData,uint64_t haveRevision,Dictionary &netconf)
  132. {
  133. Mutex::Lock _l(_lock);
  134. // Note: we can't reuse prepared statements that return const char * pointers without
  135. // making our own copy in e.g. a std::string first.
  136. if ((!signingId)||(!signingId.hasPrivate())) {
  137. netconf["error"] = "signing identity invalid or lacks private key";
  138. return NetworkController::NETCONF_QUERY_INTERNAL_SERVER_ERROR;
  139. }
  140. struct {
  141. char id[24];
  142. const char *name;
  143. const char *v4AssignMode;
  144. const char *v6AssignMode;
  145. bool isPrivate;
  146. bool enableBroadcast;
  147. bool allowPassiveBridging;
  148. int multicastLimit;
  149. uint64_t revision;
  150. } network;
  151. memset(&network,0,sizeof(network));
  152. Utils::snprintf(network.id,sizeof(network.id),"%.16llx",(unsigned long long)nwid);
  153. struct {
  154. int64_t rowid;
  155. char nodeId[16];
  156. int cachedNetconfBytes;
  157. const void *cachedNetconf;
  158. uint64_t cachedNetconfRevision;
  159. uint64_t cachedNetconfTimestamp;
  160. uint64_t clientReportedRevision;
  161. bool authorized;
  162. bool activeBridge;
  163. } member;
  164. memset(&member,0,sizeof(member));
  165. Utils::snprintf(member.nodeId,sizeof(member.nodeId),"%.10llx",(unsigned long long)identity.address().toInt());
  166. // Create/update Node record and check identity fully -- identities are first-come-first-claim
  167. sqlite3_reset(_sGetNodeIdentity);
  168. sqlite3_bind_text(_sGetNodeIdentity,1,member.nodeId,10,SQLITE_STATIC);
  169. if (sqlite3_step(_sGetNodeIdentity) == SQLITE_ROW) {
  170. try {
  171. Identity alreadyKnownIdentity((const char *)sqlite3_column_text(_sGetNodeIdentity,0));
  172. if (alreadyKnownIdentity == identity) {
  173. char lastSeen[64];
  174. Utils::snprintf(lastSeen,sizeof(lastSeen),"%llu",(unsigned long long)OSUtils::now());
  175. if (fromAddr) {
  176. std::string lastAt(fromAddr.toString());
  177. sqlite3_reset(_sUpdateNode);
  178. sqlite3_bind_text(_sUpdateNode,1,lastAt.c_str(),-1,SQLITE_STATIC);
  179. sqlite3_bind_text(_sUpdateNode,2,lastSeen,-1,SQLITE_STATIC);
  180. sqlite3_bind_text(_sUpdateNode,3,member.nodeId,10,SQLITE_STATIC);
  181. sqlite3_step(_sUpdateNode);
  182. } else { // fromAddr is empty, which means this was a relayed packet -- so don't update lastAt
  183. sqlite3_reset(_sUpdateNode2);
  184. sqlite3_bind_text(_sUpdateNode2,1,lastSeen,-1,SQLITE_STATIC);
  185. sqlite3_bind_text(_sUpdateNode2,2,member.nodeId,10,SQLITE_STATIC);
  186. sqlite3_step(_sUpdateNode2);
  187. }
  188. } else {
  189. return NetworkController::NETCONF_QUERY_ACCESS_DENIED;
  190. }
  191. } catch ( ... ) { // identity stored in database is not valid or is NULL
  192. return NetworkController::NETCONF_QUERY_ACCESS_DENIED;
  193. }
  194. } else {
  195. std::string idstr(identity.toString(false));
  196. std::string lastAt;
  197. if (fromAddr)
  198. lastAt = fromAddr.toString();
  199. char lastSeen[64];
  200. Utils::snprintf(lastSeen,sizeof(lastSeen),"%llu",(unsigned long long)OSUtils::now());
  201. sqlite3_reset(_sCreateNode);
  202. sqlite3_bind_text(_sCreateNode,1,member.nodeId,10,SQLITE_STATIC);
  203. sqlite3_bind_text(_sCreateNode,2,idstr.c_str(),-1,SQLITE_STATIC);
  204. sqlite3_bind_text(_sCreateNode,3,lastAt.c_str(),-1,SQLITE_STATIC);
  205. sqlite3_bind_text(_sCreateNode,4,lastSeen,-1,SQLITE_STATIC);
  206. sqlite3_bind_text(_sCreateNode,5,lastSeen,-1,SQLITE_STATIC);
  207. if (sqlite3_step(_sCreateNode) != SQLITE_DONE) {
  208. netconf["error"] = "unable to create new node record";
  209. return NetworkController::NETCONF_QUERY_INTERNAL_SERVER_ERROR;
  210. }
  211. }
  212. // Fetch Network record
  213. bool foundNetwork = false;
  214. sqlite3_reset(_sGetNetworkById);
  215. sqlite3_bind_text(_sGetNetworkById,1,network.id,16,SQLITE_STATIC);
  216. if (sqlite3_step(_sGetNetworkById) == SQLITE_ROW) {
  217. foundNetwork = true;
  218. network.name = (const char *)sqlite3_column_text(_sGetNetworkById,0);
  219. network.isPrivate = (sqlite3_column_int(_sGetNetworkById,1) > 0);
  220. network.enableBroadcast = (sqlite3_column_int(_sGetNetworkById,2) > 0);
  221. network.allowPassiveBridging = (sqlite3_column_int(_sGetNetworkById,3) > 0);
  222. network.v4AssignMode = (const char *)sqlite3_column_text(_sGetNetworkById,4);
  223. network.v6AssignMode = (const char *)sqlite3_column_text(_sGetNetworkById,5);
  224. network.multicastLimit = sqlite3_column_int(_sGetNetworkById,6);
  225. network.revision = (uint64_t)sqlite3_column_int64(_sGetNetworkById,7);
  226. }
  227. if (!foundNetwork)
  228. return NetworkController::NETCONF_QUERY_OBJECT_NOT_FOUND;
  229. // Fetch Member record
  230. bool foundMember = false;
  231. sqlite3_reset(_sGetMemberByNetworkAndNodeId);
  232. sqlite3_bind_text(_sGetMemberByNetworkAndNodeId,1,network.id,16,SQLITE_STATIC);
  233. sqlite3_bind_text(_sGetMemberByNetworkAndNodeId,2,member.nodeId,10,SQLITE_STATIC);
  234. if (sqlite3_step(_sGetMemberByNetworkAndNodeId) == SQLITE_ROW) {
  235. foundMember = true;
  236. member.rowid = (int64_t)sqlite3_column_int64(_sGetMemberByNetworkAndNodeId,0);
  237. member.cachedNetconfBytes = sqlite3_column_bytes(_sGetMemberByNetworkAndNodeId,1);
  238. member.cachedNetconf = sqlite3_column_blob(_sGetMemberByNetworkAndNodeId,1);
  239. member.cachedNetconfRevision = (uint64_t)sqlite3_column_int64(_sGetMemberByNetworkAndNodeId,2);
  240. member.cachedNetconfTimestamp = (uint64_t)sqlite3_column_int64(_sGetMemberByNetworkAndNodeId,3);
  241. member.clientReportedRevision = (uint64_t)sqlite3_column_int64(_sGetMemberByNetworkAndNodeId,4);
  242. member.authorized = (sqlite3_column_int(_sGetMemberByNetworkAndNodeId,5) > 0);
  243. member.activeBridge = (sqlite3_column_int(_sGetMemberByNetworkAndNodeId,6) > 0);
  244. }
  245. // Create Member record for unknown nodes, auto-authorizing if network is public
  246. if (!foundMember) {
  247. member.cachedNetconfBytes = 0;
  248. member.cachedNetconfRevision = 0;
  249. member.clientReportedRevision = 0;
  250. member.authorized = (network.isPrivate ? false : true);
  251. member.activeBridge = false;
  252. sqlite3_reset(_sCreateMember);
  253. sqlite3_bind_text(_sCreateMember,1,network.id,16,SQLITE_STATIC);
  254. sqlite3_bind_text(_sCreateMember,2,member.nodeId,10,SQLITE_STATIC);
  255. sqlite3_bind_int(_sCreateMember,3,(member.authorized ? 0 : 1));
  256. if ( (sqlite3_step(_sCreateMember) != SQLITE_DONE) && ((member.rowid = (int64_t)sqlite3_last_insert_rowid(_db)) > 0) ) {
  257. netconf["error"] = "unable to create new member record";
  258. return NetworkController::NETCONF_QUERY_INTERNAL_SERVER_ERROR;
  259. }
  260. }
  261. // Check member authorization
  262. if (!member.authorized)
  263. return NetworkController::NETCONF_QUERY_ACCESS_DENIED;
  264. // Update client's currently reported haveRevision in Member record
  265. if (member.rowid > 0) {
  266. sqlite3_reset(_sUpdateMemberClientReportedRevision);
  267. sqlite3_bind_int64(_sUpdateMemberClientReportedRevision,1,(sqlite3_int64)haveRevision);
  268. sqlite3_bind_int64(_sUpdateMemberClientReportedRevision,2,member.rowid);
  269. sqlite3_step(_sUpdateMemberClientReportedRevision);
  270. }
  271. // If netconf is unchanged from client reported revision, just tell client they're up to date
  272. if ((haveRevision > 0)&&(haveRevision == network.revision))
  273. return NetworkController::NETCONF_QUERY_OK_BUT_NOT_NEWER;
  274. // Generate or retrieve cached netconf
  275. netconf.clear();
  276. if ( (member.cachedNetconfBytes > 0)&&
  277. (member.cachedNetconfRevision == network.revision)&&
  278. ((OSUtils::now() - member.cachedNetconfTimestamp) < ZT_CACHED_NETCONF_MAX_AGE) ) {
  279. // Use cached copy
  280. std::string tmp((const char *)member.cachedNetconf,member.cachedNetconfBytes);
  281. netconf.fromString(tmp);
  282. } else {
  283. // Create and sign a new netconf, and save in database to re-use in the future
  284. char tss[24],rs[24];
  285. Utils::snprintf(tss,sizeof(tss),"%.16llx",(unsigned long long)OSUtils::now());
  286. Utils::snprintf(rs,sizeof(rs),"%.16llx",(unsigned long long)network.revision);
  287. netconf[ZT_NETWORKCONFIG_DICT_KEY_TIMESTAMP] = tss;
  288. netconf[ZT_NETWORKCONFIG_DICT_KEY_REVISION] = rs;
  289. netconf[ZT_NETWORKCONFIG_DICT_KEY_NETWORK_ID] = network.id;
  290. netconf[ZT_NETWORKCONFIG_DICT_KEY_ISSUED_TO] = member.nodeId;
  291. netconf[ZT_NETWORKCONFIG_DICT_KEY_PRIVATE] = network.isPrivate ? "1" : "0";
  292. netconf[ZT_NETWORKCONFIG_DICT_KEY_NAME] = (network.name) ? network.name : "";
  293. netconf[ZT_NETWORKCONFIG_DICT_KEY_ENABLE_BROADCAST] = network.enableBroadcast ? "1" : "0";
  294. netconf[ZT_NETWORKCONFIG_DICT_KEY_ALLOW_PASSIVE_BRIDGING] = network.allowPassiveBridging ? "1" : "0";
  295. {
  296. std::vector<int> allowedEtherTypes;
  297. sqlite3_reset(_sGetEtherTypesFromRuleTable);
  298. sqlite3_bind_text(_sGetEtherTypesFromRuleTable,1,network.id,16,SQLITE_STATIC);
  299. while (sqlite3_step(_sGetEtherTypesFromRuleTable) == SQLITE_ROW) {
  300. int et = sqlite3_column_int(_sGetEtherTypesFromRuleTable,0);
  301. if ((et >= 0)&&(et <= 0xffff))
  302. allowedEtherTypes.push_back(et);
  303. }
  304. std::sort(allowedEtherTypes.begin(),allowedEtherTypes.end());
  305. std::unique(allowedEtherTypes.begin(),allowedEtherTypes.end());
  306. std::string allowedEtherTypesCsv;
  307. for(std::vector<int>::const_iterator i(allowedEtherTypes.begin());i!=allowedEtherTypes.end();++i) {
  308. if (allowedEtherTypesCsv.length())
  309. allowedEtherTypesCsv.push_back(',');
  310. char tmp[16];
  311. Utils::snprintf(tmp,sizeof(tmp),"%.4x",(unsigned int)*i);
  312. allowedEtherTypesCsv.append(tmp);
  313. }
  314. netconf[ZT_NETWORKCONFIG_DICT_KEY_ALLOWED_ETHERNET_TYPES] = allowedEtherTypesCsv;
  315. }
  316. {
  317. std::string multicastRates;
  318. sqlite3_reset(_sGetMulticastRates);
  319. sqlite3_bind_text(_sGetMulticastRates,1,network.id,16,SQLITE_STATIC);
  320. while (sqlite3_step(_sGetMulticastRates) == SQLITE_ROW) {
  321. const char *mac = (const char *)sqlite3_column_text(_sGetMulticastRates,0);
  322. if ((mac)&&(strlen(mac) == 12)) {
  323. unsigned long adi = ((unsigned long)sqlite3_column_int64(_sGetMulticastRates,1)) & 0xffffffff;
  324. char tmp[256];
  325. 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));
  326. multicastRates.append(tmp);
  327. }
  328. }
  329. if (multicastRates.length() > 0)
  330. netconf[ZT_NETWORKCONFIG_DICT_KEY_MULTICAST_RATES] = multicastRates;
  331. if (network.multicastLimit > 0) {
  332. char ml[16];
  333. Utils::snprintf(ml,sizeof(ml),"%lx",(unsigned long)network.multicastLimit);
  334. netconf[ZT_NETWORKCONFIG_DICT_KEY_MULTICAST_LIMIT] = ml;
  335. }
  336. }
  337. {
  338. std::string activeBridges;
  339. sqlite3_reset(_sGetActiveBridges);
  340. sqlite3_bind_text(_sGetActiveBridges,1,network.id,16,SQLITE_STATIC);
  341. while (sqlite3_step(_sGetActiveBridges) == SQLITE_ROW) {
  342. const char *ab = (const char *)sqlite3_column_text(_sGetActiveBridges,0);
  343. if ((ab)&&(strlen(ab) == 10)) {
  344. if (activeBridges.length())
  345. activeBridges.push_back(',');
  346. activeBridges.append(ab);
  347. }
  348. if (activeBridges.length() > 1024) // sanity check -- you can't have too many active bridges at the moment
  349. break;
  350. }
  351. if (activeBridges.length())
  352. netconf[ZT_NETWORKCONFIG_DICT_KEY_ACTIVE_BRIDGES] = activeBridges;
  353. }
  354. {
  355. std::string relays;
  356. sqlite3_reset(_sGetRelays);
  357. sqlite3_bind_text(_sGetRelays,1,network.id,16,SQLITE_STATIC);
  358. while (sqlite3_step(_sGetRelays) == SQLITE_ROW) {
  359. const char *n = (const char *)sqlite3_column_text(_sGetRelays,0);
  360. const char *a = (const char *)sqlite3_column_text(_sGetRelays,1);
  361. if ((n)&&(a)) {
  362. Address node(n);
  363. InetAddress addr(a);
  364. if ((node)&&(addr)) {
  365. if (relays.length())
  366. relays.push_back(',');
  367. relays.append(node.toString());
  368. relays.push_back(';');
  369. relays.append(addr.toString());
  370. }
  371. }
  372. }
  373. if (relays.length())
  374. netconf[ZT_NETWORKCONFIG_DICT_KEY_RELAYS] = relays;
  375. }
  376. if ((network.v4AssignMode)&&(!strcmp(network.v4AssignMode,"zt"))) {
  377. std::string v4s;
  378. sqlite3_reset(_sGetIpAssignmentsForNode);
  379. sqlite3_bind_text(_sGetIpAssignmentsForNode,1,network.id,16,SQLITE_STATIC);
  380. sqlite3_bind_text(_sGetIpAssignmentsForNode,2,member.nodeId,10,SQLITE_STATIC);
  381. sqlite3_bind_int(_sGetIpAssignmentsForNode,3,4); // 4 == IPv4
  382. while (sqlite3_step(_sGetIpAssignmentsForNode) == SQLITE_ROW) {
  383. const unsigned char *ip = (const unsigned char *)sqlite3_column_blob(_sGetIpAssignmentsForNode,0);
  384. int ipNetmaskBits = sqlite3_column_int(_sGetIpAssignmentsForNode,1);
  385. if ((ip)&&(sqlite3_column_bytes(_sGetIpAssignmentsForNode,0) >= 4)&&(ipNetmaskBits > 0)&&(ipNetmaskBits <= 32)) {
  386. char tmp[32];
  387. Utils::snprintf(tmp,sizeof(tmp),"%d.%d.%d.%d/%d",(int)ip[0],(int)ip[1],(int)ip[2],(int)ip[3],ipNetmaskBits);
  388. if (v4s.length())
  389. v4s.push_back(',');
  390. v4s.append(tmp);
  391. }
  392. }
  393. if (!v4s.length()) {
  394. // Attempt to auto-assign an IPv4 address from an available pool if one isn't assigned already
  395. sqlite3_reset(_sGetIpAssignmentPools);
  396. sqlite3_bind_text(_sGetIpAssignmentPools,1,network.id,16,SQLITE_STATIC);
  397. sqlite3_bind_int(_sGetIpAssignmentPools,2,4); // 4 == IPv4
  398. while ((!v4s.length())&&(sqlite3_step(_sGetIpAssignmentPools) == SQLITE_ROW)) {
  399. const void *ipNetwork = sqlite3_column_blob(_sGetIpAssignmentPools,0);
  400. int ipNetmaskBits = sqlite3_column_int(_sGetIpAssignmentPools,1);
  401. if ((ipNetwork)&&(sqlite3_column_bytes(_sGetIpAssignmentPools,0) >= 4)&&(ipNetmaskBits > 0)&&(ipNetmaskBits < 32)) {
  402. uint32_t n = Utils::ntoh(*((const uint32_t *)ipNetwork)); // network in host byte order e.g. 192.168.0.0
  403. uint32_t m = 0xffffffff << (32 - ipNetmaskBits); // netmask e.g. 0xffffff00 for '24' since 32 - 24 == 8
  404. uint32_t im = ~m; // inverse mask, e.g. 0x000000ff for a netmask of 0xffffff00
  405. uint32_t abits = (uint32_t)(identity.address().toInt() & 0xffffffff); // least significant bits of member ZT address
  406. for(uint32_t k=0;k<=im;++k) { // try up to the number of IPs possible in this network
  407. uint32_t ip = ( ((abits + k) & im) | (n & m) ); // build IP using bits from ZT address of member + k
  408. if ((ip & 0x000000ff) == 0x00) continue; // no IPs ending in .0 allowed
  409. if ((ip & 0x000000ff) == 0xff) continue; // no IPs ending in .255 allowed
  410. uint32_t nip = Utils::hton(ip); // IP in big-endian "network" byte order
  411. sqlite3_reset(_sCheckIfIpIsAllocated);
  412. sqlite3_bind_text(_sCheckIfIpIsAllocated,1,network.id,16,SQLITE_STATIC);
  413. sqlite3_bind_blob(_sCheckIfIpIsAllocated,2,(const void *)&nip,4,SQLITE_STATIC);
  414. sqlite3_bind_int(_sCheckIfIpIsAllocated,3,4); // 4 == IPv4
  415. if (sqlite3_step(_sCheckIfIpIsAllocated) != SQLITE_ROW) {
  416. // No rows returned, so the IP is available
  417. sqlite3_reset(_sAllocateIp);
  418. sqlite3_bind_text(_sAllocateIp,1,network.id,16,SQLITE_STATIC);
  419. sqlite3_bind_text(_sAllocateIp,2,member.nodeId,10,SQLITE_STATIC);
  420. sqlite3_bind_blob(_sAllocateIp,3,(const void *)&nip,4,SQLITE_STATIC);
  421. sqlite3_bind_int(_sAllocateIp,4,ipNetmaskBits);
  422. sqlite3_bind_int(_sAllocateIp,5,4); // 4 == IPv4
  423. if (sqlite3_step(_sAllocateIp) == SQLITE_DONE) {
  424. char tmp[32];
  425. 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);
  426. if (v4s.length())
  427. v4s.push_back(',');
  428. v4s.append(tmp);
  429. break; // IP found and reserved! v4s containing something will cause outer while() to break.
  430. }
  431. }
  432. }
  433. }
  434. }
  435. }
  436. if (v4s.length())
  437. netconf[ZT_NETWORKCONFIG_DICT_KEY_IPV4_STATIC] = v4s;
  438. }
  439. // TODO: IPv6 auto-assign once it's supported in UI
  440. if (network.isPrivate) {
  441. CertificateOfMembership com(network.revision,ZT1_CERTIFICATE_OF_MEMBERSHIP_REVISION_MAX_DELTA,nwid,identity.address());
  442. if (com.sign(signingId)) // basically can't fail unless our identity is invalid
  443. netconf[ZT_NETWORKCONFIG_DICT_KEY_CERTIFICATE_OF_MEMBERSHIP] = com.toString();
  444. else {
  445. netconf["error"] = "unable to sign COM";
  446. return NETCONF_QUERY_INTERNAL_SERVER_ERROR;
  447. }
  448. }
  449. if (!netconf.sign(signingId,OSUtils::now())) {
  450. netconf["error"] = "unable to sign netconf dictionary";
  451. return NETCONF_QUERY_INTERNAL_SERVER_ERROR;
  452. }
  453. // Save serialized netconf for future re-use
  454. std::string netconfSerialized(netconf.toString());
  455. if (netconfSerialized.length() < 4096) { // sanity check
  456. sqlite3_reset(_sCacheNetconf);
  457. sqlite3_bind_blob(_sCacheNetconf,1,(const void *)netconfSerialized.data(),netconfSerialized.length(),SQLITE_STATIC);
  458. sqlite3_bind_int64(_sCacheNetconf,2,(sqlite3_int64)network.revision);
  459. sqlite3_bind_int64(_sCacheNetconf,3,member.rowid);
  460. sqlite3_step(_sCacheNetconf);
  461. }
  462. }
  463. return NetworkController::NETCONF_QUERY_OK;
  464. }
  465. } // namespace ZeroTier