Core.c 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328
  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/Admin.h"
  16. #include "admin/AdminLog.h"
  17. #include "admin/angel/Core.h"
  18. #include "admin/angel/InterfaceWaiter.h"
  19. #include "admin/AuthorizedPasswords.h"
  20. #include "benc/Int.h"
  21. #include "benc/serialization/standard/BencMessageReader.h"
  22. #include "benc/serialization/standard/BencMessageWriter.h"
  23. #include "crypto/AddressCalc.h"
  24. #include "crypto/random/Random.h"
  25. #include "crypto/random/libuv/LibuvEntropyProvider.h"
  26. #include "dht/Pathfinder.h"
  27. #include "exception/Jmp.h"
  28. #include "interface/Iface.h"
  29. #include "util/events/UDPAddrIface.h"
  30. #include "interface/tuntap/TUNInterface.h"
  31. #include "interface/UDPInterface_admin.h"
  32. #ifdef HAS_ETH_INTERFACE
  33. #include "interface/ETHInterface_admin.h"
  34. #endif
  35. #include "net/InterfaceController_admin.h"
  36. #include "interface/addressable/PacketHeaderToUDPAddrIface.h"
  37. #include "interface/ASynchronizer.h"
  38. #include "interface/FramingIface.h"
  39. #include "memory/Allocator.h"
  40. #include "memory/MallocAllocator.h"
  41. #include "memory/Allocator_admin.h"
  42. #include "net/SwitchPinger_admin.h"
  43. #include "tunnel/IpTunnel_admin.h"
  44. #include "util/events/EventBase.h"
  45. #include "util/events/Pipe.h"
  46. #include "util/events/Timeout.h"
  47. #include "util/Hex.h"
  48. #include "util/log/FileWriterLog.h"
  49. #include "util/log/IndirectLog.h"
  50. #include "util/platform/netdev/NetDev.h"
  51. #include "util/Security_admin.h"
  52. #include "util/Security.h"
  53. #include "util/version/Version.h"
  54. #include "net/SessionManager_admin.h"
  55. #include "wire/SwitchHeader.h"
  56. #include "wire/CryptoHeader.h"
  57. #include "wire/Headers.h"
  58. #include "net/NetCore.h"
  59. #include <crypto_scalarmult_curve25519.h>
  60. #include <stdlib.h>
  61. #include <unistd.h>
  62. // Failsafe: abort if more than 2^23 bytes are allocated (8MB)
  63. #define ALLOCATOR_FAILSAFE (1<<23)
  64. // TODO(cjd): we need to begin detecting MTU and informing the OS properly!
  65. /**
  66. * The worst possible packet overhead, we're in session setup with the endpoint.
  67. */
  68. #define WORST_CASE_OVERHEAD ( \
  69. Headers_IP4Header_SIZE \
  70. + Headers_UDPHeader_SIZE \
  71. + 4 /* Nonce */ \
  72. + 16 /* Poly1305 authenticator */ \
  73. + SwitchHeader_SIZE \
  74. + CryptoHeader_SIZE \
  75. + 4 /* Handle */ \
  76. + DataHeader_SIZE \
  77. )
  78. /** The default MTU, assuming the external MTU is 1492 (common for PPPoE DSL) */
  79. #define DEFAULT_MTU ( 1492 - WORST_CASE_OVERHEAD )
  80. static void adminPing(Dict* input, void* vadmin, String* txid, struct Allocator* requestAlloc)
  81. {
  82. Dict d = Dict_CONST(String_CONST("q"), String_OBJ(String_CONST("pong")), NULL);
  83. Admin_sendMessage(&d, txid, (struct Admin*) vadmin);
  84. }
  85. static void adminPid(Dict* input, void* vadmin, String* txid, struct Allocator* requestAlloc)
  86. {
  87. int pid = getpid();
  88. Dict d = Dict_CONST(String_CONST("pid"), Int_OBJ(pid), NULL);
  89. Admin_sendMessage(&d, txid, (struct Admin*) vadmin);
  90. }
  91. struct Context
  92. {
  93. struct Allocator* alloc;
  94. struct Admin* admin;
  95. struct Log* logger;
  96. struct EventBase* base;
  97. struct NetCore* nc;
  98. struct IpTunnel* ipTunnel;
  99. Identity
  100. };
  101. static void shutdown(void* vcontext)
  102. {
  103. struct Context* context = Identity_check((struct Context*) vcontext);
  104. Allocator_free(context->alloc);
  105. }
  106. static void adminExit(Dict* input, void* vcontext, String* txid, struct Allocator* requestAlloc)
  107. {
  108. struct Context* context = Identity_check((struct Context*) vcontext);
  109. Log_info(context->logger, "Got request to exit");
  110. Dict d = Dict_CONST(String_CONST("error"), String_OBJ(String_CONST("none")), NULL);
  111. Admin_sendMessage(&d, txid, context->admin);
  112. Timeout_setTimeout(shutdown, context, 1, context->base, context->alloc);
  113. }
  114. static void sendResponse(String* error,
  115. struct Admin* admin,
  116. String* txid,
  117. struct Allocator* tempAlloc)
  118. {
  119. Dict* output = Dict_new(tempAlloc);
  120. Dict_putString(output, String_CONST("error"), error, tempAlloc);
  121. Admin_sendMessage(output, txid, admin);
  122. }
  123. static void initTunnel2(String* desiredDeviceName,
  124. struct Context* ctx,
  125. uint8_t addressPrefix,
  126. struct Except* eh)
  127. {
  128. Log_debug(ctx->logger, "Initializing TUN device [%s]",
  129. (desiredDeviceName) ? desiredDeviceName->bytes : "<auto>");
  130. char assignedTunName[TUNInterface_IFNAMSIZ];
  131. char* desiredName = (desiredDeviceName) ? desiredDeviceName->bytes : NULL;
  132. struct Iface* tun = TUNInterface_new(
  133. desiredName, assignedTunName, 0, ctx->base, ctx->logger, eh, ctx->alloc);
  134. Iface_plumb(tun, &ctx->nc->tunAdapt->tunIf);
  135. IpTunnel_setTunName(assignedTunName, ctx->ipTunnel);
  136. struct Sockaddr* myAddr =
  137. Sockaddr_fromBytes(ctx->nc->myAddress->ip6.bytes, Sockaddr_AF_INET6, ctx->alloc);
  138. NetDev_addAddress(assignedTunName, myAddr, addressPrefix, ctx->logger, eh);
  139. NetDev_setMTU(assignedTunName, DEFAULT_MTU, ctx->logger, eh);
  140. }
  141. static void initTunnel(Dict* args, void* vcontext, String* txid, struct Allocator* requestAlloc)
  142. {
  143. struct Context* const ctx = Identity_check((struct Context*) vcontext);
  144. struct Jmp jmp;
  145. Jmp_try(jmp) {
  146. String* desiredName = Dict_getString(args, String_CONST("desiredTunName"));
  147. initTunnel2(desiredName, ctx, 8, &jmp.handler);
  148. } Jmp_catch {
  149. String* error = String_printf(requestAlloc, "Failed to configure tunnel [%s]", jmp.message);
  150. sendResponse(error, ctx->admin, txid, requestAlloc);
  151. return;
  152. }
  153. sendResponse(String_CONST("none"), ctx->admin, txid, requestAlloc);
  154. }
  155. void Core_init(struct Allocator* alloc,
  156. struct Log* logger,
  157. struct EventBase* eventBase,
  158. uint8_t privateKey[32],
  159. struct Admin* admin,
  160. struct Random* rand,
  161. struct Except* eh)
  162. {
  163. struct Security* sec = Security_new(alloc, logger, eventBase);
  164. struct NetCore* nc = NetCore_new(privateKey, alloc, eventBase, rand, logger);
  165. struct IpTunnel* ipTunnel = IpTunnel_new(logger, eventBase, alloc, rand);
  166. Iface_plumb(&nc->tunAdapt->ipTunnelIf, &ipTunnel->tunInterface);
  167. Iface_plumb(&nc->upper->ipTunnelIf, &ipTunnel->nodeInterface);
  168. // The link between the Pathfinder and the core needs to be asynchronous.
  169. struct Pathfinder* pf = Pathfinder_register(alloc, logger, eventBase, rand, admin);
  170. struct ASynchronizer* pfAsync = ASynchronizer_new(alloc, eventBase, logger);
  171. Iface_plumb(&pfAsync->ifA, &pf->eventIf);
  172. EventEmitter_regPathfinderIface(nc->ee, &pfAsync->ifB);
  173. // ------------------- Register RPC functions ----------------------- //
  174. InterfaceController_admin_register(nc->ifController, admin, alloc);
  175. SwitchPinger_admin_register(nc->sp, admin, alloc);
  176. UDPInterface_admin_register(eventBase, alloc, logger, admin, nc->ifController);
  177. #ifdef HAS_ETH_INTERFACE
  178. ETHInterface_admin_register(eventBase, alloc, logger, admin, nc->ifController);
  179. #endif
  180. AuthorizedPasswords_init(admin, nc->ca, alloc);
  181. Admin_registerFunction("ping", adminPing, admin, false, NULL, admin);
  182. Security_admin_register(alloc, logger, sec, admin);
  183. IpTunnel_admin_register(ipTunnel, admin, alloc);
  184. SessionManager_admin_register(nc->sm, admin, alloc);
  185. Allocator_admin_register(alloc, admin);
  186. struct Context* ctx = Allocator_calloc(alloc, sizeof(struct Context), 1);
  187. Identity_set(ctx);
  188. ctx->alloc = alloc;
  189. ctx->admin = admin;
  190. ctx->logger = logger;
  191. ctx->base = eventBase;
  192. ctx->ipTunnel = ipTunnel;
  193. ctx->nc = nc;
  194. Admin_registerFunction("Core_exit", adminExit, ctx, true, NULL, admin);
  195. Admin_registerFunction("Core_pid", adminPid, admin, false, NULL, admin);
  196. Admin_registerFunction("Core_initTunnel", initTunnel, ctx, true,
  197. ((struct Admin_FunctionArg[]) {
  198. { .name = "desiredTunName", .required = 0, .type = "String" }
  199. }), admin);
  200. }
  201. int Core_main(int argc, char** argv)
  202. {
  203. struct Except* eh = NULL;
  204. if (argc != 3) {
  205. Except_throw(eh, "This is internal to cjdns and shouldn't started manually.");
  206. }
  207. struct Allocator* alloc = MallocAllocator_new(ALLOCATOR_FAILSAFE);
  208. struct Log* preLogger = FileWriterLog_new(stderr, alloc);
  209. struct EventBase* eventBase = EventBase_new(alloc);
  210. // -------------------- Setup the Pre-Logger ---------------------- //
  211. struct Log* logger = IndirectLog_new(alloc);
  212. IndirectLog_set(logger, preLogger);
  213. // -------------------- Setup the PRNG ---------------------- //
  214. struct Random* rand = LibuvEntropyProvider_newDefaultRandom(eventBase, logger, eh, alloc);
  215. // -------------------- Change Canary Value ---------------------- //
  216. Allocator_setCanary(alloc, (unsigned long)Random_uint64(rand));
  217. struct Allocator* tempAlloc = Allocator_child(alloc);
  218. struct Pipe* clientPipe = Pipe_named(argv[2], eventBase, eh, tempAlloc);
  219. clientPipe->logger = logger;
  220. Log_debug(logger, "Getting pre-configuration from client");
  221. struct Message* preConf =
  222. InterfaceWaiter_waitForData(&clientPipe->iface, eventBase, tempAlloc, eh);
  223. Log_debug(logger, "Finished getting pre-configuration from client");
  224. Dict* config = BencMessageReader_read(preConf, tempAlloc, eh);
  225. String* privateKeyHex = Dict_getString(config, String_CONST("privateKey"));
  226. Dict* adminConf = Dict_getDict(config, String_CONST("admin"));
  227. String* pass = Dict_getString(adminConf, String_CONST("pass"));
  228. String* bind = Dict_getString(adminConf, String_CONST("bind"));
  229. if (!(pass && privateKeyHex && bind)) {
  230. if (!pass) {
  231. Except_throw(eh, "Expected 'pass'");
  232. }
  233. if (!bind) {
  234. Except_throw(eh, "Expected 'bind'");
  235. }
  236. if (!privateKeyHex) {
  237. Except_throw(eh, "Expected 'privateKey'");
  238. }
  239. Except_throw(eh, "Expected 'pass', 'privateKey' and 'bind' in configuration.");
  240. }
  241. Log_keys(logger, "Starting core with admin password [%s]", pass->bytes);
  242. uint8_t privateKey[32];
  243. if (privateKeyHex->len != 64
  244. || Hex_decode(privateKey, 32, (uint8_t*) privateKeyHex->bytes, 64) != 32)
  245. {
  246. Except_throw(eh, "privateKey must be 64 bytes of hex.");
  247. }
  248. struct Sockaddr_storage bindAddr;
  249. if (Sockaddr_parse(bind->bytes, &bindAddr)) {
  250. Except_throw(eh, "bind address [%s] unparsable", bind->bytes);
  251. }
  252. // --------------------- Bind Admin UDP --------------------- //
  253. struct UDPAddrIface* udpAdmin = UDPAddrIface_new(eventBase, &bindAddr.addr, alloc, eh, logger);
  254. // --------------------- Setup Admin --------------------- //
  255. struct Admin* admin = Admin_new(&udpAdmin->generic, logger, eventBase, pass);
  256. // --------------------- Setup the Logger --------------------- //
  257. Dict* logging = Dict_getDict(config, String_CONST("logging"));
  258. String* logTo = Dict_getString(logging, String_CONST("logTo"));
  259. if (logTo && String_equals(logTo, String_CONST("stdout"))) {
  260. // do nothing, continue logging to stdout.
  261. } else {
  262. struct Log* adminLogger = AdminLog_registerNew(admin, alloc, rand, eventBase);
  263. IndirectLog_set(logger, adminLogger);
  264. logger = adminLogger;
  265. }
  266. // --------------------- Inform client of UDP Addr --------------------- //
  267. char* boundAddr = Sockaddr_print(udpAdmin->generic.addr, tempAlloc);
  268. Dict adminResponse = Dict_CONST(
  269. String_CONST("bind"), String_OBJ(String_CONST(boundAddr)), NULL
  270. );
  271. Dict response = Dict_CONST(
  272. String_CONST("error"), String_OBJ(String_CONST("none")), Dict_CONST(
  273. String_CONST("admin"), Dict_OBJ(&adminResponse), NULL
  274. ));
  275. // This always times out because the angel doesn't respond.
  276. struct Message* clientResponse = Message_new(0, 512, tempAlloc);
  277. BencMessageWriter_write(&response, clientResponse, eh);
  278. Iface_CALL(clientPipe->iface.send, clientResponse, &clientPipe->iface);
  279. Allocator_free(tempAlloc);
  280. Core_init(alloc, logger, eventBase, privateKey, admin, rand, eh);
  281. EventBase_beginLoop(eventBase);
  282. return 0;
  283. }