Update copyright on all non-GPL files
[openvswitch] / switch / 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
62 #define THIS_MODULE VLM_netdev
63 #include "vlog.h"
64
65 struct netdev {
66     struct list node;
67     char *name;
68     int fd;
69     uint8_t etheraddr[ETH_ADDR_LEN];
70     int speed;
71     uint32_t features;
72     int save_flags;
73 };
74
75 static struct list netdev_list = LIST_INITIALIZER(&netdev_list);
76
77 static void init_netdev(void);
78 static int restore_flags(struct netdev *netdev);
79
80 /* Check whether device NAME has an IPv4 address assigned to it and, if so, log
81  * an error. */
82 static void
83 check_ipv4_address(const char *name)
84 {
85     int sock;
86     struct ifreq ifr;
87
88     sock = socket(AF_INET, SOCK_DGRAM, 0);
89     if (sock < 0) {
90         VLOG_WARN("socket(AF_INET): %s", strerror(errno));
91         return;
92     }
93
94     strncpy(ifr.ifr_name, name, sizeof ifr.ifr_name);
95     ifr.ifr_addr.sa_family = AF_INET;
96     if (ioctl(sock, SIOCGIFADDR, &ifr) == 0) {
97         VLOG_ERR("%s device has assigned IP address %s", name,
98                  inet_ntoa(((struct sockaddr_in*) &ifr.ifr_addr)->sin_addr));
99     }
100
101     close(sock);
102 }
103
104 static void
105 check_ipv6_address(const char *name)
106 {
107     FILE *file;
108     char line[128];
109
110     file = fopen("/proc/net/if_inet6", "r");
111     if (file == NULL) {
112         return;
113     }
114
115     while (fgets(line, sizeof line, file)) {
116         struct in6_addr in6;
117         uint8_t *s6 = in6.s6_addr;
118         char ifname[16 + 1];
119
120 #define X8 "%2"SCNx8
121         if (sscanf(line, " "X8 X8 X8 X8 X8 X8 X8 X8 X8 X8 X8 X8 X8 X8 X8 X8
122                    "%*x %*x %*x %*x %16s\n",
123                    &s6[0], &s6[1], &s6[2], &s6[3],
124                    &s6[4], &s6[5], &s6[6], &s6[7],
125                    &s6[8], &s6[9], &s6[10], &s6[11],
126                    &s6[12], &s6[13], &s6[14], &s6[15],
127                    ifname) == 17
128             && !strcmp(name, ifname))
129         {
130             char in6_name[INET6_ADDRSTRLEN + 1];
131             inet_ntop(AF_INET6, &in6, in6_name, sizeof in6_name);
132             VLOG_ERR("%s device has assigned IPv6 address %s",
133                      name, in6_name);
134         }
135     }
136
137     fclose(file);
138 }
139
140 static void
141 do_ethtool(struct netdev *netdev) 
142 {
143     struct ifreq ifr;
144     struct ethtool_cmd ecmd;
145
146     netdev->speed = 0;
147     netdev->features = 0;
148
149     memset(&ifr, 0, sizeof ifr);
150     strncpy(ifr.ifr_name, netdev->name, sizeof ifr.ifr_name);
151     ifr.ifr_data = (caddr_t) &ecmd;
152
153     memset(&ecmd, 0, sizeof ecmd);
154     ecmd.cmd = ETHTOOL_GSET;
155     if (ioctl(netdev->fd, SIOCETHTOOL, &ifr) == 0) {
156         if (ecmd.supported & SUPPORTED_10baseT_Half) {
157             netdev->features |= OFPPF_10MB_HD;
158         }
159         if (ecmd.supported & SUPPORTED_10baseT_Full) {
160             netdev->features |= OFPPF_10MB_FD;
161         }
162         if (ecmd.supported & SUPPORTED_100baseT_Half)  {
163             netdev->features |= OFPPF_100MB_HD;
164         }
165         if (ecmd.supported & SUPPORTED_100baseT_Full) {
166             netdev->features |= OFPPF_100MB_FD;
167         }
168         if (ecmd.supported & SUPPORTED_1000baseT_Half) {
169             netdev->features |= OFPPF_1GB_HD;
170         }
171         if (ecmd.supported & SUPPORTED_1000baseT_Full) {
172             netdev->features |= OFPPF_1GB_FD;
173         }
174         /* 10Gbps half-duplex doesn't exist... */
175         if (ecmd.supported & SUPPORTED_10000baseT_Full) {
176             netdev->features |= OFPPF_10GB_FD;
177         }
178
179         switch (ecmd.speed) {
180         case SPEED_10:
181             netdev->speed = 10;
182             break;
183
184         case SPEED_100:
185             netdev->speed = 100;
186             break;
187
188         case SPEED_1000:
189             netdev->speed = 1000;
190             break;
191
192         case SPEED_2500:
193             netdev->speed = 2500;
194             break;
195
196         case SPEED_10000:
197             netdev->speed = 10000;
198             break;
199         }
200     } else {
201         VLOG_DBG("ioctl(SIOCETHTOOL) failed: %s", strerror(errno));
202     }
203 }
204
205 int
206 netdev_open(const char *name, struct netdev **netdev_)
207 {
208     int fd;
209     struct sockaddr sa;
210     struct ifreq ifr;
211     unsigned int ifindex;
212     socklen_t rcvbuf_len;
213     size_t rcvbuf;
214     uint8_t etheraddr[ETH_ADDR_LEN];
215     int error;
216     struct netdev *netdev;
217
218     *netdev_ = NULL;
219     init_netdev();
220
221     /* Create raw socket.
222      *
223      * We have to use SOCK_PACKET, despite its deprecation, because only
224      * SOCK_PACKET lets us set the hardware source address of outgoing
225      * packets. */
226     fd = socket(PF_PACKET, SOCK_PACKET, htons(ETH_P_ALL));
227     if (fd < 0) {
228         return errno;
229     }
230
231     /* Bind to specific ethernet device. */
232     memset(&sa, 0, sizeof sa);
233     sa.sa_family = AF_UNSPEC;
234     strncpy((char *) sa.sa_data, name, sizeof sa.sa_data);
235     if (bind(fd, &sa, sizeof sa) < 0) {
236         VLOG_ERR("bind to %s failed: %s", name, strerror(errno));
237         goto error;
238     }
239
240     /* Between the socket() and bind() calls above, the socket receives all
241      * packets on all system interfaces.  We do not want to receive that
242      * data, but there is no way to avoid it.  So we must now drain out the
243      * receive queue.  There is no way to know how long the receive queue is,
244      * but we know that the total number of byted queued does not exceed the
245      * receive buffer size, so we pull packets until none are left or we've
246      * read that many bytes. */
247     rcvbuf_len = sizeof rcvbuf;
248     if (getsockopt(fd, SOL_SOCKET, SO_RCVBUF, &rcvbuf, &rcvbuf_len) < 0) {
249         VLOG_ERR("getsockopt(SO_RCVBUF) on %s device failed: %s",
250                  name, strerror(errno));
251         goto error;
252     }
253     while (rcvbuf > 0) {
254         char buffer;
255         ssize_t n_bytes = recv(fd, &buffer, 1, MSG_TRUNC | MSG_DONTWAIT);
256         if (n_bytes <= 0) {
257             break;
258         }
259         rcvbuf -= n_bytes;
260     }
261
262     /* Get ethernet device index and hardware address. */
263     strncpy(ifr.ifr_name, name, sizeof ifr.ifr_name);
264     if (ioctl(fd, SIOCGIFINDEX, &ifr) < 0) {
265         VLOG_ERR("ioctl(SIOCGIFINDEX) on %s device failed: %s",
266                  name, strerror(errno));
267         goto error;
268     }
269     ifindex = ifr.ifr_ifindex;
270     if (ioctl(fd, SIOCGIFHWADDR, &ifr) < 0) {
271         VLOG_ERR("ioctl(SIOCGIFHWADDR) on %s device failed: %s",
272                  name, strerror(errno));
273         goto error;
274     }
275     if (ifr.ifr_hwaddr.sa_family != AF_UNSPEC
276         && ifr.ifr_hwaddr.sa_family != ARPHRD_ETHER) {
277         VLOG_WARN("%s device has unknown hardware address family %d",
278                   name, (int) ifr.ifr_hwaddr.sa_family);
279     }
280     memcpy(etheraddr, ifr.ifr_hwaddr.sa_data, sizeof etheraddr);
281
282     /* Allocate network device. */
283     netdev = xmalloc(sizeof *netdev);
284     netdev->name = xstrdup(name);
285     netdev->fd = fd;
286     memcpy(netdev->etheraddr, etheraddr, sizeof etheraddr);
287
288     /* Get speed, features. */
289     do_ethtool(netdev);
290
291     /* Save flags to restore at close or exit. */
292     if (ioctl(fd, SIOCGIFFLAGS, &ifr) < 0) {
293         VLOG_ERR("ioctl(SIOCGIFFLAGS) on %s device failed: %s",
294                  name, strerror(errno));
295         goto error;
296     }
297     netdev->save_flags = ifr.ifr_flags;
298     fatal_signal_block();
299     list_push_back(&netdev_list, &netdev->node);
300     fatal_signal_unblock();
301
302     /* Bring up interface and set promiscuous mode. */
303     ifr.ifr_flags |= IFF_PROMISC | IFF_UP;
304     if (ioctl(fd, SIOCSIFFLAGS, &ifr) < 0) {
305         error = errno;
306         VLOG_ERR("failed to set promiscuous mode on %s device: %s",
307                  name, strerror(errno));
308         netdev_close(netdev);
309         return error;
310     }
311
312     /* Report IP addresses to administrator. */
313     check_ipv4_address(name);
314     check_ipv6_address(name);
315
316     /* Success! */
317     *netdev_ = netdev;
318     return 0;
319
320 error:
321     error = errno;
322     close(fd);
323     return error;
324 }
325
326 void
327 netdev_close(struct netdev *netdev)
328 {
329     if (netdev) {
330         /* Bring down interface and drop promiscuous mode, if we brought up
331          * the interface or enabled promiscuous mode. */
332         int error;
333         fatal_signal_block();
334         error = restore_flags(netdev);
335         list_remove(&netdev->node);
336         fatal_signal_unblock();
337         if (error) {
338             VLOG_WARN("failed to restore network device flags on %s: %s",
339                       netdev->name, strerror(error));
340         }
341
342         /* Free. */
343         free(netdev->name);
344         close(netdev->fd);
345         free(netdev);
346     }
347 }
348
349 static void
350 pad_to_minimum_length(struct buffer *buffer)
351 {
352     if (buffer->size < ETH_TOTAL_MIN) {
353         size_t shortage = ETH_TOTAL_MIN - buffer->size;
354         memset(buffer_put_uninit(buffer, shortage), 0, shortage);
355     }
356 }
357
358 int
359 netdev_recv(struct netdev *netdev, struct buffer *buffer, bool block)
360 {
361     ssize_t n_bytes;
362
363     assert(buffer->size == 0);
364     assert(buffer_tailroom(buffer) >= ETH_TOTAL_MIN);
365     do {
366         n_bytes = recv(netdev->fd,
367                        buffer_tail(buffer), buffer_tailroom(buffer),
368                        block ? 0 : MSG_DONTWAIT);
369     } while (n_bytes < 0 && errno == EINTR);
370     if (n_bytes < 0) {
371         if (errno != EAGAIN) {
372             VLOG_WARN("error receiving Ethernet packet on %s: %s",
373                       strerror(errno), netdev->name);
374         }
375         return errno;
376     } else {
377         buffer->size += n_bytes;
378
379         /* When the kernel internally sends out an Ethernet frame on an
380          * interface, it gives us a copy *before* padding the frame to the
381          * minimum length.  Thus, when it sends out something like an ARP
382          * request, we see a too-short frame.  So pad it out to the minimum
383          * length. */
384         pad_to_minimum_length(buffer);
385         return 0;
386     }
387 }
388
389 int
390 netdev_send(struct netdev *netdev, struct buffer *buffer, bool block)
391 {
392     ssize_t n_bytes;
393     const struct eth_header *eh;
394     struct sockaddr_pkt spkt;
395
396     /* Ensure packet is long enough.  (Although all incoming packets are at
397      * least ETH_TOTAL_MIN bytes long, we could have trimmed some data off a
398      * minimum-size packet, e.g. by dropping a vlan header.) */
399     pad_to_minimum_length(buffer);
400
401     /* Construct packet sockaddr, which SOCK_PACKET requires. */
402     spkt.spkt_family = AF_PACKET;
403     strncpy((char *) spkt.spkt_device, netdev->name, sizeof spkt.spkt_device);
404     eh = buffer_at_assert(buffer, 0, sizeof *eh);
405     spkt.spkt_protocol = eh->eth_type;
406
407     do {
408         n_bytes = sendto(netdev->fd, buffer->data, buffer->size,
409                          block ? 0 : MSG_DONTWAIT,
410                          (const struct sockaddr *) &spkt, sizeof spkt);
411     } while (n_bytes < 0 && errno == EINTR);
412     if (n_bytes < 0) {
413         if (errno != EAGAIN) {
414             VLOG_WARN("error sending Ethernet packet on %s: %s",
415                       netdev->name, strerror(errno)); 
416         }
417         return errno;
418     } else if (n_bytes != buffer->size) {
419         VLOG_WARN("send partial Ethernet packet (%d bytes of %d) on %s",
420                   (int) n_bytes, buffer->size, netdev->name);
421         return EMSGSIZE;
422     } else {
423         return 0;
424     }
425 }
426
427 const uint8_t *
428 netdev_get_etheraddr(const struct netdev *netdev)
429 {
430     return netdev->etheraddr;
431 }
432
433 int
434 netdev_get_fd(const struct netdev *netdev)
435 {
436     return netdev->fd;
437 }
438
439 const char *
440 netdev_get_name(const struct netdev *netdev)
441 {
442     return netdev->name;
443 }
444
445 int
446 netdev_get_speed(const struct netdev *netdev) 
447 {
448     return netdev->speed;
449 }
450
451 uint32_t
452 netdev_get_features(const struct netdev *netdev) 
453 {
454     return netdev->features;
455 }
456 \f
457 static void restore_all_flags(void *aux);
458
459 static void
460 init_netdev(void)
461 {
462     static bool inited;
463     if (!inited) {
464         inited = true;
465         fatal_signal_add_hook(restore_all_flags, NULL);
466     }
467 }
468
469 static int
470 restore_flags(struct netdev *netdev)
471 {
472     struct ifreq ifr;
473
474     /* Get current flags. */
475     strncpy(ifr.ifr_name, netdev->name, sizeof ifr.ifr_name);
476     if (ioctl(netdev->fd, SIOCGIFFLAGS, &ifr) < 0) {
477         return errno;
478     }
479
480     /* Restore flags that we might have changed, if necessary. */
481     if ((ifr.ifr_flags ^ netdev->save_flags) & (IFF_PROMISC | IFF_UP)) {
482         ifr.ifr_flags &= ~(IFF_PROMISC | IFF_UP);
483         ifr.ifr_flags |= netdev->save_flags & (IFF_PROMISC | IFF_UP);
484         if (ioctl(netdev->fd, SIOCSIFFLAGS, &ifr) < 0) {
485             return errno;
486         }
487     }
488
489     return 0;
490 }
491
492 static void
493 restore_all_flags(void *aux UNUSED)
494 {
495     struct netdev *netdev;
496     LIST_FOR_EACH (netdev, struct netdev, node, &netdev_list) {
497         restore_flags(netdev);
498     }
499 }