IpTunnel.c 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744
  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, NULL);
  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 Allocator* requestAlloc,
  151. struct IpTunnel_pvt* context)
  152. {
  153. struct Message* message = Message_new(512, 512, requestAlloc);
  154. struct Writer* w = ArrayWriter_new(message->bytes, message->length, requestAlloc);
  155. StandardBencSerializer_get()->serializeDictionary(w, dict);
  156. message->length = w->bytesWritten;
  157. #ifdef Log_DEBUG
  158. message->bytes[message->length] = '\0';
  159. uint8_t addr[40];
  160. AddrTools_printIp(addr, connection->header.nodeIp6Addr);
  161. Log_debug(context->logger, "Send message to [%s] with content [%s]", addr, message->bytes);
  162. #endif
  163. // do UDP header.
  164. Message_shift(message, Headers_UDPHeader_SIZE, NULL);
  165. struct Headers_UDPHeader* uh = (struct Headers_UDPHeader*) message->bytes;
  166. uh->srcPort_be = 0;
  167. uh->destPort_be = 0;
  168. uh->length_be = Endian_hostToBigEndian16(w->bytesWritten);
  169. uh->checksum_be = 0;
  170. uint16_t payloadLength = message->length;
  171. Message_shift(message, Headers_IP6Header_SIZE, NULL);
  172. struct Headers_IP6Header* header = (struct Headers_IP6Header*) message->bytes;
  173. header->versionClassAndFlowLabel = 0;
  174. header->flowLabelLow_be = 0;
  175. header->nextHeader = 17;
  176. header->hopLimit = 0;
  177. header->payloadLength_be = Endian_hostToBigEndian16(payloadLength);
  178. Headers_setIpVersion(header);
  179. // zero the source and dest addresses.
  180. Bits_memset(header->sourceAddr, 0, 32);
  181. uh->checksum_be = Checksum_udpIp6(header->sourceAddr,
  182. (uint8_t*) uh,
  183. message->length - Headers_IP6Header_SIZE);
  184. return sendToNode(message, connection, context);
  185. }
  186. static uint8_t requestAddresses(struct IpTunnel_Connection* conn,
  187. struct IpTunnel_pvt* context)
  188. {
  189. #ifdef Log_DEBUG
  190. uint8_t addr[40];
  191. AddrTools_printIp(addr, conn->header.nodeIp6Addr);
  192. Log_debug(context->logger, "Requesting addresses from [%s] for connection [%d]",
  193. addr, conn->number);
  194. #endif
  195. int number = conn->number;
  196. Dict d = Dict_CONST(
  197. String_CONST("q"), String_OBJ(String_CONST("IpTunnel_getAddresses")), Dict_CONST(
  198. String_CONST("txid"), String_OBJ((&(String){ .len = 4, .bytes = (char*)&number })),
  199. NULL
  200. ));
  201. struct Allocator* msgAlloc = Allocator_child(context->allocator);
  202. uint8_t ret = sendControlMessage(&d, conn, msgAlloc, context);
  203. Allocator_free(msgAlloc);
  204. return ret;
  205. }
  206. /**
  207. * Connect to another node and get IPv4 and/or IPv6 addresses from it.
  208. *
  209. * @param publicKeyOfNodeToConnectTo the key for the node to connect to.
  210. * @param tunnel the IpTunnel.
  211. * @return an connection number which is usable with IpTunnel_remove().
  212. */
  213. int IpTunnel_connectTo(uint8_t publicKeyOfNodeToConnectTo[32], struct IpTunnel* tunnel)
  214. {
  215. struct IpTunnel_pvt* context = Identity_cast((struct IpTunnel_pvt*)tunnel);
  216. struct IpTunnel_Connection* conn = newConnection(true, context);
  217. Bits_memcpyConst(conn->header.nodeKey, publicKeyOfNodeToConnectTo, 32);
  218. AddressCalc_addressForPublicKey(conn->header.nodeIp6Addr, publicKeyOfNodeToConnectTo);
  219. #ifdef Log_DEBUG
  220. uint8_t addr[40];
  221. AddrTools_printIp(addr, conn->header.nodeIp6Addr);
  222. Log_debug(context->logger, "Trying to connect to [%s]", addr);
  223. #endif
  224. requestAddresses(conn, context);
  225. return conn->number;
  226. }
  227. /**
  228. * Disconnect from a node or remove authorization to connect.
  229. *
  230. * @param connection the connection to remove.
  231. * @param tunnel the IpTunnel.
  232. */
  233. int IpTunnel_removeConnection(int connectionNumber, struct IpTunnel* tunnel)
  234. {
  235. //struct IpTunnel_pvt* context = Identity_cast((struct IpTunnel_pvt*)tunnel);
  236. return 0;
  237. }
  238. static uint8_t isControlMessageInvalid(struct Message* message, struct IpTunnel_pvt* context)
  239. {
  240. struct Headers_IP6Header* header = (struct Headers_IP6Header*) message->bytes;
  241. uint16_t length = Endian_bigEndianToHost16(header->payloadLength_be);
  242. if (header->nextHeader != 17 || message->length < length + Headers_IP6Header_SIZE) {
  243. Log_warn(context->logger, "Invalid IPv6 packet (not UDP or length field too big)");
  244. return Error_INVALID;
  245. }
  246. Message_shift(message, -Headers_IP6Header_SIZE, NULL);
  247. struct Headers_UDPHeader* udp = (struct Headers_UDPHeader*) message->bytes;
  248. if (Checksum_udpIp6(header->sourceAddr, message->bytes, length)) {
  249. Log_warn(context->logger, "Checksum mismatch");
  250. return Error_INVALID;
  251. }
  252. length -= Headers_UDPHeader_SIZE;
  253. if (Endian_bigEndianToHost16(udp->length_be) != length
  254. || udp->srcPort_be != 0
  255. || udp->destPort_be != 0)
  256. {
  257. Log_warn(context->logger, "Invalid UDP packet (length mismatch or wrong ports)");
  258. return Error_INVALID;
  259. }
  260. Message_shift(message, -Headers_UDPHeader_SIZE, NULL);
  261. message->length = length;
  262. return 0;
  263. }
  264. static uint8_t requestForAddresses(Dict* request,
  265. struct IpTunnel_Connection* conn,
  266. struct Allocator* requestAlloc,
  267. struct IpTunnel_pvt* context)
  268. {
  269. #ifdef Log_DEBUG
  270. uint8_t addr[40];
  271. AddrTools_printIp(addr, conn->header.nodeIp6Addr);
  272. Log_debug(context->logger, "Got request for addresses from [%s]", addr);
  273. #endif
  274. if (conn->isOutgoing) {
  275. Log_warn(context->logger, "got request for addresses from outgoing connection");
  276. return Error_INVALID;
  277. }
  278. Dict* addresses = Dict_new(requestAlloc);
  279. bool noAddresses = true;
  280. if (!Bits_isZero(conn->connectionIp6, 16)) {
  281. Dict_putString(addresses,
  282. String_CONST("ip6"),
  283. String_newBinary((char*)conn->connectionIp6, 16, requestAlloc),
  284. requestAlloc);
  285. noAddresses = false;
  286. }
  287. if (!Bits_isZero(conn->connectionIp4, 4)) {
  288. Dict_putString(addresses,
  289. String_CONST("ip4"),
  290. String_newBinary((char*)conn->connectionIp4, 4, requestAlloc),
  291. requestAlloc);
  292. noAddresses = false;
  293. }
  294. if (noAddresses) {
  295. Log_warn(context->logger, "no addresses to provide");
  296. return 0;
  297. }
  298. Dict* msg = Dict_new(requestAlloc);
  299. Dict_putDict(msg, String_CONST("addresses"), addresses, requestAlloc);
  300. String* txid = Dict_getString(request, String_CONST("txid"));
  301. if (txid) {
  302. Dict_putString(msg, String_CONST("txid"), txid, requestAlloc);
  303. }
  304. return sendControlMessage(msg, conn, requestAlloc, context);
  305. }
  306. static void addAddressCallback(Dict* responseMessage, void* vcontext)
  307. {
  308. struct IpTunnel_pvt* ctx = Identity_cast((struct IpTunnel_pvt*) vcontext);
  309. char* err = "invalid response";
  310. String* error = Dict_getString(responseMessage, String_CONST("error"));
  311. if (error) {
  312. err = error->bytes;
  313. }
  314. if (!error || !String_equals(error, String_CONST("none"))) {
  315. Log_error(ctx->logger, "Error setting ip address on TUN [%s]", err);
  316. }
  317. }
  318. static void addAddress(char* printedAddr, struct IpTunnel_pvt* ctx)
  319. {
  320. #ifdef Darwin
  321. int prefixLen = 3;
  322. #else
  323. int prefixLen = 0;
  324. #endif
  325. // Apple doesn't handle prefix length of 0 properly. 3 covers all IPv6 unicast space.
  326. if (!ctx->ifName) {
  327. Log_error(ctx->logger, "Failed to set IP address because TUN interface is not setup");
  328. return;
  329. }
  330. struct Jmp j;
  331. Jmp_try(j) {
  332. Dict args = Dict_CONST(
  333. String_CONST("address"), String_OBJ(String_CONST(printedAddr)), Dict_CONST(
  334. String_CONST("interfaceName"), String_OBJ(ctx->ifName), Dict_CONST(
  335. String_CONST("prefixLen"), Int_OBJ(prefixLen), NULL
  336. )));
  337. Dict msg = Dict_CONST(
  338. String_CONST("args"), Dict_OBJ(&args), Dict_CONST(
  339. String_CONST("q"), String_OBJ(String_CONST("Angel_addIp")), NULL
  340. ));
  341. Hermes_callAngel(&msg, addAddressCallback, ctx, ctx->allocator, &j.handler, ctx->hermes);
  342. } Jmp_catch {
  343. Log_error(ctx->logger, "Error setting ip address on TUN [%s]", j.message);
  344. }
  345. }
  346. static int incomingAddresses(Dict* d,
  347. struct IpTunnel_Connection* conn,
  348. struct Allocator* alloc,
  349. struct IpTunnel_pvt* context)
  350. {
  351. if (!conn->isOutgoing) {
  352. Log_warn(context->logger, "got offer of addresses from incoming connection");
  353. return Error_INVALID;
  354. }
  355. String* txid = Dict_getString(d, String_CONST("txid"));
  356. if (!txid || txid->len != 4) {
  357. Log_info(context->logger, "missing or wrong length txid");
  358. return Error_INVALID;
  359. }
  360. int number;
  361. Bits_memcpyConst(&number, txid->bytes, 4);
  362. if (number < 0 || number >= (int)context->nextConnectionNumber) {
  363. Log_info(context->logger, "txid out of range");
  364. return Error_INVALID;
  365. }
  366. if (number != conn->number) {
  367. for (int i = 0; i < (int)context->pub.connectionList.count; i++) {
  368. if (context->pub.connectionList.connections[i].number == number) {
  369. if (Bits_memcmp(conn->header.nodeKey,
  370. context->pub.connectionList.connections[i].header.nodeKey,
  371. 32))
  372. {
  373. Log_info(context->logger, "txid doesn't match origin");
  374. return Error_INVALID;
  375. } else {
  376. conn = &context->pub.connectionList.connections[i];
  377. }
  378. }
  379. }
  380. }
  381. Dict* addresses = Dict_getDict(d, String_CONST("addresses"));
  382. String* ip4 = Dict_getString(addresses, String_CONST("ip4"));
  383. if (ip4 && ip4->len == 4) {
  384. Bits_memcpyConst(conn->connectionIp4, ip4->bytes, 4);
  385. struct Sockaddr* sa = Sockaddr_clone(Sockaddr_LOOPBACK, alloc);
  386. uint8_t* addrBytes = NULL;
  387. Sockaddr_getAddress(sa, &addrBytes);
  388. Bits_memcpy(addrBytes, ip4->bytes, 4);
  389. char* printedAddr = Sockaddr_print(sa, alloc);
  390. Log_info(context->logger, "Got issued address [%s] for connection [%d]",
  391. printedAddr, conn->number);
  392. addAddress(printedAddr, context);
  393. }
  394. String* ip6 = Dict_getString(addresses, String_CONST("ip6"));
  395. if (ip6 && ip6->len == 16) {
  396. Bits_memcpyConst(conn->connectionIp6, ip6->bytes, 16);
  397. struct Sockaddr* sa = Sockaddr_clone(Sockaddr_LOOPBACK6, alloc);
  398. uint8_t* addrBytes = NULL;
  399. Sockaddr_getAddress(sa, &addrBytes);
  400. Bits_memcpy(addrBytes, ip6->bytes, 16);
  401. char* printedAddr = Sockaddr_print(sa, alloc);
  402. Log_info(context->logger, "Got issued address [%s] for connection [%d]",
  403. printedAddr, conn->number);
  404. addAddress(printedAddr, context);
  405. }
  406. return 0;
  407. }
  408. static uint8_t incomingControlMessage(struct Message* message,
  409. struct IpTunnel_Connection* conn,
  410. struct IpTunnel_pvt* context)
  411. {
  412. #ifdef Log_DEBUG
  413. uint8_t addr[40];
  414. AddrTools_printIp(addr, conn->header.nodeIp6Addr);
  415. Log_debug(context->logger, "Got incoming message from [%s]", addr);
  416. #endif
  417. // This aligns the message on the content.
  418. if (isControlMessageInvalid(message, context)) {
  419. return Error_INVALID;
  420. }
  421. #ifdef Log_DEBUG
  422. uint8_t lastChar = message->bytes[message->length - 1];
  423. message->bytes[message->length - 1] = '\0';
  424. Log_debug(context->logger, "Message content [%s%c]", message->bytes, lastChar);
  425. message->bytes[message->length - 1] = lastChar;
  426. #endif
  427. struct Allocator* alloc = Allocator_child(message->alloc);
  428. struct Reader* r = ArrayReader_new(message->bytes, message->length, alloc);
  429. Dict dStore;
  430. Dict* d = &dStore;
  431. if (StandardBencSerializer_get()->parseDictionary(r, alloc, d)) {
  432. Log_info(context->logger, "Failed to parse message");
  433. return Error_INVALID;
  434. }
  435. if (Dict_getDict(d, String_CONST("addresses"))) {
  436. return incomingAddresses(d, conn, alloc, context);
  437. }
  438. if (String_equals(String_CONST("IpTunnel_getAddresses"),
  439. Dict_getString(d, String_CONST("q"))))
  440. {
  441. return requestForAddresses(d, conn, alloc, context);
  442. }
  443. Log_warn(context->logger, "Message which is unhandled");
  444. return Error_INVALID;
  445. }
  446. /**
  447. * If there are multiple connections to the same server,
  448. * the ip address on the packet might belong to the wrong one.
  449. * In that case we get the right connection.
  450. * If the other party has sent a packet from an address which is not
  451. * valid, this will return NULL and their packet can be dropped.
  452. *
  453. * @param conn the connection which matches the other node's key.
  454. * @param sourceAndDestIp6 the source and destination IPv6 addresses,
  455. * must be NULL if sourceAndDestIp4 is specified.
  456. * @param sourceAndDestIp4 the source and destination IPv4 addresses.
  457. * must be NULL if sourceAndDestIp6 is specified.
  458. * @param context
  459. * @return the real connection or null if the packet is invalid.
  460. */
  461. static struct IpTunnel_Connection* getConnection(struct IpTunnel_Connection* conn,
  462. uint8_t sourceAndDestIp6[32],
  463. uint8_t sourceAndDestIp4[8],
  464. bool isFromTun,
  465. struct IpTunnel_pvt* context)
  466. {
  467. uint8_t* source = (sourceAndDestIp6) ? sourceAndDestIp6 : sourceAndDestIp4;
  468. uint32_t length = (sourceAndDestIp6) ? 16 : 4;
  469. #define DESTINATION source + length
  470. struct IpTunnel_Connection* lastConnection =
  471. &context->pub.connectionList.connections[context->pub.connectionList.count];
  472. do {
  473. // If this is an incoming message from the w0rld, and we're the client, we want
  474. // to make sure it's addressed to us (destination), if we're the server we want to make
  475. // sure our clients are using the addresses we gave them (source).
  476. //
  477. // If this is an outgoing message from the TUN, we just want to find a sutable server to
  478. // handle it. The behavior of this function relies on the fact that all incoming
  479. // connections are first on the list.
  480. //
  481. uint8_t* compareAddr = (isFromTun)
  482. ? ((conn->isOutgoing) ? source : DESTINATION)
  483. : ((conn->isOutgoing) ? DESTINATION : source);
  484. uint8_t* connectionAddr = (sourceAndDestIp6) ? conn->connectionIp6 : conn->connectionIp4;
  485. if (!Bits_memcmp(compareAddr, connectionAddr, length)) {
  486. return conn;
  487. }
  488. conn++;
  489. } while (conn <= lastConnection);
  490. return NULL;
  491. }
  492. static uint8_t incomingFromTun(struct Message* message, struct Interface* tunIf)
  493. {
  494. struct IpTunnel_pvt* context = Identity_cast((struct IpTunnel_pvt*)tunIf);
  495. if (message->length < 20) {
  496. Log_debug(context->logger, "Dropping runt.");
  497. }
  498. struct IpTunnel_Connection* conn = NULL;
  499. if (!context->pub.connectionList.connections) {
  500. // No connections authorized, fall through to "unrecognized address"
  501. } else if (message->length > 40 && Headers_getIpVersion(message->bytes) == 6) {
  502. struct Headers_IP6Header* header = (struct Headers_IP6Header*) message->bytes;
  503. conn = getConnection(context->pub.connectionList.connections,
  504. header->sourceAddr,
  505. NULL,
  506. true,
  507. context);
  508. } else if (message->length > 20 && Headers_getIpVersion(message->bytes) == 4) {
  509. struct Headers_IP4Header* header = (struct Headers_IP4Header*) message->bytes;
  510. conn = getConnection(context->pub.connectionList.connections,
  511. NULL,
  512. header->sourceAddr,
  513. true,
  514. context);
  515. } else {
  516. Log_info(context->logger, "Message of unknown type from TUN");
  517. return Error_INVALID;
  518. }
  519. if (!conn) {
  520. Log_info(context->logger, "Message with unrecognized address from TUN");
  521. return Error_INVALID;
  522. }
  523. return sendToNode(message, conn, context);
  524. }
  525. static uint8_t ip6FromNode(struct Message* message,
  526. struct IpTunnel_Connection* conn,
  527. struct IpTunnel_pvt* context)
  528. {
  529. struct Headers_IP6Header* header = (struct Headers_IP6Header*) message->bytes;
  530. if (Bits_isZero(header->sourceAddr, 16) || Bits_isZero(header->destinationAddr, 16)) {
  531. if (Bits_isZero(header->sourceAddr, 32)) {
  532. return incomingControlMessage(message, conn, context);
  533. }
  534. Log_debug(context->logger, "Got message with zero address");
  535. return Error_INVALID;
  536. }
  537. if (!getConnection(conn, header->sourceAddr, NULL, false, context)) {
  538. Log_debug(context->logger, "Got message with wrong address for connection");
  539. return Error_INVALID;
  540. }
  541. TUNMessageType_push(message, Ethernet_TYPE_IP6, NULL);
  542. struct Interface* tunIf = &context->pub.tunInterface;
  543. if (tunIf->receiveMessage) {
  544. tunIf->receiveMessage(message, tunIf);
  545. }
  546. return 0;
  547. }
  548. static uint8_t ip4FromNode(struct Message* message,
  549. struct IpTunnel_Connection* conn,
  550. struct IpTunnel_pvt* context)
  551. {
  552. struct Headers_IP4Header* header = (struct Headers_IP4Header*) message->bytes;
  553. if (Bits_isZero(header->sourceAddr, 4) || Bits_isZero(header->destAddr, 4)) {
  554. Log_debug(context->logger, "Got message with zero address");
  555. return Error_INVALID;
  556. }
  557. if (!getConnection(conn, NULL, header->sourceAddr, false, context)) {
  558. Log_debug(context->logger, "Got message with wrong address for connection");
  559. return Error_INVALID;
  560. }
  561. TUNMessageType_push(message, Ethernet_TYPE_IP4, NULL);
  562. struct Interface* tunIf = &context->pub.tunInterface;
  563. if (tunIf->receiveMessage) {
  564. return tunIf->receiveMessage(message, tunIf);
  565. }
  566. return 0;
  567. }
  568. static uint8_t incomingFromNode(struct Message* message, struct Interface* nodeIf)
  569. {
  570. struct IpTunnel_pvt* context =
  571. (struct IpTunnel_pvt*)(((char*)nodeIf) - offsetof(struct IpTunnel, nodeInterface));
  572. Identity_check(context);
  573. //Log_debug(context->logger, "Got incoming message");
  574. Assert_true(message->length >= IpTunnel_PacketInfoHeader_SIZE);
  575. struct IpTunnel_PacketInfoHeader* header = (struct IpTunnel_PacketInfoHeader*) message->bytes;
  576. struct IpTunnel_Connection* conn = connectionByPubKey(header->nodeKey, context);
  577. if (!conn) {
  578. #ifdef Log_DEBUG
  579. uint8_t addr[40];
  580. AddrTools_printIp(addr, header->nodeIp6Addr);
  581. Log_debug(context->logger, "Got message from unrecognized node [%s]", addr);
  582. #endif
  583. return 0;
  584. }
  585. Message_shift(message, -IpTunnel_PacketInfoHeader_SIZE, NULL);
  586. if (message->length > 40 && Headers_getIpVersion(message->bytes) == 6) {
  587. return ip6FromNode(message, conn, context);
  588. }
  589. if (message->length > 20 && Headers_getIpVersion(message->bytes) == 4) {
  590. return ip4FromNode(message, conn, context);
  591. }
  592. #ifdef Log_DEBUG
  593. uint8_t addr[40];
  594. AddrTools_printIp(addr, header->nodeIp6Addr);
  595. Log_debug(context->logger,
  596. "Got message of unknown type, length: [%d], IP version [%d] from [%s]",
  597. message->length,
  598. (message->length > 1) ? Headers_getIpVersion(message->bytes) : 0,
  599. addr);
  600. #endif
  601. return 0;
  602. }
  603. static void timeout(void* vcontext)
  604. {
  605. struct IpTunnel_pvt* context = vcontext;
  606. Log_debug(context->logger, "Checking for connections to poll. Total connections [%u]",
  607. context->pub.connectionList.count);
  608. if (!context->pub.connectionList.count) {
  609. return;
  610. }
  611. int32_t beginning = Random_int32(context->rand) % context->pub.connectionList.count;
  612. int32_t i = beginning;
  613. do {
  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. } while ((++i % (int32_t)context->pub.connectionList.count) != beginning);
  623. }
  624. void IpTunnel_setTunName(char* interfaceName, struct IpTunnel* ipTun)
  625. {
  626. struct IpTunnel_pvt* ctx = Identity_cast((struct IpTunnel_pvt*) ipTun);
  627. ctx->ifName = String_new(interfaceName, ctx->allocator);
  628. }
  629. struct IpTunnel* IpTunnel_new(struct Log* logger,
  630. struct EventBase* eventBase,
  631. struct Allocator* alloc,
  632. struct Random* rand,
  633. struct Hermes* hermes)
  634. {
  635. struct IpTunnel_pvt* context = Allocator_clone(alloc, (&(struct IpTunnel_pvt) {
  636. .pub = {
  637. .tunInterface = { .sendMessage = incomingFromTun },
  638. .nodeInterface = { .sendMessage = incomingFromNode }
  639. },
  640. .allocator = alloc,
  641. .logger = logger,
  642. .rand = rand,
  643. .hermes = hermes
  644. }));
  645. context->timeout = Timeout_setInterval(timeout, context, 10000, eventBase, alloc);
  646. Identity_set(context);
  647. return &context->pub;
  648. }