1 /* SPDX-License-Identifier: LGPL-2.1+ */
8 #include <netinet/ip.h>
17 #include "alloc-util.h"
21 #include "format-util.h"
24 #include "memory-util.h"
26 #include "parse-util.h"
27 #include "path-util.h"
28 #include "process-util.h"
29 #include "socket-util.h"
30 #include "string-table.h"
31 #include "string-util.h"
33 #include "user-util.h"
37 # define IDN_FLAGS NI_IDN
42 static const char* const socket_address_type_table
[] = {
43 [SOCK_STREAM
] = "Stream",
44 [SOCK_DGRAM
] = "Datagram",
46 [SOCK_RDM
] = "ReliableDatagram",
47 [SOCK_SEQPACKET
] = "SequentialPacket",
48 [SOCK_DCCP
] = "DatagramCongestionControl",
51 DEFINE_STRING_TABLE_LOOKUP(socket_address_type
, int);
53 int socket_address_parse(SocketAddress
*a
, const char *s
) {
54 _cleanup_free_
char *n
= NULL
;
61 *a
= (SocketAddress
) {
68 /* IPv6 in [x:.....:z]:p notation */
74 n
= strndup(s
+1, e
-s
-1);
79 if (inet_pton(AF_INET6
, n
, &a
->sockaddr
.in6
.sin6_addr
) <= 0)
80 return errno
> 0 ? -errno
: -EINVAL
;
87 r
= parse_ip_port(e
, &port
);
91 a
->sockaddr
.in6
.sin6_family
= AF_INET6
;
92 a
->sockaddr
.in6
.sin6_port
= htobe16(port
);
93 a
->size
= sizeof(struct sockaddr_in6
);
95 } else if (*s
== '/') {
101 if (l
>= sizeof(a
->sockaddr
.un
.sun_path
)) /* Note that we refuse non-NUL-terminated sockets when
102 * parsing (the kernel itself is less strict here in what it
106 a
->sockaddr
.un
.sun_family
= AF_UNIX
;
107 memcpy(a
->sockaddr
.un
.sun_path
, s
, l
);
108 a
->size
= offsetof(struct sockaddr_un
, sun_path
) + l
+ 1;
110 } else if (*s
== '@') {
111 /* Abstract AF_UNIX socket */
115 if (l
>= sizeof(a
->sockaddr
.un
.sun_path
) - 1) /* Note that we refuse non-NUL-terminated sockets here
116 * when parsing, even though abstract namespace sockets
117 * explicitly allow embedded NUL bytes and don't consider
118 * them special. But it's simply annoying to debug such
122 a
->sockaddr
.un
.sun_family
= AF_UNIX
;
123 memcpy(a
->sockaddr
.un
.sun_path
+1, s
+1, l
);
124 a
->size
= offsetof(struct sockaddr_un
, sun_path
) + 1 + l
;
126 } else if (startswith(s
, "vsock:")) {
127 /* AF_VSOCK socket in vsock:cid:port notation */
128 const char *cid_start
= s
+ STRLEN("vsock:");
131 e
= strchr(cid_start
, ':');
135 r
= safe_atou(e
+1, &port
);
139 n
= strndup(cid_start
, e
- cid_start
);
144 r
= safe_atou(n
, &a
->sockaddr
.vm
.svm_cid
);
148 a
->sockaddr
.vm
.svm_cid
= VMADDR_CID_ANY
;
150 a
->sockaddr
.vm
.svm_family
= AF_VSOCK
;
151 a
->sockaddr
.vm
.svm_port
= port
;
152 a
->size
= sizeof(struct sockaddr_vm
);
159 r
= parse_ip_port(e
+ 1, &port
);
167 /* IPv4 in w.x.y.z:p notation? */
168 r
= inet_pton(AF_INET
, n
, &a
->sockaddr
.in
.sin_addr
);
173 /* Gotcha, it's a traditional IPv4 address */
174 a
->sockaddr
.in
.sin_family
= AF_INET
;
175 a
->sockaddr
.in
.sin_port
= htobe16(port
);
176 a
->size
= sizeof(struct sockaddr_in
);
180 if (strlen(n
) > IF_NAMESIZE
-1)
183 /* Uh, our last resort, an interface name */
184 idx
= if_nametoindex(n
);
188 a
->sockaddr
.in6
.sin6_family
= AF_INET6
;
189 a
->sockaddr
.in6
.sin6_port
= htobe16(port
);
190 a
->sockaddr
.in6
.sin6_scope_id
= idx
;
191 a
->sockaddr
.in6
.sin6_addr
= in6addr_any
;
192 a
->size
= sizeof(struct sockaddr_in6
);
197 r
= parse_ip_port(s
, &port
);
201 if (socket_ipv6_is_supported()) {
202 a
->sockaddr
.in6
.sin6_family
= AF_INET6
;
203 a
->sockaddr
.in6
.sin6_port
= htobe16(port
);
204 a
->sockaddr
.in6
.sin6_addr
= in6addr_any
;
205 a
->size
= sizeof(struct sockaddr_in6
);
207 a
->sockaddr
.in
.sin_family
= AF_INET
;
208 a
->sockaddr
.in
.sin_port
= htobe16(port
);
209 a
->sockaddr
.in
.sin_addr
.s_addr
= INADDR_ANY
;
210 a
->size
= sizeof(struct sockaddr_in
);
218 int socket_address_parse_and_warn(SocketAddress
*a
, const char *s
) {
222 /* Similar to socket_address_parse() but warns for IPv6 sockets when we don't support them. */
224 r
= socket_address_parse(&b
, s
);
228 if (!socket_ipv6_is_supported() && b
.sockaddr
.sa
.sa_family
== AF_INET6
) {
229 log_warning("Binding to IPv6 address not available since kernel does not support IPv6.");
230 return -EAFNOSUPPORT
;
237 int socket_address_parse_netlink(SocketAddress
*a
, const char *s
) {
238 _cleanup_free_
char *word
= NULL
;
248 r
= extract_first_word(&s
, &word
, NULL
, 0);
254 family
= netlink_family_from_string(word
);
259 r
= safe_atou(s
, &group
);
264 a
->sockaddr
.nl
.nl_family
= AF_NETLINK
;
265 a
->sockaddr
.nl
.nl_groups
= group
;
268 a
->size
= sizeof(struct sockaddr_nl
);
269 a
->protocol
= family
;
274 int socket_address_verify(const SocketAddress
*a
, bool strict
) {
277 /* With 'strict' we enforce additional sanity constraints which are not set by the standard,
278 * but should only apply to sockets we create ourselves. */
280 switch (socket_address_family(a
)) {
283 if (a
->size
!= sizeof(struct sockaddr_in
))
286 if (a
->sockaddr
.in
.sin_port
== 0)
289 if (!IN_SET(a
->type
, SOCK_STREAM
, SOCK_DGRAM
))
295 if (a
->size
!= sizeof(struct sockaddr_in6
))
298 if (a
->sockaddr
.in6
.sin6_port
== 0)
301 if (!IN_SET(a
->type
, SOCK_STREAM
, SOCK_DGRAM
))
307 if (a
->size
< offsetof(struct sockaddr_un
, sun_path
))
309 if (a
->size
> sizeof(struct sockaddr_un
) + !strict
)
310 /* If !strict, allow one extra byte, since getsockname() on Linux will append
311 * a NUL byte if we have path sockets that are above sun_path's full size. */
314 if (a
->size
> offsetof(struct sockaddr_un
, sun_path
) &&
315 a
->sockaddr
.un
.sun_path
[0] != 0 &&
317 /* Only validate file system sockets here, and only in strict mode */
320 e
= memchr(a
->sockaddr
.un
.sun_path
, 0, sizeof(a
->sockaddr
.un
.sun_path
));
322 /* If there's an embedded NUL byte, make sure the size of the socket address matches it */
323 if (a
->size
!= offsetof(struct sockaddr_un
, sun_path
) + (e
- a
->sockaddr
.un
.sun_path
) + 1)
326 /* If there's no embedded NUL byte, then then the size needs to match the whole
327 * structure or the structure with one extra NUL byte suffixed. (Yeah, Linux is awful,
328 * and considers both equivalent: getsockname() even extends sockaddr_un beyond its
329 * size if the path is non NUL terminated.)*/
330 if (!IN_SET(a
->size
, sizeof(a
->sockaddr
.un
.sun_path
), sizeof(a
->sockaddr
.un
.sun_path
)+1))
335 if (!IN_SET(a
->type
, SOCK_STREAM
, SOCK_DGRAM
, SOCK_SEQPACKET
))
342 if (a
->size
!= sizeof(struct sockaddr_nl
))
345 if (!IN_SET(a
->type
, SOCK_RAW
, SOCK_DGRAM
))
351 if (a
->size
!= sizeof(struct sockaddr_vm
))
354 if (!IN_SET(a
->type
, SOCK_STREAM
, SOCK_DGRAM
))
360 return -EAFNOSUPPORT
;
364 int socket_address_print(const SocketAddress
*a
, char **ret
) {
370 r
= socket_address_verify(a
, false); /* We do non-strict validation, because we want to be
371 * able to pretty-print any socket the kernel considers
372 * valid. We still need to do validation to know if we
373 * can meaningfully print the address. */
377 if (socket_address_family(a
) == AF_NETLINK
) {
378 _cleanup_free_
char *sfamily
= NULL
;
380 r
= netlink_family_to_string_alloc(a
->protocol
, &sfamily
);
384 r
= asprintf(ret
, "%s %u", sfamily
, a
->sockaddr
.nl
.nl_groups
);
391 return sockaddr_pretty(&a
->sockaddr
.sa
, a
->size
, false, true, ret
);
394 bool socket_address_can_accept(const SocketAddress
*a
) {
398 IN_SET(a
->type
, SOCK_STREAM
, SOCK_SEQPACKET
);
401 bool socket_address_equal(const SocketAddress
*a
, const SocketAddress
*b
) {
405 /* Invalid addresses are unequal to all */
406 if (socket_address_verify(a
, false) < 0 ||
407 socket_address_verify(b
, false) < 0)
410 if (a
->type
!= b
->type
)
413 if (socket_address_family(a
) != socket_address_family(b
))
416 switch (socket_address_family(a
)) {
419 if (a
->sockaddr
.in
.sin_addr
.s_addr
!= b
->sockaddr
.in
.sin_addr
.s_addr
)
422 if (a
->sockaddr
.in
.sin_port
!= b
->sockaddr
.in
.sin_port
)
428 if (memcmp(&a
->sockaddr
.in6
.sin6_addr
, &b
->sockaddr
.in6
.sin6_addr
, sizeof(a
->sockaddr
.in6
.sin6_addr
)) != 0)
431 if (a
->sockaddr
.in6
.sin6_port
!= b
->sockaddr
.in6
.sin6_port
)
437 if (a
->size
<= offsetof(struct sockaddr_un
, sun_path
) ||
438 b
->size
<= offsetof(struct sockaddr_un
, sun_path
))
441 if ((a
->sockaddr
.un
.sun_path
[0] == 0) != (b
->sockaddr
.un
.sun_path
[0] == 0))
444 if (a
->sockaddr
.un
.sun_path
[0]) {
445 if (!path_equal_or_files_same(a
->sockaddr
.un
.sun_path
, b
->sockaddr
.un
.sun_path
, 0))
448 if (a
->size
!= b
->size
)
451 if (memcmp(a
->sockaddr
.un
.sun_path
, b
->sockaddr
.un
.sun_path
, a
->size
) != 0)
458 if (a
->protocol
!= b
->protocol
)
461 if (a
->sockaddr
.nl
.nl_groups
!= b
->sockaddr
.nl
.nl_groups
)
467 if (a
->sockaddr
.vm
.svm_cid
!= b
->sockaddr
.vm
.svm_cid
)
470 if (a
->sockaddr
.vm
.svm_port
!= b
->sockaddr
.vm
.svm_port
)
476 /* Cannot compare, so we assume the addresses are different */
483 bool socket_address_is(const SocketAddress
*a
, const char *s
, int type
) {
484 struct SocketAddress b
;
489 if (socket_address_parse(&b
, s
) < 0)
494 return socket_address_equal(a
, &b
);
497 bool socket_address_is_netlink(const SocketAddress
*a
, const char *s
) {
498 struct SocketAddress b
;
503 if (socket_address_parse_netlink(&b
, s
) < 0)
506 return socket_address_equal(a
, &b
);
509 const char* socket_address_get_path(const SocketAddress
*a
) {
512 if (socket_address_family(a
) != AF_UNIX
)
515 if (a
->sockaddr
.un
.sun_path
[0] == 0)
518 /* Note that this is only safe because we know that there's an extra NUL byte after the sockaddr_un
519 * structure. On Linux AF_UNIX file system socket addresses don't have to be NUL terminated if they take up the
520 * full sun_path space. */
521 assert_cc(sizeof(union sockaddr_union
) >= sizeof(struct sockaddr_un
)+1);
522 return a
->sockaddr
.un
.sun_path
;
525 bool socket_ipv6_is_supported(void) {
526 if (access("/proc/net/if_inet6", F_OK
) != 0)
532 bool socket_address_matches_fd(const SocketAddress
*a
, int fd
) {
539 b
.size
= sizeof(b
.sockaddr
);
540 if (getsockname(fd
, &b
.sockaddr
.sa
, &b
.size
) < 0)
543 if (b
.sockaddr
.sa
.sa_family
!= a
->sockaddr
.sa
.sa_family
)
546 solen
= sizeof(b
.type
);
547 if (getsockopt(fd
, SOL_SOCKET
, SO_TYPE
, &b
.type
, &solen
) < 0)
550 if (b
.type
!= a
->type
)
553 if (a
->protocol
!= 0) {
554 solen
= sizeof(b
.protocol
);
555 if (getsockopt(fd
, SOL_SOCKET
, SO_PROTOCOL
, &b
.protocol
, &solen
) < 0)
558 if (b
.protocol
!= a
->protocol
)
562 return socket_address_equal(a
, &b
);
565 int sockaddr_port(const struct sockaddr
*_sa
, unsigned *ret_port
) {
566 union sockaddr_union
*sa
= (union sockaddr_union
*) _sa
;
568 /* Note, this returns the port as 'unsigned' rather than 'uint16_t', as AF_VSOCK knows larger ports */
572 switch (sa
->sa
.sa_family
) {
575 *ret_port
= be16toh(sa
->in
.sin_port
);
579 *ret_port
= be16toh(sa
->in6
.sin6_port
);
583 *ret_port
= sa
->vm
.svm_port
;
587 return -EAFNOSUPPORT
;
592 const struct sockaddr
*_sa
,
598 union sockaddr_union
*sa
= (union sockaddr_union
*) _sa
;
603 assert(salen
>= sizeof(sa
->sa
.sa_family
));
605 switch (sa
->sa
.sa_family
) {
610 a
= be32toh(sa
->in
.sin_addr
.s_addr
);
615 a
>> 24, (a
>> 16) & 0xFF, (a
>> 8) & 0xFF, a
& 0xFF,
616 be16toh(sa
->in
.sin_port
));
620 a
>> 24, (a
>> 16) & 0xFF, (a
>> 8) & 0xFF, a
& 0xFF);
627 static const unsigned char ipv4_prefix
[] = {
628 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xFF, 0xFF
631 if (translate_ipv6
&&
632 memcmp(&sa
->in6
.sin6_addr
, ipv4_prefix
, sizeof(ipv4_prefix
)) == 0) {
633 const uint8_t *a
= sa
->in6
.sin6_addr
.s6_addr
+12;
637 a
[0], a
[1], a
[2], a
[3],
638 be16toh(sa
->in6
.sin6_port
));
642 a
[0], a
[1], a
[2], a
[3]);
646 char a
[INET6_ADDRSTRLEN
];
648 inet_ntop(AF_INET6
, &sa
->in6
.sin6_addr
, a
, sizeof(a
));
654 be16toh(sa
->in6
.sin6_port
));
668 if (salen
<= offsetof(struct sockaddr_un
, sun_path
) ||
669 (sa
->un
.sun_path
[0] == 0 && salen
== offsetof(struct sockaddr_un
, sun_path
) + 1))
670 /* The name must have at least one character (and the leading NUL does not count) */
671 p
= strdup("<unnamed>");
673 /* Note that we calculate the path pointer here through the .un_buffer[] field, in order to
674 * outtrick bounds checking tools such as ubsan, which are too smart for their own good: on
675 * Linux the kernel may return sun_path[] data one byte longer than the declared size of the
677 char *path
= (char*) sa
->un_buffer
+ offsetof(struct sockaddr_un
, sun_path
);
678 size_t path_len
= salen
- offsetof(struct sockaddr_un
, sun_path
);
681 /* Abstract socket. When parsing address information from, we
682 * explicitly reject overly long paths and paths with embedded NULs.
683 * But we might get such a socket from the outside. Let's return
684 * something meaningful and printable in this case. */
686 _cleanup_free_
char *e
= NULL
;
688 e
= cescape_length(path
+ 1, path_len
- 1);
694 if (path
[path_len
- 1] == '\0')
695 /* We expect a terminating NUL and don't print it */
698 p
= cescape_length(path
, path_len
);
708 if (sa
->vm
.svm_cid
== VMADDR_CID_ANY
)
709 r
= asprintf(&p
, "vsock::%u", sa
->vm
.svm_port
);
711 r
= asprintf(&p
, "vsock:%u:%u", sa
->vm
.svm_cid
, sa
->vm
.svm_port
);
713 r
= asprintf(&p
, "vsock:%u", sa
->vm
.svm_cid
);
726 int getpeername_pretty(int fd
, bool include_port
, char **ret
) {
727 union sockaddr_union sa
;
728 socklen_t salen
= sizeof(sa
);
734 if (getpeername(fd
, &sa
.sa
, &salen
) < 0)
737 if (sa
.sa
.sa_family
== AF_UNIX
) {
738 struct ucred ucred
= {};
740 /* UNIX connection sockets are anonymous, so let's use
741 * PID/UID as pretty credentials instead */
743 r
= getpeercred(fd
, &ucred
);
747 if (asprintf(ret
, "PID "PID_FMT
"/UID "UID_FMT
, ucred
.pid
, ucred
.uid
) < 0)
753 /* For remote sockets we translate IPv6 addresses back to IPv4
754 * if applicable, since that's nicer. */
756 return sockaddr_pretty(&sa
.sa
, salen
, true, include_port
, ret
);
759 int getsockname_pretty(int fd
, char **ret
) {
760 union sockaddr_union sa
;
761 socklen_t salen
= sizeof(sa
);
766 if (getsockname(fd
, &sa
.sa
, &salen
) < 0)
769 /* For local sockets we do not translate IPv6 addresses back
770 * to IPv6 if applicable, since this is usually used for
771 * listening sockets where the difference between IPv4 and
774 return sockaddr_pretty(&sa
.sa
, salen
, false, true, ret
);
777 int socknameinfo_pretty(union sockaddr_union
*sa
, socklen_t salen
, char **_ret
) {
779 char host
[NI_MAXHOST
], *ret
;
783 r
= getnameinfo(&sa
->sa
, salen
, host
, sizeof(host
), NULL
, 0, IDN_FLAGS
);
785 int saved_errno
= errno
;
787 r
= sockaddr_pretty(&sa
->sa
, salen
, true, true, &ret
);
791 log_debug_errno(saved_errno
, "getnameinfo(%s) failed: %m", ret
);
802 static const char* const netlink_family_table
[] = {
803 [NETLINK_ROUTE
] = "route",
804 [NETLINK_FIREWALL
] = "firewall",
805 [NETLINK_INET_DIAG
] = "inet-diag",
806 [NETLINK_NFLOG
] = "nflog",
807 [NETLINK_XFRM
] = "xfrm",
808 [NETLINK_SELINUX
] = "selinux",
809 [NETLINK_ISCSI
] = "iscsi",
810 [NETLINK_AUDIT
] = "audit",
811 [NETLINK_FIB_LOOKUP
] = "fib-lookup",
812 [NETLINK_CONNECTOR
] = "connector",
813 [NETLINK_NETFILTER
] = "netfilter",
814 [NETLINK_IP6_FW
] = "ip6-fw",
815 [NETLINK_DNRTMSG
] = "dnrtmsg",
816 [NETLINK_KOBJECT_UEVENT
] = "kobject-uevent",
817 [NETLINK_GENERIC
] = "generic",
818 [NETLINK_SCSITRANSPORT
] = "scsitransport",
819 [NETLINK_ECRYPTFS
] = "ecryptfs",
820 [NETLINK_RDMA
] = "rdma",
823 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(netlink_family
, int, INT_MAX
);
825 static const char* const socket_address_bind_ipv6_only_table
[_SOCKET_ADDRESS_BIND_IPV6_ONLY_MAX
] = {
826 [SOCKET_ADDRESS_DEFAULT
] = "default",
827 [SOCKET_ADDRESS_BOTH
] = "both",
828 [SOCKET_ADDRESS_IPV6_ONLY
] = "ipv6-only"
831 DEFINE_STRING_TABLE_LOOKUP(socket_address_bind_ipv6_only
, SocketAddressBindIPv6Only
);
833 SocketAddressBindIPv6Only
socket_address_bind_ipv6_only_or_bool_from_string(const char *n
) {
836 r
= parse_boolean(n
);
838 return SOCKET_ADDRESS_IPV6_ONLY
;
840 return SOCKET_ADDRESS_BOTH
;
842 return socket_address_bind_ipv6_only_from_string(n
);
845 bool sockaddr_equal(const union sockaddr_union
*a
, const union sockaddr_union
*b
) {
849 if (a
->sa
.sa_family
!= b
->sa
.sa_family
)
852 if (a
->sa
.sa_family
== AF_INET
)
853 return a
->in
.sin_addr
.s_addr
== b
->in
.sin_addr
.s_addr
;
855 if (a
->sa
.sa_family
== AF_INET6
)
856 return memcmp(&a
->in6
.sin6_addr
, &b
->in6
.sin6_addr
, sizeof(a
->in6
.sin6_addr
)) == 0;
858 if (a
->sa
.sa_family
== AF_VSOCK
)
859 return a
->vm
.svm_cid
== b
->vm
.svm_cid
;
864 int fd_inc_sndbuf(int fd
, size_t n
) {
866 socklen_t l
= sizeof(value
);
868 r
= getsockopt(fd
, SOL_SOCKET
, SO_SNDBUF
, &value
, &l
);
869 if (r
>= 0 && l
== sizeof(value
) && (size_t) value
>= n
*2)
872 /* If we have the privileges we will ignore the kernel limit. */
874 if (setsockopt_int(fd
, SOL_SOCKET
, SO_SNDBUF
, n
) < 0) {
875 r
= setsockopt_int(fd
, SOL_SOCKET
, SO_SNDBUFFORCE
, n
);
883 int fd_inc_rcvbuf(int fd
, size_t n
) {
885 socklen_t l
= sizeof(value
);
887 r
= getsockopt(fd
, SOL_SOCKET
, SO_RCVBUF
, &value
, &l
);
888 if (r
>= 0 && l
== sizeof(value
) && (size_t) value
>= n
*2)
891 /* If we have the privileges we will ignore the kernel limit. */
893 if (setsockopt_int(fd
, SOL_SOCKET
, SO_RCVBUF
, n
) < 0) {
894 r
= setsockopt_int(fd
, SOL_SOCKET
, SO_RCVBUFFORCE
, n
);
902 static const char* const ip_tos_table
[] = {
903 [IPTOS_LOWDELAY
] = "low-delay",
904 [IPTOS_THROUGHPUT
] = "throughput",
905 [IPTOS_RELIABILITY
] = "reliability",
906 [IPTOS_LOWCOST
] = "low-cost",
909 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(ip_tos
, int, 0xff);
911 bool ifname_valid(const char *p
) {
914 /* Checks whether a network interface name is valid. This is inspired by dev_valid_name() in the kernel sources
915 * but slightly stricter, as we only allow non-control, non-space ASCII characters in the interface name. We
916 * also don't permit names that only container numbers, to avoid confusion with numeric interface indexes. */
921 if (strlen(p
) >= IFNAMSIZ
)
924 if (dot_or_dot_dot(p
))
928 if ((unsigned char) *p
>= 127U)
931 if ((unsigned char) *p
<= 32U)
934 if (IN_SET(*p
, ':', '/'))
937 numeric
= numeric
&& (*p
>= '0' && *p
<= '9');
947 bool address_label_valid(const char *p
) {
952 if (strlen(p
) >= IFNAMSIZ
)
956 if ((uint8_t) *p
>= 127U)
959 if ((uint8_t) *p
<= 31U)
967 int getpeercred(int fd
, struct ucred
*ucred
) {
968 socklen_t n
= sizeof(struct ucred
);
975 r
= getsockopt(fd
, SOL_SOCKET
, SO_PEERCRED
, &u
, &n
);
979 if (n
!= sizeof(struct ucred
))
982 /* Check if the data is actually useful and not suppressed due to namespacing issues */
983 if (!pid_is_valid(u
.pid
))
986 /* Note that we don't check UID/GID here, as namespace translation works differently there: instead of
987 * receiving in "invalid" user/group we get the overflow UID/GID. */
993 int getpeersec(int fd
, char **ret
) {
994 _cleanup_free_
char *s
= NULL
;
1001 s
= new0(char, n
+1);
1005 if (getsockopt(fd
, SOL_SOCKET
, SO_PEERSEC
, s
, &n
) >= 0)
1008 if (errno
!= ERANGE
)
1022 int getpeergroups(int fd
, gid_t
**ret
) {
1023 socklen_t n
= sizeof(gid_t
) * 64;
1024 _cleanup_free_ gid_t
*d
= NULL
;
1034 if (getsockopt(fd
, SOL_SOCKET
, SO_PEERGROUPS
, d
, &n
) >= 0)
1037 if (errno
!= ERANGE
)
1043 assert_se(n
% sizeof(gid_t
) == 0);
1046 if ((socklen_t
) (int) n
!= n
)
1054 ssize_t
send_one_fd_iov_sa(
1057 struct iovec
*iov
, size_t iovlen
,
1058 const struct sockaddr
*sa
, socklen_t len
,
1062 struct cmsghdr cmsghdr
;
1063 uint8_t buf
[CMSG_SPACE(sizeof(int))];
1065 struct msghdr mh
= {
1066 .msg_name
= (struct sockaddr
*) sa
,
1069 .msg_iovlen
= iovlen
,
1073 assert(transport_fd
>= 0);
1076 * We need either an FD or data to send.
1077 * If there's nothing, return an error.
1083 struct cmsghdr
*cmsg
;
1085 mh
.msg_control
= &control
;
1086 mh
.msg_controllen
= sizeof(control
);
1088 cmsg
= CMSG_FIRSTHDR(&mh
);
1089 cmsg
->cmsg_level
= SOL_SOCKET
;
1090 cmsg
->cmsg_type
= SCM_RIGHTS
;
1091 cmsg
->cmsg_len
= CMSG_LEN(sizeof(int));
1092 memcpy(CMSG_DATA(cmsg
), &fd
, sizeof(int));
1094 mh
.msg_controllen
= CMSG_SPACE(sizeof(int));
1096 k
= sendmsg(transport_fd
, &mh
, MSG_NOSIGNAL
| flags
);
1098 return (ssize_t
) -errno
;
1106 const struct sockaddr
*sa
, socklen_t len
,
1111 return (int) send_one_fd_iov_sa(transport_fd
, fd
, NULL
, 0, sa
, len
, flags
);
1114 ssize_t
receive_one_fd_iov(
1116 struct iovec
*iov
, size_t iovlen
,
1121 struct cmsghdr cmsghdr
;
1122 uint8_t buf
[CMSG_SPACE(sizeof(int))];
1124 struct msghdr mh
= {
1125 .msg_control
= &control
,
1126 .msg_controllen
= sizeof(control
),
1128 .msg_iovlen
= iovlen
,
1130 struct cmsghdr
*cmsg
, *found
= NULL
;
1133 assert(transport_fd
>= 0);
1137 * Receive a single FD via @transport_fd. We don't care for
1138 * the transport-type. We retrieve a single FD at most, so for
1139 * packet-based transports, the caller must ensure to send
1140 * only a single FD per packet. This is best used in
1141 * combination with send_one_fd().
1144 k
= recvmsg(transport_fd
, &mh
, MSG_CMSG_CLOEXEC
| flags
);
1146 return (ssize_t
) -errno
;
1148 CMSG_FOREACH(cmsg
, &mh
) {
1149 if (cmsg
->cmsg_level
== SOL_SOCKET
&&
1150 cmsg
->cmsg_type
== SCM_RIGHTS
&&
1151 cmsg
->cmsg_len
== CMSG_LEN(sizeof(int))) {
1159 cmsg_close_all(&mh
);
1161 /* If didn't receive an FD or any data, return an error. */
1162 if (k
== 0 && !found
)
1166 *ret_fd
= *(int*) CMSG_DATA(found
);
1173 int receive_one_fd(int transport_fd
, int flags
) {
1177 k
= receive_one_fd_iov(transport_fd
, NULL
, 0, flags
, &fd
);
1181 /* k must be negative, since receive_one_fd_iov() only returns
1182 * a positive value if data was received through the iov. */
1187 ssize_t
next_datagram_size_fd(int fd
) {
1191 /* This is a bit like FIONREAD/SIOCINQ, however a bit more powerful. The difference being: recv(MSG_PEEK) will
1192 * actually cause the next datagram in the queue to be validated regarding checksums, which FIONREAD doesn't
1193 * do. This difference is actually of major importance as we need to be sure that the size returned here
1194 * actually matches what we will read with recvmsg() next, as otherwise we might end up allocating a buffer of
1195 * the wrong size. */
1197 l
= recv(fd
, NULL
, 0, MSG_PEEK
|MSG_TRUNC
);
1199 if (IN_SET(errno
, EOPNOTSUPP
, EFAULT
))
1212 /* Some sockets (AF_PACKET) do not support null-sized recv() with MSG_TRUNC set, let's fall back to FIONREAD
1213 * for them. Checksums don't matter for raw sockets anyway, hence this should be fine. */
1215 if (ioctl(fd
, FIONREAD
, &k
) < 0)
1221 int flush_accept(int fd
) {
1223 struct pollfd pollfd
= {
1229 /* Similar to flush_fd() but flushes all incoming connection by accepting them and immediately closing them. */
1234 r
= poll(&pollfd
, 1, 0);
1244 cfd
= accept4(fd
, NULL
, NULL
, SOCK_NONBLOCK
|SOCK_CLOEXEC
);
1249 if (errno
== EAGAIN
)
1259 struct cmsghdr
* cmsg_find(struct msghdr
*mh
, int level
, int type
, socklen_t length
) {
1260 struct cmsghdr
*cmsg
;
1264 CMSG_FOREACH(cmsg
, mh
)
1265 if (cmsg
->cmsg_level
== level
&&
1266 cmsg
->cmsg_type
== type
&&
1267 (length
== (socklen_t
) -1 || length
== cmsg
->cmsg_len
))
1273 int socket_ioctl_fd(void) {
1276 /* Create a socket to invoke the various network interface ioctl()s on. Traditionally only AF_INET was good for
1277 * that. Since kernel 4.6 AF_NETLINK works for this too. We first try to use AF_INET hence, but if that's not
1278 * available (for example, because it is made unavailable via SECCOMP or such), we'll fall back to the more
1279 * generic AF_NETLINK. */
1281 fd
= socket(AF_INET
, SOCK_DGRAM
|SOCK_CLOEXEC
, 0);
1283 fd
= socket(AF_NETLINK
, SOCK_RAW
|SOCK_CLOEXEC
, NETLINK_GENERIC
);
1290 int sockaddr_un_unlink(const struct sockaddr_un
*sa
) {
1291 const char *p
, * nul
;
1295 if (sa
->sun_family
!= AF_UNIX
)
1298 if (sa
->sun_path
[0] == 0) /* Nothing to do for abstract sockets */
1301 /* The path in .sun_path is not necessarily NUL terminated. Let's fix that. */
1302 nul
= memchr(sa
->sun_path
, 0, sizeof(sa
->sun_path
));
1306 p
= memdupa_suffix0(sa
->sun_path
, sizeof(sa
->sun_path
));
1314 int sockaddr_un_set_path(struct sockaddr_un
*ret
, const char *path
) {
1320 /* Initialize ret->sun_path from the specified argument. This will interpret paths starting with '@' as
1321 * abstract namespace sockets, and those starting with '/' as regular filesystem sockets. It won't accept
1322 * anything else (i.e. no relative paths), to avoid ambiguities. Note that this function cannot be used to
1323 * reference paths in the abstract namespace that include NUL bytes in the name. */
1328 if (!IN_SET(path
[0], '/', '@'))
1333 /* Don't allow paths larger than the space in sockaddr_un. Note that we are a tiny bit more restrictive than
1334 * the kernel is: we insist on NUL termination (both for abstract namespace and regular file system socket
1335 * addresses!), which the kernel doesn't. We do this to reduce chance of incompatibility with other apps that
1336 * do not expect non-NUL terminated file system path*/
1337 if (l
+1 > sizeof(ret
->sun_path
))
1340 *ret
= (struct sockaddr_un
) {
1341 .sun_family
= AF_UNIX
,
1344 if (path
[0] == '@') {
1345 /* Abstract namespace socket */
1346 memcpy(ret
->sun_path
+ 1, path
+ 1, l
); /* copy *with* trailing NUL byte */
1347 return (int) (offsetof(struct sockaddr_un
, sun_path
) + l
); /* 🔥 *don't* 🔥 include trailing NUL in size */
1350 assert(path
[0] == '/');
1352 /* File system socket */
1353 memcpy(ret
->sun_path
, path
, l
+ 1); /* copy *with* trailing NUL byte */
1354 return (int) (offsetof(struct sockaddr_un
, sun_path
) + l
+ 1); /* include trailing NUL in size */
1358 int socket_bind_to_ifname(int fd
, const char *ifname
) {
1361 /* Call with NULL to drop binding */
1363 if (setsockopt(fd
, SOL_SOCKET
, SO_BINDTODEVICE
, ifname
, strlen_ptr(ifname
)) < 0)
1369 int socket_bind_to_ifindex(int fd
, int ifindex
) {
1370 char ifname
[IFNAMSIZ
] = "";
1376 if (setsockopt(fd
, SOL_SOCKET
, SO_BINDTODEVICE
, NULL
, 0) < 0)
1382 if (setsockopt(fd
, SOL_SOCKET
, SO_BINDTOIFINDEX
, &ifindex
, sizeof(ifindex
)) >= 0)
1384 if (errno
!= ENOPROTOOPT
)
1387 /* Fall back to SO_BINDTODEVICE on kernels < 5.0 which didn't have SO_BINDTOIFINDEX */
1388 if (!if_indextoname(ifindex
, ifname
))
1391 return socket_bind_to_ifname(fd
, ifname
);