Expose device IP addresses through netdev.
[sliver-openvswitch.git] / lib / netdev.c
1 /* Copyright (c) 2008 The Board of Trustees of The Leland Stanford
2  * Junior University
3  * 
4  * We are making the OpenFlow specification and associated documentation
5  * (Software) available for public use and benefit with the expectation
6  * that others will use, modify and enhance the Software and contribute
7  * those enhancements back to the community. However, since we would
8  * like to make the Software available for broadest use, with as few
9  * restrictions as possible permission is hereby granted, free of
10  * charge, to any person obtaining a copy of this Software to deal in
11  * the Software under the copyrights without restriction, including
12  * without limitation the rights to use, copy, modify, merge, publish,
13  * distribute, sublicense, and/or sell copies of the Software, and to
14  * permit persons to whom the Software is furnished to do so, subject to
15  * the following conditions:
16  * 
17  * The above copyright notice and this permission notice shall be
18  * included in all copies or substantial portions of the Software.
19  * 
20  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
21  * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
22  * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
23  * NONINFRINGEMENT.  IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
24  * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
25  * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
26  * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
27  * SOFTWARE.
28  * 
29  * The name and trademarks of copyright holder(s) may NOT be used in
30  * advertising or publicity pertaining to the Software or any
31  * derivatives without specific, written prior permission.
32  */
33
34 #include "netdev.h"
35
36 #include <assert.h>
37 #include <errno.h>
38 #include <arpa/inet.h>
39 #include <inttypes.h>
40 #include <linux/types.h>
41 #include <linux/ethtool.h>
42 #include <linux/sockios.h>
43 #include <sys/types.h>
44 #include <sys/ioctl.h>
45 #include <sys/socket.h>
46 #include <netpacket/packet.h>
47 #include <net/ethernet.h>
48 #include <net/if.h>
49 #include <net/if_arp.h>
50 #include <net/if_packet.h>
51 #include <netinet/in.h>
52 #include <stdlib.h>
53 #include <string.h>
54 #include <unistd.h>
55
56 #include "list.h"
57 #include "fatal-signal.h"
58 #include "buffer.h"
59 #include "openflow.h"
60 #include "packets.h"
61 #include "poll-loop.h"
62
63 #define THIS_MODULE VLM_netdev
64 #include "vlog.h"
65
66 struct netdev {
67     struct list node;
68     char *name;
69     int fd;
70     uint8_t etheraddr[ETH_ADDR_LEN];
71     int speed;
72     int mtu;
73     uint32_t features;
74     struct in_addr in4;
75     struct in6_addr in6;
76     int save_flags;
77 };
78
79 static struct list netdev_list = LIST_INITIALIZER(&netdev_list);
80
81 static void init_netdev(void);
82 static int restore_flags(struct netdev *netdev);
83
84 /* Obtains the IPv4 address for 'name' into 'in4'.  Returns true if
85  * successful. */
86 static bool
87 get_ipv4_address(const char *name, struct in_addr *in4)
88 {
89     int sock;
90     struct ifreq ifr;
91
92     sock = socket(AF_INET, SOCK_DGRAM, 0);
93     if (sock < 0) {
94         VLOG_WARN("socket(AF_INET): %s", strerror(errno));
95         return false;
96     }
97
98     strncpy(ifr.ifr_name, name, sizeof ifr.ifr_name);
99     ifr.ifr_addr.sa_family = AF_INET;
100     if (ioctl(sock, SIOCGIFADDR, &ifr) == 0) {
101         struct sockaddr_in *sin = (struct sockaddr_in *) &ifr.ifr_addr;
102         *in4 = sin->sin_addr;
103     } else {
104         in4->s_addr = INADDR_ANY;
105     }
106
107     close(sock);
108     return true;
109 }
110
111 /* Obtains the IPv6 address for 'name' into 'in6'. */
112 static void
113 get_ipv6_address(const char *name, struct in6_addr *in6)
114 {
115     FILE *file;
116     char line[128];
117
118     file = fopen("/proc/net/if_inet6", "r");
119     if (file == NULL) {
120         /* This most likely indicates that the host doesn't have IPv6 support,
121          * so it's not really a failure condition.*/
122         *in6 = in6addr_any;
123         return;
124     }
125
126     while (fgets(line, sizeof line, file)) {
127         uint8_t *s6 = in6->s6_addr;
128         char ifname[16 + 1];
129
130 #define X8 "%2"SCNx8
131         if (sscanf(line, " "X8 X8 X8 X8 X8 X8 X8 X8 X8 X8 X8 X8 X8 X8 X8 X8
132                    "%*x %*x %*x %*x %16s\n",
133                    &s6[0], &s6[1], &s6[2], &s6[3],
134                    &s6[4], &s6[5], &s6[6], &s6[7],
135                    &s6[8], &s6[9], &s6[10], &s6[11],
136                    &s6[12], &s6[13], &s6[14], &s6[15],
137                    ifname) == 17
138             && !strcmp(name, ifname))
139         {
140             return;
141         }
142     }
143     *in6 = in6addr_any;
144
145     fclose(file);
146 }
147
148 static void
149 do_ethtool(struct netdev *netdev) 
150 {
151     struct ifreq ifr;
152     struct ethtool_cmd ecmd;
153
154     netdev->speed = 0;
155     netdev->features = 0;
156
157     memset(&ifr, 0, sizeof ifr);
158     strncpy(ifr.ifr_name, netdev->name, sizeof ifr.ifr_name);
159     ifr.ifr_data = (caddr_t) &ecmd;
160
161     memset(&ecmd, 0, sizeof ecmd);
162     ecmd.cmd = ETHTOOL_GSET;
163     if (ioctl(netdev->fd, SIOCETHTOOL, &ifr) == 0) {
164         if (ecmd.supported & SUPPORTED_10baseT_Half) {
165             netdev->features |= OFPPF_10MB_HD;
166         }
167         if (ecmd.supported & SUPPORTED_10baseT_Full) {
168             netdev->features |= OFPPF_10MB_FD;
169         }
170         if (ecmd.supported & SUPPORTED_100baseT_Half)  {
171             netdev->features |= OFPPF_100MB_HD;
172         }
173         if (ecmd.supported & SUPPORTED_100baseT_Full) {
174             netdev->features |= OFPPF_100MB_FD;
175         }
176         if (ecmd.supported & SUPPORTED_1000baseT_Half) {
177             netdev->features |= OFPPF_1GB_HD;
178         }
179         if (ecmd.supported & SUPPORTED_1000baseT_Full) {
180             netdev->features |= OFPPF_1GB_FD;
181         }
182         /* 10Gbps half-duplex doesn't exist... */
183         if (ecmd.supported & SUPPORTED_10000baseT_Full) {
184             netdev->features |= OFPPF_10GB_FD;
185         }
186
187         switch (ecmd.speed) {
188         case SPEED_10:
189             netdev->speed = 10;
190             break;
191
192         case SPEED_100:
193             netdev->speed = 100;
194             break;
195
196         case SPEED_1000:
197             netdev->speed = 1000;
198             break;
199
200         case SPEED_2500:
201             netdev->speed = 2500;
202             break;
203
204         case SPEED_10000:
205             netdev->speed = 10000;
206             break;
207         }
208     } else {
209         VLOG_DBG("ioctl(SIOCETHTOOL) failed: %s", strerror(errno));
210     }
211 }
212
213 /* Opens the network device named 'name' (e.g. "eth0") and returns zero if
214  * successful, otherwise a positive errno value.  On success, sets '*netdev'
215  * to the new network device, otherwise to null. */
216 int
217 netdev_open(const char *name, struct netdev **netdev_)
218 {
219     int fd;
220     struct sockaddr sa;
221     struct ifreq ifr;
222     unsigned int ifindex;
223     socklen_t rcvbuf_len;
224     size_t rcvbuf;
225     uint8_t etheraddr[ETH_ADDR_LEN];
226     struct in_addr in4;
227     struct in6_addr in6;
228     int mtu;
229     int error;
230     struct netdev *netdev;
231
232     *netdev_ = NULL;
233     init_netdev();
234
235     /* Create raw socket.
236      *
237      * We have to use SOCK_PACKET, despite its deprecation, because only
238      * SOCK_PACKET lets us set the hardware source address of outgoing
239      * packets. */
240     fd = socket(PF_PACKET, SOCK_PACKET, htons(ETH_P_ALL));
241     if (fd < 0) {
242         return errno;
243     }
244
245     /* Bind to specific ethernet device. */
246     memset(&sa, 0, sizeof sa);
247     sa.sa_family = AF_UNSPEC;
248     strncpy((char *) sa.sa_data, name, sizeof sa.sa_data);
249     if (bind(fd, &sa, sizeof sa) < 0) {
250         VLOG_ERR("bind to %s failed: %s", name, strerror(errno));
251         goto error;
252     }
253
254     /* Between the socket() and bind() calls above, the socket receives all
255      * packets on all system interfaces.  We do not want to receive that
256      * data, but there is no way to avoid it.  So we must now drain out the
257      * receive queue.  There is no way to know how long the receive queue is,
258      * but we know that the total number of bytes queued does not exceed the
259      * receive buffer size, so we pull packets until none are left or we've
260      * read that many bytes. */
261     rcvbuf_len = sizeof rcvbuf;
262     if (getsockopt(fd, SOL_SOCKET, SO_RCVBUF, &rcvbuf, &rcvbuf_len) < 0) {
263         VLOG_ERR("getsockopt(SO_RCVBUF) on %s device failed: %s",
264                  name, strerror(errno));
265         goto error;
266     }
267     while (rcvbuf > 0) {
268         char buffer;
269         ssize_t n_bytes = recv(fd, &buffer, 1, MSG_TRUNC | MSG_DONTWAIT);
270         if (n_bytes <= 0) {
271             break;
272         }
273         rcvbuf -= n_bytes;
274     }
275
276     /* Get ethernet device index. */
277     strncpy(ifr.ifr_name, name, sizeof ifr.ifr_name);
278     if (ioctl(fd, SIOCGIFINDEX, &ifr) < 0) {
279         VLOG_ERR("ioctl(SIOCGIFINDEX) on %s device failed: %s",
280                  name, strerror(errno));
281         goto error;
282     }
283     ifindex = ifr.ifr_ifindex;
284
285     /* Get MAC address. */
286     if (ioctl(fd, SIOCGIFHWADDR, &ifr) < 0) {
287         VLOG_ERR("ioctl(SIOCGIFHWADDR) on %s device failed: %s",
288                  name, strerror(errno));
289         goto error;
290     }
291     if (ifr.ifr_hwaddr.sa_family != AF_UNSPEC
292         && ifr.ifr_hwaddr.sa_family != ARPHRD_ETHER) {
293         VLOG_WARN("%s device has unknown hardware address family %d",
294                   name, (int) ifr.ifr_hwaddr.sa_family);
295     }
296     memcpy(etheraddr, ifr.ifr_hwaddr.sa_data, sizeof etheraddr);
297
298     /* Get MTU. */
299     if (ioctl(fd, SIOCGIFMTU, &ifr) < 0) {
300         VLOG_ERR("ioctl(SIOCGIFMTU) on %s device failed: %s",
301                  name, strerror(errno));
302         goto error;
303     }
304     mtu = ifr.ifr_mtu;
305
306     if (!get_ipv4_address(name, &in4)) {
307         goto error;
308     }
309     get_ipv6_address(name, &in6);
310
311     /* Allocate network device. */
312     netdev = xmalloc(sizeof *netdev);
313     netdev->name = xstrdup(name);
314     netdev->fd = fd;
315     memcpy(netdev->etheraddr, etheraddr, sizeof etheraddr);
316     netdev->mtu = mtu;
317     netdev->in4 = in4;
318     netdev->in6 = in6;
319
320     /* Get speed, features. */
321     do_ethtool(netdev);
322
323     /* Save flags to restore at close or exit. */
324     if (ioctl(fd, SIOCGIFFLAGS, &ifr) < 0) {
325         VLOG_ERR("ioctl(SIOCGIFFLAGS) on %s device failed: %s",
326                  name, strerror(errno));
327         goto error;
328     }
329     netdev->save_flags = ifr.ifr_flags;
330     fatal_signal_block();
331     list_push_back(&netdev_list, &netdev->node);
332     fatal_signal_unblock();
333
334     /* Bring up interface and set promiscuous mode. */
335     ifr.ifr_flags |= IFF_PROMISC | IFF_UP;
336     if (ioctl(fd, SIOCSIFFLAGS, &ifr) < 0) {
337         error = errno;
338         VLOG_ERR("failed to set promiscuous mode on %s device: %s",
339                  name, strerror(errno));
340         netdev_close(netdev);
341         return error;
342     }
343
344     /* Success! */
345     *netdev_ = netdev;
346     return 0;
347
348 error:
349     error = errno;
350     close(fd);
351     return error;
352 }
353
354 /* Closes and destroys 'netdev'. */
355 void
356 netdev_close(struct netdev *netdev)
357 {
358     if (netdev) {
359         /* Bring down interface and drop promiscuous mode, if we brought up
360          * the interface or enabled promiscuous mode. */
361         int error;
362         fatal_signal_block();
363         error = restore_flags(netdev);
364         list_remove(&netdev->node);
365         fatal_signal_unblock();
366         if (error) {
367             VLOG_WARN("failed to restore network device flags on %s: %s",
368                       netdev->name, strerror(error));
369         }
370
371         /* Free. */
372         free(netdev->name);
373         close(netdev->fd);
374         free(netdev);
375     }
376 }
377
378 /* Pads 'buffer' out with zero-bytes to the minimum valid length of an
379  * Ethernet packet, if necessary.  */
380 static void
381 pad_to_minimum_length(struct buffer *buffer)
382 {
383     if (buffer->size < ETH_TOTAL_MIN) {
384         size_t shortage = ETH_TOTAL_MIN - buffer->size;
385         memset(buffer_put_uninit(buffer, shortage), 0, shortage);
386     }
387 }
388
389 /* Attempts to receive a packet from 'netdev' into 'buffer', which the caller
390  * must have initialized with sufficient room for the packet.  The space
391  * required to receive any packet is ETH_HEADER_LEN bytes, plus VLAN_HEADER_LEN
392  * bytes, plus the device's MTU (which may be retrieved via netdev_get_mtu()).
393  * (Some devices do not allow for a VLAN header, in which case VLAN_HEADER_LEN
394  * need not be included.)
395  *
396  * If a packet is successfully retrieved, returns 0.  In this case 'buffer' is
397  * guaranteed to contain at least ETH_TOTAL_MIN bytes.  Otherwise, returns a
398  * positive errno value.  Returns EAGAIN immediately if no packet is ready to
399  * be returned.
400  */
401 int
402 netdev_recv(struct netdev *netdev, struct buffer *buffer)
403 {
404     ssize_t n_bytes;
405
406     assert(buffer->size == 0);
407     assert(buffer_tailroom(buffer) >= ETH_TOTAL_MIN);
408     do {
409         n_bytes = recv(netdev->fd,
410                        buffer_tail(buffer), buffer_tailroom(buffer),
411                        MSG_DONTWAIT);
412     } while (n_bytes < 0 && errno == EINTR);
413     if (n_bytes < 0) {
414         if (errno != EAGAIN) {
415             VLOG_WARN("error receiving Ethernet packet on %s: %s",
416                       strerror(errno), netdev->name);
417         }
418         return errno;
419     } else {
420         buffer->size += n_bytes;
421
422         /* When the kernel internally sends out an Ethernet frame on an
423          * interface, it gives us a copy *before* padding the frame to the
424          * minimum length.  Thus, when it sends out something like an ARP
425          * request, we see a too-short frame.  So pad it out to the minimum
426          * length. */
427         pad_to_minimum_length(buffer);
428         return 0;
429     }
430 }
431
432 /* Registers with the poll loop to wake up from the next call to poll_block()
433  * when a packet is ready to be received with netdev_recv() on 'netdev'. */
434 void
435 netdev_recv_wait(struct netdev *netdev)
436 {
437     poll_fd_wait(netdev->fd, POLLIN);
438 }
439
440 /* Sends 'buffer' on 'netdev'.  Returns 0 if successful, otherwise a positive
441  * errno value.  Returns EAGAIN without blocking if the packet cannot be queued
442  * immediately.  Returns EMSGSIZE if a partial packet was transmitted or if
443  * the packet is too big to transmit on the device.
444  *
445  * The kernel maintains a packet transmission queue, so the caller is not
446  * expected to do additional queuing of packets. */
447 int
448 netdev_send(struct netdev *netdev, struct buffer *buffer)
449 {
450     ssize_t n_bytes;
451     const struct eth_header *eh;
452     struct sockaddr_pkt spkt;
453
454     /* Ensure packet is long enough.  (Although all incoming packets are at
455      * least ETH_TOTAL_MIN bytes long, we could have trimmed some data off a
456      * minimum-size packet, e.g. by dropping a vlan header.)
457      *
458      * The kernel does not require this, but it ensures that we always access
459      * valid memory in grabbing the sockaddr below. */
460     pad_to_minimum_length(buffer);
461
462     /* Construct packet sockaddr, which SOCK_PACKET requires. */
463     spkt.spkt_family = AF_PACKET;
464     strncpy((char *) spkt.spkt_device, netdev->name, sizeof spkt.spkt_device);
465     eh = buffer_at_assert(buffer, 0, sizeof *eh);
466     spkt.spkt_protocol = eh->eth_type;
467
468     do {
469         n_bytes = sendto(netdev->fd, buffer->data, buffer->size, 0,
470                          (const struct sockaddr *) &spkt, sizeof spkt);
471     } while (n_bytes < 0 && errno == EINTR);
472
473     if (n_bytes < 0) {
474         /* The Linux AF_PACKET implementation never blocks waiting for room
475          * for packets, instead returning ENOBUFS.  Translate this into EAGAIN
476          * for the caller. */
477         if (errno == ENOBUFS) {
478             return EAGAIN;
479         } else if (errno != EAGAIN) {
480             VLOG_WARN("error sending Ethernet packet on %s: %s",
481                       netdev->name, strerror(errno));
482         }
483         return errno;
484     } else if (n_bytes != buffer->size) {
485         VLOG_WARN("send partial Ethernet packet (%d bytes of %zu) on %s",
486                   (int) n_bytes, buffer->size, netdev->name);
487         return EMSGSIZE;
488     } else {
489         return 0;
490     }
491 }
492
493 /* Registers with the poll loop to wake up from the next call to poll_block()
494  * when the packet transmission queue has sufficient room to transmit a packet
495  * with netdev_send().
496  *
497  * The kernel maintains a packet transmission queue, so the client is not
498  * expected to do additional queuing of packets.  Thus, this function is
499  * unlikely to ever be used.  It is included for completeness. */
500 void
501 netdev_send_wait(struct netdev *netdev)
502 {
503     poll_fd_wait(netdev->fd, POLLOUT);
504 }
505
506 /* Returns a pointer to 'netdev''s MAC address.  The caller must not modify or
507  * free the returned buffer. */
508 const uint8_t *
509 netdev_get_etheraddr(const struct netdev *netdev)
510 {
511     return netdev->etheraddr;
512 }
513
514 /* Returns the name of the network device that 'netdev' represents,
515  * e.g. "eth0".  The caller must not modify or free the returned string. */
516 const char *
517 netdev_get_name(const struct netdev *netdev)
518 {
519     return netdev->name;
520 }
521
522 /* Returns the maximum size of transmitted (and received) packets on 'netdev',
523  * in bytes, not including the hardware header; thus, this is typically 1500
524  * bytes for Ethernet devices. */
525 int
526 netdev_get_mtu(const struct netdev *netdev) 
527 {
528     return netdev->mtu;
529 }
530
531 /* Returns the current speed of the network device that 'netdev' represents, in
532  * megabits per second, or 0 if the speed is unknown. */
533 int
534 netdev_get_speed(const struct netdev *netdev) 
535 {
536     return netdev->speed;
537 }
538
539 /* Returns the features supported by 'netdev', as a bitmap of bits from enum
540  * ofp_phy_port, in host byte order. */
541 uint32_t
542 netdev_get_features(const struct netdev *netdev) 
543 {
544     return netdev->features;
545 }
546
547 /* If 'netdev' has an assigned IPv4 address, sets '*in4' to that address and
548  * returns true.  Otherwise, returns false. */
549 bool
550 netdev_get_in4(const struct netdev *netdev, struct in_addr *in4)
551 {
552     *in4 = netdev->in4;
553     return in4->s_addr != INADDR_ANY;
554 }
555
556 /* If 'netdev' has an assigned IPv6 address, sets '*in6' to that address and
557  * returns true.  Otherwise, returns false. */
558 bool
559 netdev_get_in6(const struct netdev *netdev, struct in6_addr *in6)
560 {
561     *in6 = netdev->in6;
562     return memcmp(in6, &in6addr_any, sizeof *in6) != 0;
563 }
564 \f
565 static void restore_all_flags(void *aux);
566
567 /* Set up a signal hook to restore network device flags on program
568  * termination.  */
569 static void
570 init_netdev(void)
571 {
572     static bool inited;
573     if (!inited) {
574         inited = true;
575         fatal_signal_add_hook(restore_all_flags, NULL);
576     }
577 }
578
579 /* Restore the network device flags on 'netdev' to those that were active
580  * before we changed them.  Returns 0 if successful, otherwise a positive
581  * errno value.
582  *
583  * To avoid reentry, the caller must ensure that fatal signals are blocked. */
584 static int
585 restore_flags(struct netdev *netdev)
586 {
587     struct ifreq ifr;
588
589     /* Get current flags. */
590     strncpy(ifr.ifr_name, netdev->name, sizeof ifr.ifr_name);
591     if (ioctl(netdev->fd, SIOCGIFFLAGS, &ifr) < 0) {
592         return errno;
593     }
594
595     /* Restore flags that we might have changed, if necessary. */
596     if ((ifr.ifr_flags ^ netdev->save_flags) & (IFF_PROMISC | IFF_UP)) {
597         ifr.ifr_flags &= ~(IFF_PROMISC | IFF_UP);
598         ifr.ifr_flags |= netdev->save_flags & (IFF_PROMISC | IFF_UP);
599         if (ioctl(netdev->fd, SIOCSIFFLAGS, &ifr) < 0) {
600             return errno;
601         }
602     }
603
604     return 0;
605 }
606
607 /* Retores all the flags on all network devices that we modified.  Called from
608  * a signal handler, so it does not attempt to report error conditions. */
609 static void
610 restore_all_flags(void *aux UNUSED)
611 {
612     struct netdev *netdev;
613     LIST_FOR_EACH (netdev, struct netdev, node, &netdev_list) {
614         restore_flags(netdev);
615     }
616 }