Change netdev_get_in4() to re-check the IP address on each call.
[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 <config.h>
35 #include "netdev.h"
36
37 #include <assert.h>
38 #include <errno.h>
39 #include <arpa/inet.h>
40 #include <inttypes.h>
41 #include <linux/types.h>
42 #include <linux/ethtool.h>
43 #include <linux/sockios.h>
44 #include <sys/types.h>
45 #include <sys/ioctl.h>
46 #include <sys/socket.h>
47 #include <netpacket/packet.h>
48 #include <net/ethernet.h>
49 #include <net/if.h>
50 #include <net/if_arp.h>
51 #include <net/if_packet.h>
52 #include <net/route.h>
53 #include <netinet/in.h>
54 #include <stdlib.h>
55 #include <string.h>
56 #include <unistd.h>
57
58 #include "list.h"
59 #include "fatal-signal.h"
60 #include "buffer.h"
61 #include "openflow.h"
62 #include "packets.h"
63 #include "poll-loop.h"
64 #include "socket-util.h"
65
66 #define THIS_MODULE VLM_netdev
67 #include "vlog.h"
68
69 struct netdev {
70     struct list node;
71     char *name;
72     int ifindex;
73     int fd;
74     uint8_t etheraddr[ETH_ADDR_LEN];
75     int speed;
76     int mtu;
77     uint32_t features;
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 IPv6 address for 'name' into 'in6'. */
94 static void
95 get_ipv6_address(const char *name, struct in6_addr *in6)
96 {
97     FILE *file;
98     char line[128];
99
100     file = fopen("/proc/net/if_inet6", "r");
101     if (file == NULL) {
102         /* This most likely indicates that the host doesn't have IPv6 support,
103          * so it's not really a failure condition.*/
104         *in6 = in6addr_any;
105         return;
106     }
107
108     while (fgets(line, sizeof line, file)) {
109         uint8_t *s6 = in6->s6_addr;
110         char ifname[16 + 1];
111
112 #define X8 "%2"SCNx8
113         if (sscanf(line, " "X8 X8 X8 X8 X8 X8 X8 X8 X8 X8 X8 X8 X8 X8 X8 X8
114                    "%*x %*x %*x %*x %16s\n",
115                    &s6[0], &s6[1], &s6[2], &s6[3],
116                    &s6[4], &s6[5], &s6[6], &s6[7],
117                    &s6[8], &s6[9], &s6[10], &s6[11],
118                    &s6[12], &s6[13], &s6[14], &s6[15],
119                    ifname) == 17
120             && !strcmp(name, ifname))
121         {
122             return;
123         }
124     }
125     *in6 = in6addr_any;
126
127     fclose(file);
128 }
129
130 static void
131 do_ethtool(struct netdev *netdev) 
132 {
133     struct ifreq ifr;
134     struct ethtool_cmd ecmd;
135
136     netdev->speed = 0;
137     netdev->features = 0;
138
139     memset(&ifr, 0, sizeof ifr);
140     strncpy(ifr.ifr_name, netdev->name, sizeof ifr.ifr_name);
141     ifr.ifr_data = (caddr_t) &ecmd;
142
143     memset(&ecmd, 0, sizeof ecmd);
144     ecmd.cmd = ETHTOOL_GSET;
145     if (ioctl(netdev->fd, SIOCETHTOOL, &ifr) == 0) {
146         if (ecmd.supported & SUPPORTED_10baseT_Half) {
147             netdev->features |= OFPPF_10MB_HD;
148         }
149         if (ecmd.supported & SUPPORTED_10baseT_Full) {
150             netdev->features |= OFPPF_10MB_FD;
151         }
152         if (ecmd.supported & SUPPORTED_100baseT_Half)  {
153             netdev->features |= OFPPF_100MB_HD;
154         }
155         if (ecmd.supported & SUPPORTED_100baseT_Full) {
156             netdev->features |= OFPPF_100MB_FD;
157         }
158         if (ecmd.supported & SUPPORTED_1000baseT_Half) {
159             netdev->features |= OFPPF_1GB_HD;
160         }
161         if (ecmd.supported & SUPPORTED_1000baseT_Full) {
162             netdev->features |= OFPPF_1GB_FD;
163         }
164         /* 10Gbps half-duplex doesn't exist... */
165         if (ecmd.supported & SUPPORTED_10000baseT_Full) {
166             netdev->features |= OFPPF_10GB_FD;
167         }
168
169         switch (ecmd.speed) {
170         case SPEED_10:
171             netdev->speed = 10;
172             break;
173
174         case SPEED_100:
175             netdev->speed = 100;
176             break;
177
178         case SPEED_1000:
179             netdev->speed = 1000;
180             break;
181
182         case SPEED_2500:
183             netdev->speed = 2500;
184             break;
185
186         case SPEED_10000:
187             netdev->speed = 10000;
188             break;
189         }
190     } else {
191         VLOG_DBG("ioctl(SIOCETHTOOL) failed: %s", strerror(errno));
192     }
193 }
194
195 /* Opens the network device named 'name' (e.g. "eth0") and returns zero if
196  * successful, otherwise a positive errno value.  On success, sets '*netdev'
197  * to the new network device, otherwise to null.
198  *
199  * 'ethertype' may be a 16-bit Ethernet protocol value in host byte order to
200  * capture frames of that type received on the device.  It may also be one of
201  * the 'enum netdev_pseudo_ethertype' values to receive frames in one of those
202  * categories. */
203 int
204 netdev_open(const char *name, int ethertype, struct netdev **netdev_)
205 {
206     int fd;
207     struct sockaddr_ll sll;
208     struct ifreq ifr;
209     unsigned int ifindex;
210     uint8_t etheraddr[ETH_ADDR_LEN];
211     struct in6_addr in6;
212     int mtu;
213     int error;
214     struct netdev *netdev;
215
216     *netdev_ = NULL;
217     init_netdev();
218
219     /* Create raw socket. */
220     fd = socket(PF_PACKET, SOCK_RAW,
221                 htons(ethertype == NETDEV_ETH_TYPE_NONE ? 0
222                       : ethertype == NETDEV_ETH_TYPE_ANY ? ETH_P_ALL
223                       : ethertype == NETDEV_ETH_TYPE_802_2 ? ETH_P_802_2
224                       : ethertype));
225     if (fd < 0) {
226         return errno;
227     }
228
229     /* Get ethernet device index. */
230     strncpy(ifr.ifr_name, name, sizeof ifr.ifr_name);
231     if (ioctl(fd, SIOCGIFINDEX, &ifr) < 0) {
232         VLOG_ERR("ioctl(SIOCGIFINDEX) on %s device failed: %s",
233                  name, strerror(errno));
234         goto error;
235     }
236     ifindex = ifr.ifr_ifindex;
237
238     /* Bind to specific ethernet device. */
239     memset(&sll, 0, sizeof sll);
240     sll.sll_family = AF_PACKET;
241     sll.sll_ifindex = ifindex;
242     if (bind(fd, (struct sockaddr *) &sll, sizeof sll) < 0) {
243         VLOG_ERR("bind to %s failed: %s", name, strerror(errno));
244         goto error;
245     }
246
247     if (ethertype != NETDEV_ETH_TYPE_NONE) {
248         /* Between the socket() and bind() calls above, the socket receives all
249          * packets of the requested type on all system interfaces.  We do not
250          * want to receive that data, but there is no way to avoid it.  So we
251          * must now drain out the receive queue. */
252         error = drain_rcvbuf(fd);
253         if (error) {
254             goto error;
255         }
256     }
257
258     /* Get MAC address. */
259     if (ioctl(fd, SIOCGIFHWADDR, &ifr) < 0) {
260         VLOG_ERR("ioctl(SIOCGIFHWADDR) on %s device failed: %s",
261                  name, strerror(errno));
262         goto error;
263     }
264     if (ifr.ifr_hwaddr.sa_family != AF_UNSPEC
265         && ifr.ifr_hwaddr.sa_family != ARPHRD_ETHER) {
266         VLOG_WARN("%s device has unknown hardware address family %d",
267                   name, (int) ifr.ifr_hwaddr.sa_family);
268     }
269     memcpy(etheraddr, ifr.ifr_hwaddr.sa_data, sizeof etheraddr);
270
271     /* Get MTU. */
272     if (ioctl(fd, SIOCGIFMTU, &ifr) < 0) {
273         VLOG_ERR("ioctl(SIOCGIFMTU) on %s device failed: %s",
274                  name, strerror(errno));
275         goto error;
276     }
277     mtu = ifr.ifr_mtu;
278
279     get_ipv6_address(name, &in6);
280
281     /* Allocate network device. */
282     netdev = xmalloc(sizeof *netdev);
283     netdev->name = xstrdup(name);
284     netdev->ifindex = ifindex;
285     netdev->fd = fd;
286     memcpy(netdev->etheraddr, etheraddr, sizeof etheraddr);
287     netdev->mtu = mtu;
288     netdev->in6 = in6;
289
290     /* Get speed, features. */
291     do_ethtool(netdev);
292
293     /* Save flags to restore at close or exit. */
294     error = get_flags(netdev, &netdev->save_flags);
295     if (error) {
296         goto preset_error;
297     }
298     netdev->changed_flags = 0;
299     fatal_signal_block();
300     list_push_back(&netdev_list, &netdev->node);
301     fatal_signal_unblock();
302
303     /* Success! */
304     *netdev_ = netdev;
305     return 0;
306
307 error:
308     error = errno;
309 preset_error:
310     close(fd);
311     return error;
312 }
313
314 /* Closes and destroys 'netdev'. */
315 void
316 netdev_close(struct netdev *netdev)
317 {
318     if (netdev) {
319         /* Bring down interface and drop promiscuous mode, if we brought up
320          * the interface or enabled promiscuous mode. */
321         int error;
322         fatal_signal_block();
323         error = restore_flags(netdev);
324         list_remove(&netdev->node);
325         fatal_signal_unblock();
326         if (error) {
327             VLOG_WARN("failed to restore network device flags on %s: %s",
328                       netdev->name, strerror(error));
329         }
330
331         /* Free. */
332         free(netdev->name);
333         close(netdev->fd);
334         free(netdev);
335     }
336 }
337
338 /* Pads 'buffer' out with zero-bytes to the minimum valid length of an
339  * Ethernet packet, if necessary.  */
340 static void
341 pad_to_minimum_length(struct buffer *buffer)
342 {
343     if (buffer->size < ETH_TOTAL_MIN) {
344         size_t shortage = ETH_TOTAL_MIN - buffer->size;
345         memset(buffer_put_uninit(buffer, shortage), 0, shortage);
346     }
347 }
348
349 /* Attempts to receive a packet from 'netdev' into 'buffer', which the caller
350  * must have initialized with sufficient room for the packet.  The space
351  * required to receive any packet is ETH_HEADER_LEN bytes, plus VLAN_HEADER_LEN
352  * bytes, plus the device's MTU (which may be retrieved via netdev_get_mtu()).
353  * (Some devices do not allow for a VLAN header, in which case VLAN_HEADER_LEN
354  * need not be included.)
355  *
356  * If a packet is successfully retrieved, returns 0.  In this case 'buffer' is
357  * guaranteed to contain at least ETH_TOTAL_MIN bytes.  Otherwise, returns a
358  * positive errno value.  Returns EAGAIN immediately if no packet is ready to
359  * be returned.
360  */
361 int
362 netdev_recv(struct netdev *netdev, struct buffer *buffer)
363 {
364     ssize_t n_bytes;
365
366     assert(buffer->size == 0);
367     assert(buffer_tailroom(buffer) >= ETH_TOTAL_MIN);
368     do {
369         n_bytes = recv(netdev->fd,
370                        buffer_tail(buffer), buffer_tailroom(buffer),
371                        MSG_DONTWAIT);
372     } while (n_bytes < 0 && errno == EINTR);
373     if (n_bytes < 0) {
374         if (errno != EAGAIN) {
375             VLOG_WARN("error receiving Ethernet packet on %s: %s",
376                       strerror(errno), netdev->name);
377         }
378         return errno;
379     } else {
380         buffer->size += n_bytes;
381
382         /* When the kernel internally sends out an Ethernet frame on an
383          * interface, it gives us a copy *before* padding the frame to the
384          * minimum length.  Thus, when it sends out something like an ARP
385          * request, we see a too-short frame.  So pad it out to the minimum
386          * length. */
387         pad_to_minimum_length(buffer);
388         return 0;
389     }
390 }
391
392 /* Registers with the poll loop to wake up from the next call to poll_block()
393  * when a packet is ready to be received with netdev_recv() on 'netdev'. */
394 void
395 netdev_recv_wait(struct netdev *netdev)
396 {
397     poll_fd_wait(netdev->fd, POLLIN);
398 }
399
400 /* Discards all packets waiting to be received from 'netdev'. */
401 void
402 netdev_drain(struct netdev *netdev)
403 {
404     drain_rcvbuf(netdev->fd);
405 }
406
407 /* Sends 'buffer' on 'netdev'.  Returns 0 if successful, otherwise a positive
408  * errno value.  Returns EAGAIN without blocking if the packet cannot be queued
409  * immediately.  Returns EMSGSIZE if a partial packet was transmitted or if
410  * the packet is too big or too small to transmit on the device.
411  *
412  * The caller retains ownership of 'buffer' in all cases.
413  *
414  * The kernel maintains a packet transmission queue, so the caller is not
415  * expected to do additional queuing of packets. */
416 int
417 netdev_send(struct netdev *netdev, const struct buffer *buffer)
418 {
419     ssize_t n_bytes;
420     const struct eth_header *eh;
421
422     /* Pull out the Ethernet header. */
423     if (buffer->size < ETH_HEADER_LEN) {
424         VLOG_WARN("cannot send %zu-byte frame on %s",
425                   buffer->size, netdev->name);
426         return EMSGSIZE;
427     }
428     eh = buffer_at_assert(buffer, 0, sizeof *eh);
429
430     do {
431         n_bytes = sendto(netdev->fd, buffer->data, buffer->size, 0, NULL, 0);
432     } while (n_bytes < 0 && errno == EINTR);
433
434     if (n_bytes < 0) {
435         /* The Linux AF_PACKET implementation never blocks waiting for room
436          * for packets, instead returning ENOBUFS.  Translate this into EAGAIN
437          * for the caller. */
438         if (errno == ENOBUFS) {
439             return EAGAIN;
440         } else if (errno != EAGAIN) {
441             VLOG_WARN("error sending Ethernet packet on %s: %s",
442                       netdev->name, strerror(errno));
443         }
444         return errno;
445     } else if (n_bytes != buffer->size) {
446         VLOG_WARN("send partial Ethernet packet (%d bytes of %zu) on %s",
447                   (int) n_bytes, buffer->size, netdev->name);
448         return EMSGSIZE;
449     } else {
450         return 0;
451     }
452 }
453
454 /* Registers with the poll loop to wake up from the next call to poll_block()
455  * when the packet transmission queue has sufficient room to transmit a packet
456  * with netdev_send().
457  *
458  * The kernel maintains a packet transmission queue, so the client is not
459  * expected to do additional queuing of packets.  Thus, this function is
460  * unlikely to ever be used.  It is included for completeness. */
461 void
462 netdev_send_wait(struct netdev *netdev)
463 {
464     poll_fd_wait(netdev->fd, POLLOUT);
465 }
466
467 /* Returns a pointer to 'netdev''s MAC address.  The caller must not modify or
468  * free the returned buffer. */
469 const uint8_t *
470 netdev_get_etheraddr(const struct netdev *netdev)
471 {
472     return netdev->etheraddr;
473 }
474
475 /* Returns the name of the network device that 'netdev' represents,
476  * e.g. "eth0".  The caller must not modify or free the returned string. */
477 const char *
478 netdev_get_name(const struct netdev *netdev)
479 {
480     return netdev->name;
481 }
482
483 /* Returns the maximum size of transmitted (and received) packets on 'netdev',
484  * in bytes, not including the hardware header; thus, this is typically 1500
485  * bytes for Ethernet devices. */
486 int
487 netdev_get_mtu(const struct netdev *netdev) 
488 {
489     return netdev->mtu;
490 }
491
492 /* Returns the current speed of the network device that 'netdev' represents, in
493  * megabits per second, or 0 if the speed is unknown. */
494 int
495 netdev_get_speed(const struct netdev *netdev) 
496 {
497     return netdev->speed;
498 }
499
500 /* Checks the link status.  Returns 1 or 0 to indicate the link is active 
501  * or not, respectively.  Any other return value indicates an error. */
502 int
503 netdev_get_link_status(const struct netdev *netdev) 
504 {
505     struct ifreq ifr;
506     struct ethtool_value edata;
507
508     memset(&ifr, 0, sizeof ifr);
509     strncpy(ifr.ifr_name, netdev->name, sizeof ifr.ifr_name);
510     ifr.ifr_data = (caddr_t) &edata;
511
512     memset(&edata, 0, sizeof edata);
513     edata.cmd = ETHTOOL_GLINK;
514     if (ioctl(netdev->fd, SIOCETHTOOL, &ifr) == 0) {
515         if (edata.data) {
516             return 1;
517         } else {
518             return 0;
519         }
520     }
521
522     return -1;
523 }
524
525 /* Returns the features supported by 'netdev', as a bitmap of bits from enum
526  * ofp_phy_port, in host byte order. */
527 uint32_t
528 netdev_get_features(const struct netdev *netdev) 
529 {
530     return netdev->features;
531 }
532
533 /* If 'netdev' has an assigned IPv4 address, sets '*in4' to that address (if
534  * 'in4' is non-null) and returns true.  Otherwise, returns false. */
535 bool
536 netdev_get_in4(const struct netdev *netdev, struct in_addr *in4)
537 {
538     struct ifreq ifr;
539     struct in_addr ip = { INADDR_ANY };
540
541     strncpy(ifr.ifr_name, netdev->name, sizeof ifr.ifr_name);
542     ifr.ifr_addr.sa_family = AF_INET;
543     if (ioctl(af_inet_sock, SIOCGIFADDR, &ifr) == 0) {
544         struct sockaddr_in *sin = (struct sockaddr_in *) &ifr.ifr_addr;
545         ip = sin->sin_addr;
546     } else {
547         VLOG_DBG("%s: ioctl(SIOCGIFADDR) failed: %s",
548                  netdev->name, strerror(errno));
549     }
550     if (in4) {
551         *in4 = ip;
552     }
553     return ip.s_addr != INADDR_ANY;
554 }
555
556 static void
557 make_in4_sockaddr(struct sockaddr *sa, struct in_addr addr)
558 {
559     struct sockaddr_in sin;
560     memset(&sin, 0, sizeof sin);
561     sin.sin_family = AF_INET;
562     sin.sin_addr = addr;
563     sin.sin_port = 0;
564
565     memset(sa, 0, sizeof *sa);
566     memcpy(sa, &sin, sizeof sin);
567 }
568
569 static int
570 do_set_addr(struct netdev *netdev, int sock,
571             int ioctl_nr, const char *ioctl_name, struct in_addr addr)
572 {
573     struct ifreq ifr;
574     int error;
575
576     strncpy(ifr.ifr_name, netdev->name, sizeof ifr.ifr_name);
577     make_in4_sockaddr(&ifr.ifr_addr, addr);
578     error = ioctl(sock, ioctl_nr, &ifr) < 0 ? errno : 0;
579     if (error) {
580         VLOG_WARN("ioctl(%s): %s", ioctl_name, strerror(error));
581     }
582     return error;
583 }
584
585 /* Assigns 'addr' as 'netdev''s IPv4 address and 'mask' as its netmask.  If
586  * 'addr' is INADDR_ANY, 'netdev''s IPv4 address is cleared.  Returns a
587  * positive errno value. */
588 int
589 netdev_set_in4(struct netdev *netdev, struct in_addr addr, struct in_addr mask)
590 {
591     int error;
592
593     error = do_set_addr(netdev, af_inet_sock,
594                         SIOCSIFADDR, "SIOCSIFADDR", addr);
595     if (!error && addr.s_addr != INADDR_ANY) {
596         error = do_set_addr(netdev, af_inet_sock,
597                             SIOCSIFNETMASK, "SIOCSIFNETMASK", mask);
598     }
599     return error;
600 }
601
602 /* Adds 'router' as a default gateway for 'netdev''s IP address. */
603 int
604 netdev_add_router(struct netdev *netdev, struct in_addr router)
605 {
606     struct in_addr any = { INADDR_ANY };
607     struct rtentry rt;
608     int error;
609
610     memset(&rt, 0, sizeof rt);
611     make_in4_sockaddr(&rt.rt_dst, any);
612     make_in4_sockaddr(&rt.rt_gateway, router);
613     make_in4_sockaddr(&rt.rt_genmask, any);
614     rt.rt_flags = RTF_UP | RTF_GATEWAY;
615     error = ioctl(af_inet_sock, SIOCADDRT, &rt) < 0 ? errno : 0;
616     if (error) {
617         VLOG_WARN("ioctl(SIOCADDRT): %s", strerror(error));
618     }
619     return error;
620 }
621
622 /* If 'netdev' has an assigned IPv6 address, sets '*in6' to that address (if
623  * 'in6' is non-null) and returns true.  Otherwise, returns false. */
624 bool
625 netdev_get_in6(const struct netdev *netdev, struct in6_addr *in6)
626 {
627     if (in6) {
628         *in6 = netdev->in6;
629     }
630     return memcmp(&netdev->in6, &in6addr_any, sizeof netdev->in6) != 0;
631 }
632
633 /* Obtains the current flags for 'netdev' and stores them into '*flagsp'.
634  * Returns 0 if successful, otherwise a positive errno value. */
635 int
636 netdev_get_flags(const struct netdev *netdev, enum netdev_flags *flagsp)
637 {
638     int error, flags;
639
640     error = get_flags(netdev, &flags);
641     if (error) {
642         return error;
643     }
644
645     *flagsp = 0;
646     if (flags & IFF_UP) {
647         *flagsp |= NETDEV_UP;
648     }
649     if (flags & IFF_PROMISC) {
650         *flagsp |= NETDEV_PROMISC;
651     }
652     return 0;
653 }
654
655 static int
656 nd_to_iff_flags(enum netdev_flags nd)
657 {
658     int iff = 0;
659     if (nd & NETDEV_UP) {
660         iff |= IFF_UP;
661     }
662     if (nd & NETDEV_PROMISC) {
663         iff |= IFF_PROMISC;
664     }
665     return iff;
666 }
667
668 /* On 'netdev', turns off the flags in 'off' and then turns on the flags in
669  * 'on'.  If 'permanent' is true, the changes will persist; otherwise, they
670  * will be reverted when 'netdev' is closed or the program exits.  Returns 0 if
671  * successful, otherwise a positive errno value. */
672 static int
673 do_update_flags(struct netdev *netdev, enum netdev_flags off,
674                 enum netdev_flags on, bool permanent)
675 {
676     int old_flags, new_flags;
677     int error;
678
679     error = get_flags(netdev, &old_flags);
680     if (error) {
681         return error;
682     }
683
684     new_flags = (old_flags & ~nd_to_iff_flags(off)) | nd_to_iff_flags(on);
685     if (!permanent) {
686         netdev->changed_flags |= new_flags ^ old_flags; 
687     }
688     if (new_flags != old_flags) {
689         error = set_flags(netdev, new_flags);
690     }
691     return error;
692 }
693
694 /* Sets the flags for 'netdev' to 'flags'.
695  * If 'permanent' is true, the changes will persist; otherwise, they
696  * will be reverted when 'netdev' is closed or the program exits.
697  * Returns 0 if successful, otherwise a positive errno value. */
698 int
699 netdev_set_flags(struct netdev *netdev, enum netdev_flags flags,
700                  bool permanent)
701 {
702     return do_update_flags(netdev, -1, flags, permanent);
703 }
704
705 /* Turns on the specified 'flags' on 'netdev'.
706  * If 'permanent' is true, the changes will persist; otherwise, they
707  * will be reverted when 'netdev' is closed or the program exits.
708  * Returns 0 if successful, otherwise a positive errno value. */
709 int
710 netdev_turn_flags_on(struct netdev *netdev, enum netdev_flags flags,
711                      bool permanent)
712 {
713     return do_update_flags(netdev, 0, flags, permanent);
714 }
715
716 /* Turns off the specified 'flags' on 'netdev'.
717  * If 'permanent' is true, the changes will persist; otherwise, they
718  * will be reverted when 'netdev' is closed or the program exits.
719  * Returns 0 if successful, otherwise a positive errno value. */
720 int
721 netdev_turn_flags_off(struct netdev *netdev, enum netdev_flags flags,
722                       bool permanent)
723 {
724     return do_update_flags(netdev, flags, 0, permanent);
725 }
726
727 /* Looks up the ARP table entry for 'ip' on 'netdev'.  If one exists and can be
728  * successfully retrieved, it stores the corresponding MAC address in 'mac' and
729  * returns 0.  Otherwise, it returns a positive errno value; in particular,
730  * ENXIO indicates that there is not ARP table entry for 'ip' on 'netdev'. */
731 int
732 netdev_arp_lookup(const struct netdev *netdev,
733                   uint32_t ip, uint8_t mac[ETH_ADDR_LEN]) 
734 {
735     struct arpreq r;
736     struct sockaddr_in *pa;
737     int retval;
738
739     memset(&r, 0, sizeof r);
740     pa = (struct sockaddr_in *) &r.arp_pa;
741     pa->sin_family = AF_INET;
742     pa->sin_addr.s_addr = ip;
743     pa->sin_port = 0;
744     r.arp_ha.sa_family = ARPHRD_ETHER;
745     r.arp_flags = 0;
746     strncpy(r.arp_dev, netdev->name, sizeof r.arp_dev);
747     retval = ioctl(af_inet_sock, SIOCGARP, &r) < 0 ? errno : 0;
748     if (!retval) {
749         memcpy(mac, r.arp_ha.sa_data, ETH_ADDR_LEN);
750     } else if (retval != ENXIO) {
751         VLOG_WARN("%s: could not look up ARP entry for "IP_FMT": %s",
752                   netdev->name, IP_ARGS(&ip), strerror(retval));
753     }
754     return retval;
755 }
756 \f
757 static void restore_all_flags(void *aux);
758
759 /* Set up a signal hook to restore network device flags on program
760  * termination.  */
761 static void
762 init_netdev(void)
763 {
764     static bool inited;
765     if (!inited) {
766         inited = true;
767         fatal_signal_add_hook(restore_all_flags, NULL);
768         af_inet_sock = socket(AF_INET, SOCK_DGRAM, 0);
769         if (af_inet_sock < 0) {
770             fatal(errno, "socket(AF_INET)");
771         }
772     }
773 }
774
775 /* Restore the network device flags on 'netdev' to those that were active
776  * before we changed them.  Returns 0 if successful, otherwise a positive
777  * errno value.
778  *
779  * To avoid reentry, the caller must ensure that fatal signals are blocked. */
780 static int
781 restore_flags(struct netdev *netdev)
782 {
783     struct ifreq ifr;
784     int restore_flags;
785
786     /* Get current flags. */
787     strncpy(ifr.ifr_name, netdev->name, sizeof ifr.ifr_name);
788     if (ioctl(netdev->fd, SIOCGIFFLAGS, &ifr) < 0) {
789         return errno;
790     }
791
792     /* Restore flags that we might have changed, if necessary. */
793     restore_flags = netdev->changed_flags & (IFF_PROMISC | IFF_UP);
794     if ((ifr.ifr_flags ^ netdev->save_flags) & restore_flags) {
795         ifr.ifr_flags &= ~restore_flags;
796         ifr.ifr_flags |= netdev->save_flags & restore_flags;
797         if (ioctl(netdev->fd, SIOCSIFFLAGS, &ifr) < 0) {
798             return errno;
799         }
800     }
801
802     return 0;
803 }
804
805 /* Retores all the flags on all network devices that we modified.  Called from
806  * a signal handler, so it does not attempt to report error conditions. */
807 static void
808 restore_all_flags(void *aux UNUSED)
809 {
810     struct netdev *netdev;
811     LIST_FOR_EACH (netdev, struct netdev, node, &netdev_list) {
812         restore_flags(netdev);
813     }
814 }
815
816 static int
817 get_flags(const struct netdev *netdev, int *flags)
818 {
819     struct ifreq ifr;
820     strncpy(ifr.ifr_name, netdev->name, sizeof ifr.ifr_name);
821     if (ioctl(netdev->fd, SIOCGIFFLAGS, &ifr) < 0) {
822         VLOG_ERR("ioctl(SIOCGIFFLAGS) on %s device failed: %s",
823                  netdev->name, strerror(errno));
824         return errno;
825     }
826     *flags = ifr.ifr_flags;
827     return 0;
828 }
829
830 static int
831 set_flags(struct netdev *netdev, int flags)
832 {
833     struct ifreq ifr;
834     strncpy(ifr.ifr_name, netdev->name, sizeof ifr.ifr_name);
835     ifr.ifr_flags = flags;
836     if (ioctl(netdev->fd, SIOCSIFFLAGS, &ifr) < 0) {
837         VLOG_ERR("ioctl(SIOCSIFFLAGS) on %s device failed: %s",
838                  netdev->name, strerror(errno));
839         return errno;
840     }
841     return 0;
842 }