1 /* Copyright (c) 2008 The Board of Trustees of The Leland Stanford
4 * We are making the OpenFlow specification and associated documentation
5 * (Software) available for public use and benefit with the expectation
6 * that others will use, modify and enhance the Software and contribute
7 * those enhancements back to the community. However, since we would
8 * like to make the Software available for broadest use, with as few
9 * restrictions as possible permission is hereby granted, free of
10 * charge, to any person obtaining a copy of this Software to deal in
11 * the Software under the copyrights without restriction, including
12 * without limitation the rights to use, copy, modify, merge, publish,
13 * distribute, sublicense, and/or sell copies of the Software, and to
14 * permit persons to whom the Software is furnished to do so, subject to
15 * the following conditions:
17 * The above copyright notice and this permission notice shall be
18 * included in all copies or substantial portions of the Software.
20 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
21 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
22 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
23 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
24 * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
25 * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
26 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
29 * The name and trademarks of copyright holder(s) may NOT be used in
30 * advertising or publicity pertaining to the Software or any
31 * derivatives without specific, written prior permission.
38 #include <arpa/inet.h>
40 #include <linux/types.h>
41 #include <linux/ethtool.h>
42 #include <linux/sockios.h>
43 #include <sys/types.h>
44 #include <sys/ioctl.h>
45 #include <sys/socket.h>
46 #include <netpacket/packet.h>
47 #include <net/ethernet.h>
49 #include <net/if_arp.h>
50 #include <net/if_packet.h>
51 #include <net/route.h>
52 #include <netinet/in.h>
58 #include "fatal-signal.h"
62 #include "poll-loop.h"
63 #include "socket-util.h"
65 #define THIS_MODULE VLM_netdev
73 uint8_t etheraddr[ETH_ADDR_LEN];
79 int save_flags; /* Initial device flags. */
80 int changed_flags; /* Flags that we changed. */
83 static struct list netdev_list = LIST_INITIALIZER(&netdev_list);
85 /* An AF_INET socket (used for ioctl operations). */
86 static int af_inet_sock = -1;
88 static void init_netdev(void);
89 static int restore_flags(struct netdev *netdev);
90 static int get_flags(const struct netdev *, int *flagsp);
91 static int set_flags(struct netdev *, int flags);
93 /* Obtains the IPv4 address for 'name' into 'in4'. Returns true if
96 get_ipv4_address(const char *name, struct in_addr *in4)
100 strncpy(ifr.ifr_name, name, sizeof ifr.ifr_name);
101 ifr.ifr_addr.sa_family = AF_INET;
102 if (ioctl(af_inet_sock, SIOCGIFADDR, &ifr) == 0) {
103 struct sockaddr_in *sin = (struct sockaddr_in *) &ifr.ifr_addr;
104 *in4 = sin->sin_addr;
106 in4->s_addr = INADDR_ANY;
112 /* Obtains the IPv6 address for 'name' into 'in6'. */
114 get_ipv6_address(const char *name, struct in6_addr *in6)
119 file = fopen("/proc/net/if_inet6", "r");
121 /* This most likely indicates that the host doesn't have IPv6 support,
122 * so it's not really a failure condition.*/
127 while (fgets(line, sizeof line, file)) {
128 uint8_t *s6 = in6->s6_addr;
132 if (sscanf(line, " "X8 X8 X8 X8 X8 X8 X8 X8 X8 X8 X8 X8 X8 X8 X8 X8
133 "%*x %*x %*x %*x %16s\n",
134 &s6[0], &s6[1], &s6[2], &s6[3],
135 &s6[4], &s6[5], &s6[6], &s6[7],
136 &s6[8], &s6[9], &s6[10], &s6[11],
137 &s6[12], &s6[13], &s6[14], &s6[15],
139 && !strcmp(name, ifname))
150 do_ethtool(struct netdev *netdev)
153 struct ethtool_cmd ecmd;
156 netdev->features = 0;
158 memset(&ifr, 0, sizeof ifr);
159 strncpy(ifr.ifr_name, netdev->name, sizeof ifr.ifr_name);
160 ifr.ifr_data = (caddr_t) &ecmd;
162 memset(&ecmd, 0, sizeof ecmd);
163 ecmd.cmd = ETHTOOL_GSET;
164 if (ioctl(netdev->fd, SIOCETHTOOL, &ifr) == 0) {
165 if (ecmd.supported & SUPPORTED_10baseT_Half) {
166 netdev->features |= OFPPF_10MB_HD;
168 if (ecmd.supported & SUPPORTED_10baseT_Full) {
169 netdev->features |= OFPPF_10MB_FD;
171 if (ecmd.supported & SUPPORTED_100baseT_Half) {
172 netdev->features |= OFPPF_100MB_HD;
174 if (ecmd.supported & SUPPORTED_100baseT_Full) {
175 netdev->features |= OFPPF_100MB_FD;
177 if (ecmd.supported & SUPPORTED_1000baseT_Half) {
178 netdev->features |= OFPPF_1GB_HD;
180 if (ecmd.supported & SUPPORTED_1000baseT_Full) {
181 netdev->features |= OFPPF_1GB_FD;
183 /* 10Gbps half-duplex doesn't exist... */
184 if (ecmd.supported & SUPPORTED_10000baseT_Full) {
185 netdev->features |= OFPPF_10GB_FD;
188 switch (ecmd.speed) {
198 netdev->speed = 1000;
202 netdev->speed = 2500;
206 netdev->speed = 10000;
210 VLOG_DBG("ioctl(SIOCETHTOOL) failed: %s", strerror(errno));
214 /* Opens the network device named 'name' (e.g. "eth0") and returns zero if
215 * successful, otherwise a positive errno value. On success, sets '*netdev'
216 * to the new network device, otherwise to null.
218 * 'ethertype' may be a 16-bit Ethernet protocol value in host byte order to
219 * capture frames of that type received on the device. It may also be one of
220 * the 'enum netdev_pseudo_ethertype' values to receive frames in one of those
223 netdev_open(const char *name, int ethertype, struct netdev **netdev_)
226 struct sockaddr_ll sll;
228 unsigned int ifindex;
229 uint8_t etheraddr[ETH_ADDR_LEN];
234 struct netdev *netdev;
239 /* Create raw socket. */
240 fd = socket(PF_PACKET, SOCK_RAW,
241 htons(ethertype == NETDEV_ETH_TYPE_NONE ? 0
242 : ethertype == NETDEV_ETH_TYPE_ANY ? ETH_P_ALL
243 : ethertype == NETDEV_ETH_TYPE_802_2 ? ETH_P_802_2
249 /* Get ethernet device index. */
250 strncpy(ifr.ifr_name, name, sizeof ifr.ifr_name);
251 if (ioctl(fd, SIOCGIFINDEX, &ifr) < 0) {
252 VLOG_ERR("ioctl(SIOCGIFINDEX) on %s device failed: %s",
253 name, strerror(errno));
256 ifindex = ifr.ifr_ifindex;
258 /* Bind to specific ethernet device. */
259 memset(&sll, 0, sizeof sll);
260 sll.sll_family = AF_PACKET;
261 sll.sll_ifindex = ifindex;
262 if (bind(fd, (struct sockaddr *) &sll, sizeof sll) < 0) {
263 VLOG_ERR("bind to %s failed: %s", name, strerror(errno));
267 if (ethertype != NETDEV_ETH_TYPE_NONE) {
268 /* Between the socket() and bind() calls above, the socket receives all
269 * packets of the requested type on all system interfaces. We do not
270 * want to receive that data, but there is no way to avoid it. So we
271 * must now drain out the receive queue. */
272 error = drain_rcvbuf(fd);
278 /* Get MAC address. */
279 if (ioctl(fd, SIOCGIFHWADDR, &ifr) < 0) {
280 VLOG_ERR("ioctl(SIOCGIFHWADDR) on %s device failed: %s",
281 name, strerror(errno));
284 if (ifr.ifr_hwaddr.sa_family != AF_UNSPEC
285 && ifr.ifr_hwaddr.sa_family != ARPHRD_ETHER) {
286 VLOG_WARN("%s device has unknown hardware address family %d",
287 name, (int) ifr.ifr_hwaddr.sa_family);
289 memcpy(etheraddr, ifr.ifr_hwaddr.sa_data, sizeof etheraddr);
292 if (ioctl(fd, SIOCGIFMTU, &ifr) < 0) {
293 VLOG_ERR("ioctl(SIOCGIFMTU) on %s device failed: %s",
294 name, strerror(errno));
299 if (!get_ipv4_address(name, &in4)) {
302 get_ipv6_address(name, &in6);
304 /* Allocate network device. */
305 netdev = xmalloc(sizeof *netdev);
306 netdev->name = xstrdup(name);
307 netdev->ifindex = ifindex;
309 memcpy(netdev->etheraddr, etheraddr, sizeof etheraddr);
314 /* Get speed, features. */
317 /* Save flags to restore at close or exit. */
318 error = get_flags(netdev, &netdev->save_flags);
322 netdev->changed_flags = 0;
323 fatal_signal_block();
324 list_push_back(&netdev_list, &netdev->node);
325 fatal_signal_unblock();
338 /* Closes and destroys 'netdev'. */
340 netdev_close(struct netdev *netdev)
343 /* Bring down interface and drop promiscuous mode, if we brought up
344 * the interface or enabled promiscuous mode. */
346 fatal_signal_block();
347 error = restore_flags(netdev);
348 list_remove(&netdev->node);
349 fatal_signal_unblock();
351 VLOG_WARN("failed to restore network device flags on %s: %s",
352 netdev->name, strerror(error));
362 /* Pads 'buffer' out with zero-bytes to the minimum valid length of an
363 * Ethernet packet, if necessary. */
365 pad_to_minimum_length(struct buffer *buffer)
367 if (buffer->size < ETH_TOTAL_MIN) {
368 size_t shortage = ETH_TOTAL_MIN - buffer->size;
369 memset(buffer_put_uninit(buffer, shortage), 0, shortage);
373 /* Attempts to receive a packet from 'netdev' into 'buffer', which the caller
374 * must have initialized with sufficient room for the packet. The space
375 * required to receive any packet is ETH_HEADER_LEN bytes, plus VLAN_HEADER_LEN
376 * bytes, plus the device's MTU (which may be retrieved via netdev_get_mtu()).
377 * (Some devices do not allow for a VLAN header, in which case VLAN_HEADER_LEN
378 * need not be included.)
380 * If a packet is successfully retrieved, returns 0. In this case 'buffer' is
381 * guaranteed to contain at least ETH_TOTAL_MIN bytes. Otherwise, returns a
382 * positive errno value. Returns EAGAIN immediately if no packet is ready to
386 netdev_recv(struct netdev *netdev, struct buffer *buffer)
390 assert(buffer->size == 0);
391 assert(buffer_tailroom(buffer) >= ETH_TOTAL_MIN);
393 n_bytes = recv(netdev->fd,
394 buffer_tail(buffer), buffer_tailroom(buffer),
396 } while (n_bytes < 0 && errno == EINTR);
398 if (errno != EAGAIN) {
399 VLOG_WARN("error receiving Ethernet packet on %s: %s",
400 strerror(errno), netdev->name);
404 buffer->size += n_bytes;
406 /* When the kernel internally sends out an Ethernet frame on an
407 * interface, it gives us a copy *before* padding the frame to the
408 * minimum length. Thus, when it sends out something like an ARP
409 * request, we see a too-short frame. So pad it out to the minimum
411 pad_to_minimum_length(buffer);
416 /* Registers with the poll loop to wake up from the next call to poll_block()
417 * when a packet is ready to be received with netdev_recv() on 'netdev'. */
419 netdev_recv_wait(struct netdev *netdev)
421 poll_fd_wait(netdev->fd, POLLIN);
424 /* Discards all packets waiting to be received from 'netdev'. */
426 netdev_drain(struct netdev *netdev)
428 drain_rcvbuf(netdev->fd);
431 /* Sends 'buffer' on 'netdev'. Returns 0 if successful, otherwise a positive
432 * errno value. Returns EAGAIN without blocking if the packet cannot be queued
433 * immediately. Returns EMSGSIZE if a partial packet was transmitted or if
434 * the packet is too big or too small to transmit on the device.
436 * The caller retains ownership of 'buffer' in all cases.
438 * The kernel maintains a packet transmission queue, so the caller is not
439 * expected to do additional queuing of packets. */
441 netdev_send(struct netdev *netdev, const struct buffer *buffer)
444 const struct eth_header *eh;
446 /* Pull out the Ethernet header. */
447 if (buffer->size < ETH_HEADER_LEN) {
448 VLOG_WARN("cannot send %zu-byte frame on %s",
449 buffer->size, netdev->name);
452 eh = buffer_at_assert(buffer, 0, sizeof *eh);
455 n_bytes = sendto(netdev->fd, buffer->data, buffer->size, 0, NULL, 0);
456 } while (n_bytes < 0 && errno == EINTR);
459 /* The Linux AF_PACKET implementation never blocks waiting for room
460 * for packets, instead returning ENOBUFS. Translate this into EAGAIN
462 if (errno == ENOBUFS) {
464 } else if (errno != EAGAIN) {
465 VLOG_WARN("error sending Ethernet packet on %s: %s",
466 netdev->name, strerror(errno));
469 } else if (n_bytes != buffer->size) {
470 VLOG_WARN("send partial Ethernet packet (%d bytes of %zu) on %s",
471 (int) n_bytes, buffer->size, netdev->name);
478 /* Registers with the poll loop to wake up from the next call to poll_block()
479 * when the packet transmission queue has sufficient room to transmit a packet
480 * with netdev_send().
482 * The kernel maintains a packet transmission queue, so the client is not
483 * expected to do additional queuing of packets. Thus, this function is
484 * unlikely to ever be used. It is included for completeness. */
486 netdev_send_wait(struct netdev *netdev)
488 poll_fd_wait(netdev->fd, POLLOUT);
491 /* Returns a pointer to 'netdev''s MAC address. The caller must not modify or
492 * free the returned buffer. */
494 netdev_get_etheraddr(const struct netdev *netdev)
496 return netdev->etheraddr;
499 /* Returns the name of the network device that 'netdev' represents,
500 * e.g. "eth0". The caller must not modify or free the returned string. */
502 netdev_get_name(const struct netdev *netdev)
507 /* Returns the maximum size of transmitted (and received) packets on 'netdev',
508 * in bytes, not including the hardware header; thus, this is typically 1500
509 * bytes for Ethernet devices. */
511 netdev_get_mtu(const struct netdev *netdev)
516 /* Returns the current speed of the network device that 'netdev' represents, in
517 * megabits per second, or 0 if the speed is unknown. */
519 netdev_get_speed(const struct netdev *netdev)
521 return netdev->speed;
524 /* Returns the features supported by 'netdev', as a bitmap of bits from enum
525 * ofp_phy_port, in host byte order. */
527 netdev_get_features(const struct netdev *netdev)
529 return netdev->features;
532 /* If 'netdev' has an assigned IPv4 address, sets '*in4' to that address and
533 * returns true. Otherwise, returns false. */
535 netdev_get_in4(const struct netdev *netdev, struct in_addr *in4)
538 return in4->s_addr != INADDR_ANY;
542 make_in4_sockaddr(struct sockaddr *sa, struct in_addr addr)
544 struct sockaddr_in sin;
545 memset(&sin, 0, sizeof sin);
546 sin.sin_family = AF_INET;
550 memset(sa, 0, sizeof *sa);
551 memcpy(sa, &sin, sizeof sin);
555 do_set_addr(struct netdev *netdev, int sock,
556 int ioctl_nr, const char *ioctl_name, struct in_addr addr)
561 strncpy(ifr.ifr_name, netdev->name, sizeof ifr.ifr_name);
562 make_in4_sockaddr(&ifr.ifr_addr, addr);
563 error = ioctl(sock, ioctl_nr, &ifr) < 0 ? errno : 0;
565 VLOG_WARN("ioctl(%s): %s", ioctl_name, strerror(error));
570 /* Assigns 'addr' as 'netdev''s IPv4 address and 'mask' as its netmask. If
571 * 'addr' is INADDR_ANY, 'netdev''s IPv4 address is cleared. Returns a
572 * positive errno value. */
574 netdev_set_in4(struct netdev *netdev, struct in_addr addr, struct in_addr mask)
578 error = do_set_addr(netdev, af_inet_sock,
579 SIOCSIFADDR, "SIOCSIFADDR", addr);
582 if (addr.s_addr != INADDR_ANY) {
583 error = do_set_addr(netdev, af_inet_sock,
584 SIOCSIFNETMASK, "SIOCSIFNETMASK", mask);
590 /* Adds 'router' as a default gateway for 'netdev''s IP address. */
592 netdev_add_router(struct netdev *netdev, struct in_addr router)
594 struct in_addr any = { INADDR_ANY };
598 memset(&rt, 0, sizeof rt);
599 make_in4_sockaddr(&rt.rt_dst, any);
600 make_in4_sockaddr(&rt.rt_gateway, router);
601 make_in4_sockaddr(&rt.rt_genmask, any);
602 rt.rt_flags = RTF_UP | RTF_GATEWAY;
603 error = ioctl(af_inet_sock, SIOCADDRT, &rt) < 0 ? errno : 0;
605 VLOG_WARN("ioctl(SIOCADDRT): %s", strerror(error));
610 /* If 'netdev' has an assigned IPv6 address, sets '*in6' to that address and
611 * returns true. Otherwise, returns false. */
613 netdev_get_in6(const struct netdev *netdev, struct in6_addr *in6)
616 return memcmp(in6, &in6addr_any, sizeof *in6) != 0;
619 /* Obtains the current flags for 'netdev' and stores them into '*flagsp'.
620 * Returns 0 if successful, otherwise a positive errno value. */
622 netdev_get_flags(const struct netdev *netdev, enum netdev_flags *flagsp)
626 error = get_flags(netdev, &flags);
632 if (flags & IFF_UP) {
633 *flagsp |= NETDEV_UP;
635 if (flags & IFF_PROMISC) {
636 *flagsp |= NETDEV_PROMISC;
642 nd_to_iff_flags(enum netdev_flags nd)
645 if (nd & NETDEV_UP) {
648 if (nd & NETDEV_PROMISC) {
654 /* On 'netdev', turns off the flags in 'off' and then turns on the flags in
655 * 'on'. If 'permanent' is true, the changes will persist; otherwise, they
656 * will be reverted when 'netdev' is closed or the program exits. Returns 0 if
657 * successful, otherwise a positive errno value. */
659 do_update_flags(struct netdev *netdev, enum netdev_flags off,
660 enum netdev_flags on, bool permanent)
662 int old_flags, new_flags;
665 error = get_flags(netdev, &old_flags);
670 new_flags = (old_flags & ~nd_to_iff_flags(off)) | nd_to_iff_flags(on);
672 netdev->changed_flags |= new_flags ^ old_flags;
674 if (new_flags != old_flags) {
675 error = set_flags(netdev, new_flags);
680 /* Sets the flags for 'netdev' to 'flags'.
681 * If 'permanent' is true, the changes will persist; otherwise, they
682 * will be reverted when 'netdev' is closed or the program exits.
683 * Returns 0 if successful, otherwise a positive errno value. */
685 netdev_set_flags(struct netdev *netdev, enum netdev_flags flags,
688 return do_update_flags(netdev, -1, flags, permanent);
691 /* Turns on the specified 'flags' on 'netdev'.
692 * If 'permanent' is true, the changes will persist; otherwise, they
693 * will be reverted when 'netdev' is closed or the program exits.
694 * Returns 0 if successful, otherwise a positive errno value. */
696 netdev_turn_flags_on(struct netdev *netdev, enum netdev_flags flags,
699 return do_update_flags(netdev, 0, flags, permanent);
702 /* Turns off the specified 'flags' on 'netdev'.
703 * If 'permanent' is true, the changes will persist; otherwise, they
704 * will be reverted when 'netdev' is closed or the program exits.
705 * Returns 0 if successful, otherwise a positive errno value. */
707 netdev_turn_flags_off(struct netdev *netdev, enum netdev_flags flags,
710 return do_update_flags(netdev, flags, 0, permanent);
713 /* Looks up the ARP table entry for 'ip' on 'netdev'. If one exists and can be
714 * successfully retrieved, it stores the corresponding MAC address in 'mac' and
715 * returns 0. Otherwise, it returns a positive errno value; in particular,
716 * ENXIO indicates that there is not ARP table entry for 'ip' on 'netdev'. */
718 netdev_arp_lookup(const struct netdev *netdev,
719 uint32_t ip, uint8_t mac[ETH_ADDR_LEN])
722 struct sockaddr_in *pa;
725 memset(&r, 0, sizeof r);
726 pa = (struct sockaddr_in *) &r.arp_pa;
727 pa->sin_family = AF_INET;
728 pa->sin_addr.s_addr = ip;
730 r.arp_ha.sa_family = ARPHRD_ETHER;
732 strncpy(r.arp_dev, netdev->name, sizeof r.arp_dev);
733 retval = ioctl(af_inet_sock, SIOCGARP, &r) < 0 ? errno : 0;
735 memcpy(mac, r.arp_ha.sa_data, ETH_ADDR_LEN);
736 } else if (retval != ENXIO) {
737 VLOG_WARN("%s: could not look up ARP entry for "IP_FMT": %s",
738 netdev->name, IP_ARGS(&ip), strerror(retval));
743 static void restore_all_flags(void *aux);
745 /* Set up a signal hook to restore network device flags on program
753 fatal_signal_add_hook(restore_all_flags, NULL);
754 af_inet_sock = socket(AF_INET, SOCK_DGRAM, 0);
755 if (af_inet_sock < 0) {
756 fatal(errno, "socket(AF_INET)");
761 /* Restore the network device flags on 'netdev' to those that were active
762 * before we changed them. Returns 0 if successful, otherwise a positive
765 * To avoid reentry, the caller must ensure that fatal signals are blocked. */
767 restore_flags(struct netdev *netdev)
772 /* Get current flags. */
773 strncpy(ifr.ifr_name, netdev->name, sizeof ifr.ifr_name);
774 if (ioctl(netdev->fd, SIOCGIFFLAGS, &ifr) < 0) {
778 /* Restore flags that we might have changed, if necessary. */
779 restore_flags = netdev->changed_flags & (IFF_PROMISC | IFF_UP);
780 if ((ifr.ifr_flags ^ netdev->save_flags) & restore_flags) {
781 ifr.ifr_flags &= ~restore_flags;
782 ifr.ifr_flags |= netdev->save_flags & restore_flags;
783 if (ioctl(netdev->fd, SIOCSIFFLAGS, &ifr) < 0) {
791 /* Retores all the flags on all network devices that we modified. Called from
792 * a signal handler, so it does not attempt to report error conditions. */
794 restore_all_flags(void *aux UNUSED)
796 struct netdev *netdev;
797 LIST_FOR_EACH (netdev, struct netdev, node, &netdev_list) {
798 restore_flags(netdev);
803 get_flags(const struct netdev *netdev, int *flags)
806 strncpy(ifr.ifr_name, netdev->name, sizeof ifr.ifr_name);
807 if (ioctl(netdev->fd, SIOCGIFFLAGS, &ifr) < 0) {
808 VLOG_ERR("ioctl(SIOCGIFFLAGS) on %s device failed: %s",
809 netdev->name, strerror(errno));
812 *flags = ifr.ifr_flags;
817 set_flags(struct netdev *netdev, int flags)
820 strncpy(ifr.ifr_name, netdev->name, sizeof ifr.ifr_name);
821 ifr.ifr_flags = flags;
822 if (ioctl(netdev->fd, SIOCSIFFLAGS, &ifr) < 0) {
823 VLOG_ERR("ioctl(SIOCSIFFLAGS) on %s device failed: %s",
824 netdev->name, strerror(errno));