ETHInterface_linux.c 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308
  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 "memory/Allocator.h"
  18. #include "net/InterfaceController.h"
  19. #include "wire/Headers.h"
  20. #include "wire/Message.h"
  21. #include "wire/Error.h"
  22. #include "wire/Ethernet.h"
  23. #include "util/Assert.h"
  24. #include "util/platform/Socket.h"
  25. #include "util/events/Event.h"
  26. #include "util/Identity.h"
  27. #include "util/AddrTools.h"
  28. #include "util/version/Version.h"
  29. #include "util/events/Timeout.h"
  30. #include "util/events/Time.h"
  31. #include <string.h>
  32. #include <sys/socket.h>
  33. #include <linux/if_packet.h>
  34. #include <linux/if_ether.h>
  35. #include <linux/if_arp.h>
  36. #include <sys/types.h>
  37. #include <sys/ioctl.h>
  38. #include <unistd.h>
  39. #include <errno.h>
  40. #ifndef android
  41. #include <ifaddrs.h>
  42. #endif
  43. #define MAX_PACKET_SIZE 1496
  44. #define MIN_PACKET_SIZE 46
  45. #define PADDING 512
  46. // 2 last 0x00 of .sll_addr are removed from original size (20)
  47. #define SOCKADDR_LL_LEN 18
  48. struct ETHInterface_pvt
  49. {
  50. struct ETHInterface pub;
  51. Socket socket;
  52. /** The unix interface index which is used to identify the eth device. */
  53. int ifindex;
  54. struct Log* logger;
  55. struct sockaddr_ll addrBase;
  56. String* ifName;
  57. bool timestampPackets;
  58. Identity
  59. };
  60. static void sendMessageInternal(struct Message* message,
  61. struct sockaddr_ll* addr,
  62. struct ETHInterface_pvt* context)
  63. {
  64. /* Cut down on the noise
  65. uint8_t buff[sizeof(*addr) * 2 + 1] = {0};
  66. Hex_encode(buff, sizeof(buff), (uint8_t*)addr, sizeof(*addr));
  67. Log_debug(context->logger, "Sending ethernet frame to [%s]", buff);
  68. */
  69. if (sendto(context->socket,
  70. message->bytes,
  71. message->length,
  72. 0,
  73. (struct sockaddr*) addr,
  74. sizeof(struct sockaddr_ll)) < 0)
  75. {
  76. switch (errno) {
  77. default:;
  78. Log_info(context->logger, "[%s] Got error sending to socket [%s]",
  79. context->ifName->bytes, strerror(errno));
  80. case EMSGSIZE:
  81. case ENOBUFS:
  82. case EAGAIN:;
  83. // todo: care
  84. }
  85. }
  86. return;
  87. }
  88. static Iface_DEFUN sendMessage(struct Message* msg, struct Iface* iface)
  89. {
  90. struct ETHInterface_pvt* ctx =
  91. Identity_containerOf(iface, struct ETHInterface_pvt, pub.generic.iface);
  92. struct AddrIface_Header aihdr;
  93. Message_pop(msg, &aihdr, AddrIface_Header_SIZE, NULL);
  94. struct Sockaddr* sa = (struct Sockaddr*) &aihdr.addr;
  95. Assert_true(sa->addrLen <= ETHInterface_Sockaddr_SIZE);
  96. struct ETHInterface_Sockaddr* sockaddr = (struct ETHInterface_Sockaddr*) &aihdr.addr.addr;
  97. struct sockaddr_ll addr;
  98. Bits_memcpy(&addr, &ctx->addrBase, sizeof(struct sockaddr_ll));
  99. if (sockaddr->generic.flags & Sockaddr_flags_BCAST) {
  100. Bits_memset(addr.sll_addr, 0xff, 6);
  101. } else {
  102. Assert_true(sa->addrLen == ETHInterface_Sockaddr_SIZE);
  103. Bits_memcpy(addr.sll_addr, sockaddr->mac, 6);
  104. }
  105. struct ETHInterface_Header hdr = {
  106. .version = ETHInterface_CURRENT_VERSION,
  107. .zero = 0,
  108. .length_be = Endian_hostToBigEndian16(msg->length + ETHInterface_Header_SIZE),
  109. .fc00_be = Endian_hostToBigEndian16(0xfc00)
  110. };
  111. Message_push(msg, &hdr, ETHInterface_Header_SIZE, NULL);
  112. sendMessageInternal(msg, &addr, ctx);
  113. return NULL;
  114. }
  115. static void handleEvent2(struct ETHInterface_pvt* context, struct Allocator* messageAlloc)
  116. {
  117. struct Message* msg = Message_new(MAX_PACKET_SIZE, PADDING, messageAlloc);
  118. struct sockaddr_ll addr;
  119. uint32_t addrLen = sizeof(struct sockaddr_ll);
  120. // Knock it out of alignment by 2 bytes so that it will be
  121. // aligned when the idAndPadding is shifted off.
  122. Message_shift(msg, 2, NULL);
  123. int rc = recvfrom(context->socket,
  124. msg->bytes,
  125. msg->length,
  126. 0,
  127. (struct sockaddr*) &addr,
  128. &addrLen);
  129. if (rc < ETHInterface_Header_SIZE) {
  130. Log_debug(context->logger, "Failed to receive eth frame");
  131. return;
  132. }
  133. Assert_true(msg->length >= rc);
  134. msg->length = rc;
  135. //Assert_true(addrLen == SOCKADDR_LL_LEN);
  136. struct ETHInterface_Header hdr;
  137. Message_pop(msg, &hdr, ETHInterface_Header_SIZE, NULL);
  138. // here we could put a switch statement to handle different versions differently.
  139. if (hdr.version != ETHInterface_CURRENT_VERSION) {
  140. Log_debug(context->logger, "DROP unknown version");
  141. return;
  142. }
  143. uint16_t reportedLength = Endian_bigEndianToHost16(hdr.length_be);
  144. reportedLength -= ETHInterface_Header_SIZE;
  145. if (msg->length != reportedLength) {
  146. if (msg->length < reportedLength) {
  147. Log_debug(context->logger, "DROP size field is larger than frame");
  148. return;
  149. }
  150. msg->length = reportedLength;
  151. }
  152. if (hdr.fc00_be != Endian_hostToBigEndian16(0xfc00)) {
  153. Log_debug(context->logger, "DROP bad magic");
  154. return;
  155. }
  156. struct AddrIface_Header aihdr = { .recvTime_high = 0 };
  157. struct ETHInterface_Sockaddr* sockaddr = (struct ETHInterface_Sockaddr*) &aihdr.addr;
  158. Bits_memcpy(sockaddr->mac, addr.sll_addr, 6);
  159. sockaddr->generic.addrLen = ETHInterface_Sockaddr_SIZE;
  160. if (addr.sll_pkttype == PACKET_BROADCAST) {
  161. sockaddr->generic.flags |= Sockaddr_flags_BCAST;
  162. }
  163. if (context->timestampPackets) {
  164. uint64_t recvTime = Time_hrtime();
  165. aihdr.recvTime_high = recvTime >> 32;
  166. aihdr.recvTime_low = recvTime & 0xffffffff;
  167. }
  168. Message_push(msg, &aihdr, AddrIface_Header_SIZE, NULL);
  169. Assert_true(!((uintptr_t)msg->bytes % 4) && "Alignment fault");
  170. Iface_send(&context->pub.generic.iface, msg);
  171. }
  172. static void handleEvent(void* vcontext)
  173. {
  174. struct ETHInterface_pvt* context = Identity_check((struct ETHInterface_pvt*) vcontext);
  175. struct Allocator* messageAlloc = Allocator_child(context->pub.generic.alloc);
  176. handleEvent2(context, messageAlloc);
  177. Allocator_free(messageAlloc);
  178. }
  179. List* ETHInterface_listDevices(struct Allocator* alloc, struct Except* eh)
  180. {
  181. List* out = List_new(alloc);
  182. #ifndef android
  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 && ifa->ifa_addr->sa_family == AF_PACKET) {
  189. List_addString(out, String_new(ifa->ifa_name, alloc), alloc);
  190. }
  191. }
  192. freeifaddrs(ifaddr);
  193. #endif
  194. return out;
  195. }
  196. static int closeSocket(struct Allocator_OnFreeJob* j)
  197. {
  198. struct ETHInterface_pvt* ctx = Identity_check((struct ETHInterface_pvt*) j->userData);
  199. close(ctx->socket);
  200. return 0;
  201. }
  202. bool ETHInterface_timestampPackets(struct ETHInterface* iface, bool enable)
  203. {
  204. struct ETHInterface_pvt* context = Identity_check((struct ETHInterface_pvt*) iface);
  205. bool out = context->timestampPackets;
  206. context->timestampPackets = enable;
  207. return out;
  208. }
  209. struct ETHInterface* ETHInterface_new(struct EventBase* eventBase,
  210. const char* bindDevice,
  211. struct Allocator* alloc,
  212. struct Except* exHandler,
  213. struct Log* logger)
  214. {
  215. struct ETHInterface_pvt* ctx = Allocator_calloc(alloc, sizeof(struct ETHInterface_pvt), 1);
  216. Identity_set(ctx);
  217. ctx->pub.generic.iface.send = sendMessage;
  218. ctx->pub.generic.alloc = alloc;
  219. ctx->logger = logger;
  220. struct ifreq ifr = { .ifr_ifindex = 0 };
  221. ctx->socket = socket(AF_PACKET, SOCK_DGRAM, Ethernet_TYPE_CJDNS);
  222. if (ctx->socket == -1) {
  223. Except_throw(exHandler, "call to socket() failed. [%s]", strerror(errno));
  224. }
  225. Allocator_onFree(alloc, closeSocket, ctx);
  226. CString_strncpy(ifr.ifr_name, bindDevice, IFNAMSIZ - 1);
  227. ctx->ifName = String_new(bindDevice, alloc);
  228. if (ioctl(ctx->socket, SIOCGIFINDEX, &ifr) == -1) {
  229. Except_throw(exHandler, "failed to find interface index [%s]", strerror(errno));
  230. }
  231. ctx->ifindex = ifr.ifr_ifindex;
  232. if (ioctl(ctx->socket, SIOCGIFFLAGS, &ifr) < 0) {
  233. Except_throw(exHandler, "ioctl(SIOCGIFFLAGS) [%s]", strerror(errno));
  234. }
  235. if (!((ifr.ifr_flags & IFF_UP) && (ifr.ifr_flags & IFF_RUNNING))) {
  236. Log_info(logger, "Bringing up interface [%s]", ifr.ifr_name);
  237. ifr.ifr_flags |= IFF_UP | IFF_RUNNING;
  238. if (ioctl(ctx->socket, SIOCSIFFLAGS, &ifr) < 0) {
  239. Except_throw(exHandler, "ioctl(SIOCSIFFLAGS) [%s]", strerror(errno));
  240. }
  241. }
  242. ctx->addrBase = (struct sockaddr_ll) {
  243. .sll_family = AF_PACKET,
  244. .sll_protocol = Ethernet_TYPE_CJDNS,
  245. .sll_ifindex = ctx->ifindex,
  246. .sll_hatype = ARPHRD_ETHER,
  247. .sll_pkttype = PACKET_OTHERHOST,
  248. .sll_halen = ETH_ALEN
  249. };
  250. if (bind(ctx->socket, (struct sockaddr*) &ctx->addrBase, sizeof(struct sockaddr_ll))) {
  251. Except_throw(exHandler, "call to bind() failed [%s]", strerror(errno));
  252. }
  253. Socket_makeNonBlocking(ctx->socket);
  254. Event_socketRead(handleEvent, ctx, ctx->socket, eventBase, alloc, exHandler);
  255. return &ctx->pub;
  256. }