netdev: Add ability to permanently set device flags.
[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 <net/route.h>
52 #include <netinet/in.h>
53 #include <stdlib.h>
54 #include <string.h>
55 #include <unistd.h>
56
57 #include "list.h"
58 #include "fatal-signal.h"
59 #include "buffer.h"
60 #include "openflow.h"
61 #include "packets.h"
62 #include "poll-loop.h"
63 #include "socket-util.h"
64
65 #define THIS_MODULE VLM_netdev
66 #include "vlog.h"
67
68 struct netdev {
69     struct list node;
70     char *name;
71     int ifindex;
72     int fd;
73     uint8_t etheraddr[ETH_ADDR_LEN];
74     int speed;
75     int mtu;
76     uint32_t features;
77     struct in_addr in4;
78     struct in6_addr in6;
79     int save_flags;             /* Initial device flags. */
80     int changed_flags;          /* Flags that we changed. */
81 };
82
83 static struct list netdev_list = LIST_INITIALIZER(&netdev_list);
84
85 /* An AF_INET socket (used for ioctl operations). */
86 static int af_inet_sock = -1;
87
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);
92
93 /* Obtains the IPv4 address for 'name' into 'in4'.  Returns true if
94  * successful. */
95 static bool
96 get_ipv4_address(const char *name, struct in_addr *in4)
97 {
98     struct ifreq ifr;
99
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;
105     } else {
106         in4->s_addr = INADDR_ANY;
107     }
108
109     return true;
110 }
111
112 /* Obtains the IPv6 address for 'name' into 'in6'. */
113 static void
114 get_ipv6_address(const char *name, struct in6_addr *in6)
115 {
116     FILE *file;
117     char line[128];
118
119     file = fopen("/proc/net/if_inet6", "r");
120     if (file == NULL) {
121         /* This most likely indicates that the host doesn't have IPv6 support,
122          * so it's not really a failure condition.*/
123         *in6 = in6addr_any;
124         return;
125     }
126
127     while (fgets(line, sizeof line, file)) {
128         uint8_t *s6 = in6->s6_addr;
129         char ifname[16 + 1];
130
131 #define X8 "%2"SCNx8
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],
138                    ifname) == 17
139             && !strcmp(name, ifname))
140         {
141             return;
142         }
143     }
144     *in6 = in6addr_any;
145
146     fclose(file);
147 }
148
149 static void
150 do_ethtool(struct netdev *netdev) 
151 {
152     struct ifreq ifr;
153     struct ethtool_cmd ecmd;
154
155     netdev->speed = 0;
156     netdev->features = 0;
157
158     memset(&ifr, 0, sizeof ifr);
159     strncpy(ifr.ifr_name, netdev->name, sizeof ifr.ifr_name);
160     ifr.ifr_data = (caddr_t) &ecmd;
161
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;
167         }
168         if (ecmd.supported & SUPPORTED_10baseT_Full) {
169             netdev->features |= OFPPF_10MB_FD;
170         }
171         if (ecmd.supported & SUPPORTED_100baseT_Half)  {
172             netdev->features |= OFPPF_100MB_HD;
173         }
174         if (ecmd.supported & SUPPORTED_100baseT_Full) {
175             netdev->features |= OFPPF_100MB_FD;
176         }
177         if (ecmd.supported & SUPPORTED_1000baseT_Half) {
178             netdev->features |= OFPPF_1GB_HD;
179         }
180         if (ecmd.supported & SUPPORTED_1000baseT_Full) {
181             netdev->features |= OFPPF_1GB_FD;
182         }
183         /* 10Gbps half-duplex doesn't exist... */
184         if (ecmd.supported & SUPPORTED_10000baseT_Full) {
185             netdev->features |= OFPPF_10GB_FD;
186         }
187
188         switch (ecmd.speed) {
189         case SPEED_10:
190             netdev->speed = 10;
191             break;
192
193         case SPEED_100:
194             netdev->speed = 100;
195             break;
196
197         case SPEED_1000:
198             netdev->speed = 1000;
199             break;
200
201         case SPEED_2500:
202             netdev->speed = 2500;
203             break;
204
205         case SPEED_10000:
206             netdev->speed = 10000;
207             break;
208         }
209     } else {
210         VLOG_DBG("ioctl(SIOCETHTOOL) failed: %s", strerror(errno));
211     }
212 }
213
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.
217  *
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
221  * categories. */
222 int
223 netdev_open(const char *name, int ethertype, struct netdev **netdev_)
224 {
225     int fd;
226     struct sockaddr_ll sll;
227     struct ifreq ifr;
228     unsigned int ifindex;
229     uint8_t etheraddr[ETH_ADDR_LEN];
230     struct in_addr in4;
231     struct in6_addr in6;
232     int mtu;
233     int error;
234     struct netdev *netdev;
235
236     *netdev_ = NULL;
237     init_netdev();
238
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
244                       : ethertype));
245     if (fd < 0) {
246         return errno;
247     }
248
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));
254         goto error;
255     }
256     ifindex = ifr.ifr_ifindex;
257
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));
264         goto error;
265     }
266
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);
273         if (error) {
274             goto error;
275         }
276     }
277
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));
282         goto error;
283     }
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);
288     }
289     memcpy(etheraddr, ifr.ifr_hwaddr.sa_data, sizeof etheraddr);
290
291     /* Get MTU. */
292     if (ioctl(fd, SIOCGIFMTU, &ifr) < 0) {
293         VLOG_ERR("ioctl(SIOCGIFMTU) on %s device failed: %s",
294                  name, strerror(errno));
295         goto error;
296     }
297     mtu = ifr.ifr_mtu;
298
299     if (!get_ipv4_address(name, &in4)) {
300         goto error;
301     }
302     get_ipv6_address(name, &in6);
303
304     /* Allocate network device. */
305     netdev = xmalloc(sizeof *netdev);
306     netdev->name = xstrdup(name);
307     netdev->ifindex = ifindex;
308     netdev->fd = fd;
309     memcpy(netdev->etheraddr, etheraddr, sizeof etheraddr);
310     netdev->mtu = mtu;
311     netdev->in4 = in4;
312     netdev->in6 = in6;
313
314     /* Get speed, features. */
315     do_ethtool(netdev);
316
317     /* Save flags to restore at close or exit. */
318     error = get_flags(netdev, &netdev->save_flags);
319     if (error) {
320         goto preset_error;
321     }
322     netdev->changed_flags = 0;
323     fatal_signal_block();
324     list_push_back(&netdev_list, &netdev->node);
325     fatal_signal_unblock();
326
327     /* Success! */
328     *netdev_ = netdev;
329     return 0;
330
331 error:
332     error = errno;
333 preset_error:
334     close(fd);
335     return error;
336 }
337
338 /* Closes and destroys 'netdev'. */
339 void
340 netdev_close(struct netdev *netdev)
341 {
342     if (netdev) {
343         /* Bring down interface and drop promiscuous mode, if we brought up
344          * the interface or enabled promiscuous mode. */
345         int error;
346         fatal_signal_block();
347         error = restore_flags(netdev);
348         list_remove(&netdev->node);
349         fatal_signal_unblock();
350         if (error) {
351             VLOG_WARN("failed to restore network device flags on %s: %s",
352                       netdev->name, strerror(error));
353         }
354
355         /* Free. */
356         free(netdev->name);
357         close(netdev->fd);
358         free(netdev);
359     }
360 }
361
362 /* Pads 'buffer' out with zero-bytes to the minimum valid length of an
363  * Ethernet packet, if necessary.  */
364 static void
365 pad_to_minimum_length(struct buffer *buffer)
366 {
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);
370     }
371 }
372
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.)
379  *
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
383  * be returned.
384  */
385 int
386 netdev_recv(struct netdev *netdev, struct buffer *buffer)
387 {
388     ssize_t n_bytes;
389
390     assert(buffer->size == 0);
391     assert(buffer_tailroom(buffer) >= ETH_TOTAL_MIN);
392     do {
393         n_bytes = recv(netdev->fd,
394                        buffer_tail(buffer), buffer_tailroom(buffer),
395                        MSG_DONTWAIT);
396     } while (n_bytes < 0 && errno == EINTR);
397     if (n_bytes < 0) {
398         if (errno != EAGAIN) {
399             VLOG_WARN("error receiving Ethernet packet on %s: %s",
400                       strerror(errno), netdev->name);
401         }
402         return errno;
403     } else {
404         buffer->size += n_bytes;
405
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
410          * length. */
411         pad_to_minimum_length(buffer);
412         return 0;
413     }
414 }
415
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'. */
418 void
419 netdev_recv_wait(struct netdev *netdev)
420 {
421     poll_fd_wait(netdev->fd, POLLIN);
422 }
423
424 /* Discards all packets waiting to be received from 'netdev'. */
425 void
426 netdev_drain(struct netdev *netdev)
427 {
428     drain_rcvbuf(netdev->fd);
429 }
430
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.
435  *
436  * The caller retains ownership of 'buffer' in all cases.
437  *
438  * The kernel maintains a packet transmission queue, so the caller is not
439  * expected to do additional queuing of packets. */
440 int
441 netdev_send(struct netdev *netdev, const struct buffer *buffer)
442 {
443     ssize_t n_bytes;
444     const struct eth_header *eh;
445
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);
450         return EMSGSIZE;
451     }
452     eh = buffer_at_assert(buffer, 0, sizeof *eh);
453
454     do {
455         n_bytes = sendto(netdev->fd, buffer->data, buffer->size, 0, NULL, 0);
456     } while (n_bytes < 0 && errno == EINTR);
457
458     if (n_bytes < 0) {
459         /* The Linux AF_PACKET implementation never blocks waiting for room
460          * for packets, instead returning ENOBUFS.  Translate this into EAGAIN
461          * for the caller. */
462         if (errno == ENOBUFS) {
463             return EAGAIN;
464         } else if (errno != EAGAIN) {
465             VLOG_WARN("error sending Ethernet packet on %s: %s",
466                       netdev->name, strerror(errno));
467         }
468         return 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);
472         return EMSGSIZE;
473     } else {
474         return 0;
475     }
476 }
477
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().
481  *
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. */
485 void
486 netdev_send_wait(struct netdev *netdev)
487 {
488     poll_fd_wait(netdev->fd, POLLOUT);
489 }
490
491 /* Returns a pointer to 'netdev''s MAC address.  The caller must not modify or
492  * free the returned buffer. */
493 const uint8_t *
494 netdev_get_etheraddr(const struct netdev *netdev)
495 {
496     return netdev->etheraddr;
497 }
498
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. */
501 const char *
502 netdev_get_name(const struct netdev *netdev)
503 {
504     return netdev->name;
505 }
506
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. */
510 int
511 netdev_get_mtu(const struct netdev *netdev) 
512 {
513     return netdev->mtu;
514 }
515
516 /* Returns the current speed of the network device that 'netdev' represents, in
517  * megabits per second, or 0 if the speed is unknown. */
518 int
519 netdev_get_speed(const struct netdev *netdev) 
520 {
521     return netdev->speed;
522 }
523
524 /* Returns the features supported by 'netdev', as a bitmap of bits from enum
525  * ofp_phy_port, in host byte order. */
526 uint32_t
527 netdev_get_features(const struct netdev *netdev) 
528 {
529     return netdev->features;
530 }
531
532 /* If 'netdev' has an assigned IPv4 address, sets '*in4' to that address and
533  * returns true.  Otherwise, returns false. */
534 bool
535 netdev_get_in4(const struct netdev *netdev, struct in_addr *in4)
536 {
537     *in4 = netdev->in4;
538     return in4->s_addr != INADDR_ANY;
539 }
540
541 /* If 'netdev' has an assigned IPv6 address, sets '*in6' to that address and
542  * returns true.  Otherwise, returns false. */
543 bool
544 netdev_get_in6(const struct netdev *netdev, struct in6_addr *in6)
545 {
546     *in6 = netdev->in6;
547     return memcmp(in6, &in6addr_any, sizeof *in6) != 0;
548 }
549
550 /* Obtains the current flags for 'netdev' and stores them into '*flagsp'.
551  * Returns 0 if successful, otherwise a positive errno value. */
552 int
553 netdev_get_flags(const struct netdev *netdev, enum netdev_flags *flagsp)
554 {
555     int error, flags;
556
557     error = get_flags(netdev, &flags);
558     if (error) {
559         return error;
560     }
561
562     *flagsp = 0;
563     if (flags & IFF_UP) {
564         *flagsp |= NETDEV_UP;
565     }
566     if (flags & IFF_PROMISC) {
567         *flagsp |= NETDEV_PROMISC;
568     }
569     return 0;
570 }
571
572 static int
573 nd_to_iff_flags(enum netdev_flags nd)
574 {
575     int iff = 0;
576     if (nd & NETDEV_UP) {
577         iff |= IFF_UP;
578     }
579     if (nd & NETDEV_PROMISC) {
580         iff |= IFF_PROMISC;
581     }
582     return iff;
583 }
584
585 /* On 'netdev', turns off the flags in 'off' and then turns on the flags in
586  * 'on'.  If 'permanent' is true, the changes will persist; otherwise, they
587  * will be reverted when 'netdev' is closed or the program exits.  Returns 0 if
588  * successful, otherwise a positive errno value. */
589 static int
590 do_update_flags(struct netdev *netdev, enum netdev_flags off,
591                 enum netdev_flags on, bool permanent)
592 {
593     int old_flags, new_flags;
594     int error;
595
596     error = get_flags(netdev, &old_flags);
597     if (error) {
598         return error;
599     }
600
601     new_flags = (old_flags & ~nd_to_iff_flags(off)) | nd_to_iff_flags(on);
602     if (!permanent) {
603         netdev->changed_flags |= new_flags ^ old_flags; 
604     }
605     if (new_flags != old_flags) {
606         error = set_flags(netdev, new_flags);
607     }
608     return error;
609 }
610
611 /* Sets the flags for 'netdev' to 'flags'.
612  * If 'permanent' is true, the changes will persist; otherwise, they
613  * will be reverted when 'netdev' is closed or the program exits.
614  * Returns 0 if successful, otherwise a positive errno value. */
615 int
616 netdev_set_flags(struct netdev *netdev, enum netdev_flags flags,
617                  bool permanent)
618 {
619     return do_update_flags(netdev, -1, flags, permanent);
620 }
621
622 /* Turns on the specified 'flags' on 'netdev'.
623  * If 'permanent' is true, the changes will persist; otherwise, they
624  * will be reverted when 'netdev' is closed or the program exits.
625  * Returns 0 if successful, otherwise a positive errno value. */
626 int
627 netdev_turn_flags_on(struct netdev *netdev, enum netdev_flags flags,
628                      bool permanent)
629 {
630     return do_update_flags(netdev, 0, flags, permanent);
631 }
632
633 /* Turns off the specified 'flags' on 'netdev'.
634  * If 'permanent' is true, the changes will persist; otherwise, they
635  * will be reverted when 'netdev' is closed or the program exits.
636  * Returns 0 if successful, otherwise a positive errno value. */
637 int
638 netdev_turn_flags_off(struct netdev *netdev, enum netdev_flags flags,
639                       bool permanent)
640 {
641     return do_update_flags(netdev, flags, 0, permanent);
642 }
643
644 /* Looks up the ARP table entry for 'ip' on 'netdev'.  If one exists and can be
645  * successfully retrieved, it stores the corresponding MAC address in 'mac' and
646  * returns 0.  Otherwise, it returns a positive errno value; in particular,
647  * ENXIO indicates that there is not ARP table entry for 'ip' on 'netdev'. */
648 int
649 netdev_arp_lookup(const struct netdev *netdev,
650                   uint32_t ip, uint8_t mac[ETH_ADDR_LEN]) 
651 {
652     struct arpreq r;
653     struct sockaddr_in *pa;
654     int retval;
655
656     memset(&r, 0, sizeof r);
657     pa = (struct sockaddr_in *) &r.arp_pa;
658     pa->sin_family = AF_INET;
659     pa->sin_addr.s_addr = ip;
660     pa->sin_port = 0;
661     r.arp_ha.sa_family = ARPHRD_ETHER;
662     r.arp_flags = 0;
663     strncpy(r.arp_dev, netdev->name, sizeof r.arp_dev);
664     retval = ioctl(af_inet_sock, SIOCGARP, &r) < 0 ? errno : 0;
665     if (!retval) {
666         memcpy(mac, r.arp_ha.sa_data, ETH_ADDR_LEN);
667     } else if (retval != ENXIO) {
668         VLOG_WARN("%s: could not look up ARP entry for "IP_FMT": %s",
669                   netdev->name, IP_ARGS(&ip), strerror(retval));
670     }
671     return retval;
672 }
673 \f
674 static void restore_all_flags(void *aux);
675
676 /* Set up a signal hook to restore network device flags on program
677  * termination.  */
678 static void
679 init_netdev(void)
680 {
681     static bool inited;
682     if (!inited) {
683         inited = true;
684         fatal_signal_add_hook(restore_all_flags, NULL);
685         af_inet_sock = socket(AF_INET, SOCK_DGRAM, 0);
686         if (af_inet_sock < 0) {
687             fatal(errno, "socket(AF_INET)");
688         }
689     }
690 }
691
692 /* Restore the network device flags on 'netdev' to those that were active
693  * before we changed them.  Returns 0 if successful, otherwise a positive
694  * errno value.
695  *
696  * To avoid reentry, the caller must ensure that fatal signals are blocked. */
697 static int
698 restore_flags(struct netdev *netdev)
699 {
700     struct ifreq ifr;
701     int restore_flags;
702
703     /* Get current flags. */
704     strncpy(ifr.ifr_name, netdev->name, sizeof ifr.ifr_name);
705     if (ioctl(netdev->fd, SIOCGIFFLAGS, &ifr) < 0) {
706         return errno;
707     }
708
709     /* Restore flags that we might have changed, if necessary. */
710     restore_flags = netdev->changed_flags & (IFF_PROMISC | IFF_UP);
711     if ((ifr.ifr_flags ^ netdev->save_flags) & restore_flags) {
712         ifr.ifr_flags &= ~restore_flags;
713         ifr.ifr_flags |= netdev->save_flags & restore_flags;
714         if (ioctl(netdev->fd, SIOCSIFFLAGS, &ifr) < 0) {
715             return errno;
716         }
717     }
718
719     return 0;
720 }
721
722 /* Retores all the flags on all network devices that we modified.  Called from
723  * a signal handler, so it does not attempt to report error conditions. */
724 static void
725 restore_all_flags(void *aux UNUSED)
726 {
727     struct netdev *netdev;
728     LIST_FOR_EACH (netdev, struct netdev, node, &netdev_list) {
729         restore_flags(netdev);
730     }
731 }
732
733 static int
734 get_flags(const struct netdev *netdev, int *flags)
735 {
736     struct ifreq ifr;
737     strncpy(ifr.ifr_name, netdev->name, sizeof ifr.ifr_name);
738     if (ioctl(netdev->fd, SIOCGIFFLAGS, &ifr) < 0) {
739         VLOG_ERR("ioctl(SIOCGIFFLAGS) on %s device failed: %s",
740                  netdev->name, strerror(errno));
741         return errno;
742     }
743     *flags = ifr.ifr_flags;
744     return 0;
745 }
746
747 static int
748 set_flags(struct netdev *netdev, int flags)
749 {
750     struct ifreq ifr;
751     strncpy(ifr.ifr_name, netdev->name, sizeof ifr.ifr_name);
752     ifr.ifr_flags = flags;
753     if (ioctl(netdev->fd, SIOCSIFFLAGS, &ifr) < 0) {
754         VLOG_ERR("ioctl(SIOCSIFFLAGS) on %s device failed: %s",
755                  netdev->name, strerror(errno));
756         return errno;
757     }
758     return 0;
759 }