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