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"
27 #include "memory-util.h"
28 #include "missing_socket.h"
29 #include "parse-util.h"
30 #include "path-util.h"
31 #include "process-util.h"
32 #include "socket-util.h"
33 #include "string-table.h"
34 #include "string-util.h"
36 #include "user-util.h"
40 # define IDN_FLAGS NI_IDN
45 static const char* const socket_address_type_table
[] = {
46 [SOCK_STREAM
] = "Stream",
47 [SOCK_DGRAM
] = "Datagram",
49 [SOCK_RDM
] = "ReliableDatagram",
50 [SOCK_SEQPACKET
] = "SequentialPacket",
51 [SOCK_DCCP
] = "DatagramCongestionControl",
54 DEFINE_STRING_TABLE_LOOKUP(socket_address_type
, int);
56 int socket_address_verify(const SocketAddress
*a
, bool strict
) {
59 /* With 'strict' we enforce additional sanity constraints which are not set by the standard,
60 * but should only apply to sockets we create ourselves. */
62 switch (socket_address_family(a
)) {
65 if (a
->size
!= sizeof(struct sockaddr_in
))
68 if (a
->sockaddr
.in
.sin_port
== 0)
71 if (!IN_SET(a
->type
, SOCK_STREAM
, SOCK_DGRAM
))
77 if (a
->size
!= sizeof(struct sockaddr_in6
))
80 if (a
->sockaddr
.in6
.sin6_port
== 0)
83 if (!IN_SET(a
->type
, SOCK_STREAM
, SOCK_DGRAM
))
89 if (a
->size
< offsetof(struct sockaddr_un
, sun_path
))
91 if (a
->size
> sizeof(struct sockaddr_un
) + !strict
)
92 /* If !strict, allow one extra byte, since getsockname() on Linux will append
93 * a NUL byte if we have path sockets that are above sun_path's full size. */
96 if (a
->size
> offsetof(struct sockaddr_un
, sun_path
) &&
97 a
->sockaddr
.un
.sun_path
[0] != 0 &&
99 /* Only validate file system sockets here, and only in strict mode */
102 e
= memchr(a
->sockaddr
.un
.sun_path
, 0, sizeof(a
->sockaddr
.un
.sun_path
));
104 /* If there's an embedded NUL byte, make sure the size of the socket address matches it */
105 if (a
->size
!= offsetof(struct sockaddr_un
, sun_path
) + (e
- a
->sockaddr
.un
.sun_path
) + 1)
108 /* If there's no embedded NUL byte, then then the size needs to match the whole
109 * structure or the structure with one extra NUL byte suffixed. (Yeah, Linux is awful,
110 * and considers both equivalent: getsockname() even extends sockaddr_un beyond its
111 * size if the path is non NUL terminated.)*/
112 if (!IN_SET(a
->size
, sizeof(a
->sockaddr
.un
.sun_path
), sizeof(a
->sockaddr
.un
.sun_path
)+1))
117 if (!IN_SET(a
->type
, SOCK_STREAM
, SOCK_DGRAM
, SOCK_SEQPACKET
))
124 if (a
->size
!= sizeof(struct sockaddr_nl
))
127 if (!IN_SET(a
->type
, SOCK_RAW
, SOCK_DGRAM
))
133 if (a
->size
!= sizeof(struct sockaddr_vm
))
136 if (!IN_SET(a
->type
, SOCK_STREAM
, SOCK_DGRAM
))
142 return -EAFNOSUPPORT
;
146 int socket_address_print(const SocketAddress
*a
, char **ret
) {
152 r
= socket_address_verify(a
, false); /* We do non-strict validation, because we want to be
153 * able to pretty-print any socket the kernel considers
154 * valid. We still need to do validation to know if we
155 * can meaningfully print the address. */
159 if (socket_address_family(a
) == AF_NETLINK
) {
160 _cleanup_free_
char *sfamily
= NULL
;
162 r
= netlink_family_to_string_alloc(a
->protocol
, &sfamily
);
166 r
= asprintf(ret
, "%s %u", sfamily
, a
->sockaddr
.nl
.nl_groups
);
173 return sockaddr_pretty(&a
->sockaddr
.sa
, a
->size
, false, true, ret
);
176 bool socket_address_can_accept(const SocketAddress
*a
) {
180 IN_SET(a
->type
, SOCK_STREAM
, SOCK_SEQPACKET
);
183 bool socket_address_equal(const SocketAddress
*a
, const SocketAddress
*b
) {
187 /* Invalid addresses are unequal to all */
188 if (socket_address_verify(a
, false) < 0 ||
189 socket_address_verify(b
, false) < 0)
192 if (a
->type
!= b
->type
)
195 if (socket_address_family(a
) != socket_address_family(b
))
198 switch (socket_address_family(a
)) {
201 if (a
->sockaddr
.in
.sin_addr
.s_addr
!= b
->sockaddr
.in
.sin_addr
.s_addr
)
204 if (a
->sockaddr
.in
.sin_port
!= b
->sockaddr
.in
.sin_port
)
210 if (memcmp(&a
->sockaddr
.in6
.sin6_addr
, &b
->sockaddr
.in6
.sin6_addr
, sizeof(a
->sockaddr
.in6
.sin6_addr
)) != 0)
213 if (a
->sockaddr
.in6
.sin6_port
!= b
->sockaddr
.in6
.sin6_port
)
219 if (a
->size
<= offsetof(struct sockaddr_un
, sun_path
) ||
220 b
->size
<= offsetof(struct sockaddr_un
, sun_path
))
223 if ((a
->sockaddr
.un
.sun_path
[0] == 0) != (b
->sockaddr
.un
.sun_path
[0] == 0))
226 if (a
->sockaddr
.un
.sun_path
[0]) {
227 if (!path_equal_or_files_same(a
->sockaddr
.un
.sun_path
, b
->sockaddr
.un
.sun_path
, 0))
230 if (a
->size
!= b
->size
)
233 if (memcmp(a
->sockaddr
.un
.sun_path
, b
->sockaddr
.un
.sun_path
, a
->size
) != 0)
240 if (a
->protocol
!= b
->protocol
)
243 if (a
->sockaddr
.nl
.nl_groups
!= b
->sockaddr
.nl
.nl_groups
)
249 if (a
->sockaddr
.vm
.svm_cid
!= b
->sockaddr
.vm
.svm_cid
)
252 if (a
->sockaddr
.vm
.svm_port
!= b
->sockaddr
.vm
.svm_port
)
258 /* Cannot compare, so we assume the addresses are different */
265 const char* socket_address_get_path(const SocketAddress
*a
) {
268 if (socket_address_family(a
) != AF_UNIX
)
271 if (a
->sockaddr
.un
.sun_path
[0] == 0)
274 /* Note that this is only safe because we know that there's an extra NUL byte after the sockaddr_un
275 * structure. On Linux AF_UNIX file system socket addresses don't have to be NUL terminated if they take up the
276 * full sun_path space. */
277 assert_cc(sizeof(union sockaddr_union
) >= sizeof(struct sockaddr_un
)+1);
278 return a
->sockaddr
.un
.sun_path
;
281 bool socket_ipv6_is_supported(void) {
282 if (access("/proc/net/if_inet6", F_OK
) != 0)
288 bool socket_address_matches_fd(const SocketAddress
*a
, int fd
) {
295 b
.size
= sizeof(b
.sockaddr
);
296 if (getsockname(fd
, &b
.sockaddr
.sa
, &b
.size
) < 0)
299 if (b
.sockaddr
.sa
.sa_family
!= a
->sockaddr
.sa
.sa_family
)
302 solen
= sizeof(b
.type
);
303 if (getsockopt(fd
, SOL_SOCKET
, SO_TYPE
, &b
.type
, &solen
) < 0)
306 if (b
.type
!= a
->type
)
309 if (a
->protocol
!= 0) {
310 solen
= sizeof(b
.protocol
);
311 if (getsockopt(fd
, SOL_SOCKET
, SO_PROTOCOL
, &b
.protocol
, &solen
) < 0)
314 if (b
.protocol
!= a
->protocol
)
318 return socket_address_equal(a
, &b
);
321 int sockaddr_port(const struct sockaddr
*_sa
, unsigned *ret_port
) {
322 union sockaddr_union
*sa
= (union sockaddr_union
*) _sa
;
324 /* Note, this returns the port as 'unsigned' rather than 'uint16_t', as AF_VSOCK knows larger ports */
328 switch (sa
->sa
.sa_family
) {
331 *ret_port
= be16toh(sa
->in
.sin_port
);
335 *ret_port
= be16toh(sa
->in6
.sin6_port
);
339 *ret_port
= sa
->vm
.svm_port
;
343 return -EAFNOSUPPORT
;
348 const struct sockaddr
*_sa
,
354 union sockaddr_union
*sa
= (union sockaddr_union
*) _sa
;
359 assert(salen
>= sizeof(sa
->sa
.sa_family
));
361 switch (sa
->sa
.sa_family
) {
366 a
= be32toh(sa
->in
.sin_addr
.s_addr
);
371 a
>> 24, (a
>> 16) & 0xFF, (a
>> 8) & 0xFF, a
& 0xFF,
372 be16toh(sa
->in
.sin_port
));
376 a
>> 24, (a
>> 16) & 0xFF, (a
>> 8) & 0xFF, a
& 0xFF);
383 static const unsigned char ipv4_prefix
[] = {
384 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xFF, 0xFF
387 if (translate_ipv6
&&
388 memcmp(&sa
->in6
.sin6_addr
, ipv4_prefix
, sizeof(ipv4_prefix
)) == 0) {
389 const uint8_t *a
= sa
->in6
.sin6_addr
.s6_addr
+12;
393 a
[0], a
[1], a
[2], a
[3],
394 be16toh(sa
->in6
.sin6_port
));
398 a
[0], a
[1], a
[2], a
[3]);
402 char a
[INET6_ADDRSTRLEN
];
404 inet_ntop(AF_INET6
, &sa
->in6
.sin6_addr
, a
, sizeof(a
));
410 be16toh(sa
->in6
.sin6_port
));
424 if (salen
<= offsetof(struct sockaddr_un
, sun_path
) ||
425 (sa
->un
.sun_path
[0] == 0 && salen
== offsetof(struct sockaddr_un
, sun_path
) + 1))
426 /* The name must have at least one character (and the leading NUL does not count) */
427 p
= strdup("<unnamed>");
429 /* Note that we calculate the path pointer here through the .un_buffer[] field, in order to
430 * outtrick bounds checking tools such as ubsan, which are too smart for their own good: on
431 * Linux the kernel may return sun_path[] data one byte longer than the declared size of the
433 char *path
= (char*) sa
->un_buffer
+ offsetof(struct sockaddr_un
, sun_path
);
434 size_t path_len
= salen
- offsetof(struct sockaddr_un
, sun_path
);
437 /* Abstract socket. When parsing address information from, we
438 * explicitly reject overly long paths and paths with embedded NULs.
439 * But we might get such a socket from the outside. Let's return
440 * something meaningful and printable in this case. */
442 _cleanup_free_
char *e
= NULL
;
444 e
= cescape_length(path
+ 1, path_len
- 1);
450 if (path
[path_len
- 1] == '\0')
451 /* We expect a terminating NUL and don't print it */
454 p
= cescape_length(path
, path_len
);
464 if (sa
->vm
.svm_cid
== VMADDR_CID_ANY
)
465 r
= asprintf(&p
, "vsock::%u", sa
->vm
.svm_port
);
467 r
= asprintf(&p
, "vsock:%u:%u", sa
->vm
.svm_cid
, sa
->vm
.svm_port
);
469 r
= asprintf(&p
, "vsock:%u", sa
->vm
.svm_cid
);
482 int getpeername_pretty(int fd
, bool include_port
, char **ret
) {
483 union sockaddr_union sa
;
484 socklen_t salen
= sizeof(sa
);
490 if (getpeername(fd
, &sa
.sa
, &salen
) < 0)
493 if (sa
.sa
.sa_family
== AF_UNIX
) {
494 struct ucred ucred
= {};
496 /* UNIX connection sockets are anonymous, so let's use
497 * PID/UID as pretty credentials instead */
499 r
= getpeercred(fd
, &ucred
);
503 if (asprintf(ret
, "PID "PID_FMT
"/UID "UID_FMT
, ucred
.pid
, ucred
.uid
) < 0)
509 /* For remote sockets we translate IPv6 addresses back to IPv4
510 * if applicable, since that's nicer. */
512 return sockaddr_pretty(&sa
.sa
, salen
, true, include_port
, ret
);
515 int getsockname_pretty(int fd
, char **ret
) {
516 union sockaddr_union sa
;
517 socklen_t salen
= sizeof(sa
);
522 if (getsockname(fd
, &sa
.sa
, &salen
) < 0)
525 /* For local sockets we do not translate IPv6 addresses back
526 * to IPv6 if applicable, since this is usually used for
527 * listening sockets where the difference between IPv4 and
530 return sockaddr_pretty(&sa
.sa
, salen
, false, true, ret
);
533 int socknameinfo_pretty(union sockaddr_union
*sa
, socklen_t salen
, char **_ret
) {
535 char host
[NI_MAXHOST
], *ret
;
539 r
= getnameinfo(&sa
->sa
, salen
, host
, sizeof(host
), NULL
, 0, IDN_FLAGS
);
541 int saved_errno
= errno
;
543 r
= sockaddr_pretty(&sa
->sa
, salen
, true, true, &ret
);
547 log_debug_errno(saved_errno
, "getnameinfo(%s) failed: %m", ret
);
558 static const char* const netlink_family_table
[] = {
559 [NETLINK_ROUTE
] = "route",
560 [NETLINK_FIREWALL
] = "firewall",
561 [NETLINK_INET_DIAG
] = "inet-diag",
562 [NETLINK_NFLOG
] = "nflog",
563 [NETLINK_XFRM
] = "xfrm",
564 [NETLINK_SELINUX
] = "selinux",
565 [NETLINK_ISCSI
] = "iscsi",
566 [NETLINK_AUDIT
] = "audit",
567 [NETLINK_FIB_LOOKUP
] = "fib-lookup",
568 [NETLINK_CONNECTOR
] = "connector",
569 [NETLINK_NETFILTER
] = "netfilter",
570 [NETLINK_IP6_FW
] = "ip6-fw",
571 [NETLINK_DNRTMSG
] = "dnrtmsg",
572 [NETLINK_KOBJECT_UEVENT
] = "kobject-uevent",
573 [NETLINK_GENERIC
] = "generic",
574 [NETLINK_SCSITRANSPORT
] = "scsitransport",
575 [NETLINK_ECRYPTFS
] = "ecryptfs",
576 [NETLINK_RDMA
] = "rdma",
579 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(netlink_family
, int, INT_MAX
);
581 static const char* const socket_address_bind_ipv6_only_table
[_SOCKET_ADDRESS_BIND_IPV6_ONLY_MAX
] = {
582 [SOCKET_ADDRESS_DEFAULT
] = "default",
583 [SOCKET_ADDRESS_BOTH
] = "both",
584 [SOCKET_ADDRESS_IPV6_ONLY
] = "ipv6-only"
587 DEFINE_STRING_TABLE_LOOKUP(socket_address_bind_ipv6_only
, SocketAddressBindIPv6Only
);
589 SocketAddressBindIPv6Only
socket_address_bind_ipv6_only_or_bool_from_string(const char *n
) {
592 r
= parse_boolean(n
);
594 return SOCKET_ADDRESS_IPV6_ONLY
;
596 return SOCKET_ADDRESS_BOTH
;
598 return socket_address_bind_ipv6_only_from_string(n
);
601 bool sockaddr_equal(const union sockaddr_union
*a
, const union sockaddr_union
*b
) {
605 if (a
->sa
.sa_family
!= b
->sa
.sa_family
)
608 if (a
->sa
.sa_family
== AF_INET
)
609 return a
->in
.sin_addr
.s_addr
== b
->in
.sin_addr
.s_addr
;
611 if (a
->sa
.sa_family
== AF_INET6
)
612 return memcmp(&a
->in6
.sin6_addr
, &b
->in6
.sin6_addr
, sizeof(a
->in6
.sin6_addr
)) == 0;
614 if (a
->sa
.sa_family
== AF_VSOCK
)
615 return a
->vm
.svm_cid
== b
->vm
.svm_cid
;
620 int fd_inc_sndbuf(int fd
, size_t n
) {
622 socklen_t l
= sizeof(value
);
624 r
= getsockopt(fd
, SOL_SOCKET
, SO_SNDBUF
, &value
, &l
);
625 if (r
>= 0 && l
== sizeof(value
) && (size_t) value
>= n
*2)
628 /* If we have the privileges we will ignore the kernel limit. */
630 if (setsockopt_int(fd
, SOL_SOCKET
, SO_SNDBUF
, n
) < 0) {
631 r
= setsockopt_int(fd
, SOL_SOCKET
, SO_SNDBUFFORCE
, n
);
639 int fd_inc_rcvbuf(int fd
, size_t n
) {
641 socklen_t l
= sizeof(value
);
643 r
= getsockopt(fd
, SOL_SOCKET
, SO_RCVBUF
, &value
, &l
);
644 if (r
>= 0 && l
== sizeof(value
) && (size_t) value
>= n
*2)
647 /* If we have the privileges we will ignore the kernel limit. */
649 if (setsockopt_int(fd
, SOL_SOCKET
, SO_RCVBUF
, n
) < 0) {
650 r
= setsockopt_int(fd
, SOL_SOCKET
, SO_RCVBUFFORCE
, n
);
658 static const char* const ip_tos_table
[] = {
659 [IPTOS_LOWDELAY
] = "low-delay",
660 [IPTOS_THROUGHPUT
] = "throughput",
661 [IPTOS_RELIABILITY
] = "reliability",
662 [IPTOS_LOWCOST
] = "low-cost",
665 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(ip_tos
, int, 0xff);
667 bool ifname_valid_full(const char *p
, bool alternative
) {
670 /* Checks whether a network interface name is valid. This is inspired by dev_valid_name() in the kernel sources
671 * but slightly stricter, as we only allow non-control, non-space ASCII characters in the interface name. We
672 * also don't permit names that only container numbers, to avoid confusion with numeric interface indexes. */
678 if (strlen(p
) >= ALTIFNAMSIZ
)
681 if (strlen(p
) >= IFNAMSIZ
)
685 if (dot_or_dot_dot(p
))
689 if ((unsigned char) *p
>= 127U)
692 if ((unsigned char) *p
<= 32U)
695 if (IN_SET(*p
, ':', '/'))
698 numeric
= numeric
&& (*p
>= '0' && *p
<= '9');
708 bool address_label_valid(const char *p
) {
713 if (strlen(p
) >= IFNAMSIZ
)
717 if ((uint8_t) *p
>= 127U)
720 if ((uint8_t) *p
<= 31U)
728 int getpeercred(int fd
, struct ucred
*ucred
) {
729 socklen_t n
= sizeof(struct ucred
);
736 r
= getsockopt(fd
, SOL_SOCKET
, SO_PEERCRED
, &u
, &n
);
740 if (n
!= sizeof(struct ucred
))
743 /* Check if the data is actually useful and not suppressed due to namespacing issues */
744 if (!pid_is_valid(u
.pid
))
747 /* Note that we don't check UID/GID here, as namespace translation works differently there: instead of
748 * receiving in "invalid" user/group we get the overflow UID/GID. */
754 int getpeersec(int fd
, char **ret
) {
755 _cleanup_free_
char *s
= NULL
;
766 if (getsockopt(fd
, SOL_SOCKET
, SO_PEERSEC
, s
, &n
) >= 0)
783 int getpeergroups(int fd
, gid_t
**ret
) {
784 socklen_t n
= sizeof(gid_t
) * 64;
785 _cleanup_free_ gid_t
*d
= NULL
;
795 if (getsockopt(fd
, SOL_SOCKET
, SO_PEERGROUPS
, d
, &n
) >= 0)
804 assert_se(n
% sizeof(gid_t
) == 0);
807 if ((socklen_t
) (int) n
!= n
)
815 ssize_t
send_one_fd_iov_sa(
818 struct iovec
*iov
, size_t iovlen
,
819 const struct sockaddr
*sa
, socklen_t len
,
822 CMSG_BUFFER_TYPE(CMSG_SPACE(sizeof(int))) control
= {};
824 .msg_name
= (struct sockaddr
*) sa
,
827 .msg_iovlen
= iovlen
,
831 assert(transport_fd
>= 0);
834 * We need either an FD or data to send.
835 * If there's nothing, return an error.
841 struct cmsghdr
*cmsg
;
843 mh
.msg_control
= &control
;
844 mh
.msg_controllen
= sizeof(control
);
846 cmsg
= CMSG_FIRSTHDR(&mh
);
847 cmsg
->cmsg_level
= SOL_SOCKET
;
848 cmsg
->cmsg_type
= SCM_RIGHTS
;
849 cmsg
->cmsg_len
= CMSG_LEN(sizeof(int));
850 memcpy(CMSG_DATA(cmsg
), &fd
, sizeof(int));
852 k
= sendmsg(transport_fd
, &mh
, MSG_NOSIGNAL
| flags
);
854 return (ssize_t
) -errno
;
862 const struct sockaddr
*sa
, socklen_t len
,
867 return (int) send_one_fd_iov_sa(transport_fd
, fd
, NULL
, 0, sa
, len
, flags
);
870 ssize_t
receive_one_fd_iov(
872 struct iovec
*iov
, size_t iovlen
,
876 CMSG_BUFFER_TYPE(CMSG_SPACE(sizeof(int))) control
;
878 .msg_control
= &control
,
879 .msg_controllen
= sizeof(control
),
881 .msg_iovlen
= iovlen
,
883 struct cmsghdr
*found
;
886 assert(transport_fd
>= 0);
890 * Receive a single FD via @transport_fd. We don't care for
891 * the transport-type. We retrieve a single FD at most, so for
892 * packet-based transports, the caller must ensure to send
893 * only a single FD per packet. This is best used in
894 * combination with send_one_fd().
897 k
= recvmsg_safe(transport_fd
, &mh
, MSG_CMSG_CLOEXEC
| flags
);
901 found
= cmsg_find(&mh
, SOL_SOCKET
, SCM_RIGHTS
, CMSG_LEN(sizeof(int)));
905 /* If didn't receive an FD or any data, return an error. */
911 *ret_fd
= *(int*) CMSG_DATA(found
);
918 int receive_one_fd(int transport_fd
, int flags
) {
922 k
= receive_one_fd_iov(transport_fd
, NULL
, 0, flags
, &fd
);
926 /* k must be negative, since receive_one_fd_iov() only returns
927 * a positive value if data was received through the iov. */
932 ssize_t
next_datagram_size_fd(int fd
) {
936 /* This is a bit like FIONREAD/SIOCINQ, however a bit more powerful. The difference being: recv(MSG_PEEK) will
937 * actually cause the next datagram in the queue to be validated regarding checksums, which FIONREAD doesn't
938 * do. This difference is actually of major importance as we need to be sure that the size returned here
939 * actually matches what we will read with recvmsg() next, as otherwise we might end up allocating a buffer of
942 l
= recv(fd
, NULL
, 0, MSG_PEEK
|MSG_TRUNC
);
944 if (IN_SET(errno
, EOPNOTSUPP
, EFAULT
))
957 /* Some sockets (AF_PACKET) do not support null-sized recv() with MSG_TRUNC set, let's fall back to FIONREAD
958 * for them. Checksums don't matter for raw sockets anyway, hence this should be fine. */
960 if (ioctl(fd
, FIONREAD
, &k
) < 0)
966 /* Put a limit on how many times will attempt to call accept4(). We loop
967 * only on "transient" errors, but let's make sure we don't loop forever. */
968 #define MAX_FLUSH_ITERATIONS 1024
970 int flush_accept(int fd
) {
973 socklen_t l
= sizeof(b
);
975 /* Similar to flush_fd() but flushes all incoming connections by accepting and immediately closing
978 if (getsockopt(fd
, SOL_SOCKET
, SO_ACCEPTCONN
, &b
, &l
) < 0)
981 assert(l
== sizeof(b
));
982 if (!b
) /* Let's check if this socket accepts connections before calling accept(). accept4() can
983 * return EOPNOTSUPP if the fd is not a listening socket, which we should treat as a fatal
984 * error, or in case the incoming TCP connection triggered a network issue, which we want to
985 * treat as a transient error. Thus, let's rule out the first reason for EOPNOTSUPP early, so
986 * we can loop safely on transient errors below. */
989 for (unsigned iteration
= 0;; iteration
++) {
992 r
= fd_wait_for_event(fd
, POLLIN
, 0);
1002 if (iteration
>= MAX_FLUSH_ITERATIONS
)
1003 return log_debug_errno(SYNTHETIC_ERRNO(EBUSY
),
1004 "Failed to flush connections within " STRINGIFY(MAX_FLUSH_ITERATIONS
) " iterations.");
1006 cfd
= accept4(fd
, NULL
, NULL
, SOCK_NONBLOCK
|SOCK_CLOEXEC
);
1008 if (errno
== EAGAIN
)
1011 if (ERRNO_IS_ACCEPT_AGAIN(errno
))
1021 struct cmsghdr
* cmsg_find(struct msghdr
*mh
, int level
, int type
, socklen_t length
) {
1022 struct cmsghdr
*cmsg
;
1026 CMSG_FOREACH(cmsg
, mh
)
1027 if (cmsg
->cmsg_level
== level
&&
1028 cmsg
->cmsg_type
== type
&&
1029 (length
== (socklen_t
) -1 || length
== cmsg
->cmsg_len
))
1035 int socket_ioctl_fd(void) {
1038 /* Create a socket to invoke the various network interface ioctl()s on. Traditionally only AF_INET was good for
1039 * that. Since kernel 4.6 AF_NETLINK works for this too. We first try to use AF_INET hence, but if that's not
1040 * available (for example, because it is made unavailable via SECCOMP or such), we'll fall back to the more
1041 * generic AF_NETLINK. */
1043 fd
= socket(AF_INET
, SOCK_DGRAM
|SOCK_CLOEXEC
, 0);
1045 fd
= socket(AF_NETLINK
, SOCK_RAW
|SOCK_CLOEXEC
, NETLINK_GENERIC
);
1052 int sockaddr_un_unlink(const struct sockaddr_un
*sa
) {
1053 const char *p
, * nul
;
1057 if (sa
->sun_family
!= AF_UNIX
)
1060 if (sa
->sun_path
[0] == 0) /* Nothing to do for abstract sockets */
1063 /* The path in .sun_path is not necessarily NUL terminated. Let's fix that. */
1064 nul
= memchr(sa
->sun_path
, 0, sizeof(sa
->sun_path
));
1068 p
= memdupa_suffix0(sa
->sun_path
, sizeof(sa
->sun_path
));
1076 int sockaddr_un_set_path(struct sockaddr_un
*ret
, const char *path
) {
1082 /* Initialize ret->sun_path from the specified argument. This will interpret paths starting with '@' as
1083 * abstract namespace sockets, and those starting with '/' as regular filesystem sockets. It won't accept
1084 * anything else (i.e. no relative paths), to avoid ambiguities. Note that this function cannot be used to
1085 * reference paths in the abstract namespace that include NUL bytes in the name. */
1090 if (!IN_SET(path
[0], '/', '@'))
1095 /* Don't allow paths larger than the space in sockaddr_un. Note that we are a tiny bit more restrictive than
1096 * the kernel is: we insist on NUL termination (both for abstract namespace and regular file system socket
1097 * addresses!), which the kernel doesn't. We do this to reduce chance of incompatibility with other apps that
1098 * do not expect non-NUL terminated file system path*/
1099 if (l
+1 > sizeof(ret
->sun_path
))
1102 *ret
= (struct sockaddr_un
) {
1103 .sun_family
= AF_UNIX
,
1106 if (path
[0] == '@') {
1107 /* Abstract namespace socket */
1108 memcpy(ret
->sun_path
+ 1, path
+ 1, l
); /* copy *with* trailing NUL byte */
1109 return (int) (offsetof(struct sockaddr_un
, sun_path
) + l
); /* 🔥 *don't* 🔥 include trailing NUL in size */
1112 assert(path
[0] == '/');
1114 /* File system socket */
1115 memcpy(ret
->sun_path
, path
, l
+ 1); /* copy *with* trailing NUL byte */
1116 return (int) (offsetof(struct sockaddr_un
, sun_path
) + l
+ 1); /* include trailing NUL in size */
1120 int socket_bind_to_ifname(int fd
, const char *ifname
) {
1123 /* Call with NULL to drop binding */
1125 if (setsockopt(fd
, SOL_SOCKET
, SO_BINDTODEVICE
, ifname
, strlen_ptr(ifname
)) < 0)
1131 int socket_bind_to_ifindex(int fd
, int ifindex
) {
1132 char ifname
[IF_NAMESIZE
+ 1];
1138 if (setsockopt(fd
, SOL_SOCKET
, SO_BINDTODEVICE
, NULL
, 0) < 0)
1144 if (setsockopt(fd
, SOL_SOCKET
, SO_BINDTOIFINDEX
, &ifindex
, sizeof(ifindex
)) >= 0)
1146 if (errno
!= ENOPROTOOPT
)
1149 /* Fall back to SO_BINDTODEVICE on kernels < 5.0 which didn't have SO_BINDTOIFINDEX */
1150 if (!format_ifname(ifindex
, ifname
))
1153 return socket_bind_to_ifname(fd
, ifname
);
1156 ssize_t
recvmsg_safe(int sockfd
, struct msghdr
*msg
, int flags
) {
1159 /* A wrapper around recvmsg() that checks for MSG_CTRUNC, and turns it into an error, in a reasonably
1160 * safe way, closing any SCM_RIGHTS fds in the error path.
1162 * Note that unlike our usual coding style this might modify *msg on failure. */
1164 n
= recvmsg(sockfd
, msg
, flags
);
1168 if (FLAGS_SET(msg
->msg_flags
, MSG_CTRUNC
)) {
1169 cmsg_close_all(msg
);
1170 return -EXFULL
; /* a recognizable error code */
1176 int socket_pass_pktinfo(int fd
, bool b
) {
1178 socklen_t sl
= sizeof(af
);
1180 if (getsockopt(fd
, SOL_SOCKET
, SO_DOMAIN
, &af
, &sl
) < 0)
1186 return setsockopt_int(fd
, IPPROTO_IP
, IP_PKTINFO
, b
);
1189 return setsockopt_int(fd
, IPPROTO_IPV6
, IPV6_RECVPKTINFO
, b
);
1192 return setsockopt_int(fd
, SOL_NETLINK
, NETLINK_PKTINFO
, b
);
1195 return -EAFNOSUPPORT
;