ETHInterface_darwin.c 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323
  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. Socket socket;
  51. struct Log* logger;
  52. uint8_t myMac[6];
  53. String* ifName;
  54. uint8_t* buffer;
  55. int bufLen;
  56. Identity
  57. };
  58. static Iface_DEFUN sendMessage(struct Message* msg, struct Iface* iface)
  59. {
  60. struct ETHInterface_pvt* ctx =
  61. Identity_containerOf(iface, struct ETHInterface_pvt, pub.generic.iface);
  62. struct Sockaddr* sa = (struct Sockaddr*) msg->bytes;
  63. Assert_true(msg->length >= Sockaddr_OVERHEAD);
  64. Assert_true(sa->addrLen <= ETHInterface_Sockaddr_SIZE);
  65. struct ETHInterface_Sockaddr sockaddr = { .generic = { .addrLen = 0 } };
  66. Message_pop(msg, &sockaddr, sa->addrLen, NULL);
  67. struct ETHInterface_Header hdr = {
  68. .version = ETHInterface_CURRENT_VERSION,
  69. .zero = 0,
  70. .length_be = Endian_hostToBigEndian16(msg->length + ETHInterface_Header_SIZE),
  71. .fc00_be = Endian_hostToBigEndian16(0xfc00)
  72. };
  73. Message_push(msg, &hdr, ETHInterface_Header_SIZE, NULL);
  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. Message_push(msg, &ethFr, ethernet_frame_SIZE, NULL);
  84. /*
  85. struct bpf_hdr bpfPkt = {
  86. .bh_caplen = msg->length,
  87. .bh_datalen = msg->length,
  88. .bh_hdrlen = BPF_WORDALIGN(sizeof(struct bpf_hdr))
  89. };
  90. Message_push(msg, &bpfPkt, bpfPkt.bh_hdrlen, NULL);
  91. */
  92. if (msg->length != write(ctx->socket, msg->bytes, msg->length)) {
  93. Log_debug(ctx->logger, "Error writing to eth device [%s]", strerror(errno));
  94. }
  95. Log_debug(ctx->logger, "message sent");
  96. return NULL;
  97. }
  98. static void handleEvent2(struct ETHInterface_pvt* context,
  99. uint8_t src[6],
  100. uint8_t dst[6],
  101. int length,
  102. uint8_t* data,
  103. struct Allocator* alloc)
  104. {
  105. if (length < ETHInterface_Header_SIZE) {
  106. Log_debug(context->logger, "runt");
  107. return;
  108. }
  109. uint32_t contentLength = BPF_WORDALIGN(length - ETHInterface_Header_SIZE);
  110. struct Message* msg = Message_new(contentLength, PADDING, alloc);
  111. struct ETHInterface_Header hdr;
  112. Bits_memcpy(&hdr, data, ETHInterface_Header_SIZE);
  113. Bits_memcpy(msg->bytes, &data[ETHInterface_Header_SIZE], contentLength);
  114. // here we could put a switch statement to handle different versions differently.
  115. if (hdr.version != ETHInterface_CURRENT_VERSION) {
  116. Log_debug(context->logger, "DROP unknown version");
  117. return;
  118. }
  119. uint16_t reportedLength = Endian_bigEndianToHost16(hdr.length_be);
  120. reportedLength -= ETHInterface_Header_SIZE;
  121. if (msg->length != reportedLength) {
  122. if (msg->length < reportedLength) {
  123. Log_debug(context->logger, "DROP size field is larger than frame");
  124. return;
  125. }
  126. msg->length = reportedLength;
  127. }
  128. if (hdr.fc00_be != Endian_hostToBigEndian16(0xfc00)) {
  129. Log_debug(context->logger, "DROP bad magic");
  130. return;
  131. }
  132. struct ETHInterface_Sockaddr sockaddr = { .zero = 0 };
  133. Bits_memcpy(sockaddr.mac, src, 6);
  134. sockaddr.generic.addrLen = ETHInterface_Sockaddr_SIZE;
  135. if (dst[0] == 0xff) {
  136. sockaddr.generic.flags |= Sockaddr_flags_BCAST;
  137. }
  138. Message_push(msg, &sockaddr, ETHInterface_Sockaddr_SIZE, NULL);
  139. Assert_true(!((uintptr_t)msg->bytes % 4) && "Alignment fault");
  140. Iface_send(&context->pub.generic.iface, msg);
  141. }
  142. static void handleEvent(void* vcontext)
  143. {
  144. struct ETHInterface_pvt* context = Identity_check((struct ETHInterface_pvt*) vcontext);
  145. ssize_t bytes = read(context->socket, context->buffer, context->bufLen);
  146. if (bytes < 0) {
  147. Log_debug(context->logger, "read(bpf, bpf_buf, buf_len) -> [%s]", strerror(errno));
  148. }
  149. if (bytes < 1) { return; }
  150. if (bytes < (ssize_t)sizeof(struct bpf_hdr)) {
  151. Log_debug(context->logger, "runt [%lld]", (long long) bytes);
  152. return;
  153. }
  154. int offset = 0;
  155. while (offset < bytes) {
  156. struct bpf_hdr* bpfPkt = (struct bpf_hdr*) &context->buffer[offset];
  157. struct ethernet_frame* ethFr =
  158. (struct ethernet_frame*) &context->buffer[offset + bpfPkt->bh_hdrlen];
  159. int frameLength = bpfPkt->bh_datalen;
  160. uint8_t* frameContent =
  161. (uint8_t*) &context->buffer[offset + bpfPkt->bh_hdrlen + ethernet_frame_SIZE];
  162. int contentLength = frameLength - ethernet_frame_SIZE;
  163. Assert_true(offset + bpfPkt->bh_hdrlen + frameLength <= bytes);
  164. Assert_true(Ethernet_TYPE_CJDNS == ethFr->type);
  165. struct Allocator* messageAlloc = Allocator_child(context->pub.generic.alloc);
  166. handleEvent2(context, ethFr->src, ethFr->dest, contentLength, frameContent, messageAlloc);
  167. Allocator_free(messageAlloc);
  168. offset += BPF_WORDALIGN(bpfPkt->bh_hdrlen + bpfPkt->bh_caplen);
  169. }
  170. }
  171. List* ETHInterface_listDevices(struct Allocator* alloc, struct Except* eh)
  172. {
  173. List* out = List_new(alloc);
  174. struct ifaddrs* ifaddr = NULL;
  175. if (getifaddrs(&ifaddr) || ifaddr == NULL) {
  176. Except_throw(eh, "getifaddrs() -> errno:%d [%s]", errno, strerror(errno));
  177. }
  178. for (struct ifaddrs* ifa = ifaddr; ifa; ifa = ifa->ifa_next) {
  179. if (!ifa->ifa_addr) {
  180. } else if (ifa->ifa_addr->sa_family != AF_LINK) {
  181. } else if (!(ifa->ifa_flags & IFF_UP)) {
  182. } else if (ifa->ifa_flags & IFF_LOOPBACK) {
  183. } else {
  184. List_addString(out, String_new(ifa->ifa_name, alloc), alloc);
  185. }
  186. }
  187. freeifaddrs(ifaddr);
  188. return out;
  189. }
  190. static int closeSocket(struct Allocator_OnFreeJob* j)
  191. {
  192. struct ETHInterface_pvt* ctx = Identity_check((struct ETHInterface_pvt*) j->userData);
  193. close(ctx->socket);
  194. return 0;
  195. }
  196. static int openBPF(struct Except* eh)
  197. {
  198. for (int retry = 0; retry < 100; retry++) {
  199. for (int i = 0; i < 256; i++) {
  200. char buf[11] = { 0 };
  201. snprintf(buf, 10, "/dev/bpf%i", i);
  202. int bpf = open(buf, O_RDWR);
  203. if (bpf != -1) { return bpf; }
  204. }
  205. // sleep for 0.1 seconds
  206. usleep(1000 * 100);
  207. }
  208. Except_throw(eh, "Could not find available /dev/bpf device");
  209. }
  210. static void macaddr(const char* ifname, uint8_t addrOut[6], struct Except* eh)
  211. {
  212. struct ifaddrs* ifa;
  213. if (getifaddrs(&ifa)) {
  214. Except_throw(eh, "getifaddrs() -> [%s]", strerror(errno));
  215. } else {
  216. for (struct ifaddrs* ifap = ifa; ifap; ifap = ifap->ifa_next) {
  217. if (!strcmp(ifap->ifa_name, ifname) && ifap->ifa_addr->sa_family == AF_LINK) {
  218. Bits_memcpy(addrOut, LLADDR((struct sockaddr_dl*) ifap->ifa_addr), 6);
  219. freeifaddrs(ifa);
  220. return;
  221. }
  222. }
  223. }
  224. freeifaddrs(ifa);
  225. Except_throw(eh, "Could not find mac address for [%s]", ifname);
  226. }
  227. struct ETHInterface* ETHInterface_new(struct EventBase* eventBase,
  228. const char* bindDevice,
  229. struct Allocator* alloc,
  230. struct Except* exHandler,
  231. struct Log* logger)
  232. {
  233. struct ETHInterface_pvt* ctx = Allocator_calloc(alloc, sizeof(struct ETHInterface_pvt), 1);
  234. Identity_set(ctx);
  235. ctx->pub.generic.iface.send = sendMessage;
  236. ctx->pub.generic.alloc = alloc;
  237. ctx->logger = logger;
  238. ctx->socket = openBPF(exHandler);
  239. macaddr(bindDevice, ctx->myMac, exHandler);
  240. struct ifreq ifr = { .ifr_name = { 0 } };
  241. CString_strcpy(ifr.ifr_name, bindDevice);
  242. if (ioctl(ctx->socket, BIOCSETIF, &ifr) > 0) {
  243. Except_throw(exHandler, "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. Except_throw(exHandler, "ioctl(BIOCIMMEDIATE) [%s]", strerror(errno));
  249. }
  250. // request buffer length
  251. if (ioctl(ctx->socket, BIOCGBLEN, &bufLen) == -1) {
  252. Except_throw(exHandler, "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. Except_throw(exHandler, "ioctl(BIOCSETF) [%s]", strerror(errno));
  272. }
  273. Socket_makeNonBlocking(ctx->socket);
  274. Event_socketRead(handleEvent, ctx, ctx->socket, eventBase, alloc, exHandler);
  275. Allocator_onFree(alloc, closeSocket, ctx);
  276. return &ctx->pub;
  277. }