1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
8 #include <netinet/ip.h>
14 #include <sys/ioctl.h>
18 #include "alloc-util.h"
19 #include "errno-util.h"
23 #include "format-util.h"
26 #include "memory-util.h"
27 #include "parse-util.h"
28 #include "path-util.h"
29 #include "process-util.h"
30 #include "socket-util.h"
31 #include "string-table.h"
32 #include "string-util.h"
34 #include "sysctl-util.h"
35 #include "user-util.h"
39 # define IDN_FLAGS NI_IDN
44 /* From the kernel's include/net/scm.h */
46 # define SCM_MAX_FD 253
49 static const char* const socket_address_type_table
[] = {
50 [SOCK_STREAM
] = "Stream",
51 [SOCK_DGRAM
] = "Datagram",
53 [SOCK_RDM
] = "ReliableDatagram",
54 [SOCK_SEQPACKET
] = "SequentialPacket",
55 [SOCK_DCCP
] = "DatagramCongestionControl",
58 DEFINE_STRING_TABLE_LOOKUP(socket_address_type
, int);
60 int socket_address_verify(const SocketAddress
*a
, bool strict
) {
63 /* With 'strict' we enforce additional sanity constraints which are not set by the standard,
64 * but should only apply to sockets we create ourselves. */
66 switch (socket_address_family(a
)) {
69 if (a
->size
!= sizeof(struct sockaddr_in
))
72 if (a
->sockaddr
.in
.sin_port
== 0)
75 if (!IN_SET(a
->type
, 0, SOCK_STREAM
, SOCK_DGRAM
))
81 if (a
->size
!= sizeof(struct sockaddr_in6
))
84 if (a
->sockaddr
.in6
.sin6_port
== 0)
87 if (!IN_SET(a
->type
, 0, SOCK_STREAM
, SOCK_DGRAM
))
93 if (a
->size
< offsetof(struct sockaddr_un
, sun_path
))
95 if (a
->size
> sizeof(struct sockaddr_un
) + !strict
)
96 /* If !strict, allow one extra byte, since getsockname() on Linux will append
97 * a NUL byte if we have path sockets that are above sun_path's full size. */
100 if (a
->size
> offsetof(struct sockaddr_un
, sun_path
) &&
101 a
->sockaddr
.un
.sun_path
[0] != 0 &&
103 /* Only validate file system sockets here, and only in strict mode */
106 e
= memchr(a
->sockaddr
.un
.sun_path
, 0, sizeof(a
->sockaddr
.un
.sun_path
));
108 /* If there's an embedded NUL byte, make sure the size of the socket address matches it */
109 if (a
->size
!= offsetof(struct sockaddr_un
, sun_path
) + (e
- a
->sockaddr
.un
.sun_path
) + 1)
112 /* If there's no embedded NUL byte, then the size needs to match the whole
113 * structure or the structure with one extra NUL byte suffixed. (Yeah, Linux is awful,
114 * and considers both equivalent: getsockname() even extends sockaddr_un beyond its
115 * size if the path is non NUL terminated.) */
116 if (!IN_SET(a
->size
, sizeof(a
->sockaddr
.un
.sun_path
), sizeof(a
->sockaddr
.un
.sun_path
)+1))
121 if (!IN_SET(a
->type
, 0, SOCK_STREAM
, SOCK_DGRAM
, SOCK_SEQPACKET
))
128 if (a
->size
!= sizeof(struct sockaddr_nl
))
131 if (!IN_SET(a
->type
, 0, SOCK_RAW
, SOCK_DGRAM
))
137 if (a
->size
!= sizeof(struct sockaddr_vm
))
140 if (!IN_SET(a
->type
, 0, SOCK_STREAM
, SOCK_DGRAM
))
146 return -EAFNOSUPPORT
;
150 int socket_address_print(const SocketAddress
*a
, char **ret
) {
156 r
= socket_address_verify(a
, false); /* We do non-strict validation, because we want to be
157 * able to pretty-print any socket the kernel considers
158 * valid. We still need to do validation to know if we
159 * can meaningfully print the address. */
163 if (socket_address_family(a
) == AF_NETLINK
) {
164 _cleanup_free_
char *sfamily
= NULL
;
166 r
= netlink_family_to_string_alloc(a
->protocol
, &sfamily
);
170 r
= asprintf(ret
, "%s %u", sfamily
, a
->sockaddr
.nl
.nl_groups
);
177 return sockaddr_pretty(&a
->sockaddr
.sa
, a
->size
, false, true, ret
);
180 bool socket_address_can_accept(const SocketAddress
*a
) {
184 IN_SET(a
->type
, SOCK_STREAM
, SOCK_SEQPACKET
);
187 bool socket_address_equal(const SocketAddress
*a
, const SocketAddress
*b
) {
191 /* Invalid addresses are unequal to all */
192 if (socket_address_verify(a
, false) < 0 ||
193 socket_address_verify(b
, false) < 0)
196 if (a
->type
!= b
->type
)
199 if (socket_address_family(a
) != socket_address_family(b
))
202 switch (socket_address_family(a
)) {
205 if (a
->sockaddr
.in
.sin_addr
.s_addr
!= b
->sockaddr
.in
.sin_addr
.s_addr
)
208 if (a
->sockaddr
.in
.sin_port
!= b
->sockaddr
.in
.sin_port
)
214 if (memcmp(&a
->sockaddr
.in6
.sin6_addr
, &b
->sockaddr
.in6
.sin6_addr
, sizeof(a
->sockaddr
.in6
.sin6_addr
)) != 0)
217 if (a
->sockaddr
.in6
.sin6_port
!= b
->sockaddr
.in6
.sin6_port
)
223 if (a
->size
<= offsetof(struct sockaddr_un
, sun_path
) ||
224 b
->size
<= offsetof(struct sockaddr_un
, sun_path
))
227 if ((a
->sockaddr
.un
.sun_path
[0] == 0) != (b
->sockaddr
.un
.sun_path
[0] == 0))
230 if (a
->sockaddr
.un
.sun_path
[0]) {
231 if (!path_equal_or_inode_same(a
->sockaddr
.un
.sun_path
, b
->sockaddr
.un
.sun_path
, 0))
234 if (a
->size
!= b
->size
)
237 if (memcmp(a
->sockaddr
.un
.sun_path
, b
->sockaddr
.un
.sun_path
, a
->size
) != 0)
244 if (a
->protocol
!= b
->protocol
)
247 if (a
->sockaddr
.nl
.nl_groups
!= b
->sockaddr
.nl
.nl_groups
)
253 if (a
->sockaddr
.vm
.svm_cid
!= b
->sockaddr
.vm
.svm_cid
)
256 if (a
->sockaddr
.vm
.svm_port
!= b
->sockaddr
.vm
.svm_port
)
262 /* Cannot compare, so we assume the addresses are different */
269 const char* socket_address_get_path(const SocketAddress
*a
) {
272 if (socket_address_family(a
) != AF_UNIX
)
275 if (a
->sockaddr
.un
.sun_path
[0] == 0)
278 /* Note that this is only safe because we know that there's an extra NUL byte after the sockaddr_un
279 * structure. On Linux AF_UNIX file system socket addresses don't have to be NUL terminated if they take up the
280 * full sun_path space. */
281 assert_cc(sizeof(union sockaddr_union
) >= sizeof(struct sockaddr_un
)+1);
282 return a
->sockaddr
.un
.sun_path
;
285 bool socket_ipv6_is_supported(void) {
286 static int cached
= -1;
290 if (access("/proc/net/if_inet6", F_OK
) < 0) {
292 if (errno
!= ENOENT
) {
293 log_debug_errno(errno
, "Unexpected error when checking whether /proc/net/if_inet6 exists: %m");
305 bool socket_ipv6_is_enabled(void) {
306 _cleanup_free_
char *v
= NULL
;
309 /* Much like socket_ipv6_is_supported(), but also checks that the sysctl that disables IPv6 on all
310 * interfaces isn't turned on */
312 if (!socket_ipv6_is_supported())
315 r
= sysctl_read_ip_property(AF_INET6
, "all", "disable_ipv6", &v
);
317 log_debug_errno(r
, "Unexpected error reading 'net.ipv6.conf.all.disable_ipv6' sysctl: %m");
321 r
= parse_boolean(v
);
323 log_debug_errno(r
, "Failed to pare 'net.ipv6.conf.all.disable_ipv6' sysctl: %m");
330 bool socket_address_matches_fd(const SocketAddress
*a
, int fd
) {
337 b
.size
= sizeof(b
.sockaddr
);
338 if (getsockname(fd
, &b
.sockaddr
.sa
, &b
.size
) < 0)
341 if (b
.sockaddr
.sa
.sa_family
!= a
->sockaddr
.sa
.sa_family
)
344 solen
= sizeof(b
.type
);
345 if (getsockopt(fd
, SOL_SOCKET
, SO_TYPE
, &b
.type
, &solen
) < 0)
348 if (b
.type
!= a
->type
)
351 if (a
->protocol
!= 0) {
352 solen
= sizeof(b
.protocol
);
353 if (getsockopt(fd
, SOL_SOCKET
, SO_PROTOCOL
, &b
.protocol
, &solen
) < 0)
356 if (b
.protocol
!= a
->protocol
)
360 return socket_address_equal(a
, &b
);
363 int sockaddr_port(const struct sockaddr
*_sa
, unsigned *ret_port
) {
364 const union sockaddr_union
*sa
= (const union sockaddr_union
*) _sa
;
366 /* Note, this returns the port as 'unsigned' rather than 'uint16_t', as AF_VSOCK knows larger ports */
370 switch (sa
->sa
.sa_family
) {
373 *ret_port
= be16toh(sa
->in
.sin_port
);
377 *ret_port
= be16toh(sa
->in6
.sin6_port
);
381 *ret_port
= sa
->vm
.svm_port
;
385 return -EAFNOSUPPORT
;
389 const union in_addr_union
*sockaddr_in_addr(const struct sockaddr
*_sa
) {
390 const union sockaddr_union
*sa
= (const union sockaddr_union
*) _sa
;
395 switch (sa
->sa
.sa_family
) {
398 return (const union in_addr_union
*) &sa
->in
.sin_addr
;
401 return (const union in_addr_union
*) &sa
->in6
.sin6_addr
;
408 int sockaddr_set_in_addr(
409 union sockaddr_union
*u
,
411 const union in_addr_union
*a
,
420 u
->in
= (struct sockaddr_in
) {
421 .sin_family
= AF_INET
,
423 .sin_port
= htobe16(port
),
429 u
->in6
= (struct sockaddr_in6
) {
430 .sin6_family
= AF_INET6
,
432 .sin6_port
= htobe16(port
),
438 return -EAFNOSUPPORT
;
444 const struct sockaddr
*_sa
,
450 union sockaddr_union
*sa
= (union sockaddr_union
*) _sa
;
455 assert(salen
>= sizeof(sa
->sa
.sa_family
));
457 switch (sa
->sa
.sa_family
) {
462 a
= be32toh(sa
->in
.sin_addr
.s_addr
);
467 a
>> 24, (a
>> 16) & 0xFF, (a
>> 8) & 0xFF, a
& 0xFF,
468 be16toh(sa
->in
.sin_port
));
472 a
>> 24, (a
>> 16) & 0xFF, (a
>> 8) & 0xFF, a
& 0xFF);
479 static const unsigned char ipv4_prefix
[] = {
480 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xFF, 0xFF
483 if (translate_ipv6
&&
484 memcmp(&sa
->in6
.sin6_addr
, ipv4_prefix
, sizeof(ipv4_prefix
)) == 0) {
485 const uint8_t *a
= sa
->in6
.sin6_addr
.s6_addr
+12;
489 a
[0], a
[1], a
[2], a
[3],
490 be16toh(sa
->in6
.sin6_port
));
494 a
[0], a
[1], a
[2], a
[3]);
498 const char *a
= IN6_ADDR_TO_STRING(&sa
->in6
.sin6_addr
);
504 be16toh(sa
->in6
.sin6_port
),
505 sa
->in6
.sin6_scope_id
!= 0 ? "%" : "",
506 FORMAT_IFNAME_FULL(sa
->in6
.sin6_scope_id
, FORMAT_IFNAME_IFINDEX
)) < 0)
509 if (sa
->in6
.sin6_scope_id
!= 0)
510 p
= strjoin(a
, "%", FORMAT_IFNAME_FULL(sa
->in6
.sin6_scope_id
, FORMAT_IFNAME_IFINDEX
));
522 if (salen
<= offsetof(struct sockaddr_un
, sun_path
) ||
523 (sa
->un
.sun_path
[0] == 0 && salen
== offsetof(struct sockaddr_un
, sun_path
) + 1))
524 /* The name must have at least one character (and the leading NUL does not count) */
525 p
= strdup("<unnamed>");
527 /* Note that we calculate the path pointer here through the .un_buffer[] field, in order to
528 * outtrick bounds checking tools such as ubsan, which are too smart for their own good: on
529 * Linux the kernel may return sun_path[] data one byte longer than the declared size of the
531 char *path
= (char*) sa
->un_buffer
+ offsetof(struct sockaddr_un
, sun_path
);
532 size_t path_len
= salen
- offsetof(struct sockaddr_un
, sun_path
);
535 /* Abstract socket. When parsing address information from, we
536 * explicitly reject overly long paths and paths with embedded NULs.
537 * But we might get such a socket from the outside. Let's return
538 * something meaningful and printable in this case. */
540 _cleanup_free_
char *e
= NULL
;
542 e
= cescape_length(path
+ 1, path_len
- 1);
548 if (path
[path_len
- 1] == '\0')
549 /* We expect a terminating NUL and don't print it */
552 p
= cescape_length(path
, path_len
);
562 if (sa
->vm
.svm_cid
== VMADDR_CID_ANY
)
563 r
= asprintf(&p
, "vsock::%u", sa
->vm
.svm_port
);
565 r
= asprintf(&p
, "vsock:%u:%u", sa
->vm
.svm_cid
, sa
->vm
.svm_port
);
567 r
= asprintf(&p
, "vsock:%u", sa
->vm
.svm_cid
);
580 int getpeername_pretty(int fd
, bool include_port
, char **ret
) {
581 union sockaddr_union sa
;
582 socklen_t salen
= sizeof(sa
);
588 if (getpeername(fd
, &sa
.sa
, &salen
) < 0)
591 if (sa
.sa
.sa_family
== AF_UNIX
) {
592 struct ucred ucred
= UCRED_INVALID
;
594 /* UNIX connection sockets are anonymous, so let's use
595 * PID/UID as pretty credentials instead */
597 r
= getpeercred(fd
, &ucred
);
601 if (asprintf(ret
, "PID "PID_FMT
"/UID "UID_FMT
, ucred
.pid
, ucred
.uid
) < 0)
607 /* For remote sockets we translate IPv6 addresses back to IPv4
608 * if applicable, since that's nicer. */
610 return sockaddr_pretty(&sa
.sa
, salen
, true, include_port
, ret
);
613 int getsockname_pretty(int fd
, char **ret
) {
614 union sockaddr_union sa
;
615 socklen_t salen
= sizeof(sa
);
620 if (getsockname(fd
, &sa
.sa
, &salen
) < 0)
623 /* For local sockets we do not translate IPv6 addresses back
624 * to IPv6 if applicable, since this is usually used for
625 * listening sockets where the difference between IPv4 and
628 return sockaddr_pretty(&sa
.sa
, salen
, false, true, ret
);
631 int socknameinfo_pretty(union sockaddr_union
*sa
, socklen_t salen
, char **_ret
) {
633 char host
[NI_MAXHOST
], *ret
;
637 r
= getnameinfo(&sa
->sa
, salen
, host
, sizeof(host
), NULL
, 0, IDN_FLAGS
);
639 int saved_errno
= errno
;
641 r
= sockaddr_pretty(&sa
->sa
, salen
, true, true, &ret
);
645 log_debug_errno(saved_errno
, "getnameinfo(%s) failed: %m", ret
);
656 static const char* const netlink_family_table
[] = {
657 [NETLINK_ROUTE
] = "route",
658 [NETLINK_FIREWALL
] = "firewall",
659 [NETLINK_INET_DIAG
] = "inet-diag",
660 [NETLINK_NFLOG
] = "nflog",
661 [NETLINK_XFRM
] = "xfrm",
662 [NETLINK_SELINUX
] = "selinux",
663 [NETLINK_ISCSI
] = "iscsi",
664 [NETLINK_AUDIT
] = "audit",
665 [NETLINK_FIB_LOOKUP
] = "fib-lookup",
666 [NETLINK_CONNECTOR
] = "connector",
667 [NETLINK_NETFILTER
] = "netfilter",
668 [NETLINK_IP6_FW
] = "ip6-fw",
669 [NETLINK_DNRTMSG
] = "dnrtmsg",
670 [NETLINK_KOBJECT_UEVENT
] = "kobject-uevent",
671 [NETLINK_GENERIC
] = "generic",
672 [NETLINK_SCSITRANSPORT
] = "scsitransport",
673 [NETLINK_ECRYPTFS
] = "ecryptfs",
674 [NETLINK_RDMA
] = "rdma",
677 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(netlink_family
, int, INT_MAX
);
679 static const char* const socket_address_bind_ipv6_only_table
[_SOCKET_ADDRESS_BIND_IPV6_ONLY_MAX
] = {
680 [SOCKET_ADDRESS_DEFAULT
] = "default",
681 [SOCKET_ADDRESS_BOTH
] = "both",
682 [SOCKET_ADDRESS_IPV6_ONLY
] = "ipv6-only"
685 DEFINE_STRING_TABLE_LOOKUP(socket_address_bind_ipv6_only
, SocketAddressBindIPv6Only
);
687 SocketAddressBindIPv6Only
socket_address_bind_ipv6_only_or_bool_from_string(const char *n
) {
690 r
= parse_boolean(n
);
692 return SOCKET_ADDRESS_IPV6_ONLY
;
694 return SOCKET_ADDRESS_BOTH
;
696 return socket_address_bind_ipv6_only_from_string(n
);
699 bool sockaddr_equal(const union sockaddr_union
*a
, const union sockaddr_union
*b
) {
703 if (a
->sa
.sa_family
!= b
->sa
.sa_family
)
706 if (a
->sa
.sa_family
== AF_INET
)
707 return a
->in
.sin_addr
.s_addr
== b
->in
.sin_addr
.s_addr
;
709 if (a
->sa
.sa_family
== AF_INET6
)
710 return memcmp(&a
->in6
.sin6_addr
, &b
->in6
.sin6_addr
, sizeof(a
->in6
.sin6_addr
)) == 0;
712 if (a
->sa
.sa_family
== AF_VSOCK
)
713 return a
->vm
.svm_cid
== b
->vm
.svm_cid
;
718 int fd_set_sndbuf(int fd
, size_t n
, bool increase
) {
720 socklen_t l
= sizeof(value
);
725 r
= getsockopt(fd
, SOL_SOCKET
, SO_SNDBUF
, &value
, &l
);
726 if (r
>= 0 && l
== sizeof(value
) && increase
? (size_t) value
>= n
*2 : (size_t) value
== n
*2)
729 /* First, try to set the buffer size with SO_SNDBUF. */
730 r
= setsockopt_int(fd
, SOL_SOCKET
, SO_SNDBUF
, n
);
734 /* SO_SNDBUF above may set to the kernel limit, instead of the requested size.
735 * So, we need to check the actual buffer size here. */
737 r
= getsockopt(fd
, SOL_SOCKET
, SO_SNDBUF
, &value
, &l
);
738 if (r
>= 0 && l
== sizeof(value
) && increase
? (size_t) value
>= n
*2 : (size_t) value
== n
*2)
741 /* If we have the privileges we will ignore the kernel limit. */
742 r
= setsockopt_int(fd
, SOL_SOCKET
, SO_SNDBUFFORCE
, n
);
749 int fd_set_rcvbuf(int fd
, size_t n
, bool increase
) {
751 socklen_t l
= sizeof(value
);
756 r
= getsockopt(fd
, SOL_SOCKET
, SO_RCVBUF
, &value
, &l
);
757 if (r
>= 0 && l
== sizeof(value
) && increase
? (size_t) value
>= n
*2 : (size_t) value
== n
*2)
760 /* First, try to set the buffer size with SO_RCVBUF. */
761 r
= setsockopt_int(fd
, SOL_SOCKET
, SO_RCVBUF
, n
);
765 /* SO_RCVBUF above may set to the kernel limit, instead of the requested size.
766 * So, we need to check the actual buffer size here. */
768 r
= getsockopt(fd
, SOL_SOCKET
, SO_RCVBUF
, &value
, &l
);
769 if (r
>= 0 && l
== sizeof(value
) && increase
? (size_t) value
>= n
*2 : (size_t) value
== n
*2)
772 /* If we have the privileges we will ignore the kernel limit. */
773 r
= setsockopt_int(fd
, SOL_SOCKET
, SO_RCVBUFFORCE
, n
);
780 static const char* const ip_tos_table
[] = {
781 [IPTOS_LOWDELAY
] = "low-delay",
782 [IPTOS_THROUGHPUT
] = "throughput",
783 [IPTOS_RELIABILITY
] = "reliability",
784 [IPTOS_LOWCOST
] = "low-cost",
787 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(ip_tos
, int, 0xff);
789 bool ifname_valid_char(char a
) {
790 if ((unsigned char) a
>= 127U)
793 if ((unsigned char) a
<= 32U)
797 ':', /* colons are used by the legacy "alias" interface logic */
798 '/', /* slashes cannot work, since we need to use network interfaces in sysfs paths, and in paths slashes are separators */
799 '%')) /* %d is used in the kernel's weird foo%d format string naming feature which we really really don't want to ever run into by accident */
805 bool ifname_valid_full(const char *p
, IfnameValidFlags flags
) {
808 /* Checks whether a network interface name is valid. This is inspired by dev_valid_name() in the kernel sources
809 * but slightly stricter, as we only allow non-control, non-space ASCII characters in the interface name. We
810 * also don't permit names that only container numbers, to avoid confusion with numeric interface indexes. */
812 assert(!(flags
& ~_IFNAME_VALID_ALL
));
817 /* A valid ifindex? If so, it's valid iff IFNAME_VALID_NUMERIC is set */
818 if (parse_ifindex(p
) >= 0)
819 return flags
& IFNAME_VALID_NUMERIC
;
821 if (flags
& IFNAME_VALID_ALTERNATIVE
) {
822 if (strlen(p
) >= ALTIFNAMSIZ
)
825 if (strlen(p
) >= IFNAMSIZ
)
829 if (dot_or_dot_dot(p
))
832 /* Let's refuse "all" and "default" as interface name, to avoid collisions with the special sysctl
833 * directories /proc/sys/net/{ipv4,ipv6}/conf/{all,default} */
834 if (!FLAGS_SET(flags
, IFNAME_VALID_SPECIAL
) && STR_IN_SET(p
, "all", "default"))
837 for (const char *t
= p
; *t
; t
++) {
838 if (!ifname_valid_char(*t
))
841 numeric
= numeric
&& ascii_isdigit(*t
);
844 /* It's fully numeric but didn't parse as valid ifindex above? if so, it must be too large or zero or
845 * so, let's refuse that. */
852 bool address_label_valid(const char *p
) {
857 if (strlen(p
) >= IFNAMSIZ
)
861 if ((uint8_t) *p
>= 127U)
864 if ((uint8_t) *p
<= 31U)
872 int getpeercred(int fd
, struct ucred
*ucred
) {
873 socklen_t n
= sizeof(struct ucred
);
880 r
= getsockopt(fd
, SOL_SOCKET
, SO_PEERCRED
, &u
, &n
);
884 if (n
!= sizeof(struct ucred
))
887 /* Check if the data is actually useful and not suppressed due to namespacing issues */
888 if (!pid_is_valid(u
.pid
))
891 /* Note that we don't check UID/GID here, as namespace translation works differently there: instead of
892 * receiving in "invalid" user/group we get the overflow UID/GID. */
898 int getpeersec(int fd
, char **ret
) {
899 _cleanup_free_
char *s
= NULL
;
910 if (getsockopt(fd
, SOL_SOCKET
, SO_PEERSEC
, s
, &n
) >= 0)
927 int getpeergroups(int fd
, gid_t
**ret
) {
928 socklen_t n
= sizeof(gid_t
) * 64;
929 _cleanup_free_ gid_t
*d
= NULL
;
939 if (getsockopt(fd
, SOL_SOCKET
, SO_PEERGROUPS
, d
, &n
) >= 0)
948 assert_se(n
% sizeof(gid_t
) == 0);
951 if ((socklen_t
) (int) n
!= n
)
959 ssize_t
send_many_fds_iov_sa(
961 int *fds_array
, size_t n_fds_array
,
962 const struct iovec
*iov
, size_t iovlen
,
963 const struct sockaddr
*sa
, socklen_t len
,
966 _cleanup_free_
struct cmsghdr
*cmsg
= NULL
;
968 .msg_name
= (struct sockaddr
*) sa
,
970 .msg_iov
= (struct iovec
*)iov
,
971 .msg_iovlen
= iovlen
,
975 assert(transport_fd
>= 0);
976 assert(fds_array
|| n_fds_array
== 0);
978 /* The kernel will reject sending more than SCM_MAX_FD FDs at once */
979 if (n_fds_array
> SCM_MAX_FD
)
982 /* We need either an FD array or data to send. If there's nothing, return an error. */
983 if (n_fds_array
== 0 && !iov
)
986 if (n_fds_array
> 0) {
987 mh
.msg_controllen
= CMSG_SPACE(sizeof(int) * n_fds_array
);
988 mh
.msg_control
= cmsg
= malloc(mh
.msg_controllen
);
992 *cmsg
= (struct cmsghdr
) {
993 .cmsg_len
= CMSG_LEN(sizeof(int) * n_fds_array
),
994 .cmsg_level
= SOL_SOCKET
,
995 .cmsg_type
= SCM_RIGHTS
,
997 memcpy(CMSG_DATA(cmsg
), fds_array
, sizeof(int) * n_fds_array
);
999 k
= sendmsg(transport_fd
, &mh
, MSG_NOSIGNAL
| flags
);
1001 return (ssize_t
) -errno
;
1006 ssize_t
send_one_fd_iov_sa(
1009 const struct iovec
*iov
, size_t iovlen
,
1010 const struct sockaddr
*sa
, socklen_t len
,
1013 CMSG_BUFFER_TYPE(CMSG_SPACE(sizeof(int))) control
= {};
1014 struct msghdr mh
= {
1015 .msg_name
= (struct sockaddr
*) sa
,
1017 .msg_iov
= (struct iovec
*)iov
,
1018 .msg_iovlen
= iovlen
,
1022 assert(transport_fd
>= 0);
1025 * We need either an FD or data to send.
1026 * If there's nothing, return an error.
1032 struct cmsghdr
*cmsg
;
1034 mh
.msg_control
= &control
;
1035 mh
.msg_controllen
= sizeof(control
);
1037 cmsg
= CMSG_FIRSTHDR(&mh
);
1038 cmsg
->cmsg_level
= SOL_SOCKET
;
1039 cmsg
->cmsg_type
= SCM_RIGHTS
;
1040 cmsg
->cmsg_len
= CMSG_LEN(sizeof(int));
1041 memcpy(CMSG_DATA(cmsg
), &fd
, sizeof(int));
1043 k
= sendmsg(transport_fd
, &mh
, MSG_NOSIGNAL
| flags
);
1045 return (ssize_t
) -errno
;
1053 const struct sockaddr
*sa
, socklen_t len
,
1058 return (int) send_one_fd_iov_sa(transport_fd
, fd
, NULL
, 0, sa
, len
, flags
);
1061 ssize_t
receive_many_fds_iov(
1063 struct iovec
*iov
, size_t iovlen
,
1064 int **ret_fds_array
, size_t *ret_n_fds_array
,
1067 CMSG_BUFFER_TYPE(CMSG_SPACE(sizeof(int) * SCM_MAX_FD
)) control
;
1068 struct msghdr mh
= {
1069 .msg_control
= &control
,
1070 .msg_controllen
= sizeof(control
),
1072 .msg_iovlen
= iovlen
,
1074 _cleanup_free_
int *fds_array
= NULL
;
1075 size_t n_fds_array
= 0;
1076 struct cmsghdr
*cmsg
;
1079 assert(transport_fd
>= 0);
1080 assert(ret_fds_array
);
1081 assert(ret_n_fds_array
);
1084 * Receive many FDs via @transport_fd. We don't care for the transport-type. We retrieve all the FDs
1085 * at once. This is best used in combination with send_many_fds().
1088 k
= recvmsg_safe(transport_fd
, &mh
, MSG_CMSG_CLOEXEC
| flags
);
1092 CMSG_FOREACH(cmsg
, &mh
)
1093 if (cmsg
->cmsg_level
== SOL_SOCKET
&& cmsg
->cmsg_type
== SCM_RIGHTS
) {
1094 size_t n
= (cmsg
->cmsg_len
- CMSG_LEN(0)) / sizeof(int);
1096 fds_array
= GREEDY_REALLOC(fds_array
, n_fds_array
+ n
);
1098 cmsg_close_all(&mh
);
1102 memcpy(fds_array
+ n_fds_array
, CMSG_TYPED_DATA(cmsg
, int), sizeof(int) * n
);
1106 if (n_fds_array
== 0) {
1107 cmsg_close_all(&mh
);
1109 /* If didn't receive an FD or any data, return an error. */
1114 *ret_fds_array
= TAKE_PTR(fds_array
);
1115 *ret_n_fds_array
= n_fds_array
;
1120 int receive_many_fds(int transport_fd
, int **ret_fds_array
, size_t *ret_n_fds_array
, int flags
) {
1123 k
= receive_many_fds_iov(transport_fd
, NULL
, 0, ret_fds_array
, ret_n_fds_array
, flags
);
1127 /* k must be negative, since receive_many_fds_iov() only returns a positive value if data was received
1128 * through the iov. */
1133 ssize_t
receive_one_fd_iov(
1135 struct iovec
*iov
, size_t iovlen
,
1139 CMSG_BUFFER_TYPE(CMSG_SPACE(sizeof(int))) control
;
1140 struct msghdr mh
= {
1141 .msg_control
= &control
,
1142 .msg_controllen
= sizeof(control
),
1144 .msg_iovlen
= iovlen
,
1146 struct cmsghdr
*found
;
1149 assert(transport_fd
>= 0);
1153 * Receive a single FD via @transport_fd. We don't care for
1154 * the transport-type. We retrieve a single FD at most, so for
1155 * packet-based transports, the caller must ensure to send
1156 * only a single FD per packet. This is best used in
1157 * combination with send_one_fd().
1160 k
= recvmsg_safe(transport_fd
, &mh
, MSG_CMSG_CLOEXEC
| flags
);
1164 found
= cmsg_find(&mh
, SOL_SOCKET
, SCM_RIGHTS
, CMSG_LEN(sizeof(int)));
1166 cmsg_close_all(&mh
);
1168 /* If didn't receive an FD or any data, return an error. */
1174 *ret_fd
= *CMSG_TYPED_DATA(found
, int);
1181 int receive_one_fd(int transport_fd
, int flags
) {
1185 k
= receive_one_fd_iov(transport_fd
, NULL
, 0, flags
, &fd
);
1189 /* k must be negative, since receive_one_fd_iov() only returns
1190 * a positive value if data was received through the iov. */
1195 ssize_t
next_datagram_size_fd(int fd
) {
1199 /* This is a bit like FIONREAD/SIOCINQ, however a bit more powerful. The difference being: recv(MSG_PEEK) will
1200 * actually cause the next datagram in the queue to be validated regarding checksums, which FIONREAD doesn't
1201 * do. This difference is actually of major importance as we need to be sure that the size returned here
1202 * actually matches what we will read with recvmsg() next, as otherwise we might end up allocating a buffer of
1203 * the wrong size. */
1205 l
= recv(fd
, NULL
, 0, MSG_PEEK
|MSG_TRUNC
);
1207 if (IN_SET(errno
, EOPNOTSUPP
, EFAULT
))
1220 /* Some sockets (AF_PACKET) do not support null-sized recv() with MSG_TRUNC set, let's fall back to FIONREAD
1221 * for them. Checksums don't matter for raw sockets anyway, hence this should be fine. */
1223 if (ioctl(fd
, FIONREAD
, &k
) < 0)
1229 /* Put a limit on how many times will attempt to call accept4(). We loop
1230 * only on "transient" errors, but let's make sure we don't loop forever. */
1231 #define MAX_FLUSH_ITERATIONS 1024
1233 int flush_accept(int fd
) {
1236 socklen_t l
= sizeof(b
);
1238 /* Similar to flush_fd() but flushes all incoming connections by accepting and immediately closing
1241 if (getsockopt(fd
, SOL_SOCKET
, SO_ACCEPTCONN
, &b
, &l
) < 0)
1244 assert(l
== sizeof(b
));
1245 if (!b
) /* Let's check if this socket accepts connections before calling accept(). accept4() can
1246 * return EOPNOTSUPP if the fd is not a listening socket, which we should treat as a fatal
1247 * error, or in case the incoming TCP connection triggered a network issue, which we want to
1248 * treat as a transient error. Thus, let's rule out the first reason for EOPNOTSUPP early, so
1249 * we can loop safely on transient errors below. */
1252 for (unsigned iteration
= 0;; iteration
++) {
1255 r
= fd_wait_for_event(fd
, POLLIN
, 0);
1265 if (iteration
>= MAX_FLUSH_ITERATIONS
)
1266 return log_debug_errno(SYNTHETIC_ERRNO(EBUSY
),
1267 "Failed to flush connections within " STRINGIFY(MAX_FLUSH_ITERATIONS
) " iterations.");
1269 cfd
= accept4(fd
, NULL
, NULL
, SOCK_NONBLOCK
|SOCK_CLOEXEC
);
1271 if (errno
== EAGAIN
)
1274 if (ERRNO_IS_ACCEPT_AGAIN(errno
))
1284 struct cmsghdr
* cmsg_find(struct msghdr
*mh
, int level
, int type
, socklen_t length
) {
1285 struct cmsghdr
*cmsg
;
1289 CMSG_FOREACH(cmsg
, mh
)
1290 if (cmsg
->cmsg_level
== level
&&
1291 cmsg
->cmsg_type
== type
&&
1292 (length
== (socklen_t
) -1 || length
== cmsg
->cmsg_len
))
1298 void* cmsg_find_and_copy_data(struct msghdr
*mh
, int level
, int type
, void *buf
, size_t buf_len
) {
1299 struct cmsghdr
*cmsg
;
1303 assert(buf_len
> 0);
1305 /* This is similar to cmsg_find_data(), but copy the found data to buf. This should be typically used
1306 * when reading possibly unaligned data such as timestamp, as time_t is 64-bit and size_t is 32-bit on
1307 * RISCV32. See issue #27241. */
1309 cmsg
= cmsg_find(mh
, level
, type
, CMSG_LEN(buf_len
));
1313 return memcpy_safe(buf
, CMSG_DATA(cmsg
), buf_len
);
1316 int socket_ioctl_fd(void) {
1319 /* Create a socket to invoke the various network interface ioctl()s on. Traditionally only AF_INET was good for
1320 * that. Since kernel 4.6 AF_NETLINK works for this too. We first try to use AF_INET hence, but if that's not
1321 * available (for example, because it is made unavailable via SECCOMP or such), we'll fall back to the more
1322 * generic AF_NETLINK. */
1324 fd
= socket(AF_INET
, SOCK_DGRAM
|SOCK_CLOEXEC
, 0);
1326 fd
= socket(AF_NETLINK
, SOCK_RAW
|SOCK_CLOEXEC
, NETLINK_GENERIC
);
1333 int sockaddr_un_unlink(const struct sockaddr_un
*sa
) {
1334 const char *p
, * nul
;
1338 if (sa
->sun_family
!= AF_UNIX
)
1341 if (sa
->sun_path
[0] == 0) /* Nothing to do for abstract sockets */
1344 /* The path in .sun_path is not necessarily NUL terminated. Let's fix that. */
1345 nul
= memchr(sa
->sun_path
, 0, sizeof(sa
->sun_path
));
1349 p
= memdupa_suffix0(sa
->sun_path
, sizeof(sa
->sun_path
));
1357 int sockaddr_un_set_path(struct sockaddr_un
*ret
, const char *path
) {
1363 /* Initialize ret->sun_path from the specified argument. This will interpret paths starting with '@' as
1364 * abstract namespace sockets, and those starting with '/' as regular filesystem sockets. It won't accept
1365 * anything else (i.e. no relative paths), to avoid ambiguities. Note that this function cannot be used to
1366 * reference paths in the abstract namespace that include NUL bytes in the name. */
1371 if (!IN_SET(path
[0], '/', '@'))
1374 /* Don't allow paths larger than the space in sockaddr_un. Note that we are a tiny bit more restrictive than
1375 * the kernel is: we insist on NUL termination (both for abstract namespace and regular file system socket
1376 * addresses!), which the kernel doesn't. We do this to reduce chance of incompatibility with other apps that
1377 * do not expect non-NUL terminated file system path. */
1378 if (l
+1 > sizeof(ret
->sun_path
))
1379 return path
[0] == '@' ? -EINVAL
: -ENAMETOOLONG
; /* return a recognizable error if this is
1380 * too long to fit into a sockaddr_un, but
1381 * is a file system path, and thus might be
1382 * connectible via O_PATH indirection. */
1384 *ret
= (struct sockaddr_un
) {
1385 .sun_family
= AF_UNIX
,
1388 if (path
[0] == '@') {
1389 /* Abstract namespace socket */
1390 memcpy(ret
->sun_path
+ 1, path
+ 1, l
); /* copy *with* trailing NUL byte */
1391 return (int) (offsetof(struct sockaddr_un
, sun_path
) + l
); /* 🔥 *don't* 🔥 include trailing NUL in size */
1394 assert(path
[0] == '/');
1396 /* File system socket */
1397 memcpy(ret
->sun_path
, path
, l
+ 1); /* copy *with* trailing NUL byte */
1398 return (int) (offsetof(struct sockaddr_un
, sun_path
) + l
+ 1); /* include trailing NUL in size */
1402 int socket_bind_to_ifname(int fd
, const char *ifname
) {
1405 /* Call with NULL to drop binding */
1407 return RET_NERRNO(setsockopt(fd
, SOL_SOCKET
, SO_BINDTODEVICE
, ifname
, strlen_ptr(ifname
)));
1410 int socket_bind_to_ifindex(int fd
, int ifindex
) {
1411 char ifname
[IF_NAMESIZE
];
1418 return RET_NERRNO(setsockopt(fd
, SOL_SOCKET
, SO_BINDTODEVICE
, NULL
, 0));
1420 r
= setsockopt_int(fd
, SOL_SOCKET
, SO_BINDTOIFINDEX
, ifindex
);
1421 if (r
!= -ENOPROTOOPT
)
1424 /* Fall back to SO_BINDTODEVICE on kernels < 5.0 which didn't have SO_BINDTOIFINDEX */
1425 r
= format_ifname(ifindex
, ifname
);
1429 return socket_bind_to_ifname(fd
, ifname
);
1432 ssize_t
recvmsg_safe(int sockfd
, struct msghdr
*msg
, int flags
) {
1435 /* A wrapper around recvmsg() that checks for MSG_CTRUNC, and turns it into an error, in a reasonably
1436 * safe way, closing any SCM_RIGHTS fds in the error path.
1438 * Note that unlike our usual coding style this might modify *msg on failure. */
1440 n
= recvmsg(sockfd
, msg
, flags
);
1444 if (FLAGS_SET(msg
->msg_flags
, MSG_CTRUNC
)) {
1445 cmsg_close_all(msg
);
1446 return -EXFULL
; /* a recognizable error code */
1452 int socket_get_family(int fd
) {
1454 socklen_t sl
= sizeof(af
);
1456 if (getsockopt(fd
, SOL_SOCKET
, SO_DOMAIN
, &af
, &sl
) < 0)
1459 if (sl
!= sizeof(af
))
1465 int socket_set_recvpktinfo(int fd
, int af
, bool b
) {
1467 if (af
== AF_UNSPEC
) {
1468 af
= socket_get_family(fd
);
1476 return setsockopt_int(fd
, IPPROTO_IP
, IP_PKTINFO
, b
);
1479 return setsockopt_int(fd
, IPPROTO_IPV6
, IPV6_RECVPKTINFO
, b
);
1482 return setsockopt_int(fd
, SOL_NETLINK
, NETLINK_PKTINFO
, b
);
1485 return setsockopt_int(fd
, SOL_PACKET
, PACKET_AUXDATA
, b
);
1488 return -EAFNOSUPPORT
;
1492 int socket_set_unicast_if(int fd
, int af
, int ifi
) {
1493 be32_t ifindex_be
= htobe32(ifi
);
1495 if (af
== AF_UNSPEC
) {
1496 af
= socket_get_family(fd
);
1504 return RET_NERRNO(setsockopt(fd
, IPPROTO_IP
, IP_UNICAST_IF
, &ifindex_be
, sizeof(ifindex_be
)));
1507 return RET_NERRNO(setsockopt(fd
, IPPROTO_IPV6
, IPV6_UNICAST_IF
, &ifindex_be
, sizeof(ifindex_be
)));
1510 return -EAFNOSUPPORT
;
1514 int socket_set_option(int fd
, int af
, int opt_ipv4
, int opt_ipv6
, int val
) {
1515 if (af
== AF_UNSPEC
) {
1516 af
= socket_get_family(fd
);
1524 return setsockopt_int(fd
, IPPROTO_IP
, opt_ipv4
, val
);
1527 return setsockopt_int(fd
, IPPROTO_IPV6
, opt_ipv6
, val
);
1530 return -EAFNOSUPPORT
;
1534 int socket_get_mtu(int fd
, int af
, size_t *ret
) {
1537 if (af
== AF_UNSPEC
) {
1538 af
= socket_get_family(fd
);
1546 r
= getsockopt_int(fd
, IPPROTO_IP
, IP_MTU
, &mtu
);
1550 r
= getsockopt_int(fd
, IPPROTO_IPV6
, IPV6_MTU
, &mtu
);
1554 return -EAFNOSUPPORT
;
1562 *ret
= (size_t) mtu
;
1566 static int connect_unix_path_simple(int fd
, const char *path
) {
1567 union sockaddr_union sa
= {
1568 .un
.sun_family
= AF_UNIX
,
1577 assert(l
< sizeof(sa
.un
.sun_path
));
1579 memcpy(sa
.un
.sun_path
, path
, l
+ 1);
1580 return RET_NERRNO(connect(fd
, &sa
.sa
, offsetof(struct sockaddr_un
, sun_path
) + l
+ 1));
1583 static int connect_unix_inode(int fd
, int inode_fd
) {
1585 assert(inode_fd
>= 0);
1587 return connect_unix_path_simple(fd
, FORMAT_PROC_FD_PATH(inode_fd
));
1590 int connect_unix_path(int fd
, int dir_fd
, const char *path
) {
1591 _cleanup_close_
int inode_fd
= -EBADF
;
1594 assert(dir_fd
== AT_FDCWD
|| dir_fd
>= 0);
1596 /* Connects to the specified AF_UNIX socket in the file system. Works around the 108 byte size limit
1597 * in sockaddr_un, by going via O_PATH if needed. This hence works for any kind of path. */
1600 return connect_unix_inode(fd
, dir_fd
); /* If no path is specified, then dir_fd refers to the socket inode to connect to. */
1602 /* Refuse zero length path early, to make sure AF_UNIX stack won't mistake this for an abstract
1603 * namespace path, since first char is NUL */
1607 /* Shortcut for the simple case */
1608 if (dir_fd
== AT_FDCWD
&& strlen(path
) < sizeof_field(struct sockaddr_un
, sun_path
))
1609 return connect_unix_path_simple(fd
, path
);
1611 /* If dir_fd is specified, then we need to go the indirect O_PATH route, because connectat() does not
1612 * exist. If the path is too long, we also need to take the indirect route, since we can't fit this
1613 * into a sockaddr_un directly. */
1615 inode_fd
= openat(dir_fd
, path
, O_PATH
|O_CLOEXEC
);
1619 return connect_unix_inode(fd
, inode_fd
);
1622 int socket_address_parse_unix(SocketAddress
*ret_address
, const char *s
) {
1623 struct sockaddr_un un
;
1626 assert(ret_address
);
1629 if (!IN_SET(*s
, '/', '@'))
1632 r
= sockaddr_un_set_path(&un
, s
);
1636 *ret_address
= (SocketAddress
) {
1644 int socket_address_parse_vsock(SocketAddress
*ret_address
, const char *s
) {
1645 /* AF_VSOCK socket in vsock:cid:port notation */
1646 _cleanup_free_
char *n
= NULL
;
1647 char *e
, *cid_start
;
1651 assert(ret_address
);
1654 if ((cid_start
= startswith(s
, "vsock:")))
1656 else if ((cid_start
= startswith(s
, "vsock-dgram:")))
1658 else if ((cid_start
= startswith(s
, "vsock-seqpacket:")))
1659 type
= SOCK_SEQPACKET
;
1660 else if ((cid_start
= startswith(s
, "vsock-stream:")))
1665 e
= strchr(cid_start
, ':');
1669 r
= safe_atou(e
+1, &port
);
1673 n
= strndup(cid_start
, e
- cid_start
);
1678 cid
= VMADDR_CID_ANY
;
1680 r
= safe_atou(n
, &cid
);
1685 *ret_address
= (SocketAddress
) {
1688 .svm_family
= AF_VSOCK
,
1692 .size
= sizeof(struct sockaddr_vm
),