ETHInterface_darwin.c 11 KB

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