Configurator.c 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453
  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. String* ip6 = Dict_getString(d, String_CONST("ip6Address"));
  268. if (!key) {
  269. Log_critical(ctx->logger, "In router.ipTunnel.allowedConnections[%d]"
  270. "'publicKey' required.", i);
  271. exit(1);
  272. }
  273. if (!ip4 && !ip6) {
  274. Log_critical(ctx->logger, "In router.ipTunnel.allowedConnections[%d]"
  275. "either ip4Address or ip6Address required.", i);
  276. exit(1);
  277. }
  278. Log_debug(ctx->logger, "Allowing IpTunnel connections from [%s]", key->bytes);
  279. Dict_putString(d, String_CONST("publicKeyOfAuthorizedNode"), key, tempAlloc);
  280. rpcCall0(String_CONST("IpTunnel_allowConnection"), d, ctx, tempAlloc, true);
  281. }
  282. }
  283. List* outgoing = Dict_getList(ifaceConf, String_CONST("outgoingConnections"));
  284. if (outgoing) {
  285. String* s;
  286. for (int i = 0; (s = List_getString(outgoing, i)) != NULL; i++) {
  287. Log_debug(ctx->logger, "Initiating IpTunnel connection to [%s]", s->bytes);
  288. Dict requestDict =
  289. Dict_CONST(String_CONST("publicKeyOfNodeToConnectTo"), String_OBJ(s), NULL);
  290. rpcCall0(String_CONST("IpTunnel_connectTo"), &requestDict, ctx, tempAlloc, true);
  291. }
  292. }
  293. }
  294. static void routerConfig(Dict* routerConf, struct Allocator* tempAlloc, struct Context* ctx)
  295. {
  296. tunInterface(Dict_getDict(routerConf, String_CONST("interface")), tempAlloc, ctx);
  297. ipTunnel(Dict_getDict(routerConf, String_CONST("ipTunnel")), tempAlloc, ctx);
  298. }
  299. #ifdef HAS_ETH_INTERFACE
  300. static void ethInterface(Dict* config, struct Context* ctx)
  301. {
  302. List* ifaces = Dict_getList(config, String_CONST("ETHInterface"));
  303. if (!ifaces) {
  304. ifaces = List_new(ctx->alloc);
  305. List_addDict(ifaces, Dict_getDict(config, String_CONST("ETHInterface")), ctx->alloc);
  306. }
  307. uint32_t count = List_size(ifaces);
  308. for (uint32_t i = 0; i < count; i++) {
  309. Dict *eth = List_getDict(ifaces, i);
  310. if (!eth) {
  311. continue;
  312. }
  313. // Setup the interface.
  314. String* deviceStr = Dict_getString(eth, String_CONST("bind"));
  315. Log_info(ctx->logger, "Setting up ETHInterface [%d].", i);
  316. Dict* d = Dict_new(ctx->alloc);
  317. if (deviceStr) {
  318. Log_info(ctx->logger, "Binding to device [%s].", deviceStr->bytes);
  319. Dict_putString(d, String_CONST("bindDevice"), deviceStr, ctx->alloc);
  320. }
  321. if (rpcCall0(String_CONST("ETHInterface_new"), d, ctx, ctx->alloc, false)) {
  322. Log_warn(ctx->logger, "Failed to create ETHInterface.");
  323. continue;
  324. }
  325. // Make the connections.
  326. Dict* connectTo = Dict_getDict(eth, String_CONST("connectTo"));
  327. if (connectTo) {
  328. Log_info(ctx->logger, "ETHInterface should connect to a specific node.");
  329. struct Dict_Entry* entry = *connectTo;
  330. while (entry != NULL) {
  331. String* key = (String*) entry->key;
  332. if (entry->val->type != Object_DICT) {
  333. Log_critical(ctx->logger, "interfaces.ETHInterface.connectTo: entry [%s] "
  334. "is not a dictionary type.", key->bytes);
  335. exit(-1);
  336. }
  337. Dict* value = entry->val->as.dictionary;
  338. Log_keys(ctx->logger, "Attempting to connect to node [%s].", key->bytes);
  339. struct Allocator* perCallAlloc = Allocator_child(ctx->alloc);
  340. // Turn the dict from the config into our RPC args dict by filling in all
  341. // the arguments,
  342. Dict_putString(value, String_CONST("macAddress"), key, perCallAlloc);
  343. Dict_putInt(value, String_CONST("interfaceNumber"), i, perCallAlloc);
  344. rpcCall(String_CONST("ETHInterface_beginConnection"), value, ctx, perCallAlloc);
  345. Allocator_free(perCallAlloc);
  346. entry = entry->next;
  347. }
  348. }
  349. int64_t* beaconP = Dict_getInt(eth, String_CONST("beacon"));
  350. if (beaconP) {
  351. int64_t beacon = *beaconP;
  352. if (beacon > 3 || beacon < 0) {
  353. Log_error(ctx->logger, "interfaces.ETHInterface.beacon may only be 0, 1,or 2");
  354. } else {
  355. // We can cast beacon to an int here because we know it's small enough
  356. Log_info(ctx->logger, "Setting beacon mode on ETHInterface to [%d].", (int) beacon);
  357. Dict d = Dict_CONST(String_CONST("interfaceNumber"), Int_OBJ(i),
  358. Dict_CONST(String_CONST("state"), Int_OBJ(beacon), NULL));
  359. rpcCall(String_CONST("ETHInterface_beacon"), &d, ctx, ctx->alloc);
  360. }
  361. }
  362. }
  363. }
  364. #endif
  365. static void security(struct Allocator* tempAlloc, struct Context* ctx)
  366. {
  367. Dict* d = Dict_new(tempAlloc);
  368. Dict_putString(d, String_CONST("user"), String_CONST("nobody"), tempAlloc);
  369. // it's ok if this fails
  370. rpcCall0(String_CONST("Security_setUser"), d, ctx, tempAlloc, false);
  371. d = Dict_new(tempAlloc);
  372. rpcCall(String_CONST("Security_dropPermissions"), d, ctx, tempAlloc);
  373. }
  374. void Configurator_config(Dict* config,
  375. struct Sockaddr* sockAddr,
  376. String* adminPassword,
  377. struct EventBase* eventBase,
  378. struct Log* logger,
  379. struct Allocator* alloc)
  380. {
  381. struct Except* eh = NULL;
  382. struct Allocator* tempAlloc = Allocator_child(alloc);
  383. struct AdminClient* client =
  384. AdminClient_new(sockAddr, adminPassword, eventBase, logger, tempAlloc);
  385. struct Context ctx = {
  386. .logger = logger,
  387. .alloc = tempAlloc,
  388. .client = client,
  389. .base = eventBase,
  390. };
  391. List* authedPasswords = Dict_getList(config, String_CONST("authorizedPasswords"));
  392. if (authedPasswords) {
  393. authorizedPasswords(authedPasswords, &ctx);
  394. }
  395. Dict* ifaces = Dict_getDict(config, String_CONST("interfaces"));
  396. udpInterface(ifaces, &ctx);
  397. #ifdef HAS_ETH_INTERFACE
  398. ethInterface(ifaces, &ctx);
  399. #endif
  400. Dict* routerConf = Dict_getDict(config, String_CONST("router"));
  401. routerConfig(routerConf, tempAlloc, &ctx);
  402. security(tempAlloc, &ctx);
  403. Dict* dnsConf = Dict_getDict(config, String_CONST("dns"));
  404. dns(dnsConf, &ctx, eh);
  405. Allocator_free(tempAlloc);
  406. }