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