IpTunnel.c 27 KB

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