1
0

ETHInterface_Linux.c 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383
  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);
  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);
  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);
  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);
  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 Message message =
  188. { .bytes = context->messageBuff + PADDING, .padding = PADDING, .length = MAX_PACKET_SIZE };
  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(&message, 2);
  194. int rc = recvfrom(context->socket,
  195. message.bytes,
  196. message.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(&message, &idAndPadding_be, 2);
  208. const uint16_t idAndPadding = Endian_bigEndianToHost16(idAndPadding_be);
  209. message.length = rc - 2 - ((idAndPadding & 7) * 8);
  210. const uint16_t id = idAndPadding >> 3;
  211. Message_push(&message, &id, 2);
  212. Message_push(&message, addr.sll_addr, 6);
  213. if (addr.sll_pkttype == PACKET_BROADCAST) {
  214. handleBeacon(&message, 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. context->generic.receiveMessage(&message, &context->generic);
  223. }
  224. int ETHInterface_beginConnection(const char* macAddress,
  225. uint8_t cryptoKey[32],
  226. String* password,
  227. struct ETHInterface* ethIf)
  228. {
  229. Identity_check(ethIf);
  230. struct sockaddr_ll addr;
  231. Bits_memcpyConst(&addr, &ethIf->addrBase, sizeof(struct sockaddr_ll));
  232. if (AddrTools_parseMac(addr.sll_addr, (const uint8_t*)macAddress)) {
  233. return ETHInterface_beginConnection_BAD_MAC;
  234. }
  235. struct Interface* iface = MultiInterface_ifaceForKey(ethIf->multiIface, &addr);
  236. int ret = InterfaceController_registerPeer(ethIf->ic, cryptoKey, password, false, false, iface);
  237. if (ret) {
  238. Allocator_free(iface->allocator);
  239. switch(ret) {
  240. case InterfaceController_registerPeer_BAD_KEY:
  241. return ETHInterface_beginConnection_BAD_KEY;
  242. case InterfaceController_registerPeer_OUT_OF_SPACE:
  243. return ETHInterface_beginConnection_OUT_OF_SPACE;
  244. default:
  245. return ETHInterface_beginConnection_UNKNOWN_ERROR;
  246. }
  247. }
  248. return 0;
  249. }
  250. int ETHInterface_beacon(struct ETHInterface* ethIf, int* state)
  251. {
  252. Identity_check(ethIf);
  253. if (state) {
  254. ethIf->beaconState = *state;
  255. // Send out a beacon right away so we don't have to wait.
  256. if (ethIf->beaconState == ETHInterface_beacon_ACCEPTING_AND_SENDING) {
  257. sendBeacon(ethIf);
  258. }
  259. }
  260. return ethIf->beaconState;
  261. }
  262. struct ETHInterface* ETHInterface_new(struct EventBase* base,
  263. const char* bindDevice,
  264. struct Allocator* allocator,
  265. struct Except* exHandler,
  266. struct Log* logger,
  267. struct InterfaceController* ic)
  268. {
  269. struct ETHInterface* context = Allocator_clone(allocator, (&(struct ETHInterface) {
  270. .generic = {
  271. .sendMessage = sendMessage,
  272. .allocator = allocator
  273. },
  274. .logger = logger,
  275. .ic = ic,
  276. .id = getpid()
  277. }));
  278. Identity_set(context);
  279. struct ifreq ifr = { .ifr_ifindex = 0 };
  280. context->socket = socket(AF_PACKET, SOCK_DGRAM, Ethernet_TYPE_CJDNS);
  281. if (context->socket == -1) {
  282. Except_raise(exHandler, ETHInterface_new_SOCKET_FAILED,
  283. "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_raise(exHandler, ETHInterface_new_FAILED_FIND_IFACE,
  288. "failed to find interface index [%s]", strerror(errno));
  289. }
  290. context->ifindex = ifr.ifr_ifindex;
  291. if (ioctl(context->socket, SIOCGIFHWADDR, &ifr) == -1) {
  292. Except_raise(exHandler, ETHInterface_new_FAILED_FIND_MACADDR,
  293. "failed to find mac address of interface [%s]", strerror(errno));
  294. }
  295. uint8_t srcMac[6];
  296. Bits_memcpyConst(srcMac, ifr.ifr_hwaddr.sa_data, 6);
  297. // TODO: is the node's mac addr private information?
  298. Log_info(context->logger, "found MAC for device %s [%i]: %02x:%02x:%02x:%02x:%02x:%02x\n",
  299. bindDevice, context->ifindex,
  300. srcMac[0], srcMac[1], srcMac[2], srcMac[3], srcMac[4], srcMac[5]);
  301. context->addrBase = (struct sockaddr_ll) {
  302. .sll_family = AF_PACKET,
  303. .sll_protocol = Ethernet_TYPE_CJDNS,
  304. .sll_ifindex = context->ifindex,
  305. .sll_hatype = ARPHRD_ETHER,
  306. .sll_pkttype = PACKET_OTHERHOST,
  307. .sll_halen = ETH_ALEN
  308. };
  309. if (bind(context->socket, (struct sockaddr*) &context->addrBase, sizeof(struct sockaddr_ll))) {
  310. Except_raise(exHandler, ETHInterface_new_BIND_FAILED,
  311. "call to bind() failed [%s]", strerror(errno));
  312. }
  313. Socket_makeNonBlocking(context->socket);
  314. Event_socketRead(handleEvent, context, context->socket, base, allocator, exHandler);
  315. context->multiIface = MultiInterface_new(sizeof(struct sockaddr_ll), &context->generic, ic);
  316. Timeout_setInterval(sendBeacon, context, BEACON_INTERVAL, base, allocator);
  317. return context;
  318. }