1
0

IpTunnel.c 27 KB

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