]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/basic/socket-util.c
Merge pull request #30284 from YHNdnzj/fstab-wantedby-defaultdeps
[thirdparty/systemd.git] / src / basic / socket-util.c
1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
2
3 #include <arpa/inet.h>
4 #include <errno.h>
5 #include <limits.h>
6 #include <net/if.h>
7 #include <netdb.h>
8 #include <netinet/ip.h>
9 #include <poll.h>
10 #include <stddef.h>
11 #include <stdint.h>
12 #include <stdio.h>
13 #include <stdlib.h>
14 #include <sys/ioctl.h>
15 #include <unistd.h>
16 #include <linux/if.h>
17
18 #include "alloc-util.h"
19 #include "errno-util.h"
20 #include "escape.h"
21 #include "fd-util.h"
22 #include "fileio.h"
23 #include "format-util.h"
24 #include "io-util.h"
25 #include "log.h"
26 #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"
33 #include "strv.h"
34 #include "sysctl-util.h"
35 #include "user-util.h"
36 #include "utf8.h"
37
38 #if ENABLE_IDN
39 # define IDN_FLAGS NI_IDN
40 #else
41 # define IDN_FLAGS 0
42 #endif
43
44 /* From the kernel's include/net/scm.h */
45 #ifndef SCM_MAX_FD
46 # define SCM_MAX_FD 253
47 #endif
48
49 static const char* const socket_address_type_table[] = {
50 [SOCK_STREAM] = "Stream",
51 [SOCK_DGRAM] = "Datagram",
52 [SOCK_RAW] = "Raw",
53 [SOCK_RDM] = "ReliableDatagram",
54 [SOCK_SEQPACKET] = "SequentialPacket",
55 [SOCK_DCCP] = "DatagramCongestionControl",
56 };
57
58 DEFINE_STRING_TABLE_LOOKUP(socket_address_type, int);
59
60 int socket_address_verify(const SocketAddress *a, bool strict) {
61 assert(a);
62
63 /* With 'strict' we enforce additional sanity constraints which are not set by the standard,
64 * but should only apply to sockets we create ourselves. */
65
66 switch (socket_address_family(a)) {
67
68 case AF_INET:
69 if (a->size != sizeof(struct sockaddr_in))
70 return -EINVAL;
71
72 if (a->sockaddr.in.sin_port == 0)
73 return -EINVAL;
74
75 if (!IN_SET(a->type, 0, SOCK_STREAM, SOCK_DGRAM))
76 return -EINVAL;
77
78 return 0;
79
80 case AF_INET6:
81 if (a->size != sizeof(struct sockaddr_in6))
82 return -EINVAL;
83
84 if (a->sockaddr.in6.sin6_port == 0)
85 return -EINVAL;
86
87 if (!IN_SET(a->type, 0, SOCK_STREAM, SOCK_DGRAM))
88 return -EINVAL;
89
90 return 0;
91
92 case AF_UNIX:
93 if (a->size < offsetof(struct sockaddr_un, sun_path))
94 return -EINVAL;
95 if (a->size > sizeof(struct sockaddr_un) + !strict)
96 /* If !strict, allow one extra byte, since getsockname() on Linux will append
97 * a NUL byte if we have path sockets that are above sun_path's full size. */
98 return -EINVAL;
99
100 if (a->size > offsetof(struct sockaddr_un, sun_path) &&
101 a->sockaddr.un.sun_path[0] != 0 &&
102 strict) {
103 /* Only validate file system sockets here, and only in strict mode */
104 const char *e;
105
106 e = memchr(a->sockaddr.un.sun_path, 0, sizeof(a->sockaddr.un.sun_path));
107 if (e) {
108 /* If there's an embedded NUL byte, make sure the size of the socket address matches it */
109 if (a->size != offsetof(struct sockaddr_un, sun_path) + (e - a->sockaddr.un.sun_path) + 1)
110 return -EINVAL;
111 } else {
112 /* If there's no embedded NUL byte, then the size needs to match the whole
113 * structure or the structure with one extra NUL byte suffixed. (Yeah, Linux is awful,
114 * and considers both equivalent: getsockname() even extends sockaddr_un beyond its
115 * size if the path is non NUL terminated.) */
116 if (!IN_SET(a->size, sizeof(a->sockaddr.un.sun_path), sizeof(a->sockaddr.un.sun_path)+1))
117 return -EINVAL;
118 }
119 }
120
121 if (!IN_SET(a->type, 0, SOCK_STREAM, SOCK_DGRAM, SOCK_SEQPACKET))
122 return -EINVAL;
123
124 return 0;
125
126 case AF_NETLINK:
127
128 if (a->size != sizeof(struct sockaddr_nl))
129 return -EINVAL;
130
131 if (!IN_SET(a->type, 0, SOCK_RAW, SOCK_DGRAM))
132 return -EINVAL;
133
134 return 0;
135
136 case AF_VSOCK:
137 if (a->size != sizeof(struct sockaddr_vm))
138 return -EINVAL;
139
140 if (!IN_SET(a->type, 0, SOCK_STREAM, SOCK_DGRAM))
141 return -EINVAL;
142
143 return 0;
144
145 default:
146 return -EAFNOSUPPORT;
147 }
148 }
149
150 int socket_address_print(const SocketAddress *a, char **ret) {
151 int r;
152
153 assert(a);
154 assert(ret);
155
156 r = socket_address_verify(a, false); /* We do non-strict validation, because we want to be
157 * able to pretty-print any socket the kernel considers
158 * valid. We still need to do validation to know if we
159 * can meaningfully print the address. */
160 if (r < 0)
161 return r;
162
163 if (socket_address_family(a) == AF_NETLINK) {
164 _cleanup_free_ char *sfamily = NULL;
165
166 r = netlink_family_to_string_alloc(a->protocol, &sfamily);
167 if (r < 0)
168 return r;
169
170 r = asprintf(ret, "%s %u", sfamily, a->sockaddr.nl.nl_groups);
171 if (r < 0)
172 return -ENOMEM;
173
174 return 0;
175 }
176
177 return sockaddr_pretty(&a->sockaddr.sa, a->size, false, true, ret);
178 }
179
180 bool socket_address_can_accept(const SocketAddress *a) {
181 assert(a);
182
183 return
184 IN_SET(a->type, SOCK_STREAM, SOCK_SEQPACKET);
185 }
186
187 bool socket_address_equal(const SocketAddress *a, const SocketAddress *b) {
188 assert(a);
189 assert(b);
190
191 /* Invalid addresses are unequal to all */
192 if (socket_address_verify(a, false) < 0 ||
193 socket_address_verify(b, false) < 0)
194 return false;
195
196 if (a->type != b->type)
197 return false;
198
199 if (socket_address_family(a) != socket_address_family(b))
200 return false;
201
202 switch (socket_address_family(a)) {
203
204 case AF_INET:
205 if (a->sockaddr.in.sin_addr.s_addr != b->sockaddr.in.sin_addr.s_addr)
206 return false;
207
208 if (a->sockaddr.in.sin_port != b->sockaddr.in.sin_port)
209 return false;
210
211 break;
212
213 case AF_INET6:
214 if (memcmp(&a->sockaddr.in6.sin6_addr, &b->sockaddr.in6.sin6_addr, sizeof(a->sockaddr.in6.sin6_addr)) != 0)
215 return false;
216
217 if (a->sockaddr.in6.sin6_port != b->sockaddr.in6.sin6_port)
218 return false;
219
220 break;
221
222 case AF_UNIX:
223 if (a->size <= offsetof(struct sockaddr_un, sun_path) ||
224 b->size <= offsetof(struct sockaddr_un, sun_path))
225 return false;
226
227 if ((a->sockaddr.un.sun_path[0] == 0) != (b->sockaddr.un.sun_path[0] == 0))
228 return false;
229
230 if (a->sockaddr.un.sun_path[0]) {
231 if (!path_equal_or_inode_same(a->sockaddr.un.sun_path, b->sockaddr.un.sun_path, 0))
232 return false;
233 } else {
234 if (a->size != b->size)
235 return false;
236
237 if (memcmp(a->sockaddr.un.sun_path, b->sockaddr.un.sun_path, a->size) != 0)
238 return false;
239 }
240
241 break;
242
243 case AF_NETLINK:
244 if (a->protocol != b->protocol)
245 return false;
246
247 if (a->sockaddr.nl.nl_groups != b->sockaddr.nl.nl_groups)
248 return false;
249
250 break;
251
252 case AF_VSOCK:
253 if (a->sockaddr.vm.svm_cid != b->sockaddr.vm.svm_cid)
254 return false;
255
256 if (a->sockaddr.vm.svm_port != b->sockaddr.vm.svm_port)
257 return false;
258
259 break;
260
261 default:
262 /* Cannot compare, so we assume the addresses are different */
263 return false;
264 }
265
266 return true;
267 }
268
269 const char* socket_address_get_path(const SocketAddress *a) {
270 assert(a);
271
272 if (socket_address_family(a) != AF_UNIX)
273 return NULL;
274
275 if (a->sockaddr.un.sun_path[0] == 0)
276 return NULL;
277
278 /* Note that this is only safe because we know that there's an extra NUL byte after the sockaddr_un
279 * structure. On Linux AF_UNIX file system socket addresses don't have to be NUL terminated if they take up the
280 * full sun_path space. */
281 assert_cc(sizeof(union sockaddr_union) >= sizeof(struct sockaddr_un)+1);
282 return a->sockaddr.un.sun_path;
283 }
284
285 bool socket_ipv6_is_supported(void) {
286 static int cached = -1;
287
288 if (cached < 0) {
289
290 if (access("/proc/net/if_inet6", F_OK) < 0) {
291
292 if (errno != ENOENT) {
293 log_debug_errno(errno, "Unexpected error when checking whether /proc/net/if_inet6 exists: %m");
294 return false;
295 }
296
297 cached = false;
298 } else
299 cached = true;
300 }
301
302 return cached;
303 }
304
305 bool socket_ipv6_is_enabled(void) {
306 _cleanup_free_ char *v = NULL;
307 int r;
308
309 /* Much like socket_ipv6_is_supported(), but also checks that the sysctl that disables IPv6 on all
310 * interfaces isn't turned on */
311
312 if (!socket_ipv6_is_supported())
313 return false;
314
315 r = sysctl_read_ip_property(AF_INET6, "all", "disable_ipv6", &v);
316 if (r < 0) {
317 log_debug_errno(r, "Unexpected error reading 'net.ipv6.conf.all.disable_ipv6' sysctl: %m");
318 return true;
319 }
320
321 r = parse_boolean(v);
322 if (r < 0) {
323 log_debug_errno(r, "Failed to pare 'net.ipv6.conf.all.disable_ipv6' sysctl: %m");
324 return true;
325 }
326
327 return !r;
328 }
329
330 bool socket_address_matches_fd(const SocketAddress *a, int fd) {
331 SocketAddress b;
332 socklen_t solen;
333
334 assert(a);
335 assert(fd >= 0);
336
337 b.size = sizeof(b.sockaddr);
338 if (getsockname(fd, &b.sockaddr.sa, &b.size) < 0)
339 return false;
340
341 if (b.sockaddr.sa.sa_family != a->sockaddr.sa.sa_family)
342 return false;
343
344 solen = sizeof(b.type);
345 if (getsockopt(fd, SOL_SOCKET, SO_TYPE, &b.type, &solen) < 0)
346 return false;
347
348 if (b.type != a->type)
349 return false;
350
351 if (a->protocol != 0) {
352 solen = sizeof(b.protocol);
353 if (getsockopt(fd, SOL_SOCKET, SO_PROTOCOL, &b.protocol, &solen) < 0)
354 return false;
355
356 if (b.protocol != a->protocol)
357 return false;
358 }
359
360 return socket_address_equal(a, &b);
361 }
362
363 int sockaddr_port(const struct sockaddr *_sa, unsigned *ret_port) {
364 const union sockaddr_union *sa = (const union sockaddr_union*) _sa;
365
366 /* Note, this returns the port as 'unsigned' rather than 'uint16_t', as AF_VSOCK knows larger ports */
367
368 assert(sa);
369
370 switch (sa->sa.sa_family) {
371
372 case AF_INET:
373 *ret_port = be16toh(sa->in.sin_port);
374 return 0;
375
376 case AF_INET6:
377 *ret_port = be16toh(sa->in6.sin6_port);
378 return 0;
379
380 case AF_VSOCK:
381 *ret_port = sa->vm.svm_port;
382 return 0;
383
384 default:
385 return -EAFNOSUPPORT;
386 }
387 }
388
389 const union in_addr_union *sockaddr_in_addr(const struct sockaddr *_sa) {
390 const union sockaddr_union *sa = (const union sockaddr_union*) _sa;
391
392 if (!sa)
393 return NULL;
394
395 switch (sa->sa.sa_family) {
396
397 case AF_INET:
398 return (const union in_addr_union*) &sa->in.sin_addr;
399
400 case AF_INET6:
401 return (const union in_addr_union*) &sa->in6.sin6_addr;
402
403 default:
404 return NULL;
405 }
406 }
407
408 int sockaddr_set_in_addr(
409 union sockaddr_union *u,
410 int family,
411 const union in_addr_union *a,
412 uint16_t port) {
413
414 assert(u);
415 assert(a);
416
417 switch (family) {
418
419 case AF_INET:
420 u->in = (struct sockaddr_in) {
421 .sin_family = AF_INET,
422 .sin_addr = a->in,
423 .sin_port = htobe16(port),
424 };
425
426 return 0;
427
428 case AF_INET6:
429 u->in6 = (struct sockaddr_in6) {
430 .sin6_family = AF_INET6,
431 .sin6_addr = a->in6,
432 .sin6_port = htobe16(port),
433 };
434
435 return 0;
436
437 default:
438 return -EAFNOSUPPORT;
439
440 }
441 }
442
443 int sockaddr_pretty(
444 const struct sockaddr *_sa,
445 socklen_t salen,
446 bool translate_ipv6,
447 bool include_port,
448 char **ret) {
449
450 union sockaddr_union *sa = (union sockaddr_union*) _sa;
451 char *p;
452 int r;
453
454 assert(sa);
455 assert(salen >= sizeof(sa->sa.sa_family));
456
457 switch (sa->sa.sa_family) {
458
459 case AF_INET: {
460 uint32_t a;
461
462 a = be32toh(sa->in.sin_addr.s_addr);
463
464 if (include_port)
465 r = asprintf(&p,
466 "%u.%u.%u.%u:%u",
467 a >> 24, (a >> 16) & 0xFF, (a >> 8) & 0xFF, a & 0xFF,
468 be16toh(sa->in.sin_port));
469 else
470 r = asprintf(&p,
471 "%u.%u.%u.%u",
472 a >> 24, (a >> 16) & 0xFF, (a >> 8) & 0xFF, a & 0xFF);
473 if (r < 0)
474 return -ENOMEM;
475 break;
476 }
477
478 case AF_INET6: {
479 static const unsigned char ipv4_prefix[] = {
480 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xFF, 0xFF
481 };
482
483 if (translate_ipv6 &&
484 memcmp(&sa->in6.sin6_addr, ipv4_prefix, sizeof(ipv4_prefix)) == 0) {
485 const uint8_t *a = sa->in6.sin6_addr.s6_addr+12;
486 if (include_port)
487 r = asprintf(&p,
488 "%u.%u.%u.%u:%u",
489 a[0], a[1], a[2], a[3],
490 be16toh(sa->in6.sin6_port));
491 else
492 r = asprintf(&p,
493 "%u.%u.%u.%u",
494 a[0], a[1], a[2], a[3]);
495 if (r < 0)
496 return -ENOMEM;
497 } else {
498 const char *a = IN6_ADDR_TO_STRING(&sa->in6.sin6_addr);
499
500 if (include_port) {
501 if (asprintf(&p,
502 "[%s]:%u%s%s",
503 a,
504 be16toh(sa->in6.sin6_port),
505 sa->in6.sin6_scope_id != 0 ? "%" : "",
506 FORMAT_IFNAME_FULL(sa->in6.sin6_scope_id, FORMAT_IFNAME_IFINDEX)) < 0)
507 return -ENOMEM;
508 } else {
509 if (sa->in6.sin6_scope_id != 0)
510 p = strjoin(a, "%", FORMAT_IFNAME_FULL(sa->in6.sin6_scope_id, FORMAT_IFNAME_IFINDEX));
511 else
512 p = strdup(a);
513 if (!p)
514 return -ENOMEM;
515 }
516 }
517
518 break;
519 }
520
521 case AF_UNIX:
522 if (salen <= offsetof(struct sockaddr_un, sun_path) ||
523 (sa->un.sun_path[0] == 0 && salen == offsetof(struct sockaddr_un, sun_path) + 1))
524 /* The name must have at least one character (and the leading NUL does not count) */
525 p = strdup("<unnamed>");
526 else {
527 /* Note that we calculate the path pointer here through the .un_buffer[] field, in order to
528 * outtrick bounds checking tools such as ubsan, which are too smart for their own good: on
529 * Linux the kernel may return sun_path[] data one byte longer than the declared size of the
530 * field. */
531 char *path = (char*) sa->un_buffer + offsetof(struct sockaddr_un, sun_path);
532 size_t path_len = salen - offsetof(struct sockaddr_un, sun_path);
533
534 if (path[0] == 0) {
535 /* Abstract socket. When parsing address information from, we
536 * explicitly reject overly long paths and paths with embedded NULs.
537 * But we might get such a socket from the outside. Let's return
538 * something meaningful and printable in this case. */
539
540 _cleanup_free_ char *e = NULL;
541
542 e = cescape_length(path + 1, path_len - 1);
543 if (!e)
544 return -ENOMEM;
545
546 p = strjoin("@", e);
547 } else {
548 if (path[path_len - 1] == '\0')
549 /* We expect a terminating NUL and don't print it */
550 path_len --;
551
552 p = cescape_length(path, path_len);
553 }
554 }
555 if (!p)
556 return -ENOMEM;
557
558 break;
559
560 case AF_VSOCK:
561 if (include_port) {
562 if (sa->vm.svm_cid == VMADDR_CID_ANY)
563 r = asprintf(&p, "vsock::%u", sa->vm.svm_port);
564 else
565 r = asprintf(&p, "vsock:%u:%u", sa->vm.svm_cid, sa->vm.svm_port);
566 } else
567 r = asprintf(&p, "vsock:%u", sa->vm.svm_cid);
568 if (r < 0)
569 return -ENOMEM;
570 break;
571
572 default:
573 return -EOPNOTSUPP;
574 }
575
576 *ret = p;
577 return 0;
578 }
579
580 int getpeername_pretty(int fd, bool include_port, char **ret) {
581 union sockaddr_union sa;
582 socklen_t salen = sizeof(sa);
583 int r;
584
585 assert(fd >= 0);
586 assert(ret);
587
588 if (getpeername(fd, &sa.sa, &salen) < 0)
589 return -errno;
590
591 if (sa.sa.sa_family == AF_UNIX) {
592 struct ucred ucred = UCRED_INVALID;
593
594 /* UNIX connection sockets are anonymous, so let's use
595 * PID/UID as pretty credentials instead */
596
597 r = getpeercred(fd, &ucred);
598 if (r < 0)
599 return r;
600
601 if (asprintf(ret, "PID "PID_FMT"/UID "UID_FMT, ucred.pid, ucred.uid) < 0)
602 return -ENOMEM;
603
604 return 0;
605 }
606
607 /* For remote sockets we translate IPv6 addresses back to IPv4
608 * if applicable, since that's nicer. */
609
610 return sockaddr_pretty(&sa.sa, salen, true, include_port, ret);
611 }
612
613 int getsockname_pretty(int fd, char **ret) {
614 union sockaddr_union sa;
615 socklen_t salen = sizeof(sa);
616
617 assert(fd >= 0);
618 assert(ret);
619
620 if (getsockname(fd, &sa.sa, &salen) < 0)
621 return -errno;
622
623 /* For local sockets we do not translate IPv6 addresses back
624 * to IPv6 if applicable, since this is usually used for
625 * listening sockets where the difference between IPv4 and
626 * IPv6 matters. */
627
628 return sockaddr_pretty(&sa.sa, salen, false, true, ret);
629 }
630
631 int socknameinfo_pretty(union sockaddr_union *sa, socklen_t salen, char **_ret) {
632 int r;
633 char host[NI_MAXHOST], *ret;
634
635 assert(_ret);
636
637 r = getnameinfo(&sa->sa, salen, host, sizeof(host), NULL, 0, IDN_FLAGS);
638 if (r != 0) {
639 int saved_errno = errno;
640
641 r = sockaddr_pretty(&sa->sa, salen, true, true, &ret);
642 if (r < 0)
643 return r;
644
645 log_debug_errno(saved_errno, "getnameinfo(%s) failed: %m", ret);
646 } else {
647 ret = strdup(host);
648 if (!ret)
649 return -ENOMEM;
650 }
651
652 *_ret = ret;
653 return 0;
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) * 64;
929 _cleanup_free_ gid_t *d = NULL;
930
931 assert(fd >= 0);
932 assert(ret);
933
934 for (;;) {
935 d = malloc(n);
936 if (!d)
937 return -ENOMEM;
938
939 if (getsockopt(fd, SOL_SOCKET, SO_PEERGROUPS, d, &n) >= 0)
940 break;
941
942 if (errno != ERANGE)
943 return -errno;
944
945 d = mfree(d);
946 }
947
948 assert_se(n % sizeof(gid_t) == 0);
949 n /= sizeof(gid_t);
950
951 if ((socklen_t) (int) n != n)
952 return -E2BIG;
953
954 *ret = TAKE_PTR(d);
955
956 return (int) n;
957 }
958
959 ssize_t send_many_fds_iov_sa(
960 int transport_fd,
961 int *fds_array, size_t n_fds_array,
962 const struct iovec *iov, size_t iovlen,
963 const struct sockaddr *sa, socklen_t len,
964 int flags) {
965
966 _cleanup_free_ struct cmsghdr *cmsg = NULL;
967 struct msghdr mh = {
968 .msg_name = (struct sockaddr*) sa,
969 .msg_namelen = len,
970 .msg_iov = (struct iovec *)iov,
971 .msg_iovlen = iovlen,
972 };
973 ssize_t k;
974
975 assert(transport_fd >= 0);
976 assert(fds_array || n_fds_array == 0);
977
978 /* The kernel will reject sending more than SCM_MAX_FD FDs at once */
979 if (n_fds_array > SCM_MAX_FD)
980 return -E2BIG;
981
982 /* We need either an FD array or data to send. If there's nothing, return an error. */
983 if (n_fds_array == 0 && !iov)
984 return -EINVAL;
985
986 if (n_fds_array > 0) {
987 mh.msg_controllen = CMSG_SPACE(sizeof(int) * n_fds_array);
988 mh.msg_control = cmsg = malloc(mh.msg_controllen);
989 if (!cmsg)
990 return -ENOMEM;
991
992 *cmsg = (struct cmsghdr) {
993 .cmsg_len = CMSG_LEN(sizeof(int) * n_fds_array),
994 .cmsg_level = SOL_SOCKET,
995 .cmsg_type = SCM_RIGHTS,
996 };
997 memcpy(CMSG_DATA(cmsg), fds_array, sizeof(int) * n_fds_array);
998 }
999 k = sendmsg(transport_fd, &mh, MSG_NOSIGNAL | flags);
1000 if (k < 0)
1001 return (ssize_t) -errno;
1002
1003 return k;
1004 }
1005
1006 ssize_t send_one_fd_iov_sa(
1007 int transport_fd,
1008 int fd,
1009 const struct iovec *iov, size_t iovlen,
1010 const struct sockaddr *sa, socklen_t len,
1011 int flags) {
1012
1013 CMSG_BUFFER_TYPE(CMSG_SPACE(sizeof(int))) control = {};
1014 struct msghdr mh = {
1015 .msg_name = (struct sockaddr*) sa,
1016 .msg_namelen = len,
1017 .msg_iov = (struct iovec *)iov,
1018 .msg_iovlen = iovlen,
1019 };
1020 ssize_t k;
1021
1022 assert(transport_fd >= 0);
1023
1024 /*
1025 * We need either an FD or data to send.
1026 * If there's nothing, return an error.
1027 */
1028 if (fd < 0 && !iov)
1029 return -EINVAL;
1030
1031 if (fd >= 0) {
1032 struct cmsghdr *cmsg;
1033
1034 mh.msg_control = &control;
1035 mh.msg_controllen = sizeof(control);
1036
1037 cmsg = CMSG_FIRSTHDR(&mh);
1038 cmsg->cmsg_level = SOL_SOCKET;
1039 cmsg->cmsg_type = SCM_RIGHTS;
1040 cmsg->cmsg_len = CMSG_LEN(sizeof(int));
1041 memcpy(CMSG_DATA(cmsg), &fd, sizeof(int));
1042 }
1043 k = sendmsg(transport_fd, &mh, MSG_NOSIGNAL | flags);
1044 if (k < 0)
1045 return (ssize_t) -errno;
1046
1047 return k;
1048 }
1049
1050 int send_one_fd_sa(
1051 int transport_fd,
1052 int fd,
1053 const struct sockaddr *sa, socklen_t len,
1054 int flags) {
1055
1056 assert(fd >= 0);
1057
1058 return (int) send_one_fd_iov_sa(transport_fd, fd, NULL, 0, sa, len, flags);
1059 }
1060
1061 ssize_t receive_many_fds_iov(
1062 int transport_fd,
1063 struct iovec *iov, size_t iovlen,
1064 int **ret_fds_array, size_t *ret_n_fds_array,
1065 int flags) {
1066
1067 CMSG_BUFFER_TYPE(CMSG_SPACE(sizeof(int) * SCM_MAX_FD)) control;
1068 struct msghdr mh = {
1069 .msg_control = &control,
1070 .msg_controllen = sizeof(control),
1071 .msg_iov = iov,
1072 .msg_iovlen = iovlen,
1073 };
1074 _cleanup_free_ int *fds_array = NULL;
1075 size_t n_fds_array = 0;
1076 struct cmsghdr *cmsg;
1077 ssize_t k;
1078
1079 assert(transport_fd >= 0);
1080 assert(ret_fds_array);
1081 assert(ret_n_fds_array);
1082
1083 /*
1084 * Receive many FDs via @transport_fd. We don't care for the transport-type. We retrieve all the FDs
1085 * at once. This is best used in combination with send_many_fds().
1086 */
1087
1088 k = recvmsg_safe(transport_fd, &mh, MSG_CMSG_CLOEXEC | flags);
1089 if (k < 0)
1090 return k;
1091
1092 CMSG_FOREACH(cmsg, &mh)
1093 if (cmsg->cmsg_level == SOL_SOCKET && cmsg->cmsg_type == SCM_RIGHTS) {
1094 size_t n = (cmsg->cmsg_len - CMSG_LEN(0)) / sizeof(int);
1095
1096 fds_array = GREEDY_REALLOC(fds_array, n_fds_array + n);
1097 if (!fds_array) {
1098 cmsg_close_all(&mh);
1099 return -ENOMEM;
1100 }
1101
1102 memcpy(fds_array + n_fds_array, CMSG_TYPED_DATA(cmsg, int), sizeof(int) * n);
1103 n_fds_array += n;
1104 }
1105
1106 if (n_fds_array == 0) {
1107 cmsg_close_all(&mh);
1108
1109 /* If didn't receive an FD or any data, return an error. */
1110 if (k == 0)
1111 return -EIO;
1112 }
1113
1114 *ret_fds_array = TAKE_PTR(fds_array);
1115 *ret_n_fds_array = n_fds_array;
1116
1117 return k;
1118 }
1119
1120 int receive_many_fds(int transport_fd, int **ret_fds_array, size_t *ret_n_fds_array, int flags) {
1121 ssize_t k;
1122
1123 k = receive_many_fds_iov(transport_fd, NULL, 0, ret_fds_array, ret_n_fds_array, flags);
1124 if (k == 0)
1125 return 0;
1126
1127 /* k must be negative, since receive_many_fds_iov() only returns a positive value if data was received
1128 * through the iov. */
1129 assert(k < 0);
1130 return (int) k;
1131 }
1132
1133 ssize_t receive_one_fd_iov(
1134 int transport_fd,
1135 struct iovec *iov, size_t iovlen,
1136 int flags,
1137 int *ret_fd) {
1138
1139 CMSG_BUFFER_TYPE(CMSG_SPACE(sizeof(int))) control;
1140 struct msghdr mh = {
1141 .msg_control = &control,
1142 .msg_controllen = sizeof(control),
1143 .msg_iov = iov,
1144 .msg_iovlen = iovlen,
1145 };
1146 struct cmsghdr *found;
1147 ssize_t k;
1148
1149 assert(transport_fd >= 0);
1150 assert(ret_fd);
1151
1152 /*
1153 * Receive a single FD via @transport_fd. We don't care for
1154 * the transport-type. We retrieve a single FD at most, so for
1155 * packet-based transports, the caller must ensure to send
1156 * only a single FD per packet. This is best used in
1157 * combination with send_one_fd().
1158 */
1159
1160 k = recvmsg_safe(transport_fd, &mh, MSG_CMSG_CLOEXEC | flags);
1161 if (k < 0)
1162 return k;
1163
1164 found = cmsg_find(&mh, SOL_SOCKET, SCM_RIGHTS, CMSG_LEN(sizeof(int)));
1165 if (!found) {
1166 cmsg_close_all(&mh);
1167
1168 /* If didn't receive an FD or any data, return an error. */
1169 if (k == 0)
1170 return -EIO;
1171 }
1172
1173 if (found)
1174 *ret_fd = *CMSG_TYPED_DATA(found, int);
1175 else
1176 *ret_fd = -EBADF;
1177
1178 return k;
1179 }
1180
1181 int receive_one_fd(int transport_fd, int flags) {
1182 int fd;
1183 ssize_t k;
1184
1185 k = receive_one_fd_iov(transport_fd, NULL, 0, flags, &fd);
1186 if (k == 0)
1187 return fd;
1188
1189 /* k must be negative, since receive_one_fd_iov() only returns
1190 * a positive value if data was received through the iov. */
1191 assert(k < 0);
1192 return (int) k;
1193 }
1194
1195 ssize_t next_datagram_size_fd(int fd) {
1196 ssize_t l;
1197 int k;
1198
1199 /* This is a bit like FIONREAD/SIOCINQ, however a bit more powerful. The difference being: recv(MSG_PEEK) will
1200 * actually cause the next datagram in the queue to be validated regarding checksums, which FIONREAD doesn't
1201 * do. This difference is actually of major importance as we need to be sure that the size returned here
1202 * actually matches what we will read with recvmsg() next, as otherwise we might end up allocating a buffer of
1203 * the wrong size. */
1204
1205 l = recv(fd, NULL, 0, MSG_PEEK|MSG_TRUNC);
1206 if (l < 0) {
1207 if (IN_SET(errno, EOPNOTSUPP, EFAULT))
1208 goto fallback;
1209
1210 return -errno;
1211 }
1212 if (l == 0)
1213 goto fallback;
1214
1215 return l;
1216
1217 fallback:
1218 k = 0;
1219
1220 /* Some sockets (AF_PACKET) do not support null-sized recv() with MSG_TRUNC set, let's fall back to FIONREAD
1221 * for them. Checksums don't matter for raw sockets anyway, hence this should be fine. */
1222
1223 if (ioctl(fd, FIONREAD, &k) < 0)
1224 return -errno;
1225
1226 return (ssize_t) k;
1227 }
1228
1229 /* Put a limit on how many times will attempt to call accept4(). We loop
1230 * only on "transient" errors, but let's make sure we don't loop forever. */
1231 #define MAX_FLUSH_ITERATIONS 1024
1232
1233 int flush_accept(int fd) {
1234
1235 int r, b;
1236 socklen_t l = sizeof(b);
1237
1238 /* Similar to flush_fd() but flushes all incoming connections by accepting and immediately closing
1239 * them. */
1240
1241 if (getsockopt(fd, SOL_SOCKET, SO_ACCEPTCONN, &b, &l) < 0)
1242 return -errno;
1243
1244 assert(l == sizeof(b));
1245 if (!b) /* Let's check if this socket accepts connections before calling accept(). accept4() can
1246 * return EOPNOTSUPP if the fd is not a listening socket, which we should treat as a fatal
1247 * error, or in case the incoming TCP connection triggered a network issue, which we want to
1248 * treat as a transient error. Thus, let's rule out the first reason for EOPNOTSUPP early, so
1249 * we can loop safely on transient errors below. */
1250 return -ENOTTY;
1251
1252 for (unsigned iteration = 0;; iteration++) {
1253 int cfd;
1254
1255 r = fd_wait_for_event(fd, POLLIN, 0);
1256 if (r < 0) {
1257 if (r == -EINTR)
1258 continue;
1259
1260 return r;
1261 }
1262 if (r == 0)
1263 return 0;
1264
1265 if (iteration >= MAX_FLUSH_ITERATIONS)
1266 return log_debug_errno(SYNTHETIC_ERRNO(EBUSY),
1267 "Failed to flush connections within " STRINGIFY(MAX_FLUSH_ITERATIONS) " iterations.");
1268
1269 cfd = accept4(fd, NULL, NULL, SOCK_NONBLOCK|SOCK_CLOEXEC);
1270 if (cfd < 0) {
1271 if (errno == EAGAIN)
1272 return 0;
1273
1274 if (ERRNO_IS_ACCEPT_AGAIN(errno))
1275 continue;
1276
1277 return -errno;
1278 }
1279
1280 safe_close(cfd);
1281 }
1282 }
1283
1284 struct cmsghdr* cmsg_find(struct msghdr *mh, int level, int type, socklen_t length) {
1285 struct cmsghdr *cmsg;
1286
1287 assert(mh);
1288
1289 CMSG_FOREACH(cmsg, mh)
1290 if (cmsg->cmsg_level == level &&
1291 cmsg->cmsg_type == type &&
1292 (length == (socklen_t) -1 || length == cmsg->cmsg_len))
1293 return cmsg;
1294
1295 return NULL;
1296 }
1297
1298 void* cmsg_find_and_copy_data(struct msghdr *mh, int level, int type, void *buf, size_t buf_len) {
1299 struct cmsghdr *cmsg;
1300
1301 assert(mh);
1302 assert(buf);
1303 assert(buf_len > 0);
1304
1305 /* This is similar to cmsg_find_data(), but copy the found data to buf. This should be typically used
1306 * when reading possibly unaligned data such as timestamp, as time_t is 64-bit and size_t is 32-bit on
1307 * RISCV32. See issue #27241. */
1308
1309 cmsg = cmsg_find(mh, level, type, CMSG_LEN(buf_len));
1310 if (!cmsg)
1311 return NULL;
1312
1313 return memcpy_safe(buf, CMSG_DATA(cmsg), buf_len);
1314 }
1315
1316 int socket_ioctl_fd(void) {
1317 int fd;
1318
1319 /* Create a socket to invoke the various network interface ioctl()s on. Traditionally only AF_INET was good for
1320 * that. Since kernel 4.6 AF_NETLINK works for this too. We first try to use AF_INET hence, but if that's not
1321 * available (for example, because it is made unavailable via SECCOMP or such), we'll fall back to the more
1322 * generic AF_NETLINK. */
1323
1324 fd = socket(AF_INET, SOCK_DGRAM|SOCK_CLOEXEC, 0);
1325 if (fd < 0)
1326 fd = socket(AF_NETLINK, SOCK_RAW|SOCK_CLOEXEC, NETLINK_GENERIC);
1327 if (fd < 0)
1328 return -errno;
1329
1330 return fd;
1331 }
1332
1333 int sockaddr_un_unlink(const struct sockaddr_un *sa) {
1334 const char *p, * nul;
1335
1336 assert(sa);
1337
1338 if (sa->sun_family != AF_UNIX)
1339 return -EPROTOTYPE;
1340
1341 if (sa->sun_path[0] == 0) /* Nothing to do for abstract sockets */
1342 return 0;
1343
1344 /* The path in .sun_path is not necessarily NUL terminated. Let's fix that. */
1345 nul = memchr(sa->sun_path, 0, sizeof(sa->sun_path));
1346 if (nul)
1347 p = sa->sun_path;
1348 else
1349 p = memdupa_suffix0(sa->sun_path, sizeof(sa->sun_path));
1350
1351 if (unlink(p) < 0)
1352 return -errno;
1353
1354 return 1;
1355 }
1356
1357 int sockaddr_un_set_path(struct sockaddr_un *ret, const char *path) {
1358 size_t l;
1359
1360 assert(ret);
1361 assert(path);
1362
1363 /* Initialize ret->sun_path from the specified argument. This will interpret paths starting with '@' as
1364 * abstract namespace sockets, and those starting with '/' as regular filesystem sockets. It won't accept
1365 * anything else (i.e. no relative paths), to avoid ambiguities. Note that this function cannot be used to
1366 * reference paths in the abstract namespace that include NUL bytes in the name. */
1367
1368 l = strlen(path);
1369 if (l < 2)
1370 return -EINVAL;
1371 if (!IN_SET(path[0], '/', '@'))
1372 return -EINVAL;
1373
1374 /* Don't allow paths larger than the space in sockaddr_un. Note that we are a tiny bit more restrictive than
1375 * the kernel is: we insist on NUL termination (both for abstract namespace and regular file system socket
1376 * addresses!), which the kernel doesn't. We do this to reduce chance of incompatibility with other apps that
1377 * do not expect non-NUL terminated file system path. */
1378 if (l+1 > sizeof(ret->sun_path))
1379 return path[0] == '@' ? -EINVAL : -ENAMETOOLONG; /* return a recognizable error if this is
1380 * too long to fit into a sockaddr_un, but
1381 * is a file system path, and thus might be
1382 * connectible via O_PATH indirection. */
1383
1384 *ret = (struct sockaddr_un) {
1385 .sun_family = AF_UNIX,
1386 };
1387
1388 if (path[0] == '@') {
1389 /* Abstract namespace socket */
1390 memcpy(ret->sun_path + 1, path + 1, l); /* copy *with* trailing NUL byte */
1391 return (int) (offsetof(struct sockaddr_un, sun_path) + l); /* 🔥 *don't* 🔥 include trailing NUL in size */
1392
1393 } else {
1394 assert(path[0] == '/');
1395
1396 /* File system socket */
1397 memcpy(ret->sun_path, path, l + 1); /* copy *with* trailing NUL byte */
1398 return (int) (offsetof(struct sockaddr_un, sun_path) + l + 1); /* include trailing NUL in size */
1399 }
1400 }
1401
1402 int socket_bind_to_ifname(int fd, const char *ifname) {
1403 assert(fd >= 0);
1404
1405 /* Call with NULL to drop binding */
1406
1407 return RET_NERRNO(setsockopt(fd, SOL_SOCKET, SO_BINDTODEVICE, ifname, strlen_ptr(ifname)));
1408 }
1409
1410 int socket_bind_to_ifindex(int fd, int ifindex) {
1411 char ifname[IF_NAMESIZE];
1412 int r;
1413
1414 assert(fd >= 0);
1415
1416 if (ifindex <= 0)
1417 /* Drop binding */
1418 return RET_NERRNO(setsockopt(fd, SOL_SOCKET, SO_BINDTODEVICE, NULL, 0));
1419
1420 r = setsockopt_int(fd, SOL_SOCKET, SO_BINDTOIFINDEX, ifindex);
1421 if (r != -ENOPROTOOPT)
1422 return r;
1423
1424 /* Fall back to SO_BINDTODEVICE on kernels < 5.0 which didn't have SO_BINDTOIFINDEX */
1425 r = format_ifname(ifindex, ifname);
1426 if (r < 0)
1427 return r;
1428
1429 return socket_bind_to_ifname(fd, ifname);
1430 }
1431
1432 ssize_t recvmsg_safe(int sockfd, struct msghdr *msg, int flags) {
1433 ssize_t n;
1434
1435 /* A wrapper around recvmsg() that checks for MSG_CTRUNC, and turns it into an error, in a reasonably
1436 * safe way, closing any SCM_RIGHTS fds in the error path.
1437 *
1438 * Note that unlike our usual coding style this might modify *msg on failure. */
1439
1440 n = recvmsg(sockfd, msg, flags);
1441 if (n < 0)
1442 return -errno;
1443
1444 if (FLAGS_SET(msg->msg_flags, MSG_CTRUNC)) {
1445 cmsg_close_all(msg);
1446 return -EXFULL; /* a recognizable error code */
1447 }
1448
1449 return n;
1450 }
1451
1452 int socket_get_family(int fd) {
1453 int af;
1454 socklen_t sl = sizeof(af);
1455
1456 if (getsockopt(fd, SOL_SOCKET, SO_DOMAIN, &af, &sl) < 0)
1457 return -errno;
1458
1459 if (sl != sizeof(af))
1460 return -EINVAL;
1461
1462 return af;
1463 }
1464
1465 int socket_set_recvpktinfo(int fd, int af, bool b) {
1466
1467 if (af == AF_UNSPEC) {
1468 af = socket_get_family(fd);
1469 if (af < 0)
1470 return af;
1471 }
1472
1473 switch (af) {
1474
1475 case AF_INET:
1476 return setsockopt_int(fd, IPPROTO_IP, IP_PKTINFO, b);
1477
1478 case AF_INET6:
1479 return setsockopt_int(fd, IPPROTO_IPV6, IPV6_RECVPKTINFO, b);
1480
1481 case AF_NETLINK:
1482 return setsockopt_int(fd, SOL_NETLINK, NETLINK_PKTINFO, b);
1483
1484 case AF_PACKET:
1485 return setsockopt_int(fd, SOL_PACKET, PACKET_AUXDATA, b);
1486
1487 default:
1488 return -EAFNOSUPPORT;
1489 }
1490 }
1491
1492 int socket_set_unicast_if(int fd, int af, int ifi) {
1493 be32_t ifindex_be = htobe32(ifi);
1494
1495 if (af == AF_UNSPEC) {
1496 af = socket_get_family(fd);
1497 if (af < 0)
1498 return af;
1499 }
1500
1501 switch (af) {
1502
1503 case AF_INET:
1504 return RET_NERRNO(setsockopt(fd, IPPROTO_IP, IP_UNICAST_IF, &ifindex_be, sizeof(ifindex_be)));
1505
1506 case AF_INET6:
1507 return RET_NERRNO(setsockopt(fd, IPPROTO_IPV6, IPV6_UNICAST_IF, &ifindex_be, sizeof(ifindex_be)));
1508
1509 default:
1510 return -EAFNOSUPPORT;
1511 }
1512 }
1513
1514 int socket_set_option(int fd, int af, int opt_ipv4, int opt_ipv6, int val) {
1515 if (af == AF_UNSPEC) {
1516 af = socket_get_family(fd);
1517 if (af < 0)
1518 return af;
1519 }
1520
1521 switch (af) {
1522
1523 case AF_INET:
1524 return setsockopt_int(fd, IPPROTO_IP, opt_ipv4, val);
1525
1526 case AF_INET6:
1527 return setsockopt_int(fd, IPPROTO_IPV6, opt_ipv6, val);
1528
1529 default:
1530 return -EAFNOSUPPORT;
1531 }
1532 }
1533
1534 int socket_get_mtu(int fd, int af, size_t *ret) {
1535 int mtu, r;
1536
1537 if (af == AF_UNSPEC) {
1538 af = socket_get_family(fd);
1539 if (af < 0)
1540 return af;
1541 }
1542
1543 switch (af) {
1544
1545 case AF_INET:
1546 r = getsockopt_int(fd, IPPROTO_IP, IP_MTU, &mtu);
1547 break;
1548
1549 case AF_INET6:
1550 r = getsockopt_int(fd, IPPROTO_IPV6, IPV6_MTU, &mtu);
1551 break;
1552
1553 default:
1554 return -EAFNOSUPPORT;
1555 }
1556
1557 if (r < 0)
1558 return r;
1559 if (mtu <= 0)
1560 return -EINVAL;
1561
1562 *ret = (size_t) mtu;
1563 return 0;
1564 }
1565
1566 static int connect_unix_path_simple(int fd, const char *path) {
1567 union sockaddr_union sa = {
1568 .un.sun_family = AF_UNIX,
1569 };
1570 size_t l;
1571
1572 assert(fd >= 0);
1573 assert(path);
1574
1575 l = strlen(path);
1576 assert(l > 0);
1577 assert(l < sizeof(sa.un.sun_path));
1578
1579 memcpy(sa.un.sun_path, path, l + 1);
1580 return RET_NERRNO(connect(fd, &sa.sa, offsetof(struct sockaddr_un, sun_path) + l + 1));
1581 }
1582
1583 static int connect_unix_inode(int fd, int inode_fd) {
1584 assert(fd >= 0);
1585 assert(inode_fd >= 0);
1586
1587 return connect_unix_path_simple(fd, FORMAT_PROC_FD_PATH(inode_fd));
1588 }
1589
1590 int connect_unix_path(int fd, int dir_fd, const char *path) {
1591 _cleanup_close_ int inode_fd = -EBADF;
1592
1593 assert(fd >= 0);
1594 assert(dir_fd == AT_FDCWD || dir_fd >= 0);
1595
1596 /* Connects to the specified AF_UNIX socket in the file system. Works around the 108 byte size limit
1597 * in sockaddr_un, by going via O_PATH if needed. This hence works for any kind of path. */
1598
1599 if (!path)
1600 return connect_unix_inode(fd, dir_fd); /* If no path is specified, then dir_fd refers to the socket inode to connect to. */
1601
1602 /* Refuse zero length path early, to make sure AF_UNIX stack won't mistake this for an abstract
1603 * namespace path, since first char is NUL */
1604 if (isempty(path))
1605 return -EINVAL;
1606
1607 /* Shortcut for the simple case */
1608 if (dir_fd == AT_FDCWD && strlen(path) < sizeof_field(struct sockaddr_un, sun_path))
1609 return connect_unix_path_simple(fd, path);
1610
1611 /* If dir_fd is specified, then we need to go the indirect O_PATH route, because connectat() does not
1612 * exist. If the path is too long, we also need to take the indirect route, since we can't fit this
1613 * into a sockaddr_un directly. */
1614
1615 inode_fd = openat(dir_fd, path, O_PATH|O_CLOEXEC);
1616 if (inode_fd < 0)
1617 return -errno;
1618
1619 return connect_unix_inode(fd, inode_fd);
1620 }
1621
1622 int socket_address_parse_unix(SocketAddress *ret_address, const char *s) {
1623 struct sockaddr_un un;
1624 int r;
1625
1626 assert(ret_address);
1627 assert(s);
1628
1629 if (!IN_SET(*s, '/', '@'))
1630 return -EPROTO;
1631
1632 r = sockaddr_un_set_path(&un, s);
1633 if (r < 0)
1634 return r;
1635
1636 *ret_address = (SocketAddress) {
1637 .sockaddr.un = un,
1638 .size = r,
1639 };
1640
1641 return 0;
1642 }
1643
1644 int socket_address_parse_vsock(SocketAddress *ret_address, const char *s) {
1645 /* AF_VSOCK socket in vsock:cid:port notation */
1646 _cleanup_free_ char *n = NULL;
1647 char *e, *cid_start;
1648 unsigned port, cid;
1649 int type, r;
1650
1651 assert(ret_address);
1652 assert(s);
1653
1654 if ((cid_start = startswith(s, "vsock:")))
1655 type = 0;
1656 else if ((cid_start = startswith(s, "vsock-dgram:")))
1657 type = SOCK_DGRAM;
1658 else if ((cid_start = startswith(s, "vsock-seqpacket:")))
1659 type = SOCK_SEQPACKET;
1660 else if ((cid_start = startswith(s, "vsock-stream:")))
1661 type = SOCK_STREAM;
1662 else
1663 return -EPROTO;
1664
1665 e = strchr(cid_start, ':');
1666 if (!e)
1667 return -EINVAL;
1668
1669 r = safe_atou(e+1, &port);
1670 if (r < 0)
1671 return r;
1672
1673 n = strndup(cid_start, e - cid_start);
1674 if (!n)
1675 return -ENOMEM;
1676
1677 if (isempty(n))
1678 cid = VMADDR_CID_ANY;
1679 else {
1680 r = safe_atou(n, &cid);
1681 if (r < 0)
1682 return r;
1683 }
1684
1685 *ret_address = (SocketAddress) {
1686 .sockaddr.vm = {
1687 .svm_cid = cid,
1688 .svm_family = AF_VSOCK,
1689 .svm_port = port,
1690 },
1691 .type = type,
1692 .size = sizeof(struct sockaddr_vm),
1693 };
1694
1695 return 0;
1696 }