|
| 1 | +/* |
| 2 | + * raw socket based virtual network interface feature for LKL |
| 3 | + * Copyright (c) 2015,2016 Ryo Nakamura, Hajime Tazaki |
| 4 | + * |
| 5 | + * Author: Ryo Nakamura <upa@wide.ad.jp> |
| 6 | + * Hajime Tazaki <thehajime@gmail.com> |
| 7 | + * |
| 8 | + * Current implementation is linux-specific. |
| 9 | + */ |
| 10 | + |
| 11 | +#include <stdio.h> |
| 12 | +#include <errno.h> |
| 13 | +#include <string.h> |
| 14 | +#include <unistd.h> |
| 15 | +#include <net/if.h> |
| 16 | +#include <linux/if_ether.h> |
| 17 | +#include <linux/if_packet.h> |
| 18 | +#include <arpa/inet.h> |
| 19 | +#include <fcntl.h> |
| 20 | + |
| 21 | +#include "virtio.h" |
| 22 | +#include "virtio_net_linux_fdnet.h" |
| 23 | + |
| 24 | +/* since Linux 3.14 (man 7 packet) */ |
| 25 | +#ifndef PACKET_QDISC_BYPASS |
| 26 | +#define PACKET_QDISC_BYPASS 20 |
| 27 | +#endif |
| 28 | + |
| 29 | +struct lkl_netdev *lkl_netdev_raw_create(const char *ifname) |
| 30 | +{ |
| 31 | + struct lkl_netdev_linux_fdnet *nd; |
| 32 | + int ret; |
| 33 | + struct sockaddr_ll ll; |
| 34 | + int fd, fd_flags, val; |
| 35 | + |
| 36 | + fd = socket(PF_PACKET, SOCK_RAW, htons(ETH_P_ALL)); |
| 37 | + if (fd < 0) { |
| 38 | + perror("socket"); |
| 39 | + return NULL; |
| 40 | + } |
| 41 | + |
| 42 | + memset(&ll, 0, sizeof(ll)); |
| 43 | + ll.sll_family = PF_PACKET; |
| 44 | + ll.sll_ifindex = if_nametoindex(ifname); |
| 45 | + ll.sll_protocol = htons(ETH_P_ALL); |
| 46 | + ret = bind(fd, (struct sockaddr *)&ll, sizeof(ll)); |
| 47 | + if (ret) { |
| 48 | + perror("bind"); |
| 49 | + close(fd); |
| 50 | + return NULL; |
| 51 | + } |
| 52 | + |
| 53 | + val = 1; |
| 54 | + ret = setsockopt(fd, SOL_PACKET, PACKET_QDISC_BYPASS, &val, |
| 55 | + sizeof(val)); |
| 56 | + if (ret) |
| 57 | + perror("PACKET_QDISC_BYPASS, ignoring"); |
| 58 | + |
| 59 | + fd_flags = fcntl(fd, F_GETFD, NULL); |
| 60 | + fcntl(fd, F_SETFL, fd_flags | O_NONBLOCK); |
| 61 | + |
| 62 | + nd = lkl_register_netdev_linux_fdnet(fd); |
| 63 | + if (!nd) { |
| 64 | + perror("failed to register to."); |
| 65 | + return NULL; |
| 66 | + } |
| 67 | + |
| 68 | + return (struct lkl_netdev *)nd; |
| 69 | +} |
0 commit comments