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