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