ETHInterface_linux.c 13 KB

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