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