]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/basic/socket-util.c
94089323b45fc81c7e8bf72795aa37847b8a9e0b
[thirdparty/systemd.git] / src / basic / socket-util.c
1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
2
3 /* Make sure the net/if.h header is included before any linux/ one */
4 #include <net/if.h>
5 #include <arpa/inet.h>
6 #include <errno.h>
7 #include <limits.h>
8 #include <netdb.h>
9 #include <netinet/ip.h>
10 #include <poll.h>
11 #include <stddef.h>
12 #include <stdint.h>
13 #include <stdio.h>
14 #include <stdlib.h>
15 #include <sys/ioctl.h>
16 #include <unistd.h>
17 #include <linux/if.h>
18
19 #include "alloc-util.h"
20 #include "errno-util.h"
21 #include "escape.h"
22 #include "fd-util.h"
23 #include "fileio.h"
24 #include "format-ifname.h"
25 #include "io-util.h"
26 #include "log.h"
27 #include "memory-util.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"
34 #include "strv.h"
35 #include "sysctl-util.h"
36 #include "user-util.h"
37 #include "utf8.h"
38
39 #if ENABLE_IDN
40 # define IDN_FLAGS NI_IDN
41 #else
42 # define IDN_FLAGS 0
43 #endif
44
45 /* From the kernel's include/net/scm.h */
46 #ifndef SCM_MAX_FD
47 # define SCM_MAX_FD 253
48 #endif
49
50 static const char* const socket_address_type_table[] = {
51 [SOCK_STREAM] = "Stream",
52 [SOCK_DGRAM] = "Datagram",
53 [SOCK_RAW] = "Raw",
54 [SOCK_RDM] = "ReliableDatagram",
55 [SOCK_SEQPACKET] = "SequentialPacket",
56 [SOCK_DCCP] = "DatagramCongestionControl",
57 };
58
59 DEFINE_STRING_TABLE_LOOKUP(socket_address_type, int);
60
61 int socket_address_verify(const SocketAddress *a, bool strict) {
62 assert(a);
63
64 /* With 'strict' we enforce additional sanity constraints which are not set by the standard,
65 * but should only apply to sockets we create ourselves. */
66
67 switch (socket_address_family(a)) {
68
69 case AF_INET:
70 if (a->size != sizeof(struct sockaddr_in))
71 return -EINVAL;
72
73 if (a->sockaddr.in.sin_port == 0)
74 return -EINVAL;
75
76 if (!IN_SET(a->type, 0, SOCK_STREAM, SOCK_DGRAM))
77 return -EINVAL;
78
79 return 0;
80
81 case AF_INET6:
82 if (a->size != sizeof(struct sockaddr_in6))
83 return -EINVAL;
84
85 if (a->sockaddr.in6.sin6_port == 0)
86 return -EINVAL;
87
88 if (!IN_SET(a->type, 0, SOCK_STREAM, SOCK_DGRAM))
89 return -EINVAL;
90
91 return 0;
92
93 case AF_UNIX:
94 if (a->size < offsetof(struct sockaddr_un, sun_path))
95 return -EINVAL;
96 if (a->size > sizeof(struct sockaddr_un) + !strict)
97 /* If !strict, allow one extra byte, since getsockname() on Linux will append
98 * a NUL byte if we have path sockets that are above sun_path's full size. */
99 return -EINVAL;
100
101 if (a->size > offsetof(struct sockaddr_un, sun_path) &&
102 a->sockaddr.un.sun_path[0] != 0 &&
103 strict) {
104 /* Only validate file system sockets here, and only in strict mode */
105 const char *e;
106
107 e = memchr(a->sockaddr.un.sun_path, 0, sizeof(a->sockaddr.un.sun_path));
108 if (e) {
109 /* If there's an embedded NUL byte, make sure the size of the socket address matches it */
110 if (a->size != offsetof(struct sockaddr_un, sun_path) + (e - a->sockaddr.un.sun_path) + 1)
111 return -EINVAL;
112 } else {
113 /* If there's no embedded NUL byte, then the size needs to match the whole
114 * structure or the structure with one extra NUL byte suffixed. (Yeah, Linux is awful,
115 * and considers both equivalent: getsockname() even extends sockaddr_un beyond its
116 * size if the path is non NUL terminated.) */
117 if (!IN_SET(a->size, sizeof(a->sockaddr.un.sun_path), sizeof(a->sockaddr.un.sun_path)+1))
118 return -EINVAL;
119 }
120 }
121
122 if (!IN_SET(a->type, 0, SOCK_STREAM, SOCK_DGRAM, SOCK_SEQPACKET))
123 return -EINVAL;
124
125 return 0;
126
127 case AF_NETLINK:
128
129 if (a->size != sizeof(struct sockaddr_nl))
130 return -EINVAL;
131
132 if (!IN_SET(a->type, 0, SOCK_RAW, SOCK_DGRAM))
133 return -EINVAL;
134
135 return 0;
136
137 case AF_VSOCK:
138 if (a->size != sizeof(struct sockaddr_vm))
139 return -EINVAL;
140
141 if (!IN_SET(a->type, 0, SOCK_STREAM, SOCK_DGRAM))
142 return -EINVAL;
143
144 return 0;
145
146 default:
147 return -EAFNOSUPPORT;
148 }
149 }
150
151 int socket_address_print(const SocketAddress *a, char **ret) {
152 int r;
153
154 assert(a);
155 assert(ret);
156
157 r = socket_address_verify(a, false); /* We do non-strict validation, because we want to be
158 * able to pretty-print any socket the kernel considers
159 * valid. We still need to do validation to know if we
160 * can meaningfully print the address. */
161 if (r < 0)
162 return r;
163
164 if (socket_address_family(a) == AF_NETLINK) {
165 _cleanup_free_ char *sfamily = NULL;
166
167 r = netlink_family_to_string_alloc(a->protocol, &sfamily);
168 if (r < 0)
169 return r;
170
171 r = asprintf(ret, "%s %u", sfamily, a->sockaddr.nl.nl_groups);
172 if (r < 0)
173 return -ENOMEM;
174
175 return 0;
176 }
177
178 return sockaddr_pretty(&a->sockaddr.sa, a->size, false, true, ret);
179 }
180
181 bool socket_address_can_accept(const SocketAddress *a) {
182 assert(a);
183
184 return
185 IN_SET(a->type, SOCK_STREAM, SOCK_SEQPACKET);
186 }
187
188 bool socket_address_equal(const SocketAddress *a, const SocketAddress *b) {
189 assert(a);
190 assert(b);
191
192 /* Invalid addresses are unequal to all */
193 if (socket_address_verify(a, false) < 0 ||
194 socket_address_verify(b, false) < 0)
195 return false;
196
197 if (a->type != b->type)
198 return false;
199
200 if (socket_address_family(a) != socket_address_family(b))
201 return false;
202
203 switch (socket_address_family(a)) {
204
205 case AF_INET:
206 if (a->sockaddr.in.sin_addr.s_addr != b->sockaddr.in.sin_addr.s_addr)
207 return false;
208
209 if (a->sockaddr.in.sin_port != b->sockaddr.in.sin_port)
210 return false;
211
212 break;
213
214 case AF_INET6:
215 if (memcmp(&a->sockaddr.in6.sin6_addr, &b->sockaddr.in6.sin6_addr, sizeof(a->sockaddr.in6.sin6_addr)) != 0)
216 return false;
217
218 if (a->sockaddr.in6.sin6_port != b->sockaddr.in6.sin6_port)
219 return false;
220
221 break;
222
223 case AF_UNIX:
224 if (a->size <= offsetof(struct sockaddr_un, sun_path) ||
225 b->size <= offsetof(struct sockaddr_un, sun_path))
226 return false;
227
228 if ((a->sockaddr.un.sun_path[0] == 0) != (b->sockaddr.un.sun_path[0] == 0))
229 return false;
230
231 if (a->sockaddr.un.sun_path[0]) {
232 if (!path_equal_or_inode_same(a->sockaddr.un.sun_path, b->sockaddr.un.sun_path, 0))
233 return false;
234 } else {
235 if (a->size != b->size)
236 return false;
237
238 if (memcmp(a->sockaddr.un.sun_path, b->sockaddr.un.sun_path, a->size) != 0)
239 return false;
240 }
241
242 break;
243
244 case AF_NETLINK:
245 if (a->protocol != b->protocol)
246 return false;
247
248 if (a->sockaddr.nl.nl_groups != b->sockaddr.nl.nl_groups)
249 return false;
250
251 break;
252
253 case AF_VSOCK:
254 if (a->sockaddr.vm.svm_cid != b->sockaddr.vm.svm_cid)
255 return false;
256
257 if (a->sockaddr.vm.svm_port != b->sockaddr.vm.svm_port)
258 return false;
259
260 break;
261
262 default:
263 /* Cannot compare, so we assume the addresses are different */
264 return false;
265 }
266
267 return true;
268 }
269
270 const char* socket_address_get_path(const SocketAddress *a) {
271 assert(a);
272
273 if (socket_address_family(a) != AF_UNIX)
274 return NULL;
275
276 if (a->sockaddr.un.sun_path[0] == 0)
277 return NULL;
278
279 /* Note that this is only safe because we know that there's an extra NUL byte after the sockaddr_un
280 * structure. On Linux AF_UNIX file system socket addresses don't have to be NUL terminated if they take up the
281 * full sun_path space. */
282 assert_cc(sizeof(union sockaddr_union) >= sizeof(struct sockaddr_un)+1);
283 return a->sockaddr.un.sun_path;
284 }
285
286 bool socket_ipv6_is_supported(void) {
287 static int cached = -1;
288
289 if (cached < 0) {
290
291 if (access("/proc/net/if_inet6", F_OK) < 0) {
292
293 if (errno != ENOENT) {
294 log_debug_errno(errno, "Unexpected error when checking whether /proc/net/if_inet6 exists: %m");
295 return false;
296 }
297
298 cached = false;
299 } else
300 cached = true;
301 }
302
303 return cached;
304 }
305
306 bool socket_ipv6_is_enabled(void) {
307 _cleanup_free_ char *v = NULL;
308 int r;
309
310 /* Much like socket_ipv6_is_supported(), but also checks that the sysctl that disables IPv6 on all
311 * interfaces isn't turned on */
312
313 if (!socket_ipv6_is_supported())
314 return false;
315
316 r = sysctl_read_ip_property(AF_INET6, "all", "disable_ipv6", &v);
317 if (r < 0) {
318 log_debug_errno(r, "Unexpected error reading 'net.ipv6.conf.all.disable_ipv6' sysctl: %m");
319 return true;
320 }
321
322 r = parse_boolean(v);
323 if (r < 0) {
324 log_debug_errno(r, "Failed to pare 'net.ipv6.conf.all.disable_ipv6' sysctl: %m");
325 return true;
326 }
327
328 return !r;
329 }
330
331 bool socket_address_matches_fd(const SocketAddress *a, int fd) {
332 SocketAddress b;
333 socklen_t solen;
334
335 assert(a);
336 assert(fd >= 0);
337
338 b.size = sizeof(b.sockaddr);
339 if (getsockname(fd, &b.sockaddr.sa, &b.size) < 0)
340 return false;
341
342 if (b.sockaddr.sa.sa_family != a->sockaddr.sa.sa_family)
343 return false;
344
345 solen = sizeof(b.type);
346 if (getsockopt(fd, SOL_SOCKET, SO_TYPE, &b.type, &solen) < 0)
347 return false;
348
349 if (b.type != a->type)
350 return false;
351
352 if (a->protocol != 0) {
353 solen = sizeof(b.protocol);
354 if (getsockopt(fd, SOL_SOCKET, SO_PROTOCOL, &b.protocol, &solen) < 0)
355 return false;
356
357 if (b.protocol != a->protocol)
358 return false;
359 }
360
361 return socket_address_equal(a, &b);
362 }
363
364 int sockaddr_port(const struct sockaddr *_sa, unsigned *ret_port) {
365 const union sockaddr_union *sa = (const union sockaddr_union*) _sa;
366
367 /* Note, this returns the port as 'unsigned' rather than 'uint16_t', as AF_VSOCK knows larger ports */
368
369 assert(sa);
370
371 switch (sa->sa.sa_family) {
372
373 case AF_INET:
374 *ret_port = be16toh(sa->in.sin_port);
375 return 0;
376
377 case AF_INET6:
378 *ret_port = be16toh(sa->in6.sin6_port);
379 return 0;
380
381 case AF_VSOCK:
382 *ret_port = sa->vm.svm_port;
383 return 0;
384
385 default:
386 return -EAFNOSUPPORT;
387 }
388 }
389
390 const union in_addr_union *sockaddr_in_addr(const struct sockaddr *_sa) {
391 const union sockaddr_union *sa = (const union sockaddr_union*) _sa;
392
393 if (!sa)
394 return NULL;
395
396 switch (sa->sa.sa_family) {
397
398 case AF_INET:
399 return (const union in_addr_union*) &sa->in.sin_addr;
400
401 case AF_INET6:
402 return (const union in_addr_union*) &sa->in6.sin6_addr;
403
404 default:
405 return NULL;
406 }
407 }
408
409 int sockaddr_set_in_addr(
410 union sockaddr_union *u,
411 int family,
412 const union in_addr_union *a,
413 uint16_t port) {
414
415 assert(u);
416 assert(a);
417
418 switch (family) {
419
420 case AF_INET:
421 u->in = (struct sockaddr_in) {
422 .sin_family = AF_INET,
423 .sin_addr = a->in,
424 .sin_port = htobe16(port),
425 };
426
427 return 0;
428
429 case AF_INET6:
430 u->in6 = (struct sockaddr_in6) {
431 .sin6_family = AF_INET6,
432 .sin6_addr = a->in6,
433 .sin6_port = htobe16(port),
434 };
435
436 return 0;
437
438 default:
439 return -EAFNOSUPPORT;
440
441 }
442 }
443
444 int sockaddr_pretty(
445 const struct sockaddr *_sa,
446 socklen_t salen,
447 bool translate_ipv6,
448 bool include_port,
449 char **ret) {
450
451 union sockaddr_union *sa = (union sockaddr_union*) _sa;
452 char *p;
453 int r;
454
455 assert(sa);
456 assert(salen >= sizeof(sa->sa.sa_family));
457 assert(ret);
458
459 switch (sa->sa.sa_family) {
460
461 case AF_INET: {
462 uint32_t a;
463
464 a = be32toh(sa->in.sin_addr.s_addr);
465
466 if (include_port)
467 r = asprintf(&p,
468 "%u.%u.%u.%u:%u",
469 a >> 24, (a >> 16) & 0xFF, (a >> 8) & 0xFF, a & 0xFF,
470 be16toh(sa->in.sin_port));
471 else
472 r = asprintf(&p,
473 "%u.%u.%u.%u",
474 a >> 24, (a >> 16) & 0xFF, (a >> 8) & 0xFF, a & 0xFF);
475 if (r < 0)
476 return -ENOMEM;
477 break;
478 }
479
480 case AF_INET6: {
481 static const unsigned char ipv4_prefix[] = {
482 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xFF, 0xFF
483 };
484
485 if (translate_ipv6 &&
486 memcmp(&sa->in6.sin6_addr, ipv4_prefix, sizeof(ipv4_prefix)) == 0) {
487 const uint8_t *a = sa->in6.sin6_addr.s6_addr+12;
488 if (include_port)
489 r = asprintf(&p,
490 "%u.%u.%u.%u:%u",
491 a[0], a[1], a[2], a[3],
492 be16toh(sa->in6.sin6_port));
493 else
494 r = asprintf(&p,
495 "%u.%u.%u.%u",
496 a[0], a[1], a[2], a[3]);
497 if (r < 0)
498 return -ENOMEM;
499 } else {
500 const char *a = IN6_ADDR_TO_STRING(&sa->in6.sin6_addr);
501
502 if (include_port) {
503 if (asprintf(&p,
504 "[%s]:%u%s%s",
505 a,
506 be16toh(sa->in6.sin6_port),
507 sa->in6.sin6_scope_id != 0 ? "%" : "",
508 FORMAT_IFNAME_FULL(sa->in6.sin6_scope_id, FORMAT_IFNAME_IFINDEX)) < 0)
509 return -ENOMEM;
510 } else {
511 if (sa->in6.sin6_scope_id != 0)
512 p = strjoin(a, "%", FORMAT_IFNAME_FULL(sa->in6.sin6_scope_id, FORMAT_IFNAME_IFINDEX));
513 else
514 p = strdup(a);
515 if (!p)
516 return -ENOMEM;
517 }
518 }
519
520 break;
521 }
522
523 case AF_UNIX:
524 if (salen <= offsetof(struct sockaddr_un, sun_path) ||
525 (sa->un.sun_path[0] == 0 && salen == offsetof(struct sockaddr_un, sun_path) + 1))
526 /* The name must have at least one character (and the leading NUL does not count) */
527 p = strdup("<unnamed>");
528 else {
529 /* Note that we calculate the path pointer here through the .un_buffer[] field, in order to
530 * outtrick bounds checking tools such as ubsan, which are too smart for their own good: on
531 * Linux the kernel may return sun_path[] data one byte longer than the declared size of the
532 * field. */
533 char *path = (char*) sa->un_buffer + offsetof(struct sockaddr_un, sun_path);
534 size_t path_len = salen - offsetof(struct sockaddr_un, sun_path);
535
536 if (path[0] == 0) {
537 /* Abstract socket. When parsing address information from, we
538 * explicitly reject overly long paths and paths with embedded NULs.
539 * But we might get such a socket from the outside. Let's return
540 * something meaningful and printable in this case. */
541
542 _cleanup_free_ char *e = NULL;
543
544 e = cescape_length(path + 1, path_len - 1);
545 if (!e)
546 return -ENOMEM;
547
548 p = strjoin("@", e);
549 } else {
550 if (path[path_len - 1] == '\0')
551 /* We expect a terminating NUL and don't print it */
552 path_len--;
553
554 p = cescape_length(path, path_len);
555 }
556 }
557 if (!p)
558 return -ENOMEM;
559
560 break;
561
562 case AF_VSOCK:
563 if (include_port) {
564 if (sa->vm.svm_cid == VMADDR_CID_ANY)
565 r = asprintf(&p, "vsock::%u", sa->vm.svm_port);
566 else
567 r = asprintf(&p, "vsock:%u:%u", sa->vm.svm_cid, sa->vm.svm_port);
568 } else
569 r = asprintf(&p, "vsock:%u", sa->vm.svm_cid);
570 if (r < 0)
571 return -ENOMEM;
572 break;
573
574 default:
575 return -EOPNOTSUPP;
576 }
577
578 *ret = p;
579 return 0;
580 }
581
582 int getpeername_pretty(int fd, bool include_port, char **ret) {
583 union sockaddr_union sa;
584 socklen_t salen = sizeof(sa);
585 int r;
586
587 assert(fd >= 0);
588 assert(ret);
589
590 if (getpeername(fd, &sa.sa, &salen) < 0)
591 return -errno;
592
593 if (sa.sa.sa_family == AF_UNIX) {
594 struct ucred ucred = UCRED_INVALID;
595
596 /* UNIX connection sockets are anonymous, so let's use
597 * PID/UID as pretty credentials instead */
598
599 r = getpeercred(fd, &ucred);
600 if (r < 0)
601 return r;
602
603 if (asprintf(ret, "PID "PID_FMT"/UID "UID_FMT, ucred.pid, ucred.uid) < 0)
604 return -ENOMEM;
605
606 return 0;
607 }
608
609 /* For remote sockets we translate IPv6 addresses back to IPv4
610 * if applicable, since that's nicer. */
611
612 return sockaddr_pretty(&sa.sa, salen, true, include_port, ret);
613 }
614
615 int getsockname_pretty(int fd, char **ret) {
616 union sockaddr_union sa;
617 socklen_t salen = sizeof(sa);
618
619 assert(fd >= 0);
620 assert(ret);
621
622 if (getsockname(fd, &sa.sa, &salen) < 0)
623 return -errno;
624
625 /* For local sockets we do not translate IPv6 addresses back
626 * to IPv6 if applicable, since this is usually used for
627 * listening sockets where the difference between IPv4 and
628 * IPv6 matters. */
629
630 return sockaddr_pretty(&sa.sa, salen, false, true, ret);
631 }
632
633 int socknameinfo_pretty(const struct sockaddr *sa, socklen_t salen, char **ret) {
634 char host[NI_MAXHOST];
635 int r;
636
637 assert(sa);
638 assert(salen >= sizeof(sa_family_t));
639 assert(ret);
640
641 r = getnameinfo(sa, salen, host, sizeof(host), /* service= */ NULL, /* service_len= */ 0, IDN_FLAGS);
642 if (r != 0) {
643 if (r == EAI_MEMORY)
644 return log_oom_debug();
645 if (r == EAI_SYSTEM)
646 log_debug_errno(errno, "getnameinfo() failed, ignoring: %m");
647 else
648 log_debug("getnameinfo() failed, ignoring: %s", gai_strerror(r));
649
650 return sockaddr_pretty(sa, salen, /* translate_ipv6= */ true, /* include_port= */ true, ret);
651 }
652
653 return strdup_to(ret, host);
654 }
655
656 static const char* const netlink_family_table[] = {
657 [NETLINK_ROUTE] = "route",
658 [NETLINK_FIREWALL] = "firewall",
659 [NETLINK_INET_DIAG] = "inet-diag",
660 [NETLINK_NFLOG] = "nflog",
661 [NETLINK_XFRM] = "xfrm",
662 [NETLINK_SELINUX] = "selinux",
663 [NETLINK_ISCSI] = "iscsi",
664 [NETLINK_AUDIT] = "audit",
665 [NETLINK_FIB_LOOKUP] = "fib-lookup",
666 [NETLINK_CONNECTOR] = "connector",
667 [NETLINK_NETFILTER] = "netfilter",
668 [NETLINK_IP6_FW] = "ip6-fw",
669 [NETLINK_DNRTMSG] = "dnrtmsg",
670 [NETLINK_KOBJECT_UEVENT] = "kobject-uevent",
671 [NETLINK_GENERIC] = "generic",
672 [NETLINK_SCSITRANSPORT] = "scsitransport",
673 [NETLINK_ECRYPTFS] = "ecryptfs",
674 [NETLINK_RDMA] = "rdma",
675 };
676
677 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(netlink_family, int, INT_MAX);
678
679 static const char* const socket_address_bind_ipv6_only_table[_SOCKET_ADDRESS_BIND_IPV6_ONLY_MAX] = {
680 [SOCKET_ADDRESS_DEFAULT] = "default",
681 [SOCKET_ADDRESS_BOTH] = "both",
682 [SOCKET_ADDRESS_IPV6_ONLY] = "ipv6-only"
683 };
684
685 DEFINE_STRING_TABLE_LOOKUP(socket_address_bind_ipv6_only, SocketAddressBindIPv6Only);
686
687 SocketAddressBindIPv6Only socket_address_bind_ipv6_only_or_bool_from_string(const char *n) {
688 int r;
689
690 r = parse_boolean(n);
691 if (r > 0)
692 return SOCKET_ADDRESS_IPV6_ONLY;
693 if (r == 0)
694 return SOCKET_ADDRESS_BOTH;
695
696 return socket_address_bind_ipv6_only_from_string(n);
697 }
698
699 bool sockaddr_equal(const union sockaddr_union *a, const union sockaddr_union *b) {
700 assert(a);
701 assert(b);
702
703 if (a->sa.sa_family != b->sa.sa_family)
704 return false;
705
706 if (a->sa.sa_family == AF_INET)
707 return a->in.sin_addr.s_addr == b->in.sin_addr.s_addr;
708
709 if (a->sa.sa_family == AF_INET6)
710 return memcmp(&a->in6.sin6_addr, &b->in6.sin6_addr, sizeof(a->in6.sin6_addr)) == 0;
711
712 if (a->sa.sa_family == AF_VSOCK)
713 return a->vm.svm_cid == b->vm.svm_cid;
714
715 return false;
716 }
717
718 int fd_set_sndbuf(int fd, size_t n, bool increase) {
719 int r, value;
720 socklen_t l = sizeof(value);
721
722 if (n > INT_MAX)
723 return -ERANGE;
724
725 r = getsockopt(fd, SOL_SOCKET, SO_SNDBUF, &value, &l);
726 if (r >= 0 && l == sizeof(value) && increase ? (size_t) value >= n*2 : (size_t) value == n*2)
727 return 0;
728
729 /* First, try to set the buffer size with SO_SNDBUF. */
730 r = setsockopt_int(fd, SOL_SOCKET, SO_SNDBUF, n);
731 if (r < 0)
732 return r;
733
734 /* SO_SNDBUF above may set to the kernel limit, instead of the requested size.
735 * So, we need to check the actual buffer size here. */
736 l = sizeof(value);
737 r = getsockopt(fd, SOL_SOCKET, SO_SNDBUF, &value, &l);
738 if (r >= 0 && l == sizeof(value) && increase ? (size_t) value >= n*2 : (size_t) value == n*2)
739 return 1;
740
741 /* If we have the privileges we will ignore the kernel limit. */
742 r = setsockopt_int(fd, SOL_SOCKET, SO_SNDBUFFORCE, n);
743 if (r < 0)
744 return r;
745
746 return 1;
747 }
748
749 int fd_set_rcvbuf(int fd, size_t n, bool increase) {
750 int r, value;
751 socklen_t l = sizeof(value);
752
753 if (n > INT_MAX)
754 return -ERANGE;
755
756 r = getsockopt(fd, SOL_SOCKET, SO_RCVBUF, &value, &l);
757 if (r >= 0 && l == sizeof(value) && increase ? (size_t) value >= n*2 : (size_t) value == n*2)
758 return 0;
759
760 /* First, try to set the buffer size with SO_RCVBUF. */
761 r = setsockopt_int(fd, SOL_SOCKET, SO_RCVBUF, n);
762 if (r < 0)
763 return r;
764
765 /* SO_RCVBUF above may set to the kernel limit, instead of the requested size.
766 * So, we need to check the actual buffer size here. */
767 l = sizeof(value);
768 r = getsockopt(fd, SOL_SOCKET, SO_RCVBUF, &value, &l);
769 if (r >= 0 && l == sizeof(value) && increase ? (size_t) value >= n*2 : (size_t) value == n*2)
770 return 1;
771
772 /* If we have the privileges we will ignore the kernel limit. */
773 r = setsockopt_int(fd, SOL_SOCKET, SO_RCVBUFFORCE, n);
774 if (r < 0)
775 return r;
776
777 return 1;
778 }
779
780 static const char* const ip_tos_table[] = {
781 [IPTOS_LOWDELAY] = "low-delay",
782 [IPTOS_THROUGHPUT] = "throughput",
783 [IPTOS_RELIABILITY] = "reliability",
784 [IPTOS_LOWCOST] = "low-cost",
785 };
786
787 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(ip_tos, int, 0xff);
788
789 bool ifname_valid_char(char a) {
790 if ((unsigned char) a >= 127U)
791 return false;
792
793 if ((unsigned char) a <= 32U)
794 return false;
795
796 if (IN_SET(a,
797 ':', /* colons are used by the legacy "alias" interface logic */
798 '/', /* slashes cannot work, since we need to use network interfaces in sysfs paths, and in paths slashes are separators */
799 '%')) /* %d is used in the kernel's weird foo%d format string naming feature which we really really don't want to ever run into by accident */
800 return false;
801
802 return true;
803 }
804
805 bool ifname_valid_full(const char *p, IfnameValidFlags flags) {
806 bool numeric = true;
807
808 /* Checks whether a network interface name is valid. This is inspired by dev_valid_name() in the kernel sources
809 * but slightly stricter, as we only allow non-control, non-space ASCII characters in the interface name. We
810 * also don't permit names that only container numbers, to avoid confusion with numeric interface indexes. */
811
812 assert(!(flags & ~_IFNAME_VALID_ALL));
813
814 if (isempty(p))
815 return false;
816
817 /* A valid ifindex? If so, it's valid iff IFNAME_VALID_NUMERIC is set */
818 if (parse_ifindex(p) >= 0)
819 return flags & IFNAME_VALID_NUMERIC;
820
821 if (flags & IFNAME_VALID_ALTERNATIVE) {
822 if (strlen(p) >= ALTIFNAMSIZ)
823 return false;
824 } else {
825 if (strlen(p) >= IFNAMSIZ)
826 return false;
827 }
828
829 if (dot_or_dot_dot(p))
830 return false;
831
832 /* Let's refuse "all" and "default" as interface name, to avoid collisions with the special sysctl
833 * directories /proc/sys/net/{ipv4,ipv6}/conf/{all,default} */
834 if (!FLAGS_SET(flags, IFNAME_VALID_SPECIAL) && STR_IN_SET(p, "all", "default"))
835 return false;
836
837 for (const char *t = p; *t; t++) {
838 if (!ifname_valid_char(*t))
839 return false;
840
841 numeric = numeric && ascii_isdigit(*t);
842 }
843
844 /* It's fully numeric but didn't parse as valid ifindex above? if so, it must be too large or zero or
845 * so, let's refuse that. */
846 if (numeric)
847 return false;
848
849 return true;
850 }
851
852 bool address_label_valid(const char *p) {
853
854 if (isempty(p))
855 return false;
856
857 if (strlen(p) >= IFNAMSIZ)
858 return false;
859
860 while (*p) {
861 if ((uint8_t) *p >= 127U)
862 return false;
863
864 if ((uint8_t) *p <= 31U)
865 return false;
866 p++;
867 }
868
869 return true;
870 }
871
872 int getpeercred(int fd, struct ucred *ucred) {
873 socklen_t n = sizeof(struct ucred);
874 struct ucred u;
875
876 assert(fd >= 0);
877 assert(ucred);
878
879 if (getsockopt(fd, SOL_SOCKET, SO_PEERCRED, &u, &n) < 0)
880 return -errno;
881
882 if (n != sizeof(struct ucred))
883 return -EIO;
884
885 /* Check if the data is actually useful and not suppressed due to namespacing issues */
886 if (!pid_is_valid(u.pid))
887 return -ENODATA;
888
889 /* Note that we don't check UID/GID here, as namespace translation works differently there: instead of
890 * receiving in "invalid" user/group we get the overflow UID/GID. */
891
892 *ucred = u;
893 return 0;
894 }
895
896 int getpeersec(int fd, char **ret) {
897 _cleanup_free_ char *s = NULL;
898 socklen_t n = 64;
899
900 assert(fd >= 0);
901 assert(ret);
902
903 for (;;) {
904 s = new0(char, n+1);
905 if (!s)
906 return -ENOMEM;
907
908 if (getsockopt(fd, SOL_SOCKET, SO_PEERSEC, s, &n) >= 0) {
909 s[n] = 0;
910 break;
911 }
912
913 if (errno != ERANGE)
914 return -errno;
915
916 s = mfree(s);
917 }
918
919 if (isempty(s))
920 return -EOPNOTSUPP;
921
922 *ret = TAKE_PTR(s);
923
924 return 0;
925 }
926
927 int getpeergroups(int fd, gid_t **ret) {
928 socklen_t n = sizeof(gid_t) * 64U;
929 _cleanup_free_ gid_t *d = NULL;
930
931 assert(fd >= 0);
932 assert(ret);
933
934 long ngroups_max = sysconf(_SC_NGROUPS_MAX);
935 if (ngroups_max > 0)
936 n = MAX(n, sizeof(gid_t) * (socklen_t) ngroups_max);
937
938 for (;;) {
939 d = malloc(n);
940 if (!d)
941 return -ENOMEM;
942
943 if (getsockopt(fd, SOL_SOCKET, SO_PEERGROUPS, d, &n) >= 0)
944 break;
945
946 if (errno != ERANGE)
947 return -errno;
948
949 d = mfree(d);
950 }
951
952 assert_se(n % sizeof(gid_t) == 0);
953 n /= sizeof(gid_t);
954
955 if (n > INT_MAX)
956 return -E2BIG;
957
958 *ret = TAKE_PTR(d);
959
960 return (int) n;
961 }
962
963 int getpeerpidfd(int fd) {
964 socklen_t n = sizeof(int);
965 int pidfd = -EBADF;
966
967 assert(fd >= 0);
968
969 if (getsockopt(fd, SOL_SOCKET, SO_PEERPIDFD, &pidfd, &n) < 0)
970 return -errno;
971
972 if (n != sizeof(int))
973 return -EIO;
974
975 return pidfd;
976 }
977
978 ssize_t send_many_fds_iov_sa(
979 int transport_fd,
980 int *fds_array, size_t n_fds_array,
981 const struct iovec *iov, size_t iovlen,
982 const struct sockaddr *sa, socklen_t len,
983 int flags) {
984
985 _cleanup_free_ struct cmsghdr *cmsg = NULL;
986 struct msghdr mh = {
987 .msg_name = (struct sockaddr*) sa,
988 .msg_namelen = len,
989 .msg_iov = (struct iovec *)iov,
990 .msg_iovlen = iovlen,
991 };
992 ssize_t k;
993
994 assert(transport_fd >= 0);
995 assert(fds_array || n_fds_array == 0);
996
997 /* The kernel will reject sending more than SCM_MAX_FD FDs at once */
998 if (n_fds_array > SCM_MAX_FD)
999 return -E2BIG;
1000
1001 /* We need either an FD array or data to send. If there's nothing, return an error. */
1002 if (n_fds_array == 0 && !iov)
1003 return -EINVAL;
1004
1005 if (n_fds_array > 0) {
1006 mh.msg_controllen = CMSG_SPACE(sizeof(int) * n_fds_array);
1007 mh.msg_control = cmsg = malloc(mh.msg_controllen);
1008 if (!cmsg)
1009 return -ENOMEM;
1010
1011 *cmsg = (struct cmsghdr) {
1012 .cmsg_len = CMSG_LEN(sizeof(int) * n_fds_array),
1013 .cmsg_level = SOL_SOCKET,
1014 .cmsg_type = SCM_RIGHTS,
1015 };
1016 memcpy(CMSG_DATA(cmsg), fds_array, sizeof(int) * n_fds_array);
1017 }
1018 k = sendmsg(transport_fd, &mh, MSG_NOSIGNAL | flags);
1019 if (k < 0)
1020 return (ssize_t) -errno;
1021
1022 return k;
1023 }
1024
1025 ssize_t send_one_fd_iov_sa(
1026 int transport_fd,
1027 int fd,
1028 const struct iovec *iov, size_t iovlen,
1029 const struct sockaddr *sa, socklen_t len,
1030 int flags) {
1031
1032 CMSG_BUFFER_TYPE(CMSG_SPACE(sizeof(int))) control = {};
1033 struct msghdr mh = {
1034 .msg_name = (struct sockaddr*) sa,
1035 .msg_namelen = len,
1036 .msg_iov = (struct iovec *)iov,
1037 .msg_iovlen = iovlen,
1038 };
1039 ssize_t k;
1040
1041 assert(transport_fd >= 0);
1042
1043 /*
1044 * We need either an FD or data to send.
1045 * If there's nothing, return an error.
1046 */
1047 if (fd < 0 && !iov)
1048 return -EINVAL;
1049
1050 if (fd >= 0) {
1051 struct cmsghdr *cmsg;
1052
1053 mh.msg_control = &control;
1054 mh.msg_controllen = sizeof(control);
1055
1056 cmsg = CMSG_FIRSTHDR(&mh);
1057 cmsg->cmsg_level = SOL_SOCKET;
1058 cmsg->cmsg_type = SCM_RIGHTS;
1059 cmsg->cmsg_len = CMSG_LEN(sizeof(int));
1060 memcpy(CMSG_DATA(cmsg), &fd, sizeof(int));
1061 }
1062 k = sendmsg(transport_fd, &mh, MSG_NOSIGNAL | flags);
1063 if (k < 0)
1064 return (ssize_t) -errno;
1065
1066 return k;
1067 }
1068
1069 int send_one_fd_sa(
1070 int transport_fd,
1071 int fd,
1072 const struct sockaddr *sa, socklen_t len,
1073 int flags) {
1074
1075 assert(fd >= 0);
1076
1077 return (int) send_one_fd_iov_sa(transport_fd, fd, NULL, 0, sa, len, flags);
1078 }
1079
1080 ssize_t receive_many_fds_iov(
1081 int transport_fd,
1082 struct iovec *iov, size_t iovlen,
1083 int **ret_fds_array, size_t *ret_n_fds_array,
1084 int flags) {
1085
1086 CMSG_BUFFER_TYPE(CMSG_SPACE(sizeof(int) * SCM_MAX_FD)) control;
1087 struct msghdr mh = {
1088 .msg_control = &control,
1089 .msg_controllen = sizeof(control),
1090 .msg_iov = iov,
1091 .msg_iovlen = iovlen,
1092 };
1093 _cleanup_free_ int *fds_array = NULL;
1094 size_t n_fds_array = 0;
1095 struct cmsghdr *cmsg;
1096 ssize_t k;
1097
1098 assert(transport_fd >= 0);
1099 assert(ret_fds_array);
1100 assert(ret_n_fds_array);
1101
1102 /*
1103 * Receive many FDs via @transport_fd. We don't care for the transport-type. We retrieve all the FDs
1104 * at once. This is best used in combination with send_many_fds().
1105 */
1106
1107 k = recvmsg_safe(transport_fd, &mh, MSG_CMSG_CLOEXEC | flags);
1108 if (k < 0)
1109 return k;
1110
1111 CMSG_FOREACH(cmsg, &mh)
1112 if (cmsg->cmsg_level == SOL_SOCKET && cmsg->cmsg_type == SCM_RIGHTS) {
1113 size_t n = (cmsg->cmsg_len - CMSG_LEN(0)) / sizeof(int);
1114
1115 if (!GREEDY_REALLOC_APPEND(fds_array, n_fds_array, CMSG_TYPED_DATA(cmsg, int), n)) {
1116 cmsg_close_all(&mh);
1117 return -ENOMEM;
1118 }
1119 }
1120
1121 if (n_fds_array == 0) {
1122 cmsg_close_all(&mh);
1123
1124 /* If didn't receive an FD or any data, return an error. */
1125 if (k == 0)
1126 return -EIO;
1127 }
1128
1129 *ret_fds_array = TAKE_PTR(fds_array);
1130 *ret_n_fds_array = n_fds_array;
1131
1132 return k;
1133 }
1134
1135 int receive_many_fds(int transport_fd, int **ret_fds_array, size_t *ret_n_fds_array, int flags) {
1136 ssize_t k;
1137
1138 k = receive_many_fds_iov(transport_fd, NULL, 0, ret_fds_array, ret_n_fds_array, flags);
1139 if (k == 0)
1140 return 0;
1141
1142 /* k must be negative, since receive_many_fds_iov() only returns a positive value if data was received
1143 * through the iov. */
1144 assert(k < 0);
1145 return (int) k;
1146 }
1147
1148 ssize_t receive_one_fd_iov(
1149 int transport_fd,
1150 struct iovec *iov, size_t iovlen,
1151 int flags,
1152 int *ret_fd) {
1153
1154 CMSG_BUFFER_TYPE(CMSG_SPACE(sizeof(int))) control;
1155 struct msghdr mh = {
1156 .msg_control = &control,
1157 .msg_controllen = sizeof(control),
1158 .msg_iov = iov,
1159 .msg_iovlen = iovlen,
1160 };
1161 struct cmsghdr *found;
1162 ssize_t k;
1163
1164 assert(transport_fd >= 0);
1165 assert(ret_fd);
1166
1167 /*
1168 * Receive a single FD via @transport_fd. We don't care for
1169 * the transport-type. We retrieve a single FD at most, so for
1170 * packet-based transports, the caller must ensure to send
1171 * only a single FD per packet. This is best used in
1172 * combination with send_one_fd().
1173 */
1174
1175 k = recvmsg_safe(transport_fd, &mh, MSG_CMSG_CLOEXEC | flags);
1176 if (k < 0)
1177 return k;
1178
1179 found = cmsg_find(&mh, SOL_SOCKET, SCM_RIGHTS, CMSG_LEN(sizeof(int)));
1180 if (!found) {
1181 cmsg_close_all(&mh);
1182
1183 /* If didn't receive an FD or any data, return an error. */
1184 if (k == 0)
1185 return -EIO;
1186 }
1187
1188 if (found)
1189 *ret_fd = *CMSG_TYPED_DATA(found, int);
1190 else
1191 *ret_fd = -EBADF;
1192
1193 return k;
1194 }
1195
1196 int receive_one_fd(int transport_fd, int flags) {
1197 int fd;
1198 ssize_t k;
1199
1200 k = receive_one_fd_iov(transport_fd, NULL, 0, flags, &fd);
1201 if (k == 0)
1202 return fd;
1203
1204 /* k must be negative, since receive_one_fd_iov() only returns
1205 * a positive value if data was received through the iov. */
1206 assert(k < 0);
1207 return (int) k;
1208 }
1209
1210 ssize_t next_datagram_size_fd(int fd) {
1211 ssize_t l;
1212 int k;
1213
1214 /* This is a bit like FIONREAD/SIOCINQ, however a bit more powerful. The difference being: recv(MSG_PEEK) will
1215 * actually cause the next datagram in the queue to be validated regarding checksums, which FIONREAD doesn't
1216 * do. This difference is actually of major importance as we need to be sure that the size returned here
1217 * actually matches what we will read with recvmsg() next, as otherwise we might end up allocating a buffer of
1218 * the wrong size. */
1219
1220 l = recv(fd, NULL, 0, MSG_PEEK|MSG_TRUNC);
1221 if (l < 0) {
1222 if (IN_SET(errno, EOPNOTSUPP, EFAULT))
1223 goto fallback;
1224
1225 return -errno;
1226 }
1227 if (l == 0)
1228 goto fallback;
1229
1230 return l;
1231
1232 fallback:
1233 k = 0;
1234
1235 /* Some sockets (AF_PACKET) do not support null-sized recv() with MSG_TRUNC set, let's fall back to FIONREAD
1236 * for them. Checksums don't matter for raw sockets anyway, hence this should be fine. */
1237
1238 if (ioctl(fd, FIONREAD, &k) < 0)
1239 return -errno;
1240
1241 return (ssize_t) k;
1242 }
1243
1244 /* Put a limit on how many times will attempt to call accept4(). We loop
1245 * only on "transient" errors, but let's make sure we don't loop forever. */
1246 #define MAX_FLUSH_ITERATIONS 1024
1247
1248 int flush_accept(int fd) {
1249
1250 int r, b;
1251 socklen_t l = sizeof(b);
1252
1253 /* Similar to flush_fd() but flushes all incoming connections by accepting and immediately closing
1254 * them. */
1255
1256 if (getsockopt(fd, SOL_SOCKET, SO_ACCEPTCONN, &b, &l) < 0)
1257 return -errno;
1258
1259 assert(l == sizeof(b));
1260 if (!b) /* Let's check if this socket accepts connections before calling accept(). accept4() can
1261 * return EOPNOTSUPP if the fd is not a listening socket, which we should treat as a fatal
1262 * error, or in case the incoming TCP connection triggered a network issue, which we want to
1263 * treat as a transient error. Thus, let's rule out the first reason for EOPNOTSUPP early, so
1264 * we can loop safely on transient errors below. */
1265 return -ENOTTY;
1266
1267 for (unsigned iteration = 0;; iteration++) {
1268 int cfd;
1269
1270 r = fd_wait_for_event(fd, POLLIN, 0);
1271 if (r < 0) {
1272 if (r == -EINTR)
1273 continue;
1274
1275 return r;
1276 }
1277 if (r == 0)
1278 return 0;
1279
1280 if (iteration >= MAX_FLUSH_ITERATIONS)
1281 return log_debug_errno(SYNTHETIC_ERRNO(EBUSY),
1282 "Failed to flush connections within " STRINGIFY(MAX_FLUSH_ITERATIONS) " iterations.");
1283
1284 cfd = accept4(fd, NULL, NULL, SOCK_NONBLOCK|SOCK_CLOEXEC);
1285 if (cfd < 0) {
1286 if (errno == EAGAIN)
1287 return 0;
1288
1289 if (ERRNO_IS_ACCEPT_AGAIN(errno))
1290 continue;
1291
1292 return -errno;
1293 }
1294
1295 safe_close(cfd);
1296 }
1297 }
1298
1299 struct cmsghdr* cmsg_find(struct msghdr *mh, int level, int type, socklen_t length) {
1300 struct cmsghdr *cmsg;
1301
1302 assert(mh);
1303
1304 CMSG_FOREACH(cmsg, mh)
1305 if (cmsg->cmsg_level == level &&
1306 cmsg->cmsg_type == type &&
1307 (length == (socklen_t) -1 || length == cmsg->cmsg_len))
1308 return cmsg;
1309
1310 return NULL;
1311 }
1312
1313 void* cmsg_find_and_copy_data(struct msghdr *mh, int level, int type, void *buf, size_t buf_len) {
1314 struct cmsghdr *cmsg;
1315
1316 assert(mh);
1317 assert(buf);
1318 assert(buf_len > 0);
1319
1320 /* This is similar to cmsg_find_data(), but copy the found data to buf. This should be typically used
1321 * when reading possibly unaligned data such as timestamp, as time_t is 64-bit and size_t is 32-bit on
1322 * RISCV32. See issue #27241. */
1323
1324 cmsg = cmsg_find(mh, level, type, CMSG_LEN(buf_len));
1325 if (!cmsg)
1326 return NULL;
1327
1328 return memcpy_safe(buf, CMSG_DATA(cmsg), buf_len);
1329 }
1330
1331 int socket_ioctl_fd(void) {
1332 int fd;
1333
1334 /* Create a socket to invoke the various network interface ioctl()s on. Traditionally only AF_INET was good for
1335 * that. Since kernel 4.6 AF_NETLINK works for this too. We first try to use AF_INET hence, but if that's not
1336 * available (for example, because it is made unavailable via SECCOMP or such), we'll fall back to the more
1337 * generic AF_NETLINK. */
1338
1339 fd = socket(AF_INET, SOCK_DGRAM|SOCK_CLOEXEC, 0);
1340 if (fd < 0)
1341 fd = socket(AF_NETLINK, SOCK_RAW|SOCK_CLOEXEC, NETLINK_GENERIC);
1342 if (fd < 0)
1343 return -errno;
1344
1345 return fd;
1346 }
1347
1348 int sockaddr_un_unlink(const struct sockaddr_un *sa) {
1349 const char *p, * nul;
1350
1351 assert(sa);
1352
1353 if (sa->sun_family != AF_UNIX)
1354 return -EPROTOTYPE;
1355
1356 if (sa->sun_path[0] == 0) /* Nothing to do for abstract sockets */
1357 return 0;
1358
1359 /* The path in .sun_path is not necessarily NUL terminated. Let's fix that. */
1360 nul = memchr(sa->sun_path, 0, sizeof(sa->sun_path));
1361 if (nul)
1362 p = sa->sun_path;
1363 else
1364 p = memdupa_suffix0(sa->sun_path, sizeof(sa->sun_path));
1365
1366 if (unlink(p) < 0)
1367 return -errno;
1368
1369 return 1;
1370 }
1371
1372 int sockaddr_un_set_path(struct sockaddr_un *ret, const char *path) {
1373 size_t l;
1374
1375 assert(ret);
1376 assert(path);
1377
1378 /* Initialize ret->sun_path from the specified argument. This will interpret paths starting with '@' as
1379 * abstract namespace sockets, and those starting with '/' as regular filesystem sockets. It won't accept
1380 * anything else (i.e. no relative paths), to avoid ambiguities. Note that this function cannot be used to
1381 * reference paths in the abstract namespace that include NUL bytes in the name. */
1382
1383 l = strlen(path);
1384 if (l < 2)
1385 return -EINVAL;
1386 if (!IN_SET(path[0], '/', '@'))
1387 return -EINVAL;
1388
1389 /* Don't allow paths larger than the space in sockaddr_un. Note that we are a tiny bit more restrictive than
1390 * the kernel is: we insist on NUL termination (both for abstract namespace and regular file system socket
1391 * addresses!), which the kernel doesn't. We do this to reduce chance of incompatibility with other apps that
1392 * do not expect non-NUL terminated file system path. */
1393 if (l+1 > sizeof(ret->sun_path))
1394 return path[0] == '@' ? -EINVAL : -ENAMETOOLONG; /* return a recognizable error if this is
1395 * too long to fit into a sockaddr_un, but
1396 * is a file system path, and thus might be
1397 * connectible via O_PATH indirection. */
1398
1399 *ret = (struct sockaddr_un) {
1400 .sun_family = AF_UNIX,
1401 };
1402
1403 if (path[0] == '@') {
1404 /* Abstract namespace socket */
1405 memcpy(ret->sun_path + 1, path + 1, l); /* copy *with* trailing NUL byte */
1406 return (int) (offsetof(struct sockaddr_un, sun_path) + l); /* 🔥 *don't* 🔥 include trailing NUL in size */
1407
1408 } else {
1409 assert(path[0] == '/');
1410
1411 /* File system socket */
1412 memcpy(ret->sun_path, path, l + 1); /* copy *with* trailing NUL byte */
1413 return (int) (offsetof(struct sockaddr_un, sun_path) + l + 1); /* include trailing NUL in size */
1414 }
1415 }
1416
1417 int socket_bind_to_ifname(int fd, const char *ifname) {
1418 assert(fd >= 0);
1419
1420 /* Call with NULL to drop binding */
1421
1422 return RET_NERRNO(setsockopt(fd, SOL_SOCKET, SO_BINDTODEVICE, ifname, strlen_ptr(ifname)));
1423 }
1424
1425 int socket_bind_to_ifindex(int fd, int ifindex) {
1426 char ifname[IF_NAMESIZE];
1427 int r;
1428
1429 assert(fd >= 0);
1430
1431 if (ifindex <= 0)
1432 /* Drop binding */
1433 return RET_NERRNO(setsockopt(fd, SOL_SOCKET, SO_BINDTODEVICE, NULL, 0));
1434
1435 r = setsockopt_int(fd, SOL_SOCKET, SO_BINDTOIFINDEX, ifindex);
1436 if (r != -ENOPROTOOPT)
1437 return r;
1438
1439 /* Fall back to SO_BINDTODEVICE on kernels < 5.0 which didn't have SO_BINDTOIFINDEX */
1440 r = format_ifname(ifindex, ifname);
1441 if (r < 0)
1442 return r;
1443
1444 return socket_bind_to_ifname(fd, ifname);
1445 }
1446
1447 ssize_t recvmsg_safe(int sockfd, struct msghdr *msg, int flags) {
1448 ssize_t n;
1449
1450 /* A wrapper around recvmsg() that checks for MSG_CTRUNC and MSG_TRUNC, and turns them into an error,
1451 * in a reasonably safe way, closing any received fds in the error path.
1452 *
1453 * Note that unlike our usual coding style this might modify *msg on failure. */
1454
1455 assert(sockfd >= 0);
1456 assert(msg);
1457
1458 n = recvmsg(sockfd, msg, flags);
1459 if (n < 0)
1460 return -errno;
1461
1462 if (FLAGS_SET(msg->msg_flags, MSG_CTRUNC) ||
1463 (!FLAGS_SET(flags, MSG_PEEK) && FLAGS_SET(msg->msg_flags, MSG_TRUNC))) {
1464 cmsg_close_all(msg);
1465 return FLAGS_SET(msg->msg_flags, MSG_CTRUNC) ? -ECHRNG : -EXFULL;
1466 }
1467
1468 return n;
1469 }
1470
1471 int socket_get_family(int fd) {
1472 int af;
1473 socklen_t sl = sizeof(af);
1474
1475 if (getsockopt(fd, SOL_SOCKET, SO_DOMAIN, &af, &sl) < 0)
1476 return -errno;
1477
1478 if (sl != sizeof(af))
1479 return -EINVAL;
1480
1481 return af;
1482 }
1483
1484 int socket_set_recvpktinfo(int fd, int af, bool b) {
1485
1486 if (af == AF_UNSPEC) {
1487 af = socket_get_family(fd);
1488 if (af < 0)
1489 return af;
1490 }
1491
1492 switch (af) {
1493
1494 case AF_INET:
1495 return setsockopt_int(fd, IPPROTO_IP, IP_PKTINFO, b);
1496
1497 case AF_INET6:
1498 return setsockopt_int(fd, IPPROTO_IPV6, IPV6_RECVPKTINFO, b);
1499
1500 case AF_NETLINK:
1501 return setsockopt_int(fd, SOL_NETLINK, NETLINK_PKTINFO, b);
1502
1503 case AF_PACKET:
1504 return setsockopt_int(fd, SOL_PACKET, PACKET_AUXDATA, b);
1505
1506 default:
1507 return -EAFNOSUPPORT;
1508 }
1509 }
1510
1511 int socket_set_unicast_if(int fd, int af, int ifi) {
1512 be32_t ifindex_be = htobe32(ifi);
1513
1514 if (af == AF_UNSPEC) {
1515 af = socket_get_family(fd);
1516 if (af < 0)
1517 return af;
1518 }
1519
1520 switch (af) {
1521
1522 case AF_INET:
1523 return RET_NERRNO(setsockopt(fd, IPPROTO_IP, IP_UNICAST_IF, &ifindex_be, sizeof(ifindex_be)));
1524
1525 case AF_INET6:
1526 return RET_NERRNO(setsockopt(fd, IPPROTO_IPV6, IPV6_UNICAST_IF, &ifindex_be, sizeof(ifindex_be)));
1527
1528 default:
1529 return -EAFNOSUPPORT;
1530 }
1531 }
1532
1533 int socket_set_option(int fd, int af, int opt_ipv4, int opt_ipv6, int val) {
1534 if (af == AF_UNSPEC) {
1535 af = socket_get_family(fd);
1536 if (af < 0)
1537 return af;
1538 }
1539
1540 switch (af) {
1541
1542 case AF_INET:
1543 return setsockopt_int(fd, IPPROTO_IP, opt_ipv4, val);
1544
1545 case AF_INET6:
1546 return setsockopt_int(fd, IPPROTO_IPV6, opt_ipv6, val);
1547
1548 default:
1549 return -EAFNOSUPPORT;
1550 }
1551 }
1552
1553 int socket_get_mtu(int fd, int af, size_t *ret) {
1554 int mtu, r;
1555
1556 if (af == AF_UNSPEC) {
1557 af = socket_get_family(fd);
1558 if (af < 0)
1559 return af;
1560 }
1561
1562 switch (af) {
1563
1564 case AF_INET:
1565 r = getsockopt_int(fd, IPPROTO_IP, IP_MTU, &mtu);
1566 break;
1567
1568 case AF_INET6:
1569 r = getsockopt_int(fd, IPPROTO_IPV6, IPV6_MTU, &mtu);
1570 break;
1571
1572 default:
1573 return -EAFNOSUPPORT;
1574 }
1575
1576 if (r < 0)
1577 return r;
1578 if (mtu <= 0)
1579 return -EINVAL;
1580
1581 *ret = (size_t) mtu;
1582 return 0;
1583 }
1584
1585 static int connect_unix_path_simple(int fd, const char *path) {
1586 union sockaddr_union sa = {
1587 .un.sun_family = AF_UNIX,
1588 };
1589 size_t l;
1590
1591 assert(fd >= 0);
1592 assert(path);
1593
1594 l = strlen(path);
1595 assert(l > 0);
1596 assert(l < sizeof(sa.un.sun_path));
1597
1598 memcpy(sa.un.sun_path, path, l + 1);
1599 return RET_NERRNO(connect(fd, &sa.sa, offsetof(struct sockaddr_un, sun_path) + l + 1));
1600 }
1601
1602 static int connect_unix_inode(int fd, int inode_fd) {
1603 assert(fd >= 0);
1604 assert(inode_fd >= 0);
1605
1606 return connect_unix_path_simple(fd, FORMAT_PROC_FD_PATH(inode_fd));
1607 }
1608
1609 int connect_unix_path(int fd, int dir_fd, const char *path) {
1610 _cleanup_close_ int inode_fd = -EBADF;
1611
1612 assert(fd >= 0);
1613 assert(dir_fd == AT_FDCWD || dir_fd >= 0);
1614
1615 /* Connects to the specified AF_UNIX socket in the file system. Works around the 108 byte size limit
1616 * in sockaddr_un, by going via O_PATH if needed. This hence works for any kind of path. */
1617
1618 if (!path)
1619 return connect_unix_inode(fd, dir_fd); /* If no path is specified, then dir_fd refers to the socket inode to connect to. */
1620
1621 /* Refuse zero length path early, to make sure AF_UNIX stack won't mistake this for an abstract
1622 * namespace path, since first char is NUL */
1623 if (isempty(path))
1624 return -EINVAL;
1625
1626 /* Shortcut for the simple case */
1627 if (dir_fd == AT_FDCWD && strlen(path) < sizeof_field(struct sockaddr_un, sun_path))
1628 return connect_unix_path_simple(fd, path);
1629
1630 /* If dir_fd is specified, then we need to go the indirect O_PATH route, because connectat() does not
1631 * exist. If the path is too long, we also need to take the indirect route, since we can't fit this
1632 * into a sockaddr_un directly. */
1633
1634 inode_fd = openat(dir_fd, path, O_PATH|O_CLOEXEC);
1635 if (inode_fd < 0)
1636 return -errno;
1637
1638 return connect_unix_inode(fd, inode_fd);
1639 }
1640
1641 int socket_address_parse_unix(SocketAddress *ret_address, const char *s) {
1642 struct sockaddr_un un;
1643 int r;
1644
1645 assert(ret_address);
1646 assert(s);
1647
1648 if (!IN_SET(*s, '/', '@'))
1649 return -EPROTO;
1650
1651 r = sockaddr_un_set_path(&un, s);
1652 if (r < 0)
1653 return r;
1654
1655 *ret_address = (SocketAddress) {
1656 .sockaddr.un = un,
1657 .size = r,
1658 };
1659
1660 return 0;
1661 }
1662
1663 int vsock_parse_port(const char *s, unsigned *ret) {
1664 int r;
1665
1666 assert(ret);
1667
1668 if (!s)
1669 return -EINVAL;
1670
1671 unsigned u;
1672 r = safe_atou(s, &u);
1673 if (r < 0)
1674 return r;
1675
1676 /* Port 0 is apparently valid and not special in AF_VSOCK (unlike on IP). But VMADDR_PORT_ANY
1677 * (UINT32_MAX) is. Hence refuse that. */
1678
1679 if (u == VMADDR_PORT_ANY)
1680 return -EINVAL;
1681
1682 *ret = u;
1683 return 0;
1684 }
1685
1686 int vsock_parse_cid(const char *s, unsigned *ret) {
1687 assert(ret);
1688
1689 if (!s)
1690 return -EINVAL;
1691
1692 /* Parsed an AF_VSOCK "CID". This is a 32bit entity, and the usual type is "unsigned". We recognize
1693 * the three special CIDs as strings, and otherwise parse the numeric CIDs. */
1694
1695 if (streq(s, "hypervisor"))
1696 *ret = VMADDR_CID_HYPERVISOR;
1697 else if (streq(s, "local"))
1698 *ret = VMADDR_CID_LOCAL;
1699 else if (streq(s, "host"))
1700 *ret = VMADDR_CID_HOST;
1701 else
1702 return safe_atou(s, ret);
1703
1704 return 0;
1705 }
1706
1707 int socket_address_parse_vsock(SocketAddress *ret_address, const char *s) {
1708 /* AF_VSOCK socket in vsock:cid:port notation */
1709 _cleanup_free_ char *n = NULL;
1710 char *e, *cid_start;
1711 unsigned port, cid;
1712 int type, r;
1713
1714 assert(ret_address);
1715 assert(s);
1716
1717 if ((cid_start = startswith(s, "vsock:")))
1718 type = 0;
1719 else if ((cid_start = startswith(s, "vsock-dgram:")))
1720 type = SOCK_DGRAM;
1721 else if ((cid_start = startswith(s, "vsock-seqpacket:")))
1722 type = SOCK_SEQPACKET;
1723 else if ((cid_start = startswith(s, "vsock-stream:")))
1724 type = SOCK_STREAM;
1725 else
1726 return -EPROTO;
1727
1728 e = strchr(cid_start, ':');
1729 if (!e)
1730 return -EINVAL;
1731
1732 r = vsock_parse_port(e+1, &port);
1733 if (r < 0)
1734 return r;
1735
1736 n = strndup(cid_start, e - cid_start);
1737 if (!n)
1738 return -ENOMEM;
1739
1740 if (isempty(n))
1741 cid = VMADDR_CID_ANY;
1742 else {
1743 r = vsock_parse_cid(n, &cid);
1744 if (r < 0)
1745 return r;
1746 }
1747
1748 *ret_address = (SocketAddress) {
1749 .sockaddr.vm = {
1750 .svm_family = AF_VSOCK,
1751 .svm_cid = cid,
1752 .svm_port = port,
1753 },
1754 .type = type,
1755 .size = sizeof(struct sockaddr_vm),
1756 };
1757
1758 return 0;
1759 }
1760
1761 int vsock_get_local_cid(unsigned *ret) {
1762 _cleanup_close_ int vsock_fd = -EBADF;
1763
1764 vsock_fd = open("/dev/vsock", O_RDONLY|O_CLOEXEC);
1765 if (vsock_fd < 0)
1766 return log_debug_errno(errno, "Failed to open /dev/vsock: %m");
1767
1768 unsigned tmp;
1769 if (ioctl(vsock_fd, IOCTL_VM_SOCKETS_GET_LOCAL_CID, ret ?: &tmp) < 0)
1770 return log_debug_errno(errno, "Failed to query local AF_VSOCK CID: %m");
1771
1772 return 0;
1773 }
1774
1775 int netlink_socket_get_multicast_groups(int fd, size_t *ret_len, uint32_t **ret_groups) {
1776 _cleanup_free_ uint32_t *groups = NULL;
1777 socklen_t len = 0, old_len;
1778
1779 assert(fd >= 0);
1780
1781 /* This returns ENOPROTOOPT if the kernel is older than 4.2. */
1782
1783 if (getsockopt(fd, SOL_NETLINK, NETLINK_LIST_MEMBERSHIPS, NULL, &len) < 0)
1784 return -errno;
1785
1786 if (len == 0)
1787 goto finalize;
1788
1789 groups = new0(uint32_t, len);
1790 if (!groups)
1791 return -ENOMEM;
1792
1793 old_len = len;
1794
1795 if (getsockopt(fd, SOL_NETLINK, NETLINK_LIST_MEMBERSHIPS, groups, &len) < 0)
1796 return -errno;
1797
1798 if (old_len != len)
1799 return -EIO;
1800
1801 finalize:
1802 if (ret_len)
1803 *ret_len = len;
1804 if (ret_groups)
1805 *ret_groups = TAKE_PTR(groups);
1806
1807 return 0;
1808 }