netdev: Add argument to netdev_open() to specify Ethernet type to capture.
[sliver-openvswitch.git] / lib / netdev.c
1 /* Copyright (c) 2008 The Board of Trustees of The Leland Stanford
2  * Junior University
3  * 
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:
16  * 
17  * The above copyright notice and this permission notice shall be
18  * included in all copies or substantial portions of the Software.
19  * 
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
27  * SOFTWARE.
28  * 
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.
32  */
33
34 #include "netdev.h"
35
36 #include <assert.h>
37 #include <errno.h>
38 #include <arpa/inet.h>
39 #include <inttypes.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>
48 #include <net/if.h>
49 #include <net/if_arp.h>
50 #include <net/if_packet.h>
51 #include <netinet/in.h>
52 #include <stdlib.h>
53 #include <string.h>
54 #include <unistd.h>
55
56 #include "list.h"
57 #include "fatal-signal.h"
58 #include "buffer.h"
59 #include "openflow.h"
60 #include "packets.h"
61 #include "poll-loop.h"
62
63 #define THIS_MODULE VLM_netdev
64 #include "vlog.h"
65
66 struct netdev {
67     struct list node;
68     char *name;
69     int fd;
70     uint8_t etheraddr[ETH_ADDR_LEN];
71     int speed;
72     int mtu;
73     uint32_t features;
74     struct in_addr in4;
75     struct in6_addr in6;
76     int save_flags;
77 };
78
79 static struct list netdev_list = LIST_INITIALIZER(&netdev_list);
80
81 /* An AF_INET socket (used for ioctl operations). */
82 static int af_inet_sock = -1;
83
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);
88
89 /* Obtains the IPv4 address for 'name' into 'in4'.  Returns true if
90  * successful. */
91 static bool
92 get_ipv4_address(const char *name, struct in_addr *in4)
93 {
94     struct ifreq ifr;
95
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;
101     } else {
102         in4->s_addr = INADDR_ANY;
103     }
104
105     return true;
106 }
107
108 /* Obtains the IPv6 address for 'name' into 'in6'. */
109 static void
110 get_ipv6_address(const char *name, struct in6_addr *in6)
111 {
112     FILE *file;
113     char line[128];
114
115     file = fopen("/proc/net/if_inet6", "r");
116     if (file == NULL) {
117         /* This most likely indicates that the host doesn't have IPv6 support,
118          * so it's not really a failure condition.*/
119         *in6 = in6addr_any;
120         return;
121     }
122
123     while (fgets(line, sizeof line, file)) {
124         uint8_t *s6 = in6->s6_addr;
125         char ifname[16 + 1];
126
127 #define X8 "%2"SCNx8
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],
134                    ifname) == 17
135             && !strcmp(name, ifname))
136         {
137             return;
138         }
139     }
140     *in6 = in6addr_any;
141
142     fclose(file);
143 }
144
145 static void
146 do_ethtool(struct netdev *netdev) 
147 {
148     struct ifreq ifr;
149     struct ethtool_cmd ecmd;
150
151     netdev->speed = 0;
152     netdev->features = 0;
153
154     memset(&ifr, 0, sizeof ifr);
155     strncpy(ifr.ifr_name, netdev->name, sizeof ifr.ifr_name);
156     ifr.ifr_data = (caddr_t) &ecmd;
157
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;
163         }
164         if (ecmd.supported & SUPPORTED_10baseT_Full) {
165             netdev->features |= OFPPF_10MB_FD;
166         }
167         if (ecmd.supported & SUPPORTED_100baseT_Half)  {
168             netdev->features |= OFPPF_100MB_HD;
169         }
170         if (ecmd.supported & SUPPORTED_100baseT_Full) {
171             netdev->features |= OFPPF_100MB_FD;
172         }
173         if (ecmd.supported & SUPPORTED_1000baseT_Half) {
174             netdev->features |= OFPPF_1GB_HD;
175         }
176         if (ecmd.supported & SUPPORTED_1000baseT_Full) {
177             netdev->features |= OFPPF_1GB_FD;
178         }
179         /* 10Gbps half-duplex doesn't exist... */
180         if (ecmd.supported & SUPPORTED_10000baseT_Full) {
181             netdev->features |= OFPPF_10GB_FD;
182         }
183
184         switch (ecmd.speed) {
185         case SPEED_10:
186             netdev->speed = 10;
187             break;
188
189         case SPEED_100:
190             netdev->speed = 100;
191             break;
192
193         case SPEED_1000:
194             netdev->speed = 1000;
195             break;
196
197         case SPEED_2500:
198             netdev->speed = 2500;
199             break;
200
201         case SPEED_10000:
202             netdev->speed = 10000;
203             break;
204         }
205     } else {
206         VLOG_DBG("ioctl(SIOCETHTOOL) failed: %s", strerror(errno));
207     }
208 }
209
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.
213  *
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
217  * categories. */
218 int
219 netdev_open(const char *name, int ethertype, struct netdev **netdev_)
220 {
221     int fd;
222     struct sockaddr sa;
223     struct ifreq ifr;
224     unsigned int ifindex;
225     socklen_t rcvbuf_len;
226     size_t rcvbuf;
227     uint8_t etheraddr[ETH_ADDR_LEN];
228     struct in_addr in4;
229     struct in6_addr in6;
230     int mtu;
231     int error;
232     struct netdev *netdev;
233
234     *netdev_ = NULL;
235     init_netdev();
236
237     /* Create raw socket.
238      *
239      * We have to use SOCK_PACKET, despite its deprecation, because only
240      * SOCK_PACKET lets us set the hardware source address of outgoing
241      * packets. */
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
246                       : ethertype));
247     if (fd < 0) {
248         return errno;
249     }
250
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));
257         goto error;
258     }
259
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));
271         goto error;
272     }
273     while (rcvbuf > 0) {
274         char buffer;
275         ssize_t n_bytes = recv(fd, &buffer, 1, MSG_TRUNC | MSG_DONTWAIT);
276         if (n_bytes <= 0) {
277             break;
278         }
279         rcvbuf -= n_bytes;
280     }
281
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));
287         goto error;
288     }
289     ifindex = ifr.ifr_ifindex;
290
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));
295         goto error;
296     }
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);
301     }
302     memcpy(etheraddr, ifr.ifr_hwaddr.sa_data, sizeof etheraddr);
303
304     /* Get MTU. */
305     if (ioctl(fd, SIOCGIFMTU, &ifr) < 0) {
306         VLOG_ERR("ioctl(SIOCGIFMTU) on %s device failed: %s",
307                  name, strerror(errno));
308         goto error;
309     }
310     mtu = ifr.ifr_mtu;
311
312     if (!get_ipv4_address(name, &in4)) {
313         goto error;
314     }
315     get_ipv6_address(name, &in6);
316
317     /* Allocate network device. */
318     netdev = xmalloc(sizeof *netdev);
319     netdev->name = xstrdup(name);
320     netdev->fd = fd;
321     memcpy(netdev->etheraddr, etheraddr, sizeof etheraddr);
322     netdev->mtu = mtu;
323     netdev->in4 = in4;
324     netdev->in6 = in6;
325
326     /* Get speed, features. */
327     do_ethtool(netdev);
328
329     /* Save flags to restore at close or exit. */
330     error = get_flags(netdev, &netdev->save_flags);
331     if (error) {
332         goto preset_error;
333     }
334     fatal_signal_block();
335     list_push_back(&netdev_list, &netdev->node);
336     fatal_signal_unblock();
337
338     /* Success! */
339     *netdev_ = netdev;
340     return 0;
341
342 error:
343     error = errno;
344 preset_error:
345     close(fd);
346     return error;
347 }
348
349 /* Closes and destroys 'netdev'. */
350 void
351 netdev_close(struct netdev *netdev)
352 {
353     if (netdev) {
354         /* Bring down interface and drop promiscuous mode, if we brought up
355          * the interface or enabled promiscuous mode. */
356         int error;
357         fatal_signal_block();
358         error = restore_flags(netdev);
359         list_remove(&netdev->node);
360         fatal_signal_unblock();
361         if (error) {
362             VLOG_WARN("failed to restore network device flags on %s: %s",
363                       netdev->name, strerror(error));
364         }
365
366         /* Free. */
367         free(netdev->name);
368         close(netdev->fd);
369         free(netdev);
370     }
371 }
372
373 /* Pads 'buffer' out with zero-bytes to the minimum valid length of an
374  * Ethernet packet, if necessary.  */
375 static void
376 pad_to_minimum_length(struct buffer *buffer)
377 {
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);
381     }
382 }
383
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.)
390  *
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
394  * be returned.
395  */
396 int
397 netdev_recv(struct netdev *netdev, struct buffer *buffer)
398 {
399     ssize_t n_bytes;
400
401     assert(buffer->size == 0);
402     assert(buffer_tailroom(buffer) >= ETH_TOTAL_MIN);
403     do {
404         n_bytes = recv(netdev->fd,
405                        buffer_tail(buffer), buffer_tailroom(buffer),
406                        MSG_DONTWAIT);
407     } while (n_bytes < 0 && errno == EINTR);
408     if (n_bytes < 0) {
409         if (errno != EAGAIN) {
410             VLOG_WARN("error receiving Ethernet packet on %s: %s",
411                       strerror(errno), netdev->name);
412         }
413         return errno;
414     } else {
415         buffer->size += n_bytes;
416
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
421          * length. */
422         pad_to_minimum_length(buffer);
423         return 0;
424     }
425 }
426
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'. */
429 void
430 netdev_recv_wait(struct netdev *netdev)
431 {
432     poll_fd_wait(netdev->fd, POLLIN);
433 }
434
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.
439  *
440  * The caller retains ownership of 'buffer' in all cases.
441  *
442  * The kernel maintains a packet transmission queue, so the caller is not
443  * expected to do additional queuing of packets. */
444 int
445 netdev_send(struct netdev *netdev, const struct buffer *buffer)
446 {
447     ssize_t n_bytes;
448     const struct eth_header *eh;
449     struct sockaddr_pkt spkt;
450
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);
455         return EMSGSIZE;
456     }
457     eh = buffer_at_assert(buffer, 0, sizeof *eh);
458
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;
463
464     do {
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);
468
469     if (n_bytes < 0) {
470         /* The Linux AF_PACKET implementation never blocks waiting for room
471          * for packets, instead returning ENOBUFS.  Translate this into EAGAIN
472          * for the caller. */
473         if (errno == ENOBUFS) {
474             return EAGAIN;
475         } else if (errno != EAGAIN) {
476             VLOG_WARN("error sending Ethernet packet on %s: %s",
477                       netdev->name, strerror(errno));
478         }
479         return 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);
483         return EMSGSIZE;
484     } else {
485         return 0;
486     }
487 }
488
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().
492  *
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. */
496 void
497 netdev_send_wait(struct netdev *netdev)
498 {
499     poll_fd_wait(netdev->fd, POLLOUT);
500 }
501
502 /* Returns a pointer to 'netdev''s MAC address.  The caller must not modify or
503  * free the returned buffer. */
504 const uint8_t *
505 netdev_get_etheraddr(const struct netdev *netdev)
506 {
507     return netdev->etheraddr;
508 }
509
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. */
512 const char *
513 netdev_get_name(const struct netdev *netdev)
514 {
515     return netdev->name;
516 }
517
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. */
521 int
522 netdev_get_mtu(const struct netdev *netdev) 
523 {
524     return netdev->mtu;
525 }
526
527 /* Returns the current speed of the network device that 'netdev' represents, in
528  * megabits per second, or 0 if the speed is unknown. */
529 int
530 netdev_get_speed(const struct netdev *netdev) 
531 {
532     return netdev->speed;
533 }
534
535 /* Returns the features supported by 'netdev', as a bitmap of bits from enum
536  * ofp_phy_port, in host byte order. */
537 uint32_t
538 netdev_get_features(const struct netdev *netdev) 
539 {
540     return netdev->features;
541 }
542
543 /* If 'netdev' has an assigned IPv4 address, sets '*in4' to that address and
544  * returns true.  Otherwise, returns false. */
545 bool
546 netdev_get_in4(const struct netdev *netdev, struct in_addr *in4)
547 {
548     *in4 = netdev->in4;
549     return in4->s_addr != INADDR_ANY;
550 }
551
552 /* If 'netdev' has an assigned IPv6 address, sets '*in6' to that address and
553  * returns true.  Otherwise, returns false. */
554 bool
555 netdev_get_in6(const struct netdev *netdev, struct in6_addr *in6)
556 {
557     *in6 = netdev->in6;
558     return memcmp(in6, &in6addr_any, sizeof *in6) != 0;
559 }
560
561 /* Obtains the current flags for 'netdev' and stores them into '*flagsp'.
562  * Returns 0 if successful, otherwise a positive errno value. */
563 int
564 netdev_get_flags(const struct netdev *netdev, enum netdev_flags *flagsp)
565 {
566     int error, flags;
567
568     error = get_flags(netdev, &flags);
569     if (error) {
570         return error;
571     }
572
573     *flagsp = 0;
574     if (flags & IFF_UP) {
575         *flagsp |= NETDEV_UP;
576     }
577     if (flags & IFF_PROMISC) {
578         *flagsp |= NETDEV_PROMISC;
579     }
580     return 0;
581 }
582
583 /* Sets the flags for 'netdev' to 'nd_flags'.
584  * Returns 0 if successful, otherwise a positive errno value. */
585 int
586 netdev_set_flags(struct netdev *netdev, enum netdev_flags nd_flags)
587 {
588     int old_flags, new_flags;
589     int error;
590
591     error = get_flags(netdev, &old_flags);
592     if (error) {
593         return error;
594     }
595
596     new_flags = old_flags & ~(IFF_UP | IFF_PROMISC);
597     if (nd_flags & NETDEV_UP) {
598         new_flags |= IFF_UP;
599     }
600     if (nd_flags & NETDEV_PROMISC) {
601         new_flags |= IFF_PROMISC;
602     }
603     if (new_flags != old_flags) {
604         error = set_flags(netdev, new_flags);
605     }
606     return error;
607 }
608
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'. */
613 int
614 netdev_arp_lookup(const struct netdev *netdev,
615                   uint32_t ip, uint8_t mac[ETH_ADDR_LEN]) 
616 {
617     struct arpreq r;
618     struct sockaddr_in *pa;
619     int retval;
620
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;
625     pa->sin_port = 0;
626     r.arp_ha.sa_family = ARPHRD_ETHER;
627     r.arp_flags = 0;
628     strncpy(r.arp_dev, netdev->name, sizeof r.arp_dev);
629     retval = ioctl(af_inet_sock, SIOCGARP, &r) < 0 ? errno : 0;
630     if (!retval) {
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));
635     }
636     return retval;
637 }
638 \f
639 static void restore_all_flags(void *aux);
640
641 /* Set up a signal hook to restore network device flags on program
642  * termination.  */
643 static void
644 init_netdev(void)
645 {
646     static bool inited;
647     if (!inited) {
648         inited = true;
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)");
653         }
654     }
655 }
656
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
659  * errno value.
660  *
661  * To avoid reentry, the caller must ensure that fatal signals are blocked. */
662 static int
663 restore_flags(struct netdev *netdev)
664 {
665     struct ifreq ifr;
666
667     /* Get current flags. */
668     strncpy(ifr.ifr_name, netdev->name, sizeof ifr.ifr_name);
669     if (ioctl(netdev->fd, SIOCGIFFLAGS, &ifr) < 0) {
670         return errno;
671     }
672
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) {
678             return errno;
679         }
680     }
681
682     return 0;
683 }
684
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. */
687 static void
688 restore_all_flags(void *aux UNUSED)
689 {
690     struct netdev *netdev;
691     LIST_FOR_EACH (netdev, struct netdev, node, &netdev_list) {
692         restore_flags(netdev);
693     }
694 }
695
696 static int
697 get_flags(const struct netdev *netdev, int *flags)
698 {
699     struct ifreq ifr;
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));
704         return errno;
705     }
706     *flags = ifr.ifr_flags;
707     return 0;
708 }
709
710 static int
711 set_flags(struct netdev *netdev, int flags)
712 {
713     struct ifreq ifr;
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));
719         return errno;
720     }
721     return 0;
722 }