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. #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 16 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. Identity
  66. };
  67. static uint8_t sendMessage(struct Message* message, struct Interface* ethIf)
  68. {
  69. struct ETHInterface* context = Identity_check((struct ETHInterface*) ethIf);
  70. struct sockaddr_ll addr;
  71. Bits_memcpyConst(&addr, &context->addrBase, sizeof(struct sockaddr_ll));
  72. Message_pop(message, addr.sll_addr, 6, NULL);
  73. Message_shift(message, -2, NULL);
  74. /* Cut down on the noise
  75. uint8_t buff[sizeof(addr) * 2 + 1] = {0};
  76. Hex_encode(buff, sizeof(buff), (uint8_t*)&addr, sizeof(addr));
  77. Log_debug(context->logger, "Sending ethernet frame to [%s]", buff);
  78. */
  79. // Check if we will have to pad the message and pad if necessary.
  80. int pad = 0;
  81. for (int length = message->length; length+2 < MIN_PACKET_SIZE; length += 8) {
  82. pad++;
  83. }
  84. if (pad > 0) {
  85. int length = message->length;
  86. Message_shift(message, pad*8, NULL);
  87. Bits_memset(message->bytes, 0, pad*8);
  88. Bits_memmove(message->bytes, &message->bytes[pad*8], length);
  89. }
  90. Assert_true(pad < 8);
  91. uint16_t padAndId_be = Endian_hostToBigEndian16((context->id << 3) | pad);
  92. Message_push(message, &padAndId_be, 2, NULL);
  93. if (sendto(context->socket,
  94. message->bytes,
  95. message->length,
  96. 0,
  97. (struct sockaddr*) &addr,
  98. sizeof(struct sockaddr_ll)) < 0)
  99. {
  100. switch (errno) {
  101. case EMSGSIZE:
  102. return Error_OVERSIZE_MESSAGE;
  103. case ENOBUFS:
  104. case EAGAIN:
  105. return Error_LINK_LIMIT_EXCEEDED;
  106. default:;
  107. Log_info(context->logger, "Got error sending to socket [%s]",
  108. 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_check((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 handleEvent2(struct ETHInterface* context, struct Allocator* messageAlloc)
  185. {
  186. struct Message* msg = Message_new(MAX_PACKET_SIZE, PADDING, messageAlloc);
  187. struct sockaddr_ll addr;
  188. uint32_t addrLen = sizeof(struct sockaddr_ll);
  189. // Knock it out of alignment by 2 bytes so that it will be
  190. // aligned when the idAndPadding is shifted off.
  191. Message_shift(msg, 2, NULL);
  192. int rc = recvfrom(context->socket,
  193. msg->bytes,
  194. msg->length,
  195. 0,
  196. (struct sockaddr*) &addr,
  197. &addrLen);
  198. if (rc < 0) {
  199. Log_debug(context->logger, "Failed to receive eth frame");
  200. return;
  201. }
  202. //Assert_true(addrLen == SOCKADDR_LL_LEN);
  203. // Pop the first 2 bytes of the message containing the node id and amount of padding.
  204. uint16_t idAndPadding = Message_pop16(msg, NULL);
  205. msg->length = rc - 2 - ((idAndPadding & 7) * 8);
  206. uint16_t id = idAndPadding >> 3;
  207. Message_push(msg, &id, 2, NULL);
  208. Message_push(msg, addr.sll_addr, 6, NULL);
  209. if (addr.sll_pkttype == PACKET_BROADCAST) {
  210. handleBeacon(msg, context);
  211. return;
  212. }
  213. /* Cut down on the noise
  214. uint8_t buff[sizeof(addr) * 2 + 1] = {0};
  215. Hex_encode(buff, sizeof(buff), (uint8_t*)&addr, sizeof(addr));
  216. Log_debug(context->logger, "Got ethernet frame from [%s]", buff);
  217. */
  218. Interface_receiveMessage(&context->generic, msg);
  219. }
  220. static void handleEvent(void* vcontext)
  221. {
  222. struct ETHInterface* context = Identity_check((struct ETHInterface*) vcontext);
  223. struct Allocator* messageAlloc = Allocator_child(context->generic.allocator);
  224. handleEvent2(context, messageAlloc);
  225. Allocator_free(messageAlloc);
  226. }
  227. int ETHInterface_beginConnection(const char* macAddress,
  228. uint8_t cryptoKey[32],
  229. String* password,
  230. struct ETHInterface* ethIf)
  231. {
  232. Identity_check(ethIf);
  233. struct sockaddr_ll addr;
  234. Bits_memcpyConst(&addr, &ethIf->addrBase, sizeof(struct sockaddr_ll));
  235. if (AddrTools_parseMac(addr.sll_addr, (const uint8_t*)macAddress)) {
  236. return ETHInterface_beginConnection_BAD_MAC;
  237. }
  238. struct Interface* iface = MultiInterface_ifaceForKey(ethIf->multiIface, &addr);
  239. int ret = InterfaceController_registerPeer(ethIf->ic, cryptoKey, password, false, false, iface);
  240. if (ret) {
  241. Allocator_free(iface->allocator);
  242. switch(ret) {
  243. case InterfaceController_registerPeer_BAD_KEY:
  244. return ETHInterface_beginConnection_BAD_KEY;
  245. case InterfaceController_registerPeer_OUT_OF_SPACE:
  246. return ETHInterface_beginConnection_OUT_OF_SPACE;
  247. default:
  248. return ETHInterface_beginConnection_UNKNOWN_ERROR;
  249. }
  250. }
  251. return 0;
  252. }
  253. int ETHInterface_beacon(struct ETHInterface* ethIf, int* state)
  254. {
  255. Identity_check(ethIf);
  256. if (state) {
  257. ethIf->beaconState = *state;
  258. // Send out a beacon right away so we don't have to wait.
  259. if (ethIf->beaconState == ETHInterface_beacon_ACCEPTING_AND_SENDING) {
  260. sendBeacon(ethIf);
  261. }
  262. }
  263. return ethIf->beaconState;
  264. }
  265. struct ETHInterface* ETHInterface_new(struct EventBase* base,
  266. const char* bindDevice,
  267. struct Allocator* allocator,
  268. struct Except* exHandler,
  269. struct Log* logger,
  270. struct InterfaceController* ic)
  271. {
  272. struct ETHInterface* context = Allocator_clone(allocator, (&(struct ETHInterface) {
  273. .generic = {
  274. .sendMessage = sendMessage,
  275. .allocator = allocator
  276. },
  277. .logger = logger,
  278. .ic = ic,
  279. .id = getpid()
  280. }));
  281. Identity_set(context);
  282. struct ifreq ifr = { .ifr_ifindex = 0 };
  283. context->socket = socket(AF_PACKET, SOCK_DGRAM, Ethernet_TYPE_CJDNS);
  284. if (context->socket == -1) {
  285. Except_throw(exHandler, "call to socket() failed. [%s]", strerror(errno));
  286. }
  287. CString_strncpy(ifr.ifr_name, bindDevice, IFNAMSIZ - 1);
  288. if (ioctl(context->socket, SIOCGIFINDEX, &ifr) == -1) {
  289. Except_throw(exHandler, "failed to find interface index [%s]", strerror(errno));
  290. }
  291. context->ifindex = ifr.ifr_ifindex;
  292. if (ioctl(context->socket, SIOCGIFHWADDR, &ifr) == -1) {
  293. Except_throw(exHandler, "failed to find mac address of interface [%s]",
  294. strerror(errno));
  295. }
  296. uint8_t srcMac[6];
  297. Bits_memcpyConst(srcMac, ifr.ifr_hwaddr.sa_data, 6);
  298. // TODO(cjd): 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. }