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