1
0

Configurator.c 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486
  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 "admin/AdminClient.h"
  16. #include "admin/Configurator.h"
  17. #include "benc/String.h"
  18. #include "benc/Dict.h"
  19. #include "benc/Int.h"
  20. #include "benc/List.h"
  21. #include "memory/Allocator.h"
  22. #include "util/events/Event.h"
  23. #include "util/Bits.h"
  24. #include "util/log/Log.h"
  25. #include "util/platform/Sockaddr.h"
  26. #include <stdlib.h>
  27. #include <stdbool.h>
  28. struct Context
  29. {
  30. struct Log* logger;
  31. struct Allocator* alloc;
  32. struct AdminClient* client;
  33. struct Allocator* currentReqAlloc;
  34. struct AdminClient_Result* currentResult;
  35. struct EventBase* base;
  36. };
  37. static void rpcCallback(struct AdminClient_Promise* p, struct AdminClient_Result* res)
  38. {
  39. struct Context* ctx = p->userData;
  40. Allocator_adopt(ctx->alloc, p->alloc);
  41. ctx->currentResult = res;
  42. EventBase_endLoop(ctx->base);
  43. }
  44. static void die(struct AdminClient_Result* res, struct Context* ctx, struct Allocator* alloc)
  45. {
  46. Log_keys(ctx->logger, "message bytes = [%s]", res->messageBytes);
  47. #ifndef Log_KEYS
  48. Log_critical(ctx->logger, "enable Log_LEVEL=KEYS to see message content.");
  49. #endif
  50. Dict d = NULL;
  51. struct AdminClient_Promise* exitPromise =
  52. AdminClient_rpcCall(String_CONST("Core_exit"), &d, ctx->client, alloc);
  53. exitPromise->callback = rpcCallback;
  54. exitPromise->userData = ctx;
  55. EventBase_beginLoop(ctx->base);
  56. if (ctx->currentResult->err) {
  57. Log_critical(ctx->logger, "Failed to stop the core.");
  58. }
  59. Log_critical(ctx->logger, "Aborting.");
  60. exit(1);
  61. }
  62. static int rpcCall0(String* function,
  63. Dict* args,
  64. struct Context* ctx,
  65. struct Allocator* alloc,
  66. bool exitIfError)
  67. {
  68. ctx->currentReqAlloc = Allocator_child(alloc);
  69. ctx->currentResult = NULL;
  70. struct AdminClient_Promise* promise = AdminClient_rpcCall(function, args, ctx->client, alloc);
  71. promise->callback = rpcCallback;
  72. promise->userData = ctx;
  73. EventBase_beginLoop(ctx->base);
  74. struct AdminClient_Result* res = ctx->currentResult;
  75. Assert_true(res);
  76. if (res->err) {
  77. Log_critical(ctx->logger,
  78. "Failed to make function call [%s], error: [%s]",
  79. AdminClient_errorString(res->err),
  80. function->bytes);
  81. die(res, ctx, alloc);
  82. }
  83. String* error = Dict_getString(res->responseDict, String_CONST("error"));
  84. int ret = 0;
  85. if (error && !String_equals(error, String_CONST("none"))) {
  86. if (exitIfError) {
  87. Log_critical(ctx->logger,
  88. "Got error [%s] calling [%s]",
  89. error->bytes,
  90. function->bytes);
  91. die(res, ctx, alloc);
  92. }
  93. Log_warn(ctx->logger, "Got error [%s] calling [%s], ignoring.",
  94. error->bytes, function->bytes);
  95. ret = 1;
  96. }
  97. Allocator_free(ctx->currentReqAlloc);
  98. ctx->currentReqAlloc = NULL;
  99. return ret;
  100. }
  101. static void rpcCall(String* function, Dict* args, struct Context* ctx, struct Allocator* alloc)
  102. {
  103. rpcCall0(function, args, ctx, alloc, true);
  104. }
  105. static void authorizedPasswords(List* list, struct Context* ctx)
  106. {
  107. uint32_t count = List_size(list);
  108. for (uint32_t i = 0; i < count; i++) {
  109. Dict* d = List_getDict(list, i);
  110. Log_info(ctx->logger, "Checking authorized password %d.", i);
  111. if (!d) {
  112. Log_critical(ctx->logger, "Not a dictionary type %d.", i);
  113. exit(-1);
  114. }
  115. String* passwd = Dict_getString(d, String_CONST("password"));
  116. if (!passwd) {
  117. Log_critical(ctx->logger, "Must specify a password %d.", i);
  118. exit(-1);
  119. }
  120. }
  121. for (uint32_t i = 0; i < count; i++) {
  122. struct Allocator* child = Allocator_child(ctx->alloc);
  123. Dict* d = List_getDict(list, i);
  124. String* passwd = Dict_getString(d, String_CONST("password"));
  125. String* user = Dict_getString(d, String_CONST("user"));
  126. if (!user) {
  127. user = String_printf(child, "password [%d]", i);
  128. }
  129. //String* publicKey = Dict_getString(d, String_CONST("publicKey"));
  130. String* ipv6 = Dict_getString(d, String_CONST("ipv6"));
  131. Log_info(ctx->logger, "Adding authorized password #[%d] for user [%s].", i, user->bytes);
  132. Dict *args = Dict_new(child);
  133. uint32_t i = 1;
  134. Dict_putInt(args, String_CONST("authType"), i, child);
  135. Dict_putString(args, String_CONST("password"), passwd, child);
  136. Dict_putString(args, String_CONST("user"), user, child);
  137. if (ipv6) {
  138. Log_info(ctx->logger,
  139. " This connection password restricted to [%s] only.", ipv6->bytes);
  140. Dict_putString(args, String_CONST("ipv6"), ipv6, child);
  141. }
  142. rpcCall(String_CONST("AuthorizedPasswords_add"), args, ctx, child);
  143. Allocator_free(child);
  144. }
  145. }
  146. static void dns(Dict* dns, struct Context* ctx, struct Except* eh)
  147. {
  148. List* servers = Dict_getList(dns, String_CONST("servers"));
  149. if (servers) {
  150. int count = List_size(servers);
  151. for (int i = 0; i < count; i++) {
  152. String* server = List_getString(servers, i);
  153. if (!server) {
  154. Except_throw(eh, "dns.servers[%d] is not a string", i);
  155. }
  156. Dict* d = Dict_new(ctx->alloc);
  157. Dict_putString(d, String_CONST("addr"), server, ctx->alloc);
  158. rpcCall(String_CONST("RainflyClient_addServer"), d, ctx, ctx->alloc);
  159. }
  160. }
  161. List* keys = Dict_getList(dns, String_CONST("keys"));
  162. if (keys) {
  163. int count = List_size(keys);
  164. for (int i = 0; i < count; i++) {
  165. String* key = List_getString(keys, i);
  166. if (!key) {
  167. Except_throw(eh, "dns.keys[%d] is not a string", i);
  168. }
  169. Dict* d = Dict_new(ctx->alloc);
  170. Dict_putString(d, String_CONST("ident"), key, ctx->alloc);
  171. rpcCall(String_CONST("RainflyClient_addKey"), d, ctx, ctx->alloc);
  172. }
  173. }
  174. int64_t* minSigs = Dict_getInt(dns, String_CONST("minSignatures"));
  175. if (minSigs) {
  176. Dict* d = Dict_new(ctx->alloc);
  177. Dict_putInt(d, String_CONST("count"), *minSigs, ctx->alloc);
  178. rpcCall(String_CONST("RainflyClient_minSignatures"), d, ctx, ctx->alloc);
  179. }
  180. }
  181. static void udpInterface(Dict* config, struct Context* ctx)
  182. {
  183. List* ifaces = Dict_getList(config, String_CONST("UDPInterface"));
  184. if (!ifaces) {
  185. ifaces = List_new(ctx->alloc);
  186. List_addDict(ifaces, Dict_getDict(config, String_CONST("UDPInterface")), ctx->alloc);
  187. }
  188. uint32_t count = List_size(ifaces);
  189. for (uint32_t i = 0; i < count; i++) {
  190. Dict *udp = List_getDict(ifaces, i);
  191. if (!udp) {
  192. continue;
  193. }
  194. // Setup the interface.
  195. String* bindStr = Dict_getString(udp, String_CONST("bind"));
  196. Dict* d = Dict_new(ctx->alloc);
  197. if (bindStr) {
  198. Dict_putString(d, String_CONST("bindAddress"), bindStr, ctx->alloc);
  199. }
  200. rpcCall(String_CONST("UDPInterface_new"), d, ctx, ctx->alloc);
  201. // Make the connections.
  202. Dict* connectTo = Dict_getDict(udp, String_CONST("connectTo"));
  203. if (connectTo) {
  204. struct Dict_Entry* entry = *connectTo;
  205. struct Allocator* perCallAlloc = Allocator_child(ctx->alloc);
  206. while (entry != NULL) {
  207. String* key = (String*) entry->key;
  208. if (entry->val->type != Object_DICT) {
  209. Log_critical(ctx->logger, "interfaces.UDPInterface.connectTo: entry [%s] "
  210. "is not a dictionary type.", key->bytes);
  211. exit(-1);
  212. }
  213. Dict* value = entry->val->as.dictionary;
  214. Log_keys(ctx->logger, "Attempting to connect to node [%s].", key->bytes);
  215. key = String_clone(key, perCallAlloc);
  216. char* lastColon = CString_strrchr(key->bytes, ':');
  217. if (!Sockaddr_parse(key->bytes, NULL)) {
  218. // it's a sockaddr, fall through
  219. } else if (lastColon) {
  220. // try it as a hostname.
  221. int port = atoi(lastColon+1);
  222. if (!port) {
  223. Log_critical(ctx->logger, "Couldn't get port number from [%s]", key->bytes);
  224. exit(-1);
  225. }
  226. *lastColon = '\0';
  227. struct Sockaddr* adr = Sockaddr_fromName(key->bytes, perCallAlloc);
  228. if (adr != NULL) {
  229. Sockaddr_setPort(adr, port);
  230. key = String_new(Sockaddr_print(adr, perCallAlloc), perCallAlloc);
  231. } else {
  232. Log_warn(ctx->logger, "Failed to lookup hostname [%s]", key->bytes);
  233. entry = entry->next;
  234. continue;
  235. }
  236. }
  237. Dict_putString(value, String_CONST("address"), key, perCallAlloc);
  238. rpcCall(String_CONST("UDPInterface_beginConnection"), value, ctx, perCallAlloc);
  239. entry = entry->next;
  240. }
  241. Allocator_free(perCallAlloc);
  242. }
  243. }
  244. }
  245. static void tunInterface(Dict* ifaceConf, struct Allocator* tempAlloc, struct Context* ctx)
  246. {
  247. String* ifaceType = Dict_getString(ifaceConf, String_CONST("type"));
  248. if (!String_equals(ifaceType, String_CONST("TUNInterface"))) {
  249. return;
  250. }
  251. // Setup the interface.
  252. String* device = Dict_getString(ifaceConf, String_CONST("tunDevice"));
  253. Dict* args = Dict_new(tempAlloc);
  254. if (device) {
  255. Dict_putString(args, String_CONST("desiredTunName"), device, tempAlloc);
  256. }
  257. rpcCall0(String_CONST("Core_initTunnel"), args, ctx, tempAlloc, false);
  258. }
  259. static void ipTunnel(Dict* ifaceConf, struct Allocator* tempAlloc, struct Context* ctx)
  260. {
  261. List* incoming = Dict_getList(ifaceConf, String_CONST("allowedConnections"));
  262. if (incoming) {
  263. Dict* d;
  264. for (int i = 0; (d = List_getDict(incoming, i)) != NULL; i++) {
  265. String* key = Dict_getString(d, String_CONST("publicKey"));
  266. String* ip4 = Dict_getString(d, String_CONST("ip4Address"));
  267. // Note that the prefix length has to be a proper int in the config
  268. // (not quoted!)
  269. int64_t* ip4Prefix = Dict_getInt(d, String_CONST("ip4Prefix"));
  270. String* ip6 = Dict_getString(d, String_CONST("ip6Address"));
  271. int64_t* ip6Prefix = Dict_getInt(d, String_CONST("ip6Prefix"));
  272. if (!key) {
  273. Log_critical(ctx->logger, "In router.ipTunnel.allowedConnections[%d]"
  274. "'publicKey' required.", i);
  275. exit(1);
  276. }
  277. if (!ip4 && !ip6) {
  278. Log_critical(ctx->logger, "In router.ipTunnel.allowedConnections[%d]"
  279. "either 'ip4Address' or 'ip6Address' required.", i);
  280. exit(1);
  281. } else if (ip4Prefix && !ip4) {
  282. Log_critical(ctx->logger, "In router.ipTunnel.allowedConnections[%d]"
  283. "'ip4Address' required with 'ip4Prefix'.", i);
  284. exit(1);
  285. } else if (ip6Prefix && !ip6) {
  286. Log_critical(ctx->logger, "In router.ipTunnel.allowedConnections[%d]"
  287. "'ip6Address' required with 'ip6Prefix'.", i);
  288. exit(1);
  289. }
  290. Log_debug(ctx->logger, "Allowing IpTunnel connections from [%s]", key->bytes);
  291. if (ip4) {
  292. Log_debug(ctx->logger, "Issue IPv4 address %s", ip4->bytes);
  293. if (ip4Prefix) {
  294. Log_debug(ctx->logger, "Issue IPv4 netmask/prefix length /%d",
  295. (int) *ip4Prefix);
  296. } else {
  297. Log_debug(ctx->logger, "Use default netmask/prefix length /0");
  298. }
  299. }
  300. if (ip6) {
  301. Log_debug(ctx->logger, "Issue IPv6 address [%s]", ip6->bytes);
  302. if (ip6Prefix) {
  303. Log_debug(ctx->logger, "Issue IPv6 netmask/prefix length /%d",
  304. (int) *ip6Prefix);
  305. } else {
  306. Log_debug(ctx->logger, "Use default netmask/prefix length /0");
  307. }
  308. }
  309. Dict_putString(d, String_CONST("publicKeyOfAuthorizedNode"), key, tempAlloc);
  310. rpcCall0(String_CONST("IpTunnel_allowConnection"), d, ctx, tempAlloc, true);
  311. }
  312. }
  313. List* outgoing = Dict_getList(ifaceConf, String_CONST("outgoingConnections"));
  314. if (outgoing) {
  315. String* s;
  316. for (int i = 0; (s = List_getString(outgoing, i)) != NULL; i++) {
  317. Log_debug(ctx->logger, "Initiating IpTunnel connection to [%s]", s->bytes);
  318. Dict requestDict =
  319. Dict_CONST(String_CONST("publicKeyOfNodeToConnectTo"), String_OBJ(s), NULL);
  320. rpcCall0(String_CONST("IpTunnel_connectTo"), &requestDict, ctx, tempAlloc, true);
  321. }
  322. }
  323. }
  324. static void routerConfig(Dict* routerConf, struct Allocator* tempAlloc, struct Context* ctx)
  325. {
  326. tunInterface(Dict_getDict(routerConf, String_CONST("interface")), tempAlloc, ctx);
  327. ipTunnel(Dict_getDict(routerConf, String_CONST("ipTunnel")), tempAlloc, ctx);
  328. }
  329. #ifdef HAS_ETH_INTERFACE
  330. static void ethInterface(Dict* config, struct Context* ctx)
  331. {
  332. List* ifaces = Dict_getList(config, String_CONST("ETHInterface"));
  333. if (!ifaces) {
  334. ifaces = List_new(ctx->alloc);
  335. List_addDict(ifaces, Dict_getDict(config, String_CONST("ETHInterface")), ctx->alloc);
  336. }
  337. uint32_t count = List_size(ifaces);
  338. for (uint32_t i = 0; i < count; i++) {
  339. Dict *eth = List_getDict(ifaces, i);
  340. if (!eth) {
  341. continue;
  342. }
  343. // Setup the interface.
  344. String* deviceStr = Dict_getString(eth, String_CONST("bind"));
  345. Log_info(ctx->logger, "Setting up ETHInterface [%d].", i);
  346. Dict* d = Dict_new(ctx->alloc);
  347. if (deviceStr) {
  348. Log_info(ctx->logger, "Binding to device [%s].", deviceStr->bytes);
  349. Dict_putString(d, String_CONST("bindDevice"), deviceStr, ctx->alloc);
  350. }
  351. if (rpcCall0(String_CONST("ETHInterface_new"), d, ctx, ctx->alloc, false)) {
  352. Log_warn(ctx->logger, "Failed to create ETHInterface.");
  353. continue;
  354. }
  355. // Make the connections.
  356. Dict* connectTo = Dict_getDict(eth, String_CONST("connectTo"));
  357. if (connectTo) {
  358. Log_info(ctx->logger, "ETHInterface should connect to a specific node.");
  359. struct Dict_Entry* entry = *connectTo;
  360. while (entry != NULL) {
  361. String* key = (String*) entry->key;
  362. if (entry->val->type != Object_DICT) {
  363. Log_critical(ctx->logger, "interfaces.ETHInterface.connectTo: entry [%s] "
  364. "is not a dictionary type.", key->bytes);
  365. exit(-1);
  366. }
  367. Dict* value = entry->val->as.dictionary;
  368. Log_keys(ctx->logger, "Attempting to connect to node [%s].", key->bytes);
  369. struct Allocator* perCallAlloc = Allocator_child(ctx->alloc);
  370. // Turn the dict from the config into our RPC args dict by filling in all
  371. // the arguments,
  372. Dict_putString(value, String_CONST("macAddress"), key, perCallAlloc);
  373. Dict_putInt(value, String_CONST("interfaceNumber"), i, perCallAlloc);
  374. rpcCall(String_CONST("ETHInterface_beginConnection"), value, ctx, perCallAlloc);
  375. Allocator_free(perCallAlloc);
  376. entry = entry->next;
  377. }
  378. }
  379. int64_t* beaconP = Dict_getInt(eth, String_CONST("beacon"));
  380. if (beaconP) {
  381. int64_t beacon = *beaconP;
  382. if (beacon > 3 || beacon < 0) {
  383. Log_error(ctx->logger, "interfaces.ETHInterface.beacon may only be 0, 1,or 2");
  384. } else {
  385. // We can cast beacon to an int here because we know it's small enough
  386. Log_info(ctx->logger, "Setting beacon mode on ETHInterface to [%d].", (int) beacon);
  387. Dict d = Dict_CONST(String_CONST("interfaceNumber"), Int_OBJ(i),
  388. Dict_CONST(String_CONST("state"), Int_OBJ(beacon), NULL));
  389. rpcCall(String_CONST("ETHInterface_beacon"), &d, ctx, ctx->alloc);
  390. }
  391. }
  392. }
  393. }
  394. #endif
  395. static void security(struct Allocator* tempAlloc, struct Context* ctx)
  396. {
  397. Dict* d = Dict_new(tempAlloc);
  398. Dict_putString(d, String_CONST("user"), String_CONST("nobody"), tempAlloc);
  399. // it's ok if this fails
  400. rpcCall0(String_CONST("Security_setUser"), d, ctx, tempAlloc, false);
  401. d = Dict_new(tempAlloc);
  402. rpcCall(String_CONST("Security_dropPermissions"), d, ctx, tempAlloc);
  403. }
  404. void Configurator_config(Dict* config,
  405. struct Sockaddr* sockAddr,
  406. String* adminPassword,
  407. struct EventBase* eventBase,
  408. struct Log* logger,
  409. struct Allocator* alloc)
  410. {
  411. struct Except* eh = NULL;
  412. struct Allocator* tempAlloc = Allocator_child(alloc);
  413. struct AdminClient* client =
  414. AdminClient_new(sockAddr, adminPassword, eventBase, logger, tempAlloc);
  415. struct Context ctx = {
  416. .logger = logger,
  417. .alloc = tempAlloc,
  418. .client = client,
  419. .base = eventBase,
  420. };
  421. List* authedPasswords = Dict_getList(config, String_CONST("authorizedPasswords"));
  422. if (authedPasswords) {
  423. authorizedPasswords(authedPasswords, &ctx);
  424. }
  425. Dict* ifaces = Dict_getDict(config, String_CONST("interfaces"));
  426. udpInterface(ifaces, &ctx);
  427. #ifdef HAS_ETH_INTERFACE
  428. ethInterface(ifaces, &ctx);
  429. #endif
  430. Dict* routerConf = Dict_getDict(config, String_CONST("router"));
  431. routerConfig(routerConf, tempAlloc, &ctx);
  432. security(tempAlloc, &ctx);
  433. Dict* dnsConf = Dict_getDict(config, String_CONST("dns"));
  434. dns(dnsConf, &ctx, eh);
  435. Allocator_free(tempAlloc);
  436. }