1
0

ETHInterface_linux.c 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381
  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. #define string_strncpy
  16. #define string_strerror
  17. #include "exception/Except.h"
  18. #include "interface/Interface.h"
  19. #include "interface/ETHInterface.h"
  20. #include "memory/Allocator.h"
  21. #include "interface/InterfaceController.h"
  22. #include "interface/MultiInterface.h"
  23. #include "wire/Headers.h"
  24. #include "wire/Message.h"
  25. #include "wire/Error.h"
  26. #include "wire/Ethernet.h"
  27. #include "util/Assert.h"
  28. #include "util/platform/libc/string.h"
  29. #include "util/platform/Socket.h"
  30. #include "util/events/Event.h"
  31. #include "util/Identity.h"
  32. #include "util/AddrTools.h"
  33. #include "util/version/Version.h"
  34. #include "util/events/Timeout.h"
  35. #include <sys/socket.h>
  36. #include <linux/if_packet.h>
  37. #include <linux/if_ether.h>
  38. #include <linux/if_arp.h>
  39. #include <sys/types.h>
  40. #include <sys/ioctl.h>
  41. #include <unistd.h>
  42. #include <errno.h>
  43. #define MAX_PACKET_SIZE 1496
  44. #define MIN_PACKET_SIZE 46
  45. #define PADDING 512
  46. // 2 last 0x00 of .sll_addr are removed from original size (20)
  47. #define SOCKADDR_LL_LEN 18
  48. /** Wait 16 seconds between sending beacon messages. */
  49. #define BEACON_INTERVAL 32768
  50. struct ETHInterface
  51. {
  52. struct Interface generic;
  53. Socket socket;
  54. uint8_t messageBuff[PADDING + MAX_PACKET_SIZE];
  55. /** The unix interface index which is used to identify the eth device. */
  56. int ifindex;
  57. struct Log* logger;
  58. struct InterfaceController* ic;
  59. struct MultiInterface* multiIface;
  60. struct sockaddr_ll addrBase;
  61. int beaconState;
  62. /**
  63. * A unique(ish) id which will be different every time the router starts.
  64. * This will prevent new eth frames from being confused with old frames from an expired session.
  65. */
  66. uint16_t id;
  67. Identity
  68. };
  69. static uint8_t sendMessage(struct Message* message, struct Interface* ethIf)
  70. {
  71. struct ETHInterface* context = Identity_cast((struct ETHInterface*) ethIf);
  72. struct sockaddr_ll addr;
  73. Bits_memcpyConst(&addr, &context->addrBase, sizeof(struct sockaddr_ll));
  74. Message_pop(message, addr.sll_addr, 8, NULL);
  75. /* Cut down on the noise
  76. uint8_t buff[sizeof(addr) * 2 + 1] = {0};
  77. Hex_encode(buff, sizeof(buff), (uint8_t*)&addr, sizeof(addr));
  78. Log_debug(context->logger, "Sending ethernet frame to [%s]", buff);
  79. */
  80. // Check if we will have to pad the message and pad if necessary.
  81. int pad = 0;
  82. for (int length = message->length; length+2 < MIN_PACKET_SIZE; length += 8) {
  83. pad++;
  84. }
  85. if (pad > 0) {
  86. int length = message->length;
  87. Message_shift(message, pad*8, NULL);
  88. Bits_memset(message->bytes, 0, pad*8);
  89. Bits_memmove(message->bytes, &message->bytes[pad*8], length);
  90. }
  91. Assert_true(pad < 8);
  92. uint16_t padAndId_be = Endian_hostToBigEndian16((context->id << 3) | pad);
  93. Message_push(message, &padAndId_be, 2, NULL);
  94. if (sendto(context->socket,
  95. message->bytes,
  96. message->length,
  97. 0,
  98. (struct sockaddr*) &addr,
  99. sizeof(struct sockaddr_ll)) < 0)
  100. {
  101. switch (errno) {
  102. case EMSGSIZE:
  103. return Error_OVERSIZE_MESSAGE;
  104. case ENOBUFS:
  105. case EAGAIN:
  106. return Error_LINK_LIMIT_EXCEEDED;
  107. default:;
  108. Log_info(context->logger, "Got error sending to socket [%s]", strerror(errno));
  109. }
  110. }
  111. return 0;
  112. }
  113. static void handleBeacon(struct Message* msg, struct ETHInterface* context)
  114. {
  115. if (!context->beaconState) {
  116. // accepting beacons disabled.
  117. Log_debug(context->logger, "Dropping beacon because beaconing is disabled");
  118. return;
  119. }
  120. struct sockaddr_ll addr;
  121. Bits_memcpyConst(&addr, &context->addrBase, sizeof(struct sockaddr_ll));
  122. Message_pop(msg, addr.sll_addr, 8, NULL);
  123. if (msg->length < Headers_Beacon_SIZE) {
  124. // Oversize messages are ok because beacons may contain more information in the future.
  125. Log_debug(context->logger, "Dropping wrong size beacon, expected [%d] got [%d]",
  126. Headers_Beacon_SIZE, msg->length);
  127. return;
  128. }
  129. struct Headers_Beacon* beacon = (struct Headers_Beacon*) msg->bytes;
  130. uint32_t theirVersion = Endian_bigEndianToHost32(beacon->version_be);
  131. if (!Version_isCompatible(theirVersion, Version_CURRENT_PROTOCOL)) {
  132. #ifdef Log_DEBUG
  133. uint8_t mac[18];
  134. AddrTools_printMac(mac, addr.sll_addr);
  135. Log_debug(context->logger, "Dropped beacon from [%s] which was version [%d] "
  136. "our version is [%d] making them incompatable",
  137. mac, theirVersion, Version_CURRENT_PROTOCOL);
  138. #endif
  139. return;
  140. }
  141. #ifdef Log_DEBUG
  142. uint8_t mac[18];
  143. AddrTools_printMac(mac, addr.sll_addr);
  144. Log_debug(context->logger, "Got beacon from [%s]", mac);
  145. #endif
  146. String passStr = { .bytes = (char*) beacon->password, .len = Headers_Beacon_PASSWORD_LEN };
  147. struct Interface* iface = MultiInterface_ifaceForKey(context->multiIface, addr.sll_addr);
  148. int ret = InterfaceController_registerPeer(context->ic,
  149. beacon->publicKey,
  150. &passStr,
  151. false,
  152. true,
  153. iface);
  154. if (ret != 0) {
  155. uint8_t mac[18];
  156. AddrTools_printMac(mac, addr.sll_addr);
  157. Log_info(context->logger, "Got beacon from [%s] and registerPeer returned [%d]", mac, ret);
  158. }
  159. }
  160. static void sendBeacon(void* vcontext)
  161. {
  162. struct ETHInterface* context = Identity_cast((struct ETHInterface*) vcontext);
  163. if (context->beaconState != ETHInterface_beacon_ACCEPTING_AND_SENDING) {
  164. // beaconing disabled
  165. return;
  166. }
  167. struct {
  168. struct sockaddr_ll addr;
  169. struct Headers_Beacon beacon;
  170. } content;
  171. Bits_memcpyConst(&content.addr, &context->addrBase, sizeof(struct sockaddr_ll));
  172. Bits_memset(content.addr.sll_addr, 0xff, 6);
  173. InterfaceController_populateBeacon(context->ic, &content.beacon);
  174. struct Message m = {
  175. .bytes=(uint8_t*)content.addr.sll_addr,
  176. .padding=0,
  177. .length=sizeof(struct Headers_Beacon) + 8
  178. };
  179. int ret;
  180. if ((ret = sendMessage(&m, &context->generic)) != 0) {
  181. Log_info(context->logger, "Got error [%d] sending beacon [%s]", ret, strerror(errno));
  182. }
  183. }
  184. static void handleEvent(void* vcontext)
  185. {
  186. struct ETHInterface* context = Identity_cast((struct ETHInterface*) vcontext);
  187. struct Allocator* messageAlloc = Allocator_child(context->generic.allocator);
  188. struct Message* msg = Message_new(MAX_PACKET_SIZE, PADDING, messageAlloc);
  189. struct sockaddr_ll addr;
  190. uint32_t addrLen = sizeof(struct sockaddr_ll);
  191. // Knock it out of alignment by 2 bytes so that it will be
  192. // aligned when the idAndPadding is shifted off.
  193. Message_shift(msg, 2, NULL);
  194. int rc = recvfrom(context->socket,
  195. msg->bytes,
  196. msg->length,
  197. 0,
  198. (struct sockaddr*) &addr,
  199. &addrLen);
  200. if (rc < 0) {
  201. Log_debug(context->logger, "Failed to receive eth frame");
  202. return;
  203. }
  204. //Assert_true(addrLen == SOCKADDR_LL_LEN);
  205. // Pop the first 2 bytes of the message containing the node id and amount of padding.
  206. uint16_t idAndPadding_be;
  207. Message_pop(msg, &idAndPadding_be, 2, NULL);
  208. const uint16_t idAndPadding = Endian_bigEndianToHost16(idAndPadding_be);
  209. msg->length = rc - 2 - ((idAndPadding & 7) * 8);
  210. const uint16_t id = idAndPadding >> 3;
  211. Message_push(msg, &id, 2, NULL);
  212. Message_push(msg, addr.sll_addr, 6, NULL);
  213. if (addr.sll_pkttype == PACKET_BROADCAST) {
  214. handleBeacon(msg, context);
  215. return;
  216. }
  217. /* Cut down on the noise
  218. uint8_t buff[sizeof(addr) * 2 + 1] = {0};
  219. Hex_encode(buff, sizeof(buff), (uint8_t*)&addr, sizeof(addr));
  220. Log_debug(context->logger, "Got ethernet frame from [%s]", buff);
  221. */
  222. Interface_receiveMessage(&context->generic, msg);
  223. Allocator_free(messageAlloc);
  224. }
  225. int ETHInterface_beginConnection(const char* macAddress,
  226. uint8_t cryptoKey[32],
  227. String* password,
  228. struct ETHInterface* ethIf)
  229. {
  230. Identity_check(ethIf);
  231. struct sockaddr_ll addr;
  232. Bits_memcpyConst(&addr, &ethIf->addrBase, sizeof(struct sockaddr_ll));
  233. if (AddrTools_parseMac(addr.sll_addr, (const uint8_t*)macAddress)) {
  234. return ETHInterface_beginConnection_BAD_MAC;
  235. }
  236. struct Interface* iface = MultiInterface_ifaceForKey(ethIf->multiIface, &addr);
  237. int ret = InterfaceController_registerPeer(ethIf->ic, cryptoKey, password, false, false, iface);
  238. if (ret) {
  239. Allocator_free(iface->allocator);
  240. switch(ret) {
  241. case InterfaceController_registerPeer_BAD_KEY:
  242. return ETHInterface_beginConnection_BAD_KEY;
  243. case InterfaceController_registerPeer_OUT_OF_SPACE:
  244. return ETHInterface_beginConnection_OUT_OF_SPACE;
  245. default:
  246. return ETHInterface_beginConnection_UNKNOWN_ERROR;
  247. }
  248. }
  249. return 0;
  250. }
  251. int ETHInterface_beacon(struct ETHInterface* ethIf, int* state)
  252. {
  253. Identity_check(ethIf);
  254. if (state) {
  255. ethIf->beaconState = *state;
  256. // Send out a beacon right away so we don't have to wait.
  257. if (ethIf->beaconState == ETHInterface_beacon_ACCEPTING_AND_SENDING) {
  258. sendBeacon(ethIf);
  259. }
  260. }
  261. return ethIf->beaconState;
  262. }
  263. struct ETHInterface* ETHInterface_new(struct EventBase* base,
  264. const char* bindDevice,
  265. struct Allocator* allocator,
  266. struct Except* exHandler,
  267. struct Log* logger,
  268. struct InterfaceController* ic)
  269. {
  270. struct ETHInterface* context = Allocator_clone(allocator, (&(struct ETHInterface) {
  271. .generic = {
  272. .sendMessage = sendMessage,
  273. .allocator = allocator
  274. },
  275. .logger = logger,
  276. .ic = ic,
  277. .id = getpid()
  278. }));
  279. Identity_set(context);
  280. struct ifreq ifr = { .ifr_ifindex = 0 };
  281. context->socket = socket(AF_PACKET, SOCK_DGRAM, Ethernet_TYPE_CJDNS);
  282. if (context->socket == -1) {
  283. Except_throw(exHandler, "call to socket() failed. [%s]", strerror(errno));
  284. }
  285. strncpy(ifr.ifr_name, bindDevice, IFNAMSIZ - 1);
  286. if (ioctl(context->socket, SIOCGIFINDEX, &ifr) == -1) {
  287. Except_throw(exHandler, "failed to find interface index [%s]", strerror(errno));
  288. }
  289. context->ifindex = ifr.ifr_ifindex;
  290. if (ioctl(context->socket, SIOCGIFHWADDR, &ifr) == -1) {
  291. Except_throw(exHandler, "failed to find mac address of interface [%s]", strerror(errno));
  292. }
  293. uint8_t srcMac[6];
  294. Bits_memcpyConst(srcMac, ifr.ifr_hwaddr.sa_data, 6);
  295. // TODO: is the node's mac addr private information?
  296. Log_info(context->logger, "found MAC for device %s [%i]: %02x:%02x:%02x:%02x:%02x:%02x\n",
  297. bindDevice, context->ifindex,
  298. srcMac[0], srcMac[1], srcMac[2], srcMac[3], srcMac[4], srcMac[5]);
  299. context->addrBase = (struct sockaddr_ll) {
  300. .sll_family = AF_PACKET,
  301. .sll_protocol = Ethernet_TYPE_CJDNS,
  302. .sll_ifindex = context->ifindex,
  303. .sll_hatype = ARPHRD_ETHER,
  304. .sll_pkttype = PACKET_OTHERHOST,
  305. .sll_halen = ETH_ALEN
  306. };
  307. if (bind(context->socket, (struct sockaddr*) &context->addrBase, sizeof(struct sockaddr_ll))) {
  308. Except_throw(exHandler, "call to bind() failed [%s]", strerror(errno));
  309. }
  310. Socket_makeNonBlocking(context->socket);
  311. Event_socketRead(handleEvent, context, context->socket, base, allocator, exHandler);
  312. context->multiIface = MultiInterface_new(sizeof(struct sockaddr_ll), &context->generic, ic);
  313. Timeout_setInterval(sendBeacon, context, BEACON_INTERVAL, base, allocator);
  314. return context;
  315. }