Move netdev from switch to lib.
[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     int save_flags;
75 };
76
77 static struct list netdev_list = LIST_INITIALIZER(&netdev_list);
78
79 static void init_netdev(void);
80 static int restore_flags(struct netdev *netdev);
81
82 /* Check whether device NAME has an IPv4 address assigned to it and, if so, log
83  * an error. */
84 static void
85 check_ipv4_address(const char *name)
86 {
87     int sock;
88     struct ifreq ifr;
89
90     sock = socket(AF_INET, SOCK_DGRAM, 0);
91     if (sock < 0) {
92         VLOG_WARN("socket(AF_INET): %s", strerror(errno));
93         return;
94     }
95
96     strncpy(ifr.ifr_name, name, sizeof ifr.ifr_name);
97     ifr.ifr_addr.sa_family = AF_INET;
98     if (ioctl(sock, SIOCGIFADDR, &ifr) == 0) {
99         VLOG_ERR("%s device has assigned IP address %s", name,
100                  inet_ntoa(((struct sockaddr_in*) &ifr.ifr_addr)->sin_addr));
101     }
102
103     close(sock);
104 }
105
106 /* Check whether device NAME has an IPv6 address assigned to it and, if so, log
107  * an error. */
108 static void
109 check_ipv6_address(const char *name)
110 {
111     FILE *file;
112     char line[128];
113
114     file = fopen("/proc/net/if_inet6", "r");
115     if (file == NULL) {
116         return;
117     }
118
119     while (fgets(line, sizeof line, file)) {
120         struct in6_addr in6;
121         uint8_t *s6 = in6.s6_addr;
122         char ifname[16 + 1];
123
124 #define X8 "%2"SCNx8
125         if (sscanf(line, " "X8 X8 X8 X8 X8 X8 X8 X8 X8 X8 X8 X8 X8 X8 X8 X8
126                    "%*x %*x %*x %*x %16s\n",
127                    &s6[0], &s6[1], &s6[2], &s6[3],
128                    &s6[4], &s6[5], &s6[6], &s6[7],
129                    &s6[8], &s6[9], &s6[10], &s6[11],
130                    &s6[12], &s6[13], &s6[14], &s6[15],
131                    ifname) == 17
132             && !strcmp(name, ifname))
133         {
134             char in6_name[INET6_ADDRSTRLEN + 1];
135             inet_ntop(AF_INET6, &in6, in6_name, sizeof in6_name);
136             VLOG_ERR("%s device has assigned IPv6 address %s",
137                      name, in6_name);
138         }
139     }
140
141     fclose(file);
142 }
143
144 static void
145 do_ethtool(struct netdev *netdev) 
146 {
147     struct ifreq ifr;
148     struct ethtool_cmd ecmd;
149
150     netdev->speed = 0;
151     netdev->features = 0;
152
153     memset(&ifr, 0, sizeof ifr);
154     strncpy(ifr.ifr_name, netdev->name, sizeof ifr.ifr_name);
155     ifr.ifr_data = (caddr_t) &ecmd;
156
157     memset(&ecmd, 0, sizeof ecmd);
158     ecmd.cmd = ETHTOOL_GSET;
159     if (ioctl(netdev->fd, SIOCETHTOOL, &ifr) == 0) {
160         if (ecmd.supported & SUPPORTED_10baseT_Half) {
161             netdev->features |= OFPPF_10MB_HD;
162         }
163         if (ecmd.supported & SUPPORTED_10baseT_Full) {
164             netdev->features |= OFPPF_10MB_FD;
165         }
166         if (ecmd.supported & SUPPORTED_100baseT_Half)  {
167             netdev->features |= OFPPF_100MB_HD;
168         }
169         if (ecmd.supported & SUPPORTED_100baseT_Full) {
170             netdev->features |= OFPPF_100MB_FD;
171         }
172         if (ecmd.supported & SUPPORTED_1000baseT_Half) {
173             netdev->features |= OFPPF_1GB_HD;
174         }
175         if (ecmd.supported & SUPPORTED_1000baseT_Full) {
176             netdev->features |= OFPPF_1GB_FD;
177         }
178         /* 10Gbps half-duplex doesn't exist... */
179         if (ecmd.supported & SUPPORTED_10000baseT_Full) {
180             netdev->features |= OFPPF_10GB_FD;
181         }
182
183         switch (ecmd.speed) {
184         case SPEED_10:
185             netdev->speed = 10;
186             break;
187
188         case SPEED_100:
189             netdev->speed = 100;
190             break;
191
192         case SPEED_1000:
193             netdev->speed = 1000;
194             break;
195
196         case SPEED_2500:
197             netdev->speed = 2500;
198             break;
199
200         case SPEED_10000:
201             netdev->speed = 10000;
202             break;
203         }
204     } else {
205         VLOG_DBG("ioctl(SIOCETHTOOL) failed: %s", strerror(errno));
206     }
207 }
208
209 /* Opens the network device named 'name' (e.g. "eth0") and returns zero if
210  * successful, otherwise a positive errno value.  On success, sets '*netdev'
211  * to the new network device, otherwise to null. */
212 int
213 netdev_open(const char *name, struct netdev **netdev_)
214 {
215     int fd;
216     struct sockaddr sa;
217     struct ifreq ifr;
218     unsigned int ifindex;
219     socklen_t rcvbuf_len;
220     size_t rcvbuf;
221     uint8_t etheraddr[ETH_ADDR_LEN];
222     int mtu;
223     int error;
224     struct netdev *netdev;
225
226     *netdev_ = NULL;
227     init_netdev();
228
229     /* Create raw socket.
230      *
231      * We have to use SOCK_PACKET, despite its deprecation, because only
232      * SOCK_PACKET lets us set the hardware source address of outgoing
233      * packets. */
234     fd = socket(PF_PACKET, SOCK_PACKET, htons(ETH_P_ALL));
235     if (fd < 0) {
236         return errno;
237     }
238
239     /* Bind to specific ethernet device. */
240     memset(&sa, 0, sizeof sa);
241     sa.sa_family = AF_UNSPEC;
242     strncpy((char *) sa.sa_data, name, sizeof sa.sa_data);
243     if (bind(fd, &sa, sizeof sa) < 0) {
244         VLOG_ERR("bind to %s failed: %s", name, strerror(errno));
245         goto error;
246     }
247
248     /* Between the socket() and bind() calls above, the socket receives all
249      * packets on all system interfaces.  We do not want to receive that
250      * data, but there is no way to avoid it.  So we must now drain out the
251      * receive queue.  There is no way to know how long the receive queue is,
252      * but we know that the total number of bytes queued does not exceed the
253      * receive buffer size, so we pull packets until none are left or we've
254      * read that many bytes. */
255     rcvbuf_len = sizeof rcvbuf;
256     if (getsockopt(fd, SOL_SOCKET, SO_RCVBUF, &rcvbuf, &rcvbuf_len) < 0) {
257         VLOG_ERR("getsockopt(SO_RCVBUF) on %s device failed: %s",
258                  name, strerror(errno));
259         goto error;
260     }
261     while (rcvbuf > 0) {
262         char buffer;
263         ssize_t n_bytes = recv(fd, &buffer, 1, MSG_TRUNC | MSG_DONTWAIT);
264         if (n_bytes <= 0) {
265             break;
266         }
267         rcvbuf -= n_bytes;
268     }
269
270     /* Get ethernet device index. */
271     strncpy(ifr.ifr_name, name, sizeof ifr.ifr_name);
272     if (ioctl(fd, SIOCGIFINDEX, &ifr) < 0) {
273         VLOG_ERR("ioctl(SIOCGIFINDEX) on %s device failed: %s",
274                  name, strerror(errno));
275         goto error;
276     }
277     ifindex = ifr.ifr_ifindex;
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     /* Allocate network device. */
301     netdev = xmalloc(sizeof *netdev);
302     netdev->name = xstrdup(name);
303     netdev->fd = fd;
304     memcpy(netdev->etheraddr, etheraddr, sizeof etheraddr);
305     netdev->mtu = mtu;
306
307     /* Get speed, features. */
308     do_ethtool(netdev);
309
310     /* Save flags to restore at close or exit. */
311     if (ioctl(fd, SIOCGIFFLAGS, &ifr) < 0) {
312         VLOG_ERR("ioctl(SIOCGIFFLAGS) on %s device failed: %s",
313                  name, strerror(errno));
314         goto error;
315     }
316     netdev->save_flags = ifr.ifr_flags;
317     fatal_signal_block();
318     list_push_back(&netdev_list, &netdev->node);
319     fatal_signal_unblock();
320
321     /* Bring up interface and set promiscuous mode. */
322     ifr.ifr_flags |= IFF_PROMISC | IFF_UP;
323     if (ioctl(fd, SIOCSIFFLAGS, &ifr) < 0) {
324         error = errno;
325         VLOG_ERR("failed to set promiscuous mode on %s device: %s",
326                  name, strerror(errno));
327         netdev_close(netdev);
328         return error;
329     }
330
331     /* Complain to administrator if any IP addresses are assigned to the
332      * interface.  We warn about this because packets received for that IP
333      * address will be processed both by the kernel TCP/IP stack and by us as a
334      * switch, which produces poor results. */
335     check_ipv4_address(name);
336     check_ipv6_address(name);
337
338     /* Success! */
339     *netdev_ = netdev;
340     return 0;
341
342 error:
343     error = errno;
344     close(fd);
345     return error;
346 }
347
348 /* Closes and destroys 'netdev'. */
349 void
350 netdev_close(struct netdev *netdev)
351 {
352     if (netdev) {
353         /* Bring down interface and drop promiscuous mode, if we brought up
354          * the interface or enabled promiscuous mode. */
355         int error;
356         fatal_signal_block();
357         error = restore_flags(netdev);
358         list_remove(&netdev->node);
359         fatal_signal_unblock();
360         if (error) {
361             VLOG_WARN("failed to restore network device flags on %s: %s",
362                       netdev->name, strerror(error));
363         }
364
365         /* Free. */
366         free(netdev->name);
367         close(netdev->fd);
368         free(netdev);
369     }
370 }
371
372 /* Pads 'buffer' out with zero-bytes to the minimum valid length of an
373  * Ethernet packet, if necessary.  */
374 static void
375 pad_to_minimum_length(struct buffer *buffer)
376 {
377     if (buffer->size < ETH_TOTAL_MIN) {
378         size_t shortage = ETH_TOTAL_MIN - buffer->size;
379         memset(buffer_put_uninit(buffer, shortage), 0, shortage);
380     }
381 }
382
383 /* Attempts to receive a packet from 'netdev' into 'buffer', which the caller
384  * must have initialized with sufficient room for the packet.  The space
385  * required to receive any packet is ETH_HEADER_LEN bytes, plus VLAN_HEADER_LEN
386  * bytes, plus the device's MTU (which may be retrieved via netdev_get_mtu()).
387  * (Some devices do not allow for a VLAN header, in which case VLAN_HEADER_LEN
388  * need not be included.)
389  *
390  * If a packet is successfully retrieved, returns 0.  In this case 'buffer' is
391  * guaranteed to contain at least ETH_TOTAL_MIN bytes.  Otherwise, returns a
392  * positive errno value.  Returns EAGAIN immediately if no packet is ready to
393  * be returned.
394  */
395 int
396 netdev_recv(struct netdev *netdev, struct buffer *buffer)
397 {
398     ssize_t n_bytes;
399
400     assert(buffer->size == 0);
401     assert(buffer_tailroom(buffer) >= ETH_TOTAL_MIN);
402     do {
403         n_bytes = recv(netdev->fd,
404                        buffer_tail(buffer), buffer_tailroom(buffer),
405                        MSG_DONTWAIT);
406     } while (n_bytes < 0 && errno == EINTR);
407     if (n_bytes < 0) {
408         if (errno != EAGAIN) {
409             VLOG_WARN("error receiving Ethernet packet on %s: %s",
410                       strerror(errno), netdev->name);
411         }
412         return errno;
413     } else {
414         buffer->size += n_bytes;
415
416         /* When the kernel internally sends out an Ethernet frame on an
417          * interface, it gives us a copy *before* padding the frame to the
418          * minimum length.  Thus, when it sends out something like an ARP
419          * request, we see a too-short frame.  So pad it out to the minimum
420          * length. */
421         pad_to_minimum_length(buffer);
422         return 0;
423     }
424 }
425
426 /* Registers with the poll loop to wake up from the next call to poll_block()
427  * when a packet is ready to be received with netdev_recv() on 'netdev'. */
428 void
429 netdev_recv_wait(struct netdev *netdev)
430 {
431     poll_fd_wait(netdev->fd, POLLIN);
432 }
433
434 /* Sends 'buffer' on 'netdev'.  Returns 0 if successful, otherwise a positive
435  * errno value.  Returns EAGAIN without blocking if the packet cannot be queued
436  * immediately.  Returns EMSGSIZE if a partial packet was transmitted or if
437  * the packet is too big to transmit on the device.
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, struct buffer *buffer)
443 {
444     ssize_t n_bytes;
445     const struct eth_header *eh;
446     struct sockaddr_pkt spkt;
447
448     /* Ensure packet is long enough.  (Although all incoming packets are at
449      * least ETH_TOTAL_MIN bytes long, we could have trimmed some data off a
450      * minimum-size packet, e.g. by dropping a vlan header.)
451      *
452      * The kernel does not require this, but it ensures that we always access
453      * valid memory in grabbing the sockaddr below. */
454     pad_to_minimum_length(buffer);
455
456     /* Construct packet sockaddr, which SOCK_PACKET requires. */
457     spkt.spkt_family = AF_PACKET;
458     strncpy((char *) spkt.spkt_device, netdev->name, sizeof spkt.spkt_device);
459     eh = buffer_at_assert(buffer, 0, sizeof *eh);
460     spkt.spkt_protocol = eh->eth_type;
461
462     do {
463         n_bytes = sendto(netdev->fd, buffer->data, buffer->size, 0,
464                          (const struct sockaddr *) &spkt, sizeof spkt);
465     } while (n_bytes < 0 && errno == EINTR);
466
467     if (n_bytes < 0) {
468         /* The Linux AF_PACKET implementation never blocks waiting for room
469          * for packets, instead returning ENOBUFS.  Translate this into EAGAIN
470          * for the caller. */
471         if (errno == ENOBUFS) {
472             return EAGAIN;
473         } else if (errno != EAGAIN) {
474             VLOG_WARN("error sending Ethernet packet on %s: %s",
475                       netdev->name, strerror(errno));
476         }
477         return errno;
478     } else if (n_bytes != buffer->size) {
479         VLOG_WARN("send partial Ethernet packet (%d bytes of %zu) on %s",
480                   (int) n_bytes, buffer->size, netdev->name);
481         return EMSGSIZE;
482     } else {
483         return 0;
484     }
485 }
486
487 /* Registers with the poll loop to wake up from the next call to poll_block()
488  * when the packet transmission queue has sufficient room to transmit a packet
489  * with netdev_send().
490  *
491  * The kernel maintains a packet transmission queue, so the client is not
492  * expected to do additional queuing of packets.  Thus, this function is
493  * unlikely to ever be used.  It is included for completeness. */
494 void
495 netdev_send_wait(struct netdev *netdev)
496 {
497     poll_fd_wait(netdev->fd, POLLOUT);
498 }
499
500 /* Returns a pointer to 'netdev''s MAC address.  The caller must not modify or
501  * free the returned buffer. */
502 const uint8_t *
503 netdev_get_etheraddr(const struct netdev *netdev)
504 {
505     return netdev->etheraddr;
506 }
507
508 /* Returns the name of the network device that 'netdev' represents,
509  * e.g. "eth0".  The caller must not modify or free the returned string. */
510 const char *
511 netdev_get_name(const struct netdev *netdev)
512 {
513     return netdev->name;
514 }
515
516 /* Returns the maximum size of transmitted (and received) packets on 'netdev',
517  * in bytes, not including the hardware header; thus, this is typically 1500
518  * bytes for Ethernet devices. */
519 int
520 netdev_get_mtu(const struct netdev *netdev) 
521 {
522     return netdev->mtu;
523 }
524
525 /* Returns the current speed of the network device that 'netdev' represents, in
526  * megabits per second, or 0 if the speed is unknown. */
527 int
528 netdev_get_speed(const struct netdev *netdev) 
529 {
530     return netdev->speed;
531 }
532
533 /* Returns the features supported by 'netdev', as a bitmap of bits from enum
534  * ofp_phy_port, in host byte order. */
535 uint32_t
536 netdev_get_features(const struct netdev *netdev) 
537 {
538     return netdev->features;
539 }
540 \f
541 static void restore_all_flags(void *aux);
542
543 /* Set up a signal hook to restore network device flags on program
544  * termination.  */
545 static void
546 init_netdev(void)
547 {
548     static bool inited;
549     if (!inited) {
550         inited = true;
551         fatal_signal_add_hook(restore_all_flags, NULL);
552     }
553 }
554
555 /* Restore the network device flags on 'netdev' to those that were active
556  * before we changed them.  Returns 0 if successful, otherwise a positive
557  * errno value.
558  *
559  * To avoid reentry, the caller must ensure that fatal signals are blocked. */
560 static int
561 restore_flags(struct netdev *netdev)
562 {
563     struct ifreq ifr;
564
565     /* Get current flags. */
566     strncpy(ifr.ifr_name, netdev->name, sizeof ifr.ifr_name);
567     if (ioctl(netdev->fd, SIOCGIFFLAGS, &ifr) < 0) {
568         return errno;
569     }
570
571     /* Restore flags that we might have changed, if necessary. */
572     if ((ifr.ifr_flags ^ netdev->save_flags) & (IFF_PROMISC | IFF_UP)) {
573         ifr.ifr_flags &= ~(IFF_PROMISC | IFF_UP);
574         ifr.ifr_flags |= netdev->save_flags & (IFF_PROMISC | IFF_UP);
575         if (ioctl(netdev->fd, SIOCSIFFLAGS, &ifr) < 0) {
576             return errno;
577         }
578     }
579
580     return 0;
581 }
582
583 /* Retores all the flags on all network devices that we modified.  Called from
584  * a signal handler, so it does not attempt to report error conditions. */
585 static void
586 restore_all_flags(void *aux UNUSED)
587 {
588     struct netdev *netdev;
589     LIST_FOR_EACH (netdev, struct netdev, node, &netdev_list) {
590         restore_flags(netdev);
591     }
592 }