1
0

ETHInterface_linux.c 13 KB

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