]> git.ipfire.org Git - thirdparty/systemd.git/blame - src/basic/socket-util.c
socket-util: check for sysconf() error before using value
[thirdparty/systemd.git] / src / basic / socket-util.c
CommitLineData
db9ecf05 1/* SPDX-License-Identifier: LGPL-2.1-or-later */
a7334b09 2
42f4e3c4 3#include <arpa/inet.h>
07630cea 4#include <errno.h>
11c3a366 5#include <limits.h>
542563ba 6#include <net/if.h>
b31f535c 7#include <netdb.h>
2583fbea 8#include <netinet/ip.h>
60d9771c 9#include <poll.h>
07630cea 10#include <stddef.h>
11c3a366 11#include <stdint.h>
07630cea 12#include <stdio.h>
11c3a366 13#include <stdlib.h>
f5947a5e 14#include <sys/ioctl.h>
07630cea 15#include <unistd.h>
4252696a 16#include <linux/if.h>
42f4e3c4 17
b5efdb8a 18#include "alloc-util.h"
4ff9bc2e 19#include "errno-util.h"
15dca371 20#include "escape.h"
2583fbea 21#include "fd-util.h"
07630cea 22#include "fileio.h"
f97b34a6 23#include "format-util.h"
0f2d351f 24#include "io-util.h"
93cc7779 25#include "log.h"
0a970718 26#include "memory-util.h"
6bedfcbb 27#include "parse-util.h"
9eb977db 28#include "path-util.h"
dccca82b 29#include "process-util.h"
2583fbea 30#include "socket-util.h"
8b43440b 31#include "string-table.h"
07630cea 32#include "string-util.h"
ef76dff2 33#include "strv.h"
83e03c4f 34#include "sysctl-util.h"
ee104e11 35#include "user-util.h"
ef76dff2 36#include "utf8.h"
42f4e3c4 37
349cc4a5 38#if ENABLE_IDN
cadc80b8 39# define IDN_FLAGS NI_IDN
6326a143
WB
40#else
41# define IDN_FLAGS 0
42#endif
43
598d2428
LB
44/* From the kernel's include/net/scm.h */
45#ifndef SCM_MAX_FD
46# define SCM_MAX_FD 253
47#endif
48
398ce0bc 49static const char* const socket_address_type_table[] = {
955bb7fa
ZJS
50 [SOCK_STREAM] = "Stream",
51 [SOCK_DGRAM] = "Datagram",
52 [SOCK_RAW] = "Raw",
53 [SOCK_RDM] = "ReliableDatagram",
398ce0bc 54 [SOCK_SEQPACKET] = "SequentialPacket",
955bb7fa 55 [SOCK_DCCP] = "DatagramCongestionControl",
398ce0bc
YW
56};
57
58DEFINE_STRING_TABLE_LOOKUP(socket_address_type, int);
59
15dca371 60int socket_address_verify(const SocketAddress *a, bool strict) {
42f4e3c4
LP
61 assert(a);
62
15dca371
ZJS
63 /* With 'strict' we enforce additional sanity constraints which are not set by the standard,
64 * but should only apply to sockets we create ourselves. */
65
542563ba 66 switch (socket_address_family(a)) {
42f4e3c4 67
7a22745a
LP
68 case AF_INET:
69 if (a->size != sizeof(struct sockaddr_in))
70 return -EINVAL;
42f4e3c4 71
4d49b48c 72 if (a->sockaddr.in.sin_port == 0)
7a22745a 73 return -EINVAL;
42f4e3c4 74
44ab2347 75 if (!IN_SET(a->type, 0, SOCK_STREAM, SOCK_DGRAM))
7a22745a 76 return -EINVAL;
42f4e3c4 77
7a22745a
LP
78 return 0;
79
80 case AF_INET6:
81 if (a->size != sizeof(struct sockaddr_in6))
82 return -EINVAL;
42f4e3c4 83
7a22745a
LP
84 if (a->sockaddr.in6.sin6_port == 0)
85 return -EINVAL;
42f4e3c4 86
44ab2347 87 if (!IN_SET(a->type, 0, SOCK_STREAM, SOCK_DGRAM))
7a22745a 88 return -EINVAL;
42f4e3c4 89
7a22745a 90 return 0;
42f4e3c4 91
7a22745a
LP
92 case AF_UNIX:
93 if (a->size < offsetof(struct sockaddr_un, sun_path))
94 return -EINVAL;
15dca371
ZJS
95 if (a->size > sizeof(struct sockaddr_un) + !strict)
96 /* If !strict, allow one extra byte, since getsockname() on Linux will append
97 * a NUL byte if we have path sockets that are above sun_path's full size. */
8e8132c6 98 return -EINVAL;
42f4e3c4 99
8e8132c6 100 if (a->size > offsetof(struct sockaddr_un, sun_path) &&
15dca371
ZJS
101 a->sockaddr.un.sun_path[0] != 0 &&
102 strict) {
103 /* Only validate file system sockets here, and only in strict mode */
8e8132c6 104 const char *e;
7a22745a 105
8e8132c6
LP
106 e = memchr(a->sockaddr.un.sun_path, 0, sizeof(a->sockaddr.un.sun_path));
107 if (e) {
15dca371 108 /* If there's an embedded NUL byte, make sure the size of the socket address matches it */
7a22745a
LP
109 if (a->size != offsetof(struct sockaddr_un, sun_path) + (e - a->sockaddr.un.sun_path) + 1)
110 return -EINVAL;
8e8132c6 111 } else {
d7b34e38 112 /* If there's no embedded NUL byte, then the size needs to match the whole
8e8132c6
LP
113 * structure or the structure with one extra NUL byte suffixed. (Yeah, Linux is awful,
114 * and considers both equivalent: getsockname() even extends sockaddr_un beyond its
7802194a 115 * size if the path is non NUL terminated.) */
8e8132c6
LP
116 if (!IN_SET(a->size, sizeof(a->sockaddr.un.sun_path), sizeof(a->sockaddr.un.sun_path)+1))
117 return -EINVAL;
42f4e3c4 118 }
7a22745a 119 }
42f4e3c4 120
44ab2347 121 if (!IN_SET(a->type, 0, SOCK_STREAM, SOCK_DGRAM, SOCK_SEQPACKET))
7a22745a 122 return -EINVAL;
42f4e3c4 123
7a22745a
LP
124 return 0;
125
126 case AF_NETLINK:
127
128 if (a->size != sizeof(struct sockaddr_nl))
129 return -EINVAL;
130
44ab2347 131 if (!IN_SET(a->type, 0, SOCK_RAW, SOCK_DGRAM))
7a22745a
LP
132 return -EINVAL;
133
134 return 0;
135
0fc0f14b
SH
136 case AF_VSOCK:
137 if (a->size != sizeof(struct sockaddr_vm))
138 return -EINVAL;
139
44ab2347 140 if (!IN_SET(a->type, 0, SOCK_STREAM, SOCK_DGRAM))
0fc0f14b
SH
141 return -EINVAL;
142
143 return 0;
144
7a22745a
LP
145 default:
146 return -EAFNOSUPPORT;
42f4e3c4
LP
147 }
148}
149
4d49b48c 150int socket_address_print(const SocketAddress *a, char **ret) {
42f4e3c4 151 int r;
4d49b48c 152
42f4e3c4 153 assert(a);
4d49b48c 154 assert(ret);
42f4e3c4 155
15dca371
ZJS
156 r = socket_address_verify(a, false); /* We do non-strict validation, because we want to be
157 * able to pretty-print any socket the kernel considers
158 * valid. We still need to do validation to know if we
159 * can meaningfully print the address. */
4d49b48c 160 if (r < 0)
42f4e3c4
LP
161 return r;
162
4d49b48c 163 if (socket_address_family(a) == AF_NETLINK) {
7fd1b19b 164 _cleanup_free_ char *sfamily = NULL;
7a22745a 165
f8b69d1d 166 r = netlink_family_to_string_alloc(a->protocol, &sfamily);
7a22745a 167 if (r < 0)
f8b69d1d 168 return r;
4d49b48c
LP
169
170 r = asprintf(ret, "%s %u", sfamily, a->sockaddr.nl.nl_groups);
8520cfa5
MS
171 if (r < 0)
172 return -ENOMEM;
7a22745a
LP
173
174 return 0;
175 }
176
3b1c5241 177 return sockaddr_pretty(&a->sockaddr.sa, a->size, false, true, ret);
42f4e3c4
LP
178}
179
4f2d528d
LP
180bool socket_address_can_accept(const SocketAddress *a) {
181 assert(a);
182
183 return
3742095b 184 IN_SET(a->type, SOCK_STREAM, SOCK_SEQPACKET);
4f2d528d 185}
a16e1123
LP
186
187bool socket_address_equal(const SocketAddress *a, const SocketAddress *b) {
188 assert(a);
189 assert(b);
190
191 /* Invalid addresses are unequal to all */
15dca371
ZJS
192 if (socket_address_verify(a, false) < 0 ||
193 socket_address_verify(b, false) < 0)
a16e1123
LP
194 return false;
195
196 if (a->type != b->type)
197 return false;
198
a16e1123
LP
199 if (socket_address_family(a) != socket_address_family(b))
200 return false;
201
202 switch (socket_address_family(a)) {
203
204 case AF_INET:
4d49b48c 205 if (a->sockaddr.in.sin_addr.s_addr != b->sockaddr.in.sin_addr.s_addr)
a16e1123
LP
206 return false;
207
4d49b48c 208 if (a->sockaddr.in.sin_port != b->sockaddr.in.sin_port)
a16e1123
LP
209 return false;
210
211 break;
212
213 case AF_INET6:
214 if (memcmp(&a->sockaddr.in6.sin6_addr, &b->sockaddr.in6.sin6_addr, sizeof(a->sockaddr.in6.sin6_addr)) != 0)
215 return false;
216
217 if (a->sockaddr.in6.sin6_port != b->sockaddr.in6.sin6_port)
218 return false;
219
220 break;
221
222 case AF_UNIX:
710708a5
MS
223 if (a->size <= offsetof(struct sockaddr_un, sun_path) ||
224 b->size <= offsetof(struct sockaddr_un, sun_path))
225 return false;
226
a16e1123
LP
227 if ((a->sockaddr.un.sun_path[0] == 0) != (b->sockaddr.un.sun_path[0] == 0))
228 return false;
229
230 if (a->sockaddr.un.sun_path[0]) {
563e6846 231 if (!path_equal_or_inode_same(a->sockaddr.un.sun_path, b->sockaddr.un.sun_path, 0))
a16e1123
LP
232 return false;
233 } else {
c78e47a6
MS
234 if (a->size != b->size)
235 return false;
236
b12c1e7c 237 if (memcmp(a->sockaddr.un.sun_path, b->sockaddr.un.sun_path, a->size) != 0)
a16e1123
LP
238 return false;
239 }
240
241 break;
242
7a22745a 243 case AF_NETLINK:
7a22745a
LP
244 if (a->protocol != b->protocol)
245 return false;
246
247 if (a->sockaddr.nl.nl_groups != b->sockaddr.nl.nl_groups)
248 return false;
249
250 break;
251
0fc0f14b
SH
252 case AF_VSOCK:
253 if (a->sockaddr.vm.svm_cid != b->sockaddr.vm.svm_cid)
254 return false;
255
256 if (a->sockaddr.vm.svm_port != b->sockaddr.vm.svm_port)
257 return false;
258
259 break;
260
a16e1123
LP
261 default:
262 /* Cannot compare, so we assume the addresses are different */
263 return false;
264 }
265
266 return true;
267}
268
a57f7e2c 269const char* socket_address_get_path(const SocketAddress *a) {
6e2ef85b
LP
270 assert(a);
271
272 if (socket_address_family(a) != AF_UNIX)
a57f7e2c 273 return NULL;
6e2ef85b
LP
274
275 if (a->sockaddr.un.sun_path[0] == 0)
a57f7e2c 276 return NULL;
a16e1123 277
48e6a2dc
LP
278 /* Note that this is only safe because we know that there's an extra NUL byte after the sockaddr_un
279 * structure. On Linux AF_UNIX file system socket addresses don't have to be NUL terminated if they take up the
280 * full sun_path space. */
281 assert_cc(sizeof(union sockaddr_union) >= sizeof(struct sockaddr_un)+1);
a57f7e2c 282 return a->sockaddr.un.sun_path;
a16e1123 283}
c0120d99 284
5bfcc1c6 285bool socket_ipv6_is_supported(void) {
571ec995 286 static int cached = -1;
f89f1e8f 287
571ec995
LP
288 if (cached < 0) {
289
290 if (access("/proc/net/if_inet6", F_OK) < 0) {
291
292 if (errno != ENOENT) {
293 log_debug_errno(errno, "Unexpected error when checking whether /proc/net/if_inet6 exists: %m");
294 return false;
295 }
296
297 cached = false;
298 } else
299 cached = true;
300 }
301
302 return cached;
5bfcc1c6
FF
303}
304
83e03c4f 305bool socket_ipv6_is_enabled(void) {
f96f5d54 306 _cleanup_free_ char *v = NULL;
83e03c4f
LP
307 int r;
308
309 /* Much like socket_ipv6_is_supported(), but also checks that the sysctl that disables IPv6 on all
310 * interfaces isn't turned on */
311
312 if (!socket_ipv6_is_supported())
90ab5042 313 return false;
f89f1e8f 314
83e03c4f
LP
315 r = sysctl_read_ip_property(AF_INET6, "all", "disable_ipv6", &v);
316 if (r < 0) {
317 log_debug_errno(r, "Unexpected error reading 'net.ipv6.conf.all.disable_ipv6' sysctl: %m");
318 return true;
319 }
320
321 r = parse_boolean(v);
322 if (r < 0) {
323 log_debug_errno(r, "Failed to pare 'net.ipv6.conf.all.disable_ipv6' sysctl: %m");
324 return true;
325 }
326
327 return !r;
5bfcc1c6
FF
328}
329
01e10de3 330bool socket_address_matches_fd(const SocketAddress *a, int fd) {
dbafedac
MS
331 SocketAddress b;
332 socklen_t solen;
01e10de3
LP
333
334 assert(a);
335 assert(fd >= 0);
336
dbafedac
MS
337 b.size = sizeof(b.sockaddr);
338 if (getsockname(fd, &b.sockaddr.sa, &b.size) < 0)
01e10de3
LP
339 return false;
340
dbafedac 341 if (b.sockaddr.sa.sa_family != a->sockaddr.sa.sa_family)
01e10de3
LP
342 return false;
343
dbafedac
MS
344 solen = sizeof(b.type);
345 if (getsockopt(fd, SOL_SOCKET, SO_TYPE, &b.type, &solen) < 0)
01e10de3
LP
346 return false;
347
dbafedac 348 if (b.type != a->type)
01e10de3
LP
349 return false;
350
351 if (a->protocol != 0) {
dbafedac
MS
352 solen = sizeof(b.protocol);
353 if (getsockopt(fd, SOL_SOCKET, SO_PROTOCOL, &b.protocol, &solen) < 0)
01e10de3
LP
354 return false;
355
dbafedac 356 if (b.protocol != a->protocol)
01e10de3
LP
357 return false;
358 }
359
02233928 360 return socket_address_equal(a, &b);
01e10de3
LP
361}
362
f6aac5bf 363int sockaddr_port(const struct sockaddr *_sa, unsigned *ret_port) {
31325971 364 const union sockaddr_union *sa = (const union sockaddr_union*) _sa;
3b1c5241 365
f6aac5bf
LP
366 /* Note, this returns the port as 'unsigned' rather than 'uint16_t', as AF_VSOCK knows larger ports */
367
3b1c5241
SL
368 assert(sa);
369
0fc0f14b 370 switch (sa->sa.sa_family) {
f6aac5bf 371
0fc0f14b 372 case AF_INET:
f6aac5bf 373 *ret_port = be16toh(sa->in.sin_port);
0fc0f14b 374 return 0;
3b1c5241 375
0fc0f14b 376 case AF_INET6:
f6aac5bf 377 *ret_port = be16toh(sa->in6.sin6_port);
0fc0f14b
SH
378 return 0;
379
380 case AF_VSOCK:
f6aac5bf 381 *ret_port = sa->vm.svm_port;
0fc0f14b
SH
382 return 0;
383
384 default:
385 return -EAFNOSUPPORT;
386 }
3b1c5241
SL
387}
388
31325971
LP
389const union in_addr_union *sockaddr_in_addr(const struct sockaddr *_sa) {
390 const union sockaddr_union *sa = (const union sockaddr_union*) _sa;
391
392 if (!sa)
393 return NULL;
394
395 switch (sa->sa.sa_family) {
396
397 case AF_INET:
398 return (const union in_addr_union*) &sa->in.sin_addr;
399
400 case AF_INET6:
401 return (const union in_addr_union*) &sa->in6.sin6_addr;
402
403 default:
404 return NULL;
405 }
406}
407
c1b91f06
LP
408int sockaddr_set_in_addr(
409 union sockaddr_union *u,
410 int family,
411 const union in_addr_union *a,
412 uint16_t port) {
413
414 assert(u);
415 assert(a);
416
417 switch (family) {
418
419 case AF_INET:
420 u->in = (struct sockaddr_in) {
421 .sin_family = AF_INET,
422 .sin_addr = a->in,
423 .sin_port = htobe16(port),
424 };
425
426 return 0;
427
428 case AF_INET6:
429 u->in6 = (struct sockaddr_in6) {
430 .sin6_family = AF_INET6,
431 .sin6_addr = a->in6,
432 .sin6_port = htobe16(port),
433 };
434
435 return 0;
436
437 default:
438 return -EAFNOSUPPORT;
439
440 }
441}
442
836f9cfe
LP
443int sockaddr_pretty(
444 const struct sockaddr *_sa,
445 socklen_t salen,
446 bool translate_ipv6,
447 bool include_port,
448 char **ret) {
449
4d49b48c 450 union sockaddr_union *sa = (union sockaddr_union*) _sa;
8569a776 451 char *p;
fc25ad25 452 int r;
8569a776 453
4d49b48c
LP
454 assert(sa);
455 assert(salen >= sizeof(sa->sa.sa_family));
8569a776 456
4d49b48c 457 switch (sa->sa.sa_family) {
8569a776
LP
458
459 case AF_INET: {
460 uint32_t a;
461
8e38570e 462 a = be32toh(sa->in.sin_addr.s_addr);
8569a776 463
fc25ad25
ZJS
464 if (include_port)
465 r = asprintf(&p,
3b1c5241
SL
466 "%u.%u.%u.%u:%u",
467 a >> 24, (a >> 16) & 0xFF, (a >> 8) & 0xFF, a & 0xFF,
8e38570e 468 be16toh(sa->in.sin_port));
fc25ad25
ZJS
469 else
470 r = asprintf(&p,
3b1c5241 471 "%u.%u.%u.%u",
fc25ad25
ZJS
472 a >> 24, (a >> 16) & 0xFF, (a >> 8) & 0xFF, a & 0xFF);
473 if (r < 0)
474 return -ENOMEM;
8569a776
LP
475 break;
476 }
477
478 case AF_INET6: {
479 static const unsigned char ipv4_prefix[] = {
480 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xFF, 0xFF
481 };
482
fc25ad25
ZJS
483 if (translate_ipv6 &&
484 memcmp(&sa->in6.sin6_addr, ipv4_prefix, sizeof(ipv4_prefix)) == 0) {
4d49b48c 485 const uint8_t *a = sa->in6.sin6_addr.s6_addr+12;
fc25ad25
ZJS
486 if (include_port)
487 r = asprintf(&p,
3b1c5241
SL
488 "%u.%u.%u.%u:%u",
489 a[0], a[1], a[2], a[3],
8e38570e 490 be16toh(sa->in6.sin6_port));
fc25ad25
ZJS
491 else
492 r = asprintf(&p,
3b1c5241 493 "%u.%u.%u.%u",
fc25ad25
ZJS
494 a[0], a[1], a[2], a[3]);
495 if (r < 0)
496 return -ENOMEM;
8569a776 497 } else {
071e522e 498 const char *a = IN6_ADDR_TO_STRING(&sa->in6.sin6_addr);
3b1c5241
SL
499
500 if (include_port) {
01afd0f7 501 if (asprintf(&p,
b16d17a6 502 "[%s]:%u%s%s",
3b1c5241 503 a,
b16d17a6
ZJS
504 be16toh(sa->in6.sin6_port),
505 sa->in6.sin6_scope_id != 0 ? "%" : "",
01afd0f7 506 FORMAT_IFNAME_FULL(sa->in6.sin6_scope_id, FORMAT_IFNAME_IFINDEX)) < 0)
3b1c5241
SL
507 return -ENOMEM;
508 } else {
01afd0f7
YW
509 if (sa->in6.sin6_scope_id != 0)
510 p = strjoin(a, "%", FORMAT_IFNAME_FULL(sa->in6.sin6_scope_id, FORMAT_IFNAME_IFINDEX));
511 else
512 p = strdup(a);
3b1c5241
SL
513 if (!p)
514 return -ENOMEM;
515 }
8569a776
LP
516 }
517
518 break;
519 }
520
4d49b48c 521 case AF_UNIX:
15dca371 522 if (salen <= offsetof(struct sockaddr_un, sun_path) ||
994b9d4e 523 (sa->un.sun_path[0] == 0 && salen == offsetof(struct sockaddr_un, sun_path) + 1))
15dca371 524 /* The name must have at least one character (and the leading NUL does not count) */
4d49b48c 525 p = strdup("<unnamed>");
994b9d4e 526 else {
085b39e9
LP
527 /* Note that we calculate the path pointer here through the .un_buffer[] field, in order to
528 * outtrick bounds checking tools such as ubsan, which are too smart for their own good: on
529 * Linux the kernel may return sun_path[] data one byte longer than the declared size of the
530 * field. */
531 char *path = (char*) sa->un_buffer + offsetof(struct sockaddr_un, sun_path);
15dca371 532 size_t path_len = salen - offsetof(struct sockaddr_un, sun_path);
8569a776 533
085b39e9 534 if (path[0] == 0) {
15dca371
ZJS
535 /* Abstract socket. When parsing address information from, we
536 * explicitly reject overly long paths and paths with embedded NULs.
537 * But we might get such a socket from the outside. Let's return
538 * something meaningful and printable in this case. */
4d49b48c 539
15dca371 540 _cleanup_free_ char *e = NULL;
4d49b48c 541
085b39e9 542 e = cescape_length(path + 1, path_len - 1);
15dca371
ZJS
543 if (!e)
544 return -ENOMEM;
4d49b48c 545
15dca371
ZJS
546 p = strjoin("@", e);
547 } else {
085b39e9 548 if (path[path_len - 1] == '\0')
15dca371 549 /* We expect a terminating NUL and don't print it */
b3a9d980 550 path_len--;
15dca371 551
085b39e9 552 p = cescape_length(path, path_len);
15dca371 553 }
4d49b48c 554 }
994b9d4e
LP
555 if (!p)
556 return -ENOMEM;
8569a776
LP
557
558 break;
8569a776 559
0fc0f14b 560 case AF_VSOCK:
3a484991
ZJS
561 if (include_port) {
562 if (sa->vm.svm_cid == VMADDR_CID_ANY)
563 r = asprintf(&p, "vsock::%u", sa->vm.svm_port);
564 else
565 r = asprintf(&p, "vsock:%u:%u", sa->vm.svm_cid, sa->vm.svm_port);
566 } else
0fc0f14b
SH
567 r = asprintf(&p, "vsock:%u", sa->vm.svm_cid);
568 if (r < 0)
569 return -ENOMEM;
570 break;
571
8569a776 572 default:
15411c0c 573 return -EOPNOTSUPP;
8569a776
LP
574 }
575
576 *ret = p;
577 return 0;
578}
579
366b7db4 580int getpeername_pretty(int fd, bool include_port, char **ret) {
4d49b48c 581 union sockaddr_union sa;
b31f535c 582 socklen_t salen = sizeof(sa);
eff05270 583 int r;
4d49b48c
LP
584
585 assert(fd >= 0);
586 assert(ret);
587
4d49b48c
LP
588 if (getpeername(fd, &sa.sa, &salen) < 0)
589 return -errno;
590
591 if (sa.sa.sa_family == AF_UNIX) {
a995ce47 592 struct ucred ucred = UCRED_INVALID;
4d49b48c
LP
593
594 /* UNIX connection sockets are anonymous, so let's use
595 * PID/UID as pretty credentials instead */
596
eff05270
LP
597 r = getpeercred(fd, &ucred);
598 if (r < 0)
599 return r;
4d49b48c 600
de0671ee 601 if (asprintf(ret, "PID "PID_FMT"/UID "UID_FMT, ucred.pid, ucred.uid) < 0)
4d49b48c
LP
602 return -ENOMEM;
603
604 return 0;
605 }
606
607 /* For remote sockets we translate IPv6 addresses back to IPv4
608 * if applicable, since that's nicer. */
609
366b7db4 610 return sockaddr_pretty(&sa.sa, salen, true, include_port, ret);
4d49b48c
LP
611}
612
613int getsockname_pretty(int fd, char **ret) {
614 union sockaddr_union sa;
b31f535c 615 socklen_t salen = sizeof(sa);
4d49b48c
LP
616
617 assert(fd >= 0);
618 assert(ret);
619
4d49b48c
LP
620 if (getsockname(fd, &sa.sa, &salen) < 0)
621 return -errno;
622
623 /* For local sockets we do not translate IPv6 addresses back
624 * to IPv6 if applicable, since this is usually used for
625 * listening sockets where the difference between IPv4 and
626 * IPv6 matters. */
627
3b1c5241 628 return sockaddr_pretty(&sa.sa, salen, false, true, ret);
4d49b48c
LP
629}
630
fc1f05eb
LP
631int socknameinfo_pretty(const struct sockaddr *sa, socklen_t salen, char **ret) {
632 char host[NI_MAXHOST];
b31f535c 633 int r;
b31f535c 634
fc1f05eb
LP
635 assert(sa);
636 assert(salen > sizeof(sa_family_t));
b31f535c 637
fc1f05eb 638 r = getnameinfo(sa, salen, host, sizeof(host), /* service= */ NULL, /* service_len= */ 0, IDN_FLAGS);
b31f535c 639 if (r != 0) {
fc1f05eb
LP
640 if (r == EAI_MEMORY)
641 return log_oom_debug();
642 if (r == EAI_SYSTEM)
643 log_debug_errno(errno, "getnameinfo() failed, ignoring: %m");
644 else
645 log_debug("getnameinfo() failed, ignoring: %s", gai_strerror(r));
b31f535c 646
fc1f05eb
LP
647 return sockaddr_pretty(sa, salen, /* translate_ipv6= */ true, /* include_port= */ true, ret);
648 }
b31f535c 649
fc1f05eb
LP
650 if (ret) {
651 char *copy = strdup(host);
652 if (!copy)
1938ac51 653 return -ENOMEM;
fc1f05eb
LP
654
655 *ret = copy;
cb651834 656 }
b31f535c 657
b31f535c
ZJS
658 return 0;
659}
660
7a22745a 661static const char* const netlink_family_table[] = {
0d7e34e3
ZJS
662 [NETLINK_ROUTE] = "route",
663 [NETLINK_FIREWALL] = "firewall",
664 [NETLINK_INET_DIAG] = "inet-diag",
665 [NETLINK_NFLOG] = "nflog",
666 [NETLINK_XFRM] = "xfrm",
667 [NETLINK_SELINUX] = "selinux",
668 [NETLINK_ISCSI] = "iscsi",
669 [NETLINK_AUDIT] = "audit",
670 [NETLINK_FIB_LOOKUP] = "fib-lookup",
671 [NETLINK_CONNECTOR] = "connector",
672 [NETLINK_NETFILTER] = "netfilter",
673 [NETLINK_IP6_FW] = "ip6-fw",
674 [NETLINK_DNRTMSG] = "dnrtmsg",
7a22745a 675 [NETLINK_KOBJECT_UEVENT] = "kobject-uevent",
0d7e34e3
ZJS
676 [NETLINK_GENERIC] = "generic",
677 [NETLINK_SCSITRANSPORT] = "scsitransport",
678 [NETLINK_ECRYPTFS] = "ecryptfs",
679 [NETLINK_RDMA] = "rdma",
7a22745a
LP
680};
681
f8b69d1d 682DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(netlink_family, int, INT_MAX);
7a22745a 683
c0120d99
LP
684static const char* const socket_address_bind_ipv6_only_table[_SOCKET_ADDRESS_BIND_IPV6_ONLY_MAX] = {
685 [SOCKET_ADDRESS_DEFAULT] = "default",
686 [SOCKET_ADDRESS_BOTH] = "both",
687 [SOCKET_ADDRESS_IPV6_ONLY] = "ipv6-only"
688};
689
690DEFINE_STRING_TABLE_LOOKUP(socket_address_bind_ipv6_only, SocketAddressBindIPv6Only);
f01e5736 691
b54e98ef 692SocketAddressBindIPv6Only socket_address_bind_ipv6_only_or_bool_from_string(const char *n) {
6f90844f
YW
693 int r;
694
695 r = parse_boolean(n);
696 if (r > 0)
697 return SOCKET_ADDRESS_IPV6_ONLY;
698 if (r == 0)
699 return SOCKET_ADDRESS_BOTH;
700
701 return socket_address_bind_ipv6_only_from_string(n);
702}
703
f01e5736
LP
704bool sockaddr_equal(const union sockaddr_union *a, const union sockaddr_union *b) {
705 assert(a);
706 assert(b);
707
708 if (a->sa.sa_family != b->sa.sa_family)
709 return false;
710
711 if (a->sa.sa_family == AF_INET)
712 return a->in.sin_addr.s_addr == b->in.sin_addr.s_addr;
713
714 if (a->sa.sa_family == AF_INET6)
715 return memcmp(&a->in6.sin6_addr, &b->in6.sin6_addr, sizeof(a->in6.sin6_addr)) == 0;
716
0fc0f14b
SH
717 if (a->sa.sa_family == AF_VSOCK)
718 return a->vm.svm_cid == b->vm.svm_cid;
719
f01e5736
LP
720 return false;
721}
2583fbea 722
d9d9b2a0 723int fd_set_sndbuf(int fd, size_t n, bool increase) {
2583fbea
LP
724 int r, value;
725 socklen_t l = sizeof(value);
726
1263c85e
YW
727 if (n > INT_MAX)
728 return -ERANGE;
729
2583fbea 730 r = getsockopt(fd, SOL_SOCKET, SO_SNDBUF, &value, &l);
d9d9b2a0 731 if (r >= 0 && l == sizeof(value) && increase ? (size_t) value >= n*2 : (size_t) value == n*2)
2583fbea
LP
732 return 0;
733
b92f3507
YW
734 /* First, try to set the buffer size with SO_SNDBUF. */
735 r = setsockopt_int(fd, SOL_SOCKET, SO_SNDBUF, n);
736 if (r < 0)
737 return r;
2583fbea 738
b92f3507
YW
739 /* SO_SNDBUF above may set to the kernel limit, instead of the requested size.
740 * So, we need to check the actual buffer size here. */
67f5ae2d 741 l = sizeof(value);
b92f3507 742 r = getsockopt(fd, SOL_SOCKET, SO_SNDBUF, &value, &l);
d9d9b2a0 743 if (r >= 0 && l == sizeof(value) && increase ? (size_t) value >= n*2 : (size_t) value == n*2)
b92f3507
YW
744 return 1;
745
746 /* If we have the privileges we will ignore the kernel limit. */
747 r = setsockopt_int(fd, SOL_SOCKET, SO_SNDBUFFORCE, n);
748 if (r < 0)
749 return r;
2583fbea
LP
750
751 return 1;
752}
753
d9d9b2a0 754int fd_set_rcvbuf(int fd, size_t n, bool increase) {
2583fbea
LP
755 int r, value;
756 socklen_t l = sizeof(value);
757
1263c85e
YW
758 if (n > INT_MAX)
759 return -ERANGE;
760
2583fbea 761 r = getsockopt(fd, SOL_SOCKET, SO_RCVBUF, &value, &l);
d9d9b2a0 762 if (r >= 0 && l == sizeof(value) && increase ? (size_t) value >= n*2 : (size_t) value == n*2)
2583fbea
LP
763 return 0;
764
b92f3507
YW
765 /* First, try to set the buffer size with SO_RCVBUF. */
766 r = setsockopt_int(fd, SOL_SOCKET, SO_RCVBUF, n);
767 if (r < 0)
768 return r;
2583fbea 769
b92f3507
YW
770 /* SO_RCVBUF above may set to the kernel limit, instead of the requested size.
771 * So, we need to check the actual buffer size here. */
67f5ae2d 772 l = sizeof(value);
b92f3507 773 r = getsockopt(fd, SOL_SOCKET, SO_RCVBUF, &value, &l);
d9d9b2a0 774 if (r >= 0 && l == sizeof(value) && increase ? (size_t) value >= n*2 : (size_t) value == n*2)
b92f3507
YW
775 return 1;
776
777 /* If we have the privileges we will ignore the kernel limit. */
778 r = setsockopt_int(fd, SOL_SOCKET, SO_RCVBUFFORCE, n);
779 if (r < 0)
780 return r;
9e5b6496 781
2583fbea
LP
782 return 1;
783}
784
785static const char* const ip_tos_table[] = {
0d7e34e3
ZJS
786 [IPTOS_LOWDELAY] = "low-delay",
787 [IPTOS_THROUGHPUT] = "throughput",
2583fbea 788 [IPTOS_RELIABILITY] = "reliability",
0d7e34e3 789 [IPTOS_LOWCOST] = "low-cost",
2583fbea
LP
790};
791
792DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(ip_tos, int, 0xff);
793
5a3586db
YW
794bool ifname_valid_char(char a) {
795 if ((unsigned char) a >= 127U)
796 return false;
797
798 if ((unsigned char) a <= 32U)
799 return false;
800
801 if (IN_SET(a,
802 ':', /* colons are used by the legacy "alias" interface logic */
803 '/', /* slashes cannot work, since we need to use network interfaces in sysfs paths, and in paths slashes are separators */
804 '%')) /* %d is used in the kernel's weird foo%d format string naming feature which we really really don't want to ever run into by accident */
805 return false;
806
807 return true;
808}
809
2313524a 810bool ifname_valid_full(const char *p, IfnameValidFlags flags) {
ef76dff2
LP
811 bool numeric = true;
812
813 /* Checks whether a network interface name is valid. This is inspired by dev_valid_name() in the kernel sources
814 * but slightly stricter, as we only allow non-control, non-space ASCII characters in the interface name. We
815 * also don't permit names that only container numbers, to avoid confusion with numeric interface indexes. */
816
2313524a
ZJS
817 assert(!(flags & ~_IFNAME_VALID_ALL));
818
ef76dff2
LP
819 if (isempty(p))
820 return false;
821
ee29bd5d
LP
822 /* A valid ifindex? If so, it's valid iff IFNAME_VALID_NUMERIC is set */
823 if (parse_ifindex(p) >= 0)
824 return flags & IFNAME_VALID_NUMERIC;
825
2313524a 826 if (flags & IFNAME_VALID_ALTERNATIVE) {
4252696a
YW
827 if (strlen(p) >= ALTIFNAMSIZ)
828 return false;
829 } else {
830 if (strlen(p) >= IFNAMSIZ)
831 return false;
832 }
ef76dff2 833
49bfc877 834 if (dot_or_dot_dot(p))
ef76dff2
LP
835 return false;
836
07a7441a
LP
837 /* Let's refuse "all" and "default" as interface name, to avoid collisions with the special sysctl
838 * directories /proc/sys/net/{ipv4,ipv6}/conf/{all,default} */
6aebfec3 839 if (!FLAGS_SET(flags, IFNAME_VALID_SPECIAL) && STR_IN_SET(p, "all", "default"))
07a7441a
LP
840 return false;
841
2313524a 842 for (const char *t = p; *t; t++) {
5a3586db 843 if (!ifname_valid_char(*t))
ef76dff2
LP
844 return false;
845
ff25d338 846 numeric = numeric && ascii_isdigit(*t);
ef76dff2
LP
847 }
848
ee29bd5d
LP
849 /* It's fully numeric but didn't parse as valid ifindex above? if so, it must be too large or zero or
850 * so, let's refuse that. */
851 if (numeric)
852 return false;
ef76dff2
LP
853
854 return true;
855}
856
26808948
SS
857bool address_label_valid(const char *p) {
858
859 if (isempty(p))
860 return false;
861
862 if (strlen(p) >= IFNAMSIZ)
863 return false;
864
865 while (*p) {
866 if ((uint8_t) *p >= 127U)
867 return false;
868
869 if ((uint8_t) *p <= 31U)
870 return false;
871 p++;
872 }
873
874 return true;
875}
876
2583fbea
LP
877int getpeercred(int fd, struct ucred *ucred) {
878 socklen_t n = sizeof(struct ucred);
879 struct ucred u;
2583fbea
LP
880
881 assert(fd >= 0);
882 assert(ucred);
883
fccad706 884 if (getsockopt(fd, SOL_SOCKET, SO_PEERCRED, &u, &n) < 0)
2583fbea
LP
885 return -errno;
886
887 if (n != sizeof(struct ucred))
888 return -EIO;
889
bbcc701e
LP
890 /* Check if the data is actually useful and not suppressed due to namespacing issues */
891 if (!pid_is_valid(u.pid))
2583fbea
LP
892 return -ENODATA;
893
bbcc701e
LP
894 /* Note that we don't check UID/GID here, as namespace translation works differently there: instead of
895 * receiving in "invalid" user/group we get the overflow UID/GID. */
896
2583fbea
LP
897 *ucred = u;
898 return 0;
899}
900
901int getpeersec(int fd, char **ret) {
217d8967 902 _cleanup_free_ char *s = NULL;
2583fbea 903 socklen_t n = 64;
2583fbea
LP
904
905 assert(fd >= 0);
906 assert(ret);
907
217d8967
LP
908 for (;;) {
909 s = new0(char, n+1);
910 if (!s)
911 return -ENOMEM;
2583fbea 912
989740eb
LP
913 if (getsockopt(fd, SOL_SOCKET, SO_PEERSEC, s, &n) >= 0) {
914 s[n] = 0;
217d8967 915 break;
989740eb 916 }
2583fbea
LP
917
918 if (errno != ERANGE)
919 return -errno;
920
217d8967 921 s = mfree(s);
2583fbea
LP
922 }
923
217d8967 924 if (isempty(s))
2583fbea 925 return -EOPNOTSUPP;
2583fbea 926
ae2a15bc 927 *ret = TAKE_PTR(s);
217d8967 928
2583fbea
LP
929 return 0;
930}
931
43f2c88d 932int getpeergroups(int fd, gid_t **ret) {
9c41e4eb 933 socklen_t n = sizeof(gid_t) * 64U;
43f2c88d
LP
934 _cleanup_free_ gid_t *d = NULL;
935
75f40779 936 assert(fd >= 0);
43f2c88d
LP
937 assert(ret);
938
7e8aa5c2 939 long ngroups_max = sysconf(_SC_NGROUPS_MAX);
9c41e4eb
LB
940 if (ngroups_max > 0)
941 n = MAX(n, sizeof(gid_t) * (socklen_t) ngroups_max);
7e8aa5c2 942
43f2c88d
LP
943 for (;;) {
944 d = malloc(n);
945 if (!d)
946 return -ENOMEM;
947
948 if (getsockopt(fd, SOL_SOCKET, SO_PEERGROUPS, d, &n) >= 0)
949 break;
950
951 if (errno != ERANGE)
952 return -errno;
953
954 d = mfree(d);
955 }
956
957 assert_se(n % sizeof(gid_t) == 0);
958 n /= sizeof(gid_t);
959
7e8aa5c2 960 if (n > INT_MAX)
43f2c88d
LP
961 return -E2BIG;
962
1cc6c93a 963 *ret = TAKE_PTR(d);
43f2c88d
LP
964
965 return (int) n;
966}
967
da5e0c44
LP
968int getpeerpidfd(int fd) {
969 socklen_t n = sizeof(int);
970 int pidfd = -EBADF;
971
972 assert(fd >= 0);
973
974 if (getsockopt(fd, SOL_SOCKET, SO_PEERPIDFD, &pidfd, &n) < 0)
975 return -errno;
976
977 if (n != sizeof(int))
978 return -EIO;
979
980 return pidfd;
981}
982
598d2428
LB
983ssize_t send_many_fds_iov_sa(
984 int transport_fd,
985 int *fds_array, size_t n_fds_array,
986 const struct iovec *iov, size_t iovlen,
987 const struct sockaddr *sa, socklen_t len,
988 int flags) {
989
990 _cleanup_free_ struct cmsghdr *cmsg = NULL;
991 struct msghdr mh = {
992 .msg_name = (struct sockaddr*) sa,
993 .msg_namelen = len,
994 .msg_iov = (struct iovec *)iov,
995 .msg_iovlen = iovlen,
996 };
997 ssize_t k;
998
999 assert(transport_fd >= 0);
1000 assert(fds_array || n_fds_array == 0);
1001
1002 /* The kernel will reject sending more than SCM_MAX_FD FDs at once */
1003 if (n_fds_array > SCM_MAX_FD)
1004 return -E2BIG;
1005
1006 /* We need either an FD array or data to send. If there's nothing, return an error. */
1007 if (n_fds_array == 0 && !iov)
1008 return -EINVAL;
1009
1010 if (n_fds_array > 0) {
1011 mh.msg_controllen = CMSG_SPACE(sizeof(int) * n_fds_array);
1012 mh.msg_control = cmsg = malloc(mh.msg_controllen);
1013 if (!cmsg)
1014 return -ENOMEM;
1015
1016 *cmsg = (struct cmsghdr) {
1017 .cmsg_len = CMSG_LEN(sizeof(int) * n_fds_array),
1018 .cmsg_level = SOL_SOCKET,
1019 .cmsg_type = SCM_RIGHTS,
1020 };
1021 memcpy(CMSG_DATA(cmsg), fds_array, sizeof(int) * n_fds_array);
1022 }
1023 k = sendmsg(transport_fd, &mh, MSG_NOSIGNAL | flags);
1024 if (k < 0)
1025 return (ssize_t) -errno;
1026
1027 return k;
1028}
1029
d34673ec 1030ssize_t send_one_fd_iov_sa(
726f4c47
ZJS
1031 int transport_fd,
1032 int fd,
f621b8d7 1033 const struct iovec *iov, size_t iovlen,
726f4c47
ZJS
1034 const struct sockaddr *sa, socklen_t len,
1035 int flags) {
1036
fb29cdbe 1037 CMSG_BUFFER_TYPE(CMSG_SPACE(sizeof(int))) control = {};
2583fbea 1038 struct msghdr mh = {
726f4c47
ZJS
1039 .msg_name = (struct sockaddr*) sa,
1040 .msg_namelen = len,
f621b8d7 1041 .msg_iov = (struct iovec *)iov,
d34673ec 1042 .msg_iovlen = iovlen,
2583fbea 1043 };
d34673ec 1044 ssize_t k;
2583fbea
LP
1045
1046 assert(transport_fd >= 0);
2583fbea 1047
d34673ec
FB
1048 /*
1049 * We need either an FD or data to send.
1050 * If there's nothing, return an error.
1051 */
1052 if (fd < 0 && !iov)
1053 return -EINVAL;
2583fbea 1054
d34673ec
FB
1055 if (fd >= 0) {
1056 struct cmsghdr *cmsg;
2583fbea 1057
d34673ec
FB
1058 mh.msg_control = &control;
1059 mh.msg_controllen = sizeof(control);
1060
1061 cmsg = CMSG_FIRSTHDR(&mh);
1062 cmsg->cmsg_level = SOL_SOCKET;
1063 cmsg->cmsg_type = SCM_RIGHTS;
1064 cmsg->cmsg_len = CMSG_LEN(sizeof(int));
1065 memcpy(CMSG_DATA(cmsg), &fd, sizeof(int));
d34673ec
FB
1066 }
1067 k = sendmsg(transport_fd, &mh, MSG_NOSIGNAL | flags);
1068 if (k < 0)
1069 return (ssize_t) -errno;
1070
1071 return k;
2583fbea
LP
1072}
1073
d34673ec
FB
1074int send_one_fd_sa(
1075 int transport_fd,
1076 int fd,
1077 const struct sockaddr *sa, socklen_t len,
1078 int flags) {
1079
1080 assert(fd >= 0);
1081
1082 return (int) send_one_fd_iov_sa(transport_fd, fd, NULL, 0, sa, len, flags);
1083}
1084
598d2428
LB
1085ssize_t receive_many_fds_iov(
1086 int transport_fd,
1087 struct iovec *iov, size_t iovlen,
1088 int **ret_fds_array, size_t *ret_n_fds_array,
1089 int flags) {
1090
1091 CMSG_BUFFER_TYPE(CMSG_SPACE(sizeof(int) * SCM_MAX_FD)) control;
1092 struct msghdr mh = {
1093 .msg_control = &control,
1094 .msg_controllen = sizeof(control),
1095 .msg_iov = iov,
1096 .msg_iovlen = iovlen,
1097 };
1098 _cleanup_free_ int *fds_array = NULL;
1099 size_t n_fds_array = 0;
1100 struct cmsghdr *cmsg;
1101 ssize_t k;
1102
1103 assert(transport_fd >= 0);
1104 assert(ret_fds_array);
1105 assert(ret_n_fds_array);
1106
1107 /*
1108 * Receive many FDs via @transport_fd. We don't care for the transport-type. We retrieve all the FDs
1109 * at once. This is best used in combination with send_many_fds().
1110 */
1111
1112 k = recvmsg_safe(transport_fd, &mh, MSG_CMSG_CLOEXEC | flags);
1113 if (k < 0)
1114 return k;
1115
1116 CMSG_FOREACH(cmsg, &mh)
1117 if (cmsg->cmsg_level == SOL_SOCKET && cmsg->cmsg_type == SCM_RIGHTS) {
1118 size_t n = (cmsg->cmsg_len - CMSG_LEN(0)) / sizeof(int);
1119
1120 fds_array = GREEDY_REALLOC(fds_array, n_fds_array + n);
1121 if (!fds_array) {
1122 cmsg_close_all(&mh);
1123 return -ENOMEM;
1124 }
1125
1126 memcpy(fds_array + n_fds_array, CMSG_TYPED_DATA(cmsg, int), sizeof(int) * n);
1127 n_fds_array += n;
1128 }
1129
1130 if (n_fds_array == 0) {
1131 cmsg_close_all(&mh);
1132
1133 /* If didn't receive an FD or any data, return an error. */
1134 if (k == 0)
1135 return -EIO;
1136 }
1137
1138 *ret_fds_array = TAKE_PTR(fds_array);
1139 *ret_n_fds_array = n_fds_array;
1140
1141 return k;
1142}
1143
1144int receive_many_fds(int transport_fd, int **ret_fds_array, size_t *ret_n_fds_array, int flags) {
1145 ssize_t k;
1146
1147 k = receive_many_fds_iov(transport_fd, NULL, 0, ret_fds_array, ret_n_fds_array, flags);
1148 if (k == 0)
1149 return 0;
1150
1151 /* k must be negative, since receive_many_fds_iov() only returns a positive value if data was received
1152 * through the iov. */
1153 assert(k < 0);
1154 return (int) k;
1155}
1156
d34673ec
FB
1157ssize_t receive_one_fd_iov(
1158 int transport_fd,
1159 struct iovec *iov, size_t iovlen,
1160 int flags,
1161 int *ret_fd) {
1162
fb29cdbe 1163 CMSG_BUFFER_TYPE(CMSG_SPACE(sizeof(int))) control;
2583fbea
LP
1164 struct msghdr mh = {
1165 .msg_control = &control,
1166 .msg_controllen = sizeof(control),
d34673ec
FB
1167 .msg_iov = iov,
1168 .msg_iovlen = iovlen,
2583fbea 1169 };
dac556fa 1170 struct cmsghdr *found;
d34673ec 1171 ssize_t k;
2583fbea
LP
1172
1173 assert(transport_fd >= 0);
d34673ec 1174 assert(ret_fd);
2583fbea
LP
1175
1176 /*
1177 * Receive a single FD via @transport_fd. We don't care for
1178 * the transport-type. We retrieve a single FD at most, so for
1179 * packet-based transports, the caller must ensure to send
1180 * only a single FD per packet. This is best used in
1181 * combination with send_one_fd().
1182 */
1183
3691bcf3 1184 k = recvmsg_safe(transport_fd, &mh, MSG_CMSG_CLOEXEC | flags);
d34673ec 1185 if (k < 0)
3691bcf3 1186 return k;
2583fbea 1187
dac556fa 1188 found = cmsg_find(&mh, SOL_SOCKET, SCM_RIGHTS, CMSG_LEN(sizeof(int)));
3691bcf3 1189 if (!found) {
2583fbea 1190 cmsg_close_all(&mh);
d34673ec 1191
3691bcf3
LP
1192 /* If didn't receive an FD or any data, return an error. */
1193 if (k == 0)
1194 return -EIO;
1195 }
2583fbea 1196
d34673ec 1197 if (found)
b1d02191 1198 *ret_fd = *CMSG_TYPED_DATA(found, int);
d34673ec 1199 else
254d1313 1200 *ret_fd = -EBADF;
d34673ec
FB
1201
1202 return k;
1203}
1204
1205int receive_one_fd(int transport_fd, int flags) {
1206 int fd;
1207 ssize_t k;
1208
1209 k = receive_one_fd_iov(transport_fd, NULL, 0, flags, &fd);
1210 if (k == 0)
1211 return fd;
1212
1213 /* k must be negative, since receive_one_fd_iov() only returns
1214 * a positive value if data was received through the iov. */
1215 assert(k < 0);
1216 return (int) k;
2583fbea 1217}
4edc2c9b
LP
1218
1219ssize_t next_datagram_size_fd(int fd) {
1220 ssize_t l;
1221 int k;
1222
1223 /* This is a bit like FIONREAD/SIOCINQ, however a bit more powerful. The difference being: recv(MSG_PEEK) will
96d49011 1224 * actually cause the next datagram in the queue to be validated regarding checksums, which FIONREAD doesn't
4edc2c9b
LP
1225 * do. This difference is actually of major importance as we need to be sure that the size returned here
1226 * actually matches what we will read with recvmsg() next, as otherwise we might end up allocating a buffer of
1227 * the wrong size. */
1228
1229 l = recv(fd, NULL, 0, MSG_PEEK|MSG_TRUNC);
1230 if (l < 0) {
3742095b 1231 if (IN_SET(errno, EOPNOTSUPP, EFAULT))
4edc2c9b
LP
1232 goto fallback;
1233
1234 return -errno;
1235 }
1236 if (l == 0)
1237 goto fallback;
1238
1239 return l;
1240
1241fallback:
1242 k = 0;
1243
1244 /* Some sockets (AF_PACKET) do not support null-sized recv() with MSG_TRUNC set, let's fall back to FIONREAD
1245 * for them. Checksums don't matter for raw sockets anyway, hence this should be fine. */
1246
1247 if (ioctl(fd, FIONREAD, &k) < 0)
1248 return -errno;
1249
1250 return (ssize_t) k;
1251}
60d9771c 1252
67962036
ZJS
1253/* Put a limit on how many times will attempt to call accept4(). We loop
1254 * only on "transient" errors, but let's make sure we don't loop forever. */
1255#define MAX_FLUSH_ITERATIONS 1024
1256
60d9771c
LP
1257int flush_accept(int fd) {
1258
f3d75364
LP
1259 int r, b;
1260 socklen_t l = sizeof(b);
1261
644cb4cc
ZJS
1262 /* Similar to flush_fd() but flushes all incoming connections by accepting and immediately closing
1263 * them. */
f3d75364
LP
1264
1265 if (getsockopt(fd, SOL_SOCKET, SO_ACCEPTCONN, &b, &l) < 0)
1266 return -errno;
60d9771c 1267
f3d75364 1268 assert(l == sizeof(b));
644cb4cc
ZJS
1269 if (!b) /* Let's check if this socket accepts connections before calling accept(). accept4() can
1270 * return EOPNOTSUPP if the fd is not a listening socket, which we should treat as a fatal
1271 * error, or in case the incoming TCP connection triggered a network issue, which we want to
1272 * treat as a transient error. Thus, let's rule out the first reason for EOPNOTSUPP early, so
1273 * we can loop safely on transient errors below. */
f3d75364 1274 return -ENOTTY;
60d9771c 1275
67962036 1276 for (unsigned iteration = 0;; iteration++) {
60d9771c
LP
1277 int cfd;
1278
0f2d351f 1279 r = fd_wait_for_event(fd, POLLIN, 0);
60d9771c 1280 if (r < 0) {
0f2d351f 1281 if (r == -EINTR)
60d9771c
LP
1282 continue;
1283
0f2d351f 1284 return r;
4ff9bc2e
LP
1285 }
1286 if (r == 0)
60d9771c
LP
1287 return 0;
1288
67962036
ZJS
1289 if (iteration >= MAX_FLUSH_ITERATIONS)
1290 return log_debug_errno(SYNTHETIC_ERRNO(EBUSY),
1291 "Failed to flush connections within " STRINGIFY(MAX_FLUSH_ITERATIONS) " iterations.");
1292
60d9771c
LP
1293 cfd = accept4(fd, NULL, NULL, SOCK_NONBLOCK|SOCK_CLOEXEC);
1294 if (cfd < 0) {
60d9771c
LP
1295 if (errno == EAGAIN)
1296 return 0;
1297
4ff9bc2e
LP
1298 if (ERRNO_IS_ACCEPT_AGAIN(errno))
1299 continue;
1300
60d9771c
LP
1301 return -errno;
1302 }
1303
4ff9bc2e 1304 safe_close(cfd);
60d9771c
LP
1305 }
1306}
29206d46
LP
1307
1308struct cmsghdr* cmsg_find(struct msghdr *mh, int level, int type, socklen_t length) {
1309 struct cmsghdr *cmsg;
1310
1311 assert(mh);
1312
1313 CMSG_FOREACH(cmsg, mh)
1314 if (cmsg->cmsg_level == level &&
1315 cmsg->cmsg_type == type &&
1316 (length == (socklen_t) -1 || length == cmsg->cmsg_len))
1317 return cmsg;
1318
1319 return NULL;
1320}
429b4350 1321
4836f4c6
YW
1322void* cmsg_find_and_copy_data(struct msghdr *mh, int level, int type, void *buf, size_t buf_len) {
1323 struct cmsghdr *cmsg;
1324
1325 assert(mh);
1326 assert(buf);
1327 assert(buf_len > 0);
1328
1329 /* This is similar to cmsg_find_data(), but copy the found data to buf. This should be typically used
da890466 1330 * when reading possibly unaligned data such as timestamp, as time_t is 64-bit and size_t is 32-bit on
4836f4c6
YW
1331 * RISCV32. See issue #27241. */
1332
1333 cmsg = cmsg_find(mh, level, type, CMSG_LEN(buf_len));
1334 if (!cmsg)
1335 return NULL;
1336
1337 return memcpy_safe(buf, CMSG_DATA(cmsg), buf_len);
1338}
1339
429b4350
LP
1340int socket_ioctl_fd(void) {
1341 int fd;
1342
1343 /* Create a socket to invoke the various network interface ioctl()s on. Traditionally only AF_INET was good for
1344 * that. Since kernel 4.6 AF_NETLINK works for this too. We first try to use AF_INET hence, but if that's not
1345 * available (for example, because it is made unavailable via SECCOMP or such), we'll fall back to the more
1346 * generic AF_NETLINK. */
1347
1348 fd = socket(AF_INET, SOCK_DGRAM|SOCK_CLOEXEC, 0);
1349 if (fd < 0)
1350 fd = socket(AF_NETLINK, SOCK_RAW|SOCK_CLOEXEC, NETLINK_GENERIC);
1351 if (fd < 0)
1352 return -errno;
1353
1354 return fd;
1355}
9f20fc28
LP
1356
1357int sockaddr_un_unlink(const struct sockaddr_un *sa) {
1358 const char *p, * nul;
1359
1360 assert(sa);
1361
1362 if (sa->sun_family != AF_UNIX)
1363 return -EPROTOTYPE;
1364
1365 if (sa->sun_path[0] == 0) /* Nothing to do for abstract sockets */
1366 return 0;
1367
1368 /* The path in .sun_path is not necessarily NUL terminated. Let's fix that. */
1369 nul = memchr(sa->sun_path, 0, sizeof(sa->sun_path));
1370 if (nul)
1371 p = sa->sun_path;
1372 else
1373 p = memdupa_suffix0(sa->sun_path, sizeof(sa->sun_path));
1374
1375 if (unlink(p) < 0)
1376 return -errno;
1377
1378 return 1;
1379}
5cf91ea9
LP
1380
1381int sockaddr_un_set_path(struct sockaddr_un *ret, const char *path) {
1382 size_t l;
1383
1384 assert(ret);
1385 assert(path);
1386
1387 /* Initialize ret->sun_path from the specified argument. This will interpret paths starting with '@' as
1388 * abstract namespace sockets, and those starting with '/' as regular filesystem sockets. It won't accept
1389 * anything else (i.e. no relative paths), to avoid ambiguities. Note that this function cannot be used to
1390 * reference paths in the abstract namespace that include NUL bytes in the name. */
1391
1392 l = strlen(path);
c097bf1f 1393 if (l < 2)
5cf91ea9
LP
1394 return -EINVAL;
1395 if (!IN_SET(path[0], '/', '@'))
1396 return -EINVAL;
5cf91ea9
LP
1397
1398 /* Don't allow paths larger than the space in sockaddr_un. Note that we are a tiny bit more restrictive than
1399 * the kernel is: we insist on NUL termination (both for abstract namespace and regular file system socket
1400 * addresses!), which the kernel doesn't. We do this to reduce chance of incompatibility with other apps that
7802194a 1401 * do not expect non-NUL terminated file system path. */
5cf91ea9 1402 if (l+1 > sizeof(ret->sun_path))
dfa2b389
LP
1403 return path[0] == '@' ? -EINVAL : -ENAMETOOLONG; /* return a recognizable error if this is
1404 * too long to fit into a sockaddr_un, but
1405 * is a file system path, and thus might be
1406 * connectible via O_PATH indirection. */
5cf91ea9
LP
1407
1408 *ret = (struct sockaddr_un) {
1409 .sun_family = AF_UNIX,
1410 };
1411
1412 if (path[0] == '@') {
1413 /* Abstract namespace socket */
1414 memcpy(ret->sun_path + 1, path + 1, l); /* copy *with* trailing NUL byte */
1415 return (int) (offsetof(struct sockaddr_un, sun_path) + l); /* 🔥 *don't* 🔥 include trailing NUL in size */
1416
1417 } else {
1418 assert(path[0] == '/');
1419
1420 /* File system socket */
1421 memcpy(ret->sun_path, path, l + 1); /* copy *with* trailing NUL byte */
1422 return (int) (offsetof(struct sockaddr_un, sun_path) + l + 1); /* include trailing NUL in size */
1423 }
1424}
5d594d01
LP
1425
1426int socket_bind_to_ifname(int fd, const char *ifname) {
1427 assert(fd >= 0);
1428
1429 /* Call with NULL to drop binding */
1430
7c248223 1431 return RET_NERRNO(setsockopt(fd, SOL_SOCKET, SO_BINDTODEVICE, ifname, strlen_ptr(ifname)));
5d594d01
LP
1432}
1433
1434int socket_bind_to_ifindex(int fd, int ifindex) {
01afd0f7 1435 char ifname[IF_NAMESIZE];
5e958e1d 1436 int r;
5d594d01
LP
1437
1438 assert(fd >= 0);
1439
7c248223 1440 if (ifindex <= 0)
5d594d01 1441 /* Drop binding */
7c248223 1442 return RET_NERRNO(setsockopt(fd, SOL_SOCKET, SO_BINDTODEVICE, NULL, 0));
5d594d01 1443
5e958e1d
YW
1444 r = setsockopt_int(fd, SOL_SOCKET, SO_BINDTOIFINDEX, ifindex);
1445 if (r != -ENOPROTOOPT)
1446 return r;
5d594d01
LP
1447
1448 /* Fall back to SO_BINDTODEVICE on kernels < 5.0 which didn't have SO_BINDTOIFINDEX */
01afd0f7
YW
1449 r = format_ifname(ifindex, ifname);
1450 if (r < 0)
1451 return r;
5d594d01
LP
1452
1453 return socket_bind_to_ifname(fd, ifname);
1454}
47eae6ce
LP
1455
1456ssize_t recvmsg_safe(int sockfd, struct msghdr *msg, int flags) {
1457 ssize_t n;
1458
1459 /* A wrapper around recvmsg() that checks for MSG_CTRUNC, and turns it into an error, in a reasonably
1460 * safe way, closing any SCM_RIGHTS fds in the error path.
1461 *
1462 * Note that unlike our usual coding style this might modify *msg on failure. */
1463
1464 n = recvmsg(sockfd, msg, flags);
1465 if (n < 0)
1466 return -errno;
1467
1468 if (FLAGS_SET(msg->msg_flags, MSG_CTRUNC)) {
1469 cmsg_close_all(msg);
1470 return -EXFULL; /* a recognizable error code */
1471 }
1472
1473 return n;
35a3eb9b
LP
1474}
1475
5f64d2bf 1476int socket_get_family(int fd) {
35a3eb9b
LP
1477 int af;
1478 socklen_t sl = sizeof(af);
1479
1480 if (getsockopt(fd, SOL_SOCKET, SO_DOMAIN, &af, &sl) < 0)
1481 return -errno;
1482
5d0fe423
LP
1483 if (sl != sizeof(af))
1484 return -EINVAL;
1485
1486 return af;
1487}
1488
1489int socket_set_recvpktinfo(int fd, int af, bool b) {
5d0fe423
LP
1490
1491 if (af == AF_UNSPEC) {
5f64d2bf
LP
1492 af = socket_get_family(fd);
1493 if (af < 0)
1494 return af;
5d0fe423
LP
1495 }
1496
35a3eb9b
LP
1497 switch (af) {
1498
1499 case AF_INET:
1500 return setsockopt_int(fd, IPPROTO_IP, IP_PKTINFO, b);
47eae6ce 1501
35a3eb9b
LP
1502 case AF_INET6:
1503 return setsockopt_int(fd, IPPROTO_IPV6, IPV6_RECVPKTINFO, b);
1504
1505 case AF_NETLINK:
1506 return setsockopt_int(fd, SOL_NETLINK, NETLINK_PKTINFO, b);
1507
2d6d4136
LP
1508 case AF_PACKET:
1509 return setsockopt_int(fd, SOL_PACKET, PACKET_AUXDATA, b);
1510
35a3eb9b
LP
1511 default:
1512 return -EAFNOSUPPORT;
1513 }
47eae6ce 1514}
5d0fe423 1515
5d0fe423
LP
1516int socket_set_unicast_if(int fd, int af, int ifi) {
1517 be32_t ifindex_be = htobe32(ifi);
5d0fe423
LP
1518
1519 if (af == AF_UNSPEC) {
5f64d2bf
LP
1520 af = socket_get_family(fd);
1521 if (af < 0)
1522 return af;
5d0fe423
LP
1523 }
1524
1525 switch (af) {
1526
1527 case AF_INET:
7c248223 1528 return RET_NERRNO(setsockopt(fd, IPPROTO_IP, IP_UNICAST_IF, &ifindex_be, sizeof(ifindex_be)));
5d0fe423
LP
1529
1530 case AF_INET6:
7c248223 1531 return RET_NERRNO(setsockopt(fd, IPPROTO_IPV6, IPV6_UNICAST_IF, &ifindex_be, sizeof(ifindex_be)));
5d0fe423
LP
1532
1533 default:
1534 return -EAFNOSUPPORT;
1535 }
1536}
1537
402506ce 1538int socket_set_option(int fd, int af, int opt_ipv4, int opt_ipv6, int val) {
5d0fe423 1539 if (af == AF_UNSPEC) {
5f64d2bf
LP
1540 af = socket_get_family(fd);
1541 if (af < 0)
1542 return af;
5d0fe423
LP
1543 }
1544
1545 switch (af) {
1546
1547 case AF_INET:
402506ce 1548 return setsockopt_int(fd, IPPROTO_IP, opt_ipv4, val);
5d0fe423
LP
1549
1550 case AF_INET6:
402506ce 1551 return setsockopt_int(fd, IPPROTO_IPV6, opt_ipv6, val);
5d0fe423
LP
1552
1553 default:
1554 return -EAFNOSUPPORT;
1555 }
1556}
52975f86
LP
1557
1558int socket_get_mtu(int fd, int af, size_t *ret) {
1559 int mtu, r;
1560
1561 if (af == AF_UNSPEC) {
5f64d2bf
LP
1562 af = socket_get_family(fd);
1563 if (af < 0)
1564 return af;
52975f86
LP
1565 }
1566
1567 switch (af) {
1568
1569 case AF_INET:
1570 r = getsockopt_int(fd, IPPROTO_IP, IP_MTU, &mtu);
1571 break;
1572
1573 case AF_INET6:
1574 r = getsockopt_int(fd, IPPROTO_IPV6, IPV6_MTU, &mtu);
1575 break;
1576
1577 default:
1578 return -EAFNOSUPPORT;
1579 }
1580
1581 if (r < 0)
1582 return r;
1583 if (mtu <= 0)
1584 return -EINVAL;
1585
1586 *ret = (size_t) mtu;
1587 return 0;
1588}
2679aee4 1589
9a603dc2 1590static int connect_unix_path_simple(int fd, const char *path) {
2679aee4
LP
1591 union sockaddr_union sa = {
1592 .un.sun_family = AF_UNIX,
1593 };
9a603dc2 1594 size_t l;
2679aee4
LP
1595
1596 assert(fd >= 0);
2679aee4
LP
1597 assert(path);
1598
9a603dc2
LP
1599 l = strlen(path);
1600 assert(l > 0);
1601 assert(l < sizeof(sa.un.sun_path));
1602
1603 memcpy(sa.un.sun_path, path, l + 1);
1604 return RET_NERRNO(connect(fd, &sa.sa, offsetof(struct sockaddr_un, sun_path) + l + 1));
1605}
1606
1607static int connect_unix_inode(int fd, int inode_fd) {
1608 assert(fd >= 0);
1609 assert(inode_fd >= 0);
1610
1611 return connect_unix_path_simple(fd, FORMAT_PROC_FD_PATH(inode_fd));
1612}
1613
1614int connect_unix_path(int fd, int dir_fd, const char *path) {
1615 _cleanup_close_ int inode_fd = -EBADF;
1616
1617 assert(fd >= 0);
1618 assert(dir_fd == AT_FDCWD || dir_fd >= 0);
1619
2679aee4
LP
1620 /* Connects to the specified AF_UNIX socket in the file system. Works around the 108 byte size limit
1621 * in sockaddr_un, by going via O_PATH if needed. This hence works for any kind of path. */
1622
9a603dc2
LP
1623 if (!path)
1624 return connect_unix_inode(fd, dir_fd); /* If no path is specified, then dir_fd refers to the socket inode to connect to. */
2679aee4
LP
1625
1626 /* Refuse zero length path early, to make sure AF_UNIX stack won't mistake this for an abstract
1627 * namespace path, since first char is NUL */
9a603dc2 1628 if (isempty(path))
2679aee4
LP
1629 return -EINVAL;
1630
9a603dc2
LP
1631 /* Shortcut for the simple case */
1632 if (dir_fd == AT_FDCWD && strlen(path) < sizeof_field(struct sockaddr_un, sun_path))
1633 return connect_unix_path_simple(fd, path);
2679aee4 1634
9a603dc2
LP
1635 /* If dir_fd is specified, then we need to go the indirect O_PATH route, because connectat() does not
1636 * exist. If the path is too long, we also need to take the indirect route, since we can't fit this
1637 * into a sockaddr_un directly. */
2679aee4 1638
9a603dc2
LP
1639 inode_fd = openat(dir_fd, path, O_PATH|O_CLOEXEC);
1640 if (inode_fd < 0)
1641 return -errno;
2679aee4 1642
9a603dc2 1643 return connect_unix_inode(fd, inode_fd);
2679aee4 1644}
747b5d96
LB
1645
1646int socket_address_parse_unix(SocketAddress *ret_address, const char *s) {
1647 struct sockaddr_un un;
1648 int r;
1649
1650 assert(ret_address);
1651 assert(s);
1652
1653 if (!IN_SET(*s, '/', '@'))
1654 return -EPROTO;
1655
1656 r = sockaddr_un_set_path(&un, s);
1657 if (r < 0)
1658 return r;
1659
1660 *ret_address = (SocketAddress) {
1661 .sockaddr.un = un,
1662 .size = r,
1663 };
1664
1665 return 0;
1666}
1667
8e471c6a
LP
1668int vsock_parse_port(const char *s, unsigned *ret) {
1669 int r;
1670
1671 assert(ret);
1672
1673 if (!s)
1674 return -EINVAL;
1675
1676 unsigned u;
1677 r = safe_atou(s, &u);
1678 if (r < 0)
1679 return r;
1680
1681 /* Port 0 is apparently valid and not special in AF_VSOCK (unlike on IP). But VMADDR_PORT_ANY
1682 * (UINT32_MAX) is. Hence refuse that. */
1683
1684 if (u == VMADDR_PORT_ANY)
1685 return -EINVAL;
1686
1687 *ret = u;
1688 return 0;
1689}
1690
1691int vsock_parse_cid(const char *s, unsigned *ret) {
1692 assert(ret);
1693
1694 if (!s)
1695 return -EINVAL;
1696
1697 /* Parsed an AF_VSOCK "CID". This is a 32bit entity, and the usual type is "unsigned". We recognize
1698 * the three special CIDs as strings, and otherwise parse the numeric CIDs. */
1699
1700 if (streq(s, "hypervisor"))
1701 *ret = VMADDR_CID_HYPERVISOR;
1702 else if (streq(s, "local"))
1703 *ret = VMADDR_CID_LOCAL;
1704 else if (streq(s, "host"))
1705 *ret = VMADDR_CID_HOST;
1706 else
1707 return safe_atou(s, ret);
1708
1709 return 0;
1710}
1711
747b5d96
LB
1712int socket_address_parse_vsock(SocketAddress *ret_address, const char *s) {
1713 /* AF_VSOCK socket in vsock:cid:port notation */
1714 _cleanup_free_ char *n = NULL;
1715 char *e, *cid_start;
1716 unsigned port, cid;
c31984e3 1717 int type, r;
747b5d96
LB
1718
1719 assert(ret_address);
1720 assert(s);
1721
c31984e3
DDM
1722 if ((cid_start = startswith(s, "vsock:")))
1723 type = 0;
1724 else if ((cid_start = startswith(s, "vsock-dgram:")))
1725 type = SOCK_DGRAM;
1726 else if ((cid_start = startswith(s, "vsock-seqpacket:")))
1727 type = SOCK_SEQPACKET;
1728 else if ((cid_start = startswith(s, "vsock-stream:")))
1729 type = SOCK_STREAM;
1730 else
747b5d96
LB
1731 return -EPROTO;
1732
1733 e = strchr(cid_start, ':');
1734 if (!e)
1735 return -EINVAL;
1736
8e471c6a 1737 r = vsock_parse_port(e+1, &port);
747b5d96
LB
1738 if (r < 0)
1739 return r;
1740
1741 n = strndup(cid_start, e - cid_start);
1742 if (!n)
1743 return -ENOMEM;
1744
1745 if (isempty(n))
1746 cid = VMADDR_CID_ANY;
1747 else {
8e471c6a 1748 r = vsock_parse_cid(n, &cid);
747b5d96
LB
1749 if (r < 0)
1750 return r;
1751 }
1752
1753 *ret_address = (SocketAddress) {
1754 .sockaddr.vm = {
747b5d96 1755 .svm_family = AF_VSOCK,
8e471c6a 1756 .svm_cid = cid,
747b5d96
LB
1757 .svm_port = port,
1758 },
c31984e3 1759 .type = type,
747b5d96
LB
1760 .size = sizeof(struct sockaddr_vm),
1761 };
1762
1763 return 0;
1764}
d3109d8d
LP
1765
1766int vsock_get_local_cid(unsigned *ret) {
1767 _cleanup_close_ int vsock_fd = -EBADF;
1768
1769 assert(ret);
1770
1771 vsock_fd = open("/dev/vsock", O_RDONLY|O_CLOEXEC);
1772 if (vsock_fd < 0)
1773 return log_debug_errno(errno, "Failed to open /dev/vsock: %m");
1774
1775 if (ioctl(vsock_fd, IOCTL_VM_SOCKETS_GET_LOCAL_CID, ret) < 0)
1776 return log_debug_errno(errno, "Failed to query local AF_VSOCK CID: %m");
1777
1778 return 0;
1779}