testnet.cpp 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765
  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. /* SEE: testnet/README.md */
  28. #include <stdio.h>
  29. #include <stdlib.h>
  30. #include <stdint.h>
  31. #include <string.h>
  32. #include <string>
  33. #include <map>
  34. #include <vector>
  35. #include <set>
  36. #include "node/Constants.hpp"
  37. #include "node/Node.hpp"
  38. #include "node/Utils.hpp"
  39. #include "node/Address.hpp"
  40. #include "node/Identity.hpp"
  41. #include "node/Thread.hpp"
  42. #include "node/CMWC4096.hpp"
  43. #include "node/Dictionary.hpp"
  44. #include "testnet/SimNet.hpp"
  45. #include "testnet/SimNetSocketManager.hpp"
  46. #include "testnet/TestEthernetTap.hpp"
  47. #include "testnet/TestEthernetTapFactory.hpp"
  48. #ifdef __WINDOWS__
  49. #include <windows.h>
  50. #else
  51. #include <unistd.h>
  52. #include <sys/stat.h>
  53. #endif
  54. using namespace ZeroTier;
  55. class SimNode
  56. {
  57. public:
  58. SimNode(SimNet &net,const std::string &hp,const char *rootTopology,bool issn,const InetAddress &addr) :
  59. home(hp),
  60. tapFactory(),
  61. socketManager(net.newEndpoint(addr)),
  62. node(home.c_str(),&tapFactory,socketManager,false,rootTopology),
  63. reasonForTermination(Node::NODE_RUNNING),
  64. supernode(issn)
  65. {
  66. thread = Thread::start(this);
  67. }
  68. ~SimNode()
  69. {
  70. node.terminate(Node::NODE_NORMAL_TERMINATION,"SimNode shutdown");
  71. Thread::join(thread);
  72. }
  73. void threadMain()
  74. throw()
  75. {
  76. reasonForTermination = node.run();
  77. }
  78. std::string home;
  79. TestEthernetTapFactory tapFactory;
  80. SimNetSocketManager *socketManager;
  81. Node node;
  82. Node::ReasonForTermination reasonForTermination;
  83. bool supernode;
  84. Thread thread;
  85. };
  86. static std::string basePath;
  87. static SimNet net;
  88. static std::map< Address,SimNode * > nodes;
  89. static std::map< InetAddress,Address > usedIps;
  90. static CMWC4096 prng;
  91. static std::string rootTopology;
  92. // Converts an address into a fake IP not already claimed.
  93. // Be sure to call only once, as this claims the IP before returning it.
  94. static InetAddress inetAddressFromZeroTierAddress(const Address &addr)
  95. {
  96. uint32_t ip = (uint32_t)(addr.toInt() & 0xffffffff);
  97. for(;;) {
  98. if (((ip >> 24) & 0xff) >= 240) {
  99. ip &= 0x00ffffff;
  100. ip |= (((ip >> 24) & 0xff) % 240) << 24;
  101. }
  102. if (((ip >> 24) & 0xff) == 0)
  103. ip |= 0x01000000;
  104. if (((ip & 0xff) == 0)||((ip & 0xff) == 255))
  105. ip ^= 0x00000001;
  106. InetAddress inaddr(Utils::hton(ip),9993);
  107. if (usedIps.find(inaddr) == usedIps.end()) {
  108. usedIps[inaddr] = addr;
  109. return inaddr;
  110. }
  111. ++ip; // keep looking sequentially for an unclaimed IP
  112. }
  113. }
  114. static Identity makeNodeHome(bool super)
  115. {
  116. Identity id;
  117. id.generate();
  118. std::string path(basePath + ZT_PATH_SEPARATOR_S + (super ? "S" : "N") + id.address().toString());
  119. #ifdef __WINDOWS__
  120. CreateDirectoryA(path.c_str(),NULL);
  121. #else
  122. mkdir(path.c_str(),0700);
  123. #endif
  124. if (!Utils::writeFile((path + ZT_PATH_SEPARATOR_S + "identity.secret").c_str(),id.toString(true)))
  125. return Identity();
  126. if (!Utils::writeFile((path + ZT_PATH_SEPARATOR_S + "identity.public").c_str(),id.toString(false)))
  127. return Identity();
  128. return id;
  129. }
  130. // Instantiates supernodes by scanning for S########## subdirectories
  131. static std::vector<Address> initSupernodes()
  132. {
  133. Dictionary supernodes;
  134. std::vector< std::pair<Identity,InetAddress> > snids;
  135. std::map<std::string,bool> dir(Utils::listDirectory(basePath.c_str()));
  136. for(std::map<std::string,bool>::iterator d(dir.begin());d!=dir.end();++d) {
  137. if ((d->first.length() == 11)&&(d->second)&&(d->first[0] == 'S')) {
  138. std::string idbuf;
  139. if (Utils::readFile((basePath + ZT_PATH_SEPARATOR_S + d->first + ZT_PATH_SEPARATOR_S + "identity.public").c_str(),idbuf)) {
  140. Identity id(idbuf);
  141. if (id) {
  142. InetAddress inaddr(inetAddressFromZeroTierAddress(id.address()));
  143. snids.push_back(std::pair<Identity,InetAddress>(id,inaddr));
  144. Dictionary snd;
  145. snd["id"] = id.toString(false);
  146. snd["udp"] = inaddr.toString();
  147. snd["desc"] = id.address().toString();
  148. snd["dns"] = inaddr.toIpString();
  149. supernodes[id.address().toString()] = snd.toString();
  150. }
  151. }
  152. }
  153. }
  154. Dictionary rtd;
  155. rtd["supernodes"] = supernodes.toString();
  156. rtd["noupdate"] = "1";
  157. rootTopology = rtd.toString();
  158. std::vector<Address> newNodes;
  159. for(std::vector< std::pair<Identity,InetAddress> >::iterator i(snids.begin());i!=snids.end();++i) {
  160. SimNode *n = new SimNode(net,(basePath + ZT_PATH_SEPARATOR_S + "S" + i->first.address().toString()),rootTopology.c_str(),true,i->second);
  161. nodes[i->first.address()] = n;
  162. newNodes.push_back(i->first.address());
  163. }
  164. return newNodes;
  165. }
  166. // Instantiates any not-already-instantiated regular nodes
  167. static std::vector<Address> scanForNewNodes()
  168. {
  169. std::vector<Address> newNodes;
  170. std::map<std::string,bool> dir(Utils::listDirectory(basePath.c_str()));
  171. for(std::map<std::string,bool>::iterator d(dir.begin());d!=dir.end();++d) {
  172. if ((d->first.length() == 11)&&(d->second)&&(d->first[0] == 'N')) {
  173. Address na(d->first.c_str() + 1);
  174. if (nodes.find(na) == nodes.end()) {
  175. InetAddress inaddr(inetAddressFromZeroTierAddress(na));
  176. SimNode *n = new SimNode(net,(basePath + ZT_PATH_SEPARATOR_S + d->first),rootTopology.c_str(),false,inaddr);
  177. nodes[na] = n;
  178. newNodes.push_back(na);
  179. }
  180. }
  181. }
  182. return newNodes;
  183. }
  184. static void doHelp(const std::vector<std::string> &cmd)
  185. {
  186. printf("---------- help"ZT_EOL_S);
  187. printf("---------- mksn <number of supernodes>"ZT_EOL_S);
  188. printf("---------- mkn <number of normal nodes>"ZT_EOL_S);
  189. printf("---------- list"ZT_EOL_S);
  190. printf("---------- join <address/*/**> <network ID>"ZT_EOL_S);
  191. printf("---------- leave <address/*/**> <network ID>"ZT_EOL_S);
  192. printf("---------- listnetworks <address/*/**>"ZT_EOL_S);
  193. printf("---------- listpeers <address/*/**>"ZT_EOL_S);
  194. printf("---------- unicast <address/*/**> <address/*/**> <network ID> <frame length, min: 16> [<timeout (sec)>]"ZT_EOL_S);
  195. printf("---------- multicast <address/*/**> <MAC/* for bcast> <network ID> <frame length, min: 16> [<timeout (sec)>]"ZT_EOL_S);
  196. printf("---------- quit"ZT_EOL_S);
  197. printf("---------- ( * means all regular nodes, ** means including supernodes )"ZT_EOL_S);
  198. printf("---------- ( . runs previous command again )"ZT_EOL_S);
  199. }
  200. static void doMKSN(const std::vector<std::string> &cmd)
  201. {
  202. if (cmd.size() < 2) {
  203. doHelp(cmd);
  204. return;
  205. }
  206. if (nodes.size() > 0) {
  207. printf("---------- mksn error: mksn can only be called once (network already exists)"ZT_EOL_S);
  208. return;
  209. }
  210. int count = Utils::strToInt(cmd[1].c_str());
  211. for(int i=0;i<count;++i) {
  212. Identity id(makeNodeHome(true));
  213. printf("%s identity created"ZT_EOL_S,id.address().toString().c_str());
  214. }
  215. std::vector<Address> nodes(initSupernodes());
  216. for(std::vector<Address>::iterator a(nodes.begin());a!=nodes.end();++a)
  217. printf("%s started (supernode)"ZT_EOL_S,a->toString().c_str());
  218. //printf("---------- root topology is: %s"ZT_EOL_S,rootTopology.c_str());
  219. }
  220. static void doMKN(const std::vector<std::string> &cmd)
  221. {
  222. if (cmd.size() < 2) {
  223. doHelp(cmd);
  224. return;
  225. }
  226. if (nodes.size() == 0) {
  227. printf("---------- mkn error: use mksn to create supernodes first."ZT_EOL_S);
  228. return;
  229. }
  230. int count = Utils::strToInt(cmd[1].c_str());
  231. for(int i=0;i<count;++i) {
  232. Identity id(makeNodeHome(false));
  233. printf("%s identity created"ZT_EOL_S,id.address().toString().c_str());
  234. }
  235. std::vector<Address> nodes(scanForNewNodes());
  236. for(std::vector<Address>::iterator a(nodes.begin());a!=nodes.end();++a)
  237. printf("%s started (regular node)"ZT_EOL_S,a->toString().c_str());
  238. }
  239. static void doList(const std::vector<std::string> &cmd)
  240. {
  241. unsigned int peers = 0,supernodes = 0;
  242. ZT1_Node_Status status;
  243. for(std::map< Address,SimNode * >::iterator n(nodes.begin());n!=nodes.end();++n) {
  244. n->second->node.status(&status);
  245. if (status.initialized) {
  246. printf("%s %c %s (%u peers, %u direct links)"ZT_EOL_S,
  247. n->first.toString().c_str(),
  248. n->second->supernode ? 'S' : 'N',
  249. (status.online ? "ONLINE" : "OFFLINE"),
  250. status.knownPeers,
  251. status.directlyConnectedPeers);
  252. if (n->second->supernode)
  253. ++supernodes;
  254. else ++peers;
  255. } else printf("%s ? INITIALIZING (0 peers, 0 direct links)"ZT_EOL_S,n->first.toString().c_str());
  256. }
  257. printf("---------- %u regular peers, %u supernodes"ZT_EOL_S,peers,supernodes);
  258. }
  259. static void doJoin(const std::vector<std::string> &cmd)
  260. {
  261. if (cmd.size() < 3) {
  262. doHelp(cmd);
  263. return;
  264. }
  265. std::vector<Address> addrs;
  266. if ((cmd[1] == "*")||(cmd[1] == "**")) {
  267. bool includeSuper = (cmd[1] == "**");
  268. for(std::map< Address,SimNode * >::iterator n(nodes.begin());n!=nodes.end();++n) {
  269. if ((includeSuper)||(!n->second->supernode))
  270. addrs.push_back(n->first);
  271. }
  272. } else addrs.push_back(Address(cmd[1]));
  273. uint64_t nwid = Utils::hexStrToU64(cmd[2].c_str());
  274. for(std::vector<Address>::iterator a(addrs.begin());a!=addrs.end();++a) {
  275. std::map< Address,SimNode * >::iterator n(nodes.find(*a));
  276. if (n != nodes.end()) {
  277. n->second->node.join(nwid);
  278. printf("%s join %.16llx"ZT_EOL_S,n->first.toString().c_str(),(unsigned long long)nwid);
  279. }
  280. }
  281. }
  282. static void doLeave(const std::vector<std::string> &cmd)
  283. {
  284. if (cmd.size() < 3) {
  285. doHelp(cmd);
  286. return;
  287. }
  288. std::vector<Address> addrs;
  289. if ((cmd[1] == "*")||(cmd[1] == "**")) {
  290. bool includeSuper = (cmd[1] == "**");
  291. for(std::map< Address,SimNode * >::iterator n(nodes.begin());n!=nodes.end();++n) {
  292. if ((includeSuper)||(!n->second->supernode))
  293. addrs.push_back(n->first);
  294. }
  295. } else addrs.push_back(Address(cmd[1]));
  296. uint64_t nwid = Utils::hexStrToU64(cmd[2].c_str());
  297. for(std::vector<Address>::iterator a(addrs.begin());a!=addrs.end();++a) {
  298. std::map< Address,SimNode * >::iterator n(nodes.find(*a));
  299. if (n != nodes.end()) {
  300. n->second->node.leave(nwid);
  301. printf("%s leave %.16llx"ZT_EOL_S,n->first.toString().c_str(),(unsigned long long)nwid);
  302. }
  303. }
  304. }
  305. static void doListNetworks(const std::vector<std::string> &cmd)
  306. {
  307. if (cmd.size() < 2) {
  308. doHelp(cmd);
  309. return;
  310. }
  311. std::vector<Address> addrs;
  312. if ((cmd[1] == "*")||(cmd[1] == "**")) {
  313. bool includeSuper = (cmd[1] == "**");
  314. for(std::map< Address,SimNode * >::iterator n(nodes.begin());n!=nodes.end();++n) {
  315. if ((includeSuper)||(!n->second->supernode))
  316. addrs.push_back(n->first);
  317. }
  318. } else addrs.push_back(Address(cmd[1]));
  319. printf("---------- <nwid> <name> <mac> <status> <config age> <type> <dev> <ips>"ZT_EOL_S);
  320. for(std::vector<Address>::iterator a(addrs.begin());a!=addrs.end();++a) {
  321. std::string astr(a->toString());
  322. std::map< Address,SimNode * >::iterator n(nodes.find(*a));
  323. if (n != nodes.end()) {
  324. ZT1_Node_NetworkList *nl = n->second->node.listNetworks();
  325. if (nl) {
  326. for(unsigned int i=0;i<nl->numNetworks;++i) {
  327. printf("%s %s %s %s %s %ld %s %s ",
  328. astr.c_str(),
  329. nl->networks[i].nwidHex,
  330. nl->networks[i].name,
  331. nl->networks[i].macStr,
  332. nl->networks[i].statusStr,
  333. nl->networks[i].configAge,
  334. (nl->networks[i].isPrivate ? "private" : "public"),
  335. nl->networks[i].device);
  336. if (nl->networks[i].numIps > 0) {
  337. for(unsigned int j=0;j<nl->networks[i].numIps;++j) {
  338. if (j > 0)
  339. printf(",");
  340. printf("%s/%d",nl->networks[i].ips[j].ascii,(int)nl->networks[i].ips[j].port);
  341. }
  342. } else printf("-");
  343. printf(ZT_EOL_S);
  344. }
  345. n->second->node.freeQueryResult(nl);
  346. }
  347. }
  348. }
  349. }
  350. static void doListPeers(const std::vector<std::string> &cmd)
  351. {
  352. if (cmd.size() < 2) {
  353. doHelp(cmd);
  354. return;
  355. }
  356. std::vector<Address> addrs;
  357. if ((cmd[1] == "*")||(cmd[1] == "**")) {
  358. bool includeSuper = (cmd[1] == "**");
  359. for(std::map< Address,SimNode * >::iterator n(nodes.begin());n!=nodes.end();++n) {
  360. if ((includeSuper)||(!n->second->supernode))
  361. addrs.push_back(n->first);
  362. }
  363. } else addrs.push_back(Address(cmd[1]));
  364. printf("---------- <ztaddr> <paths> <latency> <version> <role>"ZT_EOL_S);
  365. for(std::vector<Address>::iterator a(addrs.begin());a!=addrs.end();++a) {
  366. std::string astr(a->toString());
  367. std::map< Address,SimNode * >::iterator n(nodes.find(*a));
  368. if (n != nodes.end()) {
  369. ZT1_Node_PeerList *pl = n->second->node.listPeers();
  370. if (pl) {
  371. for(unsigned int i=0;i<pl->numPeers;++i) {
  372. printf("%s %.10llx ",astr.c_str(),(unsigned long long)pl->peers[i].rawAddress);
  373. if (pl->peers[i].numPaths == 0)
  374. printf("-");
  375. else {
  376. for(unsigned int j=0;j<pl->peers[i].numPaths;++j) {
  377. if (j > 0)
  378. printf(",");
  379. switch(pl->peers[i].paths[j].type) {
  380. default:
  381. printf("unknown;");
  382. break;
  383. case ZT1_Node_PhysicalPath_TYPE_UDP:
  384. printf("udp;");
  385. break;
  386. case ZT1_Node_PhysicalPath_TYPE_TCP_OUT:
  387. printf("tcp_out;");
  388. break;
  389. case ZT1_Node_PhysicalPath_TYPE_TCP_IN:
  390. printf("tcp_in;");
  391. break;
  392. case ZT1_Node_PhysicalPath_TYPE_ETHERNET:
  393. printf("eth;");
  394. break;
  395. }
  396. printf("%s/%d;%ld;%ld;%ld;%s",
  397. pl->peers[i].paths[j].address.ascii,
  398. (int)pl->peers[i].paths[j].address.port,
  399. pl->peers[i].paths[j].lastSend,
  400. pl->peers[i].paths[j].lastReceive,
  401. pl->peers[i].paths[j].lastPing,
  402. (pl->peers[i].paths[j].fixed ? "fixed" : (pl->peers[i].paths[j].active ? "active" : "inactive")));
  403. }
  404. }
  405. const char *rolestr;
  406. switch(pl->peers[i].role) {
  407. case ZT1_Node_Peer_SUPERNODE: rolestr = "SUPERNODE"; break;
  408. case ZT1_Node_Peer_HUB: rolestr = "HUB"; break;
  409. case ZT1_Node_Peer_NODE: rolestr = "NODE"; break;
  410. default: rolestr = "?"; break;
  411. }
  412. printf(" %u %s %s"ZT_EOL_S,
  413. pl->peers[i].latency,
  414. ((pl->peers[i].remoteVersion[0]) ? pl->peers[i].remoteVersion : "-"),
  415. rolestr);
  416. }
  417. n->second->node.freeQueryResult(pl);
  418. }
  419. }
  420. }
  421. }
  422. static void doUnicast(const std::vector<std::string> &cmd)
  423. {
  424. union {
  425. uint64_t i[2];
  426. unsigned char data[2800];
  427. } pkt;
  428. if (cmd.size() < 5) {
  429. doHelp(cmd);
  430. return;
  431. }
  432. uint64_t nwid = Utils::hexStrToU64(cmd[3].c_str());
  433. unsigned int frameLen = Utils::strToUInt(cmd[4].c_str());
  434. uint64_t tout = 2000;
  435. if (cmd.size() >= 6)
  436. tout = Utils::strToU64(cmd[5].c_str()) * 1000ULL;
  437. if (frameLen < 16)
  438. frameLen = 16;
  439. if (frameLen > 2800)
  440. frameLen = 2800;
  441. std::vector<Address> senders;
  442. if ((cmd[1] == "*")||(cmd[1] == "**")) {
  443. bool includeSuper = (cmd[1] == "**");
  444. for(std::map< Address,SimNode * >::iterator n(nodes.begin());n!=nodes.end();++n) {
  445. if ((includeSuper)||(!n->second->supernode))
  446. senders.push_back(n->first);
  447. }
  448. } else senders.push_back(Address(cmd[1]));
  449. std::vector<Address> receivers;
  450. if ((cmd[2] == "*")||(cmd[2] == "**")) {
  451. bool includeSuper = (cmd[2] == "**");
  452. for(std::map< Address,SimNode * >::iterator n(nodes.begin());n!=nodes.end();++n) {
  453. if ((includeSuper)||(!n->second->supernode))
  454. receivers.push_back(n->first);
  455. }
  456. } else receivers.push_back(Address(cmd[2]));
  457. for(unsigned int i=0;i<frameLen;++i)
  458. pkt.data[i] = (unsigned char)prng.next32();
  459. std::set< std::pair<Address,Address> > sentPairs;
  460. for(std::vector<Address>::iterator s(senders.begin());s!=senders.end();++s) {
  461. for(std::vector<Address>::iterator r(receivers.begin());r!=receivers.end();++r) {
  462. if (*s == *r)
  463. continue;
  464. SimNode *sender = nodes[*s];
  465. SimNode *receiver = nodes[*r];
  466. TestEthernetTap *stap = sender->tapFactory.getByNwid(nwid);
  467. TestEthernetTap *rtap = receiver->tapFactory.getByNwid(nwid);
  468. if ((stap)&&(rtap)) {
  469. pkt.i[0] = s->toInt();
  470. pkt.i[1] = Utils::now();
  471. stap->injectPacketFromHost(stap->mac(),rtap->mac(),0xdead,pkt.data,frameLen);
  472. printf("%s -> %s etherType 0xdead network %.16llx length %u"ZT_EOL_S,s->toString().c_str(),r->toString().c_str(),(unsigned long long)nwid,frameLen);
  473. sentPairs.insert(std::pair<Address,Address>(*s,*r));
  474. } else if (stap) {
  475. printf("%s -> !%s (receiver not a member of %.16llx)"ZT_EOL_S,s->toString().c_str(),r->toString().c_str(),(unsigned long long)nwid);
  476. } else if (rtap) {
  477. printf("%s -> !%s (sender not a member of %.16llx)"ZT_EOL_S,s->toString().c_str(),r->toString().c_str(),(unsigned long long)nwid);
  478. } else {
  479. printf("%s -> !%s (neither party is a member of %.16llx)"ZT_EOL_S,s->toString().c_str(),r->toString().c_str(),(unsigned long long)nwid);
  480. }
  481. }
  482. }
  483. printf("---------- waiting up to %llu seconds..."ZT_EOL_S,tout / 1000ULL);
  484. std::set< std::pair<Address,Address> > receivedPairs;
  485. TestEthernetTap::TestFrame frame;
  486. uint64_t toutend = Utils::now() + tout;
  487. do {
  488. for(std::vector<Address>::iterator r(receivers.begin());r!=receivers.end();++r) {
  489. SimNode *receiver = nodes[*r];
  490. TestEthernetTap *rtap = receiver->tapFactory.getByNwid(nwid);
  491. if ((rtap)&&(rtap->getNextReceivedFrame(frame,5))) {
  492. if ((frame.len == frameLen)&&(!memcmp(frame.data + 16,pkt.data + 16,frameLen - 16))) {
  493. uint64_t ints[2];
  494. memcpy(ints,frame.data,16);
  495. printf("%s <- %.10llx received test packet, length == %u, latency == %llums"ZT_EOL_S,r->toString().c_str(),(unsigned long long)ints[0],frame.len,(unsigned long long)(frame.timestamp - ints[1]));
  496. receivedPairs.insert(std::pair<Address,Address>(Address(ints[0]),*r));
  497. } else {
  498. printf("%s !! got spurious packet, length == %u, etherType == 0x%.4x"ZT_EOL_S,r->toString().c_str(),frame.len,frame.etherType);
  499. }
  500. }
  501. }
  502. Thread::sleep(100);
  503. } while ((receivedPairs.size() < sentPairs.size())&&(Utils::now() < toutend));
  504. for(std::vector<Address>::iterator s(senders.begin());s!=senders.end();++s) {
  505. for(std::vector<Address>::iterator r(receivers.begin());r!=receivers.end();++r) {
  506. if (*s == *r)
  507. continue;
  508. if ((sentPairs.count(std::pair<Address,Address>(*s,*r)))&&(!receivedPairs.count(std::pair<Address,Address>(*s,*r)))) {
  509. printf("%s <- %s was never received (timed out)"ZT_EOL_S,r->toString().c_str(),s->toString().c_str());
  510. }
  511. }
  512. }
  513. printf("---------- sent %u, received %u"ZT_EOL_S,(unsigned int)sentPairs.size(),(unsigned int)receivedPairs.size());
  514. }
  515. static void doMulticast(const std::vector<std::string> &cmd)
  516. {
  517. union {
  518. uint64_t i[2];
  519. unsigned char data[2800];
  520. } pkt;
  521. if (cmd.size() < 5) {
  522. doHelp(cmd);
  523. return;
  524. }
  525. uint64_t nwid = Utils::hexStrToU64(cmd[3].c_str());
  526. unsigned int frameLen = Utils::strToUInt(cmd[4].c_str());
  527. uint64_t tout = 2000;
  528. if (cmd.size() >= 6)
  529. tout = Utils::strToU64(cmd[5].c_str()) * 1000ULL;
  530. if (frameLen < 16)
  531. frameLen = 16;
  532. if (frameLen > 2800)
  533. frameLen = 2800;
  534. std::vector<Address> senders;
  535. if ((cmd[1] == "*")||(cmd[1] == "**")) {
  536. bool includeSuper = (cmd[1] == "**");
  537. for(std::map< Address,SimNode * >::iterator n(nodes.begin());n!=nodes.end();++n) {
  538. if ((includeSuper)||(!n->second->supernode))
  539. senders.push_back(n->first);
  540. }
  541. } else senders.push_back(Address(cmd[1]));
  542. MAC mcaddr;
  543. if (cmd[2] == "*")
  544. mcaddr = MAC(0xff,0xff,0xff,0xff,0xff,0xff);
  545. else mcaddr.fromString(cmd[2].c_str());
  546. if (!mcaddr.isMulticast()) {
  547. printf("---------- %s is not a multicast MAC address"ZT_EOL_S,mcaddr.toString().c_str());
  548. return;
  549. }
  550. for(unsigned int i=0;i<frameLen;++i)
  551. pkt.data[i] = (unsigned char)prng.next32();
  552. for(std::vector<Address>::iterator s(senders.begin());s!=senders.end();++s) {
  553. SimNode *sender = nodes[*s];
  554. TestEthernetTap *stap = sender->tapFactory.getByNwid(nwid);
  555. if (stap) {
  556. pkt.i[0] = s->toInt();
  557. pkt.i[1] = Utils::now();
  558. stap->injectPacketFromHost(stap->mac(),mcaddr,0xdead,pkt.data,frameLen);
  559. printf("%s -> %s etherType 0xdead network %.16llx length %u"ZT_EOL_S,s->toString().c_str(),mcaddr.toString().c_str(),(unsigned long long)nwid,frameLen);
  560. } else {
  561. printf("%s -> !%s (sender is not a member of %.16llx)"ZT_EOL_S,s->toString().c_str(),mcaddr.toString().c_str(),(unsigned long long)nwid);
  562. }
  563. }
  564. printf("---------- waiting %llu seconds..."ZT_EOL_S,tout / 1000ULL);
  565. unsigned int receiveCount = 0;
  566. TestEthernetTap::TestFrame frame;
  567. uint64_t toutend = Utils::now() + tout;
  568. do {
  569. for(std::map< Address,SimNode * >::iterator nn(nodes.begin());nn!=nodes.end();++nn) {
  570. SimNode *receiver = nn->second;
  571. TestEthernetTap *rtap = receiver->tapFactory.getByNwid(nwid);
  572. if ((rtap)&&(rtap->getNextReceivedFrame(frame,5))) {
  573. if ((frame.len == frameLen)&&(!memcmp(frame.data + 16,pkt.data + 16,frameLen - 16))) {
  574. uint64_t ints[2];
  575. memcpy(ints,frame.data,16);
  576. printf("%s <- %.10llx received test packet, length == %u, latency == %llums"ZT_EOL_S,nn->first.toString().c_str(),(unsigned long long)ints[0],frame.len,(unsigned long long)(frame.timestamp - ints[1]));
  577. ++receiveCount;
  578. } else {
  579. printf("%s !! got spurious packet, length == %u, etherType == 0x%.4x"ZT_EOL_S,nn->first.toString().c_str(),frame.len,frame.etherType);
  580. }
  581. }
  582. }
  583. Thread::sleep(100);
  584. } while (Utils::now() < toutend);
  585. printf("---------- test multicast received by %u peers"ZT_EOL_S,receiveCount);
  586. }
  587. int main(int argc,char **argv)
  588. {
  589. char linebuf[1024];
  590. if (argc <= 1) {
  591. fprintf(stderr,"Usage: %s <base path for temporary node home directories>"ZT_EOL_S,argv[0]);
  592. return 1;
  593. }
  594. basePath = argv[1];
  595. #ifdef __WINDOWS__
  596. CreateDirectoryA(basePath.c_str(),NULL);
  597. #else
  598. mkdir(basePath.c_str(),0700);
  599. #endif
  600. printf("*** ZeroTier One Version %s -- Headless Network Simulator ***"ZT_EOL_S,Node::versionString());
  601. printf(ZT_EOL_S);
  602. {
  603. printf("---------- scanning '%s' for existing network..."ZT_EOL_S,basePath.c_str());
  604. std::vector<Address> snodes(initSupernodes());
  605. if (snodes.empty()) {
  606. printf("---------- no existing network found; use 'mksn' to create one."ZT_EOL_S);
  607. } else {
  608. for(std::vector<Address>::iterator a(snodes.begin());a!=snodes.end();++a)
  609. printf("%s started (supernode)"ZT_EOL_S,a->toString().c_str());
  610. //printf("---------- root topology is: %s"ZT_EOL_S,rootTopology.c_str());
  611. std::vector<Address> nodes(scanForNewNodes());
  612. for(std::vector<Address>::iterator a(nodes.begin());a!=nodes.end();++a)
  613. printf("%s started (normal peer)"ZT_EOL_S,a->toString().c_str());
  614. printf("---------- %u peers and %u supernodes loaded!"ZT_EOL_S,(unsigned int)nodes.size(),(unsigned int)snodes.size());
  615. }
  616. }
  617. printf(ZT_EOL_S);
  618. printf("Type 'help' for help."ZT_EOL_S);
  619. printf(ZT_EOL_S);
  620. std::vector<std::string> cmd,prevCmd;
  621. bool run = true;
  622. while (run) {
  623. printf(">> ");
  624. fflush(stdout);
  625. if (!fgets(linebuf,sizeof(linebuf),stdin))
  626. break;
  627. cmd = Utils::split(linebuf," \r\n\t","\\","\"");
  628. for(;;) {
  629. if (cmd.size() == 0)
  630. break;
  631. else if (cmd[0] == "quit")
  632. run = false;
  633. else if (cmd[0] == "help")
  634. doHelp(cmd);
  635. else if (cmd[0] == "mksn")
  636. doMKSN(cmd);
  637. else if (cmd[0] == "mkn")
  638. doMKN(cmd);
  639. else if (cmd[0] == "list")
  640. doList(cmd);
  641. else if (cmd[0] == "join")
  642. doJoin(cmd);
  643. else if (cmd[0] == "leave")
  644. doLeave(cmd);
  645. else if (cmd[0] == "listnetworks")
  646. doListNetworks(cmd);
  647. else if (cmd[0] == "listpeers")
  648. doListPeers(cmd);
  649. else if (cmd[0] == "unicast")
  650. doUnicast(cmd);
  651. else if (cmd[0] == "multicast")
  652. doMulticast(cmd);
  653. else if ((cmd[0] == ".")&&(prevCmd.size() > 0)) {
  654. cmd = prevCmd;
  655. continue;
  656. } else doHelp(cmd);
  657. break;
  658. }
  659. if ((cmd.size() > 0)&&(cmd[0] != "."))
  660. prevCmd = cmd;
  661. }
  662. for(std::map< Address,SimNode * >::iterator n(nodes.begin());n!=nodes.end();++n) {
  663. printf("%s shutting down..."ZT_EOL_S,n->first.toString().c_str());
  664. delete n->second;
  665. }
  666. return 0;
  667. }