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 static const char* const socket_address_type_table
[] = {
45 [SOCK_STREAM
] = "Stream",
46 [SOCK_DGRAM
] = "Datagram",
48 [SOCK_RDM
] = "ReliableDatagram",
49 [SOCK_SEQPACKET
] = "SequentialPacket",
50 [SOCK_DCCP
] = "DatagramCongestionControl",
53 DEFINE_STRING_TABLE_LOOKUP(socket_address_type
, int);
55 int socket_address_verify(const SocketAddress
*a
, bool strict
) {
58 /* With 'strict' we enforce additional sanity constraints which are not set by the standard,
59 * but should only apply to sockets we create ourselves. */
61 switch (socket_address_family(a
)) {
64 if (a
->size
!= sizeof(struct sockaddr_in
))
67 if (a
->sockaddr
.in
.sin_port
== 0)
70 if (!IN_SET(a
->type
, 0, SOCK_STREAM
, SOCK_DGRAM
))
76 if (a
->size
!= sizeof(struct sockaddr_in6
))
79 if (a
->sockaddr
.in6
.sin6_port
== 0)
82 if (!IN_SET(a
->type
, 0, SOCK_STREAM
, SOCK_DGRAM
))
88 if (a
->size
< offsetof(struct sockaddr_un
, sun_path
))
90 if (a
->size
> sizeof(struct sockaddr_un
) + !strict
)
91 /* If !strict, allow one extra byte, since getsockname() on Linux will append
92 * a NUL byte if we have path sockets that are above sun_path's full size. */
95 if (a
->size
> offsetof(struct sockaddr_un
, sun_path
) &&
96 a
->sockaddr
.un
.sun_path
[0] != 0 &&
98 /* Only validate file system sockets here, and only in strict mode */
101 e
= memchr(a
->sockaddr
.un
.sun_path
, 0, sizeof(a
->sockaddr
.un
.sun_path
));
103 /* If there's an embedded NUL byte, make sure the size of the socket address matches it */
104 if (a
->size
!= offsetof(struct sockaddr_un
, sun_path
) + (e
- a
->sockaddr
.un
.sun_path
) + 1)
107 /* If there's no embedded NUL byte, then the size needs to match the whole
108 * structure or the structure with one extra NUL byte suffixed. (Yeah, Linux is awful,
109 * and considers both equivalent: getsockname() even extends sockaddr_un beyond its
110 * size if the path is non NUL terminated.) */
111 if (!IN_SET(a
->size
, sizeof(a
->sockaddr
.un
.sun_path
), sizeof(a
->sockaddr
.un
.sun_path
)+1))
116 if (!IN_SET(a
->type
, 0, SOCK_STREAM
, SOCK_DGRAM
, SOCK_SEQPACKET
))
123 if (a
->size
!= sizeof(struct sockaddr_nl
))
126 if (!IN_SET(a
->type
, 0, SOCK_RAW
, SOCK_DGRAM
))
132 if (a
->size
!= sizeof(struct sockaddr_vm
))
135 if (!IN_SET(a
->type
, 0, SOCK_STREAM
, SOCK_DGRAM
))
141 return -EAFNOSUPPORT
;
145 int socket_address_print(const SocketAddress
*a
, char **ret
) {
151 r
= socket_address_verify(a
, false); /* We do non-strict validation, because we want to be
152 * able to pretty-print any socket the kernel considers
153 * valid. We still need to do validation to know if we
154 * can meaningfully print the address. */
158 if (socket_address_family(a
) == AF_NETLINK
) {
159 _cleanup_free_
char *sfamily
= NULL
;
161 r
= netlink_family_to_string_alloc(a
->protocol
, &sfamily
);
165 r
= asprintf(ret
, "%s %u", sfamily
, a
->sockaddr
.nl
.nl_groups
);
172 return sockaddr_pretty(&a
->sockaddr
.sa
, a
->size
, false, true, ret
);
175 bool socket_address_can_accept(const SocketAddress
*a
) {
179 IN_SET(a
->type
, SOCK_STREAM
, SOCK_SEQPACKET
);
182 bool socket_address_equal(const SocketAddress
*a
, const SocketAddress
*b
) {
186 /* Invalid addresses are unequal to all */
187 if (socket_address_verify(a
, false) < 0 ||
188 socket_address_verify(b
, false) < 0)
191 if (a
->type
!= b
->type
)
194 if (socket_address_family(a
) != socket_address_family(b
))
197 switch (socket_address_family(a
)) {
200 if (a
->sockaddr
.in
.sin_addr
.s_addr
!= b
->sockaddr
.in
.sin_addr
.s_addr
)
203 if (a
->sockaddr
.in
.sin_port
!= b
->sockaddr
.in
.sin_port
)
209 if (memcmp(&a
->sockaddr
.in6
.sin6_addr
, &b
->sockaddr
.in6
.sin6_addr
, sizeof(a
->sockaddr
.in6
.sin6_addr
)) != 0)
212 if (a
->sockaddr
.in6
.sin6_port
!= b
->sockaddr
.in6
.sin6_port
)
218 if (a
->size
<= offsetof(struct sockaddr_un
, sun_path
) ||
219 b
->size
<= offsetof(struct sockaddr_un
, sun_path
))
222 if ((a
->sockaddr
.un
.sun_path
[0] == 0) != (b
->sockaddr
.un
.sun_path
[0] == 0))
225 if (a
->sockaddr
.un
.sun_path
[0]) {
226 if (!path_equal_or_files_same(a
->sockaddr
.un
.sun_path
, b
->sockaddr
.un
.sun_path
, 0))
229 if (a
->size
!= b
->size
)
232 if (memcmp(a
->sockaddr
.un
.sun_path
, b
->sockaddr
.un
.sun_path
, a
->size
) != 0)
239 if (a
->protocol
!= b
->protocol
)
242 if (a
->sockaddr
.nl
.nl_groups
!= b
->sockaddr
.nl
.nl_groups
)
248 if (a
->sockaddr
.vm
.svm_cid
!= b
->sockaddr
.vm
.svm_cid
)
251 if (a
->sockaddr
.vm
.svm_port
!= b
->sockaddr
.vm
.svm_port
)
257 /* Cannot compare, so we assume the addresses are different */
264 const char* socket_address_get_path(const SocketAddress
*a
) {
267 if (socket_address_family(a
) != AF_UNIX
)
270 if (a
->sockaddr
.un
.sun_path
[0] == 0)
273 /* Note that this is only safe because we know that there's an extra NUL byte after the sockaddr_un
274 * structure. On Linux AF_UNIX file system socket addresses don't have to be NUL terminated if they take up the
275 * full sun_path space. */
276 assert_cc(sizeof(union sockaddr_union
) >= sizeof(struct sockaddr_un
)+1);
277 return a
->sockaddr
.un
.sun_path
;
280 bool socket_ipv6_is_supported(void) {
281 static int cached
= -1;
285 if (access("/proc/net/if_inet6", F_OK
) < 0) {
287 if (errno
!= ENOENT
) {
288 log_debug_errno(errno
, "Unexpected error when checking whether /proc/net/if_inet6 exists: %m");
300 bool socket_ipv6_is_enabled(void) {
301 _cleanup_free_
char *v
= NULL
;
304 /* Much like socket_ipv6_is_supported(), but also checks that the sysctl that disables IPv6 on all
305 * interfaces isn't turned on */
307 if (!socket_ipv6_is_supported())
310 r
= sysctl_read_ip_property(AF_INET6
, "all", "disable_ipv6", &v
);
312 log_debug_errno(r
, "Unexpected error reading 'net.ipv6.conf.all.disable_ipv6' sysctl: %m");
316 r
= parse_boolean(v
);
318 log_debug_errno(r
, "Failed to pare 'net.ipv6.conf.all.disable_ipv6' sysctl: %m");
325 bool socket_address_matches_fd(const SocketAddress
*a
, int fd
) {
332 b
.size
= sizeof(b
.sockaddr
);
333 if (getsockname(fd
, &b
.sockaddr
.sa
, &b
.size
) < 0)
336 if (b
.sockaddr
.sa
.sa_family
!= a
->sockaddr
.sa
.sa_family
)
339 solen
= sizeof(b
.type
);
340 if (getsockopt(fd
, SOL_SOCKET
, SO_TYPE
, &b
.type
, &solen
) < 0)
343 if (b
.type
!= a
->type
)
346 if (a
->protocol
!= 0) {
347 solen
= sizeof(b
.protocol
);
348 if (getsockopt(fd
, SOL_SOCKET
, SO_PROTOCOL
, &b
.protocol
, &solen
) < 0)
351 if (b
.protocol
!= a
->protocol
)
355 return socket_address_equal(a
, &b
);
358 int sockaddr_port(const struct sockaddr
*_sa
, unsigned *ret_port
) {
359 const union sockaddr_union
*sa
= (const union sockaddr_union
*) _sa
;
361 /* Note, this returns the port as 'unsigned' rather than 'uint16_t', as AF_VSOCK knows larger ports */
365 switch (sa
->sa
.sa_family
) {
368 *ret_port
= be16toh(sa
->in
.sin_port
);
372 *ret_port
= be16toh(sa
->in6
.sin6_port
);
376 *ret_port
= sa
->vm
.svm_port
;
380 return -EAFNOSUPPORT
;
384 const union in_addr_union
*sockaddr_in_addr(const struct sockaddr
*_sa
) {
385 const union sockaddr_union
*sa
= (const union sockaddr_union
*) _sa
;
390 switch (sa
->sa
.sa_family
) {
393 return (const union in_addr_union
*) &sa
->in
.sin_addr
;
396 return (const union in_addr_union
*) &sa
->in6
.sin6_addr
;
403 int sockaddr_set_in_addr(
404 union sockaddr_union
*u
,
406 const union in_addr_union
*a
,
415 u
->in
= (struct sockaddr_in
) {
416 .sin_family
= AF_INET
,
418 .sin_port
= htobe16(port
),
424 u
->in6
= (struct sockaddr_in6
) {
425 .sin6_family
= AF_INET6
,
427 .sin6_port
= htobe16(port
),
433 return -EAFNOSUPPORT
;
439 const struct sockaddr
*_sa
,
445 union sockaddr_union
*sa
= (union sockaddr_union
*) _sa
;
450 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(union sockaddr_union
*sa
, socklen_t salen
, char **_ret
) {
628 char host
[NI_MAXHOST
], *ret
;
632 r
= getnameinfo(&sa
->sa
, salen
, host
, sizeof(host
), NULL
, 0, IDN_FLAGS
);
634 int saved_errno
= errno
;
636 r
= sockaddr_pretty(&sa
->sa
, salen
, true, true, &ret
);
640 log_debug_errno(saved_errno
, "getnameinfo(%s) failed: %m", ret
);
651 static const char* const netlink_family_table
[] = {
652 [NETLINK_ROUTE
] = "route",
653 [NETLINK_FIREWALL
] = "firewall",
654 [NETLINK_INET_DIAG
] = "inet-diag",
655 [NETLINK_NFLOG
] = "nflog",
656 [NETLINK_XFRM
] = "xfrm",
657 [NETLINK_SELINUX
] = "selinux",
658 [NETLINK_ISCSI
] = "iscsi",
659 [NETLINK_AUDIT
] = "audit",
660 [NETLINK_FIB_LOOKUP
] = "fib-lookup",
661 [NETLINK_CONNECTOR
] = "connector",
662 [NETLINK_NETFILTER
] = "netfilter",
663 [NETLINK_IP6_FW
] = "ip6-fw",
664 [NETLINK_DNRTMSG
] = "dnrtmsg",
665 [NETLINK_KOBJECT_UEVENT
] = "kobject-uevent",
666 [NETLINK_GENERIC
] = "generic",
667 [NETLINK_SCSITRANSPORT
] = "scsitransport",
668 [NETLINK_ECRYPTFS
] = "ecryptfs",
669 [NETLINK_RDMA
] = "rdma",
672 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(netlink_family
, int, INT_MAX
);
674 static const char* const socket_address_bind_ipv6_only_table
[_SOCKET_ADDRESS_BIND_IPV6_ONLY_MAX
] = {
675 [SOCKET_ADDRESS_DEFAULT
] = "default",
676 [SOCKET_ADDRESS_BOTH
] = "both",
677 [SOCKET_ADDRESS_IPV6_ONLY
] = "ipv6-only"
680 DEFINE_STRING_TABLE_LOOKUP(socket_address_bind_ipv6_only
, SocketAddressBindIPv6Only
);
682 SocketAddressBindIPv6Only
socket_address_bind_ipv6_only_or_bool_from_string(const char *n
) {
685 r
= parse_boolean(n
);
687 return SOCKET_ADDRESS_IPV6_ONLY
;
689 return SOCKET_ADDRESS_BOTH
;
691 return socket_address_bind_ipv6_only_from_string(n
);
694 bool sockaddr_equal(const union sockaddr_union
*a
, const union sockaddr_union
*b
) {
698 if (a
->sa
.sa_family
!= b
->sa
.sa_family
)
701 if (a
->sa
.sa_family
== AF_INET
)
702 return a
->in
.sin_addr
.s_addr
== b
->in
.sin_addr
.s_addr
;
704 if (a
->sa
.sa_family
== AF_INET6
)
705 return memcmp(&a
->in6
.sin6_addr
, &b
->in6
.sin6_addr
, sizeof(a
->in6
.sin6_addr
)) == 0;
707 if (a
->sa
.sa_family
== AF_VSOCK
)
708 return a
->vm
.svm_cid
== b
->vm
.svm_cid
;
713 int fd_set_sndbuf(int fd
, size_t n
, bool increase
) {
715 socklen_t l
= sizeof(value
);
720 r
= getsockopt(fd
, SOL_SOCKET
, SO_SNDBUF
, &value
, &l
);
721 if (r
>= 0 && l
== sizeof(value
) && increase
? (size_t) value
>= n
*2 : (size_t) value
== n
*2)
724 /* First, try to set the buffer size with SO_SNDBUF. */
725 r
= setsockopt_int(fd
, SOL_SOCKET
, SO_SNDBUF
, n
);
729 /* SO_SNDBUF above may set to the kernel limit, instead of the requested size.
730 * So, we need to check the actual buffer size here. */
732 r
= getsockopt(fd
, SOL_SOCKET
, SO_SNDBUF
, &value
, &l
);
733 if (r
>= 0 && l
== sizeof(value
) && increase
? (size_t) value
>= n
*2 : (size_t) value
== n
*2)
736 /* If we have the privileges we will ignore the kernel limit. */
737 r
= setsockopt_int(fd
, SOL_SOCKET
, SO_SNDBUFFORCE
, n
);
744 int fd_set_rcvbuf(int fd
, size_t n
, bool increase
) {
746 socklen_t l
= sizeof(value
);
751 r
= getsockopt(fd
, SOL_SOCKET
, SO_RCVBUF
, &value
, &l
);
752 if (r
>= 0 && l
== sizeof(value
) && increase
? (size_t) value
>= n
*2 : (size_t) value
== n
*2)
755 /* First, try to set the buffer size with SO_RCVBUF. */
756 r
= setsockopt_int(fd
, SOL_SOCKET
, SO_RCVBUF
, n
);
760 /* SO_RCVBUF above may set to the kernel limit, instead of the requested size.
761 * So, we need to check the actual buffer size here. */
763 r
= getsockopt(fd
, SOL_SOCKET
, SO_RCVBUF
, &value
, &l
);
764 if (r
>= 0 && l
== sizeof(value
) && increase
? (size_t) value
>= n
*2 : (size_t) value
== n
*2)
767 /* If we have the privileges we will ignore the kernel limit. */
768 r
= setsockopt_int(fd
, SOL_SOCKET
, SO_RCVBUFFORCE
, n
);
775 static const char* const ip_tos_table
[] = {
776 [IPTOS_LOWDELAY
] = "low-delay",
777 [IPTOS_THROUGHPUT
] = "throughput",
778 [IPTOS_RELIABILITY
] = "reliability",
779 [IPTOS_LOWCOST
] = "low-cost",
782 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(ip_tos
, int, 0xff);
784 bool ifname_valid_char(char a
) {
785 if ((unsigned char) a
>= 127U)
788 if ((unsigned char) a
<= 32U)
792 ':', /* colons are used by the legacy "alias" interface logic */
793 '/', /* slashes cannot work, since we need to use network interfaces in sysfs paths, and in paths slashes are separators */
794 '%')) /* %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 */
800 bool ifname_valid_full(const char *p
, IfnameValidFlags flags
) {
803 /* Checks whether a network interface name is valid. This is inspired by dev_valid_name() in the kernel sources
804 * but slightly stricter, as we only allow non-control, non-space ASCII characters in the interface name. We
805 * also don't permit names that only container numbers, to avoid confusion with numeric interface indexes. */
807 assert(!(flags
& ~_IFNAME_VALID_ALL
));
812 /* A valid ifindex? If so, it's valid iff IFNAME_VALID_NUMERIC is set */
813 if (parse_ifindex(p
) >= 0)
814 return flags
& IFNAME_VALID_NUMERIC
;
816 if (flags
& IFNAME_VALID_ALTERNATIVE
) {
817 if (strlen(p
) >= ALTIFNAMSIZ
)
820 if (strlen(p
) >= IFNAMSIZ
)
824 if (dot_or_dot_dot(p
))
827 /* Let's refuse "all" and "default" as interface name, to avoid collisions with the special sysctl
828 * directories /proc/sys/net/{ipv4,ipv6}/conf/{all,default} */
829 if (!FLAGS_SET(flags
, IFNAME_VALID_SPECIAL
) && STR_IN_SET(p
, "all", "default"))
832 for (const char *t
= p
; *t
; t
++) {
833 if (!ifname_valid_char(*t
))
836 numeric
= numeric
&& ascii_isdigit(*t
);
839 /* It's fully numeric but didn't parse as valid ifindex above? if so, it must be too large or zero or
840 * so, let's refuse that. */
847 bool address_label_valid(const char *p
) {
852 if (strlen(p
) >= IFNAMSIZ
)
856 if ((uint8_t) *p
>= 127U)
859 if ((uint8_t) *p
<= 31U)
867 int getpeercred(int fd
, struct ucred
*ucred
) {
868 socklen_t n
= sizeof(struct ucred
);
875 r
= getsockopt(fd
, SOL_SOCKET
, SO_PEERCRED
, &u
, &n
);
879 if (n
!= sizeof(struct ucred
))
882 /* Check if the data is actually useful and not suppressed due to namespacing issues */
883 if (!pid_is_valid(u
.pid
))
886 /* Note that we don't check UID/GID here, as namespace translation works differently there: instead of
887 * receiving in "invalid" user/group we get the overflow UID/GID. */
893 int getpeersec(int fd
, char **ret
) {
894 _cleanup_free_
char *s
= NULL
;
905 if (getsockopt(fd
, SOL_SOCKET
, SO_PEERSEC
, s
, &n
) >= 0)
922 int getpeergroups(int fd
, gid_t
**ret
) {
923 socklen_t n
= sizeof(gid_t
) * 64;
924 _cleanup_free_ gid_t
*d
= NULL
;
934 if (getsockopt(fd
, SOL_SOCKET
, SO_PEERGROUPS
, d
, &n
) >= 0)
943 assert_se(n
% sizeof(gid_t
) == 0);
946 if ((socklen_t
) (int) n
!= n
)
954 ssize_t
send_one_fd_iov_sa(
957 const struct iovec
*iov
, size_t iovlen
,
958 const struct sockaddr
*sa
, socklen_t len
,
961 CMSG_BUFFER_TYPE(CMSG_SPACE(sizeof(int))) control
= {};
963 .msg_name
= (struct sockaddr
*) sa
,
965 .msg_iov
= (struct iovec
*)iov
,
966 .msg_iovlen
= iovlen
,
970 assert(transport_fd
>= 0);
973 * We need either an FD or data to send.
974 * If there's nothing, return an error.
980 struct cmsghdr
*cmsg
;
982 mh
.msg_control
= &control
;
983 mh
.msg_controllen
= sizeof(control
);
985 cmsg
= CMSG_FIRSTHDR(&mh
);
986 cmsg
->cmsg_level
= SOL_SOCKET
;
987 cmsg
->cmsg_type
= SCM_RIGHTS
;
988 cmsg
->cmsg_len
= CMSG_LEN(sizeof(int));
989 memcpy(CMSG_DATA(cmsg
), &fd
, sizeof(int));
991 k
= sendmsg(transport_fd
, &mh
, MSG_NOSIGNAL
| flags
);
993 return (ssize_t
) -errno
;
1001 const struct sockaddr
*sa
, socklen_t len
,
1006 return (int) send_one_fd_iov_sa(transport_fd
, fd
, NULL
, 0, sa
, len
, flags
);
1009 ssize_t
receive_one_fd_iov(
1011 struct iovec
*iov
, size_t iovlen
,
1015 CMSG_BUFFER_TYPE(CMSG_SPACE(sizeof(int))) control
;
1016 struct msghdr mh
= {
1017 .msg_control
= &control
,
1018 .msg_controllen
= sizeof(control
),
1020 .msg_iovlen
= iovlen
,
1022 struct cmsghdr
*found
;
1025 assert(transport_fd
>= 0);
1029 * Receive a single FD via @transport_fd. We don't care for
1030 * the transport-type. We retrieve a single FD at most, so for
1031 * packet-based transports, the caller must ensure to send
1032 * only a single FD per packet. This is best used in
1033 * combination with send_one_fd().
1036 k
= recvmsg_safe(transport_fd
, &mh
, MSG_CMSG_CLOEXEC
| flags
);
1040 found
= cmsg_find(&mh
, SOL_SOCKET
, SCM_RIGHTS
, CMSG_LEN(sizeof(int)));
1042 cmsg_close_all(&mh
);
1044 /* If didn't receive an FD or any data, return an error. */
1050 *ret_fd
= *(int*) CMSG_DATA(found
);
1057 int receive_one_fd(int transport_fd
, int flags
) {
1061 k
= receive_one_fd_iov(transport_fd
, NULL
, 0, flags
, &fd
);
1065 /* k must be negative, since receive_one_fd_iov() only returns
1066 * a positive value if data was received through the iov. */
1071 ssize_t
next_datagram_size_fd(int fd
) {
1075 /* This is a bit like FIONREAD/SIOCINQ, however a bit more powerful. The difference being: recv(MSG_PEEK) will
1076 * actually cause the next datagram in the queue to be validated regarding checksums, which FIONREAD doesn't
1077 * do. This difference is actually of major importance as we need to be sure that the size returned here
1078 * actually matches what we will read with recvmsg() next, as otherwise we might end up allocating a buffer of
1079 * the wrong size. */
1081 l
= recv(fd
, NULL
, 0, MSG_PEEK
|MSG_TRUNC
);
1083 if (IN_SET(errno
, EOPNOTSUPP
, EFAULT
))
1096 /* Some sockets (AF_PACKET) do not support null-sized recv() with MSG_TRUNC set, let's fall back to FIONREAD
1097 * for them. Checksums don't matter for raw sockets anyway, hence this should be fine. */
1099 if (ioctl(fd
, FIONREAD
, &k
) < 0)
1105 /* Put a limit on how many times will attempt to call accept4(). We loop
1106 * only on "transient" errors, but let's make sure we don't loop forever. */
1107 #define MAX_FLUSH_ITERATIONS 1024
1109 int flush_accept(int fd
) {
1112 socklen_t l
= sizeof(b
);
1114 /* Similar to flush_fd() but flushes all incoming connections by accepting and immediately closing
1117 if (getsockopt(fd
, SOL_SOCKET
, SO_ACCEPTCONN
, &b
, &l
) < 0)
1120 assert(l
== sizeof(b
));
1121 if (!b
) /* Let's check if this socket accepts connections before calling accept(). accept4() can
1122 * return EOPNOTSUPP if the fd is not a listening socket, which we should treat as a fatal
1123 * error, or in case the incoming TCP connection triggered a network issue, which we want to
1124 * treat as a transient error. Thus, let's rule out the first reason for EOPNOTSUPP early, so
1125 * we can loop safely on transient errors below. */
1128 for (unsigned iteration
= 0;; iteration
++) {
1131 r
= fd_wait_for_event(fd
, POLLIN
, 0);
1141 if (iteration
>= MAX_FLUSH_ITERATIONS
)
1142 return log_debug_errno(SYNTHETIC_ERRNO(EBUSY
),
1143 "Failed to flush connections within " STRINGIFY(MAX_FLUSH_ITERATIONS
) " iterations.");
1145 cfd
= accept4(fd
, NULL
, NULL
, SOCK_NONBLOCK
|SOCK_CLOEXEC
);
1147 if (errno
== EAGAIN
)
1150 if (ERRNO_IS_ACCEPT_AGAIN(errno
))
1160 struct cmsghdr
* cmsg_find(struct msghdr
*mh
, int level
, int type
, socklen_t length
) {
1161 struct cmsghdr
*cmsg
;
1165 CMSG_FOREACH(cmsg
, mh
)
1166 if (cmsg
->cmsg_level
== level
&&
1167 cmsg
->cmsg_type
== type
&&
1168 (length
== (socklen_t
) -1 || length
== cmsg
->cmsg_len
))
1174 int socket_ioctl_fd(void) {
1177 /* Create a socket to invoke the various network interface ioctl()s on. Traditionally only AF_INET was good for
1178 * that. Since kernel 4.6 AF_NETLINK works for this too. We first try to use AF_INET hence, but if that's not
1179 * available (for example, because it is made unavailable via SECCOMP or such), we'll fall back to the more
1180 * generic AF_NETLINK. */
1182 fd
= socket(AF_INET
, SOCK_DGRAM
|SOCK_CLOEXEC
, 0);
1184 fd
= socket(AF_NETLINK
, SOCK_RAW
|SOCK_CLOEXEC
, NETLINK_GENERIC
);
1191 int sockaddr_un_unlink(const struct sockaddr_un
*sa
) {
1192 const char *p
, * nul
;
1196 if (sa
->sun_family
!= AF_UNIX
)
1199 if (sa
->sun_path
[0] == 0) /* Nothing to do for abstract sockets */
1202 /* The path in .sun_path is not necessarily NUL terminated. Let's fix that. */
1203 nul
= memchr(sa
->sun_path
, 0, sizeof(sa
->sun_path
));
1207 p
= memdupa_suffix0(sa
->sun_path
, sizeof(sa
->sun_path
));
1215 int sockaddr_un_set_path(struct sockaddr_un
*ret
, const char *path
) {
1221 /* Initialize ret->sun_path from the specified argument. This will interpret paths starting with '@' as
1222 * abstract namespace sockets, and those starting with '/' as regular filesystem sockets. It won't accept
1223 * anything else (i.e. no relative paths), to avoid ambiguities. Note that this function cannot be used to
1224 * reference paths in the abstract namespace that include NUL bytes in the name. */
1229 if (!IN_SET(path
[0], '/', '@'))
1232 /* Don't allow paths larger than the space in sockaddr_un. Note that we are a tiny bit more restrictive than
1233 * the kernel is: we insist on NUL termination (both for abstract namespace and regular file system socket
1234 * addresses!), which the kernel doesn't. We do this to reduce chance of incompatibility with other apps that
1235 * do not expect non-NUL terminated file system path. */
1236 if (l
+1 > sizeof(ret
->sun_path
))
1237 return path
[0] == '@' ? -EINVAL
: -ENAMETOOLONG
; /* return a recognizable error if this is
1238 * too long to fit into a sockaddr_un, but
1239 * is a file system path, and thus might be
1240 * connectible via O_PATH indirection. */
1242 *ret
= (struct sockaddr_un
) {
1243 .sun_family
= AF_UNIX
,
1246 if (path
[0] == '@') {
1247 /* Abstract namespace socket */
1248 memcpy(ret
->sun_path
+ 1, path
+ 1, l
); /* copy *with* trailing NUL byte */
1249 return (int) (offsetof(struct sockaddr_un
, sun_path
) + l
); /* 🔥 *don't* 🔥 include trailing NUL in size */
1252 assert(path
[0] == '/');
1254 /* File system socket */
1255 memcpy(ret
->sun_path
, path
, l
+ 1); /* copy *with* trailing NUL byte */
1256 return (int) (offsetof(struct sockaddr_un
, sun_path
) + l
+ 1); /* include trailing NUL in size */
1260 int socket_bind_to_ifname(int fd
, const char *ifname
) {
1263 /* Call with NULL to drop binding */
1265 return RET_NERRNO(setsockopt(fd
, SOL_SOCKET
, SO_BINDTODEVICE
, ifname
, strlen_ptr(ifname
)));
1268 int socket_bind_to_ifindex(int fd
, int ifindex
) {
1269 char ifname
[IF_NAMESIZE
];
1276 return RET_NERRNO(setsockopt(fd
, SOL_SOCKET
, SO_BINDTODEVICE
, NULL
, 0));
1278 r
= setsockopt_int(fd
, SOL_SOCKET
, SO_BINDTOIFINDEX
, ifindex
);
1279 if (r
!= -ENOPROTOOPT
)
1282 /* Fall back to SO_BINDTODEVICE on kernels < 5.0 which didn't have SO_BINDTOIFINDEX */
1283 r
= format_ifname(ifindex
, ifname
);
1287 return socket_bind_to_ifname(fd
, ifname
);
1290 ssize_t
recvmsg_safe(int sockfd
, struct msghdr
*msg
, int flags
) {
1293 /* A wrapper around recvmsg() that checks for MSG_CTRUNC, and turns it into an error, in a reasonably
1294 * safe way, closing any SCM_RIGHTS fds in the error path.
1296 * Note that unlike our usual coding style this might modify *msg on failure. */
1298 n
= recvmsg(sockfd
, msg
, flags
);
1302 if (FLAGS_SET(msg
->msg_flags
, MSG_CTRUNC
)) {
1303 cmsg_close_all(msg
);
1304 return -EXFULL
; /* a recognizable error code */
1310 int socket_get_family(int fd
, int *ret
) {
1312 socklen_t sl
= sizeof(af
);
1314 if (getsockopt(fd
, SOL_SOCKET
, SO_DOMAIN
, &af
, &sl
) < 0)
1317 if (sl
!= sizeof(af
))
1323 int socket_set_recvpktinfo(int fd
, int af
, bool b
) {
1326 if (af
== AF_UNSPEC
) {
1327 r
= socket_get_family(fd
, &af
);
1335 return setsockopt_int(fd
, IPPROTO_IP
, IP_PKTINFO
, b
);
1338 return setsockopt_int(fd
, IPPROTO_IPV6
, IPV6_RECVPKTINFO
, b
);
1341 return setsockopt_int(fd
, SOL_NETLINK
, NETLINK_PKTINFO
, b
);
1344 return setsockopt_int(fd
, SOL_PACKET
, PACKET_AUXDATA
, b
);
1347 return -EAFNOSUPPORT
;
1351 int socket_set_unicast_if(int fd
, int af
, int ifi
) {
1352 be32_t ifindex_be
= htobe32(ifi
);
1355 if (af
== AF_UNSPEC
) {
1356 r
= socket_get_family(fd
, &af
);
1364 return RET_NERRNO(setsockopt(fd
, IPPROTO_IP
, IP_UNICAST_IF
, &ifindex_be
, sizeof(ifindex_be
)));
1367 return RET_NERRNO(setsockopt(fd
, IPPROTO_IPV6
, IPV6_UNICAST_IF
, &ifindex_be
, sizeof(ifindex_be
)));
1370 return -EAFNOSUPPORT
;
1374 int socket_set_option(int fd
, int af
, int opt_ipv4
, int opt_ipv6
, int val
) {
1377 if (af
== AF_UNSPEC
) {
1378 r
= socket_get_family(fd
, &af
);
1386 return setsockopt_int(fd
, IPPROTO_IP
, opt_ipv4
, val
);
1389 return setsockopt_int(fd
, IPPROTO_IPV6
, opt_ipv6
, val
);
1392 return -EAFNOSUPPORT
;
1396 int socket_get_mtu(int fd
, int af
, size_t *ret
) {
1399 if (af
== AF_UNSPEC
) {
1400 r
= socket_get_family(fd
, &af
);
1408 r
= getsockopt_int(fd
, IPPROTO_IP
, IP_MTU
, &mtu
);
1412 r
= getsockopt_int(fd
, IPPROTO_IPV6
, IPV6_MTU
, &mtu
);
1416 return -EAFNOSUPPORT
;
1424 *ret
= (size_t) mtu
;
1428 int connect_unix_path(int fd
, int dir_fd
, const char *path
) {
1429 _cleanup_close_
int inode_fd
= -1;
1430 union sockaddr_union sa
= {
1431 .un
.sun_family
= AF_UNIX
,
1437 assert(dir_fd
== AT_FDCWD
|| dir_fd
>= 0);
1440 /* Connects to the specified AF_UNIX socket in the file system. Works around the 108 byte size limit
1441 * in sockaddr_un, by going via O_PATH if needed. This hence works for any kind of path. */
1443 path_len
= strlen(path
);
1445 /* Refuse zero length path early, to make sure AF_UNIX stack won't mistake this for an abstract
1446 * namespace path, since first char is NUL */
1450 if (dir_fd
== AT_FDCWD
&& path_len
< sizeof(sa
.un
.sun_path
)) {
1451 memcpy(sa
.un
.sun_path
, path
, path_len
+ 1);
1452 salen
= offsetof(struct sockaddr_un
, sun_path
) + path_len
+ 1;
1457 /* If dir_fd is specified, then we need to go the indirect O_PATH route, because connectat()
1458 * does not exist. If the path is too long, we also need to take the indirect route, since we
1459 * can't fit this into a sockaddr_un directly. */
1461 inode_fd
= openat(dir_fd
, path
, O_PATH
|O_CLOEXEC
);
1465 proc
= FORMAT_PROC_FD_PATH(inode_fd
);
1466 proc_len
= strlen(proc
);
1468 assert(proc_len
< sizeof(sa
.un
.sun_path
));
1469 memcpy(sa
.un
.sun_path
, proc
, proc_len
+ 1);
1470 salen
= offsetof(struct sockaddr_un
, sun_path
) + proc_len
+ 1;
1473 return RET_NERRNO(connect(fd
, &sa
.sa
, salen
));