IpTunnel.c 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746
  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/angel/Hermes.h"
  16. #include "benc/String.h"
  17. #include "benc/Dict.h"
  18. #include "benc/List.h"
  19. #include "benc/Int.h"
  20. #include "benc/serialization/standard/BencMessageWriter.h"
  21. #include "benc/serialization/standard/BencMessageReader.h"
  22. #include "crypto/random/Random.h"
  23. #include "exception/Jmp.h"
  24. #include "interface/tuntap/TUNMessageType.h"
  25. #include "memory/Allocator.h"
  26. #include "tunnel/IpTunnel.h"
  27. #include "crypto/AddressCalc.h"
  28. #include "util/Checksum.h"
  29. #include "util/AddrTools.h"
  30. #include "util/events/EventBase.h"
  31. #include "util/Identity.h"
  32. #include "util/events/Timeout.h"
  33. #include "wire/Error.h"
  34. #include "wire/Headers.h"
  35. #include "wire/Ethernet.h"
  36. #include <stddef.h>
  37. struct IpTunnel_pvt
  38. {
  39. struct IpTunnel pub;
  40. struct Allocator* allocator;
  41. struct Log* logger;
  42. uint32_t connectionCapacity;
  43. /** An always incrementing number which represents the connections. */
  44. uint32_t nextConnectionNumber;
  45. /** The name of the TUN interface so that ip addresses can be added. */
  46. String* ifName;
  47. /**
  48. * Every 10 seconds check for connections which the other end has
  49. * not provided ip addresses and send more requests.
  50. */
  51. struct Timeout* timeout;
  52. struct Random* rand;
  53. /** The angel connector for setting IP addresses. */
  54. struct Hermes* hermes;
  55. /** For verifying the integrity of the structure. */
  56. Identity
  57. };
  58. static struct IpTunnel_Connection* newConnection(bool isOutgoing, struct IpTunnel_pvt* context)
  59. {
  60. if (context->pub.connectionList.count == context->connectionCapacity) {
  61. uint32_t newSize = (context->connectionCapacity + 4) * sizeof(struct IpTunnel_Connection);
  62. context->pub.connectionList.connections =
  63. Allocator_realloc(context->allocator, context->pub.connectionList.connections, newSize);
  64. context->connectionCapacity += 4;
  65. }
  66. struct IpTunnel_Connection* conn =
  67. &context->pub.connectionList.connections[context->pub.connectionList.count];
  68. // If it's an incoming connection, it must be lower on the list than any outgoing connections.
  69. if (!isOutgoing) {
  70. for (int i = (int)context->pub.connectionList.count - 1; i >= 0; i--) {
  71. if (!context->pub.connectionList.connections[i].isOutgoing
  72. && conn != &context->pub.connectionList.connections[i + 1])
  73. {
  74. Bits_memcpyConst(conn,
  75. &context->pub.connectionList.connections[i + 1],
  76. sizeof(struct IpTunnel_Connection));
  77. conn = &context->pub.connectionList.connections[i + 1];
  78. }
  79. }
  80. }
  81. context->pub.connectionList.count++;
  82. Bits_memset(conn, 0, sizeof(struct IpTunnel_Connection));
  83. conn->number = context->nextConnectionNumber++;
  84. conn->isOutgoing = isOutgoing;
  85. // if there are 2 billion calls, die.
  86. Assert_true(context->nextConnectionNumber < (UINT32_MAX >> 1));
  87. return conn;
  88. }
  89. static struct IpTunnel_Connection* connectionByPubKey(uint8_t pubKey[32],
  90. struct IpTunnel_pvt* context)
  91. {
  92. for (int i = 0; i < (int)context->pub.connectionList.count; i++) {
  93. if (!Bits_memcmp(pubKey, context->pub.connectionList.connections[i].header.nodeKey, 32)) {
  94. return &context->pub.connectionList.connections[i];
  95. }
  96. }
  97. return NULL;
  98. }
  99. /**
  100. * Allow another node to tunnel IPv4 and/or ICANN IPv6 through this node.
  101. *
  102. * @param publicKeyOfAuthorizedNode the key for the node which will be allowed to connect.
  103. * @param ip6Addr the IPv6 address which the node will be issued or NULL.
  104. * @param ip4Addr the IPv4 address which the node will be issued or NULL.
  105. * @param tunnel the IpTunnel.
  106. * @return an connection number which is usable with IpTunnel_remove().
  107. */
  108. int IpTunnel_allowConnection(uint8_t publicKeyOfAuthorizedNode[32],
  109. struct Sockaddr* ip6Addr,
  110. struct Sockaddr* ip4Addr,
  111. struct IpTunnel* tunnel)
  112. {
  113. struct IpTunnel_pvt* context = Identity_check((struct IpTunnel_pvt*)tunnel);
  114. uint8_t* ip6Address = NULL;
  115. uint8_t* ip4Address = NULL;
  116. if (ip6Addr) {
  117. Sockaddr_getAddress(ip6Addr, &ip6Address);
  118. }
  119. if (ip4Addr) {
  120. Sockaddr_getAddress(ip4Addr, &ip4Address);
  121. }
  122. struct IpTunnel_Connection* conn = newConnection(false, context);
  123. Bits_memcpyConst(conn->header.nodeKey, publicKeyOfAuthorizedNode, 32);
  124. AddressCalc_addressForPublicKey(conn->header.nodeIp6Addr, publicKeyOfAuthorizedNode);
  125. if (ip4Address) {
  126. Bits_memcpyConst(conn->connectionIp4, ip4Address, 4);
  127. }
  128. if (ip6Address) {
  129. Bits_memcpyConst(conn->connectionIp6, ip6Address, 16);
  130. }
  131. return conn->number;
  132. }
  133. static uint8_t sendToNode(struct Message* message,
  134. struct IpTunnel_Connection* connection,
  135. struct IpTunnel_pvt* context)
  136. {
  137. Message_push(message, &connection->header, IpTunnel_PacketInfoHeader_SIZE, NULL);
  138. if (context->pub.nodeInterface.receiveMessage) {
  139. return context->pub.nodeInterface.receiveMessage(message, &context->pub.nodeInterface);
  140. }
  141. Log_info(context->logger, "Message undeliverable because IpTunnel is not registered");
  142. return Error_UNDELIVERABLE;
  143. }
  144. static uint8_t sendControlMessage(Dict* dict,
  145. struct IpTunnel_Connection* connection,
  146. struct Allocator* requestAlloc,
  147. struct IpTunnel_pvt* context)
  148. {
  149. struct Message* msg = Message_new(0, 1024, requestAlloc);
  150. BencMessageWriter_write(dict, msg, NULL);
  151. int length = msg->length;
  152. // do UDP header.
  153. Message_shift(msg, Headers_UDPHeader_SIZE, NULL);
  154. struct Headers_UDPHeader* uh = (struct Headers_UDPHeader*) msg->bytes;
  155. uh->srcPort_be = 0;
  156. uh->destPort_be = 0;
  157. uh->length_be = Endian_hostToBigEndian16(length);
  158. uh->checksum_be = 0;
  159. uint16_t payloadLength = msg->length;
  160. Message_shift(msg, Headers_IP6Header_SIZE, NULL);
  161. struct Headers_IP6Header* header = (struct Headers_IP6Header*) msg->bytes;
  162. header->versionClassAndFlowLabel = 0;
  163. header->flowLabelLow_be = 0;
  164. header->nextHeader = 17;
  165. header->hopLimit = 0;
  166. header->payloadLength_be = Endian_hostToBigEndian16(payloadLength);
  167. Headers_setIpVersion(header);
  168. // zero the source and dest addresses.
  169. Bits_memset(header->sourceAddr, 0, 32);
  170. uh->checksum_be = Checksum_udpIp6(header->sourceAddr,
  171. (uint8_t*) uh,
  172. msg->length - Headers_IP6Header_SIZE);
  173. return sendToNode(msg, connection, context);
  174. }
  175. static uint8_t requestAddresses(struct IpTunnel_Connection* conn,
  176. struct IpTunnel_pvt* context)
  177. {
  178. #ifdef Log_DEBUG
  179. uint8_t addr[40];
  180. AddrTools_printIp(addr, conn->header.nodeIp6Addr);
  181. Log_debug(context->logger, "Requesting addresses from [%s] for connection [%d]",
  182. addr, conn->number);
  183. #endif
  184. int number = conn->number;
  185. Dict d = Dict_CONST(
  186. String_CONST("q"), String_OBJ(String_CONST("IpTunnel_getAddresses")), Dict_CONST(
  187. String_CONST("txid"), String_OBJ((&(String){ .len = 4, .bytes = (char*)&number })),
  188. NULL
  189. ));
  190. struct Allocator* msgAlloc = Allocator_child(context->allocator);
  191. uint8_t ret = sendControlMessage(&d, conn, msgAlloc, context);
  192. Allocator_free(msgAlloc);
  193. return ret;
  194. }
  195. /**
  196. * Connect to another node and get IPv4 and/or IPv6 addresses from it.
  197. *
  198. * @param publicKeyOfNodeToConnectTo the key for the node to connect to.
  199. * @param tunnel the IpTunnel.
  200. * @return an connection number which is usable with IpTunnel_remove().
  201. */
  202. int IpTunnel_connectTo(uint8_t publicKeyOfNodeToConnectTo[32], struct IpTunnel* tunnel)
  203. {
  204. struct IpTunnel_pvt* context = Identity_check((struct IpTunnel_pvt*)tunnel);
  205. struct IpTunnel_Connection* conn = newConnection(true, context);
  206. Bits_memcpyConst(conn->header.nodeKey, publicKeyOfNodeToConnectTo, 32);
  207. AddressCalc_addressForPublicKey(conn->header.nodeIp6Addr, publicKeyOfNodeToConnectTo);
  208. #ifdef Log_DEBUG
  209. uint8_t addr[40];
  210. AddrTools_printIp(addr, conn->header.nodeIp6Addr);
  211. Log_debug(context->logger, "Trying to connect to [%s]", addr);
  212. #endif
  213. requestAddresses(conn, context);
  214. return conn->number;
  215. }
  216. /**
  217. * Disconnect from a node or remove authorization to connect.
  218. *
  219. * @param connection the connection to remove.
  220. * @param tunnel the IpTunnel.
  221. */
  222. int IpTunnel_removeConnection(int connectionNumber, struct IpTunnel* tunnel)
  223. {
  224. //struct IpTunnel_pvt* context = Identity_check((struct IpTunnel_pvt*)tunnel);
  225. return 0;
  226. }
  227. static uint8_t isControlMessageInvalid(struct Message* message, struct IpTunnel_pvt* context)
  228. {
  229. struct Headers_IP6Header* header = (struct Headers_IP6Header*) message->bytes;
  230. uint16_t length = Endian_bigEndianToHost16(header->payloadLength_be);
  231. if (header->nextHeader != 17 || message->length < length + Headers_IP6Header_SIZE) {
  232. Log_warn(context->logger, "Invalid IPv6 packet (not UDP or length field too big)");
  233. return Error_INVALID;
  234. }
  235. Message_shift(message, -Headers_IP6Header_SIZE, NULL);
  236. struct Headers_UDPHeader* udp = (struct Headers_UDPHeader*) message->bytes;
  237. if (Checksum_udpIp6(header->sourceAddr, message->bytes, length)) {
  238. Log_warn(context->logger, "Checksum mismatch");
  239. return Error_INVALID;
  240. }
  241. length -= Headers_UDPHeader_SIZE;
  242. if (Endian_bigEndianToHost16(udp->length_be) != length
  243. || udp->srcPort_be != 0
  244. || udp->destPort_be != 0)
  245. {
  246. Log_warn(context->logger, "Invalid UDP packet (length mismatch or wrong ports)");
  247. return Error_INVALID;
  248. }
  249. Message_shift(message, -Headers_UDPHeader_SIZE, NULL);
  250. message->length = length;
  251. return 0;
  252. }
  253. static uint8_t requestForAddresses(Dict* request,
  254. struct IpTunnel_Connection* conn,
  255. struct Allocator* requestAlloc,
  256. struct IpTunnel_pvt* context)
  257. {
  258. #ifdef Log_DEBUG
  259. uint8_t addr[40];
  260. AddrTools_printIp(addr, conn->header.nodeIp6Addr);
  261. Log_debug(context->logger, "Got request for addresses from [%s]", addr);
  262. #endif
  263. if (conn->isOutgoing) {
  264. Log_warn(context->logger, "got request for addresses from outgoing connection");
  265. return Error_INVALID;
  266. }
  267. Dict* addresses = Dict_new(requestAlloc);
  268. bool noAddresses = true;
  269. if (!Bits_isZero(conn->connectionIp6, 16)) {
  270. Dict_putString(addresses,
  271. String_CONST("ip6"),
  272. String_newBinary((char*)conn->connectionIp6, 16, requestAlloc),
  273. requestAlloc);
  274. noAddresses = false;
  275. }
  276. if (!Bits_isZero(conn->connectionIp4, 4)) {
  277. Dict_putString(addresses,
  278. String_CONST("ip4"),
  279. String_newBinary((char*)conn->connectionIp4, 4, requestAlloc),
  280. requestAlloc);
  281. noAddresses = false;
  282. }
  283. if (noAddresses) {
  284. Log_warn(context->logger, "no addresses to provide");
  285. return 0;
  286. }
  287. Dict* msg = Dict_new(requestAlloc);
  288. Dict_putDict(msg, String_CONST("addresses"), addresses, requestAlloc);
  289. String* txid = Dict_getString(request, String_CONST("txid"));
  290. if (txid) {
  291. Dict_putString(msg, String_CONST("txid"), txid, requestAlloc);
  292. }
  293. return sendControlMessage(msg, conn, requestAlloc, context);
  294. }
  295. static void addAddressCallback(Dict* responseMessage, void* vcontext)
  296. {
  297. struct IpTunnel_pvt* ctx = Identity_check((struct IpTunnel_pvt*) vcontext);
  298. char* err = "invalid response";
  299. String* error = Dict_getString(responseMessage, String_CONST("error"));
  300. if (error) {
  301. err = error->bytes;
  302. }
  303. if (!error || !String_equals(error, String_CONST("none"))) {
  304. Log_error(ctx->logger, "Error setting ip address on TUN [%s]", err);
  305. #ifndef Log_ERROR
  306. // this whole function does essentially nothing but log an error so unused vars.
  307. err = err;
  308. ctx = ctx;
  309. #endif
  310. }
  311. }
  312. static void addAddress(char* printedAddr, struct IpTunnel_pvt* ctx)
  313. {
  314. #ifdef Darwin
  315. int prefixLen = 3;
  316. #else
  317. int prefixLen = 0;
  318. #endif
  319. // Apple doesn't handle prefix length of 0 properly. 3 covers all IPv6 unicast space.
  320. if (!ctx->ifName) {
  321. Log_error(ctx->logger, "Failed to set IP address because TUN interface is not setup");
  322. return;
  323. }
  324. struct Jmp j;
  325. Jmp_try(j) {
  326. Dict args = Dict_CONST(
  327. String_CONST("address"), String_OBJ(String_CONST(printedAddr)), Dict_CONST(
  328. String_CONST("interfaceName"), String_OBJ(ctx->ifName), Dict_CONST(
  329. String_CONST("prefixLen"), Int_OBJ(prefixLen), NULL
  330. )));
  331. Dict msg = Dict_CONST(
  332. String_CONST("args"), Dict_OBJ(&args), Dict_CONST(
  333. String_CONST("q"), String_OBJ(String_CONST("Angel_addIp")), NULL
  334. ));
  335. Hermes_callAngel(&msg, addAddressCallback, ctx, ctx->allocator, &j.handler, ctx->hermes);
  336. } Jmp_catch {
  337. Log_error(ctx->logger, "Error setting ip address on TUN [%s]", j.message);
  338. }
  339. }
  340. static int incomingAddresses(Dict* d,
  341. struct IpTunnel_Connection* conn,
  342. struct Allocator* alloc,
  343. struct IpTunnel_pvt* context)
  344. {
  345. if (!conn->isOutgoing) {
  346. Log_warn(context->logger, "got offer of addresses from incoming connection");
  347. return Error_INVALID;
  348. }
  349. String* txid = Dict_getString(d, String_CONST("txid"));
  350. if (!txid || txid->len != 4) {
  351. Log_info(context->logger, "missing or wrong length txid");
  352. return Error_INVALID;
  353. }
  354. int number;
  355. Bits_memcpyConst(&number, txid->bytes, 4);
  356. if (number < 0 || number >= (int)context->nextConnectionNumber) {
  357. Log_info(context->logger, "txid out of range");
  358. return Error_INVALID;
  359. }
  360. if (number != conn->number) {
  361. for (int i = 0; i < (int)context->pub.connectionList.count; i++) {
  362. if (context->pub.connectionList.connections[i].number == number) {
  363. if (Bits_memcmp(conn->header.nodeKey,
  364. context->pub.connectionList.connections[i].header.nodeKey,
  365. 32))
  366. {
  367. Log_info(context->logger, "txid doesn't match origin");
  368. return Error_INVALID;
  369. } else {
  370. conn = &context->pub.connectionList.connections[i];
  371. }
  372. }
  373. }
  374. }
  375. Dict* addresses = Dict_getDict(d, String_CONST("addresses"));
  376. String* ip4 = Dict_getString(addresses, String_CONST("ip4"));
  377. if (ip4 && ip4->len == 4) {
  378. Bits_memcpyConst(conn->connectionIp4, ip4->bytes, 4);
  379. struct Sockaddr* sa = Sockaddr_clone(Sockaddr_LOOPBACK, alloc);
  380. uint8_t* addrBytes = NULL;
  381. Sockaddr_getAddress(sa, &addrBytes);
  382. Bits_memcpy(addrBytes, ip4->bytes, 4);
  383. char* printedAddr = Sockaddr_print(sa, alloc);
  384. Log_info(context->logger, "Got issued address [%s] for connection [%d]",
  385. printedAddr, conn->number);
  386. addAddress(printedAddr, context);
  387. }
  388. String* ip6 = Dict_getString(addresses, String_CONST("ip6"));
  389. if (ip6 && ip6->len == 16) {
  390. Bits_memcpyConst(conn->connectionIp6, ip6->bytes, 16);
  391. struct Sockaddr* sa = Sockaddr_clone(Sockaddr_LOOPBACK6, alloc);
  392. uint8_t* addrBytes = NULL;
  393. Sockaddr_getAddress(sa, &addrBytes);
  394. Bits_memcpy(addrBytes, ip6->bytes, 16);
  395. char* printedAddr = Sockaddr_print(sa, alloc);
  396. Log_info(context->logger, "Got issued address [%s] for connection [%d]",
  397. printedAddr, conn->number);
  398. addAddress(printedAddr, context);
  399. }
  400. return 0;
  401. }
  402. static uint8_t incomingControlMessage(struct Message* message,
  403. struct IpTunnel_Connection* conn,
  404. struct IpTunnel_pvt* context)
  405. {
  406. #ifdef Log_DEBUG
  407. uint8_t addr[40];
  408. AddrTools_printIp(addr, conn->header.nodeIp6Addr);
  409. Log_debug(context->logger, "Got incoming message from [%s]", addr);
  410. #endif
  411. // This aligns the message on the content.
  412. if (isControlMessageInvalid(message, context)) {
  413. return Error_INVALID;
  414. }
  415. #ifdef Log_DEBUG
  416. uint8_t lastChar = message->bytes[message->length - 1];
  417. message->bytes[message->length - 1] = '\0';
  418. Log_debug(context->logger, "Message content [%s%c]", message->bytes, lastChar);
  419. message->bytes[message->length - 1] = lastChar;
  420. #endif
  421. struct Allocator* alloc = Allocator_child(message->alloc);
  422. Dict* d = NULL;
  423. char* err = BencMessageReader_readNoExcept(message, alloc, &d);
  424. if (err) {
  425. Log_info(context->logger, "Failed to parse message [%s]", err);
  426. return Error_INVALID;
  427. }
  428. if (Dict_getDict(d, String_CONST("addresses"))) {
  429. return incomingAddresses(d, conn, alloc, context);
  430. }
  431. if (String_equals(String_CONST("IpTunnel_getAddresses"),
  432. Dict_getString(d, String_CONST("q"))))
  433. {
  434. return requestForAddresses(d, conn, alloc, context);
  435. }
  436. Log_warn(context->logger, "Message which is unhandled");
  437. return Error_INVALID;
  438. }
  439. /**
  440. * If there are multiple connections to the same server,
  441. * the ip address on the packet might belong to the wrong one.
  442. * In that case we get the right connection.
  443. * If the other party has sent a packet from an address which is not
  444. * valid, this will return NULL and their packet can be dropped.
  445. *
  446. * @param conn the connection which matches the other node's key.
  447. * @param sourceAndDestIp6 the source and destination IPv6 addresses,
  448. * must be NULL if sourceAndDestIp4 is specified.
  449. * @param sourceAndDestIp4 the source and destination IPv4 addresses.
  450. * must be NULL if sourceAndDestIp6 is specified.
  451. * @param context
  452. * @return the real connection or null if the packet is invalid.
  453. */
  454. static struct IpTunnel_Connection* getConnection(struct IpTunnel_Connection* conn,
  455. uint8_t sourceAndDestIp6[32],
  456. uint8_t sourceAndDestIp4[8],
  457. bool isFromTun,
  458. struct IpTunnel_pvt* context)
  459. {
  460. uint8_t* source = (sourceAndDestIp6) ? sourceAndDestIp6 : sourceAndDestIp4;
  461. uint32_t length = (sourceAndDestIp6) ? 16 : 4;
  462. uint8_t* destination = source + length;
  463. if (sourceAndDestIp6) {
  464. // never allowed
  465. if (source[0] == 0xfc || destination[0] == 0xfc) {
  466. return NULL;
  467. }
  468. }
  469. struct IpTunnel_Connection* lastConnection =
  470. &context->pub.connectionList.connections[context->pub.connectionList.count];
  471. do {
  472. // If this is an incoming message from the w0rld, and we're the client, we want
  473. // to make sure it's addressed to us (destination), if we're the server we want to make
  474. // sure our clients are using the addresses we gave them (source).
  475. //
  476. // If this is an outgoing message from the TUN, we just want to find a sutable server to
  477. // handle it. The behavior of this function relies on the fact that all incoming
  478. // connections are first on the list.
  479. //
  480. uint8_t* compareAddr = (isFromTun)
  481. ? ((conn->isOutgoing) ? source : destination)
  482. : ((conn->isOutgoing) ? destination : source);
  483. uint8_t* connectionAddr = (sourceAndDestIp6) ? conn->connectionIp6 : conn->connectionIp4;
  484. if (!Bits_memcmp(compareAddr, connectionAddr, length)) {
  485. return conn;
  486. }
  487. conn++;
  488. } while (conn <= lastConnection);
  489. return NULL;
  490. }
  491. static uint8_t incomingFromTun(struct Message* message, struct Interface* tunIf)
  492. {
  493. struct IpTunnel_pvt* context = Identity_check((struct IpTunnel_pvt*)tunIf);
  494. if (message->length < 20) {
  495. Log_debug(context->logger, "Dropping runt.");
  496. }
  497. struct IpTunnel_Connection* conn = NULL;
  498. if (!context->pub.connectionList.connections) {
  499. // No connections authorized, fall through to "unrecognized address"
  500. } else if (message->length > 40 && Headers_getIpVersion(message->bytes) == 6) {
  501. struct Headers_IP6Header* header = (struct Headers_IP6Header*) message->bytes;
  502. conn = getConnection(context->pub.connectionList.connections,
  503. header->sourceAddr,
  504. NULL,
  505. true,
  506. context);
  507. } else if (message->length > 20 && Headers_getIpVersion(message->bytes) == 4) {
  508. struct Headers_IP4Header* header = (struct Headers_IP4Header*) message->bytes;
  509. conn = getConnection(context->pub.connectionList.connections,
  510. NULL,
  511. header->sourceAddr,
  512. true,
  513. context);
  514. } else {
  515. Log_info(context->logger, "Message of unknown type from TUN");
  516. return Error_INVALID;
  517. }
  518. if (!conn) {
  519. Log_info(context->logger, "Message with unrecognized address from TUN");
  520. return Error_INVALID;
  521. }
  522. return sendToNode(message, conn, context);
  523. }
  524. static uint8_t ip6FromNode(struct Message* message,
  525. struct IpTunnel_Connection* conn,
  526. struct IpTunnel_pvt* context)
  527. {
  528. struct Headers_IP6Header* header = (struct Headers_IP6Header*) message->bytes;
  529. if (Bits_isZero(header->sourceAddr, 16) || Bits_isZero(header->destinationAddr, 16)) {
  530. if (Bits_isZero(header->sourceAddr, 32)) {
  531. return incomingControlMessage(message, conn, context);
  532. }
  533. Log_debug(context->logger, "Got message with zero address");
  534. return Error_INVALID;
  535. }
  536. if (!getConnection(conn, header->sourceAddr, NULL, false, context)) {
  537. Log_debug(context->logger, "Got message with wrong address for connection");
  538. return Error_INVALID;
  539. }
  540. TUNMessageType_push(message, Ethernet_TYPE_IP6, NULL);
  541. struct Interface* tunIf = &context->pub.tunInterface;
  542. if (tunIf->receiveMessage) {
  543. tunIf->receiveMessage(message, tunIf);
  544. }
  545. return 0;
  546. }
  547. static uint8_t ip4FromNode(struct Message* message,
  548. struct IpTunnel_Connection* conn,
  549. struct IpTunnel_pvt* context)
  550. {
  551. struct Headers_IP4Header* header = (struct Headers_IP4Header*) message->bytes;
  552. if (Bits_isZero(header->sourceAddr, 4) || Bits_isZero(header->destAddr, 4)) {
  553. Log_debug(context->logger, "Got message with zero address");
  554. return Error_INVALID;
  555. }
  556. if (!getConnection(conn, NULL, header->sourceAddr, false, context)) {
  557. Log_debug(context->logger, "Got message with wrong address for connection");
  558. return Error_INVALID;
  559. }
  560. TUNMessageType_push(message, Ethernet_TYPE_IP4, NULL);
  561. struct Interface* tunIf = &context->pub.tunInterface;
  562. if (tunIf->receiveMessage) {
  563. return tunIf->receiveMessage(message, tunIf);
  564. }
  565. return 0;
  566. }
  567. static uint8_t incomingFromNode(struct Message* message, struct Interface* nodeIf)
  568. {
  569. struct IpTunnel_pvt* context =
  570. (struct IpTunnel_pvt*)(((char*)nodeIf) - offsetof(struct IpTunnel, nodeInterface));
  571. Identity_check(context);
  572. //Log_debug(context->logger, "Got incoming message");
  573. Assert_true(message->length >= IpTunnel_PacketInfoHeader_SIZE);
  574. struct IpTunnel_PacketInfoHeader* header = (struct IpTunnel_PacketInfoHeader*) message->bytes;
  575. struct IpTunnel_Connection* conn = connectionByPubKey(header->nodeKey, context);
  576. if (!conn) {
  577. #ifdef Log_DEBUG
  578. uint8_t addr[40];
  579. AddrTools_printIp(addr, header->nodeIp6Addr);
  580. Log_debug(context->logger, "Got message from unrecognized node [%s]", addr);
  581. #endif
  582. return 0;
  583. }
  584. Message_shift(message, -IpTunnel_PacketInfoHeader_SIZE, NULL);
  585. if (message->length > 40 && Headers_getIpVersion(message->bytes) == 6) {
  586. return ip6FromNode(message, conn, context);
  587. }
  588. if (message->length > 20 && Headers_getIpVersion(message->bytes) == 4) {
  589. return ip4FromNode(message, conn, context);
  590. }
  591. #ifdef Log_DEBUG
  592. uint8_t addr[40];
  593. AddrTools_printIp(addr, header->nodeIp6Addr);
  594. Log_debug(context->logger,
  595. "Got message of unknown type, length: [%d], IP version [%d] from [%s]",
  596. message->length,
  597. (message->length > 1) ? Headers_getIpVersion(message->bytes) : 0,
  598. addr);
  599. #endif
  600. return 0;
  601. }
  602. static void timeout(void* vcontext)
  603. {
  604. struct IpTunnel_pvt* context = vcontext;
  605. if (!context->pub.connectionList.count) {
  606. return;
  607. }
  608. Log_debug(context->logger, "Checking for connections to poll. Total connections [%u]",
  609. context->pub.connectionList.count);
  610. uint32_t beginning = Random_uint32(context->rand) % context->pub.connectionList.count;
  611. uint32_t i = beginning;
  612. do {
  613. Assert_true(i < context->pub.connectionList.count);
  614. struct IpTunnel_Connection* conn = &context->pub.connectionList.connections[i];
  615. if (conn->isOutgoing
  616. && Bits_isZero(conn->connectionIp6, 16)
  617. && Bits_isZero(conn->connectionIp4, 4))
  618. {
  619. requestAddresses(conn, context);
  620. break;
  621. }
  622. i = (i + 1) % context->pub.connectionList.count;
  623. } while (i != beginning);
  624. }
  625. void IpTunnel_setTunName(char* interfaceName, struct IpTunnel* ipTun)
  626. {
  627. struct IpTunnel_pvt* ctx = Identity_check((struct IpTunnel_pvt*) ipTun);
  628. ctx->ifName = String_new(interfaceName, ctx->allocator);
  629. }
  630. struct IpTunnel* IpTunnel_new(struct Log* logger,
  631. struct EventBase* eventBase,
  632. struct Allocator* alloc,
  633. struct Random* rand,
  634. struct Hermes* hermes)
  635. {
  636. struct IpTunnel_pvt* context = Allocator_clone(alloc, (&(struct IpTunnel_pvt) {
  637. .pub = {
  638. .tunInterface = { .sendMessage = incomingFromTun },
  639. .nodeInterface = { .sendMessage = incomingFromNode }
  640. },
  641. .allocator = alloc,
  642. .logger = logger,
  643. .rand = rand,
  644. .hermes = hermes
  645. }));
  646. context->timeout = Timeout_setInterval(timeout, context, 10000, eventBase, alloc);
  647. Identity_set(context);
  648. return &context->pub;
  649. }