sybilsim.c 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420
  1. /* vim: set expandtab ts=4 sw=4: */
  2. /*
  3. * You may redistribute this program and/or modify it under the terms of
  4. * the GNU General Public License as published by the Free Software Foundation,
  5. * either version 3 of the License, or (at your option) any later version.
  6. *
  7. * This program is distributed in the hope that it will be useful,
  8. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. * GNU General Public License for more details.
  11. *
  12. * You should have received a copy of the GNU General Public License
  13. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  14. */
  15. #include "benc/serialization/standard/BencMessageReader.h"
  16. #include "benc/serialization/standard/BencMessageWriter.h"
  17. #include "benc/serialization/json/JsonBencSerializer.h"
  18. #include "benc/serialization/BencSerializer.h"
  19. #include "benc/List.h"
  20. #include "io/ArrayReader.h"
  21. #include "admin/angel/Core.h"
  22. #include "client/AdminClient.h"
  23. #include "interface/ASynchronizer.h"
  24. #include "interface/addressable/AddrIfaceAdapter.h"
  25. #include "memory/MallocAllocator.h"
  26. #include "memory/Allocator.h"
  27. #include "util/log/FileWriterLog.h"
  28. #include "wire/Message.h"
  29. #include "util/events/EventBase.h"
  30. #include "crypto/random/Random.h"
  31. #include "crypto/random/libuv/LibuvEntropyProvider.h"
  32. #include "exception/Except.h"
  33. #include "util/events/Timeout.h"
  34. #include "crypto/Key.h"
  35. #include "util/log/Log_impl.h"
  36. #include "io/FileReader.h"
  37. #include "io/ArrayWriter.h"
  38. #include "util/Hex.h"
  39. #include "crypto_scalarmult_curve25519.h"
  40. #include <unistd.h> // isatty()
  41. struct NodeContext {
  42. struct Sockaddr* boundAddr;
  43. struct Allocator* alloc;
  44. struct EventBase* base;
  45. uint8_t privateKey[32];
  46. String* publicKey;
  47. struct AdminClient* adminClient;
  48. struct Admin* admin;
  49. char* nodeName;
  50. /** Admin socket to bind */
  51. String* bind;
  52. /** Admin password */
  53. String* pass;
  54. /** UDPInterface */
  55. int ifNum;
  56. struct Sockaddr* udpAddr;
  57. struct Log nodeLog;
  58. struct Log* parentLogger;
  59. Identity
  60. };
  61. struct RPCCall;
  62. typedef void (* RPCCallback)(struct RPCCall* call, struct AdminClient_Result* res);
  63. struct RPCCall
  64. {
  65. String* func;
  66. Dict* args;
  67. struct NodeContext* node;
  68. RPCCallback callback;
  69. };
  70. struct Context
  71. {
  72. struct RPCCall* rpcCalls;
  73. int rpcCallCount;
  74. int nextCall;
  75. struct Allocator* rpcAlloc;
  76. struct Random* rand;
  77. struct EventBase* base;
  78. struct Log* logger;
  79. struct Allocator* alloc;
  80. struct NodeContext** nodes;
  81. Dict* confNodes;
  82. String** names;
  83. Identity
  84. };
  85. static String* pubKeyForPriv(uint8_t* privateKey, struct Allocator* alloc)
  86. {
  87. uint8_t publicKey[32];
  88. crypto_scalarmult_curve25519_base(publicKey, privateKey);
  89. return Key_stringify(publicKey, alloc);
  90. }
  91. static void printLog(struct Log* log,
  92. enum Log_Level logLevel,
  93. const char* file,
  94. int line,
  95. const char* format,
  96. va_list args)
  97. {
  98. struct NodeContext* ctx = Identity_check(
  99. (struct NodeContext*) (((char*)log) - offsetof(struct NodeContext, nodeLog))
  100. );
  101. struct Allocator* alloc = Allocator_child(ctx->alloc);
  102. String* str = String_printf(alloc, "[%s] %s", ctx->nodeName, file);
  103. ctx->parentLogger->print(ctx->parentLogger, logLevel, str->bytes, line, format, args);
  104. Allocator_free(alloc);
  105. }
  106. static struct RPCCall* pushCall(struct Context* ctx)
  107. {
  108. ctx->rpcCalls = Allocator_realloc(ctx->rpcAlloc,
  109. ctx->rpcCalls,
  110. sizeof(struct RPCCall) * (ctx->rpcCallCount+1));
  111. Bits_memset(&ctx->rpcCalls[ctx->rpcCallCount], 0, sizeof(struct RPCCall));
  112. return &ctx->rpcCalls[ctx->rpcCallCount++];
  113. }
  114. static void bindUDPCallback(struct RPCCall* call, struct AdminClient_Result* res)
  115. {
  116. Assert_true(!res->err);
  117. Log_debug(&call->node->nodeLog, "UDPInterface_new() -> [%s]", res->messageBytes);
  118. String* addr = Dict_getString(res->responseDict, String_CONST("bindAddress"));
  119. int64_t* ifNum = Dict_getInt(res->responseDict, String_CONST("interfaceNumber"));
  120. struct Sockaddr_storage ss;
  121. Assert_true(!Sockaddr_parse(addr->bytes, &ss));
  122. call->node->ifNum = *ifNum;
  123. call->node->udpAddr = Sockaddr_clone(&ss.addr, call->node->alloc);
  124. }
  125. static void bindUDP(struct Context* ctx, struct NodeContext* node)
  126. {
  127. struct RPCCall* call = pushCall(ctx);
  128. call->func = String_new("UDPInterface_new", ctx->rpcAlloc);
  129. call->args = Dict_new(ctx->rpcAlloc);
  130. call->node = node;
  131. call->callback = bindUDPCallback;
  132. }
  133. static void securitySetupComplete(struct Context* ctx, struct NodeContext* node)
  134. {
  135. struct RPCCall* call = pushCall(ctx);
  136. call->func = String_new("Security_setupComplete", ctx->rpcAlloc);
  137. call->args = Dict_new(ctx->rpcAlloc);
  138. call->node = node;
  139. }
  140. static struct NodeContext* startNode(char* nodeName,
  141. char* privateKeyHex,
  142. Dict* admin,
  143. struct Context* ctx,
  144. struct Except* eh)
  145. {
  146. struct NodeContext* node = Allocator_clone(ctx->alloc, (&(struct NodeContext) {
  147. .alloc = ctx->alloc,
  148. .base = ctx->base,
  149. .nodeLog = {
  150. .print = printLog
  151. },
  152. .parentLogger = ctx->logger,
  153. .nodeName = nodeName
  154. }));
  155. Identity_set(node);
  156. node->bind = Dict_getString(admin, String_CONST("bind"));
  157. if (!node->bind) {
  158. node->bind = String_new("127.0.0.1:0", ctx->alloc);
  159. }
  160. node->pass = Dict_getString(admin, String_CONST("password"));
  161. if (!node->pass) {
  162. node->pass = String_new("x", ctx->alloc);
  163. }
  164. Assert_true(Hex_decode(node->privateKey, 32, privateKeyHex, 64) == 32);
  165. struct AddrIfaceAdapter* adminClientIface = AddrIfaceAdapter_new(node->alloc);
  166. struct AddrIfaceAdapter* adminIface = AddrIfaceAdapter_new(node->alloc);
  167. struct ASynchronizer* asyncer = ASynchronizer_new(node->alloc, ctx->base);
  168. Iface_plumb(&asyncer->ifA, &adminClientIface->inputIf);
  169. Iface_plumb(&asyncer->ifB, &adminIface->inputIf);
  170. String* pass = String_new("12345", node->alloc);
  171. node->adminClient = AdminClient_new(&adminClientIface->generic,
  172. Sockaddr_clone(Sockaddr_LOOPBACK, node->alloc),
  173. pass,
  174. ctx->base,
  175. &node->nodeLog,
  176. node->alloc);
  177. node->admin = Admin_new(&adminIface->generic, &node->nodeLog, ctx->base, pass);
  178. Core_init(node->alloc, &node->nodeLog, ctx->base, node->privateKey, node->admin, ctx->rand, eh);
  179. securitySetupComplete(ctx, node);
  180. bindUDP(ctx, node);
  181. node->publicKey = pubKeyForPriv(node->privateKey, node->alloc);
  182. return node;
  183. }
  184. static void beginConnectionCallback(struct RPCCall* call, struct AdminClient_Result* res)
  185. {
  186. Assert_true(!res->err);
  187. Log_debug(&call->node->nodeLog, "UDPInterface_beginConnection() -> [%s]", res->messageBytes);
  188. }
  189. static void linkNodes(struct Context* ctx, struct NodeContext* client, struct NodeContext* server)
  190. {
  191. Dict* addPasswordArgs = Dict_new(ctx->rpcAlloc);
  192. String* clientStr = String_printf(ctx->rpcAlloc, "%ld", (long) (uintptr_t) client);
  193. Dict_putString(addPasswordArgs,
  194. String_new("password", ctx->rpcAlloc),
  195. clientStr,
  196. ctx->rpcAlloc);
  197. Dict_putString(addPasswordArgs,
  198. String_new("user", ctx->rpcAlloc),
  199. clientStr,
  200. ctx->rpcAlloc);
  201. struct RPCCall* addPasswordCall = pushCall(ctx);
  202. addPasswordCall->func = String_new("AuthorizedPasswords_add", ctx->rpcAlloc);
  203. addPasswordCall->args = addPasswordArgs;
  204. addPasswordCall->node = server;
  205. // client
  206. Dict* beginConnectionArgs = Dict_new(ctx->rpcAlloc);
  207. Dict_putInt(beginConnectionArgs,
  208. String_new("interfaceNumber", ctx->rpcAlloc),
  209. client->ifNum,
  210. ctx->rpcAlloc);
  211. Dict_putString(beginConnectionArgs,
  212. String_new("password", ctx->rpcAlloc),
  213. clientStr,
  214. ctx->rpcAlloc);
  215. Dict_putString(beginConnectionArgs,
  216. String_new("publicKey", ctx->rpcAlloc),
  217. server->publicKey,
  218. ctx->rpcAlloc);
  219. char* udpAddr = Sockaddr_print(server->udpAddr, ctx->rpcAlloc);
  220. Dict_putString(beginConnectionArgs,
  221. String_new("address", ctx->rpcAlloc),
  222. String_new(udpAddr, ctx->rpcAlloc),
  223. ctx->rpcAlloc);
  224. Log_info(ctx->logger, "Linking [%s] with [%s/%s]",
  225. client->nodeName, server->nodeName, udpAddr);
  226. struct RPCCall* connectCall = pushCall(ctx);
  227. connectCall->func = String_new("UDPInterface_beginConnection", ctx->rpcAlloc);
  228. connectCall->args = beginConnectionArgs;
  229. connectCall->node = client;
  230. connectCall->callback = beginConnectionCallback;
  231. }
  232. static void linkAllNodes(struct Context* ctx)
  233. {
  234. int i = 0;
  235. String* key = NULL;
  236. Dict_forEach(ctx->confNodes, key) {
  237. Dict* val = Dict_getDict(ctx->confNodes, key);
  238. List* connectTo = Dict_getList(val, String_CONST("peers"));
  239. for (int j = 0; j < List_size(connectTo); j++) {
  240. String* server = List_getString(connectTo, j);
  241. Assert_true(server);
  242. for (int k = 0; k < Dict_size(ctx->confNodes); k++) {
  243. if (String_equals(server, ctx->names[k])) {
  244. linkNodes(ctx, ctx->nodes[i], ctx->nodes[k]);
  245. break;
  246. }
  247. }
  248. }
  249. i++;
  250. }
  251. ctx->confNodes = NULL;
  252. }
  253. static void startRpc(void* vcontext);
  254. static void rpcCallback(struct AdminClient_Promise* promise, struct AdminClient_Result* res)
  255. {
  256. struct Context* ctx = promise->userData;
  257. Identity_check(ctx);
  258. struct RPCCall* thisCall = &ctx->rpcCalls[ctx->nextCall];
  259. if (thisCall->callback) {
  260. thisCall->callback(thisCall, res);
  261. }
  262. ctx->nextCall++;
  263. startRpc(ctx);
  264. }
  265. static void startRpc(void* vcontext)
  266. {
  267. struct Context* ctx = vcontext;
  268. Identity_check(ctx);
  269. if (ctx->nextCall >= ctx->rpcCallCount) {
  270. if (ctx->confNodes) {
  271. linkAllNodes(ctx);
  272. }
  273. }
  274. if (ctx->nextCall >= ctx->rpcCallCount) {
  275. Log_info(ctx->logger, "\n\nCompleted setting up simulation\n\n");
  276. Allocator_free(ctx->rpcAlloc);
  277. ctx->rpcAlloc = NULL;
  278. ctx->rpcCalls = NULL;
  279. ctx->rpcCallCount = 0;
  280. return;
  281. }
  282. struct RPCCall* nextCall = &ctx->rpcCalls[ctx->nextCall];
  283. struct AdminClient_Promise* promise = AdminClient_rpcCall(nextCall->func,
  284. nextCall->args,
  285. nextCall->node->adminClient,
  286. ctx->rpcAlloc);
  287. promise->callback = rpcCallback;
  288. promise->userData = ctx;
  289. }
  290. static void letErRip(Dict* config, struct Allocator* alloc)
  291. {
  292. struct Except* eh = NULL;
  293. struct Log* logger = FileWriterLog_new(stdout, alloc);
  294. struct EventBase* base = EventBase_new(alloc);
  295. struct Random* rand = LibuvEntropyProvider_newDefaultRandom(base, logger, eh, alloc);
  296. Allocator_setCanary(alloc, (unsigned long)Random_uint64(rand));
  297. struct Context sctx = {
  298. .rpcAlloc = Allocator_child(alloc),
  299. .logger = logger,
  300. .base = base,
  301. .rand = rand,
  302. .alloc = alloc,
  303. };
  304. struct Context* ctx = &sctx;
  305. Identity_set(ctx);
  306. ctx->confNodes = Dict_getDict(config, String_CONST("nodes"));
  307. ctx->nodes = Allocator_calloc(alloc, sizeof(char*), Dict_size(ctx->confNodes));
  308. ctx->names = Allocator_calloc(alloc, sizeof(String*), Dict_size(ctx->confNodes));
  309. String* key = NULL;
  310. int i = 0;
  311. Dict_forEach(ctx->confNodes, key) {
  312. Dict* val = Dict_getDict(ctx->confNodes, key);
  313. String* privateKeyHex = Dict_getString(val, String_CONST("privateKey"));
  314. Dict* admin = Dict_getDict(val, String_CONST("admin"));
  315. ctx->names[i] = key;
  316. ctx->nodes[i] = startNode(key->bytes, privateKeyHex->bytes, admin, ctx, eh);
  317. i++;
  318. }
  319. // begin the chain of RPC calls which sets up the net
  320. Timeout_setTimeout(startRpc, ctx, 0, base, ctx->rpcAlloc);
  321. EventBase_beginLoop(base);
  322. Allocator_free(alloc);
  323. }
  324. static int usage(char* appName)
  325. {
  326. printf("Example usage: %s < config.json\n"
  327. "Example config:\n"
  328. "{\n"
  329. " \"nodes\": {\n"
  330. " \"alice\": {\n"
  331. " \"privateKey\": "
  332. "\"5e2295679394e5e1db67c238abbc10292ad9b127904394c52cc5fff39383e920\",\n"
  333. " \"peers\": []\n"
  334. " },\n"
  335. " \"bob\": {\n"
  336. " \"privateKey\": "
  337. "\"6569bf3f0d168faa6dfb2912f8ee5ee9b938319e97618fdf06caed73b1aad1cc\",\n"
  338. " \"peers\": [\n"
  339. " \"alice\"\n"
  340. " ]\n"
  341. " }\n"
  342. " }\n"
  343. "}\n", appName);
  344. return 0;
  345. }
  346. int main(int argc, char** argv)
  347. {
  348. Assert_true(argc > 0);
  349. if (isatty(STDIN_FILENO)) {
  350. return usage(argv[0]);
  351. }
  352. struct Allocator* alloc = MallocAllocator_new(1<<30);
  353. struct Reader* stdinReader = FileReader_new(stdin, alloc);
  354. Dict config;
  355. if (JsonBencSerializer_get()->parseDictionary(stdinReader, alloc, &config)) {
  356. fprintf(stderr, "Failed to parse configuration.\n");
  357. return -1;
  358. }
  359. letErRip(&config, alloc);
  360. }