datapath-windows: Add WMI Script that updates Hyper-V friendly port names.
[cascardo/ovs.git] / lib / socket-util.c
1 /*
2  * Copyright (c) 2008, 2009, 2010, 2011, 2012, 2013, 2014 Nicira, Inc.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at:
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 #include <config.h>
18 #include "socket-util.h"
19 #include <arpa/inet.h>
20 #include <errno.h>
21 #include <fcntl.h>
22 #include <net/if.h>
23 #include <netdb.h>
24 #include <poll.h>
25 #include <stddef.h>
26 #include <stdio.h>
27 #include <stdlib.h>
28 #include <string.h>
29 #include <sys/socket.h>
30 #include <sys/stat.h>
31 #include <sys/uio.h>
32 #include <sys/un.h>
33 #include <unistd.h>
34 #include "dynamic-string.h"
35 #include "ovs-thread.h"
36 #include "packets.h"
37 #include "poll-loop.h"
38 #include "util.h"
39 #include "vlog.h"
40 #ifdef __linux__
41 #include <linux/if_packet.h>
42 #endif
43 #ifdef HAVE_NETLINK
44 #include "netlink-protocol.h"
45 #include "netlink-socket.h"
46 #endif
47
48 VLOG_DEFINE_THIS_MODULE(socket_util);
49
50 static int getsockopt_int(int fd, int level, int option, const char *optname,
51                           int *valuep);
52
53 /* Sets 'fd' to non-blocking mode.  Returns 0 if successful, otherwise a
54  * positive errno value. */
55 int
56 set_nonblocking(int fd)
57 {
58 #ifndef _WIN32
59     int flags = fcntl(fd, F_GETFL, 0);
60     if (flags != -1) {
61         if (fcntl(fd, F_SETFL, flags | O_NONBLOCK) != -1) {
62             return 0;
63         } else {
64             VLOG_ERR("fcntl(F_SETFL) failed: %s", ovs_strerror(errno));
65             return errno;
66         }
67     } else {
68         VLOG_ERR("fcntl(F_GETFL) failed: %s", ovs_strerror(errno));
69         return errno;
70     }
71 #else
72     unsigned long arg = 1;
73     if (ioctlsocket(fd, FIONBIO, &arg)) {
74         int error = sock_errno();
75         VLOG_ERR("set_nonblocking failed: %s", sock_strerror(error));
76         return error;
77     }
78     return 0;
79 #endif
80 }
81
82 void
83 xset_nonblocking(int fd)
84 {
85     if (set_nonblocking(fd)) {
86         exit(EXIT_FAILURE);
87     }
88 }
89
90 int
91 set_dscp(int fd, uint8_t dscp)
92 {
93     int val;
94     bool success;
95
96 #ifdef _WIN32
97     /* XXX: Consider using QoS2 APIs for Windows to set dscp. */
98     return 0;
99 #endif
100
101     if (dscp > 63) {
102         return EINVAL;
103     }
104
105     /* Note: this function is used for both of IPv4 and IPv6 sockets */
106     success = false;
107     val = dscp << 2;
108     if (setsockopt(fd, IPPROTO_IP, IP_TOS, &val, sizeof val)) {
109         if (sock_errno() != ENOPROTOOPT) {
110             return sock_errno();
111         }
112     } else {
113         success = true;
114     }
115     if (setsockopt(fd, IPPROTO_IPV6, IPV6_TCLASS, &val, sizeof val)) {
116         if (sock_errno() != ENOPROTOOPT) {
117             return sock_errno();
118         }
119     } else {
120         success = true;
121     }
122     if (!success) {
123         return ENOPROTOOPT;
124     }
125
126     return 0;
127 }
128
129 /* Translates 'host_name', which must be a string representation of an IP
130  * address, into a numeric IP address in '*addr'.  Returns 0 if successful,
131  * otherwise a positive errno value. */
132 int
133 lookup_ip(const char *host_name, struct in_addr *addr)
134 {
135     if (!inet_pton(AF_INET, host_name, addr)) {
136         static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
137         VLOG_ERR_RL(&rl, "\"%s\" is not a valid IP address", host_name);
138         return ENOENT;
139     }
140     return 0;
141 }
142
143 /* Translates 'host_name', which must be a string representation of an IPv6
144  * address, into a numeric IPv6 address in '*addr'.  Returns 0 if successful,
145  * otherwise a positive errno value. */
146 int
147 lookup_ipv6(const char *host_name, struct in6_addr *addr)
148 {
149     if (inet_pton(AF_INET6, host_name, addr) != 1) {
150         static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
151         VLOG_ERR_RL(&rl, "\"%s\" is not a valid IPv6 address", host_name);
152         return ENOENT;
153     }
154     return 0;
155 }
156
157 /* Translates 'host_name', which must be a host name or a string representation
158  * of an IP address, into a numeric IP address in '*addr'.  Returns 0 if
159  * successful, otherwise a positive errno value.
160  *
161  * Most Open vSwitch code should not use this because it causes deadlocks:
162  * getaddrinfo() sends out a DNS request but that starts a new flow for which
163  * OVS must set up a flow, but it can't because it's waiting for a DNS reply.
164  * The synchronous lookup also delays other activity.  (Of course we can solve
165  * this but it doesn't seem worthwhile quite yet.)  */
166 int
167 lookup_hostname(const char *host_name, struct in_addr *addr)
168 {
169     struct addrinfo *result;
170     struct addrinfo hints;
171
172     if (inet_pton(AF_INET, host_name, addr)) {
173         return 0;
174     }
175
176     memset(&hints, 0, sizeof hints);
177     hints.ai_family = AF_INET;
178
179     switch (getaddrinfo(host_name, NULL, &hints, &result)) {
180     case 0:
181         *addr = ALIGNED_CAST(struct sockaddr_in *,
182                              result->ai_addr)->sin_addr;
183         freeaddrinfo(result);
184         return 0;
185
186 #ifdef EAI_ADDRFAMILY
187     case EAI_ADDRFAMILY:
188 #endif
189     case EAI_NONAME:
190     case EAI_SERVICE:
191         return ENOENT;
192
193     case EAI_AGAIN:
194         return EAGAIN;
195
196     case EAI_BADFLAGS:
197     case EAI_FAMILY:
198     case EAI_SOCKTYPE:
199         return EINVAL;
200
201     case EAI_FAIL:
202         return EIO;
203
204     case EAI_MEMORY:
205         return ENOMEM;
206
207 #if defined (EAI_NODATA) && EAI_NODATA != EAI_NONAME
208     case EAI_NODATA:
209         return ENXIO;
210 #endif
211
212 #ifdef EAI_SYSTEM
213     case EAI_SYSTEM:
214         return sock_errno();
215 #endif
216
217     default:
218         return EPROTO;
219     }
220 }
221
222 int
223 check_connection_completion(int fd)
224 {
225     static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(5, 10);
226     struct pollfd pfd;
227     int retval;
228
229     pfd.fd = fd;
230     pfd.events = POLLOUT;
231
232 #ifndef _WIN32
233     do {
234         retval = poll(&pfd, 1, 0);
235     } while (retval < 0 && errno == EINTR);
236 #else
237     retval = WSAPoll(&pfd, 1, 0);
238 #endif
239     if (retval == 1) {
240         if (pfd.revents & POLLERR) {
241             ssize_t n = send(fd, "", 1, 0);
242             if (n < 0) {
243                 return sock_errno();
244             } else {
245                 VLOG_ERR_RL(&rl, "poll return POLLERR but send succeeded");
246                 return EPROTO;
247             }
248         }
249         return 0;
250     } else if (retval < 0) {
251         VLOG_ERR_RL(&rl, "poll: %s", sock_strerror(sock_errno()));
252         return errno;
253     } else {
254         return EAGAIN;
255     }
256 }
257
258 /* Returns the size of socket 'sock''s receive buffer (SO_RCVBUF), or a
259  * negative errno value if an error occurs. */
260 int
261 get_socket_rcvbuf(int sock)
262 {
263     int rcvbuf;
264     int error;
265
266     error = getsockopt_int(sock, SOL_SOCKET, SO_RCVBUF, "SO_RCVBUF", &rcvbuf);
267     return error ? -error : rcvbuf;
268 }
269
270 /* Reads and discards up to 'n' datagrams from 'fd', stopping as soon as no
271  * more data can be immediately read.  ('fd' should therefore be in
272  * non-blocking mode.)*/
273 void
274 drain_fd(int fd, size_t n_packets)
275 {
276     for (; n_packets > 0; n_packets--) {
277         /* 'buffer' only needs to be 1 byte long in most circumstances.  This
278          * size is defensive against the possibility that we someday want to
279          * use a Linux tap device without TUN_NO_PI, in which case a buffer
280          * smaller than sizeof(struct tun_pi) will give EINVAL on read. */
281         char buffer[128];
282         if (read(fd, buffer, sizeof buffer) <= 0) {
283             break;
284         }
285     }
286 }
287
288 ovs_be32
289 guess_netmask(ovs_be32 ip_)
290 {
291     uint32_t ip = ntohl(ip_);
292     return ((ip >> 31) == 0 ? htonl(0xff000000)   /* Class A */
293             : (ip >> 30) == 2 ? htonl(0xffff0000) /* Class B */
294             : (ip >> 29) == 6 ? htonl(0xffffff00) /* Class C */
295             : htonl(0));                          /* ??? */
296 }
297
298 /* This is like strsep() except:
299  *
300  *    - The separator string is ":".
301  *
302  *    - Square brackets [] quote ":" separators and are removed from the
303  *      tokens. */
304 static char *
305 parse_bracketed_token(char **pp)
306 {
307     char *p = *pp;
308
309     if (p == NULL) {
310         return NULL;
311     } else if (*p == '\0') {
312         *pp = NULL;
313         return p;
314     } else if (*p == '[') {
315         char *start = p + 1;
316         char *end = start + strcspn(start, "]");
317         *pp = (*end == '\0' ? NULL
318                : end[1] == ':' ? end + 2
319                : end + 1);
320         *end = '\0';
321         return start;
322     } else {
323         char *start = p;
324         char *end = start + strcspn(start, ":");
325         *pp = *end == '\0' ? NULL : end + 1;
326         *end = '\0';
327         return start;
328     }
329 }
330
331 static bool
332 parse_sockaddr_components(struct sockaddr_storage *ss,
333                           const char *host_s,
334                           const char *port_s, uint16_t default_port,
335                           const char *s)
336 {
337     struct sockaddr_in *sin = ALIGNED_CAST(struct sockaddr_in *, ss);
338     int port;
339
340     if (port_s && port_s[0]) {
341         if (!str_to_int(port_s, 10, &port) || port < 0 || port > 65535) {
342             VLOG_ERR("%s: bad port number \"%s\"", s, port_s);
343         }
344     } else {
345         port = default_port;
346     }
347
348     memset(ss, 0, sizeof *ss);
349     if (strchr(host_s, ':')) {
350         struct sockaddr_in6 *sin6
351             = ALIGNED_CAST(struct sockaddr_in6 *, ss);
352
353         sin6->sin6_family = AF_INET6;
354         sin6->sin6_port = htons(port);
355         if (!inet_pton(AF_INET6, host_s, sin6->sin6_addr.s6_addr)) {
356             VLOG_ERR("%s: bad IPv6 address \"%s\"", s, host_s);
357             goto exit;
358         }
359     } else {
360         sin->sin_family = AF_INET;
361         sin->sin_port = htons(port);
362         if (!inet_pton(AF_INET, host_s, &sin->sin_addr.s_addr)) {
363             VLOG_ERR("%s: bad IPv4 address \"%s\"", s, host_s);
364             goto exit;
365         }
366     }
367
368     return true;
369
370 exit:
371     memset(ss, 0, sizeof *ss);
372     return false;
373 }
374
375 /* Parses 'target', which should be a string in the format "<host>[:<port>]".
376  * <host>, which is required, may be an IPv4 address or an IPv6 address
377  * enclosed in square brackets.  If 'default_port' is nonzero then <port> is
378  * optional and defaults to 'default_port'.
379  *
380  * On success, returns true and stores the parsed remote address into '*ss'.
381  * On failure, logs an error, stores zeros into '*ss', and returns false. */
382 bool
383 inet_parse_active(const char *target_, uint16_t default_port,
384                   struct sockaddr_storage *ss)
385 {
386     char *target = xstrdup(target_);
387     const char *port;
388     const char *host;
389     char *p;
390     bool ok;
391
392     p = target;
393     host = parse_bracketed_token(&p);
394     port = parse_bracketed_token(&p);
395     if (!host) {
396         VLOG_ERR("%s: host must be specified", target_);
397         ok = false;
398     } else if (!port && !default_port) {
399         VLOG_ERR("%s: port must be specified", target_);
400         ok = false;
401     } else {
402         ok = parse_sockaddr_components(ss, host, port, default_port, target_);
403     }
404     if (!ok) {
405         memset(ss, 0, sizeof *ss);
406     }
407     free(target);
408     return ok;
409 }
410
411
412 /* Opens a non-blocking IPv4 or IPv6 socket of the specified 'style' and
413  * connects to 'target', which should be a string in the format
414  * "<host>[:<port>]".  <host>, which is required, may be an IPv4 address or an
415  * IPv6 address enclosed in square brackets.  If 'default_port' is nonzero then
416  * <port> is optional and defaults to 'default_port'.
417  *
418  * 'style' should be SOCK_STREAM (for TCP) or SOCK_DGRAM (for UDP).
419  *
420  * On success, returns 0 (indicating connection complete) or EAGAIN (indicating
421  * connection in progress), in which case the new file descriptor is stored
422  * into '*fdp'.  On failure, returns a positive errno value other than EAGAIN
423  * and stores -1 into '*fdp'.
424  *
425  * If 'ss' is non-null, then on success stores the target address into '*ss'.
426  *
427  * 'dscp' becomes the DSCP bits in the IP headers for the new connection.  It
428  * should be in the range [0, 63] and will automatically be shifted to the
429  * appropriately place in the IP tos field. */
430 int
431 inet_open_active(int style, const char *target, uint16_t default_port,
432                  struct sockaddr_storage *ssp, int *fdp, uint8_t dscp)
433 {
434     struct sockaddr_storage ss;
435     int fd = -1;
436     int error;
437
438     /* Parse. */
439     if (!inet_parse_active(target, default_port, &ss)) {
440         error = EAFNOSUPPORT;
441         goto exit;
442     }
443
444     /* Create non-blocking socket. */
445     fd = socket(ss.ss_family, style, 0);
446     if (fd < 0) {
447         error = sock_errno();
448         VLOG_ERR("%s: socket: %s", target, sock_strerror(error));
449         goto exit;
450     }
451     error = set_nonblocking(fd);
452     if (error) {
453         goto exit;
454     }
455
456     /* The dscp bits must be configured before connect() to ensure that the
457      * TOS field is set during the connection establishment.  If set after
458      * connect(), the handshake SYN frames will be sent with a TOS of 0. */
459     error = set_dscp(fd, dscp);
460     if (error) {
461         VLOG_ERR("%s: set_dscp: %s", target, sock_strerror(error));
462         goto exit;
463     }
464
465     /* Connect. */
466     error = connect(fd, (struct sockaddr *) &ss, ss_length(&ss)) == 0
467                     ? 0
468                     : sock_errno();
469     if (error == EINPROGRESS
470 #ifdef _WIN32
471         || error == WSAEALREADY || error == WSAEWOULDBLOCK
472 #endif
473         ) {
474         error = EAGAIN;
475     }
476
477 exit:
478     if (error && error != EAGAIN) {
479         if (ssp) {
480             memset(ssp, 0, sizeof *ssp);
481         }
482         if (fd >= 0) {
483             closesocket(fd);
484             fd = -1;
485         }
486     } else {
487         if (ssp) {
488             *ssp = ss;
489         }
490     }
491     *fdp = fd;
492     return error;
493 }
494
495 /* Parses 'target', which should be a string in the format "[<port>][:<host>]":
496  *
497  *      - If 'default_port' is -1, then <port> is required.  Otherwise, if
498  *        <port> is omitted, then 'default_port' is used instead.
499  *
500  *      - If <port> (or 'default_port', if used) is 0, then no port is bound
501  *        and the TCP/IP stack will select a port.
502  *
503  *      - <host> is optional.  If supplied, it may be an IPv4 address or an
504  *        IPv6 address enclosed in square brackets.  If omitted, the IP address
505  *        is wildcarded.
506  *
507  * If successful, stores the address into '*ss' and returns true; otherwise
508  * zeros '*ss' and returns false. */
509 bool
510 inet_parse_passive(const char *target_, int default_port,
511                    struct sockaddr_storage *ss)
512 {
513     char *target = xstrdup(target_);
514     const char *port;
515     const char *host;
516     char *p;
517     bool ok;
518
519     p = target;
520     port = parse_bracketed_token(&p);
521     host = parse_bracketed_token(&p);
522     if (!port && default_port < 0) {
523         VLOG_ERR("%s: port must be specified", target_);
524         ok = false;
525     } else {
526         ok = parse_sockaddr_components(ss, host ? host : "0.0.0.0",
527                                        port, default_port, target_);
528     }
529     if (!ok) {
530         memset(ss, 0, sizeof *ss);
531     }
532     free(target);
533     return ok;
534 }
535
536
537 /* Opens a non-blocking IPv4 or IPv6 socket of the specified 'style', binds to
538  * 'target', and listens for incoming connections.  Parses 'target' in the same
539  * way was inet_parse_passive().
540  *
541  * 'style' should be SOCK_STREAM (for TCP) or SOCK_DGRAM (for UDP).
542  *
543  * For TCP, the socket will have SO_REUSEADDR turned on.
544  *
545  * On success, returns a non-negative file descriptor.  On failure, returns a
546  * negative errno value.
547  *
548  * If 'ss' is non-null, then on success stores the bound address into '*ss'.
549  *
550  * 'dscp' becomes the DSCP bits in the IP headers for the new connection.  It
551  * should be in the range [0, 63] and will automatically be shifted to the
552  * appropriately place in the IP tos field.
553  *
554  * If 'kernel_print_port' is true and the port is dynamically assigned by
555  * the kernel, print the chosen port. */
556 int
557 inet_open_passive(int style, const char *target, int default_port,
558                   struct sockaddr_storage *ssp, uint8_t dscp,
559                   bool kernel_print_port)
560 {
561     bool kernel_chooses_port;
562     struct sockaddr_storage ss;
563     int fd = 0, error;
564     unsigned int yes = 1;
565
566     if (!inet_parse_passive(target, default_port, &ss)) {
567         return -EAFNOSUPPORT;
568     }
569     kernel_chooses_port = ss_get_port(&ss) == 0;
570
571     /* Create non-blocking socket, set SO_REUSEADDR. */
572     fd = socket(ss.ss_family, style, 0);
573     if (fd < 0) {
574         error = sock_errno();
575         VLOG_ERR("%s: socket: %s", target, sock_strerror(error));
576         return -error;
577     }
578     error = set_nonblocking(fd);
579     if (error) {
580         goto error;
581     }
582     if (style == SOCK_STREAM
583         && setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof yes) < 0) {
584         error = sock_errno();
585         VLOG_ERR("%s: setsockopt(SO_REUSEADDR): %s",
586                  target, sock_strerror(error));
587         goto error;
588     }
589
590     /* Bind. */
591     if (bind(fd, (struct sockaddr *) &ss, ss_length(&ss)) < 0) {
592         error = sock_errno();
593         VLOG_ERR("%s: bind: %s", target, sock_strerror(error));
594         goto error;
595     }
596
597     /* The dscp bits must be configured before connect() to ensure that the TOS
598      * field is set during the connection establishment.  If set after
599      * connect(), the handshake SYN frames will be sent with a TOS of 0. */
600     error = set_dscp(fd, dscp);
601     if (error) {
602         VLOG_ERR("%s: set_dscp: %s", target, sock_strerror(error));
603         goto error;
604     }
605
606     /* Listen. */
607     if (style == SOCK_STREAM && listen(fd, 10) < 0) {
608         error = sock_errno();
609         VLOG_ERR("%s: listen: %s", target, sock_strerror(error));
610         goto error;
611     }
612
613     if (ssp || kernel_chooses_port) {
614         socklen_t ss_len = sizeof ss;
615         if (getsockname(fd, (struct sockaddr *) &ss, &ss_len) < 0) {
616             error = sock_errno();
617             VLOG_ERR("%s: getsockname: %s", target, sock_strerror(error));
618             goto error;
619         }
620         if (kernel_chooses_port && kernel_print_port) {
621             VLOG_INFO("%s: listening on port %"PRIu16,
622                       target, ss_get_port(&ss));
623         }
624         if (ssp) {
625             *ssp = ss;
626         }
627     }
628
629     return fd;
630
631 error:
632     if (ssp) {
633         memset(ssp, 0, sizeof *ssp);
634     }
635     closesocket(fd);
636     return -error;
637 }
638
639 int
640 read_fully(int fd, void *p_, size_t size, size_t *bytes_read)
641 {
642     uint8_t *p = p_;
643
644     *bytes_read = 0;
645     while (size > 0) {
646         ssize_t retval = read(fd, p, size);
647         if (retval > 0) {
648             *bytes_read += retval;
649             size -= retval;
650             p += retval;
651         } else if (retval == 0) {
652             return EOF;
653         } else if (errno != EINTR) {
654             return errno;
655         }
656     }
657     return 0;
658 }
659
660 int
661 write_fully(int fd, const void *p_, size_t size, size_t *bytes_written)
662 {
663     const uint8_t *p = p_;
664
665     *bytes_written = 0;
666     while (size > 0) {
667         ssize_t retval = write(fd, p, size);
668         if (retval > 0) {
669             *bytes_written += retval;
670             size -= retval;
671             p += retval;
672         } else if (retval == 0) {
673             VLOG_WARN("write returned 0");
674             return EPROTO;
675         } else if (errno != EINTR) {
676             return errno;
677         }
678     }
679     return 0;
680 }
681
682 /* Given file name 'file_name', fsyncs the directory in which it is contained.
683  * Returns 0 if successful, otherwise a positive errno value. */
684 int
685 fsync_parent_dir(const char *file_name)
686 {
687     int error = 0;
688 #ifndef _WIN32
689     char *dir;
690     int fd;
691
692     dir = dir_name(file_name);
693     fd = open(dir, O_RDONLY);
694     if (fd >= 0) {
695         if (fsync(fd)) {
696             if (errno == EINVAL || errno == EROFS) {
697                 /* This directory does not support synchronization.  Not
698                  * really an error. */
699             } else {
700                 error = errno;
701                 VLOG_ERR("%s: fsync failed (%s)", dir, ovs_strerror(error));
702             }
703         }
704         close(fd);
705     } else {
706         error = errno;
707         VLOG_ERR("%s: open failed (%s)", dir, ovs_strerror(error));
708     }
709     free(dir);
710 #endif
711
712     return error;
713 }
714
715 /* Obtains the modification time of the file named 'file_name' to the greatest
716  * supported precision.  If successful, stores the mtime in '*mtime' and
717  * returns 0.  On error, returns a positive errno value and stores zeros in
718  * '*mtime'. */
719 int
720 get_mtime(const char *file_name, struct timespec *mtime)
721 {
722     struct stat s;
723
724     if (!stat(file_name, &s)) {
725         mtime->tv_sec = s.st_mtime;
726
727 #if HAVE_STRUCT_STAT_ST_MTIM_TV_NSEC
728         mtime->tv_nsec = s.st_mtim.tv_nsec;
729 #elif HAVE_STRUCT_STAT_ST_MTIMENSEC
730         mtime->tv_nsec = s.st_mtimensec;
731 #else
732         mtime->tv_nsec = 0;
733 #endif
734
735         return 0;
736     } else {
737         mtime->tv_sec = mtime->tv_nsec = 0;
738         return errno;
739     }
740 }
741
742 static int
743 getsockopt_int(int fd, int level, int option, const char *optname, int *valuep)
744 {
745     static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(5, 10);
746     socklen_t len;
747     int value;
748     int error;
749
750     len = sizeof value;
751     if (getsockopt(fd, level, option, &value, &len)) {
752         error = sock_errno();
753         VLOG_ERR_RL(&rl, "getsockopt(%s): %s", optname, sock_strerror(error));
754     } else if (len != sizeof value) {
755         error = EINVAL;
756         VLOG_ERR_RL(&rl, "getsockopt(%s): value is %u bytes (expected %"PRIuSIZE")",
757                     optname, (unsigned int) len, sizeof value);
758     } else {
759         error = 0;
760     }
761
762     *valuep = error ? 0 : value;
763     return error;
764 }
765
766 static void
767 describe_sockaddr(struct ds *string, int fd,
768                   int (*getaddr)(int, struct sockaddr *, socklen_t *))
769 {
770     struct sockaddr_storage ss;
771     socklen_t len = sizeof ss;
772
773     if (!getaddr(fd, (struct sockaddr *) &ss, &len)) {
774         if (ss.ss_family == AF_INET || ss.ss_family == AF_INET6) {
775             char addrbuf[SS_NTOP_BUFSIZE];
776
777             ds_put_format(string, "%s:%"PRIu16,
778                           ss_format_address(&ss, addrbuf, sizeof addrbuf),
779                           ss_get_port(&ss));
780 #ifndef _WIN32
781         } else if (ss.ss_family == AF_UNIX) {
782             struct sockaddr_un sun;
783             const char *null;
784             size_t maxlen;
785
786             memcpy(&sun, &ss, sizeof sun);
787             maxlen = len - offsetof(struct sockaddr_un, sun_path);
788             null = memchr(sun.sun_path, '\0', maxlen);
789             ds_put_buffer(string, sun.sun_path,
790                           null ? null - sun.sun_path : maxlen);
791 #endif
792         }
793 #ifdef HAVE_NETLINK
794         else if (ss.ss_family == AF_NETLINK) {
795             int protocol;
796
797 /* SO_PROTOCOL was introduced in 2.6.32.  Support it regardless of the version
798  * of the Linux kernel headers in use at build time. */
799 #ifndef SO_PROTOCOL
800 #define SO_PROTOCOL 38
801 #endif
802
803             if (!getsockopt_int(fd, SOL_SOCKET, SO_PROTOCOL, "SO_PROTOCOL",
804                                 &protocol)) {
805                 switch (protocol) {
806                 case NETLINK_ROUTE:
807                     ds_put_cstr(string, "NETLINK_ROUTE");
808                     break;
809
810                 case NETLINK_GENERIC:
811                     ds_put_cstr(string, "NETLINK_GENERIC");
812                     break;
813
814                 default:
815                     ds_put_format(string, "AF_NETLINK family %d", protocol);
816                     break;
817                 }
818             } else {
819                 ds_put_cstr(string, "AF_NETLINK");
820             }
821         }
822 #endif
823 #if __linux__
824         else if (ss.ss_family == AF_PACKET) {
825             struct sockaddr_ll sll;
826
827             memcpy(&sll, &ss, sizeof sll);
828             ds_put_cstr(string, "AF_PACKET");
829             if (sll.sll_ifindex) {
830                 char name[IFNAMSIZ];
831
832                 if (if_indextoname(sll.sll_ifindex, name)) {
833                     ds_put_format(string, "(%s)", name);
834                 } else {
835                     ds_put_format(string, "(ifindex=%d)", sll.sll_ifindex);
836                 }
837             }
838             if (sll.sll_protocol) {
839                 ds_put_format(string, "(protocol=0x%"PRIu16")",
840                               ntohs(sll.sll_protocol));
841             }
842         }
843 #endif
844         else if (ss.ss_family == AF_UNSPEC) {
845             ds_put_cstr(string, "AF_UNSPEC");
846         } else {
847             ds_put_format(string, "AF_%d", (int) ss.ss_family);
848         }
849     }
850 }
851
852
853 #ifdef __linux__
854 static void
855 put_fd_filename(struct ds *string, int fd)
856 {
857     char buf[1024];
858     char *linkname;
859     int n;
860
861     linkname = xasprintf("/proc/self/fd/%d", fd);
862     n = readlink(linkname, buf, sizeof buf);
863     if (n > 0) {
864         ds_put_char(string, ' ');
865         ds_put_buffer(string, buf, n);
866         if (n > sizeof buf) {
867             ds_put_cstr(string, "...");
868         }
869     }
870     free(linkname);
871 }
872 #endif
873
874 /* Returns a malloc()'d string describing 'fd', for use in logging. */
875 char *
876 describe_fd(int fd)
877 {
878     struct ds string;
879     struct stat s;
880
881     ds_init(&string);
882 #ifndef _WIN32
883     if (fstat(fd, &s)) {
884         ds_put_format(&string, "fstat failed (%s)", ovs_strerror(errno));
885     } else if (S_ISSOCK(s.st_mode)) {
886         describe_sockaddr(&string, fd, getsockname);
887         ds_put_cstr(&string, "<->");
888         describe_sockaddr(&string, fd, getpeername);
889     } else {
890         ds_put_cstr(&string, (isatty(fd) ? "tty"
891                               : S_ISDIR(s.st_mode) ? "directory"
892                               : S_ISCHR(s.st_mode) ? "character device"
893                               : S_ISBLK(s.st_mode) ? "block device"
894                               : S_ISREG(s.st_mode) ? "file"
895                               : S_ISFIFO(s.st_mode) ? "FIFO"
896                               : S_ISLNK(s.st_mode) ? "symbolic link"
897                               : "unknown"));
898 #ifdef __linux__
899         put_fd_filename(&string, fd);
900 #endif
901     }
902 #else
903     ds_put_format(&string,"file descriptor");
904 #endif /* _WIN32 */
905     return ds_steal_cstr(&string);
906 }
907
908 \f
909 /* sockaddr_storage helpers. */
910
911 /* Returns the IPv4 or IPv6 port in 'ss'. */
912 uint16_t
913 ss_get_port(const struct sockaddr_storage *ss)
914 {
915     if (ss->ss_family == AF_INET) {
916         const struct sockaddr_in *sin
917             = ALIGNED_CAST(const struct sockaddr_in *, ss);
918         return ntohs(sin->sin_port);
919     } else if (ss->ss_family == AF_INET6) {
920         const struct sockaddr_in6 *sin6
921             = ALIGNED_CAST(const struct sockaddr_in6 *, ss);
922         return ntohs(sin6->sin6_port);
923     } else {
924         OVS_NOT_REACHED();
925     }
926 }
927
928 /* Formats the IPv4 or IPv6 address in 'ss' into the 'bufsize' bytes in 'buf'.
929  * If 'ss' is an IPv6 address, puts square brackets around the address.
930  * 'bufsize' should be at least SS_NTOP_BUFSIZE.
931  *
932  * Returns 'buf'. */
933 char *
934 ss_format_address(const struct sockaddr_storage *ss,
935                   char *buf, size_t bufsize)
936 {
937     ovs_assert(bufsize >= SS_NTOP_BUFSIZE);
938     if (ss->ss_family == AF_INET) {
939         const struct sockaddr_in *sin
940             = ALIGNED_CAST(const struct sockaddr_in *, ss);
941
942         snprintf(buf, bufsize, IP_FMT, IP_ARGS(sin->sin_addr.s_addr));
943     } else if (ss->ss_family == AF_INET6) {
944         const struct sockaddr_in6 *sin6
945             = ALIGNED_CAST(const struct sockaddr_in6 *, ss);
946
947         buf[0] = '[';
948         inet_ntop(AF_INET6, sin6->sin6_addr.s6_addr, buf + 1, bufsize - 1);
949         strcpy(strchr(buf, '\0'), "]");
950     } else {
951         OVS_NOT_REACHED();
952     }
953
954     return buf;
955 }
956
957 size_t
958 ss_length(const struct sockaddr_storage *ss)
959 {
960     switch (ss->ss_family) {
961     case AF_INET:
962         return sizeof(struct sockaddr_in);
963
964     case AF_INET6:
965         return sizeof(struct sockaddr_in6);
966
967     default:
968         OVS_NOT_REACHED();
969     }
970 }
971
972 /* For Windows socket calls, 'errno' is not set.  One has to call
973  * WSAGetLastError() to get the error number and then pass it to
974  * this function to get the correct error string.
975  *
976  * ovs_strerror() calls strerror_r() and would not get the correct error
977  * string for Windows sockets, but is good for POSIX. */
978 const char *
979 sock_strerror(int error)
980 {
981 #ifdef _WIN32
982     return ovs_format_message(error);
983 #else
984     return ovs_strerror(error);
985 #endif
986 }