1
0

IpTunnel.c 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736
  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 "benc/String.h"
  16. #include "benc/Dict.h"
  17. #include "benc/List.h"
  18. #include "benc/Int.h"
  19. #include "benc/serialization/standard/BencMessageWriter.h"
  20. #include "benc/serialization/standard/BencMessageReader.h"
  21. #include "crypto/random/Random.h"
  22. #include "exception/Jmp.h"
  23. #include "interface/tuntap/TUNMessageType.h"
  24. #include "memory/Allocator.h"
  25. #include "tunnel/IpTunnel.h"
  26. #include "crypto/AddressCalc.h"
  27. #include "util/platform/netdev/NetDev.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 "util/Defined.h"
  34. #include "wire/Error.h"
  35. #include "wire/Headers.h"
  36. #include "wire/Ethernet.h"
  37. #include "wire/DataHeader.h"
  38. #include <stddef.h>
  39. struct IpTunnel_pvt
  40. {
  41. struct IpTunnel pub;
  42. struct Allocator* allocator;
  43. struct Log* logger;
  44. uint32_t connectionCapacity;
  45. /** An always incrementing number which represents the connections. */
  46. uint32_t nextConnectionNumber;
  47. /** The name of the TUN interface so that ip addresses can be added. */
  48. String* ifName;
  49. /**
  50. * Every 10 seconds check for connections which the other end has
  51. * not provided ip addresses and send more requests.
  52. */
  53. struct Timeout* timeout;
  54. struct Random* rand;
  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. struct IpTunnel_Connection* conn = &context->pub.connectionList.connections[i];
  94. if (!Bits_memcmp(pubKey, conn->routeHeader.publicKey, 32)) {
  95. return conn;
  96. }
  97. }
  98. return NULL;
  99. }
  100. /**
  101. * Allow another node to tunnel IPv4 and/or ICANN IPv6 through this node.
  102. *
  103. * @param publicKeyOfAuthorizedNode the key for the node which will be allowed to connect.
  104. * @param ip6Addr the IPv6 address which the node will be issued or NULL.
  105. * @param ip6Prefix the IPv6 netmask/prefix length.
  106. * @param ip4Addr the IPv4 address which the node will be issued or NULL.
  107. * @param ip4Prefix the IPv4 netmask/prefix length.
  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, uint8_t ip6Prefix,
  113. struct Sockaddr* ip4Addr, uint8_t ip4Prefix,
  114. struct IpTunnel* tunnel)
  115. {
  116. struct IpTunnel_pvt* context = Identity_check((struct IpTunnel_pvt*)tunnel);
  117. Log_debug(context->logger, "IPv4 Prefix to allow: %d", ip4Prefix);
  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->routeHeader.publicKey, publicKeyOfAuthorizedNode, 32);
  128. AddressCalc_addressForPublicKey(conn->routeHeader.ip6, publicKeyOfAuthorizedNode);
  129. if (ip4Address) {
  130. Bits_memcpyConst(conn->connectionIp4, ip4Address, 4);
  131. conn->connectionIp4Prefix = ip4Prefix;
  132. }
  133. if (ip6Address) {
  134. Bits_memcpyConst(conn->connectionIp6, ip6Address, 16);
  135. conn->connectionIp6Prefix = ip6Prefix;
  136. }
  137. return conn->number;
  138. }
  139. static Iface_DEFUN sendToNode(struct Message* message,
  140. struct IpTunnel_Connection* connection,
  141. struct IpTunnel_pvt* context)
  142. {
  143. Message_push(message, NULL, DataHeader_SIZE, NULL);
  144. struct DataHeader* dh = (struct DataHeader*) message->bytes;
  145. DataHeader_setContentType(dh, ContentType_IPTUN);
  146. DataHeader_setVersion(dh, DataHeader_CURRENT_VERSION);
  147. Message_push(message, &connection->routeHeader, RouteHeader_SIZE, NULL);
  148. return Iface_next(&context->pub.nodeInterface, message);
  149. }
  150. static void sendControlMessage(Dict* dict,
  151. struct IpTunnel_Connection* connection,
  152. struct Allocator* requestAlloc,
  153. struct IpTunnel_pvt* context)
  154. {
  155. struct Message* msg = Message_new(0, 1024, requestAlloc);
  156. BencMessageWriter_write(dict, msg, NULL);
  157. int length = msg->length;
  158. // do UDP header.
  159. Message_shift(msg, Headers_UDPHeader_SIZE, NULL);
  160. struct Headers_UDPHeader* uh = (struct Headers_UDPHeader*) msg->bytes;
  161. uh->srcPort_be = 0;
  162. uh->destPort_be = 0;
  163. uh->length_be = Endian_hostToBigEndian16(length);
  164. uh->checksum_be = 0;
  165. uint16_t payloadLength = msg->length;
  166. Message_shift(msg, Headers_IP6Header_SIZE, NULL);
  167. struct Headers_IP6Header* header = (struct Headers_IP6Header*) msg->bytes;
  168. header->versionClassAndFlowLabel = 0;
  169. header->flowLabelLow_be = 0;
  170. header->nextHeader = 17;
  171. header->hopLimit = 0;
  172. header->payloadLength_be = Endian_hostToBigEndian16(payloadLength);
  173. Headers_setIpVersion(header);
  174. // zero the source and dest addresses.
  175. Bits_memset(header->sourceAddr, 0, 32);
  176. uh->checksum_be = Checksum_udpIp6(header->sourceAddr,
  177. (uint8_t*) uh,
  178. msg->length - Headers_IP6Header_SIZE);
  179. Iface_CALL(sendToNode, msg, connection, context);
  180. }
  181. static void requestAddresses(struct IpTunnel_Connection* conn, struct IpTunnel_pvt* context)
  182. {
  183. if (Defined(Log_DEBUG)) {
  184. uint8_t addr[40];
  185. AddrTools_printIp(addr, conn->routeHeader.ip6);
  186. Log_debug(context->logger, "Requesting addresses from [%s] for connection [%d]",
  187. addr, conn->number);
  188. }
  189. int number = conn->number;
  190. Dict d = Dict_CONST(
  191. String_CONST("q"), String_OBJ(String_CONST("IpTunnel_getAddresses")), Dict_CONST(
  192. String_CONST("txid"), String_OBJ((&(String){ .len = 4, .bytes = (char*)&number })),
  193. NULL
  194. ));
  195. struct Allocator* msgAlloc = Allocator_child(context->allocator);
  196. sendControlMessage(&d, conn, msgAlloc, context);
  197. Allocator_free(msgAlloc);
  198. }
  199. /**
  200. * Connect to another node and get IPv4 and/or IPv6 addresses from it.
  201. *
  202. * @param publicKeyOfNodeToConnectTo the key for the node to connect to.
  203. * @param tunnel the IpTunnel.
  204. * @return an connection number which is usable with IpTunnel_remove().
  205. */
  206. int IpTunnel_connectTo(uint8_t publicKeyOfNodeToConnectTo[32], struct IpTunnel* tunnel)
  207. {
  208. struct IpTunnel_pvt* context = Identity_check((struct IpTunnel_pvt*)tunnel);
  209. struct IpTunnel_Connection* conn = newConnection(true, context);
  210. Bits_memcpyConst(conn->routeHeader.publicKey, publicKeyOfNodeToConnectTo, 32);
  211. AddressCalc_addressForPublicKey(conn->routeHeader.ip6, publicKeyOfNodeToConnectTo);
  212. if (Defined(Log_DEBUG)) {
  213. uint8_t addr[40];
  214. AddrTools_printIp(addr, conn->routeHeader.ip6);
  215. Log_debug(context->logger, "Trying to connect to [%s]", addr);
  216. }
  217. requestAddresses(conn, context);
  218. return conn->number;
  219. }
  220. /**
  221. * Disconnect from a node or remove authorization to connect.
  222. *
  223. * @param connection the connection to remove.
  224. * @param tunnel the IpTunnel.
  225. */
  226. int IpTunnel_removeConnection(int connectionNumber, struct IpTunnel* tunnel)
  227. {
  228. //struct IpTunnel_pvt* context = Identity_check((struct IpTunnel_pvt*)tunnel);
  229. return 0;
  230. }
  231. static bool isControlMessageInvalid(struct Message* message, struct IpTunnel_pvt* context)
  232. {
  233. struct Headers_IP6Header* header = (struct Headers_IP6Header*) message->bytes;
  234. uint16_t length = Endian_bigEndianToHost16(header->payloadLength_be);
  235. if (header->nextHeader != 17 || message->length < length + Headers_IP6Header_SIZE) {
  236. Log_warn(context->logger, "Invalid IPv6 packet (not UDP or length field too big)");
  237. return true;
  238. }
  239. Message_shift(message, -Headers_IP6Header_SIZE, NULL);
  240. struct Headers_UDPHeader* udp = (struct Headers_UDPHeader*) message->bytes;
  241. if (Checksum_udpIp6(header->sourceAddr, message->bytes, length)) {
  242. Log_warn(context->logger, "Checksum mismatch");
  243. return true;
  244. }
  245. length -= Headers_UDPHeader_SIZE;
  246. if (Endian_bigEndianToHost16(udp->length_be) != length
  247. || udp->srcPort_be != 0
  248. || udp->destPort_be != 0)
  249. {
  250. Log_warn(context->logger, "Invalid UDP packet (length mismatch or wrong ports)");
  251. return true;
  252. }
  253. Message_shift(message, -Headers_UDPHeader_SIZE, NULL);
  254. message->length = length;
  255. return false;
  256. }
  257. static Iface_DEFUN requestForAddresses(Dict* request,
  258. struct IpTunnel_Connection* conn,
  259. struct Allocator* requestAlloc,
  260. struct IpTunnel_pvt* context)
  261. {
  262. if (Defined(Log_DEBUG)) {
  263. uint8_t addr[40];
  264. AddrTools_printIp(addr, conn->routeHeader.ip6);
  265. Log_debug(context->logger, "Got request for addresses from [%s]", addr);
  266. }
  267. if (conn->isOutgoing) {
  268. Log_warn(context->logger, "got request for addresses from outgoing connection");
  269. return 0;
  270. }
  271. Dict* addresses = Dict_new(requestAlloc);
  272. bool noAddresses = true;
  273. if (!Bits_isZero(conn->connectionIp6, 16)) {
  274. Dict_putString(addresses,
  275. String_CONST("ip6"),
  276. String_newBinary((char*)conn->connectionIp6, 16, requestAlloc),
  277. requestAlloc);
  278. Dict_putInt(addresses,
  279. String_CONST("ip6Prefix"), (int64_t)conn->connectionIp6Prefix,
  280. requestAlloc);
  281. noAddresses = false;
  282. }
  283. if (!Bits_isZero(conn->connectionIp4, 4)) {
  284. Dict_putString(addresses,
  285. String_CONST("ip4"),
  286. String_newBinary((char*)conn->connectionIp4, 4, requestAlloc),
  287. requestAlloc);
  288. Dict_putInt(addresses,
  289. String_CONST("ip4Prefix"), (int64_t)conn->connectionIp4Prefix,
  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. sendControlMessage(msg, conn, requestAlloc, context);
  304. return 0;
  305. }
  306. static void addAddress(char* printedAddr, uint8_t prefixLen, struct IpTunnel_pvt* ctx)
  307. {
  308. if (!ctx->ifName) {
  309. Log_error(ctx->logger, "Failed to set IP address because TUN interface is not setup");
  310. return;
  311. }
  312. struct Sockaddr_storage ss;
  313. if (Sockaddr_parse(printedAddr, &ss)) {
  314. Log_error(ctx->logger, "Invalid ip, setting ip address on TUN");
  315. return;
  316. }
  317. struct Jmp j;
  318. Jmp_try(j) {
  319. NetDev_addAddress(ctx->ifName->bytes, &ss.addr, prefixLen, NULL, &j.handler);
  320. } Jmp_catch {
  321. Log_error(ctx->logger, "Error setting ip address on TUN [%s]", j.message);
  322. }
  323. }
  324. static Iface_DEFUN incomingAddresses(Dict* d,
  325. struct IpTunnel_Connection* conn,
  326. struct Allocator* alloc,
  327. struct IpTunnel_pvt* context)
  328. {
  329. if (!conn->isOutgoing) {
  330. Log_warn(context->logger, "got offer of addresses from incoming connection");
  331. return 0;
  332. }
  333. String* txid = Dict_getString(d, String_CONST("txid"));
  334. if (!txid || txid->len != 4) {
  335. Log_info(context->logger, "missing or wrong length txid");
  336. return 0;
  337. }
  338. int number;
  339. Bits_memcpyConst(&number, txid->bytes, 4);
  340. if (number < 0 || number >= (int)context->nextConnectionNumber) {
  341. Log_info(context->logger, "txid out of range");
  342. return 0;
  343. }
  344. if (number != conn->number) {
  345. for (int i = 0; i < (int)context->pub.connectionList.count; i++) {
  346. if (context->pub.connectionList.connections[i].number == number) {
  347. if (Bits_memcmp(conn->routeHeader.publicKey,
  348. context->pub.connectionList.connections[i].routeHeader.publicKey,
  349. 32))
  350. {
  351. Log_info(context->logger, "txid doesn't match origin");
  352. return 0;
  353. } else {
  354. conn = &context->pub.connectionList.connections[i];
  355. }
  356. }
  357. }
  358. }
  359. Dict* addresses = Dict_getDict(d, String_CONST("addresses"));
  360. String* ip4 = Dict_getString(addresses, String_CONST("ip4"));
  361. int64_t* ip4Prefix = Dict_getInt(addresses, String_CONST("ip4Prefix"));
  362. if (ip4 && ip4->len == 4) {
  363. Bits_memcpyConst(conn->connectionIp4, ip4->bytes, 4);
  364. if (ip4Prefix && *ip4Prefix >= 0 && *ip4Prefix <= 32) {
  365. conn->connectionIp4Prefix = (uint8_t) *ip4Prefix;
  366. } else {
  367. conn->connectionIp4Prefix = 0;
  368. }
  369. struct Sockaddr* sa = Sockaddr_clone(Sockaddr_LOOPBACK, alloc);
  370. uint8_t* addrBytes = NULL;
  371. Sockaddr_getAddress(sa, &addrBytes);
  372. Bits_memcpy(addrBytes, ip4->bytes, 4);
  373. char* printedAddr = Sockaddr_print(sa, alloc);
  374. Log_info(context->logger, "Got issued address [%s/%d] for connection [%d]",
  375. printedAddr, conn->connectionIp4Prefix, conn->number);
  376. addAddress(printedAddr, conn->connectionIp4Prefix, context);
  377. }
  378. String* ip6 = Dict_getString(addresses, String_CONST("ip6"));
  379. int64_t* ip6Prefix = Dict_getInt(addresses, String_CONST("ip6Prefix"));
  380. if (ip6 && ip6->len == 16) {
  381. Bits_memcpyConst(conn->connectionIp6, ip6->bytes, 16);
  382. if (ip6Prefix && *ip6Prefix >= 0 && *ip6Prefix <= 128) {
  383. conn->connectionIp6Prefix = (uint8_t) *ip6Prefix;
  384. } else {
  385. conn->connectionIp6Prefix = 0;
  386. }
  387. if (Defined(Darwin) && conn->connectionIp6Prefix < 3) {
  388. // Apple doesn't handle prefix length of 0 properly. 3 covers
  389. // all IPv6 unicast space.
  390. conn->connectionIp6Prefix = 3;
  391. }
  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/%d] for connection [%d]",
  398. printedAddr, conn->connectionIp6Prefix, conn->number);
  399. addAddress(printedAddr, conn->connectionIp6Prefix, context);
  400. }
  401. return 0;
  402. }
  403. static Iface_DEFUN incomingControlMessage(struct Message* message,
  404. struct IpTunnel_Connection* conn,
  405. struct IpTunnel_pvt* context)
  406. {
  407. if (Defined(Log_DEBUG)) {
  408. uint8_t addr[40];
  409. AddrTools_printIp(addr, conn->routeHeader.ip6);
  410. Log_debug(context->logger, "Got incoming message from [%s]", addr);
  411. }
  412. // This aligns the message on the content.
  413. if (isControlMessageInvalid(message, context)) {
  414. return 0;
  415. }
  416. if (Defined(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. }
  422. struct Allocator* alloc = Allocator_child(message->alloc);
  423. Dict* d = NULL;
  424. char* err = BencMessageReader_readNoExcept(message, alloc, &d);
  425. if (err) {
  426. Log_info(context->logger, "Failed to parse message [%s]", err);
  427. return 0;
  428. }
  429. if (Dict_getDict(d, String_CONST("addresses"))) {
  430. return incomingAddresses(d, conn, alloc, context);
  431. }
  432. if (String_equals(String_CONST("IpTunnel_getAddresses"),
  433. Dict_getString(d, String_CONST("q"))))
  434. {
  435. return requestForAddresses(d, conn, alloc, context);
  436. }
  437. Log_warn(context->logger, "Message which is unhandled");
  438. return 0;
  439. }
  440. /**
  441. * If there are multiple connections to the same server,
  442. * the ip address on the packet might belong to the wrong one.
  443. * In that case we get the right connection.
  444. * If the other party has sent a packet from an address which is not
  445. * valid, this will return NULL and their packet can be dropped.
  446. *
  447. * @param conn the connection which matches the other node's key.
  448. * @param sourceAndDestIp6 the source and destination IPv6 addresses,
  449. * must be NULL if sourceAndDestIp4 is specified.
  450. * @param sourceAndDestIp4 the source and destination IPv4 addresses.
  451. * must be NULL if sourceAndDestIp6 is specified.
  452. * @param context
  453. * @return the real connection or null if the packet is invalid.
  454. */
  455. static struct IpTunnel_Connection* getConnection(struct IpTunnel_Connection* conn,
  456. uint8_t sourceAndDestIp6[32],
  457. uint8_t sourceAndDestIp4[8],
  458. bool isFromTun,
  459. struct IpTunnel_pvt* context)
  460. {
  461. uint8_t* source = (sourceAndDestIp6) ? sourceAndDestIp6 : sourceAndDestIp4;
  462. uint32_t length = (sourceAndDestIp6) ? 16 : 4;
  463. uint8_t* destination = source + length;
  464. if (sourceAndDestIp6) {
  465. // never allowed
  466. if (source[0] == 0xfc || destination[0] == 0xfc) {
  467. return NULL;
  468. }
  469. }
  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 Iface_DEFUN incomingFromTun(struct Message* message, struct Iface* tunIf)
  493. {
  494. struct IpTunnel_pvt* context = Identity_check((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 0;
  518. }
  519. if (!conn) {
  520. Log_info(context->logger, "Message with unrecognized address from TUN");
  521. return 0;
  522. }
  523. return sendToNode(message, conn, context);
  524. }
  525. static Iface_DEFUN 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 0;
  536. }
  537. if (!getConnection(conn, header->sourceAddr, NULL, false, context)) {
  538. Log_debug(context->logger, "Got message with wrong address for connection");
  539. return 0;
  540. }
  541. TUNMessageType_push(message, Ethernet_TYPE_IP6, NULL);
  542. return Iface_next(&context->pub.tunInterface, message);
  543. }
  544. static Iface_DEFUN ip4FromNode(struct Message* message,
  545. struct IpTunnel_Connection* conn,
  546. struct IpTunnel_pvt* context)
  547. {
  548. struct Headers_IP4Header* header = (struct Headers_IP4Header*) message->bytes;
  549. if (Bits_isZero(header->sourceAddr, 4) || Bits_isZero(header->destAddr, 4)) {
  550. Log_debug(context->logger, "Got message with zero address");
  551. return 0;
  552. } else if (!getConnection(conn, NULL, header->sourceAddr, false, context)) {
  553. Log_debug(context->logger, "Got message with wrong address for connection");
  554. return 0;
  555. }
  556. TUNMessageType_push(message, Ethernet_TYPE_IP4, NULL);
  557. return Iface_next(&context->pub.tunInterface, message);
  558. }
  559. static Iface_DEFUN incomingFromNode(struct Message* message, struct Iface* nodeIf)
  560. {
  561. struct IpTunnel_pvt* context =
  562. Identity_containerOf(nodeIf, struct IpTunnel_pvt, pub.nodeInterface);
  563. //Log_debug(context->logger, "Got incoming message");
  564. Assert_true(message->length >= RouteHeader_SIZE + DataHeader_SIZE);
  565. struct RouteHeader* rh = (struct RouteHeader*) message->bytes;
  566. struct DataHeader* dh = (struct DataHeader*) &rh[1];
  567. Assert_true(DataHeader_getContentType(dh) == ContentType_IPTUN);
  568. struct IpTunnel_Connection* conn = connectionByPubKey(rh->publicKey, context);
  569. if (!conn) {
  570. if (Defined(Log_DEBUG)) {
  571. uint8_t addr[40];
  572. AddrTools_printIp(addr, rh->ip6);
  573. Log_debug(context->logger, "Got message from unrecognized node [%s]", addr);
  574. }
  575. return 0;
  576. }
  577. Message_shift(message, -(RouteHeader_SIZE + DataHeader_SIZE), NULL);
  578. if (message->length > 40 && Headers_getIpVersion(message->bytes) == 6) {
  579. return ip6FromNode(message, conn, context);
  580. }
  581. if (message->length > 20 && Headers_getIpVersion(message->bytes) == 4) {
  582. return ip4FromNode(message, conn, context);
  583. }
  584. if (Defined(Log_DEBUG)) {
  585. uint8_t addr[40];
  586. AddrTools_printIp(addr, rh->ip6);
  587. Log_debug(context->logger,
  588. "Got message of unknown type, length: [%d], IP version [%d] from [%s]",
  589. message->length,
  590. (message->length > 1) ? Headers_getIpVersion(message->bytes) : 0,
  591. addr);
  592. }
  593. return 0;
  594. }
  595. static void timeout(void* vcontext)
  596. {
  597. struct IpTunnel_pvt* context = vcontext;
  598. if (!context->pub.connectionList.count) {
  599. return;
  600. }
  601. Log_debug(context->logger, "Checking for connections to poll. Total connections [%u]",
  602. context->pub.connectionList.count);
  603. uint32_t beginning = Random_uint32(context->rand) % context->pub.connectionList.count;
  604. uint32_t i = beginning;
  605. do {
  606. Assert_true(i < context->pub.connectionList.count);
  607. struct IpTunnel_Connection* conn = &context->pub.connectionList.connections[i];
  608. if (conn->isOutgoing
  609. && Bits_isZero(conn->connectionIp6, 16)
  610. && Bits_isZero(conn->connectionIp4, 4))
  611. {
  612. requestAddresses(conn, context);
  613. break;
  614. }
  615. i = (i + 1) % context->pub.connectionList.count;
  616. } while (i != beginning);
  617. }
  618. void IpTunnel_setTunName(char* interfaceName, struct IpTunnel* ipTun)
  619. {
  620. struct IpTunnel_pvt* ctx = Identity_check((struct IpTunnel_pvt*) ipTun);
  621. ctx->ifName = String_new(interfaceName, ctx->allocator);
  622. }
  623. struct IpTunnel* IpTunnel_new(struct Log* logger,
  624. struct EventBase* eventBase,
  625. struct Allocator* alloc,
  626. struct Random* rand)
  627. {
  628. struct IpTunnel_pvt* context = Allocator_clone(alloc, (&(struct IpTunnel_pvt) {
  629. .pub = {
  630. .tunInterface = { .send = incomingFromTun },
  631. .nodeInterface = { .send = incomingFromNode }
  632. },
  633. .allocator = alloc,
  634. .logger = logger,
  635. .rand = rand
  636. }));
  637. context->timeout = Timeout_setInterval(timeout, context, 10000, eventBase, alloc);
  638. Identity_set(context);
  639. return &context->pub;
  640. }