Core.c 13 KB

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