Debian Codegraph @

src/basic/socket-util.c

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