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