1 /* SPDX-License-Identifier: LGPL-2.1+ */
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 "missing_socket.h"
28 #include "parse-util.h"
29 #include "path-util.h"
30 #include "process-util.h"
31 #include "socket-util.h"
32 #include "string-table.h"
33 #include "string-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
, 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
, 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 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
, SOCK_STREAM
, SOCK_DGRAM
, SOCK_SEQPACKET
))
123 if (a
->size
!= sizeof(struct sockaddr_nl
))
126 if (!IN_SET(a
->type
, SOCK_RAW
, SOCK_DGRAM
))
132 if (a
->size
!= sizeof(struct sockaddr_vm
))
135 if (!IN_SET(a
->type
, 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 if (access("/proc/net/if_inet6", F_OK
) != 0)
287 bool socket_address_matches_fd(const SocketAddress
*a
, int fd
) {
294 b
.size
= sizeof(b
.sockaddr
);
295 if (getsockname(fd
, &b
.sockaddr
.sa
, &b
.size
) < 0)
298 if (b
.sockaddr
.sa
.sa_family
!= a
->sockaddr
.sa
.sa_family
)
301 solen
= sizeof(b
.type
);
302 if (getsockopt(fd
, SOL_SOCKET
, SO_TYPE
, &b
.type
, &solen
) < 0)
305 if (b
.type
!= a
->type
)
308 if (a
->protocol
!= 0) {
309 solen
= sizeof(b
.protocol
);
310 if (getsockopt(fd
, SOL_SOCKET
, SO_PROTOCOL
, &b
.protocol
, &solen
) < 0)
313 if (b
.protocol
!= a
->protocol
)
317 return socket_address_equal(a
, &b
);
320 int sockaddr_port(const struct sockaddr
*_sa
, unsigned *ret_port
) {
321 union sockaddr_union
*sa
= (union sockaddr_union
*) _sa
;
323 /* Note, this returns the port as 'unsigned' rather than 'uint16_t', as AF_VSOCK knows larger ports */
327 switch (sa
->sa
.sa_family
) {
330 *ret_port
= be16toh(sa
->in
.sin_port
);
334 *ret_port
= be16toh(sa
->in6
.sin6_port
);
338 *ret_port
= sa
->vm
.svm_port
;
342 return -EAFNOSUPPORT
;
347 const struct sockaddr
*_sa
,
353 union sockaddr_union
*sa
= (union sockaddr_union
*) _sa
;
358 assert(salen
>= sizeof(sa
->sa
.sa_family
));
360 switch (sa
->sa
.sa_family
) {
365 a
= be32toh(sa
->in
.sin_addr
.s_addr
);
370 a
>> 24, (a
>> 16) & 0xFF, (a
>> 8) & 0xFF, a
& 0xFF,
371 be16toh(sa
->in
.sin_port
));
375 a
>> 24, (a
>> 16) & 0xFF, (a
>> 8) & 0xFF, a
& 0xFF);
382 static const unsigned char ipv4_prefix
[] = {
383 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xFF, 0xFF
386 if (translate_ipv6
&&
387 memcmp(&sa
->in6
.sin6_addr
, ipv4_prefix
, sizeof(ipv4_prefix
)) == 0) {
388 const uint8_t *a
= sa
->in6
.sin6_addr
.s6_addr
+12;
392 a
[0], a
[1], a
[2], a
[3],
393 be16toh(sa
->in6
.sin6_port
));
397 a
[0], a
[1], a
[2], a
[3]);
401 char a
[INET6_ADDRSTRLEN
];
403 inet_ntop(AF_INET6
, &sa
->in6
.sin6_addr
, a
, sizeof(a
));
409 be16toh(sa
->in6
.sin6_port
));
423 if (salen
<= offsetof(struct sockaddr_un
, sun_path
) ||
424 (sa
->un
.sun_path
[0] == 0 && salen
== offsetof(struct sockaddr_un
, sun_path
) + 1))
425 /* The name must have at least one character (and the leading NUL does not count) */
426 p
= strdup("<unnamed>");
428 /* Note that we calculate the path pointer here through the .un_buffer[] field, in order to
429 * outtrick bounds checking tools such as ubsan, which are too smart for their own good: on
430 * Linux the kernel may return sun_path[] data one byte longer than the declared size of the
432 char *path
= (char*) sa
->un_buffer
+ offsetof(struct sockaddr_un
, sun_path
);
433 size_t path_len
= salen
- offsetof(struct sockaddr_un
, sun_path
);
436 /* Abstract socket. When parsing address information from, we
437 * explicitly reject overly long paths and paths with embedded NULs.
438 * But we might get such a socket from the outside. Let's return
439 * something meaningful and printable in this case. */
441 _cleanup_free_
char *e
= NULL
;
443 e
= cescape_length(path
+ 1, path_len
- 1);
449 if (path
[path_len
- 1] == '\0')
450 /* We expect a terminating NUL and don't print it */
453 p
= cescape_length(path
, path_len
);
463 if (sa
->vm
.svm_cid
== VMADDR_CID_ANY
)
464 r
= asprintf(&p
, "vsock::%u", sa
->vm
.svm_port
);
466 r
= asprintf(&p
, "vsock:%u:%u", sa
->vm
.svm_cid
, sa
->vm
.svm_port
);
468 r
= asprintf(&p
, "vsock:%u", sa
->vm
.svm_cid
);
481 int getpeername_pretty(int fd
, bool include_port
, char **ret
) {
482 union sockaddr_union sa
;
483 socklen_t salen
= sizeof(sa
);
489 if (getpeername(fd
, &sa
.sa
, &salen
) < 0)
492 if (sa
.sa
.sa_family
== AF_UNIX
) {
493 struct ucred ucred
= {};
495 /* UNIX connection sockets are anonymous, so let's use
496 * PID/UID as pretty credentials instead */
498 r
= getpeercred(fd
, &ucred
);
502 if (asprintf(ret
, "PID "PID_FMT
"/UID "UID_FMT
, ucred
.pid
, ucred
.uid
) < 0)
508 /* For remote sockets we translate IPv6 addresses back to IPv4
509 * if applicable, since that's nicer. */
511 return sockaddr_pretty(&sa
.sa
, salen
, true, include_port
, ret
);
514 int getsockname_pretty(int fd
, char **ret
) {
515 union sockaddr_union sa
;
516 socklen_t salen
= sizeof(sa
);
521 if (getsockname(fd
, &sa
.sa
, &salen
) < 0)
524 /* For local sockets we do not translate IPv6 addresses back
525 * to IPv6 if applicable, since this is usually used for
526 * listening sockets where the difference between IPv4 and
529 return sockaddr_pretty(&sa
.sa
, salen
, false, true, ret
);
532 int socknameinfo_pretty(union sockaddr_union
*sa
, socklen_t salen
, char **_ret
) {
534 char host
[NI_MAXHOST
], *ret
;
538 r
= getnameinfo(&sa
->sa
, salen
, host
, sizeof(host
), NULL
, 0, IDN_FLAGS
);
540 int saved_errno
= errno
;
542 r
= sockaddr_pretty(&sa
->sa
, salen
, true, true, &ret
);
546 log_debug_errno(saved_errno
, "getnameinfo(%s) failed: %m", ret
);
557 static const char* const netlink_family_table
[] = {
558 [NETLINK_ROUTE
] = "route",
559 [NETLINK_FIREWALL
] = "firewall",
560 [NETLINK_INET_DIAG
] = "inet-diag",
561 [NETLINK_NFLOG
] = "nflog",
562 [NETLINK_XFRM
] = "xfrm",
563 [NETLINK_SELINUX
] = "selinux",
564 [NETLINK_ISCSI
] = "iscsi",
565 [NETLINK_AUDIT
] = "audit",
566 [NETLINK_FIB_LOOKUP
] = "fib-lookup",
567 [NETLINK_CONNECTOR
] = "connector",
568 [NETLINK_NETFILTER
] = "netfilter",
569 [NETLINK_IP6_FW
] = "ip6-fw",
570 [NETLINK_DNRTMSG
] = "dnrtmsg",
571 [NETLINK_KOBJECT_UEVENT
] = "kobject-uevent",
572 [NETLINK_GENERIC
] = "generic",
573 [NETLINK_SCSITRANSPORT
] = "scsitransport",
574 [NETLINK_ECRYPTFS
] = "ecryptfs",
575 [NETLINK_RDMA
] = "rdma",
578 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(netlink_family
, int, INT_MAX
);
580 static const char* const socket_address_bind_ipv6_only_table
[_SOCKET_ADDRESS_BIND_IPV6_ONLY_MAX
] = {
581 [SOCKET_ADDRESS_DEFAULT
] = "default",
582 [SOCKET_ADDRESS_BOTH
] = "both",
583 [SOCKET_ADDRESS_IPV6_ONLY
] = "ipv6-only"
586 DEFINE_STRING_TABLE_LOOKUP(socket_address_bind_ipv6_only
, SocketAddressBindIPv6Only
);
588 SocketAddressBindIPv6Only
socket_address_bind_ipv6_only_or_bool_from_string(const char *n
) {
591 r
= parse_boolean(n
);
593 return SOCKET_ADDRESS_IPV6_ONLY
;
595 return SOCKET_ADDRESS_BOTH
;
597 return socket_address_bind_ipv6_only_from_string(n
);
600 bool sockaddr_equal(const union sockaddr_union
*a
, const union sockaddr_union
*b
) {
604 if (a
->sa
.sa_family
!= b
->sa
.sa_family
)
607 if (a
->sa
.sa_family
== AF_INET
)
608 return a
->in
.sin_addr
.s_addr
== b
->in
.sin_addr
.s_addr
;
610 if (a
->sa
.sa_family
== AF_INET6
)
611 return memcmp(&a
->in6
.sin6_addr
, &b
->in6
.sin6_addr
, sizeof(a
->in6
.sin6_addr
)) == 0;
613 if (a
->sa
.sa_family
== AF_VSOCK
)
614 return a
->vm
.svm_cid
== b
->vm
.svm_cid
;
619 int fd_inc_sndbuf(int fd
, size_t n
) {
621 socklen_t l
= sizeof(value
);
623 r
= getsockopt(fd
, SOL_SOCKET
, SO_SNDBUF
, &value
, &l
);
624 if (r
>= 0 && l
== sizeof(value
) && (size_t) value
>= n
*2)
627 /* If we have the privileges we will ignore the kernel limit. */
629 if (setsockopt_int(fd
, SOL_SOCKET
, SO_SNDBUF
, n
) < 0) {
630 r
= setsockopt_int(fd
, SOL_SOCKET
, SO_SNDBUFFORCE
, n
);
638 int fd_inc_rcvbuf(int fd
, size_t n
) {
640 socklen_t l
= sizeof(value
);
642 r
= getsockopt(fd
, SOL_SOCKET
, SO_RCVBUF
, &value
, &l
);
643 if (r
>= 0 && l
== sizeof(value
) && (size_t) value
>= n
*2)
646 /* If we have the privileges we will ignore the kernel limit. */
648 if (setsockopt_int(fd
, SOL_SOCKET
, SO_RCVBUF
, n
) < 0) {
649 r
= setsockopt_int(fd
, SOL_SOCKET
, SO_RCVBUFFORCE
, n
);
657 static const char* const ip_tos_table
[] = {
658 [IPTOS_LOWDELAY
] = "low-delay",
659 [IPTOS_THROUGHPUT
] = "throughput",
660 [IPTOS_RELIABILITY
] = "reliability",
661 [IPTOS_LOWCOST
] = "low-cost",
664 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(ip_tos
, int, 0xff);
666 bool ifname_valid_full(const char *p
, bool alternative
) {
669 /* Checks whether a network interface name is valid. This is inspired by dev_valid_name() in the kernel sources
670 * but slightly stricter, as we only allow non-control, non-space ASCII characters in the interface name. We
671 * also don't permit names that only container numbers, to avoid confusion with numeric interface indexes. */
677 if (strlen(p
) >= ALTIFNAMSIZ
)
680 if (strlen(p
) >= IFNAMSIZ
)
684 if (dot_or_dot_dot(p
))
688 if ((unsigned char) *p
>= 127U)
691 if ((unsigned char) *p
<= 32U)
694 if (IN_SET(*p
, ':', '/'))
697 numeric
= numeric
&& (*p
>= '0' && *p
<= '9');
707 bool address_label_valid(const char *p
) {
712 if (strlen(p
) >= IFNAMSIZ
)
716 if ((uint8_t) *p
>= 127U)
719 if ((uint8_t) *p
<= 31U)
727 int getpeercred(int fd
, struct ucred
*ucred
) {
728 socklen_t n
= sizeof(struct ucred
);
735 r
= getsockopt(fd
, SOL_SOCKET
, SO_PEERCRED
, &u
, &n
);
739 if (n
!= sizeof(struct ucred
))
742 /* Check if the data is actually useful and not suppressed due to namespacing issues */
743 if (!pid_is_valid(u
.pid
))
746 /* Note that we don't check UID/GID here, as namespace translation works differently there: instead of
747 * receiving in "invalid" user/group we get the overflow UID/GID. */
753 int getpeersec(int fd
, char **ret
) {
754 _cleanup_free_
char *s
= NULL
;
765 if (getsockopt(fd
, SOL_SOCKET
, SO_PEERSEC
, s
, &n
) >= 0)
782 int getpeergroups(int fd
, gid_t
**ret
) {
783 socklen_t n
= sizeof(gid_t
) * 64;
784 _cleanup_free_ gid_t
*d
= NULL
;
794 if (getsockopt(fd
, SOL_SOCKET
, SO_PEERGROUPS
, d
, &n
) >= 0)
803 assert_se(n
% sizeof(gid_t
) == 0);
806 if ((socklen_t
) (int) n
!= n
)
814 ssize_t
send_one_fd_iov_sa(
817 struct iovec
*iov
, size_t iovlen
,
818 const struct sockaddr
*sa
, socklen_t len
,
821 CMSG_BUFFER_TYPE(CMSG_SPACE(sizeof(int))) control
= {};
823 .msg_name
= (struct sockaddr
*) sa
,
826 .msg_iovlen
= iovlen
,
830 assert(transport_fd
>= 0);
833 * We need either an FD or data to send.
834 * If there's nothing, return an error.
840 struct cmsghdr
*cmsg
;
842 mh
.msg_control
= &control
;
843 mh
.msg_controllen
= sizeof(control
);
845 cmsg
= CMSG_FIRSTHDR(&mh
);
846 cmsg
->cmsg_level
= SOL_SOCKET
;
847 cmsg
->cmsg_type
= SCM_RIGHTS
;
848 cmsg
->cmsg_len
= CMSG_LEN(sizeof(int));
849 memcpy(CMSG_DATA(cmsg
), &fd
, sizeof(int));
851 k
= sendmsg(transport_fd
, &mh
, MSG_NOSIGNAL
| flags
);
853 return (ssize_t
) -errno
;
861 const struct sockaddr
*sa
, socklen_t len
,
866 return (int) send_one_fd_iov_sa(transport_fd
, fd
, NULL
, 0, sa
, len
, flags
);
869 ssize_t
receive_one_fd_iov(
871 struct iovec
*iov
, size_t iovlen
,
875 CMSG_BUFFER_TYPE(CMSG_SPACE(sizeof(int))) control
;
877 .msg_control
= &control
,
878 .msg_controllen
= sizeof(control
),
880 .msg_iovlen
= iovlen
,
882 struct cmsghdr
*found
;
885 assert(transport_fd
>= 0);
889 * Receive a single FD via @transport_fd. We don't care for
890 * the transport-type. We retrieve a single FD at most, so for
891 * packet-based transports, the caller must ensure to send
892 * only a single FD per packet. This is best used in
893 * combination with send_one_fd().
896 k
= recvmsg_safe(transport_fd
, &mh
, MSG_CMSG_CLOEXEC
| flags
);
900 found
= cmsg_find(&mh
, SOL_SOCKET
, SCM_RIGHTS
, CMSG_LEN(sizeof(int)));
904 /* If didn't receive an FD or any data, return an error. */
910 *ret_fd
= *(int*) CMSG_DATA(found
);
917 int receive_one_fd(int transport_fd
, int flags
) {
921 k
= receive_one_fd_iov(transport_fd
, NULL
, 0, flags
, &fd
);
925 /* k must be negative, since receive_one_fd_iov() only returns
926 * a positive value if data was received through the iov. */
931 ssize_t
next_datagram_size_fd(int fd
) {
935 /* This is a bit like FIONREAD/SIOCINQ, however a bit more powerful. The difference being: recv(MSG_PEEK) will
936 * actually cause the next datagram in the queue to be validated regarding checksums, which FIONREAD doesn't
937 * do. This difference is actually of major importance as we need to be sure that the size returned here
938 * actually matches what we will read with recvmsg() next, as otherwise we might end up allocating a buffer of
941 l
= recv(fd
, NULL
, 0, MSG_PEEK
|MSG_TRUNC
);
943 if (IN_SET(errno
, EOPNOTSUPP
, EFAULT
))
956 /* Some sockets (AF_PACKET) do not support null-sized recv() with MSG_TRUNC set, let's fall back to FIONREAD
957 * for them. Checksums don't matter for raw sockets anyway, hence this should be fine. */
959 if (ioctl(fd
, FIONREAD
, &k
) < 0)
965 /* Put a limit on how many times will attempt to call accept4(). We loop
966 * only on "transient" errors, but let's make sure we don't loop forever. */
967 #define MAX_FLUSH_ITERATIONS 1024
969 int flush_accept(int fd
) {
971 struct pollfd pollfd
= {
976 socklen_t l
= sizeof(b
);
978 /* Similar to flush_fd() but flushes all incoming connections by accepting and immediately closing
981 if (getsockopt(fd
, SOL_SOCKET
, SO_ACCEPTCONN
, &b
, &l
) < 0)
984 assert(l
== sizeof(b
));
985 if (!b
) /* Let's check if this socket accepts connections before calling accept(). accept4() can
986 * return EOPNOTSUPP if the fd is not a listening socket, which we should treat as a fatal
987 * error, or in case the incoming TCP connection triggered a network issue, which we want to
988 * treat as a transient error. Thus, let's rule out the first reason for EOPNOTSUPP early, so
989 * we can loop safely on transient errors below. */
992 for (unsigned iteration
= 0;; iteration
++) {
995 r
= poll(&pollfd
, 1, 0);
1005 if (iteration
>= MAX_FLUSH_ITERATIONS
)
1006 return log_debug_errno(SYNTHETIC_ERRNO(EBUSY
),
1007 "Failed to flush connections within " STRINGIFY(MAX_FLUSH_ITERATIONS
) " iterations.");
1009 cfd
= accept4(fd
, NULL
, NULL
, SOCK_NONBLOCK
|SOCK_CLOEXEC
);
1011 if (errno
== EAGAIN
)
1014 if (ERRNO_IS_ACCEPT_AGAIN(errno
))
1024 struct cmsghdr
* cmsg_find(struct msghdr
*mh
, int level
, int type
, socklen_t length
) {
1025 struct cmsghdr
*cmsg
;
1029 CMSG_FOREACH(cmsg
, mh
)
1030 if (cmsg
->cmsg_level
== level
&&
1031 cmsg
->cmsg_type
== type
&&
1032 (length
== (socklen_t
) -1 || length
== cmsg
->cmsg_len
))
1038 int socket_ioctl_fd(void) {
1041 /* Create a socket to invoke the various network interface ioctl()s on. Traditionally only AF_INET was good for
1042 * that. Since kernel 4.6 AF_NETLINK works for this too. We first try to use AF_INET hence, but if that's not
1043 * available (for example, because it is made unavailable via SECCOMP or such), we'll fall back to the more
1044 * generic AF_NETLINK. */
1046 fd
= socket(AF_INET
, SOCK_DGRAM
|SOCK_CLOEXEC
, 0);
1048 fd
= socket(AF_NETLINK
, SOCK_RAW
|SOCK_CLOEXEC
, NETLINK_GENERIC
);
1055 int sockaddr_un_unlink(const struct sockaddr_un
*sa
) {
1056 const char *p
, * nul
;
1060 if (sa
->sun_family
!= AF_UNIX
)
1063 if (sa
->sun_path
[0] == 0) /* Nothing to do for abstract sockets */
1066 /* The path in .sun_path is not necessarily NUL terminated. Let's fix that. */
1067 nul
= memchr(sa
->sun_path
, 0, sizeof(sa
->sun_path
));
1071 p
= memdupa_suffix0(sa
->sun_path
, sizeof(sa
->sun_path
));
1079 int sockaddr_un_set_path(struct sockaddr_un
*ret
, const char *path
) {
1085 /* Initialize ret->sun_path from the specified argument. This will interpret paths starting with '@' as
1086 * abstract namespace sockets, and those starting with '/' as regular filesystem sockets. It won't accept
1087 * anything else (i.e. no relative paths), to avoid ambiguities. Note that this function cannot be used to
1088 * reference paths in the abstract namespace that include NUL bytes in the name. */
1093 if (!IN_SET(path
[0], '/', '@'))
1098 /* Don't allow paths larger than the space in sockaddr_un. Note that we are a tiny bit more restrictive than
1099 * the kernel is: we insist on NUL termination (both for abstract namespace and regular file system socket
1100 * addresses!), which the kernel doesn't. We do this to reduce chance of incompatibility with other apps that
1101 * do not expect non-NUL terminated file system path*/
1102 if (l
+1 > sizeof(ret
->sun_path
))
1105 *ret
= (struct sockaddr_un
) {
1106 .sun_family
= AF_UNIX
,
1109 if (path
[0] == '@') {
1110 /* Abstract namespace socket */
1111 memcpy(ret
->sun_path
+ 1, path
+ 1, l
); /* copy *with* trailing NUL byte */
1112 return (int) (offsetof(struct sockaddr_un
, sun_path
) + l
); /* 🔥 *don't* 🔥 include trailing NUL in size */
1115 assert(path
[0] == '/');
1117 /* File system socket */
1118 memcpy(ret
->sun_path
, path
, l
+ 1); /* copy *with* trailing NUL byte */
1119 return (int) (offsetof(struct sockaddr_un
, sun_path
) + l
+ 1); /* include trailing NUL in size */
1123 int socket_bind_to_ifname(int fd
, const char *ifname
) {
1126 /* Call with NULL to drop binding */
1128 if (setsockopt(fd
, SOL_SOCKET
, SO_BINDTODEVICE
, ifname
, strlen_ptr(ifname
)) < 0)
1134 int socket_bind_to_ifindex(int fd
, int ifindex
) {
1135 char ifname
[IF_NAMESIZE
+ 1];
1141 if (setsockopt(fd
, SOL_SOCKET
, SO_BINDTODEVICE
, NULL
, 0) < 0)
1147 if (setsockopt(fd
, SOL_SOCKET
, SO_BINDTOIFINDEX
, &ifindex
, sizeof(ifindex
)) >= 0)
1149 if (errno
!= ENOPROTOOPT
)
1152 /* Fall back to SO_BINDTODEVICE on kernels < 5.0 which didn't have SO_BINDTOIFINDEX */
1153 if (!format_ifname(ifindex
, ifname
))
1156 return socket_bind_to_ifname(fd
, ifname
);
1159 ssize_t
recvmsg_safe(int sockfd
, struct msghdr
*msg
, int flags
) {
1162 /* A wrapper around recvmsg() that checks for MSG_CTRUNC, and turns it into an error, in a reasonably
1163 * safe way, closing any SCM_RIGHTS fds in the error path.
1165 * Note that unlike our usual coding style this might modify *msg on failure. */
1167 n
= recvmsg(sockfd
, msg
, flags
);
1171 if (FLAGS_SET(msg
->msg_flags
, MSG_CTRUNC
)) {
1172 cmsg_close_all(msg
);
1173 return -EXFULL
; /* a recognizable error code */
1179 int socket_pass_pktinfo(int fd
, bool b
) {
1181 socklen_t sl
= sizeof(af
);
1183 if (getsockopt(fd
, SOL_SOCKET
, SO_DOMAIN
, &af
, &sl
) < 0)
1189 return setsockopt_int(fd
, IPPROTO_IP
, IP_PKTINFO
, b
);
1192 return setsockopt_int(fd
, IPPROTO_IPV6
, IPV6_RECVPKTINFO
, b
);
1195 return setsockopt_int(fd
, SOL_NETLINK
, NETLINK_PKTINFO
, b
);
1198 return -EAFNOSUPPORT
;