1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
5 #include <linux/if_arp.h>
9 #include <netinet/ip.h>
12 #include <sys/ioctl.h>
15 #include "alloc-util.h"
16 #include "errno-util.h"
19 #include "format-ifname.h"
20 #include "format-util.h"
21 #include "in-addr-util.h"
24 #include "memory-util.h"
25 #include "parse-util.h"
26 #include "path-util.h"
28 #include "process-util.h"
29 #include "random-util.h"
30 #include "socket-util.h"
31 #include "sparse-endian.h"
32 #include "string-table.h"
33 #include "string-util.h"
35 #include "sysctl-util.h"
38 # define IDN_FLAGS NI_IDN
43 static const char* const socket_address_type_table
[] = {
44 [SOCK_STREAM
] = "Stream",
45 [SOCK_DGRAM
] = "Datagram",
47 [SOCK_RDM
] = "ReliableDatagram",
48 [SOCK_SEQPACKET
] = "SequentialPacket",
49 [SOCK_DCCP
] = "DatagramCongestionControl",
52 DEFINE_STRING_TABLE_LOOKUP(socket_address_type
, int);
54 int socket_address_verify(const SocketAddress
*a
, bool strict
) {
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. */
60 switch (socket_address_family(a
)) {
63 if (a
->size
!= sizeof(struct sockaddr_in
))
66 if (a
->sockaddr
.in
.sin_port
== 0)
69 if (!IN_SET(a
->type
, 0, SOCK_STREAM
, SOCK_DGRAM
))
75 if (a
->size
!= sizeof(struct sockaddr_in6
))
78 if (a
->sockaddr
.in6
.sin6_port
== 0)
81 if (!IN_SET(a
->type
, 0, SOCK_STREAM
, SOCK_DGRAM
))
87 if (a
->size
< offsetof(struct sockaddr_un
, sun_path
))
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. */
94 if (a
->size
> offsetof(struct sockaddr_un
, sun_path
) &&
95 a
->sockaddr
.un
.sun_path
[0] != 0 &&
97 /* Only validate file system sockets here, and only in strict mode */
100 e
= memchr(a
->sockaddr
.un
.sun_path
, 0, sizeof(a
->sockaddr
.un
.sun_path
));
102 /* If there's an embedded NUL byte, make sure the size of the socket address matches it */
103 if (a
->size
!= offsetof(struct sockaddr_un
, sun_path
) + (e
- a
->sockaddr
.un
.sun_path
) + 1)
106 /* If there's no embedded NUL byte, then the size needs to match the whole
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
109 * size if the path is non NUL terminated.) */
110 if (!IN_SET(a
->size
, sizeof(a
->sockaddr
.un
.sun_path
), sizeof(a
->sockaddr
.un
.sun_path
)+1))
115 if (!IN_SET(a
->type
, 0, SOCK_STREAM
, SOCK_DGRAM
, SOCK_SEQPACKET
))
122 if (a
->size
!= sizeof(struct sockaddr_nl
))
125 if (!IN_SET(a
->type
, 0, SOCK_RAW
, SOCK_DGRAM
))
131 if (a
->size
!= sizeof(struct sockaddr_vm
))
134 if (!IN_SET(a
->type
, 0, SOCK_STREAM
, SOCK_DGRAM
))
140 return -EAFNOSUPPORT
;
144 int socket_address_print(const SocketAddress
*a
, char **ret
) {
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. */
157 if (socket_address_family(a
) == AF_NETLINK
) {
158 _cleanup_free_
char *sfamily
= NULL
;
160 r
= netlink_family_to_string_alloc(a
->protocol
, &sfamily
);
164 r
= asprintf(ret
, "%s %u", sfamily
, a
->sockaddr
.nl
.nl_groups
);
171 return sockaddr_pretty(&a
->sockaddr
.sa
, a
->size
, false, true, ret
);
174 bool socket_address_can_accept(const SocketAddress
*a
) {
178 IN_SET(a
->type
, SOCK_STREAM
, SOCK_SEQPACKET
);
181 bool socket_address_equal(const SocketAddress
*a
, const SocketAddress
*b
) {
185 /* Invalid addresses are unequal to all */
186 if (socket_address_verify(a
, false) < 0 ||
187 socket_address_verify(b
, false) < 0)
190 if (a
->type
!= b
->type
)
193 if (socket_address_family(a
) != socket_address_family(b
))
196 switch (socket_address_family(a
)) {
199 if (a
->sockaddr
.in
.sin_addr
.s_addr
!= b
->sockaddr
.in
.sin_addr
.s_addr
)
202 if (a
->sockaddr
.in
.sin_port
!= b
->sockaddr
.in
.sin_port
)
208 if (memcmp(&a
->sockaddr
.in6
.sin6_addr
, &b
->sockaddr
.in6
.sin6_addr
, sizeof(a
->sockaddr
.in6
.sin6_addr
)) != 0)
211 if (a
->sockaddr
.in6
.sin6_port
!= b
->sockaddr
.in6
.sin6_port
)
217 if (a
->size
<= offsetof(struct sockaddr_un
, sun_path
) ||
218 b
->size
<= offsetof(struct sockaddr_un
, sun_path
))
221 if ((a
->sockaddr
.un
.sun_path
[0] == 0) != (b
->sockaddr
.un
.sun_path
[0] == 0))
224 if (a
->sockaddr
.un
.sun_path
[0]) {
225 if (!path_equal_or_inode_same(a
->sockaddr
.un
.sun_path
, b
->sockaddr
.un
.sun_path
, 0))
228 if (a
->size
!= b
->size
)
231 if (memcmp(a
->sockaddr
.un
.sun_path
, b
->sockaddr
.un
.sun_path
, a
->size
) != 0)
238 if (a
->protocol
!= b
->protocol
)
241 if (a
->sockaddr
.nl
.nl_groups
!= b
->sockaddr
.nl
.nl_groups
)
247 if (a
->sockaddr
.vm
.svm_cid
!= b
->sockaddr
.vm
.svm_cid
)
250 if (a
->sockaddr
.vm
.svm_port
!= b
->sockaddr
.vm
.svm_port
)
256 /* Cannot compare, so we assume the addresses are different */
263 const char* socket_address_get_path(const SocketAddress
*a
) {
266 if (socket_address_family(a
) != AF_UNIX
)
269 if (a
->sockaddr
.un
.sun_path
[0] == 0)
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);
276 return a
->sockaddr
.un
.sun_path
;
279 bool socket_ipv6_is_supported(void) {
280 static int cached
= -1;
284 if (access("/proc/net/if_inet6", F_OK
) < 0) {
286 if (errno
!= ENOENT
) {
287 log_debug_errno(errno
, "Unexpected error when checking whether /proc/net/if_inet6 exists: %m");
299 bool socket_ipv6_is_enabled(void) {
300 _cleanup_free_
char *v
= NULL
;
303 /* Much like socket_ipv6_is_supported(), but also checks that the sysctl that disables IPv6 on all
304 * interfaces isn't turned on */
306 if (!socket_ipv6_is_supported())
309 r
= sysctl_read_ip_property(AF_INET6
, "all", "disable_ipv6", &v
);
311 log_debug_errno(r
, "Unexpected error reading 'net.ipv6.conf.all.disable_ipv6' sysctl: %m");
315 r
= parse_boolean(v
);
317 log_debug_errno(r
, "Failed to pare 'net.ipv6.conf.all.disable_ipv6' sysctl: %m");
324 bool socket_address_matches_fd(const SocketAddress
*a
, int fd
) {
331 b
.size
= sizeof(b
.sockaddr
);
332 if (getsockname(fd
, &b
.sockaddr
.sa
, &b
.size
) < 0)
335 if (b
.sockaddr
.sa
.sa_family
!= a
->sockaddr
.sa
.sa_family
)
338 solen
= sizeof(b
.type
);
339 if (getsockopt(fd
, SOL_SOCKET
, SO_TYPE
, &b
.type
, &solen
) < 0)
342 if (b
.type
!= a
->type
)
345 if (a
->protocol
!= 0) {
346 solen
= sizeof(b
.protocol
);
347 if (getsockopt(fd
, SOL_SOCKET
, SO_PROTOCOL
, &b
.protocol
, &solen
) < 0)
350 if (b
.protocol
!= a
->protocol
)
354 return socket_address_equal(a
, &b
);
357 int sockaddr_port(const struct sockaddr
*_sa
, unsigned *ret_port
) {
358 const union sockaddr_union
*sa
= (const union sockaddr_union
*) _sa
;
360 /* Note, this returns the port as 'unsigned' rather than 'uint16_t', as AF_VSOCK knows larger ports */
364 switch (sa
->sa
.sa_family
) {
367 *ret_port
= be16toh(sa
->in
.sin_port
);
371 *ret_port
= be16toh(sa
->in6
.sin6_port
);
375 *ret_port
= sa
->vm
.svm_port
;
379 return -EAFNOSUPPORT
;
383 const union in_addr_union
*sockaddr_in_addr(const struct sockaddr
*_sa
) {
384 const union sockaddr_union
*sa
= (const union sockaddr_union
*) _sa
;
389 switch (sa
->sa
.sa_family
) {
392 return (const union in_addr_union
*) &sa
->in
.sin_addr
;
395 return (const union in_addr_union
*) &sa
->in6
.sin6_addr
;
402 int sockaddr_set_in_addr(
403 union sockaddr_union
*u
,
405 const union in_addr_union
*a
,
414 u
->in
= (struct sockaddr_in
) {
415 .sin_family
= AF_INET
,
417 .sin_port
= htobe16(port
),
423 u
->in6
= (struct sockaddr_in6
) {
424 .sin6_family
= AF_INET6
,
426 .sin6_port
= htobe16(port
),
432 return -EAFNOSUPPORT
;
438 const struct sockaddr
*_sa
,
444 union sockaddr_union
*sa
= (union sockaddr_union
*) _sa
;
449 assert(salen
>= sizeof(sa
->sa
.sa_family
));
452 switch (sa
->sa
.sa_family
) {
457 a
= be32toh(sa
->in
.sin_addr
.s_addr
);
462 a
>> 24, (a
>> 16) & 0xFF, (a
>> 8) & 0xFF, a
& 0xFF,
463 be16toh(sa
->in
.sin_port
));
467 a
>> 24, (a
>> 16) & 0xFF, (a
>> 8) & 0xFF, a
& 0xFF);
474 static const unsigned char ipv4_prefix
[] = {
475 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xFF, 0xFF
478 if (translate_ipv6
&&
479 memcmp(&sa
->in6
.sin6_addr
, ipv4_prefix
, sizeof(ipv4_prefix
)) == 0) {
480 const uint8_t *a
= sa
->in6
.sin6_addr
.s6_addr
+12;
484 a
[0], a
[1], a
[2], a
[3],
485 be16toh(sa
->in6
.sin6_port
));
489 a
[0], a
[1], a
[2], a
[3]);
493 const char *a
= IN6_ADDR_TO_STRING(&sa
->in6
.sin6_addr
);
499 be16toh(sa
->in6
.sin6_port
),
500 sa
->in6
.sin6_scope_id
!= 0 ? "%" : "",
501 FORMAT_IFNAME_FULL(sa
->in6
.sin6_scope_id
, FORMAT_IFNAME_IFINDEX
)) < 0)
504 if (sa
->in6
.sin6_scope_id
!= 0)
505 p
= strjoin(a
, "%", FORMAT_IFNAME_FULL(sa
->in6
.sin6_scope_id
, FORMAT_IFNAME_IFINDEX
));
517 if (salen
<= offsetof(struct sockaddr_un
, sun_path
) ||
518 (sa
->un
.sun_path
[0] == 0 && salen
== offsetof(struct sockaddr_un
, sun_path
) + 1))
519 /* The name must have at least one character (and the leading NUL does not count) */
520 p
= strdup("<unnamed>");
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
526 char *path
= (char*) sa
->un_buffer
+ offsetof(struct sockaddr_un
, sun_path
);
527 size_t path_len
= salen
- offsetof(struct sockaddr_un
, sun_path
);
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. */
535 _cleanup_free_
char *e
= NULL
;
537 e
= cescape_length(path
+ 1, path_len
- 1);
543 if (path
[path_len
- 1] == '\0')
544 /* We expect a terminating NUL and don't print it */
547 p
= cescape_length(path
, path_len
);
557 if (sa
->vm
.svm_cid
== VMADDR_CID_ANY
)
558 r
= asprintf(&p
, "vsock::%u", sa
->vm
.svm_port
);
560 r
= asprintf(&p
, "vsock:%u:%u", sa
->vm
.svm_cid
, sa
->vm
.svm_port
);
562 r
= asprintf(&p
, "vsock:%u", sa
->vm
.svm_cid
);
575 int getpeername_pretty(int fd
, bool include_port
, char **ret
) {
576 union sockaddr_union sa
;
577 socklen_t salen
= sizeof(sa
);
583 if (getpeername(fd
, &sa
.sa
, &salen
) < 0)
586 if (sa
.sa
.sa_family
== AF_UNIX
) {
587 struct ucred ucred
= UCRED_INVALID
;
589 /* UNIX connection sockets are anonymous, so let's use
590 * PID/UID as pretty credentials instead */
592 r
= getpeercred(fd
, &ucred
);
596 if (asprintf(ret
, "PID "PID_FMT
"/UID "UID_FMT
, ucred
.pid
, ucred
.uid
) < 0)
602 /* For remote sockets we translate IPv6 addresses back to IPv4
603 * if applicable, since that's nicer. */
605 return sockaddr_pretty(&sa
.sa
, salen
, true, include_port
, ret
);
608 int getsockname_pretty(int fd
, char **ret
) {
609 union sockaddr_union sa
;
610 socklen_t salen
= sizeof(sa
);
615 if (getsockname(fd
, &sa
.sa
, &salen
) < 0)
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
623 return sockaddr_pretty(&sa
.sa
, salen
, false, true, ret
);
626 int socknameinfo_pretty(const struct sockaddr
*sa
, socklen_t salen
, char **ret
) {
627 char host
[NI_MAXHOST
];
631 assert(salen
>= sizeof(sa_family_t
));
634 r
= getnameinfo(sa
, salen
, host
, sizeof(host
), /* service= */ NULL
, /* service_len= */ 0, IDN_FLAGS
);
637 return log_oom_debug();
639 log_debug_errno(errno
, "getnameinfo() failed, ignoring: %m");
641 log_debug("getnameinfo() failed, ignoring: %s", gai_strerror(r
));
643 return sockaddr_pretty(sa
, salen
, /* translate_ipv6= */ true, /* include_port= */ true, ret
);
646 return strdup_to(ret
, host
);
649 static const char* const netlink_family_table
[] = {
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",
663 [NETLINK_KOBJECT_UEVENT
] = "kobject-uevent",
664 [NETLINK_GENERIC
] = "generic",
665 [NETLINK_SCSITRANSPORT
] = "scsitransport",
666 [NETLINK_ECRYPTFS
] = "ecryptfs",
667 [NETLINK_RDMA
] = "rdma",
670 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(netlink_family
, int, INT_MAX
);
672 static 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"
678 DEFINE_STRING_TABLE_LOOKUP(socket_address_bind_ipv6_only
, SocketAddressBindIPv6Only
);
680 SocketAddressBindIPv6Only
socket_address_bind_ipv6_only_or_bool_from_string(const char *n
) {
683 r
= parse_boolean(n
);
685 return SOCKET_ADDRESS_IPV6_ONLY
;
687 return SOCKET_ADDRESS_BOTH
;
689 return socket_address_bind_ipv6_only_from_string(n
);
692 bool sockaddr_equal(const union sockaddr_union
*a
, const union sockaddr_union
*b
) {
696 if (a
->sa
.sa_family
!= b
->sa
.sa_family
)
699 if (a
->sa
.sa_family
== AF_INET
)
700 return a
->in
.sin_addr
.s_addr
== b
->in
.sin_addr
.s_addr
;
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;
705 if (a
->sa
.sa_family
== AF_VSOCK
)
706 return a
->vm
.svm_cid
== b
->vm
.svm_cid
;
711 int fd_set_sndbuf(int fd
, size_t n
, bool increase
) {
713 socklen_t l
= sizeof(value
);
718 r
= getsockopt(fd
, SOL_SOCKET
, SO_SNDBUF
, &value
, &l
);
719 if (r
>= 0 && l
== sizeof(value
) && increase
? (size_t) value
>= n
*2 : (size_t) value
== n
*2)
722 /* First, try to set the buffer size with SO_SNDBUF. */
723 r
= setsockopt_int(fd
, SOL_SOCKET
, SO_SNDBUF
, n
);
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. */
730 r
= getsockopt(fd
, SOL_SOCKET
, SO_SNDBUF
, &value
, &l
);
731 if (r
>= 0 && l
== sizeof(value
) && increase
? (size_t) value
>= n
*2 : (size_t) value
== n
*2)
734 /* If we have the privileges we will ignore the kernel limit. */
735 r
= setsockopt_int(fd
, SOL_SOCKET
, SO_SNDBUFFORCE
, n
);
742 int fd_set_rcvbuf(int fd
, size_t n
, bool increase
) {
744 socklen_t l
= sizeof(value
);
749 r
= getsockopt(fd
, SOL_SOCKET
, SO_RCVBUF
, &value
, &l
);
750 if (r
>= 0 && l
== sizeof(value
) && increase
? (size_t) value
>= n
*2 : (size_t) value
== n
*2)
753 /* First, try to set the buffer size with SO_RCVBUF. */
754 r
= setsockopt_int(fd
, SOL_SOCKET
, SO_RCVBUF
, n
);
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. */
761 r
= getsockopt(fd
, SOL_SOCKET
, SO_RCVBUF
, &value
, &l
);
762 if (r
>= 0 && l
== sizeof(value
) && increase
? (size_t) value
>= n
*2 : (size_t) value
== n
*2)
765 /* If we have the privileges we will ignore the kernel limit. */
766 r
= setsockopt_int(fd
, SOL_SOCKET
, SO_RCVBUFFORCE
, n
);
773 static const char* const ip_tos_table
[] = {
774 [IPTOS_LOWDELAY
] = "low-delay",
775 [IPTOS_THROUGHPUT
] = "throughput",
776 [IPTOS_RELIABILITY
] = "reliability",
777 [IPTOS_LOWCOST
] = "low-cost",
780 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(ip_tos
, int, 0xff);
782 bool ifname_valid_char(char a
) {
783 if ((unsigned char) a
>= 127U)
786 if ((unsigned char) a
<= 32U)
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 */
798 bool ifname_valid_full(const char *p
, IfnameValidFlags flags
) {
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. */
805 assert(!(flags
& ~_IFNAME_VALID_ALL
));
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
;
814 if (flags
& IFNAME_VALID_ALTERNATIVE
) {
815 if (strlen(p
) >= ALTIFNAMSIZ
)
818 if (strlen(p
) >= IFNAMSIZ
)
822 if (dot_or_dot_dot(p
))
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} */
827 if (!FLAGS_SET(flags
, IFNAME_VALID_SPECIAL
) && STR_IN_SET(p
, "all", "default"))
830 for (const char *t
= p
; *t
; t
++) {
831 if (!ifname_valid_char(*t
))
834 numeric
= numeric
&& ascii_isdigit(*t
);
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. */
845 bool address_label_valid(const char *p
) {
850 if (strlen(p
) >= IFNAMSIZ
)
854 if ((uint8_t) *p
>= 127U)
857 if ((uint8_t) *p
<= 31U)
865 int getpeercred(int fd
, struct ucred
*ucred
) {
866 socklen_t n
= sizeof(struct ucred
);
872 if (getsockopt(fd
, SOL_SOCKET
, SO_PEERCRED
, &u
, &n
) < 0)
875 if (n
!= sizeof(struct ucred
))
878 /* Check if the data is actually useful and not suppressed due to namespacing issues */
879 if (!pid_is_valid(u
.pid
))
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. */
889 int getpeersec(int fd
, char **ret
) {
890 _cleanup_free_
char *s
= NULL
;
901 if (getsockopt(fd
, SOL_SOCKET
, SO_PEERSEC
, s
, &n
) >= 0) {
920 int getpeergroups(int fd
, gid_t
**ret
) {
921 socklen_t n
= sizeof(gid_t
) * 64U;
922 _cleanup_free_ gid_t
*d
= NULL
;
927 long ngroups_max
= sysconf(_SC_NGROUPS_MAX
);
929 n
= MAX(n
, sizeof(gid_t
) * (socklen_t
) ngroups_max
);
936 if (getsockopt(fd
, SOL_SOCKET
, SO_PEERGROUPS
, d
, &n
) >= 0)
945 assert_se(n
% sizeof(gid_t
) == 0);
956 int getpeerpidfd(int fd
) {
957 socklen_t n
= sizeof(int);
962 if (getsockopt(fd
, SOL_SOCKET
, SO_PEERPIDFD
, &pidfd
, &n
) < 0)
965 if (n
!= sizeof(int))
971 int getpeerpidref(int fd
, PidRef
*ret
) {
977 int pidfd
= getpeerpidfd(fd
);
979 if (!ERRNO_IS_NEG_NOT_SUPPORTED(pidfd
))
983 r
= getpeercred(fd
, &ucred
);
987 return pidref_set_pid(ret
, ucred
.pid
);
990 return pidref_set_pidfd_consume(ret
, pidfd
);
993 ssize_t
send_many_fds_iov_sa(
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
,
1000 _cleanup_free_
struct cmsghdr
*cmsg
= NULL
;
1001 struct msghdr mh
= {
1002 .msg_name
= (struct sockaddr
*) sa
,
1004 .msg_iov
= (struct iovec
*)iov
,
1005 .msg_iovlen
= iovlen
,
1009 assert(transport_fd
>= 0);
1010 assert(fds_array
|| n_fds_array
== 0);
1012 /* The kernel will reject sending more than SCM_MAX_FD FDs at once */
1013 if (n_fds_array
> SCM_MAX_FD
)
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
)
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
);
1026 *cmsg
= (struct cmsghdr
) {
1027 .cmsg_len
= CMSG_LEN(sizeof(int) * n_fds_array
),
1028 .cmsg_level
= SOL_SOCKET
,
1029 .cmsg_type
= SCM_RIGHTS
,
1031 memcpy(CMSG_DATA(cmsg
), fds_array
, sizeof(int) * n_fds_array
);
1033 k
= sendmsg(transport_fd
, &mh
, MSG_NOSIGNAL
| flags
);
1035 return (ssize_t
) -errno
;
1040 ssize_t
send_one_fd_iov_sa(
1043 const struct iovec
*iov
, size_t iovlen
,
1044 const struct sockaddr
*sa
, socklen_t len
,
1047 CMSG_BUFFER_TYPE(CMSG_SPACE(sizeof(int))) control
= {};
1048 struct msghdr mh
= {
1049 .msg_name
= (struct sockaddr
*) sa
,
1051 .msg_iov
= (struct iovec
*)iov
,
1052 .msg_iovlen
= iovlen
,
1056 assert(transport_fd
>= 0);
1059 * We need either an FD or data to send.
1060 * If there's nothing, return an error.
1066 struct cmsghdr
*cmsg
;
1068 mh
.msg_control
= &control
;
1069 mh
.msg_controllen
= sizeof(control
);
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));
1077 k
= sendmsg(transport_fd
, &mh
, MSG_NOSIGNAL
| flags
);
1079 return (ssize_t
) -errno
;
1087 const struct sockaddr
*sa
, socklen_t len
,
1092 return (int) send_one_fd_iov_sa(transport_fd
, fd
, NULL
, 0, sa
, len
, flags
);
1095 ssize_t
receive_many_fds_iov(
1097 struct iovec
*iov
, size_t iovlen
,
1098 int **ret_fds_array
, size_t *ret_n_fds_array
,
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
),
1106 .msg_iovlen
= iovlen
,
1108 _cleanup_free_
int *fds_array
= NULL
;
1109 size_t n_fds_array
= 0;
1110 struct cmsghdr
*cmsg
;
1113 assert(transport_fd
>= 0);
1114 assert(ret_fds_array
);
1115 assert(ret_n_fds_array
);
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().
1122 k
= recvmsg_safe(transport_fd
, &mh
, MSG_CMSG_CLOEXEC
| flags
);
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);
1130 if (!GREEDY_REALLOC_APPEND(fds_array
, n_fds_array
, CMSG_TYPED_DATA(cmsg
, int), n
)) {
1131 cmsg_close_all(&mh
);
1136 if (n_fds_array
== 0) {
1137 cmsg_close_all(&mh
);
1139 /* If didn't receive an FD or any data, return an error. */
1144 *ret_fds_array
= TAKE_PTR(fds_array
);
1145 *ret_n_fds_array
= n_fds_array
;
1150 int receive_many_fds(int transport_fd
, int **ret_fds_array
, size_t *ret_n_fds_array
, int flags
) {
1153 k
= receive_many_fds_iov(transport_fd
, NULL
, 0, ret_fds_array
, ret_n_fds_array
, flags
);
1157 /* k must be negative, since receive_many_fds_iov() only returns a positive value if data was received
1158 * through the iov. */
1163 ssize_t
receive_one_fd_iov(
1165 struct iovec
*iov
, size_t iovlen
,
1169 CMSG_BUFFER_TYPE(CMSG_SPACE(sizeof(int))) control
;
1170 struct msghdr mh
= {
1171 .msg_control
= &control
,
1172 .msg_controllen
= sizeof(control
),
1174 .msg_iovlen
= iovlen
,
1176 struct cmsghdr
*found
;
1179 assert(transport_fd
>= 0);
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().
1190 k
= recvmsg_safe(transport_fd
, &mh
, MSG_CMSG_CLOEXEC
| flags
);
1194 found
= cmsg_find(&mh
, SOL_SOCKET
, SCM_RIGHTS
, CMSG_LEN(sizeof(int)));
1196 cmsg_close_all(&mh
);
1198 /* If didn't receive an FD or any data, return an error. */
1204 *ret_fd
= *CMSG_TYPED_DATA(found
, int);
1211 int receive_one_fd(int transport_fd
, int flags
) {
1215 k
= receive_one_fd_iov(transport_fd
, NULL
, 0, flags
, &fd
);
1219 /* k must be negative, since receive_one_fd_iov() only returns
1220 * a positive value if data was received through the iov. */
1225 ssize_t
next_datagram_size_fd(int fd
) {
1229 /* This is a bit like FIONREAD/SIOCINQ, however a bit more powerful. The difference being: recv(MSG_PEEK) will
1230 * actually cause the next datagram in the queue to be validated regarding checksums, which FIONREAD doesn't
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. */
1235 l
= recv(fd
, NULL
, 0, MSG_PEEK
|MSG_TRUNC
);
1237 if (IN_SET(errno
, EOPNOTSUPP
, EFAULT
))
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. */
1253 if (ioctl(fd
, FIONREAD
, &k
) < 0)
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
1263 int flush_accept(int fd
) {
1266 socklen_t l
= sizeof(b
);
1268 /* Similar to flush_fd() but flushes all incoming connections by accepting and immediately closing
1271 if (getsockopt(fd
, SOL_SOCKET
, SO_ACCEPTCONN
, &b
, &l
) < 0)
1274 assert(l
== sizeof(b
));
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. */
1282 for (unsigned iteration
= 0;; iteration
++) {
1285 r
= fd_wait_for_event(fd
, POLLIN
, 0);
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.");
1299 cfd
= accept4(fd
, NULL
, NULL
, SOCK_NONBLOCK
|SOCK_CLOEXEC
);
1301 if (errno
== EAGAIN
)
1304 if (ERRNO_IS_ACCEPT_AGAIN(errno
))
1314 ssize_t
flush_mqueue(int fd
) {
1315 _cleanup_free_
char *buf
= NULL
;
1316 struct mq_attr attr
;
1322 /* Similar to flush_fd() but flushes all messages from a POSIX message queue. */
1327 r
= fd_wait_for_event(fd
, POLLIN
, /* timeout= */ 0);
1338 /* Buffer must be at least as large as mq_msgsize. */
1339 if (mq_getattr(fd
, &attr
) < 0)
1342 buf
= malloc(attr
.mq_msgsize
);
1347 l
= mq_receive(fd
, buf
, attr
.mq_msgsize
, /* msg_prio = */ NULL
);
1352 if (errno
== EAGAIN
)
1362 struct cmsghdr
* cmsg_find(struct msghdr
*mh
, int level
, int type
, socklen_t length
) {
1363 struct cmsghdr
*cmsg
;
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
))
1376 void* cmsg_find_and_copy_data(struct msghdr
*mh
, int level
, int type
, void *buf
, size_t buf_len
) {
1377 struct cmsghdr
*cmsg
;
1381 assert(buf_len
> 0);
1383 /* This is similar to cmsg_find_data(), but copy the found data to buf. This should be typically used
1384 * when reading possibly unaligned data such as timestamp, as time_t is 64-bit and size_t is 32-bit on
1385 * RISCV32. See issue #27241. */
1387 cmsg
= cmsg_find(mh
, level
, type
, CMSG_LEN(buf_len
));
1391 return memcpy_safe(buf
, CMSG_DATA(cmsg
), buf_len
);
1394 size_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. */
1399 assert(sa
->sll_family
== AF_PACKET
);
1401 size_t mac_len
= sizeof(sa
->sll_addr
);
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
);
1408 return offsetof(struct sockaddr_ll
, sll_addr
) + mac_len
;
1411 size_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. */
1414 assert(sa
->sun_family
== AF_UNIX
);
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);
1422 size_t sockaddr_len(const union sockaddr_union
*sa
) {
1423 switch (sa
->sa
.sa_family
) {
1425 return sizeof(struct sockaddr_in
);
1427 return sizeof(struct sockaddr_in6
);
1429 return sockaddr_un_len(&sa
->un
);
1431 return sockaddr_ll_len(&sa
->ll
);
1433 return sizeof(struct sockaddr_nl
);
1435 return sizeof(struct sockaddr_vm
);
1437 assert_not_reached();
1441 int socket_ioctl_fd(void) {
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. */
1449 fd
= socket(AF_INET
, SOCK_DGRAM
|SOCK_CLOEXEC
, 0);
1451 fd
= socket(AF_NETLINK
, SOCK_RAW
|SOCK_CLOEXEC
, NETLINK_GENERIC
);
1458 int sockaddr_un_unlink(const struct sockaddr_un
*sa
) {
1459 const char *p
, * nul
;
1463 if (sa
->sun_family
!= AF_UNIX
)
1466 if (sa
->sun_path
[0] == 0) /* Nothing to do for abstract sockets */
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
));
1474 p
= memdupa_suffix0(sa
->sun_path
, sizeof(sa
->sun_path
));
1482 int sockaddr_un_set_path(struct sockaddr_un
*ret
, const char *path
) {
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. */
1496 if (!IN_SET(path
[0], '/', '@'))
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
1502 * do not expect non-NUL terminated file system path. */
1503 if (l
+1 > sizeof(ret
->sun_path
))
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. */
1509 *ret
= (struct sockaddr_un
) {
1510 .sun_family
= AF_UNIX
,
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 */
1519 assert(path
[0] == '/');
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 */
1527 int getsockopt_int(int fd
, int level
, int optname
, int *ret
) {
1529 socklen_t sl
= sizeof(v
);
1534 if (getsockopt(fd
, level
, optname
, &v
, &sl
) < 0)
1535 return negative_errno();
1536 if (sl
!= sizeof(v
))
1543 int socket_bind_to_ifname(int fd
, const char *ifname
) {
1546 /* Call with NULL to drop binding */
1548 return RET_NERRNO(setsockopt(fd
, SOL_SOCKET
, SO_BINDTODEVICE
, ifname
, strlen_ptr(ifname
)));
1551 int socket_bind_to_ifindex(int fd
, int ifindex
) {
1556 return RET_NERRNO(setsockopt(fd
, SOL_SOCKET
, SO_BINDTODEVICE
, NULL
, 0));
1558 return setsockopt_int(fd
, SOL_SOCKET
, SO_BINDTOIFINDEX
, ifindex
);
1561 int socket_autobind(int fd
, char **ret_name
) {
1562 _cleanup_free_
char *name
= NULL
;
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. */
1571 random
= random_u64();
1573 if (asprintf(&name
, "@%" PRIu64
, random
) < 0)
1576 union sockaddr_union sa
;
1577 assert_cc(DECIMAL_STR_MAX(uint64_t) < sizeof(sa
.un
.sun_path
));
1579 r
= sockaddr_un_set_path(&sa
.un
, name
);
1583 if (bind(fd
, &sa
.sa
, r
) < 0)
1587 *ret_name
= TAKE_PTR(name
);
1591 ssize_t
recvmsg_safe(int sockfd
, struct msghdr
*msg
, int flags
) {
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.
1597 * Note that unlike our usual coding style this might modify *msg on failure. */
1599 assert(sockfd
>= 0);
1602 n
= recvmsg(sockfd
, msg
, flags
);
1606 if (FLAGS_SET(msg
->msg_flags
, MSG_CTRUNC
) ||
1607 (!FLAGS_SET(flags
, MSG_PEEK
) && FLAGS_SET(msg
->msg_flags
, MSG_TRUNC
))) {
1608 cmsg_close_all(msg
);
1609 return FLAGS_SET(msg
->msg_flags
, MSG_CTRUNC
) ? -ECHRNG
: -EXFULL
;
1615 int socket_get_family(int fd
) {
1617 socklen_t sl
= sizeof(af
);
1619 if (getsockopt(fd
, SOL_SOCKET
, SO_DOMAIN
, &af
, &sl
) < 0)
1622 if (sl
!= sizeof(af
))
1628 int socket_set_recvpktinfo(int fd
, int af
, bool b
) {
1630 if (af
== AF_UNSPEC
) {
1631 af
= socket_get_family(fd
);
1639 return setsockopt_int(fd
, IPPROTO_IP
, IP_PKTINFO
, b
);
1642 return setsockopt_int(fd
, IPPROTO_IPV6
, IPV6_RECVPKTINFO
, b
);
1645 return setsockopt_int(fd
, SOL_NETLINK
, NETLINK_PKTINFO
, b
);
1648 return setsockopt_int(fd
, SOL_PACKET
, PACKET_AUXDATA
, b
);
1651 return -EAFNOSUPPORT
;
1655 int socket_set_unicast_if(int fd
, int af
, int ifi
) {
1656 be32_t ifindex_be
= htobe32(ifi
);
1658 if (af
== AF_UNSPEC
) {
1659 af
= socket_get_family(fd
);
1667 return RET_NERRNO(setsockopt(fd
, IPPROTO_IP
, IP_UNICAST_IF
, &ifindex_be
, sizeof(ifindex_be
)));
1670 return RET_NERRNO(setsockopt(fd
, IPPROTO_IPV6
, IPV6_UNICAST_IF
, &ifindex_be
, sizeof(ifindex_be
)));
1673 return -EAFNOSUPPORT
;
1677 int socket_set_option(int fd
, int af
, int opt_ipv4
, int opt_ipv6
, int val
) {
1678 if (af
== AF_UNSPEC
) {
1679 af
= socket_get_family(fd
);
1687 return setsockopt_int(fd
, IPPROTO_IP
, opt_ipv4
, val
);
1690 return setsockopt_int(fd
, IPPROTO_IPV6
, opt_ipv6
, val
);
1693 return -EAFNOSUPPORT
;
1697 int socket_get_mtu(int fd
, int af
, size_t *ret
) {
1700 if (af
== AF_UNSPEC
) {
1701 af
= socket_get_family(fd
);
1709 r
= getsockopt_int(fd
, IPPROTO_IP
, IP_MTU
, &mtu
);
1713 r
= getsockopt_int(fd
, IPPROTO_IPV6
, IPV6_MTU
, &mtu
);
1717 return -EAFNOSUPPORT
;
1725 *ret
= (size_t) mtu
;
1729 static int connect_unix_path_simple(int fd
, const char *path
) {
1730 union sockaddr_union sa
= {
1731 .un
.sun_family
= AF_UNIX
,
1740 assert(l
< sizeof(sa
.un
.sun_path
));
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));
1746 static int connect_unix_inode(int fd
, int inode_fd
) {
1748 assert(inode_fd
>= 0);
1750 return connect_unix_path_simple(fd
, FORMAT_PROC_FD_PATH(inode_fd
));
1753 int connect_unix_path(int fd
, int dir_fd
, const char *path
) {
1754 _cleanup_close_
int inode_fd
= -EBADF
;
1757 assert(dir_fd
== AT_FDCWD
|| dir_fd
>= 0);
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. */
1763 return connect_unix_inode(fd
, dir_fd
); /* If no path is specified, then dir_fd refers to the socket inode to connect to. */
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 */
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
);
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. */
1778 inode_fd
= openat(dir_fd
, path
, O_PATH
|O_CLOEXEC
);
1782 return connect_unix_inode(fd
, inode_fd
);
1785 int socket_address_parse_unix(SocketAddress
*ret_address
, const char *s
) {
1786 struct sockaddr_un un
;
1789 assert(ret_address
);
1792 if (!IN_SET(*s
, '/', '@'))
1795 r
= sockaddr_un_set_path(&un
, s
);
1799 *ret_address
= (SocketAddress
) {
1807 int socket_address_equal_unix(const char *a
, const char *b
) {
1808 SocketAddress socket_a
, socket_b
;
1814 r
= socket_address_parse_unix(&socket_a
, a
);
1818 r
= socket_address_parse_unix(&socket_b
, b
);
1822 return sockaddr_equal(&socket_a
.sockaddr
, &socket_b
.sockaddr
);
1825 int vsock_parse_port(const char *s
, unsigned *ret
) {
1834 r
= safe_atou(s
, &u
);
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. */
1841 if (u
== VMADDR_PORT_ANY
)
1848 int vsock_parse_cid(const char *s
, unsigned *ret
) {
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. */
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
;
1864 return safe_atou(s
, ret
);
1869 int 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
;
1876 assert(ret_address
);
1879 if ((cid_start
= startswith(s
, "vsock:")))
1881 else if ((cid_start
= startswith(s
, "vsock-dgram:")))
1883 else if ((cid_start
= startswith(s
, "vsock-seqpacket:")))
1884 type
= SOCK_SEQPACKET
;
1885 else if ((cid_start
= startswith(s
, "vsock-stream:")))
1890 e
= strchr(cid_start
, ':');
1894 r
= vsock_parse_port(e
+1, &port
);
1898 n
= strndup(cid_start
, e
- cid_start
);
1903 cid
= VMADDR_CID_ANY
;
1905 r
= vsock_parse_cid(n
, &cid
);
1910 *ret_address
= (SocketAddress
) {
1912 .svm_family
= AF_VSOCK
,
1917 .size
= sizeof(struct sockaddr_vm
),
1923 int vsock_get_local_cid(unsigned *ret
) {
1924 _cleanup_close_
int vsock_fd
= -EBADF
;
1926 vsock_fd
= open("/dev/vsock", O_RDONLY
|O_CLOEXEC
);
1928 return log_debug_errno(errno
, "Failed to open %s: %m", "/dev/vsock");
1931 if (ioctl(vsock_fd
, IOCTL_VM_SOCKETS_GET_LOCAL_CID
, ret
?: &tmp
) < 0)
1932 return log_debug_errno(errno
, "Failed to query local AF_VSOCK CID: %m");
1937 int 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
;
1943 if (getsockopt(fd
, SOL_NETLINK
, NETLINK_LIST_MEMBERSHIPS
, NULL
, &len
) < 0)
1949 groups
= new0(uint32_t, len
);
1955 if (getsockopt(fd
, SOL_NETLINK
, NETLINK_LIST_MEMBERSHIPS
, groups
, &len
) < 0)
1965 *ret_groups
= TAKE_PTR(groups
);
1970 int socket_get_cookie(int fd
, uint64_t *ret
) {
1973 uint64_t cookie
= 0;
1974 socklen_t cookie_len
= sizeof(cookie
);
1975 if (getsockopt(fd
, SOL_SOCKET
, SO_COOKIE
, &cookie
, &cookie_len
) < 0)
1978 assert(cookie_len
== sizeof(cookie
));
1985 void cmsg_close_all(struct msghdr
*mh
) {
1988 struct cmsghdr
*cmsg
;
1989 CMSG_FOREACH(cmsg
, mh
) {
1990 if (cmsg
->cmsg_level
!= SOL_SOCKET
)
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));