ETHInterface_darwin.c 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324
  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 <https://www.gnu.org/licenses/>.
  14. */
  15. #include "interface/ETHInterface.h"
  16. #include "exception/Except.h"
  17. #include "wire/Message.h"
  18. #include "wire/Ethernet.h"
  19. #include "util/Assert.h"
  20. #include "util/platform/Socket.h"
  21. #include "util/events/Event.h"
  22. #include "util/Identity.h"
  23. #include "util/version/Version.h"
  24. #include <ifaddrs.h>
  25. #include <string.h>
  26. #include <sys/socket.h>
  27. #include <sys/ioctl.h>
  28. #include <errno.h>
  29. #include <net/bpf.h>
  30. #include <unistd.h>
  31. #include <stdio.h>
  32. #include <fcntl.h>
  33. #include <net/if.h>
  34. #include <net/if_dl.h>
  35. #define MAX_PACKET_SIZE 1496
  36. #define MIN_PACKET_SIZE 46
  37. #define PADDING 512
  38. // single ethernet_frame
  39. struct ethernet_frame
  40. {
  41. uint8_t dest[6];
  42. uint8_t src[6];
  43. uint16_t type;
  44. } Gcc_PACKED;
  45. #define ethernet_frame_SIZE 14
  46. Assert_compileTime(ethernet_frame_SIZE == sizeof(struct ethernet_frame));
  47. struct ETHInterface_pvt
  48. {
  49. struct ETHInterface pub;
  50. int socket;
  51. Iface_t iface;
  52. struct Log* logger;
  53. uint8_t myMac[6];
  54. String* ifName;
  55. uint8_t* buffer;
  56. int bufLen;
  57. Identity
  58. };
  59. static Iface_DEFUN sendMessage(struct Message* msg, struct Iface* iface)
  60. {
  61. struct ETHInterface_pvt* ctx = Identity_containerOf(iface, struct ETHInterface_pvt, iface);
  62. struct Sockaddr* sa = (struct Sockaddr*) msg->msgbytes;
  63. Assert_true(Message_getLength(msg) >= Sockaddr_OVERHEAD);
  64. Assert_true(sa->addrLen <= ETHInterface_Sockaddr_SIZE);
  65. struct ETHInterface_Sockaddr sockaddr = { .generic = { .addrLen = 0 } };
  66. Er_assert(Message_epop(msg, &sockaddr, sa->addrLen));
  67. struct ETHInterface_Header hdr = {
  68. .version = ETHInterface_CURRENT_VERSION,
  69. .zero = 0,
  70. .length_be = Endian_hostToBigEndian16(Message_getLength(msg) + ETHInterface_Header_SIZE),
  71. .fc00_be = Endian_hostToBigEndian16(0xfc00)
  72. };
  73. Er_assert(Message_epush(msg, &hdr, ETHInterface_Header_SIZE));
  74. struct ethernet_frame ethFr = {
  75. .type = Ethernet_TYPE_CJDNS
  76. };
  77. if (sockaddr.generic.flags & Sockaddr_flags_BCAST) {
  78. Bits_memset(ethFr.dest, 0xff, 6);
  79. } else {
  80. Bits_memcpy(ethFr.dest, sockaddr.mac, 6);
  81. }
  82. Bits_memcpy(ethFr.src, ctx->myMac, 6);
  83. Er_assert(Message_epush(msg, &ethFr, ethernet_frame_SIZE));
  84. /*
  85. struct bpf_hdr bpfPkt = {
  86. .bh_caplen = Message_getLength(msg),
  87. .bh_datalen = Message_getLength(msg),
  88. .bh_hdrlen = BPF_WORDALIGN(sizeof(struct bpf_hdr))
  89. };
  90. Er_assert(Message_epush(msg, &bpfPkt, bpfPkt.bh_hdrlen));
  91. */
  92. if (Message_getLength(msg) != write(ctx->socket, msg->msgbytes, Message_getLength(msg))) {
  93. Log_debug(ctx->logger, "Error writing to eth device [%s]", strerror(errno));
  94. }
  95. return NULL;
  96. }
  97. static void handleEvent2(struct ETHInterface_pvt* context,
  98. uint8_t src[6],
  99. uint8_t dst[6],
  100. int length,
  101. uint8_t* data,
  102. struct Allocator* alloc)
  103. {
  104. if (length < ETHInterface_Header_SIZE) {
  105. Log_debug(context->logger, "runt");
  106. return;
  107. }
  108. uint32_t contentLength = BPF_WORDALIGN(length - ETHInterface_Header_SIZE);
  109. struct Message* msg = Message_new(contentLength, PADDING, alloc);
  110. struct ETHInterface_Header hdr;
  111. Bits_memcpy(&hdr, data, ETHInterface_Header_SIZE);
  112. Bits_memcpy(msg->msgbytes, &data[ETHInterface_Header_SIZE], contentLength);
  113. // here we could put a switch statement to handle different versions differently.
  114. if (hdr.version != ETHInterface_CURRENT_VERSION) {
  115. Log_debug(context->logger, "DROP unknown version");
  116. return;
  117. }
  118. uint16_t reportedLength = Endian_bigEndianToHost16(hdr.length_be);
  119. reportedLength -= ETHInterface_Header_SIZE;
  120. if (Message_getLength(msg) != reportedLength) {
  121. if (Message_getLength(msg) < reportedLength) {
  122. Log_debug(context->logger, "DROP size field is larger than frame");
  123. return;
  124. }
  125. Er_assert(Message_truncate(msg, reportedLength));
  126. }
  127. if (hdr.fc00_be != Endian_hostToBigEndian16(0xfc00)) {
  128. Log_debug(context->logger, "DROP bad magic");
  129. return;
  130. }
  131. struct ETHInterface_Sockaddr sockaddr = { .zero = 0 };
  132. Bits_memcpy(sockaddr.mac, src, 6);
  133. sockaddr.generic.addrLen = ETHInterface_Sockaddr_SIZE;
  134. if (dst[0] == 0xff) {
  135. sockaddr.generic.flags |= Sockaddr_flags_BCAST;
  136. }
  137. Er_assert(Message_epush(msg, &sockaddr, ETHInterface_Sockaddr_SIZE));
  138. Assert_true(!((uintptr_t)msg->msgbytes % 4) && "Alignment fault");
  139. Iface_send(context->pub.generic.iface, msg);
  140. }
  141. static void handleEvent(void* vcontext)
  142. {
  143. struct ETHInterface_pvt* context = Identity_check((struct ETHInterface_pvt*) vcontext);
  144. ssize_t bytes = read(context->socket, context->buffer, context->bufLen);
  145. if (bytes < 0) {
  146. Log_debug(context->logger, "read(bpf, bpf_buf, buf_len) -> [%s]", strerror(errno));
  147. }
  148. if (bytes < 1) { return; }
  149. if (bytes < (ssize_t)sizeof(struct bpf_hdr)) {
  150. Log_debug(context->logger, "runt [%lld]", (long long) bytes);
  151. return;
  152. }
  153. int offset = 0;
  154. while (offset < bytes) {
  155. struct bpf_hdr* bpfPkt = (struct bpf_hdr*) &context->buffer[offset];
  156. struct ethernet_frame* ethFr =
  157. (struct ethernet_frame*) &context->buffer[offset + bpfPkt->bh_hdrlen];
  158. int frameLength = bpfPkt->bh_datalen;
  159. uint8_t* frameContent =
  160. (uint8_t*) &context->buffer[offset + bpfPkt->bh_hdrlen + ethernet_frame_SIZE];
  161. int contentLength = frameLength - ethernet_frame_SIZE;
  162. Assert_true(offset + bpfPkt->bh_hdrlen + frameLength <= bytes);
  163. Assert_true(Ethernet_TYPE_CJDNS == ethFr->type);
  164. struct Allocator* messageAlloc = Allocator_child(context->pub.generic.alloc);
  165. handleEvent2(context, ethFr->src, ethFr->dest, contentLength, frameContent, messageAlloc);
  166. Allocator_free(messageAlloc);
  167. offset += BPF_WORDALIGN(bpfPkt->bh_hdrlen + bpfPkt->bh_caplen);
  168. }
  169. }
  170. Er_DEFUN(List* ETHInterface_listDevices(struct Allocator* alloc))
  171. {
  172. List* out = List_new(alloc);
  173. struct ifaddrs* ifaddr = NULL;
  174. if (getifaddrs(&ifaddr) || ifaddr == NULL) {
  175. Er_raise(alloc, "getifaddrs() -> errno:%d [%s]", errno, strerror(errno));
  176. }
  177. for (struct ifaddrs* ifa = ifaddr; ifa; ifa = ifa->ifa_next) {
  178. if (!ifa->ifa_addr) {
  179. } else if (ifa->ifa_addr->sa_family != AF_LINK) {
  180. } else if (!(ifa->ifa_flags & IFF_UP)) {
  181. } else if (ifa->ifa_flags & IFF_LOOPBACK) {
  182. } else {
  183. List_addString(out, String_new(ifa->ifa_name, alloc), alloc);
  184. }
  185. }
  186. freeifaddrs(ifaddr);
  187. Er_ret(out);
  188. }
  189. static int closeSocket(struct Allocator_OnFreeJob* j)
  190. {
  191. struct ETHInterface_pvt* ctx = Identity_check((struct ETHInterface_pvt*) j->userData);
  192. close(ctx->socket);
  193. return 0;
  194. }
  195. static Er_DEFUN(int openBPF(struct Allocator* alloc))
  196. {
  197. for (int retry = 0; retry < 100; retry++) {
  198. for (int i = 0; i < 256; i++) {
  199. char buf[21] = { 0 };
  200. snprintf(buf, 20, "/dev/bpf%i", i);
  201. int bpf = open(buf, O_RDWR);
  202. if (bpf != -1) { Er_ret(bpf); }
  203. }
  204. // sleep for 0.1 seconds
  205. usleep(1000 * 100);
  206. }
  207. Er_raise(alloc, "Could not find available /dev/bpf device");
  208. }
  209. static Er_DEFUN(void macaddr(const char* ifname, uint8_t addrOut[6], struct Allocator* alloc))
  210. {
  211. struct ifaddrs* ifa;
  212. if (getifaddrs(&ifa)) {
  213. Er_raise(alloc, "getifaddrs() -> [%s]", strerror(errno));
  214. } else {
  215. for (struct ifaddrs* ifap = ifa; ifap; ifap = ifap->ifa_next) {
  216. if (!strcmp(ifap->ifa_name, ifname) && ifap->ifa_addr->sa_family == AF_LINK) {
  217. Bits_memcpy(addrOut, LLADDR((struct sockaddr_dl*) ifap->ifa_addr), 6);
  218. freeifaddrs(ifa);
  219. Er_ret();
  220. }
  221. }
  222. }
  223. freeifaddrs(ifa);
  224. Er_raise(alloc, "Could not find mac address for [%s]", ifname);
  225. Er_ret();
  226. }
  227. Er_DEFUN(struct ETHInterface* ETHInterface_new(struct EventBase* eventBase,
  228. const char* bindDevice,
  229. struct Allocator* alloc,
  230. struct Log* logger))
  231. {
  232. struct ETHInterface_pvt* ctx = Allocator_calloc(alloc, sizeof(struct ETHInterface_pvt), 1);
  233. Identity_set(ctx);
  234. ctx->iface.send = sendMessage;
  235. ctx->pub.generic.iface = &ctx->iface;
  236. ctx->pub.generic.alloc = alloc;
  237. ctx->logger = logger;
  238. ctx->socket = Er(openBPF(alloc));
  239. Er(macaddr(bindDevice, ctx->myMac, alloc));
  240. struct ifreq ifr = { .ifr_name = { 0 } };
  241. CString_strcpy(ifr.ifr_name, bindDevice);
  242. if (ioctl(ctx->socket, BIOCSETIF, &ifr) > 0) {
  243. Er_raise(alloc, "ioctl(BIOCSETIF, [%s]) [%s]", bindDevice, strerror(errno));
  244. }
  245. // activate immediate mode (therefore, bufLen is initially set to "1")
  246. int bufLen = 1;
  247. if (ioctl(ctx->socket, BIOCIMMEDIATE, &bufLen) == -1) {
  248. Er_raise(alloc, "ioctl(BIOCIMMEDIATE) [%s]", strerror(errno));
  249. }
  250. // request buffer length
  251. if (ioctl(ctx->socket, BIOCGBLEN, &bufLen) == -1) {
  252. Er_raise(alloc, "ioctl(BIOCGBLEN) [%s]", strerror(errno));
  253. }
  254. Log_debug(logger, "ioctl(BIOCGBLEN) -> bufLen=%i", bufLen);
  255. ctx->buffer = Allocator_malloc(alloc, bufLen);
  256. ctx->bufLen = bufLen;
  257. // filter for cjdns ethertype (0xfc00)
  258. static struct bpf_insn cjdnsFilter[] = {
  259. BPF_STMT(BPF_LD+BPF_H+BPF_ABS, 12),
  260. BPF_JUMP(BPF_JMP+BPF_JEQ+BPF_K, /* Ethernet_TYPE_CJDNS */ 0xfc00, 1, 0),
  261. // drop
  262. BPF_STMT(BPF_RET+BPF_K, 0),
  263. // How much of the packet to ask for...
  264. BPF_STMT(BPF_RET+BPF_K, ~0u)
  265. };
  266. struct bpf_program cjdnsFilterProgram = {
  267. .bf_len = (sizeof(cjdnsFilter) / sizeof(struct bpf_insn)),
  268. .bf_insns = cjdnsFilter,
  269. };
  270. if (ioctl(ctx->socket, BIOCSETF, &cjdnsFilterProgram) == -1) {
  271. Er_raise(alloc, "ioctl(BIOCSETF) [%s]", strerror(errno));
  272. }
  273. Socket_makeNonBlocking(ctx->socket);
  274. Event_socketRead(handleEvent, ctx, ctx->socket, eventBase, alloc);
  275. Allocator_onFree(alloc, closeSocket, ctx);
  276. Er_ret(&ctx->pub);
  277. }