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 <netinet/in.h>
57 #include "fatal-signal.h"
61 #include "poll-loop.h"
63 #define THIS_MODULE VLM_netdev
70 uint8_t etheraddr[ETH_ADDR_LEN];
79 static struct list netdev_list = LIST_INITIALIZER(&netdev_list);
81 /* An AF_INET socket (used for ioctl operations). */
82 static int af_inet_sock = -1;
84 static void init_netdev(void);
85 static int restore_flags(struct netdev *netdev);
86 static int get_flags(const struct netdev *, int *flagsp);
87 static int set_flags(struct netdev *, int flags);
89 /* Obtains the IPv4 address for 'name' into 'in4'. Returns true if
92 get_ipv4_address(const char *name, struct in_addr *in4)
96 strncpy(ifr.ifr_name, name, sizeof ifr.ifr_name);
97 ifr.ifr_addr.sa_family = AF_INET;
98 if (ioctl(af_inet_sock, SIOCGIFADDR, &ifr) == 0) {
99 struct sockaddr_in *sin = (struct sockaddr_in *) &ifr.ifr_addr;
100 *in4 = sin->sin_addr;
102 in4->s_addr = INADDR_ANY;
108 /* Obtains the IPv6 address for 'name' into 'in6'. */
110 get_ipv6_address(const char *name, struct in6_addr *in6)
115 file = fopen("/proc/net/if_inet6", "r");
117 /* This most likely indicates that the host doesn't have IPv6 support,
118 * so it's not really a failure condition.*/
123 while (fgets(line, sizeof line, file)) {
124 uint8_t *s6 = in6->s6_addr;
128 if (sscanf(line, " "X8 X8 X8 X8 X8 X8 X8 X8 X8 X8 X8 X8 X8 X8 X8 X8
129 "%*x %*x %*x %*x %16s\n",
130 &s6[0], &s6[1], &s6[2], &s6[3],
131 &s6[4], &s6[5], &s6[6], &s6[7],
132 &s6[8], &s6[9], &s6[10], &s6[11],
133 &s6[12], &s6[13], &s6[14], &s6[15],
135 && !strcmp(name, ifname))
146 do_ethtool(struct netdev *netdev)
149 struct ethtool_cmd ecmd;
152 netdev->features = 0;
154 memset(&ifr, 0, sizeof ifr);
155 strncpy(ifr.ifr_name, netdev->name, sizeof ifr.ifr_name);
156 ifr.ifr_data = (caddr_t) &ecmd;
158 memset(&ecmd, 0, sizeof ecmd);
159 ecmd.cmd = ETHTOOL_GSET;
160 if (ioctl(netdev->fd, SIOCETHTOOL, &ifr) == 0) {
161 if (ecmd.supported & SUPPORTED_10baseT_Half) {
162 netdev->features |= OFPPF_10MB_HD;
164 if (ecmd.supported & SUPPORTED_10baseT_Full) {
165 netdev->features |= OFPPF_10MB_FD;
167 if (ecmd.supported & SUPPORTED_100baseT_Half) {
168 netdev->features |= OFPPF_100MB_HD;
170 if (ecmd.supported & SUPPORTED_100baseT_Full) {
171 netdev->features |= OFPPF_100MB_FD;
173 if (ecmd.supported & SUPPORTED_1000baseT_Half) {
174 netdev->features |= OFPPF_1GB_HD;
176 if (ecmd.supported & SUPPORTED_1000baseT_Full) {
177 netdev->features |= OFPPF_1GB_FD;
179 /* 10Gbps half-duplex doesn't exist... */
180 if (ecmd.supported & SUPPORTED_10000baseT_Full) {
181 netdev->features |= OFPPF_10GB_FD;
184 switch (ecmd.speed) {
194 netdev->speed = 1000;
198 netdev->speed = 2500;
202 netdev->speed = 10000;
206 VLOG_DBG("ioctl(SIOCETHTOOL) failed: %s", strerror(errno));
210 /* Opens the network device named 'name' (e.g. "eth0") and returns zero if
211 * successful, otherwise a positive errno value. On success, sets '*netdev'
212 * to the new network device, otherwise to null.
214 * 'ethertype' may be a 16-bit Ethernet protocol value in host byte order to
215 * capture frames of that type received on the device. It may also be one of
216 * the 'enum netdev_pseudo_ethertype' values to receive frames in one of those
219 netdev_open(const char *name, int ethertype, struct netdev **netdev_)
224 unsigned int ifindex;
225 socklen_t rcvbuf_len;
227 uint8_t etheraddr[ETH_ADDR_LEN];
232 struct netdev *netdev;
237 /* Create raw socket.
239 * We have to use SOCK_PACKET, despite its deprecation, because only
240 * SOCK_PACKET lets us set the hardware source address of outgoing
242 fd = socket(PF_PACKET, SOCK_PACKET,
243 htons(ethertype == NETDEV_ETH_TYPE_NONE ? 0
244 : ethertype == NETDEV_ETH_TYPE_ANY ? ETH_P_ALL
245 : ethertype == NETDEV_ETH_TYPE_802_2 ? ETH_P_802_2
251 /* Bind to specific ethernet device. */
252 memset(&sa, 0, sizeof sa);
253 sa.sa_family = AF_UNSPEC;
254 strncpy((char *) sa.sa_data, name, sizeof sa.sa_data);
255 if (bind(fd, &sa, sizeof sa) < 0) {
256 VLOG_ERR("bind to %s failed: %s", name, strerror(errno));
260 /* Between the socket() and bind() calls above, the socket receives all
261 * packets on all system interfaces. We do not want to receive that
262 * data, but there is no way to avoid it. So we must now drain out the
263 * receive queue. There is no way to know how long the receive queue is,
264 * but we know that the total number of bytes queued does not exceed the
265 * receive buffer size, so we pull packets until none are left or we've
266 * read that many bytes. */
267 rcvbuf_len = sizeof rcvbuf;
268 if (getsockopt(fd, SOL_SOCKET, SO_RCVBUF, &rcvbuf, &rcvbuf_len) < 0) {
269 VLOG_ERR("getsockopt(SO_RCVBUF) on %s device failed: %s",
270 name, strerror(errno));
275 ssize_t n_bytes = recv(fd, &buffer, 1, MSG_TRUNC | MSG_DONTWAIT);
282 /* Get ethernet device index. */
283 strncpy(ifr.ifr_name, name, sizeof ifr.ifr_name);
284 if (ioctl(fd, SIOCGIFINDEX, &ifr) < 0) {
285 VLOG_ERR("ioctl(SIOCGIFINDEX) on %s device failed: %s",
286 name, strerror(errno));
289 ifindex = ifr.ifr_ifindex;
291 /* Get MAC address. */
292 if (ioctl(fd, SIOCGIFHWADDR, &ifr) < 0) {
293 VLOG_ERR("ioctl(SIOCGIFHWADDR) on %s device failed: %s",
294 name, strerror(errno));
297 if (ifr.ifr_hwaddr.sa_family != AF_UNSPEC
298 && ifr.ifr_hwaddr.sa_family != ARPHRD_ETHER) {
299 VLOG_WARN("%s device has unknown hardware address family %d",
300 name, (int) ifr.ifr_hwaddr.sa_family);
302 memcpy(etheraddr, ifr.ifr_hwaddr.sa_data, sizeof etheraddr);
305 if (ioctl(fd, SIOCGIFMTU, &ifr) < 0) {
306 VLOG_ERR("ioctl(SIOCGIFMTU) on %s device failed: %s",
307 name, strerror(errno));
312 if (!get_ipv4_address(name, &in4)) {
315 get_ipv6_address(name, &in6);
317 /* Allocate network device. */
318 netdev = xmalloc(sizeof *netdev);
319 netdev->name = xstrdup(name);
321 memcpy(netdev->etheraddr, etheraddr, sizeof etheraddr);
326 /* Get speed, features. */
329 /* Save flags to restore at close or exit. */
330 error = get_flags(netdev, &netdev->save_flags);
334 fatal_signal_block();
335 list_push_back(&netdev_list, &netdev->node);
336 fatal_signal_unblock();
349 /* Closes and destroys 'netdev'. */
351 netdev_close(struct netdev *netdev)
354 /* Bring down interface and drop promiscuous mode, if we brought up
355 * the interface or enabled promiscuous mode. */
357 fatal_signal_block();
358 error = restore_flags(netdev);
359 list_remove(&netdev->node);
360 fatal_signal_unblock();
362 VLOG_WARN("failed to restore network device flags on %s: %s",
363 netdev->name, strerror(error));
373 /* Pads 'buffer' out with zero-bytes to the minimum valid length of an
374 * Ethernet packet, if necessary. */
376 pad_to_minimum_length(struct buffer *buffer)
378 if (buffer->size < ETH_TOTAL_MIN) {
379 size_t shortage = ETH_TOTAL_MIN - buffer->size;
380 memset(buffer_put_uninit(buffer, shortage), 0, shortage);
384 /* Attempts to receive a packet from 'netdev' into 'buffer', which the caller
385 * must have initialized with sufficient room for the packet. The space
386 * required to receive any packet is ETH_HEADER_LEN bytes, plus VLAN_HEADER_LEN
387 * bytes, plus the device's MTU (which may be retrieved via netdev_get_mtu()).
388 * (Some devices do not allow for a VLAN header, in which case VLAN_HEADER_LEN
389 * need not be included.)
391 * If a packet is successfully retrieved, returns 0. In this case 'buffer' is
392 * guaranteed to contain at least ETH_TOTAL_MIN bytes. Otherwise, returns a
393 * positive errno value. Returns EAGAIN immediately if no packet is ready to
397 netdev_recv(struct netdev *netdev, struct buffer *buffer)
401 assert(buffer->size == 0);
402 assert(buffer_tailroom(buffer) >= ETH_TOTAL_MIN);
404 n_bytes = recv(netdev->fd,
405 buffer_tail(buffer), buffer_tailroom(buffer),
407 } while (n_bytes < 0 && errno == EINTR);
409 if (errno != EAGAIN) {
410 VLOG_WARN("error receiving Ethernet packet on %s: %s",
411 strerror(errno), netdev->name);
415 buffer->size += n_bytes;
417 /* When the kernel internally sends out an Ethernet frame on an
418 * interface, it gives us a copy *before* padding the frame to the
419 * minimum length. Thus, when it sends out something like an ARP
420 * request, we see a too-short frame. So pad it out to the minimum
422 pad_to_minimum_length(buffer);
427 /* Registers with the poll loop to wake up from the next call to poll_block()
428 * when a packet is ready to be received with netdev_recv() on 'netdev'. */
430 netdev_recv_wait(struct netdev *netdev)
432 poll_fd_wait(netdev->fd, POLLIN);
435 /* Sends 'buffer' on 'netdev'. Returns 0 if successful, otherwise a positive
436 * errno value. Returns EAGAIN without blocking if the packet cannot be queued
437 * immediately. Returns EMSGSIZE if a partial packet was transmitted or if
438 * the packet is too big or too small to transmit on the device.
440 * The caller retains ownership of 'buffer' in all cases.
442 * The kernel maintains a packet transmission queue, so the caller is not
443 * expected to do additional queuing of packets. */
445 netdev_send(struct netdev *netdev, const struct buffer *buffer)
448 const struct eth_header *eh;
449 struct sockaddr_pkt spkt;
451 /* Pull out the Ethernet header. */
452 if (buffer->size < ETH_HEADER_LEN) {
453 VLOG_WARN("cannot send %zu-byte frame on %s",
454 buffer->size, netdev->name);
457 eh = buffer_at_assert(buffer, 0, sizeof *eh);
459 /* Construct packet sockaddr, which SOCK_PACKET requires. */
460 spkt.spkt_family = AF_PACKET;
461 strncpy((char *) spkt.spkt_device, netdev->name, sizeof spkt.spkt_device);
462 spkt.spkt_protocol = eh->eth_type;
465 n_bytes = sendto(netdev->fd, buffer->data, buffer->size, 0,
466 (const struct sockaddr *) &spkt, sizeof spkt);
467 } while (n_bytes < 0 && errno == EINTR);
470 /* The Linux AF_PACKET implementation never blocks waiting for room
471 * for packets, instead returning ENOBUFS. Translate this into EAGAIN
473 if (errno == ENOBUFS) {
475 } else if (errno != EAGAIN) {
476 VLOG_WARN("error sending Ethernet packet on %s: %s",
477 netdev->name, strerror(errno));
480 } else if (n_bytes != buffer->size) {
481 VLOG_WARN("send partial Ethernet packet (%d bytes of %zu) on %s",
482 (int) n_bytes, buffer->size, netdev->name);
489 /* Registers with the poll loop to wake up from the next call to poll_block()
490 * when the packet transmission queue has sufficient room to transmit a packet
491 * with netdev_send().
493 * The kernel maintains a packet transmission queue, so the client is not
494 * expected to do additional queuing of packets. Thus, this function is
495 * unlikely to ever be used. It is included for completeness. */
497 netdev_send_wait(struct netdev *netdev)
499 poll_fd_wait(netdev->fd, POLLOUT);
502 /* Returns a pointer to 'netdev''s MAC address. The caller must not modify or
503 * free the returned buffer. */
505 netdev_get_etheraddr(const struct netdev *netdev)
507 return netdev->etheraddr;
510 /* Returns the name of the network device that 'netdev' represents,
511 * e.g. "eth0". The caller must not modify or free the returned string. */
513 netdev_get_name(const struct netdev *netdev)
518 /* Returns the maximum size of transmitted (and received) packets on 'netdev',
519 * in bytes, not including the hardware header; thus, this is typically 1500
520 * bytes for Ethernet devices. */
522 netdev_get_mtu(const struct netdev *netdev)
527 /* Returns the current speed of the network device that 'netdev' represents, in
528 * megabits per second, or 0 if the speed is unknown. */
530 netdev_get_speed(const struct netdev *netdev)
532 return netdev->speed;
535 /* Returns the features supported by 'netdev', as a bitmap of bits from enum
536 * ofp_phy_port, in host byte order. */
538 netdev_get_features(const struct netdev *netdev)
540 return netdev->features;
543 /* If 'netdev' has an assigned IPv4 address, sets '*in4' to that address and
544 * returns true. Otherwise, returns false. */
546 netdev_get_in4(const struct netdev *netdev, struct in_addr *in4)
549 return in4->s_addr != INADDR_ANY;
552 /* If 'netdev' has an assigned IPv6 address, sets '*in6' to that address and
553 * returns true. Otherwise, returns false. */
555 netdev_get_in6(const struct netdev *netdev, struct in6_addr *in6)
558 return memcmp(in6, &in6addr_any, sizeof *in6) != 0;
561 /* Obtains the current flags for 'netdev' and stores them into '*flagsp'.
562 * Returns 0 if successful, otherwise a positive errno value. */
564 netdev_get_flags(const struct netdev *netdev, enum netdev_flags *flagsp)
568 error = get_flags(netdev, &flags);
574 if (flags & IFF_UP) {
575 *flagsp |= NETDEV_UP;
577 if (flags & IFF_PROMISC) {
578 *flagsp |= NETDEV_PROMISC;
583 /* Sets the flags for 'netdev' to 'nd_flags'.
584 * Returns 0 if successful, otherwise a positive errno value. */
586 netdev_set_flags(struct netdev *netdev, enum netdev_flags nd_flags)
588 int old_flags, new_flags;
591 error = get_flags(netdev, &old_flags);
596 new_flags = old_flags & ~(IFF_UP | IFF_PROMISC);
597 if (nd_flags & NETDEV_UP) {
600 if (nd_flags & NETDEV_PROMISC) {
601 new_flags |= IFF_PROMISC;
603 if (new_flags != old_flags) {
604 error = set_flags(netdev, new_flags);
609 /* Looks up the ARP table entry for 'ip' on 'netdev'. If one exists and can be
610 * successfully retrieved, it stores the corresponding MAC address in 'mac' and
611 * returns 0. Otherwise, it returns a positive errno value; in particular,
612 * ENXIO indicates that there is not ARP table entry for 'ip' on 'netdev'. */
614 netdev_arp_lookup(const struct netdev *netdev,
615 uint32_t ip, uint8_t mac[ETH_ADDR_LEN])
618 struct sockaddr_in *pa;
621 memset(&r, 0, sizeof r);
622 pa = (struct sockaddr_in *) &r.arp_pa;
623 pa->sin_family = AF_INET;
624 pa->sin_addr.s_addr = ip;
626 r.arp_ha.sa_family = ARPHRD_ETHER;
628 strncpy(r.arp_dev, netdev->name, sizeof r.arp_dev);
629 retval = ioctl(af_inet_sock, SIOCGARP, &r) < 0 ? errno : 0;
631 memcpy(mac, r.arp_ha.sa_data, ETH_ADDR_LEN);
632 } else if (retval != ENXIO) {
633 VLOG_WARN("%s: could not look up ARP entry for "IP_FMT": %s",
634 netdev->name, IP_ARGS(&ip), strerror(retval));
639 static void restore_all_flags(void *aux);
641 /* Set up a signal hook to restore network device flags on program
649 fatal_signal_add_hook(restore_all_flags, NULL);
650 af_inet_sock = socket(AF_INET, SOCK_DGRAM, 0);
651 if (af_inet_sock < 0) {
652 fatal(errno, "socket(AF_INET)");
657 /* Restore the network device flags on 'netdev' to those that were active
658 * before we changed them. Returns 0 if successful, otherwise a positive
661 * To avoid reentry, the caller must ensure that fatal signals are blocked. */
663 restore_flags(struct netdev *netdev)
667 /* Get current flags. */
668 strncpy(ifr.ifr_name, netdev->name, sizeof ifr.ifr_name);
669 if (ioctl(netdev->fd, SIOCGIFFLAGS, &ifr) < 0) {
673 /* Restore flags that we might have changed, if necessary. */
674 if ((ifr.ifr_flags ^ netdev->save_flags) & (IFF_PROMISC | IFF_UP)) {
675 ifr.ifr_flags &= ~(IFF_PROMISC | IFF_UP);
676 ifr.ifr_flags |= netdev->save_flags & (IFF_PROMISC | IFF_UP);
677 if (ioctl(netdev->fd, SIOCSIFFLAGS, &ifr) < 0) {
685 /* Retores all the flags on all network devices that we modified. Called from
686 * a signal handler, so it does not attempt to report error conditions. */
688 restore_all_flags(void *aux UNUSED)
690 struct netdev *netdev;
691 LIST_FOR_EACH (netdev, struct netdev, node, &netdev_list) {
692 restore_flags(netdev);
697 get_flags(const struct netdev *netdev, int *flags)
700 strncpy(ifr.ifr_name, netdev->name, sizeof ifr.ifr_name);
701 if (ioctl(netdev->fd, SIOCGIFFLAGS, &ifr) < 0) {
702 VLOG_ERR("ioctl(SIOCGIFFLAGS) on %s device failed: %s",
703 netdev->name, strerror(errno));
706 *flags = ifr.ifr_flags;
711 set_flags(struct netdev *netdev, int flags)
714 strncpy(ifr.ifr_name, netdev->name, sizeof ifr.ifr_name);
715 ifr.ifr_flags = flags;
716 if (ioctl(netdev->fd, SIOCSIFFLAGS, &ifr) < 0) {
717 VLOG_ERR("ioctl(SIOCSIFFLAGS) on %s device failed: %s",
718 netdev->name, strerror(errno));