SqliteNetworkController.cpp 88 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003
  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 <set>
  38. #include "../include/ZeroTierOne.h"
  39. #include "../node/Constants.hpp"
  40. #include "../ext/json-parser/json.h"
  41. #include "SqliteNetworkController.hpp"
  42. #include "../node/Node.hpp"
  43. #include "../node/Utils.hpp"
  44. #include "../node/CertificateOfMembership.hpp"
  45. #include "../node/NetworkConfig.hpp"
  46. #include "../node/InetAddress.hpp"
  47. #include "../node/MAC.hpp"
  48. #include "../node/Address.hpp"
  49. #include "../osdep/OSUtils.hpp"
  50. // Include ZT_NETCONF_SCHEMA_SQL constant to init database
  51. #include "schema.sql.c"
  52. // Stored in database as schemaVersion key in Config.
  53. // If not present, database is assumed to be empty and at the current schema version
  54. // and this key/value is added automatically.
  55. #define ZT_NETCONF_SQLITE_SCHEMA_VERSION 1
  56. #define ZT_NETCONF_SQLITE_SCHEMA_VERSION_STR "1"
  57. // API version reported via JSON control plane
  58. #define ZT_NETCONF_CONTROLLER_API_VERSION 1
  59. // Drop requests for a given peer and network ID that occur more frequently
  60. // than this (ms).
  61. #define ZT_NETCONF_MIN_REQUEST_PERIOD 1000
  62. // Delay between backups in milliseconds
  63. #define ZT_NETCONF_BACKUP_PERIOD 120000
  64. namespace ZeroTier {
  65. namespace {
  66. static std::string _jsonEscape(const char *s)
  67. {
  68. if (!s)
  69. return std::string();
  70. std::string buf;
  71. for(const char *p=s;(*p);++p) {
  72. switch(*p) {
  73. case '\t': buf.append("\\t"); break;
  74. case '\b': buf.append("\\b"); break;
  75. case '\r': buf.append("\\r"); break;
  76. case '\n': buf.append("\\n"); break;
  77. case '\f': buf.append("\\f"); break;
  78. case '"': buf.append("\\\""); break;
  79. case '\\': buf.append("\\\\"); break;
  80. case '/': buf.append("\\/"); break;
  81. default: buf.push_back(*p); break;
  82. }
  83. }
  84. return buf;
  85. }
  86. static std::string _jsonEscape(const std::string &s) { return _jsonEscape(s.c_str()); }
  87. struct MemberRecord {
  88. int64_t rowid;
  89. char nodeId[16];
  90. bool authorized;
  91. bool activeBridge;
  92. };
  93. struct NetworkRecord {
  94. char id[24];
  95. const char *name;
  96. const char *v4AssignMode;
  97. const char *v6AssignMode;
  98. bool isPrivate;
  99. bool enableBroadcast;
  100. bool allowPassiveBridging;
  101. int multicastLimit;
  102. uint64_t creationTime;
  103. uint64_t revision;
  104. uint64_t memberRevisionCounter;
  105. };
  106. } // anonymous namespace
  107. SqliteNetworkController::SqliteNetworkController(Node *node,const char *dbPath,const char *circuitTestPath) :
  108. _node(node),
  109. _backupThreadRun(true),
  110. _dbPath(dbPath),
  111. _circuitTestPath(circuitTestPath),
  112. _db((sqlite3 *)0)
  113. {
  114. if (sqlite3_open_v2(dbPath,&_db,SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE,(const char *)0) != SQLITE_OK)
  115. throw std::runtime_error("SqliteNetworkController cannot open database file");
  116. sqlite3_busy_timeout(_db,10000);
  117. sqlite3_stmt *s = (sqlite3_stmt *)0;
  118. if ((sqlite3_prepare_v2(_db,"SELECT v FROM Config WHERE k = 'schemaVersion';",-1,&s,(const char **)0) == SQLITE_OK)&&(s)) {
  119. int schemaVersion = -1234;
  120. if (sqlite3_step(s) == SQLITE_ROW) {
  121. schemaVersion = sqlite3_column_int(s,0);
  122. }
  123. sqlite3_finalize(s);
  124. if (schemaVersion == -1234) {
  125. sqlite3_close(_db);
  126. throw std::runtime_error("SqliteNetworkController schemaVersion not found in Config table (init failure?)");
  127. } else if (schemaVersion != ZT_NETCONF_SQLITE_SCHEMA_VERSION) {
  128. // Note -- this will eventually run auto-upgrades so this isn't how it'll work going forward
  129. sqlite3_close(_db);
  130. throw std::runtime_error("SqliteNetworkController database schema version mismatch");
  131. }
  132. } else {
  133. // Prepare statement will fail if Config table doesn't exist, which means our DB
  134. // needs to be initialized.
  135. 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) {
  136. char err[1024];
  137. Utils::snprintf(err,sizeof(err),"SqliteNetworkController cannot initialize database and/or insert schemaVersion into Config table: %s",sqlite3_errmsg(_db));
  138. sqlite3_close(_db);
  139. throw std::runtime_error(err);
  140. }
  141. }
  142. if (
  143. /* Network */
  144. (sqlite3_prepare_v2(_db,"SELECT name,private,enableBroadcast,allowPassiveBridging,v4AssignMode,v6AssignMode,multicastLimit,creationTime,revision,memberRevisionCounter,(SELECT COUNT(1) FROM Member WHERE Member.networkId = Network.id AND Member.authorized > 0) FROM Network WHERE id = ?",-1,&_sGetNetworkById,(const char **)0) != SQLITE_OK)
  145. ||(sqlite3_prepare_v2(_db,"SELECT revision FROM Network WHERE id = ?",-1,&_sGetNetworkRevision,(const char **)0) != SQLITE_OK)
  146. ||(sqlite3_prepare_v2(_db,"UPDATE Network SET revision = ? WHERE id = ?",-1,&_sSetNetworkRevision,(const char **)0) != SQLITE_OK)
  147. ||(sqlite3_prepare_v2(_db,"INSERT INTO Network (id,name,creationTime,revision) VALUES (?,?,?,1)",-1,&_sCreateNetwork,(const char **)0) != SQLITE_OK)
  148. ||(sqlite3_prepare_v2(_db,"DELETE FROM Network WHERE id = ?",-1,&_sDeleteNetwork,(const char **)0) != SQLITE_OK)
  149. ||(sqlite3_prepare_v2(_db,"SELECT id FROM Network ORDER BY id ASC",-1,&_sListNetworks,(const char **)0) != SQLITE_OK)
  150. ||(sqlite3_prepare_v2(_db,"UPDATE Network SET memberRevisionCounter = (memberRevisionCounter + 1) WHERE id = ?",-1,&_sIncrementMemberRevisionCounter,(const char **)0) != SQLITE_OK)
  151. /* Node */
  152. ||(sqlite3_prepare_v2(_db,"SELECT identity FROM Node WHERE id = ?",-1,&_sGetNodeIdentity,(const char **)0) != SQLITE_OK)
  153. ||(sqlite3_prepare_v2(_db,"INSERT OR REPLACE INTO Node (id,identity) VALUES (?,?)",-1,&_sCreateOrReplaceNode,(const char **)0) != SQLITE_OK)
  154. /* Rule */
  155. ||(sqlite3_prepare_v2(_db,"SELECT etherType FROM Rule WHERE networkId = ? AND \"action\" = 'accept'",-1,&_sGetEtherTypesFromRuleTable,(const char **)0) != SQLITE_OK)
  156. ||(sqlite3_prepare_v2(_db,"INSERT INTO Rule (networkId,ruleNo,nodeId,sourcePort,destPort,vlanId,vlanPcP,etherType,macSource,macDest,ipSource,ipDest,ipTos,ipProtocol,ipSourcePort,ipDestPort,flags,invFlags,\"action\") VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)",-1,&_sCreateRule,(const char **)0) != SQLITE_OK)
  157. ||(sqlite3_prepare_v2(_db,"SELECT ruleNo,nodeId,sourcePort,destPort,vlanId,vlanPcp,etherType,macSource,macDest,ipSource,ipDest,ipTos,ipProtocol,ipSourcePort,ipDestPort,\"flags\",invFlags,\"action\" FROM Rule WHERE networkId = ? ORDER BY ruleNo ASC",-1,&_sListRules,(const char **)0) != SQLITE_OK)
  158. ||(sqlite3_prepare_v2(_db,"DELETE FROM Rule WHERE networkId = ?",-1,&_sDeleteRulesForNetwork,(const char **)0) != SQLITE_OK)
  159. /* IpAssignmentPool */
  160. ||(sqlite3_prepare_v2(_db,"SELECT ipRangeStart,ipRangeEnd FROM IpAssignmentPool WHERE networkId = ? AND ipVersion = ?",-1,&_sGetIpAssignmentPools,(const char **)0) != SQLITE_OK)
  161. ||(sqlite3_prepare_v2(_db,"SELECT ipRangeStart,ipRangeEnd,ipVersion FROM IpAssignmentPool WHERE networkId = ? ORDER BY ipRangeStart ASC",-1,&_sGetIpAssignmentPools2,(const char **)0) != SQLITE_OK)
  162. ||(sqlite3_prepare_v2(_db,"INSERT INTO IpAssignmentPool (networkId,ipRangeStart,ipRangeEnd,ipVersion) VALUES (?,?,?,?)",-1,&_sCreateIpAssignmentPool,(const char **)0) != SQLITE_OK)
  163. ||(sqlite3_prepare_v2(_db,"DELETE FROM IpAssignmentPool WHERE networkId = ?",-1,&_sDeleteIpAssignmentPoolsForNetwork,(const char **)0) != SQLITE_OK)
  164. /* IpAssignment */
  165. ||(sqlite3_prepare_v2(_db,"SELECT \"type\",ip,ipNetmaskBits FROM IpAssignment WHERE networkId = ? AND (nodeId = ? OR nodeId IS NULL) AND ipVersion = ?",-1,&_sGetIpAssignmentsForNode,(const char **)0) != SQLITE_OK)
  166. ||(sqlite3_prepare_v2(_db,"SELECT ip,ipNetmaskBits,ipVersion FROM IpAssignment WHERE networkId = ? AND nodeId = ? AND \"type\" = ? ORDER BY ip ASC",-1,&_sGetIpAssignmentsForNode2,(const char **)0) != SQLITE_OK)
  167. ||(sqlite3_prepare_v2(_db,"SELECT ip,ipNetmaskBits,ipVersion FROM IpAssignment WHERE networkId = ? AND nodeId IS NULL AND \"type\" = ?",-1,&_sGetLocalRoutes,(const char **)0) != SQLITE_OK)
  168. ||(sqlite3_prepare_v2(_db,"SELECT 1 FROM IpAssignment WHERE networkId = ? AND ip = ? AND ipVersion = ? AND \"type\" = ?",-1,&_sCheckIfIpIsAllocated,(const char **)0) != SQLITE_OK)
  169. ||(sqlite3_prepare_v2(_db,"INSERT INTO IpAssignment (networkId,nodeId,\"type\",ip,ipNetmaskBits,ipVersion) VALUES (?,?,?,?,?,?)",-1,&_sAllocateIp,(const char **)0) != SQLITE_OK)
  170. ||(sqlite3_prepare_v2(_db,"DELETE FROM IpAssignment WHERE networkId = ? AND nodeId = ? AND \"type\" = ?",-1,&_sDeleteIpAllocations,(const char **)0) != SQLITE_OK)
  171. ||(sqlite3_prepare_v2(_db,"DELETE FROM IpAssignment WHERE networkId = ? AND nodeId IS NULL AND \"type\" = ?",-1,&_sDeleteLocalRoutes,(const char **)0) != SQLITE_OK)
  172. /* Relay */
  173. ||(sqlite3_prepare_v2(_db,"SELECT \"address\",\"phyAddress\" FROM Relay WHERE \"networkId\" = ? ORDER BY \"address\" ASC",-1,&_sGetRelays,(const char **)0) != SQLITE_OK)
  174. ||(sqlite3_prepare_v2(_db,"DELETE FROM Relay WHERE networkId = ?",-1,&_sDeleteRelaysForNetwork,(const char **)0) != SQLITE_OK)
  175. ||(sqlite3_prepare_v2(_db,"INSERT INTO Relay (\"networkId\",\"address\",\"phyAddress\") VALUES (?,?,?)",-1,&_sCreateRelay,(const char **)0) != SQLITE_OK)
  176. /* Member */
  177. ||(sqlite3_prepare_v2(_db,"SELECT rowid,authorized,activeBridge FROM Member WHERE networkId = ? AND nodeId = ?",-1,&_sGetMember,(const char **)0) != SQLITE_OK)
  178. ||(sqlite3_prepare_v2(_db,"SELECT m.authorized,m.activeBridge,m.memberRevision,n.identity FROM Member AS m LEFT OUTER JOIN Node AS n ON n.id = m.nodeId WHERE m.networkId = ? AND m.nodeId = ?",-1,&_sGetMember2,(const char **)0) != SQLITE_OK)
  179. ||(sqlite3_prepare_v2(_db,"INSERT INTO Member (networkId,nodeId,authorized,activeBridge,memberRevision) VALUES (?,?,?,0,(SELECT memberRevisionCounter FROM Network WHERE id = ?))",-1,&_sCreateMember,(const char **)0) != SQLITE_OK)
  180. ||(sqlite3_prepare_v2(_db,"SELECT nodeId FROM Member WHERE networkId = ? AND activeBridge > 0 AND authorized > 0",-1,&_sGetActiveBridges,(const char **)0) != SQLITE_OK)
  181. ||(sqlite3_prepare_v2(_db,"SELECT m.nodeId,m.memberRevision FROM Member AS m WHERE m.networkId = ? ORDER BY m.nodeId ASC",-1,&_sListNetworkMembers,(const char **)0) != SQLITE_OK)
  182. ||(sqlite3_prepare_v2(_db,"UPDATE Member SET authorized = ?,memberRevision = (SELECT memberRevisionCounter FROM Network WHERE id = ?) WHERE rowid = ?",-1,&_sUpdateMemberAuthorized,(const char **)0) != SQLITE_OK)
  183. ||(sqlite3_prepare_v2(_db,"UPDATE Member SET activeBridge = ?,memberRevision = (SELECT memberRevisionCounter FROM Network WHERE id = ?) WHERE rowid = ?",-1,&_sUpdateMemberActiveBridge,(const char **)0) != SQLITE_OK)
  184. ||(sqlite3_prepare_v2(_db,"DELETE FROM Member WHERE networkId = ? AND nodeId = ?",-1,&_sDeleteMember,(const char **)0) != SQLITE_OK)
  185. ||(sqlite3_prepare_v2(_db,"DELETE FROM Member WHERE networkId = ?",-1,&_sDeleteAllNetworkMembers,(const char **)0) != SQLITE_OK)
  186. /* Gateway */
  187. ||(sqlite3_prepare_v2(_db,"SELECT \"ip\",ipVersion,metric FROM Gateway WHERE networkId = ? ORDER BY metric ASC",-1,&_sGetGateways,(const char **)0) != SQLITE_OK)
  188. ||(sqlite3_prepare_v2(_db,"DELETE FROM Gateway WHERE networkId = ?",-1,&_sDeleteGateways,(const char **)0) != SQLITE_OK)
  189. ||(sqlite3_prepare_v2(_db,"INSERT INTO Gateway (networkId,\"ip\",ipVersion,metric) VALUES (?,?,?,?)",-1,&_sCreateGateway,(const char **)0) != SQLITE_OK)
  190. /* Config */
  191. ||(sqlite3_prepare_v2(_db,"SELECT \"v\" FROM \"Config\" WHERE \"k\" = ?",-1,&_sGetConfig,(const char **)0) != SQLITE_OK)
  192. ||(sqlite3_prepare_v2(_db,"INSERT OR REPLACE INTO \"Config\" (\"k\",\"v\") VALUES (?,?)",-1,&_sSetConfig,(const char **)0) != SQLITE_OK)
  193. ) {
  194. //printf("%s\n",sqlite3_errmsg(_db));
  195. sqlite3_close(_db);
  196. throw std::runtime_error("SqliteNetworkController unable to initialize one or more prepared statements");
  197. }
  198. /* Generate a 128-bit / 32-character "instance ID" if one isn't already
  199. * defined. Clients can use this to determine if this is the same controller
  200. * database they know and love. */
  201. sqlite3_reset(_sGetConfig);
  202. sqlite3_bind_text(_sGetConfig,1,"instanceId",10,SQLITE_STATIC);
  203. if (sqlite3_step(_sGetConfig) != SQLITE_ROW) {
  204. unsigned char sr[32];
  205. Utils::getSecureRandom(sr,32);
  206. for(unsigned int i=0;i<32;++i)
  207. _instanceId.push_back("0123456789abcdef"[(unsigned int)sr[i] & 0xf]);
  208. sqlite3_reset(_sSetConfig);
  209. sqlite3_bind_text(_sSetConfig,1,"instanceId",10,SQLITE_STATIC);
  210. sqlite3_bind_text(_sSetConfig,2,_instanceId.c_str(),-1,SQLITE_STATIC);
  211. if (sqlite3_step(_sSetConfig) != SQLITE_DONE)
  212. throw std::runtime_error("SqliteNetworkController unable to read or initialize instanceId");
  213. } else {
  214. const char *iid = reinterpret_cast<const char *>(sqlite3_column_text(_sGetConfig,0));
  215. if (!iid)
  216. throw std::runtime_error("SqliteNetworkController unable to read instanceId (it's NULL)");
  217. _instanceId = iid;
  218. }
  219. _backupThread = Thread::start(this);
  220. }
  221. SqliteNetworkController::~SqliteNetworkController()
  222. {
  223. _backupThreadRun = false;
  224. Thread::join(_backupThread);
  225. Mutex::Lock _l(_lock);
  226. if (_db) {
  227. sqlite3_finalize(_sGetNetworkById);
  228. sqlite3_finalize(_sGetMember);
  229. sqlite3_finalize(_sCreateMember);
  230. sqlite3_finalize(_sGetNodeIdentity);
  231. sqlite3_finalize(_sCreateOrReplaceNode);
  232. sqlite3_finalize(_sGetEtherTypesFromRuleTable);
  233. sqlite3_finalize(_sGetActiveBridges);
  234. sqlite3_finalize(_sGetIpAssignmentsForNode);
  235. sqlite3_finalize(_sGetIpAssignmentPools);
  236. sqlite3_finalize(_sGetLocalRoutes);
  237. sqlite3_finalize(_sCheckIfIpIsAllocated);
  238. sqlite3_finalize(_sAllocateIp);
  239. sqlite3_finalize(_sDeleteIpAllocations);
  240. sqlite3_finalize(_sDeleteLocalRoutes);
  241. sqlite3_finalize(_sGetRelays);
  242. sqlite3_finalize(_sListNetworks);
  243. sqlite3_finalize(_sListNetworkMembers);
  244. sqlite3_finalize(_sGetMember2);
  245. sqlite3_finalize(_sGetIpAssignmentPools2);
  246. sqlite3_finalize(_sListRules);
  247. sqlite3_finalize(_sCreateRule);
  248. sqlite3_finalize(_sCreateNetwork);
  249. sqlite3_finalize(_sGetNetworkRevision);
  250. sqlite3_finalize(_sSetNetworkRevision);
  251. sqlite3_finalize(_sGetIpAssignmentsForNode2);
  252. sqlite3_finalize(_sDeleteRelaysForNetwork);
  253. sqlite3_finalize(_sCreateRelay);
  254. sqlite3_finalize(_sDeleteIpAssignmentPoolsForNetwork);
  255. sqlite3_finalize(_sDeleteRulesForNetwork);
  256. sqlite3_finalize(_sCreateIpAssignmentPool);
  257. sqlite3_finalize(_sUpdateMemberAuthorized);
  258. sqlite3_finalize(_sUpdateMemberActiveBridge);
  259. sqlite3_finalize(_sDeleteMember);
  260. sqlite3_finalize(_sDeleteAllNetworkMembers);
  261. sqlite3_finalize(_sDeleteNetwork);
  262. sqlite3_finalize(_sGetGateways);
  263. sqlite3_finalize(_sDeleteGateways);
  264. sqlite3_finalize(_sCreateGateway);
  265. sqlite3_finalize(_sIncrementMemberRevisionCounter);
  266. sqlite3_finalize(_sGetConfig);
  267. sqlite3_finalize(_sSetConfig);
  268. sqlite3_close(_db);
  269. }
  270. }
  271. NetworkController::ResultCode SqliteNetworkController::doNetworkConfigRequest(const InetAddress &fromAddr,const Identity &signingId,const Identity &identity,uint64_t nwid,const Dictionary &metaData,Dictionary &netconf)
  272. {
  273. Mutex::Lock _l(_lock);
  274. return _doNetworkConfigRequest(fromAddr,signingId,identity,nwid,metaData,netconf);
  275. }
  276. unsigned int SqliteNetworkController::handleControlPlaneHttpGET(
  277. const std::vector<std::string> &path,
  278. const std::map<std::string,std::string> &urlArgs,
  279. const std::map<std::string,std::string> &headers,
  280. const std::string &body,
  281. std::string &responseBody,
  282. std::string &responseContentType)
  283. {
  284. Mutex::Lock _l(_lock);
  285. return _doCPGet(path,urlArgs,headers,body,responseBody,responseContentType);
  286. }
  287. unsigned int SqliteNetworkController::handleControlPlaneHttpPOST(
  288. const std::vector<std::string> &path,
  289. const std::map<std::string,std::string> &urlArgs,
  290. const std::map<std::string,std::string> &headers,
  291. const std::string &body,
  292. std::string &responseBody,
  293. std::string &responseContentType)
  294. {
  295. if (path.empty())
  296. return 404;
  297. Mutex::Lock _l(_lock);
  298. if (path[0] == "network") {
  299. if ((path.size() >= 2)&&(path[1].length() == 16)) {
  300. uint64_t nwid = Utils::hexStrToU64(path[1].c_str());
  301. char nwids[24];
  302. Utils::snprintf(nwids,sizeof(nwids),"%.16llx",(unsigned long long)nwid);
  303. int64_t revision = 0;
  304. sqlite3_reset(_sGetNetworkRevision);
  305. sqlite3_bind_text(_sGetNetworkRevision,1,nwids,16,SQLITE_STATIC);
  306. bool networkExists = false;
  307. if (sqlite3_step(_sGetNetworkRevision) == SQLITE_ROW) {
  308. networkExists = true;
  309. revision = sqlite3_column_int64(_sGetNetworkRevision,0);
  310. }
  311. if (path.size() >= 3) {
  312. if (!networkExists)
  313. return 404;
  314. if ((path.size() == 4)&&(path[2] == "member")&&(path[3].length() == 10)) {
  315. uint64_t address = Utils::hexStrToU64(path[3].c_str());
  316. char addrs[24];
  317. Utils::snprintf(addrs,sizeof(addrs),"%.10llx",address);
  318. int64_t addToNetworkRevision = 0;
  319. int64_t memberRowId = 0;
  320. sqlite3_reset(_sGetMember);
  321. sqlite3_bind_text(_sGetMember,1,nwids,16,SQLITE_STATIC);
  322. sqlite3_bind_text(_sGetMember,2,addrs,10,SQLITE_STATIC);
  323. bool memberExists = false;
  324. if (sqlite3_step(_sGetMember) == SQLITE_ROW) {
  325. memberExists = true;
  326. memberRowId = sqlite3_column_int64(_sGetMember,0);
  327. }
  328. if (!memberExists) {
  329. sqlite3_reset(_sCreateMember);
  330. sqlite3_bind_text(_sCreateMember,1,nwids,16,SQLITE_STATIC);
  331. sqlite3_bind_text(_sCreateMember,2,addrs,10,SQLITE_STATIC);
  332. sqlite3_bind_int(_sCreateMember,3,0);
  333. sqlite3_bind_text(_sCreateMember,4,nwids,16,SQLITE_STATIC);
  334. if (sqlite3_step(_sCreateMember) != SQLITE_DONE)
  335. return 500;
  336. memberRowId = (int64_t)sqlite3_last_insert_rowid(_db);
  337. sqlite3_reset(_sIncrementMemberRevisionCounter);
  338. sqlite3_bind_text(_sIncrementMemberRevisionCounter,1,nwids,16,SQLITE_STATIC);
  339. sqlite3_step(_sIncrementMemberRevisionCounter);
  340. addToNetworkRevision = 1;
  341. }
  342. json_value *j = json_parse(body.c_str(),body.length());
  343. if (j) {
  344. if (j->type == json_object) {
  345. for(unsigned int k=0;k<j->u.object.length;++k) {
  346. if (!strcmp(j->u.object.values[k].name,"authorized")) {
  347. if (j->u.object.values[k].value->type == json_boolean) {
  348. sqlite3_reset(_sUpdateMemberAuthorized);
  349. sqlite3_bind_int(_sUpdateMemberAuthorized,1,(j->u.object.values[k].value->u.boolean == 0) ? 0 : 1);
  350. sqlite3_bind_text(_sUpdateMemberAuthorized,2,nwids,16,SQLITE_STATIC);
  351. sqlite3_bind_int64(_sUpdateMemberAuthorized,3,memberRowId);
  352. if (sqlite3_step(_sUpdateMemberAuthorized) != SQLITE_DONE)
  353. return 500;
  354. sqlite3_reset(_sIncrementMemberRevisionCounter);
  355. sqlite3_bind_text(_sIncrementMemberRevisionCounter,1,nwids,16,SQLITE_STATIC);
  356. sqlite3_step(_sIncrementMemberRevisionCounter);
  357. addToNetworkRevision = 1;
  358. }
  359. } else if (!strcmp(j->u.object.values[k].name,"activeBridge")) {
  360. if (j->u.object.values[k].value->type == json_boolean) {
  361. sqlite3_reset(_sUpdateMemberActiveBridge);
  362. sqlite3_bind_int(_sUpdateMemberActiveBridge,1,(j->u.object.values[k].value->u.boolean == 0) ? 0 : 1);
  363. sqlite3_bind_text(_sUpdateMemberActiveBridge,2,nwids,16,SQLITE_STATIC);
  364. sqlite3_bind_int64(_sUpdateMemberActiveBridge,3,memberRowId);
  365. if (sqlite3_step(_sUpdateMemberActiveBridge) != SQLITE_DONE)
  366. return 500;
  367. sqlite3_reset(_sIncrementMemberRevisionCounter);
  368. sqlite3_bind_text(_sIncrementMemberRevisionCounter,1,nwids,16,SQLITE_STATIC);
  369. sqlite3_step(_sIncrementMemberRevisionCounter);
  370. addToNetworkRevision = 1;
  371. }
  372. } else if (!strcmp(j->u.object.values[k].name,"ipAssignments")) {
  373. if (j->u.object.values[k].value->type == json_array) {
  374. sqlite3_reset(_sDeleteIpAllocations);
  375. sqlite3_bind_text(_sDeleteIpAllocations,1,nwids,16,SQLITE_STATIC);
  376. sqlite3_bind_text(_sDeleteIpAllocations,2,addrs,10,SQLITE_STATIC);
  377. sqlite3_bind_int(_sDeleteIpAllocations,3,(int)ZT_IP_ASSIGNMENT_TYPE_ADDRESS);
  378. if (sqlite3_step(_sDeleteIpAllocations) != SQLITE_DONE)
  379. return 500;
  380. for(unsigned int kk=0;kk<j->u.object.values[k].value->u.array.length;++kk) {
  381. json_value *ipalloc = j->u.object.values[k].value->u.array.values[kk];
  382. if (ipalloc->type == json_string) {
  383. InetAddress a(ipalloc->u.string.ptr);
  384. char ipBlob[16];
  385. int ipVersion = 0;
  386. switch(a.ss_family) {
  387. case AF_INET:
  388. if ((a.netmaskBits() > 0)&&(a.netmaskBits() <= 32)) {
  389. memset(ipBlob,0,12);
  390. memcpy(ipBlob + 12,a.rawIpData(),4);
  391. ipVersion = 4;
  392. }
  393. break;
  394. case AF_INET6:
  395. if ((a.netmaskBits() > 0)&&(a.netmaskBits() <= 128)) {
  396. memcpy(ipBlob,a.rawIpData(),16);
  397. ipVersion = 6;
  398. }
  399. break;
  400. }
  401. if (ipVersion > 0) {
  402. sqlite3_reset(_sAllocateIp);
  403. sqlite3_bind_text(_sAllocateIp,1,nwids,16,SQLITE_STATIC);
  404. sqlite3_bind_text(_sAllocateIp,2,addrs,10,SQLITE_STATIC);
  405. sqlite3_bind_int(_sAllocateIp,3,(int)ZT_IP_ASSIGNMENT_TYPE_ADDRESS);
  406. sqlite3_bind_blob(_sAllocateIp,4,(const void *)ipBlob,16,SQLITE_STATIC);
  407. sqlite3_bind_int(_sAllocateIp,5,(int)a.netmaskBits());
  408. sqlite3_bind_int(_sAllocateIp,6,ipVersion);
  409. if (sqlite3_step(_sAllocateIp) != SQLITE_DONE)
  410. return 500;
  411. }
  412. }
  413. }
  414. addToNetworkRevision = 1;
  415. }
  416. } else if (!strcmp(j->u.object.values[k].name,"identity")) {
  417. // Identity is technically an immutable field, but if the member's Node has
  418. // no identity we allow it to be populated. This is primarily for migrating
  419. // node data from another controller.
  420. json_value *idstr = j->u.object.values[k].value;
  421. if (idstr->type == json_string) {
  422. bool alreadyHaveIdentity = false;
  423. sqlite3_reset(_sGetNodeIdentity);
  424. sqlite3_bind_text(_sGetNodeIdentity,1,addrs,10,SQLITE_STATIC);
  425. if (sqlite3_step(_sGetNodeIdentity) == SQLITE_ROW) {
  426. const char *tmp2 = (const char *)sqlite3_column_text(_sGetNodeIdentity,0);
  427. if ((tmp2)&&(tmp2[0]))
  428. alreadyHaveIdentity = true;
  429. }
  430. if (!alreadyHaveIdentity) {
  431. try {
  432. Identity id2(idstr->u.string.ptr);
  433. if (id2) {
  434. std::string idstr2(id2.toString(false)); // object must persist until after sqlite3_step() for SQLITE_STATIC
  435. sqlite3_reset(_sCreateOrReplaceNode);
  436. sqlite3_bind_text(_sCreateOrReplaceNode,1,addrs,10,SQLITE_STATIC);
  437. sqlite3_bind_text(_sCreateOrReplaceNode,2,idstr2.c_str(),-1,SQLITE_STATIC);
  438. sqlite3_step(_sCreateOrReplaceNode);
  439. }
  440. } catch ( ... ) {} // ignore invalid identities
  441. }
  442. }
  443. }
  444. }
  445. }
  446. json_value_free(j);
  447. }
  448. if ((addToNetworkRevision > 0)&&(revision > 0)) {
  449. sqlite3_reset(_sSetNetworkRevision);
  450. sqlite3_bind_int64(_sSetNetworkRevision,1,revision + addToNetworkRevision);
  451. sqlite3_bind_text(_sSetNetworkRevision,2,nwids,16,SQLITE_STATIC);
  452. sqlite3_step(_sSetNetworkRevision);
  453. }
  454. return _doCPGet(path,urlArgs,headers,body,responseBody,responseContentType);
  455. } else if ((path.size() == 3)&&(path[2] == "test")) {
  456. ZT_CircuitTest *test = (ZT_CircuitTest *)malloc(sizeof(ZT_CircuitTest));
  457. memset(test,0,sizeof(ZT_CircuitTest));
  458. Utils::getSecureRandom(&(test->testId),sizeof(test->testId));
  459. test->credentialNetworkId = nwid;
  460. test->ptr = (void *)this;
  461. json_value *j = json_parse(body.c_str(),body.length());
  462. if (j) {
  463. if (j->type == json_object) {
  464. for(unsigned int k=0;k<j->u.object.length;++k) {
  465. if (!strcmp(j->u.object.values[k].name,"hops")) {
  466. if (j->u.object.values[k].value->type == json_array) {
  467. for(unsigned int kk=0;kk<j->u.object.values[k].value->u.array.length;++kk) {
  468. json_value *hop = j->u.object.values[k].value->u.array.values[kk];
  469. if (hop->type == json_array) {
  470. for(unsigned int kkk=0;kkk<hop->u.array.length;++kkk) {
  471. if (hop->u.array.values[kkk]->type == json_string) {
  472. test->hops[test->hopCount].addresses[test->hops[test->hopCount].breadth++] = Utils::hexStrToU64(hop->u.array.values[kkk]->u.string.ptr) & 0xffffffffffULL;
  473. }
  474. }
  475. ++test->hopCount;
  476. }
  477. }
  478. }
  479. } else if (!strcmp(j->u.object.values[k].name,"reportAtEveryHop")) {
  480. if (j->u.object.values[k].value->type == json_boolean)
  481. test->reportAtEveryHop = (j->u.object.values[k].value->u.boolean == 0) ? 0 : 1;
  482. }
  483. }
  484. }
  485. json_value_free(j);
  486. }
  487. if (!test->hopCount) {
  488. ::free((void *)test);
  489. return 500;
  490. }
  491. test->timestamp = OSUtils::now();
  492. _circuitTests[test->testId] = test;
  493. _node->circuitTestBegin(test,&(SqliteNetworkController::_circuitTestCallback));
  494. return 200;
  495. } // else 404
  496. } else {
  497. std::vector<std::string> path_copy(path);
  498. if (!networkExists) {
  499. if (path[1].substr(10) == "______") {
  500. // A special POST /network/##########______ feature lets users create a network
  501. // with an arbitrary unused network number at this controller.
  502. nwid = 0;
  503. uint64_t nwidPrefix = (Utils::hexStrToU64(path[1].substr(0,10).c_str()) << 24) & 0xffffffffff000000ULL;
  504. uint64_t nwidPostfix = 0;
  505. Utils::getSecureRandom(&nwidPostfix,sizeof(nwidPostfix));
  506. uint64_t nwidOriginalPostfix = nwidPostfix;
  507. do {
  508. uint64_t tryNwid = nwidPrefix | (nwidPostfix & 0xffffffULL);
  509. if (!nwidPostfix)
  510. tryNwid |= 1;
  511. Utils::snprintf(nwids,sizeof(nwids),"%.16llx",(unsigned long long)tryNwid);
  512. sqlite3_reset(_sGetNetworkRevision);
  513. sqlite3_bind_text(_sGetNetworkRevision,1,nwids,16,SQLITE_STATIC);
  514. if (sqlite3_step(_sGetNetworkRevision) != SQLITE_ROW) {
  515. nwid = tryNwid;
  516. break;
  517. }
  518. ++nwidPostfix;
  519. } while (nwidPostfix != nwidOriginalPostfix);
  520. // 503 means we have no more free IDs for this prefix. You shouldn't host anywhere
  521. // near 16 million networks on the same controller, so shouldn't happen.
  522. if (!nwid)
  523. return 503;
  524. }
  525. sqlite3_reset(_sCreateNetwork);
  526. sqlite3_bind_text(_sCreateNetwork,1,nwids,16,SQLITE_STATIC);
  527. sqlite3_bind_text(_sCreateNetwork,2,"",0,SQLITE_STATIC);
  528. sqlite3_bind_int64(_sCreateNetwork,3,(long long)OSUtils::now());
  529. if (sqlite3_step(_sCreateNetwork) != SQLITE_DONE)
  530. return 500;
  531. path_copy[1].assign(nwids);
  532. }
  533. json_value *j = json_parse(body.c_str(),body.length());
  534. if (j) {
  535. if (j->type == json_object) {
  536. for(unsigned int k=0;k<j->u.object.length;++k) {
  537. sqlite3_stmt *stmt = (sqlite3_stmt *)0;
  538. if (!strcmp(j->u.object.values[k].name,"name")) {
  539. if ((j->u.object.values[k].value->type == json_string)&&(j->u.object.values[k].value->u.string.ptr[0])) {
  540. if (sqlite3_prepare_v2(_db,"UPDATE Network SET \"name\" = ? WHERE id = ?",-1,&stmt,(const char **)0) == SQLITE_OK)
  541. sqlite3_bind_text(stmt,1,j->u.object.values[k].value->u.string.ptr,-1,SQLITE_STATIC);
  542. }
  543. } else if (!strcmp(j->u.object.values[k].name,"private")) {
  544. if (j->u.object.values[k].value->type == json_boolean) {
  545. if (sqlite3_prepare_v2(_db,"UPDATE Network SET \"private\" = ? WHERE id = ?",-1,&stmt,(const char **)0) == SQLITE_OK)
  546. sqlite3_bind_int(stmt,1,(j->u.object.values[k].value->u.boolean == 0) ? 0 : 1);
  547. }
  548. } else if (!strcmp(j->u.object.values[k].name,"enableBroadcast")) {
  549. if (j->u.object.values[k].value->type == json_boolean) {
  550. if (sqlite3_prepare_v2(_db,"UPDATE Network SET enableBroadcast = ? WHERE id = ?",-1,&stmt,(const char **)0) == SQLITE_OK)
  551. sqlite3_bind_int(stmt,1,(j->u.object.values[k].value->u.boolean == 0) ? 0 : 1);
  552. }
  553. } else if (!strcmp(j->u.object.values[k].name,"allowPassiveBridging")) {
  554. if (j->u.object.values[k].value->type == json_boolean) {
  555. if (sqlite3_prepare_v2(_db,"UPDATE Network SET allowPassiveBridging = ? WHERE id = ?",-1,&stmt,(const char **)0) == SQLITE_OK)
  556. sqlite3_bind_int(stmt,1,(j->u.object.values[k].value->u.boolean == 0) ? 0 : 1);
  557. }
  558. } else if (!strcmp(j->u.object.values[k].name,"v4AssignMode")) {
  559. if (j->u.object.values[k].value->type == json_string) {
  560. if (sqlite3_prepare_v2(_db,"UPDATE Network SET v4AssignMode = ? WHERE id = ?",-1,&stmt,(const char **)0) == SQLITE_OK)
  561. sqlite3_bind_text(stmt,1,j->u.object.values[k].value->u.string.ptr,-1,SQLITE_STATIC);
  562. }
  563. } else if (!strcmp(j->u.object.values[k].name,"v6AssignMode")) {
  564. if (j->u.object.values[k].value->type == json_string) {
  565. if (sqlite3_prepare_v2(_db,"UPDATE Network SET v6AssignMode = ? WHERE id = ?",-1,&stmt,(const char **)0) == SQLITE_OK)
  566. sqlite3_bind_text(stmt,1,j->u.object.values[k].value->u.string.ptr,-1,SQLITE_STATIC);
  567. }
  568. } else if (!strcmp(j->u.object.values[k].name,"multicastLimit")) {
  569. if (j->u.object.values[k].value->type == json_integer) {
  570. if (sqlite3_prepare_v2(_db,"UPDATE Network SET multicastLimit = ? WHERE id = ?",-1,&stmt,(const char **)0) == SQLITE_OK)
  571. sqlite3_bind_int(stmt,1,(int)j->u.object.values[k].value->u.integer);
  572. }
  573. } else if (!strcmp(j->u.object.values[k].name,"relays")) {
  574. if (j->u.object.values[k].value->type == json_array) {
  575. std::map<Address,InetAddress> nodeIdToPhyAddress;
  576. for(unsigned int kk=0;kk<j->u.object.values[k].value->u.array.length;++kk) {
  577. json_value *relay = j->u.object.values[k].value->u.array.values[kk];
  578. const char *address = (const char *)0;
  579. const char *phyAddress = (const char *)0;
  580. if ((relay)&&(relay->type == json_object)) {
  581. for(unsigned int rk=0;rk<relay->u.object.length;++rk) {
  582. if ((!strcmp(relay->u.object.values[rk].name,"address"))&&(relay->u.object.values[rk].value->type == json_string))
  583. address = relay->u.object.values[rk].value->u.string.ptr;
  584. else if ((!strcmp(relay->u.object.values[rk].name,"phyAddress"))&&(relay->u.object.values[rk].value->type == json_string))
  585. phyAddress = relay->u.object.values[rk].value->u.string.ptr;
  586. }
  587. }
  588. if ((address)&&(phyAddress))
  589. nodeIdToPhyAddress[Address(address)] = InetAddress(phyAddress);
  590. }
  591. sqlite3_reset(_sDeleteRelaysForNetwork);
  592. sqlite3_bind_text(_sDeleteRelaysForNetwork,1,nwids,16,SQLITE_STATIC);
  593. sqlite3_step(_sDeleteRelaysForNetwork);
  594. for(std::map<Address,InetAddress>::iterator rl(nodeIdToPhyAddress.begin());rl!=nodeIdToPhyAddress.end();++rl) {
  595. sqlite3_reset(_sCreateRelay);
  596. sqlite3_bind_text(_sCreateRelay,1,nwids,16,SQLITE_STATIC);
  597. std::string a(rl->first.toString()),b(rl->second.toString()); // don't destroy strings until sqlite3_step()
  598. sqlite3_bind_text(_sCreateRelay,2,a.c_str(),-1,SQLITE_STATIC);
  599. sqlite3_bind_text(_sCreateRelay,3,b.c_str(),-1,SQLITE_STATIC);
  600. sqlite3_step(_sCreateRelay);
  601. }
  602. }
  603. } else if (!strcmp(j->u.object.values[k].name,"gateways")) {
  604. sqlite3_reset(_sDeleteGateways);
  605. sqlite3_bind_text(_sDeleteGateways,1,nwids,16,SQLITE_STATIC);
  606. sqlite3_step(_sDeleteGateways);
  607. if (j->u.object.values[k].value->type == json_array) {
  608. for(unsigned int kk=0;kk<j->u.object.values[k].value->u.array.length;++kk) {
  609. json_value *gateway = j->u.object.values[k].value->u.array.values[kk];
  610. if ((gateway)&&(gateway->type == json_string)) {
  611. InetAddress gwip(gateway->u.string.ptr);
  612. sqlite3_reset(_sCreateGateway);
  613. sqlite3_bind_text(_sCreateGateway,1,nwids,16,SQLITE_STATIC);
  614. sqlite3_bind_int(_sCreateGateway,4,(int)gwip.metric());
  615. if (gwip.ss_family == AF_INET) {
  616. char ipBlob[16];
  617. memset(ipBlob,0,12);
  618. memcpy(ipBlob + 12,gwip.rawIpData(),4);
  619. sqlite3_bind_blob(_sCreateGateway,2,(const void *)ipBlob,16,SQLITE_STATIC);
  620. sqlite3_bind_int(_sCreateGateway,3,4);
  621. sqlite3_step(_sCreateGateway);
  622. } else if (gwip.ss_family == AF_INET6) {
  623. sqlite3_bind_blob(_sCreateGateway,2,gwip.rawIpData(),16,SQLITE_STATIC);
  624. sqlite3_bind_int(_sCreateGateway,3,6);
  625. sqlite3_step(_sCreateGateway);
  626. }
  627. }
  628. }
  629. }
  630. } else if (!strcmp(j->u.object.values[k].name,"ipLocalRoutes")) {
  631. sqlite3_reset(_sDeleteLocalRoutes);
  632. sqlite3_bind_text(_sDeleteLocalRoutes,1,nwids,16,SQLITE_STATIC);
  633. sqlite3_bind_int(_sDeleteLocalRoutes,2,(int)ZT_IP_ASSIGNMENT_TYPE_NETWORK);
  634. sqlite3_step(_sDeleteLocalRoutes);
  635. if (j->u.object.values[k].value->type == json_array) {
  636. for(unsigned int kk=0;kk<j->u.object.values[k].value->u.array.length;++kk) {
  637. json_value *localRoute = j->u.object.values[k].value->u.array.values[kk];
  638. if ((localRoute)&&(localRoute->type == json_string)) {
  639. InetAddress lr(localRoute->u.string.ptr);
  640. if (lr.ss_family == AF_INET) {
  641. char ipBlob[16];
  642. memset(ipBlob,0,12);
  643. memcpy(ipBlob + 12,lr.rawIpData(),4);
  644. sqlite3_reset(_sAllocateIp);
  645. sqlite3_bind_text(_sAllocateIp,1,nwids,16,SQLITE_STATIC);
  646. sqlite3_bind_null(_sAllocateIp,2);
  647. sqlite3_bind_int(_sAllocateIp,3,(int)ZT_IP_ASSIGNMENT_TYPE_NETWORK);
  648. sqlite3_bind_blob(_sAllocateIp,4,(const void *)ipBlob,16,SQLITE_STATIC);
  649. sqlite3_bind_int(_sAllocateIp,5,lr.netmaskBits());
  650. sqlite3_bind_int(_sAllocateIp,6,4);
  651. sqlite3_step(_sAllocateIp);
  652. } else if (lr.ss_family == AF_INET6) {
  653. sqlite3_reset(_sAllocateIp);
  654. sqlite3_bind_text(_sAllocateIp,1,nwids,16,SQLITE_STATIC);
  655. sqlite3_bind_null(_sAllocateIp,2);
  656. sqlite3_bind_int(_sAllocateIp,3,(int)ZT_IP_ASSIGNMENT_TYPE_NETWORK);
  657. sqlite3_bind_blob(_sAllocateIp,4,lr.rawIpData(),16,SQLITE_STATIC);
  658. sqlite3_bind_int(_sAllocateIp,5,lr.netmaskBits());
  659. sqlite3_bind_int(_sAllocateIp,6,6);
  660. sqlite3_step(_sAllocateIp);
  661. }
  662. }
  663. }
  664. }
  665. } else if (!strcmp(j->u.object.values[k].name,"ipAssignmentPools")) {
  666. if (j->u.object.values[k].value->type == json_array) {
  667. std::vector< std::pair<InetAddress,InetAddress> > pools;
  668. for(unsigned int kk=0;kk<j->u.object.values[k].value->u.array.length;++kk) {
  669. json_value *pool = j->u.object.values[k].value->u.array.values[kk];
  670. const char *iprs = (const char *)0;
  671. const char *ipre = (const char *)0;
  672. if ((pool)&&(pool->type == json_object)) {
  673. for(unsigned int rk=0;rk<pool->u.object.length;++rk) {
  674. if ((!strcmp(pool->u.object.values[rk].name,"ipRangeStart"))&&(pool->u.object.values[rk].value->type == json_string))
  675. iprs = pool->u.object.values[rk].value->u.string.ptr;
  676. else if ((!strcmp(pool->u.object.values[rk].name,"ipRangeEnd"))&&(pool->u.object.values[rk].value->type == json_string))
  677. ipre = pool->u.object.values[rk].value->u.string.ptr;
  678. }
  679. }
  680. if ((iprs)&&(ipre)) {
  681. InetAddress iprs2(iprs);
  682. InetAddress ipre2(ipre);
  683. if (iprs2.ss_family == ipre2.ss_family) {
  684. iprs2.setPort(0);
  685. ipre2.setPort(0);
  686. pools.push_back(std::pair<InetAddress,InetAddress>(iprs2,ipre2));
  687. }
  688. }
  689. }
  690. std::sort(pools.begin(),pools.end());
  691. pools.erase(std::unique(pools.begin(),pools.end()),pools.end());
  692. sqlite3_reset(_sDeleteIpAssignmentPoolsForNetwork);
  693. sqlite3_bind_text(_sDeleteIpAssignmentPoolsForNetwork,1,nwids,16,SQLITE_STATIC);
  694. sqlite3_step(_sDeleteIpAssignmentPoolsForNetwork);
  695. for(std::vector< std::pair<InetAddress,InetAddress> >::const_iterator p(pools.begin());p!=pools.end();++p) {
  696. char ipBlob1[16],ipBlob2[16];
  697. sqlite3_reset(_sCreateIpAssignmentPool);
  698. sqlite3_bind_text(_sCreateIpAssignmentPool,1,nwids,16,SQLITE_STATIC);
  699. if (p->first.ss_family == AF_INET) {
  700. memset(ipBlob1,0,12);
  701. memcpy(ipBlob1 + 12,p->first.rawIpData(),4);
  702. memset(ipBlob2,0,12);
  703. memcpy(ipBlob2 + 12,p->second.rawIpData(),4);
  704. sqlite3_bind_blob(_sCreateIpAssignmentPool,2,(const void *)ipBlob1,16,SQLITE_STATIC);
  705. sqlite3_bind_blob(_sCreateIpAssignmentPool,3,(const void *)ipBlob2,16,SQLITE_STATIC);
  706. sqlite3_bind_int(_sCreateIpAssignmentPool,4,4);
  707. } else if (p->first.ss_family == AF_INET6) {
  708. sqlite3_bind_blob(_sCreateIpAssignmentPool,2,p->first.rawIpData(),16,SQLITE_STATIC);
  709. sqlite3_bind_blob(_sCreateIpAssignmentPool,3,p->second.rawIpData(),16,SQLITE_STATIC);
  710. sqlite3_bind_int(_sCreateIpAssignmentPool,4,6);
  711. } else continue;
  712. sqlite3_step(_sCreateIpAssignmentPool);
  713. }
  714. }
  715. } else if (!strcmp(j->u.object.values[k].name,"rules")) {
  716. if (j->u.object.values[k].value->type == json_array) {
  717. sqlite3_reset(_sDeleteRulesForNetwork);
  718. sqlite3_bind_text(_sDeleteRulesForNetwork,1,nwids,16,SQLITE_STATIC);
  719. sqlite3_step(_sDeleteRulesForNetwork);
  720. for(unsigned int kk=0;kk<j->u.object.values[k].value->u.array.length;++kk) {
  721. json_value *rj = j->u.object.values[k].value->u.array.values[kk];
  722. if ((rj)&&(rj->type == json_object)) {
  723. struct { // NULL pointers indicate missing or NULL -- wildcards
  724. const json_int_t *ruleNo;
  725. const char *nodeId;
  726. const char *sourcePort;
  727. const char *destPort;
  728. const json_int_t *vlanId;
  729. const json_int_t *vlanPcp;
  730. const json_int_t *etherType;
  731. const char *macSource;
  732. const char *macDest;
  733. const char *ipSource;
  734. const char *ipDest;
  735. const json_int_t *ipTos;
  736. const json_int_t *ipProtocol;
  737. const json_int_t *ipSourcePort;
  738. const json_int_t *ipDestPort;
  739. const json_int_t *flags;
  740. const json_int_t *invFlags;
  741. const char *action;
  742. } rule;
  743. memset(&rule,0,sizeof(rule));
  744. for(unsigned int rk=0;rk<rj->u.object.length;++rk) {
  745. if ((!strcmp(rj->u.object.values[rk].name,"ruleNo"))&&(rj->u.object.values[rk].value->type == json_integer))
  746. rule.ruleNo = &(rj->u.object.values[rk].value->u.integer);
  747. else if ((!strcmp(rj->u.object.values[rk].name,"nodeId"))&&(rj->u.object.values[rk].value->type == json_string))
  748. rule.nodeId = rj->u.object.values[rk].value->u.string.ptr;
  749. else if ((!strcmp(rj->u.object.values[rk].name,"sourcePort"))&&(rj->u.object.values[rk].value->type == json_string))
  750. rule.sourcePort = rj->u.object.values[rk].value->u.string.ptr;
  751. else if ((!strcmp(rj->u.object.values[rk].name,"destPort"))&&(rj->u.object.values[rk].value->type == json_string))
  752. rule.destPort = rj->u.object.values[rk].value->u.string.ptr;
  753. else if ((!strcmp(rj->u.object.values[rk].name,"vlanId"))&&(rj->u.object.values[rk].value->type == json_integer))
  754. rule.vlanId = &(rj->u.object.values[rk].value->u.integer);
  755. else if ((!strcmp(rj->u.object.values[rk].name,"vlanPcp"))&&(rj->u.object.values[rk].value->type == json_integer))
  756. rule.vlanPcp = &(rj->u.object.values[rk].value->u.integer);
  757. else if ((!strcmp(rj->u.object.values[rk].name,"etherType"))&&(rj->u.object.values[rk].value->type == json_integer))
  758. rule.etherType = &(rj->u.object.values[rk].value->u.integer);
  759. else if ((!strcmp(rj->u.object.values[rk].name,"macSource"))&&(rj->u.object.values[rk].value->type == json_string))
  760. rule.macSource = rj->u.object.values[rk].value->u.string.ptr;
  761. else if ((!strcmp(rj->u.object.values[rk].name,"macDest"))&&(rj->u.object.values[rk].value->type == json_string))
  762. rule.macDest = rj->u.object.values[rk].value->u.string.ptr;
  763. else if ((!strcmp(rj->u.object.values[rk].name,"ipSource"))&&(rj->u.object.values[rk].value->type == json_string))
  764. rule.ipSource = rj->u.object.values[rk].value->u.string.ptr;
  765. else if ((!strcmp(rj->u.object.values[rk].name,"ipDest"))&&(rj->u.object.values[rk].value->type == json_string))
  766. rule.ipDest = rj->u.object.values[rk].value->u.string.ptr;
  767. else if ((!strcmp(rj->u.object.values[rk].name,"ipTos"))&&(rj->u.object.values[rk].value->type == json_integer))
  768. rule.ipTos = &(rj->u.object.values[rk].value->u.integer);
  769. else if ((!strcmp(rj->u.object.values[rk].name,"ipProtocol"))&&(rj->u.object.values[rk].value->type == json_integer))
  770. rule.ipProtocol = &(rj->u.object.values[rk].value->u.integer);
  771. else if ((!strcmp(rj->u.object.values[rk].name,"ipSourcePort"))&&(rj->u.object.values[rk].value->type == json_integer))
  772. rule.ipSourcePort = &(rj->u.object.values[rk].value->u.integer);
  773. else if ((!strcmp(rj->u.object.values[rk].name,"ipDestPort"))&&(rj->u.object.values[rk].value->type == json_integer))
  774. rule.ipDestPort = &(rj->u.object.values[rk].value->u.integer);
  775. else if ((!strcmp(rj->u.object.values[rk].name,"flags"))&&(rj->u.object.values[rk].value->type == json_integer))
  776. rule.flags = &(rj->u.object.values[rk].value->u.integer);
  777. else if ((!strcmp(rj->u.object.values[rk].name,"invFlags"))&&(rj->u.object.values[rk].value->type == json_integer))
  778. rule.invFlags = &(rj->u.object.values[rk].value->u.integer);
  779. else if ((!strcmp(rj->u.object.values[rk].name,"action"))&&(rj->u.object.values[rk].value->type == json_string))
  780. rule.action = rj->u.object.values[rk].value->u.string.ptr;
  781. }
  782. if ((rule.ruleNo)&&(rule.action)&&(rule.action[0])) {
  783. char mactmp1[16],mactmp2[16];
  784. sqlite3_reset(_sCreateRule);
  785. sqlite3_bind_text(_sCreateRule,1,nwids,16,SQLITE_STATIC);
  786. sqlite3_bind_int64(_sCreateRule,2,*rule.ruleNo);
  787. // Optional values: null by default
  788. for(int i=3;i<=18;++i)
  789. sqlite3_bind_null(_sCreateRule,i);
  790. if ((rule.nodeId)&&(strlen(rule.nodeId) == 10)) sqlite3_bind_text(_sCreateRule,3,rule.nodeId,10,SQLITE_STATIC);
  791. if ((rule.sourcePort)&&(strlen(rule.sourcePort) == 10)) sqlite3_bind_text(_sCreateRule,4,rule.sourcePort,10,SQLITE_STATIC);
  792. if ((rule.destPort)&&(strlen(rule.destPort) == 10)) sqlite3_bind_text(_sCreateRule,5,rule.destPort,10,SQLITE_STATIC);
  793. if (rule.vlanId) sqlite3_bind_int(_sCreateRule,6,(int)*rule.vlanId);
  794. if (rule.vlanPcp) sqlite3_bind_int(_sCreateRule,7,(int)*rule.vlanPcp);
  795. if (rule.etherType) sqlite3_bind_int(_sCreateRule,8,(int)*rule.etherType & (int)0xffff);
  796. if (rule.macSource) {
  797. MAC m(rule.macSource);
  798. Utils::snprintf(mactmp1,sizeof(mactmp1),"%.12llx",(unsigned long long)m.toInt());
  799. sqlite3_bind_text(_sCreateRule,9,mactmp1,-1,SQLITE_STATIC);
  800. }
  801. if (rule.macDest) {
  802. MAC m(rule.macDest);
  803. Utils::snprintf(mactmp2,sizeof(mactmp2),"%.12llx",(unsigned long long)m.toInt());
  804. sqlite3_bind_text(_sCreateRule,10,mactmp2,-1,SQLITE_STATIC);
  805. }
  806. if (rule.ipSource) sqlite3_bind_text(_sCreateRule,11,rule.ipSource,-1,SQLITE_STATIC);
  807. if (rule.ipDest) sqlite3_bind_text(_sCreateRule,12,rule.ipDest,-1,SQLITE_STATIC);
  808. if (rule.ipTos) sqlite3_bind_int(_sCreateRule,13,(int)*rule.ipTos);
  809. if (rule.ipProtocol) sqlite3_bind_int(_sCreateRule,14,(int)*rule.ipProtocol);
  810. if (rule.ipSourcePort) sqlite3_bind_int(_sCreateRule,15,(int)*rule.ipSourcePort & (int)0xffff);
  811. if (rule.ipDestPort) sqlite3_bind_int(_sCreateRule,16,(int)*rule.ipDestPort & (int)0xffff);
  812. if (rule.flags) sqlite3_bind_int64(_sCreateRule,17,(int64_t)*rule.flags);
  813. if (rule.invFlags) sqlite3_bind_int64(_sCreateRule,18,(int64_t)*rule.invFlags);
  814. sqlite3_bind_text(_sCreateRule,19,rule.action,-1,SQLITE_STATIC);
  815. sqlite3_step(_sCreateRule);
  816. }
  817. }
  818. }
  819. }
  820. }
  821. if (stmt) {
  822. sqlite3_bind_text(stmt,2,nwids,16,SQLITE_STATIC);
  823. sqlite3_step(stmt);
  824. sqlite3_finalize(stmt);
  825. }
  826. }
  827. }
  828. json_value_free(j);
  829. }
  830. sqlite3_reset(_sSetNetworkRevision);
  831. sqlite3_bind_int64(_sSetNetworkRevision,1,revision += 1);
  832. sqlite3_bind_text(_sSetNetworkRevision,2,nwids,16,SQLITE_STATIC);
  833. sqlite3_step(_sSetNetworkRevision);
  834. return _doCPGet(path_copy,urlArgs,headers,body,responseBody,responseContentType);
  835. }
  836. } // else 404
  837. } // else 404
  838. return 404;
  839. }
  840. unsigned int SqliteNetworkController::handleControlPlaneHttpDELETE(
  841. const std::vector<std::string> &path,
  842. const std::map<std::string,std::string> &urlArgs,
  843. const std::map<std::string,std::string> &headers,
  844. const std::string &body,
  845. std::string &responseBody,
  846. std::string &responseContentType)
  847. {
  848. if (path.empty())
  849. return 404;
  850. Mutex::Lock _l(_lock);
  851. if (path[0] == "network") {
  852. if ((path.size() >= 2)&&(path[1].length() == 16)) {
  853. uint64_t nwid = Utils::hexStrToU64(path[1].c_str());
  854. char nwids[24];
  855. Utils::snprintf(nwids,sizeof(nwids),"%.16llx",(unsigned long long)nwid);
  856. sqlite3_reset(_sGetNetworkById);
  857. sqlite3_bind_text(_sGetNetworkById,1,nwids,16,SQLITE_STATIC);
  858. if (sqlite3_step(_sGetNetworkById) != SQLITE_ROW)
  859. return 404;
  860. if (path.size() >= 3) {
  861. if ((path.size() == 4)&&(path[2] == "member")&&(path[3].length() == 10)) {
  862. uint64_t address = Utils::hexStrToU64(path[3].c_str());
  863. char addrs[24];
  864. Utils::snprintf(addrs,sizeof(addrs),"%.10llx",address);
  865. sqlite3_reset(_sGetMember);
  866. sqlite3_bind_text(_sGetMember,1,nwids,16,SQLITE_STATIC);
  867. sqlite3_bind_text(_sGetMember,2,addrs,10,SQLITE_STATIC);
  868. if (sqlite3_step(_sGetMember) != SQLITE_ROW)
  869. return 404;
  870. sqlite3_reset(_sDeleteIpAllocations);
  871. sqlite3_bind_text(_sDeleteIpAllocations,1,nwids,16,SQLITE_STATIC);
  872. sqlite3_bind_text(_sDeleteIpAllocations,2,addrs,10,SQLITE_STATIC);
  873. sqlite3_bind_int(_sDeleteIpAllocations,3,(int)ZT_IP_ASSIGNMENT_TYPE_ADDRESS);
  874. if (sqlite3_step(_sDeleteIpAllocations) == SQLITE_DONE) {
  875. sqlite3_reset(_sDeleteMember);
  876. sqlite3_bind_text(_sDeleteMember,1,nwids,16,SQLITE_STATIC);
  877. sqlite3_bind_text(_sDeleteMember,2,addrs,10,SQLITE_STATIC);
  878. if (sqlite3_step(_sDeleteMember) != SQLITE_DONE)
  879. return 500;
  880. } else return 500;
  881. return 200;
  882. }
  883. } else {
  884. sqlite3_reset(_sDeleteNetwork);
  885. sqlite3_bind_text(_sDeleteNetwork,1,nwids,16,SQLITE_STATIC);
  886. if (sqlite3_step(_sDeleteNetwork) == SQLITE_DONE) {
  887. sqlite3_reset(_sDeleteAllNetworkMembers);
  888. sqlite3_bind_text(_sDeleteAllNetworkMembers,1,nwids,16,SQLITE_STATIC);
  889. sqlite3_step(_sDeleteAllNetworkMembers);
  890. return 200;
  891. } else return 500;
  892. }
  893. } // else 404
  894. } // else 404
  895. return 404;
  896. }
  897. void SqliteNetworkController::threadMain()
  898. throw()
  899. {
  900. uint64_t lastBackupTime = 0;
  901. while (_backupThreadRun) {
  902. if ((OSUtils::now() - lastBackupTime) >= ZT_NETCONF_BACKUP_PERIOD) {
  903. lastBackupTime = OSUtils::now();
  904. char backupPath[4096],backupPath2[4096];
  905. Utils::snprintf(backupPath,sizeof(backupPath),"%s.backupInProgress",_dbPath.c_str());
  906. Utils::snprintf(backupPath2,sizeof(backupPath),"%s.backup",_dbPath.c_str());
  907. OSUtils::rm(backupPath); // delete any unfinished backups
  908. sqlite3 *bakdb = (sqlite3 *)0;
  909. sqlite3_backup *bak = (sqlite3_backup *)0;
  910. if (sqlite3_open_v2(backupPath,&bakdb,SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE,(const char *)0) != SQLITE_OK) {
  911. fprintf(stderr,"SqliteNetworkController: CRITICAL: backup failed on sqlite3_open_v2()"ZT_EOL_S);
  912. continue;
  913. }
  914. bak = sqlite3_backup_init(bakdb,"main",_db,"main");
  915. if (!bak) {
  916. sqlite3_close(bakdb);
  917. OSUtils::rm(backupPath); // delete any unfinished backups
  918. fprintf(stderr,"SqliteNetworkController: CRITICAL: backup failed on sqlite3_backup_init()"ZT_EOL_S);
  919. continue;
  920. }
  921. int rc = SQLITE_OK;
  922. for(;;) {
  923. if (!_backupThreadRun) {
  924. sqlite3_backup_finish(bak);
  925. sqlite3_close(bakdb);
  926. OSUtils::rm(backupPath);
  927. return;
  928. }
  929. _lock.lock();
  930. rc = sqlite3_backup_step(bak,64);
  931. _lock.unlock();
  932. if ((rc == SQLITE_OK)||(rc == SQLITE_LOCKED)||(rc == SQLITE_BUSY))
  933. Thread::sleep(50);
  934. else break;
  935. }
  936. sqlite3_backup_finish(bak);
  937. sqlite3_close(bakdb);
  938. OSUtils::rm(backupPath2);
  939. ::rename(backupPath,backupPath2);
  940. }
  941. Thread::sleep(250);
  942. }
  943. }
  944. unsigned int SqliteNetworkController::_doCPGet(
  945. const std::vector<std::string> &path,
  946. const std::map<std::string,std::string> &urlArgs,
  947. const std::map<std::string,std::string> &headers,
  948. const std::string &body,
  949. std::string &responseBody,
  950. std::string &responseContentType)
  951. {
  952. // Assumes _lock is locked
  953. char json[65536];
  954. if ((path.size() > 0)&&(path[0] == "network")) {
  955. if ((path.size() >= 2)&&(path[1].length() == 16)) {
  956. uint64_t nwid = Utils::hexStrToU64(path[1].c_str());
  957. char nwids[24];
  958. Utils::snprintf(nwids,sizeof(nwids),"%.16llx",(unsigned long long)nwid);
  959. if (path.size() >= 3) {
  960. // /network/<nwid>/...
  961. if (path[2] == "member") {
  962. if (path.size() >= 4) {
  963. // Get specific member info
  964. uint64_t address = Utils::hexStrToU64(path[3].c_str());
  965. char addrs[24];
  966. Utils::snprintf(addrs,sizeof(addrs),"%.10llx",address);
  967. sqlite3_reset(_sGetMember2);
  968. sqlite3_bind_text(_sGetMember2,1,nwids,16,SQLITE_STATIC);
  969. sqlite3_bind_text(_sGetMember2,2,addrs,10,SQLITE_STATIC);
  970. if (sqlite3_step(_sGetMember2) == SQLITE_ROW) {
  971. const char *memberIdStr = (const char *)sqlite3_column_text(_sGetMember2,3);
  972. // If testSingingId is included in the URL or X-ZT1-TestSigningId in the headers
  973. // and if it contains an identity with a secret portion, the resturned JSON
  974. // will contain an extra field called _testConf. This will contain several
  975. // fields that report the result of doNetworkConfigRequest() for this member.
  976. std::string testFields;
  977. {
  978. Identity testOutputSigningId;
  979. std::map<std::string,std::string>::const_iterator sid(urlArgs.find("testSigningId"));
  980. if (sid != urlArgs.end()) {
  981. testOutputSigningId.fromString(sid->second.c_str());
  982. } else {
  983. sid = headers.find("x-zt1-testsigningid");
  984. if (sid != headers.end())
  985. testOutputSigningId.fromString(sid->second.c_str());
  986. }
  987. if ((testOutputSigningId.hasPrivate())&&(memberIdStr)) {
  988. Dictionary testNetconf;
  989. NetworkController::ResultCode rc = this->_doNetworkConfigRequest(
  990. InetAddress(),
  991. testOutputSigningId,
  992. Identity(memberIdStr),
  993. nwid,
  994. Dictionary(), // TODO: allow passing of meta-data for testing
  995. testNetconf);
  996. char rcs[16];
  997. Utils::snprintf(rcs,sizeof(rcs),"%d,\n",(int)rc);
  998. testFields.append("\t\"_test\": {\n");
  999. testFields.append("\t\t\"resultCode\": "); testFields.append(rcs);
  1000. testFields.append("\t\t\"result\": \""); testFields.append(_jsonEscape(testNetconf.toString().c_str()).c_str()); testFields.append("\",\n");
  1001. testFields.append("\t\t\"resultJson\": {\n");
  1002. for(Dictionary::const_iterator i(testNetconf.begin());i!=testNetconf.end();++i) {
  1003. if (i != testNetconf.begin())
  1004. testFields.append(",\n");
  1005. testFields.append("\t\t\t\"");
  1006. testFields.append(i->first);
  1007. testFields.append("\": \"");
  1008. testFields.append(_jsonEscape(i->second.c_str()));
  1009. testFields.push_back('"');
  1010. }
  1011. testFields.append("\n\t\t}\n");
  1012. testFields.append("\t},\n");
  1013. }
  1014. }
  1015. Utils::snprintf(json,sizeof(json),
  1016. "{\n%s"
  1017. "\t\"nwid\": \"%s\",\n"
  1018. "\t\"address\": \"%s\",\n"
  1019. "\t\"controllerInstanceId\": \"%s\",\n"
  1020. "\t\"authorized\": %s,\n"
  1021. "\t\"activeBridge\": %s,\n"
  1022. "\t\"memberRevision\": %llu,\n"
  1023. "\t\"clock\": %llu,\n"
  1024. "\t\"identity\": \"%s\",\n"
  1025. "\t\"ipAssignments\": [",
  1026. testFields.c_str(),
  1027. nwids,
  1028. addrs,
  1029. _instanceId.c_str(),
  1030. (sqlite3_column_int(_sGetMember2,0) > 0) ? "true" : "false",
  1031. (sqlite3_column_int(_sGetMember2,1) > 0) ? "true" : "false",
  1032. (unsigned long long)sqlite3_column_int64(_sGetMember2,2),
  1033. (unsigned long long)OSUtils::now(),
  1034. _jsonEscape(memberIdStr).c_str());
  1035. responseBody = json;
  1036. sqlite3_reset(_sGetIpAssignmentsForNode2);
  1037. sqlite3_bind_text(_sGetIpAssignmentsForNode2,1,nwids,16,SQLITE_STATIC);
  1038. sqlite3_bind_text(_sGetIpAssignmentsForNode2,2,addrs,10,SQLITE_STATIC);
  1039. sqlite3_bind_int(_sGetIpAssignmentsForNode2,3,(int)ZT_IP_ASSIGNMENT_TYPE_ADDRESS);
  1040. bool firstIp = true;
  1041. while (sqlite3_step(_sGetIpAssignmentsForNode2) == SQLITE_ROW) {
  1042. int ipversion = sqlite3_column_int(_sGetIpAssignmentsForNode2,2);
  1043. char ipBlob[16];
  1044. memcpy(ipBlob,(const void *)sqlite3_column_blob(_sGetIpAssignmentsForNode2,0),16);
  1045. InetAddress ip(
  1046. (const void *)(ipversion == 6 ? ipBlob : &ipBlob[12]),
  1047. (ipversion == 6 ? 16 : 4),
  1048. (unsigned int)sqlite3_column_int(_sGetIpAssignmentsForNode2,1)
  1049. );
  1050. responseBody.append(firstIp ? "\"" : ",\"");
  1051. firstIp = false;
  1052. responseBody.append(_jsonEscape(ip.toString()));
  1053. responseBody.push_back('"');
  1054. }
  1055. responseBody.append("],\n\t\"recentLog\": [");
  1056. {
  1057. std::map< std::pair<Address,uint64_t>,_LLEntry >::const_iterator lli(_lastLog.find(std::pair<Address,uint64_t>(Address(address),nwid)));
  1058. if (lli != _lastLog.end()) {
  1059. const _LLEntry &lastLogEntry = lli->second;
  1060. uint64_t eptr = lastLogEntry.totalRequests;
  1061. for(int k=0;k<ZT_SQLITENETWORKCONTROLLER_IN_MEMORY_LOG_SIZE;++k) {
  1062. if (!eptr--)
  1063. break;
  1064. const unsigned long ptr = (unsigned long)eptr % ZT_SQLITENETWORKCONTROLLER_IN_MEMORY_LOG_SIZE;
  1065. char tsbuf[64];
  1066. Utils::snprintf(tsbuf,sizeof(tsbuf),"%llu",(unsigned long long)lastLogEntry.l[ptr].ts);
  1067. responseBody.append((k == 0) ? "{" : ",{");
  1068. responseBody.append("\"ts\":");
  1069. responseBody.append(tsbuf);
  1070. responseBody.append(lastLogEntry.l[ptr].authorized ? ",\"authorized\":false,\"version\":" : ",\"authorized\":true,\"version\":");
  1071. if (lastLogEntry.l[ptr].version[0]) {
  1072. responseBody.push_back('"');
  1073. responseBody.append(_jsonEscape(lastLogEntry.l[ptr].version));
  1074. responseBody.append("\",\"fromAddr\":");
  1075. } else responseBody.append("null,\"fromAddr\":");
  1076. if (lastLogEntry.l[ptr].fromAddr) {
  1077. responseBody.push_back('"');
  1078. responseBody.append(_jsonEscape(lastLogEntry.l[ptr].fromAddr.toString()));
  1079. responseBody.append("\"}");
  1080. } else responseBody.append("null}");
  1081. }
  1082. }
  1083. }
  1084. responseBody.append("]\n}\n");
  1085. responseContentType = "application/json";
  1086. return 200;
  1087. } // else 404
  1088. } else {
  1089. // List members
  1090. sqlite3_reset(_sListNetworkMembers);
  1091. sqlite3_bind_text(_sListNetworkMembers,1,nwids,16,SQLITE_STATIC);
  1092. responseBody.append("{");
  1093. bool firstMember = true;
  1094. while (sqlite3_step(_sListNetworkMembers) == SQLITE_ROW) {
  1095. responseBody.append(firstMember ? "\"" : ",\"");
  1096. firstMember = false;
  1097. responseBody.append((const char *)sqlite3_column_text(_sListNetworkMembers,0));
  1098. responseBody.append("\":");
  1099. responseBody.append((const char *)sqlite3_column_text(_sListNetworkMembers,1));
  1100. }
  1101. responseBody.push_back('}');
  1102. responseContentType = "application/json";
  1103. return 200;
  1104. }
  1105. } // else 404
  1106. } else {
  1107. // get network info
  1108. sqlite3_reset(_sGetNetworkById);
  1109. sqlite3_bind_text(_sGetNetworkById,1,nwids,16,SQLITE_STATIC);
  1110. if (sqlite3_step(_sGetNetworkById) == SQLITE_ROW) {
  1111. Utils::snprintf(json,sizeof(json),
  1112. "{\n"
  1113. "\t\"nwid\": \"%s\",\n"
  1114. "\t\"controllerInstanceId\": \"%s\",\n"
  1115. "\t\"clock\": %llu,\n"
  1116. "\t\"name\": \"%s\",\n"
  1117. "\t\"private\": %s,\n"
  1118. "\t\"enableBroadcast\": %s,\n"
  1119. "\t\"allowPassiveBridging\": %s,\n"
  1120. "\t\"v4AssignMode\": \"%s\",\n"
  1121. "\t\"v6AssignMode\": \"%s\",\n"
  1122. "\t\"multicastLimit\": %d,\n"
  1123. "\t\"creationTime\": %llu,\n"
  1124. "\t\"revision\": %llu,\n"
  1125. "\t\"memberRevisionCounter\": %llu,\n"
  1126. "\t\"authorizedMemberCount\": %llu,\n"
  1127. "\t\"relays\": [",
  1128. nwids,
  1129. _instanceId.c_str(),
  1130. (unsigned long long)OSUtils::now(),
  1131. _jsonEscape((const char *)sqlite3_column_text(_sGetNetworkById,0)).c_str(),
  1132. (sqlite3_column_int(_sGetNetworkById,1) > 0) ? "true" : "false",
  1133. (sqlite3_column_int(_sGetNetworkById,2) > 0) ? "true" : "false",
  1134. (sqlite3_column_int(_sGetNetworkById,3) > 0) ? "true" : "false",
  1135. _jsonEscape((const char *)sqlite3_column_text(_sGetNetworkById,4)).c_str(),
  1136. _jsonEscape((const char *)sqlite3_column_text(_sGetNetworkById,5)).c_str(),
  1137. sqlite3_column_int(_sGetNetworkById,6),
  1138. (unsigned long long)sqlite3_column_int64(_sGetNetworkById,7),
  1139. (unsigned long long)sqlite3_column_int64(_sGetNetworkById,8),
  1140. (unsigned long long)sqlite3_column_int64(_sGetNetworkById,9),
  1141. (unsigned long long)sqlite3_column_int64(_sGetNetworkById,10));
  1142. responseBody = json;
  1143. sqlite3_reset(_sGetRelays);
  1144. sqlite3_bind_text(_sGetRelays,1,nwids,16,SQLITE_STATIC);
  1145. bool firstRelay = true;
  1146. while (sqlite3_step(_sGetRelays) == SQLITE_ROW) {
  1147. responseBody.append(firstRelay ? "\n\t\t" : ",\n\t\t");
  1148. firstRelay = false;
  1149. responseBody.append("{\"address\":\"");
  1150. responseBody.append((const char *)sqlite3_column_text(_sGetRelays,0));
  1151. responseBody.append("\",\"phyAddress\":\"");
  1152. responseBody.append(_jsonEscape((const char *)sqlite3_column_text(_sGetRelays,1)));
  1153. responseBody.append("\"}");
  1154. }
  1155. responseBody.append("],\n\t\"gateways\": [");
  1156. sqlite3_reset(_sGetGateways);
  1157. sqlite3_bind_text(_sGetGateways,1,nwids,16,SQLITE_STATIC);
  1158. bool firstGateway = true;
  1159. while (sqlite3_step(_sGetGateways) == SQLITE_ROW) {
  1160. char tmp[128];
  1161. const unsigned char *ip = (const unsigned char *)sqlite3_column_blob(_sGetGateways,0);
  1162. switch(sqlite3_column_int(_sGetGateways,1)) { // ipVersion
  1163. case 4:
  1164. Utils::snprintf(tmp,sizeof(tmp),"%s%d.%d.%d.%d/%d\"",
  1165. (firstGateway) ? "\"" : ",\"",
  1166. (int)ip[12],
  1167. (int)ip[13],
  1168. (int)ip[14],
  1169. (int)ip[15],
  1170. (int)sqlite3_column_int(_sGetGateways,2)); // metric
  1171. break;
  1172. case 6:
  1173. Utils::snprintf(tmp,sizeof(tmp),"%s%.2x%.2x:%.2x%.2x:%.2x%.2x:%.2x%.2x:%.2x%.2x:%.2x%.2x:%.2x%.2x:%.2x%.2x/%d\"",
  1174. (firstGateway) ? "\"" : ",\"",
  1175. (int)ip[0],
  1176. (int)ip[1],
  1177. (int)ip[2],
  1178. (int)ip[3],
  1179. (int)ip[4],
  1180. (int)ip[5],
  1181. (int)ip[6],
  1182. (int)ip[7],
  1183. (int)ip[8],
  1184. (int)ip[9],
  1185. (int)ip[10],
  1186. (int)ip[11],
  1187. (int)ip[12],
  1188. (int)ip[13],
  1189. (int)ip[14],
  1190. (int)ip[15],
  1191. (int)sqlite3_column_int(_sGetGateways,2)); // metric
  1192. break;
  1193. }
  1194. responseBody.append(tmp);
  1195. firstGateway = false;
  1196. }
  1197. responseBody.append("],\n\t\"ipLocalRoutes\": [");
  1198. sqlite3_reset(_sGetLocalRoutes);
  1199. sqlite3_bind_text(_sGetLocalRoutes,1,nwids,16,SQLITE_STATIC);
  1200. sqlite3_bind_int(_sGetLocalRoutes,2,(int)ZT_IP_ASSIGNMENT_TYPE_NETWORK);
  1201. bool firstLocalRoute = true;
  1202. while (sqlite3_step(_sGetLocalRoutes) == SQLITE_ROW) {
  1203. char tmp[128];
  1204. const unsigned char *ip = (const unsigned char *)sqlite3_column_blob(_sGetLocalRoutes,0);
  1205. switch (sqlite3_column_int(_sGetLocalRoutes,2)) {
  1206. case 4:
  1207. Utils::snprintf(tmp,sizeof(tmp),"%s%d.%d.%d.%d/%d\"",
  1208. (firstLocalRoute) ? "\"" : ",\"",
  1209. (int)ip[12],
  1210. (int)ip[13],
  1211. (int)ip[14],
  1212. (int)ip[15],
  1213. (int)sqlite3_column_int(_sGetLocalRoutes,1)); // netmask bits
  1214. break;
  1215. case 6:
  1216. Utils::snprintf(tmp,sizeof(tmp),"%s%.2x%.2x:%.2x%.2x:%.2x%.2x:%.2x%.2x:%.2x%.2x:%.2x%.2x:%.2x%.2x:%.2x%.2x/%d\"",
  1217. (firstLocalRoute) ? "\"" : ",\"",
  1218. (int)ip[0],
  1219. (int)ip[1],
  1220. (int)ip[2],
  1221. (int)ip[3],
  1222. (int)ip[4],
  1223. (int)ip[5],
  1224. (int)ip[6],
  1225. (int)ip[7],
  1226. (int)ip[8],
  1227. (int)ip[9],
  1228. (int)ip[10],
  1229. (int)ip[11],
  1230. (int)ip[12],
  1231. (int)ip[13],
  1232. (int)ip[14],
  1233. (int)ip[15],
  1234. (int)sqlite3_column_int(_sGetLocalRoutes,1)); // netmask bits
  1235. break;
  1236. }
  1237. responseBody.append(tmp);
  1238. firstLocalRoute = false;
  1239. }
  1240. responseBody.append("],\n\t\"ipAssignmentPools\": [");
  1241. sqlite3_reset(_sGetIpAssignmentPools2);
  1242. sqlite3_bind_text(_sGetIpAssignmentPools2,1,nwids,16,SQLITE_STATIC);
  1243. bool firstIpAssignmentPool = true;
  1244. while (sqlite3_step(_sGetIpAssignmentPools2) == SQLITE_ROW) {
  1245. const char *ipRangeStartB = reinterpret_cast<const char *>(sqlite3_column_blob(_sGetIpAssignmentPools2,0));
  1246. const char *ipRangeEndB = reinterpret_cast<const char *>(sqlite3_column_blob(_sGetIpAssignmentPools2,1));
  1247. if ((ipRangeStartB)&&(ipRangeEndB)) {
  1248. InetAddress ipps,ippe;
  1249. int ipVersion = sqlite3_column_int(_sGetIpAssignmentPools2,2);
  1250. if (ipVersion == 4) {
  1251. ipps.set((const void *)(ipRangeStartB + 12),4,0);
  1252. ippe.set((const void *)(ipRangeEndB + 12),4,0);
  1253. } else if (ipVersion == 6) {
  1254. ipps.set((const void *)ipRangeStartB,16,0);
  1255. ippe.set((const void *)ipRangeEndB,16,0);
  1256. }
  1257. if (ipps) {
  1258. responseBody.append(firstIpAssignmentPool ? "\n\t\t" : ",\n\t\t");
  1259. firstIpAssignmentPool = false;
  1260. Utils::snprintf(json,sizeof(json),"{\"ipRangeStart\":\"%s\",\"ipRangeEnd\":\"%s\"}",
  1261. _jsonEscape(ipps.toIpString()).c_str(),
  1262. _jsonEscape(ippe.toIpString()).c_str());
  1263. responseBody.append(json);
  1264. }
  1265. }
  1266. }
  1267. responseBody.append("],\n\t\"rules\": [");
  1268. sqlite3_reset(_sListRules);
  1269. sqlite3_bind_text(_sListRules,1,nwids,16,SQLITE_STATIC);
  1270. bool firstRule = true;
  1271. while (sqlite3_step(_sListRules) == SQLITE_ROW) {
  1272. responseBody.append(firstRule ? "\n\t{\n" : ",{\n");
  1273. firstRule = false;
  1274. Utils::snprintf(json,sizeof(json),"\t\t\"ruleNo\": %lld,\n",sqlite3_column_int64(_sListRules,0));
  1275. responseBody.append(json);
  1276. if (sqlite3_column_type(_sListRules,1) != SQLITE_NULL) {
  1277. Utils::snprintf(json,sizeof(json),"\t\t\"nodeId\": \"%s\",\n",(const char *)sqlite3_column_text(_sListRules,1));
  1278. responseBody.append(json);
  1279. }
  1280. if (sqlite3_column_type(_sListRules,2) != SQLITE_NULL) {
  1281. Utils::snprintf(json,sizeof(json),"\t\t\"sourcePort\": \"%s\",\n",(const char *)sqlite3_column_text(_sListRules,2));
  1282. responseBody.append(json);
  1283. }
  1284. if (sqlite3_column_type(_sListRules,3) != SQLITE_NULL) {
  1285. Utils::snprintf(json,sizeof(json),"\t\t\"destPort\": \"%s\",\n",(const char *)sqlite3_column_text(_sListRules,3));
  1286. responseBody.append(json);
  1287. }
  1288. if (sqlite3_column_type(_sListRules,4) != SQLITE_NULL) {
  1289. Utils::snprintf(json,sizeof(json),"\t\t\"vlanId\": %d,\n",sqlite3_column_int(_sListRules,4));
  1290. responseBody.append(json);
  1291. }
  1292. if (sqlite3_column_type(_sListRules,5) != SQLITE_NULL) {
  1293. Utils::snprintf(json,sizeof(json),"\t\t\"vlanPcp\": %d,\n",sqlite3_column_int(_sListRules,5));
  1294. responseBody.append(json);
  1295. }
  1296. if (sqlite3_column_type(_sListRules,6) != SQLITE_NULL) {
  1297. Utils::snprintf(json,sizeof(json),"\t\t\"etherType\": %d,\n",sqlite3_column_int(_sListRules,6));
  1298. responseBody.append(json);
  1299. }
  1300. if (sqlite3_column_type(_sListRules,7) != SQLITE_NULL) {
  1301. Utils::snprintf(json,sizeof(json),"\t\t\"macSource\": \"%s\",\n",MAC((const char *)sqlite3_column_text(_sListRules,7)).toString().c_str());
  1302. responseBody.append(json);
  1303. }
  1304. if (sqlite3_column_type(_sListRules,8) != SQLITE_NULL) {
  1305. Utils::snprintf(json,sizeof(json),"\t\t\"macDest\": \"%s\",\n",MAC((const char *)sqlite3_column_text(_sListRules,8)).toString().c_str());
  1306. responseBody.append(json);
  1307. }
  1308. if (sqlite3_column_type(_sListRules,9) != SQLITE_NULL) {
  1309. Utils::snprintf(json,sizeof(json),"\t\t\"ipSource\": \"%s\",\n",_jsonEscape((const char *)sqlite3_column_text(_sListRules,9)).c_str());
  1310. responseBody.append(json);
  1311. }
  1312. if (sqlite3_column_type(_sListRules,10) != SQLITE_NULL) {
  1313. Utils::snprintf(json,sizeof(json),"\t\t\"ipDest\": \"%s\",\n",_jsonEscape((const char *)sqlite3_column_text(_sListRules,10)).c_str());
  1314. responseBody.append(json);
  1315. }
  1316. if (sqlite3_column_type(_sListRules,11) != SQLITE_NULL) {
  1317. Utils::snprintf(json,sizeof(json),"\t\t\"ipTos\": %d,\n",sqlite3_column_int(_sListRules,11));
  1318. responseBody.append(json);
  1319. }
  1320. if (sqlite3_column_type(_sListRules,12) != SQLITE_NULL) {
  1321. Utils::snprintf(json,sizeof(json),"\t\t\"ipProtocol\": %d,\n",sqlite3_column_int(_sListRules,12));
  1322. responseBody.append(json);
  1323. }
  1324. if (sqlite3_column_type(_sListRules,13) != SQLITE_NULL) {
  1325. Utils::snprintf(json,sizeof(json),"\t\t\"ipSourcePort\": %d,\n",sqlite3_column_int(_sListRules,13));
  1326. responseBody.append(json);
  1327. }
  1328. if (sqlite3_column_type(_sListRules,14) != SQLITE_NULL) {
  1329. Utils::snprintf(json,sizeof(json),"\t\t\"ipDestPort\": %d,\n",sqlite3_column_int(_sListRules,14));
  1330. responseBody.append(json);
  1331. }
  1332. if (sqlite3_column_type(_sListRules,15) != SQLITE_NULL) {
  1333. Utils::snprintf(json,sizeof(json),"\t\t\"flags\": %lu,\n",(unsigned long)sqlite3_column_int64(_sListRules,15));
  1334. responseBody.append(json);
  1335. }
  1336. if (sqlite3_column_type(_sListRules,16) != SQLITE_NULL) {
  1337. Utils::snprintf(json,sizeof(json),"\t\t\"invFlags\": %lu,\n",(unsigned long)sqlite3_column_int64(_sListRules,16));
  1338. responseBody.append(json);
  1339. }
  1340. responseBody.append("\t\t\"action\": \"");
  1341. responseBody.append(_jsonEscape( (sqlite3_column_type(_sListRules,17) == SQLITE_NULL) ? "drop" : (const char *)sqlite3_column_text(_sListRules,17) ));
  1342. responseBody.append("\"\n\t}");
  1343. }
  1344. responseBody.append("]\n}\n");
  1345. responseContentType = "application/json";
  1346. return 200;
  1347. } // else 404
  1348. }
  1349. } else if (path.size() == 1) {
  1350. // list networks
  1351. sqlite3_reset(_sListNetworks);
  1352. responseContentType = "application/json";
  1353. responseBody = "[";
  1354. bool first = true;
  1355. while (sqlite3_step(_sListNetworks) == SQLITE_ROW) {
  1356. if (first) {
  1357. first = false;
  1358. responseBody.push_back('"');
  1359. } else responseBody.append(",\"");
  1360. responseBody.append((const char *)sqlite3_column_text(_sListNetworks,0));
  1361. responseBody.push_back('"');
  1362. }
  1363. responseBody.push_back(']');
  1364. return 200;
  1365. } // else 404
  1366. } else {
  1367. // GET /controller returns status and API version if controller is supported
  1368. Utils::snprintf(json,sizeof(json),"{\n\t\"controller\": true,\n\t\"apiVersion\": %d,\n\t\"clock\": %llu,\n\t\"instanceId\": \"%s\"\n}\n",ZT_NETCONF_CONTROLLER_API_VERSION,(unsigned long long)OSUtils::now(),_instanceId.c_str());
  1369. responseBody = json;
  1370. responseContentType = "application/json";
  1371. return 200;
  1372. }
  1373. return 404;
  1374. }
  1375. NetworkController::ResultCode SqliteNetworkController::_doNetworkConfigRequest(const InetAddress &fromAddr,const Identity &signingId,const Identity &identity,uint64_t nwid,const Dictionary &metaData,Dictionary &netconf)
  1376. {
  1377. // Assumes _lock is locked
  1378. // Decode some stuff from metaData
  1379. const unsigned int clientMajorVersion = (unsigned int)metaData.getHexUInt(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_NODE_MAJOR_VERSION,0);
  1380. const unsigned int clientMinorVersion = (unsigned int)metaData.getHexUInt(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_NODE_MINOR_VERSION,0);
  1381. const unsigned int clientRevision = (unsigned int)metaData.getHexUInt(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_NODE_REVISION,0);
  1382. const bool clientIs104 = (Utils::compareVersion(clientMajorVersion,clientMinorVersion,clientRevision,1,0,4) >= 0);
  1383. // Note: we can't reuse prepared statements that return const char * pointers without
  1384. // making our own copy in e.g. a std::string first.
  1385. if ((!signingId)||(!signingId.hasPrivate())) {
  1386. netconf["error"] = "signing identity invalid or lacks private key";
  1387. return NetworkController::NETCONF_QUERY_INTERNAL_SERVER_ERROR;
  1388. }
  1389. if (signingId.address().toInt() != (nwid >> 24)) {
  1390. netconf["error"] = "signing identity address does not match most significant 40 bits of network ID";
  1391. return NetworkController::NETCONF_QUERY_INTERNAL_SERVER_ERROR;
  1392. }
  1393. // Check rate limit circuit breaker to prevent flooding
  1394. const uint64_t now = OSUtils::now();
  1395. _LLEntry &lastLogEntry = _lastLog[std::pair<Address,uint64_t>(identity.address(),nwid)];
  1396. if ((now - lastLogEntry.lastRequestTime) <= ZT_NETCONF_MIN_REQUEST_PERIOD)
  1397. return NetworkController::NETCONF_QUERY_IGNORE;
  1398. lastLogEntry.lastRequestTime = now;
  1399. NetworkRecord network;
  1400. memset(&network,0,sizeof(network));
  1401. Utils::snprintf(network.id,sizeof(network.id),"%.16llx",(unsigned long long)nwid);
  1402. MemberRecord member;
  1403. memset(&member,0,sizeof(member));
  1404. Utils::snprintf(member.nodeId,sizeof(member.nodeId),"%.10llx",(unsigned long long)identity.address().toInt());
  1405. // Create Node record or do full identity check if we already have one
  1406. sqlite3_reset(_sGetNodeIdentity);
  1407. sqlite3_bind_text(_sGetNodeIdentity,1,member.nodeId,10,SQLITE_STATIC);
  1408. if (sqlite3_step(_sGetNodeIdentity) == SQLITE_ROW) {
  1409. try {
  1410. Identity alreadyKnownIdentity((const char *)sqlite3_column_text(_sGetNodeIdentity,0));
  1411. if (alreadyKnownIdentity != identity)
  1412. return NetworkController::NETCONF_QUERY_ACCESS_DENIED;
  1413. } catch ( ... ) { // identity stored in database is not valid or is NULL
  1414. return NetworkController::NETCONF_QUERY_ACCESS_DENIED;
  1415. }
  1416. } else {
  1417. std::string idstr(identity.toString(false));
  1418. sqlite3_reset(_sCreateOrReplaceNode);
  1419. sqlite3_bind_text(_sCreateOrReplaceNode,1,member.nodeId,10,SQLITE_STATIC);
  1420. sqlite3_bind_text(_sCreateOrReplaceNode,2,idstr.c_str(),-1,SQLITE_STATIC);
  1421. if (sqlite3_step(_sCreateOrReplaceNode) != SQLITE_DONE) {
  1422. netconf["error"] = "unable to create new Node record";
  1423. return NetworkController::NETCONF_QUERY_INTERNAL_SERVER_ERROR;
  1424. }
  1425. }
  1426. // Fetch Network record
  1427. sqlite3_reset(_sGetNetworkById);
  1428. sqlite3_bind_text(_sGetNetworkById,1,network.id,16,SQLITE_STATIC);
  1429. if (sqlite3_step(_sGetNetworkById) == SQLITE_ROW) {
  1430. network.name = (const char *)sqlite3_column_text(_sGetNetworkById,0);
  1431. network.isPrivate = (sqlite3_column_int(_sGetNetworkById,1) > 0);
  1432. network.enableBroadcast = (sqlite3_column_int(_sGetNetworkById,2) > 0);
  1433. network.allowPassiveBridging = (sqlite3_column_int(_sGetNetworkById,3) > 0);
  1434. network.v4AssignMode = (const char *)sqlite3_column_text(_sGetNetworkById,4);
  1435. network.v6AssignMode = (const char *)sqlite3_column_text(_sGetNetworkById,5);
  1436. network.multicastLimit = sqlite3_column_int(_sGetNetworkById,6);
  1437. network.creationTime = (uint64_t)sqlite3_column_int64(_sGetNetworkById,7);
  1438. network.revision = (uint64_t)sqlite3_column_int64(_sGetNetworkById,8);
  1439. network.memberRevisionCounter = (uint64_t)sqlite3_column_int64(_sGetNetworkById,9);
  1440. } else {
  1441. return NetworkController::NETCONF_QUERY_OBJECT_NOT_FOUND;
  1442. }
  1443. // Fetch Member record
  1444. bool foundMember = false;
  1445. sqlite3_reset(_sGetMember);
  1446. sqlite3_bind_text(_sGetMember,1,network.id,16,SQLITE_STATIC);
  1447. sqlite3_bind_text(_sGetMember,2,member.nodeId,10,SQLITE_STATIC);
  1448. if (sqlite3_step(_sGetMember) == SQLITE_ROW) {
  1449. foundMember = true;
  1450. member.rowid = (int64_t)sqlite3_column_int64(_sGetMember,0);
  1451. member.authorized = (sqlite3_column_int(_sGetMember,1) > 0);
  1452. member.activeBridge = (sqlite3_column_int(_sGetMember,2) > 0);
  1453. }
  1454. // Create Member record for unknown nodes, auto-authorizing if network is public
  1455. if (!foundMember) {
  1456. member.authorized = (network.isPrivate ? false : true);
  1457. member.activeBridge = false;
  1458. sqlite3_reset(_sCreateMember);
  1459. sqlite3_bind_text(_sCreateMember,1,network.id,16,SQLITE_STATIC);
  1460. sqlite3_bind_text(_sCreateMember,2,member.nodeId,10,SQLITE_STATIC);
  1461. sqlite3_bind_int(_sCreateMember,3,(member.authorized ? 1 : 0));
  1462. sqlite3_bind_text(_sCreateMember,4,network.id,16,SQLITE_STATIC);
  1463. if (sqlite3_step(_sCreateMember) != SQLITE_DONE) {
  1464. netconf["error"] = "unable to create new member record";
  1465. return NetworkController::NETCONF_QUERY_INTERNAL_SERVER_ERROR;
  1466. }
  1467. member.rowid = (int64_t)sqlite3_last_insert_rowid(_db);
  1468. sqlite3_reset(_sIncrementMemberRevisionCounter);
  1469. sqlite3_bind_text(_sIncrementMemberRevisionCounter,1,network.id,16,SQLITE_STATIC);
  1470. sqlite3_step(_sIncrementMemberRevisionCounter);
  1471. }
  1472. // Add log entry to in-memory circular log
  1473. {
  1474. const unsigned long ptr = (unsigned long)lastLogEntry.totalRequests % ZT_SQLITENETWORKCONTROLLER_IN_MEMORY_LOG_SIZE;
  1475. lastLogEntry.l[ptr].ts = now;
  1476. lastLogEntry.l[ptr].fromAddr = fromAddr;
  1477. if ((clientMajorVersion > 0)||(clientMinorVersion > 0)||(clientRevision > 0))
  1478. Utils::snprintf(lastLogEntry.l[ptr].version,sizeof(lastLogEntry.l[ptr].version),"%u.%u.%u",clientMajorVersion,clientMinorVersion,clientRevision);
  1479. else lastLogEntry.l[ptr].version[0] = (char)0;
  1480. lastLogEntry.l[ptr].authorized = member.authorized;
  1481. ++lastLogEntry.totalRequests;
  1482. // TODO: push or save these somewhere
  1483. }
  1484. // Check member authorization
  1485. if (!member.authorized)
  1486. return NetworkController::NETCONF_QUERY_ACCESS_DENIED;
  1487. // Create and sign netconf
  1488. netconf.clear();
  1489. {
  1490. char tss[24],rs[24];
  1491. Utils::snprintf(tss,sizeof(tss),"%.16llx",(unsigned long long)now);
  1492. Utils::snprintf(rs,sizeof(rs),"%.16llx",(unsigned long long)network.revision);
  1493. netconf[ZT_NETWORKCONFIG_DICT_KEY_TIMESTAMP] = tss;
  1494. netconf[ZT_NETWORKCONFIG_DICT_KEY_REVISION] = rs;
  1495. netconf[ZT_NETWORKCONFIG_DICT_KEY_NETWORK_ID] = network.id;
  1496. netconf[ZT_NETWORKCONFIG_DICT_KEY_ISSUED_TO] = member.nodeId;
  1497. netconf[ZT_NETWORKCONFIG_DICT_KEY_PRIVATE] = network.isPrivate ? "1" : "0";
  1498. netconf[ZT_NETWORKCONFIG_DICT_KEY_NAME] = (network.name) ? network.name : "";
  1499. netconf[ZT_NETWORKCONFIG_DICT_KEY_ENABLE_BROADCAST] = network.enableBroadcast ? "1" : "0";
  1500. netconf[ZT_NETWORKCONFIG_DICT_KEY_ALLOW_PASSIVE_BRIDGING] = network.allowPassiveBridging ? "1" : "0";
  1501. { // TODO: right now only etherTypes are supported in rules
  1502. std::vector<int> allowedEtherTypes;
  1503. sqlite3_reset(_sGetEtherTypesFromRuleTable);
  1504. sqlite3_bind_text(_sGetEtherTypesFromRuleTable,1,network.id,16,SQLITE_STATIC);
  1505. while (sqlite3_step(_sGetEtherTypesFromRuleTable) == SQLITE_ROW) {
  1506. if (sqlite3_column_type(_sGetEtherTypesFromRuleTable,0) == SQLITE_NULL) {
  1507. allowedEtherTypes.clear();
  1508. allowedEtherTypes.push_back(0); // NULL 'allow' matches ANY
  1509. break;
  1510. } else {
  1511. int et = sqlite3_column_int(_sGetEtherTypesFromRuleTable,0);
  1512. if ((et >= 0)&&(et <= 0xffff))
  1513. allowedEtherTypes.push_back(et);
  1514. }
  1515. }
  1516. std::sort(allowedEtherTypes.begin(),allowedEtherTypes.end());
  1517. allowedEtherTypes.erase(std::unique(allowedEtherTypes.begin(),allowedEtherTypes.end()),allowedEtherTypes.end());
  1518. std::string allowedEtherTypesCsv;
  1519. for(std::vector<int>::const_iterator i(allowedEtherTypes.begin());i!=allowedEtherTypes.end();++i) {
  1520. if (allowedEtherTypesCsv.length())
  1521. allowedEtherTypesCsv.push_back(',');
  1522. char tmp[16];
  1523. Utils::snprintf(tmp,sizeof(tmp),"%.4x",(unsigned int)*i);
  1524. allowedEtherTypesCsv.append(tmp);
  1525. }
  1526. netconf[ZT_NETWORKCONFIG_DICT_KEY_ALLOWED_ETHERNET_TYPES] = allowedEtherTypesCsv;
  1527. }
  1528. if (network.multicastLimit > 0) {
  1529. char ml[16];
  1530. Utils::snprintf(ml,sizeof(ml),"%lx",(unsigned long)network.multicastLimit);
  1531. netconf[ZT_NETWORKCONFIG_DICT_KEY_MULTICAST_LIMIT] = ml;
  1532. }
  1533. {
  1534. std::string activeBridges;
  1535. sqlite3_reset(_sGetActiveBridges);
  1536. sqlite3_bind_text(_sGetActiveBridges,1,network.id,16,SQLITE_STATIC);
  1537. while (sqlite3_step(_sGetActiveBridges) == SQLITE_ROW) {
  1538. const char *ab = (const char *)sqlite3_column_text(_sGetActiveBridges,0);
  1539. if ((ab)&&(strlen(ab) == 10)) {
  1540. if (activeBridges.length())
  1541. activeBridges.push_back(',');
  1542. activeBridges.append(ab);
  1543. }
  1544. if (activeBridges.length() > 1024) // sanity check -- you can't have too many active bridges at the moment
  1545. break;
  1546. }
  1547. if (activeBridges.length())
  1548. netconf[ZT_NETWORKCONFIG_DICT_KEY_ACTIVE_BRIDGES] = activeBridges;
  1549. }
  1550. // Do not send relays to 1.1.0 since it had a serious bug in using them
  1551. // 1.1.0 will still work, it'll just fall back to roots instead of using network preferred relays
  1552. if (!((clientMajorVersion == 1)&&(clientMinorVersion == 1)&&(clientRevision == 0))) {
  1553. std::string relays;
  1554. sqlite3_reset(_sGetRelays);
  1555. sqlite3_bind_text(_sGetRelays,1,network.id,16,SQLITE_STATIC);
  1556. while (sqlite3_step(_sGetRelays) == SQLITE_ROW) {
  1557. const char *n = (const char *)sqlite3_column_text(_sGetRelays,0);
  1558. const char *a = (const char *)sqlite3_column_text(_sGetRelays,1);
  1559. if ((n)&&(a)) {
  1560. Address node(n);
  1561. InetAddress addr(a);
  1562. if ((node)&&(addr)) {
  1563. if (relays.length())
  1564. relays.push_back(',');
  1565. relays.append(node.toString());
  1566. relays.push_back(';');
  1567. relays.append(addr.toString());
  1568. }
  1569. }
  1570. }
  1571. if (relays.length())
  1572. netconf[ZT_NETWORKCONFIG_DICT_KEY_RELAYS] = relays;
  1573. }
  1574. {
  1575. char tmp[128];
  1576. std::string gateways;
  1577. sqlite3_reset(_sGetGateways);
  1578. sqlite3_bind_text(_sGetGateways,1,network.id,16,SQLITE_STATIC);
  1579. while (sqlite3_step(_sGetGateways) == SQLITE_ROW) {
  1580. const unsigned char *ip = (const unsigned char *)sqlite3_column_blob(_sGetGateways,0);
  1581. switch(sqlite3_column_int(_sGetGateways,1)) { // ipVersion
  1582. case 4:
  1583. Utils::snprintf(tmp,sizeof(tmp),"%s%d.%d.%d.%d/%d",
  1584. (gateways.length() > 0) ? "," : "",
  1585. (int)ip[12],
  1586. (int)ip[13],
  1587. (int)ip[14],
  1588. (int)ip[15],
  1589. (int)sqlite3_column_int(_sGetGateways,2)); // metric
  1590. gateways.append(tmp);
  1591. break;
  1592. case 6:
  1593. Utils::snprintf(tmp,sizeof(tmp),"%s%.2x%.2x:%.2x%.2x:%.2x%.2x:%.2x%.2x:%.2x%.2x:%.2x%.2x:%.2x%.2x:%.2x%.2x/%d",
  1594. (gateways.length() > 0) ? "," : "",
  1595. (int)ip[0],
  1596. (int)ip[1],
  1597. (int)ip[2],
  1598. (int)ip[3],
  1599. (int)ip[4],
  1600. (int)ip[5],
  1601. (int)ip[6],
  1602. (int)ip[7],
  1603. (int)ip[8],
  1604. (int)ip[9],
  1605. (int)ip[10],
  1606. (int)ip[11],
  1607. (int)ip[12],
  1608. (int)ip[13],
  1609. (int)ip[14],
  1610. (int)ip[15],
  1611. (int)sqlite3_column_int(_sGetGateways,2)); // metric
  1612. gateways.append(tmp);
  1613. break;
  1614. }
  1615. }
  1616. if (gateways.length())
  1617. netconf[ZT_NETWORKCONFIG_DICT_KEY_GATEWAYS] = gateways;
  1618. }
  1619. if ((network.v4AssignMode)&&(!strcmp(network.v4AssignMode,"zt"))) {
  1620. std::string v4s;
  1621. // Get existing IPv4 IP assignments and network routes -- keep routes in a
  1622. // vector for use in auto-assign if we need them.
  1623. std::vector< std::pair<uint32_t,int> > routedNetworks;
  1624. bool haveStaticIpAssignment = false;
  1625. sqlite3_reset(_sGetIpAssignmentsForNode);
  1626. sqlite3_bind_text(_sGetIpAssignmentsForNode,1,network.id,16,SQLITE_STATIC);
  1627. sqlite3_bind_text(_sGetIpAssignmentsForNode,2,member.nodeId,10,SQLITE_STATIC);
  1628. sqlite3_bind_int(_sGetIpAssignmentsForNode,3,4); // 4 == IPv4
  1629. while (sqlite3_step(_sGetIpAssignmentsForNode) == SQLITE_ROW) {
  1630. const unsigned char *ip = (const unsigned char *)sqlite3_column_blob(_sGetIpAssignmentsForNode,1);
  1631. if ((!ip)||(sqlite3_column_bytes(_sGetIpAssignmentsForNode,1) != 16))
  1632. continue;
  1633. int ipNetmaskBits = sqlite3_column_int(_sGetIpAssignmentsForNode,2);
  1634. if ((ipNetmaskBits <= 0)||(ipNetmaskBits > 32))
  1635. continue;
  1636. const IpAssignmentType ipt = (IpAssignmentType)sqlite3_column_int(_sGetIpAssignmentsForNode,0);
  1637. switch(ipt) {
  1638. case ZT_IP_ASSIGNMENT_TYPE_ADDRESS:
  1639. haveStaticIpAssignment = true;
  1640. break;
  1641. case ZT_IP_ASSIGNMENT_TYPE_NETWORK:
  1642. routedNetworks.push_back(std::pair<uint32_t,int>(Utils::ntoh(*(reinterpret_cast<const uint32_t *>(ip + 12))),ipNetmaskBits));
  1643. break;
  1644. default:
  1645. continue;
  1646. }
  1647. // 1.0.4 or newer clients support network routes in addition to IPs.
  1648. // Older clients only support IP address / netmask entries.
  1649. if ((clientIs104)||(ipt == ZT_IP_ASSIGNMENT_TYPE_ADDRESS)) {
  1650. char tmp[32];
  1651. Utils::snprintf(tmp,sizeof(tmp),"%d.%d.%d.%d/%d",(int)ip[12],(int)ip[13],(int)ip[14],(int)ip[15],ipNetmaskBits);
  1652. if (v4s.length())
  1653. v4s.push_back(',');
  1654. v4s.append(tmp);
  1655. }
  1656. }
  1657. if (!haveStaticIpAssignment) {
  1658. // Attempt to auto-assign an IPv4 address from an available routed pool
  1659. sqlite3_reset(_sGetIpAssignmentPools);
  1660. sqlite3_bind_text(_sGetIpAssignmentPools,1,network.id,16,SQLITE_STATIC);
  1661. sqlite3_bind_int(_sGetIpAssignmentPools,2,4); // 4 == IPv4
  1662. while (sqlite3_step(_sGetIpAssignmentPools) == SQLITE_ROW) {
  1663. const unsigned char *ipRangeStartB = reinterpret_cast<const unsigned char *>(sqlite3_column_blob(_sGetIpAssignmentPools,0));
  1664. const unsigned char *ipRangeEndB = reinterpret_cast<const unsigned char *>(sqlite3_column_blob(_sGetIpAssignmentPools,1));
  1665. if ((!ipRangeStartB)||(!ipRangeEndB)||(sqlite3_column_bytes(_sGetIpAssignmentPools,0) != 16)||(sqlite3_column_bytes(_sGetIpAssignmentPools,1) != 16))
  1666. continue;
  1667. uint32_t ipRangeStart = Utils::ntoh(*(reinterpret_cast<const uint32_t *>(ipRangeStartB + 12)));
  1668. uint32_t ipRangeEnd = Utils::ntoh(*(reinterpret_cast<const uint32_t *>(ipRangeEndB + 12)));
  1669. if (ipRangeEnd < ipRangeStart)
  1670. continue;
  1671. uint32_t ipRangeLen = ipRangeEnd - ipRangeStart;
  1672. // Start with the LSB of the member's address
  1673. uint32_t ipTrialCounter = (uint32_t)(identity.address().toInt() & 0xffffffff);
  1674. for(uint32_t k=ipRangeStart,l=0;(k<=ipRangeEnd)&&(l < 1000000);++k,++l) {
  1675. uint32_t ip = (ipRangeLen > 0) ? (ipRangeStart + (ipTrialCounter % ipRangeLen)) : ipRangeStart;
  1676. ++ipTrialCounter;
  1677. if ((ip & 0x000000ff) == 0x000000ff)
  1678. continue; // don't allow addresses that end in .255
  1679. for(std::vector< std::pair<uint32_t,int> >::const_iterator r(routedNetworks.begin());r!=routedNetworks.end();++r) {
  1680. if ((ip & (0xffffffff << (32 - r->second))) == r->first) {
  1681. // IP is included in a routed network, so check if it's allocated
  1682. uint32_t ipBlob[4];
  1683. ipBlob[0] = 0; ipBlob[1] = 0; ipBlob[2] = 0; ipBlob[3] = Utils::hton(ip);
  1684. sqlite3_reset(_sCheckIfIpIsAllocated);
  1685. sqlite3_bind_text(_sCheckIfIpIsAllocated,1,network.id,16,SQLITE_STATIC);
  1686. sqlite3_bind_blob(_sCheckIfIpIsAllocated,2,(const void *)ipBlob,16,SQLITE_STATIC);
  1687. sqlite3_bind_int(_sCheckIfIpIsAllocated,3,4); // 4 == IPv4
  1688. sqlite3_bind_int(_sCheckIfIpIsAllocated,4,(int)ZT_IP_ASSIGNMENT_TYPE_ADDRESS);
  1689. if (sqlite3_step(_sCheckIfIpIsAllocated) != SQLITE_ROW) {
  1690. // No rows returned, so the IP is available
  1691. sqlite3_reset(_sAllocateIp);
  1692. sqlite3_bind_text(_sAllocateIp,1,network.id,16,SQLITE_STATIC);
  1693. sqlite3_bind_text(_sAllocateIp,2,member.nodeId,10,SQLITE_STATIC);
  1694. sqlite3_bind_int(_sAllocateIp,3,(int)ZT_IP_ASSIGNMENT_TYPE_ADDRESS);
  1695. sqlite3_bind_blob(_sAllocateIp,4,(const void *)ipBlob,16,SQLITE_STATIC);
  1696. sqlite3_bind_int(_sAllocateIp,5,r->second); // IP netmask bits from matching route
  1697. sqlite3_bind_int(_sAllocateIp,6,4); // 4 == IPv4
  1698. if (sqlite3_step(_sAllocateIp) == SQLITE_DONE) {
  1699. char tmp[32];
  1700. 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),r->second);
  1701. if (v4s.length())
  1702. v4s.push_back(',');
  1703. v4s.append(tmp);
  1704. haveStaticIpAssignment = true; // break outer loop
  1705. }
  1706. }
  1707. break; // stop checking routed networks
  1708. }
  1709. }
  1710. if (haveStaticIpAssignment)
  1711. break;
  1712. }
  1713. }
  1714. }
  1715. if (v4s.length())
  1716. netconf[ZT_NETWORKCONFIG_DICT_KEY_IPV4_STATIC] = v4s;
  1717. }
  1718. if ((network.v6AssignMode)&&(!strcmp(network.v6AssignMode,"rfc4193"))) {
  1719. InetAddress rfc4193Addr(InetAddress::makeIpv6rfc4193(nwid,identity.address().toInt()));
  1720. netconf[ZT_NETWORKCONFIG_DICT_KEY_IPV6_STATIC] = rfc4193Addr.toString();
  1721. }
  1722. if (network.isPrivate) {
  1723. CertificateOfMembership com(now,ZT_NETWORK_AUTOCONF_DELAY + (ZT_NETWORK_AUTOCONF_DELAY / 2),nwid,identity.address());
  1724. if (com.sign(signingId)) // basically can't fail unless our identity is invalid
  1725. netconf[ZT_NETWORKCONFIG_DICT_KEY_CERTIFICATE_OF_MEMBERSHIP] = com.toString();
  1726. else {
  1727. netconf["error"] = "unable to sign COM";
  1728. return NETCONF_QUERY_INTERNAL_SERVER_ERROR;
  1729. }
  1730. }
  1731. if (!netconf.sign(signingId,now)) {
  1732. netconf["error"] = "unable to sign netconf dictionary";
  1733. return NETCONF_QUERY_INTERNAL_SERVER_ERROR;
  1734. }
  1735. }
  1736. return NetworkController::NETCONF_QUERY_OK;
  1737. }
  1738. void SqliteNetworkController::_circuitTestCallback(ZT_Node *node,ZT_CircuitTest *test,const ZT_CircuitTestReport *report)
  1739. {
  1740. static Mutex circuitTestWriteLock;
  1741. const uint64_t now = OSUtils::now();
  1742. SqliteNetworkController *const c = reinterpret_cast<SqliteNetworkController *>(test->ptr);
  1743. char tmp[128];
  1744. std::string reportSavePath(c->_circuitTestPath);
  1745. OSUtils::mkdir(reportSavePath);
  1746. Utils::snprintf(tmp,sizeof(tmp),ZT_PATH_SEPARATOR_S"%.16llx",test->credentialNetworkId);
  1747. reportSavePath.append(tmp);
  1748. OSUtils::mkdir(reportSavePath);
  1749. Utils::snprintf(tmp,sizeof(tmp),ZT_PATH_SEPARATOR_S"%.16llx_%.16llx",test->timestamp,test->testId);
  1750. reportSavePath.append(tmp);
  1751. OSUtils::mkdir(reportSavePath);
  1752. Utils::snprintf(tmp,sizeof(tmp),ZT_PATH_SEPARATOR_S"%.16llx_%.10llx_%.10llx",now,report->upstream,report->current);
  1753. reportSavePath.append(tmp);
  1754. {
  1755. Mutex::Lock _l(circuitTestWriteLock);
  1756. FILE *f = fopen(reportSavePath.c_str(),"a");
  1757. if (!f)
  1758. return;
  1759. fseek(f,0,SEEK_END);
  1760. fprintf(f,"%s{\n"
  1761. "\t\"timestamp\": %llu,"ZT_EOL_S
  1762. "\t\"testId\": \"%.16llx\","ZT_EOL_S
  1763. "\t\"upstream\": \"%.10llx\","ZT_EOL_S
  1764. "\t\"current\": \"%.10llx\","ZT_EOL_S
  1765. "\t\"receivedTimestamp\": %llu,"ZT_EOL_S
  1766. "\t\"remoteTimestamp\": %llu,"ZT_EOL_S
  1767. "\t\"sourcePacketId\": \"%.16llx\","ZT_EOL_S
  1768. "\t\"flags\": %llu,"ZT_EOL_S
  1769. "\t\"sourcePacketHopCount\": %u,"ZT_EOL_S
  1770. "\t\"errorCode\": %u,"ZT_EOL_S
  1771. "\t\"vendor\": %d,"ZT_EOL_S
  1772. "\t\"protocolVersion\": %u,"ZT_EOL_S
  1773. "\t\"majorVersion\": %u,"ZT_EOL_S
  1774. "\t\"minorVersion\": %u,"ZT_EOL_S
  1775. "\t\"revision\": %u,"ZT_EOL_S
  1776. "\t\"platform\": %d,"ZT_EOL_S
  1777. "\t\"architecture\": %d,"ZT_EOL_S
  1778. "\t\"receivedOnLocalAddress\": \"%s\","ZT_EOL_S
  1779. "\t\"receivedFromRemoteAddress\": \"%s\""ZT_EOL_S
  1780. "}",
  1781. ((ftell(f) > 0) ? ",\n" : ""),
  1782. (unsigned long long)report->timestamp,
  1783. (unsigned long long)test->testId,
  1784. (unsigned long long)report->upstream,
  1785. (unsigned long long)report->current,
  1786. (unsigned long long)now,
  1787. (unsigned long long)report->remoteTimestamp,
  1788. (unsigned long long)report->sourcePacketId,
  1789. (unsigned long long)report->flags,
  1790. report->sourcePacketHopCount,
  1791. report->errorCode,
  1792. (int)report->vendor,
  1793. report->protocolVersion,
  1794. report->majorVersion,
  1795. report->minorVersion,
  1796. report->revision,
  1797. (int)report->platform,
  1798. (int)report->architecture,
  1799. reinterpret_cast<const InetAddress *>(&(report->receivedOnLocalAddress))->toString().c_str(),
  1800. reinterpret_cast<const InetAddress *>(&(report->receivedFromRemoteAddress))->toString().c_str());
  1801. fclose(f);
  1802. }
  1803. }
  1804. } // namespace ZeroTier