1 /* SPDX-License-Identifier: LGPL-2.1+ */
8 #include <netinet/ip.h>
17 #include "alloc-util.h"
18 #include "errno-util.h"
22 #include "format-util.h"
25 #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 "user-util.h"
38 # define IDN_FLAGS NI_IDN
43 static const char* const socket_address_type_table
[] = {
44 [SOCK_STREAM
] = "Stream",
45 [SOCK_DGRAM
] = "Datagram",
47 [SOCK_RDM
] = "ReliableDatagram",
48 [SOCK_SEQPACKET
] = "SequentialPacket",
49 [SOCK_DCCP
] = "DatagramCongestionControl",
52 DEFINE_STRING_TABLE_LOOKUP(socket_address_type
, int);
54 int socket_address_parse(SocketAddress
*a
, const char *s
) {
55 _cleanup_free_
char *n
= NULL
;
62 *a
= (SocketAddress
) {
69 /* IPv6 in [x:.....:z]:p notation */
75 n
= strndup(s
+1, e
-s
-1);
80 if (inet_pton(AF_INET6
, n
, &a
->sockaddr
.in6
.sin6_addr
) <= 0)
81 return errno
> 0 ? -errno
: -EINVAL
;
88 r
= parse_ip_port(e
, &port
);
92 a
->sockaddr
.in6
.sin6_family
= AF_INET6
;
93 a
->sockaddr
.in6
.sin6_port
= htobe16(port
);
94 a
->size
= sizeof(struct sockaddr_in6
);
96 } else if (*s
== '/') {
102 if (l
>= sizeof(a
->sockaddr
.un
.sun_path
)) /* Note that we refuse non-NUL-terminated sockets when
103 * parsing (the kernel itself is less strict here in what it
107 a
->sockaddr
.un
.sun_family
= AF_UNIX
;
108 memcpy(a
->sockaddr
.un
.sun_path
, s
, l
);
109 a
->size
= offsetof(struct sockaddr_un
, sun_path
) + l
+ 1;
111 } else if (*s
== '@') {
112 /* Abstract AF_UNIX socket */
116 if (l
>= sizeof(a
->sockaddr
.un
.sun_path
) - 1) /* Note that we refuse non-NUL-terminated sockets here
117 * when parsing, even though abstract namespace sockets
118 * explicitly allow embedded NUL bytes and don't consider
119 * them special. But it's simply annoying to debug such
123 a
->sockaddr
.un
.sun_family
= AF_UNIX
;
124 memcpy(a
->sockaddr
.un
.sun_path
+1, s
+1, l
);
125 a
->size
= offsetof(struct sockaddr_un
, sun_path
) + 1 + l
;
127 } else if (startswith(s
, "vsock:")) {
128 /* AF_VSOCK socket in vsock:cid:port notation */
129 const char *cid_start
= s
+ STRLEN("vsock:");
132 e
= strchr(cid_start
, ':');
136 r
= safe_atou(e
+1, &port
);
140 n
= strndup(cid_start
, e
- cid_start
);
145 r
= safe_atou(n
, &a
->sockaddr
.vm
.svm_cid
);
149 a
->sockaddr
.vm
.svm_cid
= VMADDR_CID_ANY
;
151 a
->sockaddr
.vm
.svm_family
= AF_VSOCK
;
152 a
->sockaddr
.vm
.svm_port
= port
;
153 a
->size
= sizeof(struct sockaddr_vm
);
160 r
= parse_ip_port(e
+ 1, &port
);
168 /* IPv4 in w.x.y.z:p notation? */
169 r
= inet_pton(AF_INET
, n
, &a
->sockaddr
.in
.sin_addr
);
174 /* Gotcha, it's a traditional IPv4 address */
175 a
->sockaddr
.in
.sin_family
= AF_INET
;
176 a
->sockaddr
.in
.sin_port
= htobe16(port
);
177 a
->size
= sizeof(struct sockaddr_in
);
181 if (strlen(n
) > IF_NAMESIZE
-1)
184 /* Uh, our last resort, an interface name */
185 idx
= if_nametoindex(n
);
189 a
->sockaddr
.in6
.sin6_family
= AF_INET6
;
190 a
->sockaddr
.in6
.sin6_port
= htobe16(port
);
191 a
->sockaddr
.in6
.sin6_scope_id
= idx
;
192 a
->sockaddr
.in6
.sin6_addr
= in6addr_any
;
193 a
->size
= sizeof(struct sockaddr_in6
);
198 r
= parse_ip_port(s
, &port
);
202 if (socket_ipv6_is_supported()) {
203 a
->sockaddr
.in6
.sin6_family
= AF_INET6
;
204 a
->sockaddr
.in6
.sin6_port
= htobe16(port
);
205 a
->sockaddr
.in6
.sin6_addr
= in6addr_any
;
206 a
->size
= sizeof(struct sockaddr_in6
);
208 a
->sockaddr
.in
.sin_family
= AF_INET
;
209 a
->sockaddr
.in
.sin_port
= htobe16(port
);
210 a
->sockaddr
.in
.sin_addr
.s_addr
= INADDR_ANY
;
211 a
->size
= sizeof(struct sockaddr_in
);
219 int socket_address_parse_and_warn(SocketAddress
*a
, const char *s
) {
223 /* Similar to socket_address_parse() but warns for IPv6 sockets when we don't support them. */
225 r
= socket_address_parse(&b
, s
);
229 if (!socket_ipv6_is_supported() && b
.sockaddr
.sa
.sa_family
== AF_INET6
) {
230 log_warning("Binding to IPv6 address not available since kernel does not support IPv6.");
231 return -EAFNOSUPPORT
;
238 int socket_address_parse_netlink(SocketAddress
*a
, const char *s
) {
239 _cleanup_free_
char *word
= NULL
;
249 r
= extract_first_word(&s
, &word
, NULL
, 0);
255 family
= netlink_family_from_string(word
);
260 r
= safe_atou(s
, &group
);
265 a
->sockaddr
.nl
.nl_family
= AF_NETLINK
;
266 a
->sockaddr
.nl
.nl_groups
= group
;
269 a
->size
= sizeof(struct sockaddr_nl
);
270 a
->protocol
= family
;
275 int socket_address_verify(const SocketAddress
*a
, bool strict
) {
278 /* With 'strict' we enforce additional sanity constraints which are not set by the standard,
279 * but should only apply to sockets we create ourselves. */
281 switch (socket_address_family(a
)) {
284 if (a
->size
!= sizeof(struct sockaddr_in
))
287 if (a
->sockaddr
.in
.sin_port
== 0)
290 if (!IN_SET(a
->type
, SOCK_STREAM
, SOCK_DGRAM
))
296 if (a
->size
!= sizeof(struct sockaddr_in6
))
299 if (a
->sockaddr
.in6
.sin6_port
== 0)
302 if (!IN_SET(a
->type
, SOCK_STREAM
, SOCK_DGRAM
))
308 if (a
->size
< offsetof(struct sockaddr_un
, sun_path
))
310 if (a
->size
> sizeof(struct sockaddr_un
) + !strict
)
311 /* If !strict, allow one extra byte, since getsockname() on Linux will append
312 * a NUL byte if we have path sockets that are above sun_path's full size. */
315 if (a
->size
> offsetof(struct sockaddr_un
, sun_path
) &&
316 a
->sockaddr
.un
.sun_path
[0] != 0 &&
318 /* Only validate file system sockets here, and only in strict mode */
321 e
= memchr(a
->sockaddr
.un
.sun_path
, 0, sizeof(a
->sockaddr
.un
.sun_path
));
323 /* If there's an embedded NUL byte, make sure the size of the socket address matches it */
324 if (a
->size
!= offsetof(struct sockaddr_un
, sun_path
) + (e
- a
->sockaddr
.un
.sun_path
) + 1)
327 /* If there's no embedded NUL byte, then then the size needs to match the whole
328 * structure or the structure with one extra NUL byte suffixed. (Yeah, Linux is awful,
329 * and considers both equivalent: getsockname() even extends sockaddr_un beyond its
330 * size if the path is non NUL terminated.)*/
331 if (!IN_SET(a
->size
, sizeof(a
->sockaddr
.un
.sun_path
), sizeof(a
->sockaddr
.un
.sun_path
)+1))
336 if (!IN_SET(a
->type
, SOCK_STREAM
, SOCK_DGRAM
, SOCK_SEQPACKET
))
343 if (a
->size
!= sizeof(struct sockaddr_nl
))
346 if (!IN_SET(a
->type
, SOCK_RAW
, SOCK_DGRAM
))
352 if (a
->size
!= sizeof(struct sockaddr_vm
))
355 if (!IN_SET(a
->type
, SOCK_STREAM
, SOCK_DGRAM
))
361 return -EAFNOSUPPORT
;
365 int socket_address_print(const SocketAddress
*a
, char **ret
) {
371 r
= socket_address_verify(a
, false); /* We do non-strict validation, because we want to be
372 * able to pretty-print any socket the kernel considers
373 * valid. We still need to do validation to know if we
374 * can meaningfully print the address. */
378 if (socket_address_family(a
) == AF_NETLINK
) {
379 _cleanup_free_
char *sfamily
= NULL
;
381 r
= netlink_family_to_string_alloc(a
->protocol
, &sfamily
);
385 r
= asprintf(ret
, "%s %u", sfamily
, a
->sockaddr
.nl
.nl_groups
);
392 return sockaddr_pretty(&a
->sockaddr
.sa
, a
->size
, false, true, ret
);
395 bool socket_address_can_accept(const SocketAddress
*a
) {
399 IN_SET(a
->type
, SOCK_STREAM
, SOCK_SEQPACKET
);
402 bool socket_address_equal(const SocketAddress
*a
, const SocketAddress
*b
) {
406 /* Invalid addresses are unequal to all */
407 if (socket_address_verify(a
, false) < 0 ||
408 socket_address_verify(b
, false) < 0)
411 if (a
->type
!= b
->type
)
414 if (socket_address_family(a
) != socket_address_family(b
))
417 switch (socket_address_family(a
)) {
420 if (a
->sockaddr
.in
.sin_addr
.s_addr
!= b
->sockaddr
.in
.sin_addr
.s_addr
)
423 if (a
->sockaddr
.in
.sin_port
!= b
->sockaddr
.in
.sin_port
)
429 if (memcmp(&a
->sockaddr
.in6
.sin6_addr
, &b
->sockaddr
.in6
.sin6_addr
, sizeof(a
->sockaddr
.in6
.sin6_addr
)) != 0)
432 if (a
->sockaddr
.in6
.sin6_port
!= b
->sockaddr
.in6
.sin6_port
)
438 if (a
->size
<= offsetof(struct sockaddr_un
, sun_path
) ||
439 b
->size
<= offsetof(struct sockaddr_un
, sun_path
))
442 if ((a
->sockaddr
.un
.sun_path
[0] == 0) != (b
->sockaddr
.un
.sun_path
[0] == 0))
445 if (a
->sockaddr
.un
.sun_path
[0]) {
446 if (!path_equal_or_files_same(a
->sockaddr
.un
.sun_path
, b
->sockaddr
.un
.sun_path
, 0))
449 if (a
->size
!= b
->size
)
452 if (memcmp(a
->sockaddr
.un
.sun_path
, b
->sockaddr
.un
.sun_path
, a
->size
) != 0)
459 if (a
->protocol
!= b
->protocol
)
462 if (a
->sockaddr
.nl
.nl_groups
!= b
->sockaddr
.nl
.nl_groups
)
468 if (a
->sockaddr
.vm
.svm_cid
!= b
->sockaddr
.vm
.svm_cid
)
471 if (a
->sockaddr
.vm
.svm_port
!= b
->sockaddr
.vm
.svm_port
)
477 /* Cannot compare, so we assume the addresses are different */
484 bool socket_address_is(const SocketAddress
*a
, const char *s
, int type
) {
485 struct SocketAddress b
;
490 if (socket_address_parse(&b
, s
) < 0)
495 return socket_address_equal(a
, &b
);
498 bool socket_address_is_netlink(const SocketAddress
*a
, const char *s
) {
499 struct SocketAddress b
;
504 if (socket_address_parse_netlink(&b
, s
) < 0)
507 return socket_address_equal(a
, &b
);
510 const char* socket_address_get_path(const SocketAddress
*a
) {
513 if (socket_address_family(a
) != AF_UNIX
)
516 if (a
->sockaddr
.un
.sun_path
[0] == 0)
519 /* Note that this is only safe because we know that there's an extra NUL byte after the sockaddr_un
520 * structure. On Linux AF_UNIX file system socket addresses don't have to be NUL terminated if they take up the
521 * full sun_path space. */
522 assert_cc(sizeof(union sockaddr_union
) >= sizeof(struct sockaddr_un
)+1);
523 return a
->sockaddr
.un
.sun_path
;
526 bool socket_ipv6_is_supported(void) {
527 if (access("/proc/net/if_inet6", F_OK
) != 0)
533 bool socket_address_matches_fd(const SocketAddress
*a
, int fd
) {
540 b
.size
= sizeof(b
.sockaddr
);
541 if (getsockname(fd
, &b
.sockaddr
.sa
, &b
.size
) < 0)
544 if (b
.sockaddr
.sa
.sa_family
!= a
->sockaddr
.sa
.sa_family
)
547 solen
= sizeof(b
.type
);
548 if (getsockopt(fd
, SOL_SOCKET
, SO_TYPE
, &b
.type
, &solen
) < 0)
551 if (b
.type
!= a
->type
)
554 if (a
->protocol
!= 0) {
555 solen
= sizeof(b
.protocol
);
556 if (getsockopt(fd
, SOL_SOCKET
, SO_PROTOCOL
, &b
.protocol
, &solen
) < 0)
559 if (b
.protocol
!= a
->protocol
)
563 return socket_address_equal(a
, &b
);
566 int sockaddr_port(const struct sockaddr
*_sa
, unsigned *ret_port
) {
567 union sockaddr_union
*sa
= (union sockaddr_union
*) _sa
;
569 /* Note, this returns the port as 'unsigned' rather than 'uint16_t', as AF_VSOCK knows larger ports */
573 switch (sa
->sa
.sa_family
) {
576 *ret_port
= be16toh(sa
->in
.sin_port
);
580 *ret_port
= be16toh(sa
->in6
.sin6_port
);
584 *ret_port
= sa
->vm
.svm_port
;
588 return -EAFNOSUPPORT
;
593 const struct sockaddr
*_sa
,
599 union sockaddr_union
*sa
= (union sockaddr_union
*) _sa
;
604 assert(salen
>= sizeof(sa
->sa
.sa_family
));
606 switch (sa
->sa
.sa_family
) {
611 a
= be32toh(sa
->in
.sin_addr
.s_addr
);
616 a
>> 24, (a
>> 16) & 0xFF, (a
>> 8) & 0xFF, a
& 0xFF,
617 be16toh(sa
->in
.sin_port
));
621 a
>> 24, (a
>> 16) & 0xFF, (a
>> 8) & 0xFF, a
& 0xFF);
628 static const unsigned char ipv4_prefix
[] = {
629 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xFF, 0xFF
632 if (translate_ipv6
&&
633 memcmp(&sa
->in6
.sin6_addr
, ipv4_prefix
, sizeof(ipv4_prefix
)) == 0) {
634 const uint8_t *a
= sa
->in6
.sin6_addr
.s6_addr
+12;
638 a
[0], a
[1], a
[2], a
[3],
639 be16toh(sa
->in6
.sin6_port
));
643 a
[0], a
[1], a
[2], a
[3]);
647 char a
[INET6_ADDRSTRLEN
];
649 inet_ntop(AF_INET6
, &sa
->in6
.sin6_addr
, a
, sizeof(a
));
655 be16toh(sa
->in6
.sin6_port
));
669 if (salen
<= offsetof(struct sockaddr_un
, sun_path
) ||
670 (sa
->un
.sun_path
[0] == 0 && salen
== offsetof(struct sockaddr_un
, sun_path
) + 1))
671 /* The name must have at least one character (and the leading NUL does not count) */
672 p
= strdup("<unnamed>");
674 /* Note that we calculate the path pointer here through the .un_buffer[] field, in order to
675 * outtrick bounds checking tools such as ubsan, which are too smart for their own good: on
676 * Linux the kernel may return sun_path[] data one byte longer than the declared size of the
678 char *path
= (char*) sa
->un_buffer
+ offsetof(struct sockaddr_un
, sun_path
);
679 size_t path_len
= salen
- offsetof(struct sockaddr_un
, sun_path
);
682 /* Abstract socket. When parsing address information from, we
683 * explicitly reject overly long paths and paths with embedded NULs.
684 * But we might get such a socket from the outside. Let's return
685 * something meaningful and printable in this case. */
687 _cleanup_free_
char *e
= NULL
;
689 e
= cescape_length(path
+ 1, path_len
- 1);
695 if (path
[path_len
- 1] == '\0')
696 /* We expect a terminating NUL and don't print it */
699 p
= cescape_length(path
, path_len
);
709 if (sa
->vm
.svm_cid
== VMADDR_CID_ANY
)
710 r
= asprintf(&p
, "vsock::%u", sa
->vm
.svm_port
);
712 r
= asprintf(&p
, "vsock:%u:%u", sa
->vm
.svm_cid
, sa
->vm
.svm_port
);
714 r
= asprintf(&p
, "vsock:%u", sa
->vm
.svm_cid
);
727 int getpeername_pretty(int fd
, bool include_port
, char **ret
) {
728 union sockaddr_union sa
;
729 socklen_t salen
= sizeof(sa
);
735 if (getpeername(fd
, &sa
.sa
, &salen
) < 0)
738 if (sa
.sa
.sa_family
== AF_UNIX
) {
739 struct ucred ucred
= {};
741 /* UNIX connection sockets are anonymous, so let's use
742 * PID/UID as pretty credentials instead */
744 r
= getpeercred(fd
, &ucred
);
748 if (asprintf(ret
, "PID "PID_FMT
"/UID "UID_FMT
, ucred
.pid
, ucred
.uid
) < 0)
754 /* For remote sockets we translate IPv6 addresses back to IPv4
755 * if applicable, since that's nicer. */
757 return sockaddr_pretty(&sa
.sa
, salen
, true, include_port
, ret
);
760 int getsockname_pretty(int fd
, char **ret
) {
761 union sockaddr_union sa
;
762 socklen_t salen
= sizeof(sa
);
767 if (getsockname(fd
, &sa
.sa
, &salen
) < 0)
770 /* For local sockets we do not translate IPv6 addresses back
771 * to IPv6 if applicable, since this is usually used for
772 * listening sockets where the difference between IPv4 and
775 return sockaddr_pretty(&sa
.sa
, salen
, false, true, ret
);
778 int socknameinfo_pretty(union sockaddr_union
*sa
, socklen_t salen
, char **_ret
) {
780 char host
[NI_MAXHOST
], *ret
;
784 r
= getnameinfo(&sa
->sa
, salen
, host
, sizeof(host
), NULL
, 0, IDN_FLAGS
);
786 int saved_errno
= errno
;
788 r
= sockaddr_pretty(&sa
->sa
, salen
, true, true, &ret
);
792 log_debug_errno(saved_errno
, "getnameinfo(%s) failed: %m", ret
);
803 static const char* const netlink_family_table
[] = {
804 [NETLINK_ROUTE
] = "route",
805 [NETLINK_FIREWALL
] = "firewall",
806 [NETLINK_INET_DIAG
] = "inet-diag",
807 [NETLINK_NFLOG
] = "nflog",
808 [NETLINK_XFRM
] = "xfrm",
809 [NETLINK_SELINUX
] = "selinux",
810 [NETLINK_ISCSI
] = "iscsi",
811 [NETLINK_AUDIT
] = "audit",
812 [NETLINK_FIB_LOOKUP
] = "fib-lookup",
813 [NETLINK_CONNECTOR
] = "connector",
814 [NETLINK_NETFILTER
] = "netfilter",
815 [NETLINK_IP6_FW
] = "ip6-fw",
816 [NETLINK_DNRTMSG
] = "dnrtmsg",
817 [NETLINK_KOBJECT_UEVENT
] = "kobject-uevent",
818 [NETLINK_GENERIC
] = "generic",
819 [NETLINK_SCSITRANSPORT
] = "scsitransport",
820 [NETLINK_ECRYPTFS
] = "ecryptfs",
821 [NETLINK_RDMA
] = "rdma",
824 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(netlink_family
, int, INT_MAX
);
826 static const char* const socket_address_bind_ipv6_only_table
[_SOCKET_ADDRESS_BIND_IPV6_ONLY_MAX
] = {
827 [SOCKET_ADDRESS_DEFAULT
] = "default",
828 [SOCKET_ADDRESS_BOTH
] = "both",
829 [SOCKET_ADDRESS_IPV6_ONLY
] = "ipv6-only"
832 DEFINE_STRING_TABLE_LOOKUP(socket_address_bind_ipv6_only
, SocketAddressBindIPv6Only
);
834 SocketAddressBindIPv6Only
socket_address_bind_ipv6_only_or_bool_from_string(const char *n
) {
837 r
= parse_boolean(n
);
839 return SOCKET_ADDRESS_IPV6_ONLY
;
841 return SOCKET_ADDRESS_BOTH
;
843 return socket_address_bind_ipv6_only_from_string(n
);
846 bool sockaddr_equal(const union sockaddr_union
*a
, const union sockaddr_union
*b
) {
850 if (a
->sa
.sa_family
!= b
->sa
.sa_family
)
853 if (a
->sa
.sa_family
== AF_INET
)
854 return a
->in
.sin_addr
.s_addr
== b
->in
.sin_addr
.s_addr
;
856 if (a
->sa
.sa_family
== AF_INET6
)
857 return memcmp(&a
->in6
.sin6_addr
, &b
->in6
.sin6_addr
, sizeof(a
->in6
.sin6_addr
)) == 0;
859 if (a
->sa
.sa_family
== AF_VSOCK
)
860 return a
->vm
.svm_cid
== b
->vm
.svm_cid
;
865 int fd_inc_sndbuf(int fd
, size_t n
) {
867 socklen_t l
= sizeof(value
);
869 r
= getsockopt(fd
, SOL_SOCKET
, SO_SNDBUF
, &value
, &l
);
870 if (r
>= 0 && l
== sizeof(value
) && (size_t) value
>= n
*2)
873 /* If we have the privileges we will ignore the kernel limit. */
875 if (setsockopt_int(fd
, SOL_SOCKET
, SO_SNDBUF
, n
) < 0) {
876 r
= setsockopt_int(fd
, SOL_SOCKET
, SO_SNDBUFFORCE
, n
);
884 int fd_inc_rcvbuf(int fd
, size_t n
) {
886 socklen_t l
= sizeof(value
);
888 r
= getsockopt(fd
, SOL_SOCKET
, SO_RCVBUF
, &value
, &l
);
889 if (r
>= 0 && l
== sizeof(value
) && (size_t) value
>= n
*2)
892 /* If we have the privileges we will ignore the kernel limit. */
894 if (setsockopt_int(fd
, SOL_SOCKET
, SO_RCVBUF
, n
) < 0) {
895 r
= setsockopt_int(fd
, SOL_SOCKET
, SO_RCVBUFFORCE
, n
);
903 static const char* const ip_tos_table
[] = {
904 [IPTOS_LOWDELAY
] = "low-delay",
905 [IPTOS_THROUGHPUT
] = "throughput",
906 [IPTOS_RELIABILITY
] = "reliability",
907 [IPTOS_LOWCOST
] = "low-cost",
910 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(ip_tos
, int, 0xff);
912 bool ifname_valid(const char *p
) {
915 /* Checks whether a network interface name is valid. This is inspired by dev_valid_name() in the kernel sources
916 * but slightly stricter, as we only allow non-control, non-space ASCII characters in the interface name. We
917 * also don't permit names that only container numbers, to avoid confusion with numeric interface indexes. */
922 if (strlen(p
) >= IFNAMSIZ
)
925 if (dot_or_dot_dot(p
))
929 if ((unsigned char) *p
>= 127U)
932 if ((unsigned char) *p
<= 32U)
935 if (IN_SET(*p
, ':', '/'))
938 numeric
= numeric
&& (*p
>= '0' && *p
<= '9');
948 bool address_label_valid(const char *p
) {
953 if (strlen(p
) >= IFNAMSIZ
)
957 if ((uint8_t) *p
>= 127U)
960 if ((uint8_t) *p
<= 31U)
968 int getpeercred(int fd
, struct ucred
*ucred
) {
969 socklen_t n
= sizeof(struct ucred
);
976 r
= getsockopt(fd
, SOL_SOCKET
, SO_PEERCRED
, &u
, &n
);
980 if (n
!= sizeof(struct ucred
))
983 /* Check if the data is actually useful and not suppressed due to namespacing issues */
984 if (!pid_is_valid(u
.pid
))
987 /* Note that we don't check UID/GID here, as namespace translation works differently there: instead of
988 * receiving in "invalid" user/group we get the overflow UID/GID. */
994 int getpeersec(int fd
, char **ret
) {
995 _cleanup_free_
char *s
= NULL
;
1002 s
= new0(char, n
+1);
1006 if (getsockopt(fd
, SOL_SOCKET
, SO_PEERSEC
, s
, &n
) >= 0)
1009 if (errno
!= ERANGE
)
1023 int getpeergroups(int fd
, gid_t
**ret
) {
1024 socklen_t n
= sizeof(gid_t
) * 64;
1025 _cleanup_free_ gid_t
*d
= NULL
;
1035 if (getsockopt(fd
, SOL_SOCKET
, SO_PEERGROUPS
, d
, &n
) >= 0)
1038 if (errno
!= ERANGE
)
1044 assert_se(n
% sizeof(gid_t
) == 0);
1047 if ((socklen_t
) (int) n
!= n
)
1055 ssize_t
send_one_fd_iov_sa(
1058 struct iovec
*iov
, size_t iovlen
,
1059 const struct sockaddr
*sa
, socklen_t len
,
1063 struct cmsghdr cmsghdr
;
1064 uint8_t buf
[CMSG_SPACE(sizeof(int))];
1066 struct msghdr mh
= {
1067 .msg_name
= (struct sockaddr
*) sa
,
1070 .msg_iovlen
= iovlen
,
1074 assert(transport_fd
>= 0);
1077 * We need either an FD or data to send.
1078 * If there's nothing, return an error.
1084 struct cmsghdr
*cmsg
;
1086 mh
.msg_control
= &control
;
1087 mh
.msg_controllen
= sizeof(control
);
1089 cmsg
= CMSG_FIRSTHDR(&mh
);
1090 cmsg
->cmsg_level
= SOL_SOCKET
;
1091 cmsg
->cmsg_type
= SCM_RIGHTS
;
1092 cmsg
->cmsg_len
= CMSG_LEN(sizeof(int));
1093 memcpy(CMSG_DATA(cmsg
), &fd
, sizeof(int));
1095 mh
.msg_controllen
= CMSG_SPACE(sizeof(int));
1097 k
= sendmsg(transport_fd
, &mh
, MSG_NOSIGNAL
| flags
);
1099 return (ssize_t
) -errno
;
1107 const struct sockaddr
*sa
, socklen_t len
,
1112 return (int) send_one_fd_iov_sa(transport_fd
, fd
, NULL
, 0, sa
, len
, flags
);
1115 ssize_t
receive_one_fd_iov(
1117 struct iovec
*iov
, size_t iovlen
,
1122 struct cmsghdr cmsghdr
;
1123 uint8_t buf
[CMSG_SPACE(sizeof(int))];
1125 struct msghdr mh
= {
1126 .msg_control
= &control
,
1127 .msg_controllen
= sizeof(control
),
1129 .msg_iovlen
= iovlen
,
1131 struct cmsghdr
*cmsg
, *found
= NULL
;
1134 assert(transport_fd
>= 0);
1138 * Receive a single FD via @transport_fd. We don't care for
1139 * the transport-type. We retrieve a single FD at most, so for
1140 * packet-based transports, the caller must ensure to send
1141 * only a single FD per packet. This is best used in
1142 * combination with send_one_fd().
1145 k
= recvmsg(transport_fd
, &mh
, MSG_CMSG_CLOEXEC
| flags
);
1147 return (ssize_t
) -errno
;
1149 CMSG_FOREACH(cmsg
, &mh
) {
1150 if (cmsg
->cmsg_level
== SOL_SOCKET
&&
1151 cmsg
->cmsg_type
== SCM_RIGHTS
&&
1152 cmsg
->cmsg_len
== CMSG_LEN(sizeof(int))) {
1160 cmsg_close_all(&mh
);
1162 /* If didn't receive an FD or any data, return an error. */
1163 if (k
== 0 && !found
)
1167 *ret_fd
= *(int*) CMSG_DATA(found
);
1174 int receive_one_fd(int transport_fd
, int flags
) {
1178 k
= receive_one_fd_iov(transport_fd
, NULL
, 0, flags
, &fd
);
1182 /* k must be negative, since receive_one_fd_iov() only returns
1183 * a positive value if data was received through the iov. */
1188 ssize_t
next_datagram_size_fd(int fd
) {
1192 /* This is a bit like FIONREAD/SIOCINQ, however a bit more powerful. The difference being: recv(MSG_PEEK) will
1193 * actually cause the next datagram in the queue to be validated regarding checksums, which FIONREAD doesn't
1194 * do. This difference is actually of major importance as we need to be sure that the size returned here
1195 * actually matches what we will read with recvmsg() next, as otherwise we might end up allocating a buffer of
1196 * the wrong size. */
1198 l
= recv(fd
, NULL
, 0, MSG_PEEK
|MSG_TRUNC
);
1200 if (IN_SET(errno
, EOPNOTSUPP
, EFAULT
))
1213 /* Some sockets (AF_PACKET) do not support null-sized recv() with MSG_TRUNC set, let's fall back to FIONREAD
1214 * for them. Checksums don't matter for raw sockets anyway, hence this should be fine. */
1216 if (ioctl(fd
, FIONREAD
, &k
) < 0)
1222 int flush_accept(int fd
) {
1224 struct pollfd pollfd
= {
1230 /* Similar to flush_fd() but flushes all incoming connection by accepting them and immediately closing them. */
1235 r
= poll(&pollfd
, 1, 0);
1245 cfd
= accept4(fd
, NULL
, NULL
, SOCK_NONBLOCK
|SOCK_CLOEXEC
);
1247 if (errno
== EAGAIN
)
1250 if (ERRNO_IS_ACCEPT_AGAIN(errno
))
1260 struct cmsghdr
* cmsg_find(struct msghdr
*mh
, int level
, int type
, socklen_t length
) {
1261 struct cmsghdr
*cmsg
;
1265 CMSG_FOREACH(cmsg
, mh
)
1266 if (cmsg
->cmsg_level
== level
&&
1267 cmsg
->cmsg_type
== type
&&
1268 (length
== (socklen_t
) -1 || length
== cmsg
->cmsg_len
))
1274 int socket_ioctl_fd(void) {
1277 /* Create a socket to invoke the various network interface ioctl()s on. Traditionally only AF_INET was good for
1278 * that. Since kernel 4.6 AF_NETLINK works for this too. We first try to use AF_INET hence, but if that's not
1279 * available (for example, because it is made unavailable via SECCOMP or such), we'll fall back to the more
1280 * generic AF_NETLINK. */
1282 fd
= socket(AF_INET
, SOCK_DGRAM
|SOCK_CLOEXEC
, 0);
1284 fd
= socket(AF_NETLINK
, SOCK_RAW
|SOCK_CLOEXEC
, NETLINK_GENERIC
);
1291 int sockaddr_un_unlink(const struct sockaddr_un
*sa
) {
1292 const char *p
, * nul
;
1296 if (sa
->sun_family
!= AF_UNIX
)
1299 if (sa
->sun_path
[0] == 0) /* Nothing to do for abstract sockets */
1302 /* The path in .sun_path is not necessarily NUL terminated. Let's fix that. */
1303 nul
= memchr(sa
->sun_path
, 0, sizeof(sa
->sun_path
));
1307 p
= memdupa_suffix0(sa
->sun_path
, sizeof(sa
->sun_path
));
1315 int sockaddr_un_set_path(struct sockaddr_un
*ret
, const char *path
) {
1321 /* Initialize ret->sun_path from the specified argument. This will interpret paths starting with '@' as
1322 * abstract namespace sockets, and those starting with '/' as regular filesystem sockets. It won't accept
1323 * anything else (i.e. no relative paths), to avoid ambiguities. Note that this function cannot be used to
1324 * reference paths in the abstract namespace that include NUL bytes in the name. */
1329 if (!IN_SET(path
[0], '/', '@'))
1334 /* Don't allow paths larger than the space in sockaddr_un. Note that we are a tiny bit more restrictive than
1335 * the kernel is: we insist on NUL termination (both for abstract namespace and regular file system socket
1336 * addresses!), which the kernel doesn't. We do this to reduce chance of incompatibility with other apps that
1337 * do not expect non-NUL terminated file system path*/
1338 if (l
+1 > sizeof(ret
->sun_path
))
1341 *ret
= (struct sockaddr_un
) {
1342 .sun_family
= AF_UNIX
,
1345 if (path
[0] == '@') {
1346 /* Abstract namespace socket */
1347 memcpy(ret
->sun_path
+ 1, path
+ 1, l
); /* copy *with* trailing NUL byte */
1348 return (int) (offsetof(struct sockaddr_un
, sun_path
) + l
); /* 🔥 *don't* 🔥 include trailing NUL in size */
1351 assert(path
[0] == '/');
1353 /* File system socket */
1354 memcpy(ret
->sun_path
, path
, l
+ 1); /* copy *with* trailing NUL byte */
1355 return (int) (offsetof(struct sockaddr_un
, sun_path
) + l
+ 1); /* include trailing NUL in size */
1359 int socket_bind_to_ifname(int fd
, const char *ifname
) {
1362 /* Call with NULL to drop binding */
1364 if (setsockopt(fd
, SOL_SOCKET
, SO_BINDTODEVICE
, ifname
, strlen_ptr(ifname
)) < 0)
1370 int socket_bind_to_ifindex(int fd
, int ifindex
) {
1371 char ifname
[IFNAMSIZ
] = "";
1377 if (setsockopt(fd
, SOL_SOCKET
, SO_BINDTODEVICE
, NULL
, 0) < 0)
1383 if (setsockopt(fd
, SOL_SOCKET
, SO_BINDTOIFINDEX
, &ifindex
, sizeof(ifindex
)) >= 0)
1385 if (errno
!= ENOPROTOOPT
)
1388 /* Fall back to SO_BINDTODEVICE on kernels < 5.0 which didn't have SO_BINDTOIFINDEX */
1389 if (!if_indextoname(ifindex
, ifname
))
1392 return socket_bind_to_ifname(fd
, ifname
);