]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/basic/socket-util.c
Merge pull request #20219 from khfeng/use-intel-hid-rfkill
[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 static const char* const socket_address_type_table[] = {
45 [SOCK_STREAM] = "Stream",
46 [SOCK_DGRAM] = "Datagram",
47 [SOCK_RAW] = "Raw",
48 [SOCK_RDM] = "ReliableDatagram",
49 [SOCK_SEQPACKET] = "SequentialPacket",
50 [SOCK_DCCP] = "DatagramCongestionControl",
51 };
52
53 DEFINE_STRING_TABLE_LOOKUP(socket_address_type, int);
54
55 int socket_address_verify(const SocketAddress *a, bool strict) {
56 assert(a);
57
58 /* With 'strict' we enforce additional sanity constraints which are not set by the standard,
59 * but should only apply to sockets we create ourselves. */
60
61 switch (socket_address_family(a)) {
62
63 case AF_INET:
64 if (a->size != sizeof(struct sockaddr_in))
65 return -EINVAL;
66
67 if (a->sockaddr.in.sin_port == 0)
68 return -EINVAL;
69
70 if (!IN_SET(a->type, 0, SOCK_STREAM, SOCK_DGRAM))
71 return -EINVAL;
72
73 return 0;
74
75 case AF_INET6:
76 if (a->size != sizeof(struct sockaddr_in6))
77 return -EINVAL;
78
79 if (a->sockaddr.in6.sin6_port == 0)
80 return -EINVAL;
81
82 if (!IN_SET(a->type, 0, SOCK_STREAM, SOCK_DGRAM))
83 return -EINVAL;
84
85 return 0;
86
87 case AF_UNIX:
88 if (a->size < offsetof(struct sockaddr_un, sun_path))
89 return -EINVAL;
90 if (a->size > sizeof(struct sockaddr_un) + !strict)
91 /* If !strict, allow one extra byte, since getsockname() on Linux will append
92 * a NUL byte if we have path sockets that are above sun_path's full size. */
93 return -EINVAL;
94
95 if (a->size > offsetof(struct sockaddr_un, sun_path) &&
96 a->sockaddr.un.sun_path[0] != 0 &&
97 strict) {
98 /* Only validate file system sockets here, and only in strict mode */
99 const char *e;
100
101 e = memchr(a->sockaddr.un.sun_path, 0, sizeof(a->sockaddr.un.sun_path));
102 if (e) {
103 /* If there's an embedded NUL byte, make sure the size of the socket address matches it */
104 if (a->size != offsetof(struct sockaddr_un, sun_path) + (e - a->sockaddr.un.sun_path) + 1)
105 return -EINVAL;
106 } else {
107 /* If there's no embedded NUL byte, then the size needs to match the whole
108 * structure or the structure with one extra NUL byte suffixed. (Yeah, Linux is awful,
109 * and considers both equivalent: getsockname() even extends sockaddr_un beyond its
110 * size if the path is non NUL terminated.) */
111 if (!IN_SET(a->size, sizeof(a->sockaddr.un.sun_path), sizeof(a->sockaddr.un.sun_path)+1))
112 return -EINVAL;
113 }
114 }
115
116 if (!IN_SET(a->type, 0, SOCK_STREAM, SOCK_DGRAM, SOCK_SEQPACKET))
117 return -EINVAL;
118
119 return 0;
120
121 case AF_NETLINK:
122
123 if (a->size != sizeof(struct sockaddr_nl))
124 return -EINVAL;
125
126 if (!IN_SET(a->type, 0, SOCK_RAW, SOCK_DGRAM))
127 return -EINVAL;
128
129 return 0;
130
131 case AF_VSOCK:
132 if (a->size != sizeof(struct sockaddr_vm))
133 return -EINVAL;
134
135 if (!IN_SET(a->type, 0, SOCK_STREAM, SOCK_DGRAM))
136 return -EINVAL;
137
138 return 0;
139
140 default:
141 return -EAFNOSUPPORT;
142 }
143 }
144
145 int socket_address_print(const SocketAddress *a, char **ret) {
146 int r;
147
148 assert(a);
149 assert(ret);
150
151 r = socket_address_verify(a, false); /* We do non-strict validation, because we want to be
152 * able to pretty-print any socket the kernel considers
153 * valid. We still need to do validation to know if we
154 * can meaningfully print the address. */
155 if (r < 0)
156 return r;
157
158 if (socket_address_family(a) == AF_NETLINK) {
159 _cleanup_free_ char *sfamily = NULL;
160
161 r = netlink_family_to_string_alloc(a->protocol, &sfamily);
162 if (r < 0)
163 return r;
164
165 r = asprintf(ret, "%s %u", sfamily, a->sockaddr.nl.nl_groups);
166 if (r < 0)
167 return -ENOMEM;
168
169 return 0;
170 }
171
172 return sockaddr_pretty(&a->sockaddr.sa, a->size, false, true, ret);
173 }
174
175 bool socket_address_can_accept(const SocketAddress *a) {
176 assert(a);
177
178 return
179 IN_SET(a->type, SOCK_STREAM, SOCK_SEQPACKET);
180 }
181
182 bool socket_address_equal(const SocketAddress *a, const SocketAddress *b) {
183 assert(a);
184 assert(b);
185
186 /* Invalid addresses are unequal to all */
187 if (socket_address_verify(a, false) < 0 ||
188 socket_address_verify(b, false) < 0)
189 return false;
190
191 if (a->type != b->type)
192 return false;
193
194 if (socket_address_family(a) != socket_address_family(b))
195 return false;
196
197 switch (socket_address_family(a)) {
198
199 case AF_INET:
200 if (a->sockaddr.in.sin_addr.s_addr != b->sockaddr.in.sin_addr.s_addr)
201 return false;
202
203 if (a->sockaddr.in.sin_port != b->sockaddr.in.sin_port)
204 return false;
205
206 break;
207
208 case AF_INET6:
209 if (memcmp(&a->sockaddr.in6.sin6_addr, &b->sockaddr.in6.sin6_addr, sizeof(a->sockaddr.in6.sin6_addr)) != 0)
210 return false;
211
212 if (a->sockaddr.in6.sin6_port != b->sockaddr.in6.sin6_port)
213 return false;
214
215 break;
216
217 case AF_UNIX:
218 if (a->size <= offsetof(struct sockaddr_un, sun_path) ||
219 b->size <= offsetof(struct sockaddr_un, sun_path))
220 return false;
221
222 if ((a->sockaddr.un.sun_path[0] == 0) != (b->sockaddr.un.sun_path[0] == 0))
223 return false;
224
225 if (a->sockaddr.un.sun_path[0]) {
226 if (!path_equal_or_files_same(a->sockaddr.un.sun_path, b->sockaddr.un.sun_path, 0))
227 return false;
228 } else {
229 if (a->size != b->size)
230 return false;
231
232 if (memcmp(a->sockaddr.un.sun_path, b->sockaddr.un.sun_path, a->size) != 0)
233 return false;
234 }
235
236 break;
237
238 case AF_NETLINK:
239 if (a->protocol != b->protocol)
240 return false;
241
242 if (a->sockaddr.nl.nl_groups != b->sockaddr.nl.nl_groups)
243 return false;
244
245 break;
246
247 case AF_VSOCK:
248 if (a->sockaddr.vm.svm_cid != b->sockaddr.vm.svm_cid)
249 return false;
250
251 if (a->sockaddr.vm.svm_port != b->sockaddr.vm.svm_port)
252 return false;
253
254 break;
255
256 default:
257 /* Cannot compare, so we assume the addresses are different */
258 return false;
259 }
260
261 return true;
262 }
263
264 const char* socket_address_get_path(const SocketAddress *a) {
265 assert(a);
266
267 if (socket_address_family(a) != AF_UNIX)
268 return NULL;
269
270 if (a->sockaddr.un.sun_path[0] == 0)
271 return NULL;
272
273 /* Note that this is only safe because we know that there's an extra NUL byte after the sockaddr_un
274 * structure. On Linux AF_UNIX file system socket addresses don't have to be NUL terminated if they take up the
275 * full sun_path space. */
276 assert_cc(sizeof(union sockaddr_union) >= sizeof(struct sockaddr_un)+1);
277 return a->sockaddr.un.sun_path;
278 }
279
280 bool socket_ipv6_is_supported(void) {
281 static int cached = -1;
282
283 if (cached < 0) {
284
285 if (access("/proc/net/if_inet6", F_OK) < 0) {
286
287 if (errno != ENOENT) {
288 log_debug_errno(errno, "Unexpected error when checking whether /proc/net/if_inet6 exists: %m");
289 return false;
290 }
291
292 cached = false;
293 } else
294 cached = true;
295 }
296
297 return cached;
298 }
299
300 bool socket_ipv6_is_enabled(void) {
301 _cleanup_free_ char *v = NULL;
302 int r;
303
304 /* Much like socket_ipv6_is_supported(), but also checks that the sysctl that disables IPv6 on all
305 * interfaces isn't turned on */
306
307 if (!socket_ipv6_is_supported())
308 return false;
309
310 r = sysctl_read_ip_property(AF_INET6, "all", "disable_ipv6", &v);
311 if (r < 0) {
312 log_debug_errno(r, "Unexpected error reading 'net.ipv6.conf.all.disable_ipv6' sysctl: %m");
313 return true;
314 }
315
316 r = parse_boolean(v);
317 if (r < 0) {
318 log_debug_errno(r, "Failed to pare 'net.ipv6.conf.all.disable_ipv6' sysctl: %m");
319 return true;
320 }
321
322 return !r;
323 }
324
325 bool socket_address_matches_fd(const SocketAddress *a, int fd) {
326 SocketAddress b;
327 socklen_t solen;
328
329 assert(a);
330 assert(fd >= 0);
331
332 b.size = sizeof(b.sockaddr);
333 if (getsockname(fd, &b.sockaddr.sa, &b.size) < 0)
334 return false;
335
336 if (b.sockaddr.sa.sa_family != a->sockaddr.sa.sa_family)
337 return false;
338
339 solen = sizeof(b.type);
340 if (getsockopt(fd, SOL_SOCKET, SO_TYPE, &b.type, &solen) < 0)
341 return false;
342
343 if (b.type != a->type)
344 return false;
345
346 if (a->protocol != 0) {
347 solen = sizeof(b.protocol);
348 if (getsockopt(fd, SOL_SOCKET, SO_PROTOCOL, &b.protocol, &solen) < 0)
349 return false;
350
351 if (b.protocol != a->protocol)
352 return false;
353 }
354
355 return socket_address_equal(a, &b);
356 }
357
358 int sockaddr_port(const struct sockaddr *_sa, unsigned *ret_port) {
359 const union sockaddr_union *sa = (const union sockaddr_union*) _sa;
360
361 /* Note, this returns the port as 'unsigned' rather than 'uint16_t', as AF_VSOCK knows larger ports */
362
363 assert(sa);
364
365 switch (sa->sa.sa_family) {
366
367 case AF_INET:
368 *ret_port = be16toh(sa->in.sin_port);
369 return 0;
370
371 case AF_INET6:
372 *ret_port = be16toh(sa->in6.sin6_port);
373 return 0;
374
375 case AF_VSOCK:
376 *ret_port = sa->vm.svm_port;
377 return 0;
378
379 default:
380 return -EAFNOSUPPORT;
381 }
382 }
383
384 const union in_addr_union *sockaddr_in_addr(const struct sockaddr *_sa) {
385 const union sockaddr_union *sa = (const union sockaddr_union*) _sa;
386
387 if (!sa)
388 return NULL;
389
390 switch (sa->sa.sa_family) {
391
392 case AF_INET:
393 return (const union in_addr_union*) &sa->in.sin_addr;
394
395 case AF_INET6:
396 return (const union in_addr_union*) &sa->in6.sin6_addr;
397
398 default:
399 return NULL;
400 }
401 }
402
403 int sockaddr_pretty(
404 const struct sockaddr *_sa,
405 socklen_t salen,
406 bool translate_ipv6,
407 bool include_port,
408 char **ret) {
409
410 union sockaddr_union *sa = (union sockaddr_union*) _sa;
411 char *p;
412 int r;
413
414 assert(sa);
415 assert(salen >= sizeof(sa->sa.sa_family));
416
417 switch (sa->sa.sa_family) {
418
419 case AF_INET: {
420 uint32_t a;
421
422 a = be32toh(sa->in.sin_addr.s_addr);
423
424 if (include_port)
425 r = asprintf(&p,
426 "%u.%u.%u.%u:%u",
427 a >> 24, (a >> 16) & 0xFF, (a >> 8) & 0xFF, a & 0xFF,
428 be16toh(sa->in.sin_port));
429 else
430 r = asprintf(&p,
431 "%u.%u.%u.%u",
432 a >> 24, (a >> 16) & 0xFF, (a >> 8) & 0xFF, a & 0xFF);
433 if (r < 0)
434 return -ENOMEM;
435 break;
436 }
437
438 case AF_INET6: {
439 static const unsigned char ipv4_prefix[] = {
440 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xFF, 0xFF
441 };
442
443 if (translate_ipv6 &&
444 memcmp(&sa->in6.sin6_addr, ipv4_prefix, sizeof(ipv4_prefix)) == 0) {
445 const uint8_t *a = sa->in6.sin6_addr.s6_addr+12;
446 if (include_port)
447 r = asprintf(&p,
448 "%u.%u.%u.%u:%u",
449 a[0], a[1], a[2], a[3],
450 be16toh(sa->in6.sin6_port));
451 else
452 r = asprintf(&p,
453 "%u.%u.%u.%u",
454 a[0], a[1], a[2], a[3]);
455 if (r < 0)
456 return -ENOMEM;
457 } else {
458 char a[INET6_ADDRSTRLEN];
459
460 inet_ntop(AF_INET6, &sa->in6.sin6_addr, a, sizeof(a));
461
462 if (include_port) {
463 if (asprintf(&p,
464 "[%s]:%u%s%s",
465 a,
466 be16toh(sa->in6.sin6_port),
467 sa->in6.sin6_scope_id != 0 ? "%" : "",
468 FORMAT_IFNAME_FULL(sa->in6.sin6_scope_id, FORMAT_IFNAME_IFINDEX)) < 0)
469 return -ENOMEM;
470 } else {
471 if (sa->in6.sin6_scope_id != 0)
472 p = strjoin(a, "%", FORMAT_IFNAME_FULL(sa->in6.sin6_scope_id, FORMAT_IFNAME_IFINDEX));
473 else
474 p = strdup(a);
475 if (!p)
476 return -ENOMEM;
477 }
478 }
479
480 break;
481 }
482
483 case AF_UNIX:
484 if (salen <= offsetof(struct sockaddr_un, sun_path) ||
485 (sa->un.sun_path[0] == 0 && salen == offsetof(struct sockaddr_un, sun_path) + 1))
486 /* The name must have at least one character (and the leading NUL does not count) */
487 p = strdup("<unnamed>");
488 else {
489 /* Note that we calculate the path pointer here through the .un_buffer[] field, in order to
490 * outtrick bounds checking tools such as ubsan, which are too smart for their own good: on
491 * Linux the kernel may return sun_path[] data one byte longer than the declared size of the
492 * field. */
493 char *path = (char*) sa->un_buffer + offsetof(struct sockaddr_un, sun_path);
494 size_t path_len = salen - offsetof(struct sockaddr_un, sun_path);
495
496 if (path[0] == 0) {
497 /* Abstract socket. When parsing address information from, we
498 * explicitly reject overly long paths and paths with embedded NULs.
499 * But we might get such a socket from the outside. Let's return
500 * something meaningful and printable in this case. */
501
502 _cleanup_free_ char *e = NULL;
503
504 e = cescape_length(path + 1, path_len - 1);
505 if (!e)
506 return -ENOMEM;
507
508 p = strjoin("@", e);
509 } else {
510 if (path[path_len - 1] == '\0')
511 /* We expect a terminating NUL and don't print it */
512 path_len --;
513
514 p = cescape_length(path, path_len);
515 }
516 }
517 if (!p)
518 return -ENOMEM;
519
520 break;
521
522 case AF_VSOCK:
523 if (include_port) {
524 if (sa->vm.svm_cid == VMADDR_CID_ANY)
525 r = asprintf(&p, "vsock::%u", sa->vm.svm_port);
526 else
527 r = asprintf(&p, "vsock:%u:%u", sa->vm.svm_cid, sa->vm.svm_port);
528 } else
529 r = asprintf(&p, "vsock:%u", sa->vm.svm_cid);
530 if (r < 0)
531 return -ENOMEM;
532 break;
533
534 default:
535 return -EOPNOTSUPP;
536 }
537
538 *ret = p;
539 return 0;
540 }
541
542 int getpeername_pretty(int fd, bool include_port, char **ret) {
543 union sockaddr_union sa;
544 socklen_t salen = sizeof(sa);
545 int r;
546
547 assert(fd >= 0);
548 assert(ret);
549
550 if (getpeername(fd, &sa.sa, &salen) < 0)
551 return -errno;
552
553 if (sa.sa.sa_family == AF_UNIX) {
554 struct ucred ucred = {};
555
556 /* UNIX connection sockets are anonymous, so let's use
557 * PID/UID as pretty credentials instead */
558
559 r = getpeercred(fd, &ucred);
560 if (r < 0)
561 return r;
562
563 if (asprintf(ret, "PID "PID_FMT"/UID "UID_FMT, ucred.pid, ucred.uid) < 0)
564 return -ENOMEM;
565
566 return 0;
567 }
568
569 /* For remote sockets we translate IPv6 addresses back to IPv4
570 * if applicable, since that's nicer. */
571
572 return sockaddr_pretty(&sa.sa, salen, true, include_port, ret);
573 }
574
575 int getsockname_pretty(int fd, char **ret) {
576 union sockaddr_union sa;
577 socklen_t salen = sizeof(sa);
578
579 assert(fd >= 0);
580 assert(ret);
581
582 if (getsockname(fd, &sa.sa, &salen) < 0)
583 return -errno;
584
585 /* For local sockets we do not translate IPv6 addresses back
586 * to IPv6 if applicable, since this is usually used for
587 * listening sockets where the difference between IPv4 and
588 * IPv6 matters. */
589
590 return sockaddr_pretty(&sa.sa, salen, false, true, ret);
591 }
592
593 int socknameinfo_pretty(union sockaddr_union *sa, socklen_t salen, char **_ret) {
594 int r;
595 char host[NI_MAXHOST], *ret;
596
597 assert(_ret);
598
599 r = getnameinfo(&sa->sa, salen, host, sizeof(host), NULL, 0, IDN_FLAGS);
600 if (r != 0) {
601 int saved_errno = errno;
602
603 r = sockaddr_pretty(&sa->sa, salen, true, true, &ret);
604 if (r < 0)
605 return r;
606
607 log_debug_errno(saved_errno, "getnameinfo(%s) failed: %m", ret);
608 } else {
609 ret = strdup(host);
610 if (!ret)
611 return -ENOMEM;
612 }
613
614 *_ret = ret;
615 return 0;
616 }
617
618 static const char* const netlink_family_table[] = {
619 [NETLINK_ROUTE] = "route",
620 [NETLINK_FIREWALL] = "firewall",
621 [NETLINK_INET_DIAG] = "inet-diag",
622 [NETLINK_NFLOG] = "nflog",
623 [NETLINK_XFRM] = "xfrm",
624 [NETLINK_SELINUX] = "selinux",
625 [NETLINK_ISCSI] = "iscsi",
626 [NETLINK_AUDIT] = "audit",
627 [NETLINK_FIB_LOOKUP] = "fib-lookup",
628 [NETLINK_CONNECTOR] = "connector",
629 [NETLINK_NETFILTER] = "netfilter",
630 [NETLINK_IP6_FW] = "ip6-fw",
631 [NETLINK_DNRTMSG] = "dnrtmsg",
632 [NETLINK_KOBJECT_UEVENT] = "kobject-uevent",
633 [NETLINK_GENERIC] = "generic",
634 [NETLINK_SCSITRANSPORT] = "scsitransport",
635 [NETLINK_ECRYPTFS] = "ecryptfs",
636 [NETLINK_RDMA] = "rdma",
637 };
638
639 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(netlink_family, int, INT_MAX);
640
641 static const char* const socket_address_bind_ipv6_only_table[_SOCKET_ADDRESS_BIND_IPV6_ONLY_MAX] = {
642 [SOCKET_ADDRESS_DEFAULT] = "default",
643 [SOCKET_ADDRESS_BOTH] = "both",
644 [SOCKET_ADDRESS_IPV6_ONLY] = "ipv6-only"
645 };
646
647 DEFINE_STRING_TABLE_LOOKUP(socket_address_bind_ipv6_only, SocketAddressBindIPv6Only);
648
649 SocketAddressBindIPv6Only socket_address_bind_ipv6_only_or_bool_from_string(const char *n) {
650 int r;
651
652 r = parse_boolean(n);
653 if (r > 0)
654 return SOCKET_ADDRESS_IPV6_ONLY;
655 if (r == 0)
656 return SOCKET_ADDRESS_BOTH;
657
658 return socket_address_bind_ipv6_only_from_string(n);
659 }
660
661 bool sockaddr_equal(const union sockaddr_union *a, const union sockaddr_union *b) {
662 assert(a);
663 assert(b);
664
665 if (a->sa.sa_family != b->sa.sa_family)
666 return false;
667
668 if (a->sa.sa_family == AF_INET)
669 return a->in.sin_addr.s_addr == b->in.sin_addr.s_addr;
670
671 if (a->sa.sa_family == AF_INET6)
672 return memcmp(&a->in6.sin6_addr, &b->in6.sin6_addr, sizeof(a->in6.sin6_addr)) == 0;
673
674 if (a->sa.sa_family == AF_VSOCK)
675 return a->vm.svm_cid == b->vm.svm_cid;
676
677 return false;
678 }
679
680 int fd_set_sndbuf(int fd, size_t n, bool increase) {
681 int r, value;
682 socklen_t l = sizeof(value);
683
684 if (n > INT_MAX)
685 return -ERANGE;
686
687 r = getsockopt(fd, SOL_SOCKET, SO_SNDBUF, &value, &l);
688 if (r >= 0 && l == sizeof(value) && increase ? (size_t) value >= n*2 : (size_t) value == n*2)
689 return 0;
690
691 /* First, try to set the buffer size with SO_SNDBUF. */
692 r = setsockopt_int(fd, SOL_SOCKET, SO_SNDBUF, n);
693 if (r < 0)
694 return r;
695
696 /* SO_SNDBUF above may set to the kernel limit, instead of the requested size.
697 * So, we need to check the actual buffer size here. */
698 l = sizeof(value);
699 r = getsockopt(fd, SOL_SOCKET, SO_SNDBUF, &value, &l);
700 if (r >= 0 && l == sizeof(value) && increase ? (size_t) value >= n*2 : (size_t) value == n*2)
701 return 1;
702
703 /* If we have the privileges we will ignore the kernel limit. */
704 r = setsockopt_int(fd, SOL_SOCKET, SO_SNDBUFFORCE, n);
705 if (r < 0)
706 return r;
707
708 return 1;
709 }
710
711 int fd_set_rcvbuf(int fd, size_t n, bool increase) {
712 int r, value;
713 socklen_t l = sizeof(value);
714
715 if (n > INT_MAX)
716 return -ERANGE;
717
718 r = getsockopt(fd, SOL_SOCKET, SO_RCVBUF, &value, &l);
719 if (r >= 0 && l == sizeof(value) && increase ? (size_t) value >= n*2 : (size_t) value == n*2)
720 return 0;
721
722 /* First, try to set the buffer size with SO_RCVBUF. */
723 r = setsockopt_int(fd, SOL_SOCKET, SO_RCVBUF, n);
724 if (r < 0)
725 return r;
726
727 /* SO_RCVBUF above may set to the kernel limit, instead of the requested size.
728 * So, we need to check the actual buffer size here. */
729 l = sizeof(value);
730 r = getsockopt(fd, SOL_SOCKET, SO_RCVBUF, &value, &l);
731 if (r >= 0 && l == sizeof(value) && increase ? (size_t) value >= n*2 : (size_t) value == n*2)
732 return 1;
733
734 /* If we have the privileges we will ignore the kernel limit. */
735 r = setsockopt_int(fd, SOL_SOCKET, SO_RCVBUFFORCE, n);
736 if (r < 0)
737 return r;
738
739 return 1;
740 }
741
742 static const char* const ip_tos_table[] = {
743 [IPTOS_LOWDELAY] = "low-delay",
744 [IPTOS_THROUGHPUT] = "throughput",
745 [IPTOS_RELIABILITY] = "reliability",
746 [IPTOS_LOWCOST] = "low-cost",
747 };
748
749 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(ip_tos, int, 0xff);
750
751 bool ifname_valid_char(char a) {
752 if ((unsigned char) a >= 127U)
753 return false;
754
755 if ((unsigned char) a <= 32U)
756 return false;
757
758 if (IN_SET(a,
759 ':', /* colons are used by the legacy "alias" interface logic */
760 '/', /* slashes cannot work, since we need to use network interfaces in sysfs paths, and in paths slashes are separators */
761 '%')) /* %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 */
762 return false;
763
764 return true;
765 }
766
767 bool ifname_valid_full(const char *p, IfnameValidFlags flags) {
768 bool numeric = true;
769
770 /* Checks whether a network interface name is valid. This is inspired by dev_valid_name() in the kernel sources
771 * but slightly stricter, as we only allow non-control, non-space ASCII characters in the interface name. We
772 * also don't permit names that only container numbers, to avoid confusion with numeric interface indexes. */
773
774 assert(!(flags & ~_IFNAME_VALID_ALL));
775
776 if (isempty(p))
777 return false;
778
779 /* A valid ifindex? If so, it's valid iff IFNAME_VALID_NUMERIC is set */
780 if (parse_ifindex(p) >= 0)
781 return flags & IFNAME_VALID_NUMERIC;
782
783 if (flags & IFNAME_VALID_ALTERNATIVE) {
784 if (strlen(p) >= ALTIFNAMSIZ)
785 return false;
786 } else {
787 if (strlen(p) >= IFNAMSIZ)
788 return false;
789 }
790
791 if (dot_or_dot_dot(p))
792 return false;
793
794 /* Let's refuse "all" and "default" as interface name, to avoid collisions with the special sysctl
795 * directories /proc/sys/net/{ipv4,ipv6}/conf/{all,default} */
796 if (!FLAGS_SET(flags, IFNAME_VALID_SPECIAL) && STR_IN_SET(p, "all", "default"))
797 return false;
798
799 for (const char *t = p; *t; t++) {
800 if (!ifname_valid_char(*t))
801 return false;
802
803 numeric = numeric && (*t >= '0' && *t <= '9');
804 }
805
806 /* It's fully numeric but didn't parse as valid ifindex above? if so, it must be too large or zero or
807 * so, let's refuse that. */
808 if (numeric)
809 return false;
810
811 return true;
812 }
813
814 bool address_label_valid(const char *p) {
815
816 if (isempty(p))
817 return false;
818
819 if (strlen(p) >= IFNAMSIZ)
820 return false;
821
822 while (*p) {
823 if ((uint8_t) *p >= 127U)
824 return false;
825
826 if ((uint8_t) *p <= 31U)
827 return false;
828 p++;
829 }
830
831 return true;
832 }
833
834 int getpeercred(int fd, struct ucred *ucred) {
835 socklen_t n = sizeof(struct ucred);
836 struct ucred u;
837 int r;
838
839 assert(fd >= 0);
840 assert(ucred);
841
842 r = getsockopt(fd, SOL_SOCKET, SO_PEERCRED, &u, &n);
843 if (r < 0)
844 return -errno;
845
846 if (n != sizeof(struct ucred))
847 return -EIO;
848
849 /* Check if the data is actually useful and not suppressed due to namespacing issues */
850 if (!pid_is_valid(u.pid))
851 return -ENODATA;
852
853 /* Note that we don't check UID/GID here, as namespace translation works differently there: instead of
854 * receiving in "invalid" user/group we get the overflow UID/GID. */
855
856 *ucred = u;
857 return 0;
858 }
859
860 int getpeersec(int fd, char **ret) {
861 _cleanup_free_ char *s = NULL;
862 socklen_t n = 64;
863
864 assert(fd >= 0);
865 assert(ret);
866
867 for (;;) {
868 s = new0(char, n+1);
869 if (!s)
870 return -ENOMEM;
871
872 if (getsockopt(fd, SOL_SOCKET, SO_PEERSEC, s, &n) >= 0)
873 break;
874
875 if (errno != ERANGE)
876 return -errno;
877
878 s = mfree(s);
879 }
880
881 if (isempty(s))
882 return -EOPNOTSUPP;
883
884 *ret = TAKE_PTR(s);
885
886 return 0;
887 }
888
889 int getpeergroups(int fd, gid_t **ret) {
890 socklen_t n = sizeof(gid_t) * 64;
891 _cleanup_free_ gid_t *d = NULL;
892
893 assert(fd >= 0);
894 assert(ret);
895
896 for (;;) {
897 d = malloc(n);
898 if (!d)
899 return -ENOMEM;
900
901 if (getsockopt(fd, SOL_SOCKET, SO_PEERGROUPS, d, &n) >= 0)
902 break;
903
904 if (errno != ERANGE)
905 return -errno;
906
907 d = mfree(d);
908 }
909
910 assert_se(n % sizeof(gid_t) == 0);
911 n /= sizeof(gid_t);
912
913 if ((socklen_t) (int) n != n)
914 return -E2BIG;
915
916 *ret = TAKE_PTR(d);
917
918 return (int) n;
919 }
920
921 ssize_t send_one_fd_iov_sa(
922 int transport_fd,
923 int fd,
924 const struct iovec *iov, size_t iovlen,
925 const struct sockaddr *sa, socklen_t len,
926 int flags) {
927
928 CMSG_BUFFER_TYPE(CMSG_SPACE(sizeof(int))) control = {};
929 struct msghdr mh = {
930 .msg_name = (struct sockaddr*) sa,
931 .msg_namelen = len,
932 .msg_iov = (struct iovec *)iov,
933 .msg_iovlen = iovlen,
934 };
935 ssize_t k;
936
937 assert(transport_fd >= 0);
938
939 /*
940 * We need either an FD or data to send.
941 * If there's nothing, return an error.
942 */
943 if (fd < 0 && !iov)
944 return -EINVAL;
945
946 if (fd >= 0) {
947 struct cmsghdr *cmsg;
948
949 mh.msg_control = &control;
950 mh.msg_controllen = sizeof(control);
951
952 cmsg = CMSG_FIRSTHDR(&mh);
953 cmsg->cmsg_level = SOL_SOCKET;
954 cmsg->cmsg_type = SCM_RIGHTS;
955 cmsg->cmsg_len = CMSG_LEN(sizeof(int));
956 memcpy(CMSG_DATA(cmsg), &fd, sizeof(int));
957 }
958 k = sendmsg(transport_fd, &mh, MSG_NOSIGNAL | flags);
959 if (k < 0)
960 return (ssize_t) -errno;
961
962 return k;
963 }
964
965 int send_one_fd_sa(
966 int transport_fd,
967 int fd,
968 const struct sockaddr *sa, socklen_t len,
969 int flags) {
970
971 assert(fd >= 0);
972
973 return (int) send_one_fd_iov_sa(transport_fd, fd, NULL, 0, sa, len, flags);
974 }
975
976 ssize_t receive_one_fd_iov(
977 int transport_fd,
978 struct iovec *iov, size_t iovlen,
979 int flags,
980 int *ret_fd) {
981
982 CMSG_BUFFER_TYPE(CMSG_SPACE(sizeof(int))) control;
983 struct msghdr mh = {
984 .msg_control = &control,
985 .msg_controllen = sizeof(control),
986 .msg_iov = iov,
987 .msg_iovlen = iovlen,
988 };
989 struct cmsghdr *found;
990 ssize_t k;
991
992 assert(transport_fd >= 0);
993 assert(ret_fd);
994
995 /*
996 * Receive a single FD via @transport_fd. We don't care for
997 * the transport-type. We retrieve a single FD at most, so for
998 * packet-based transports, the caller must ensure to send
999 * only a single FD per packet. This is best used in
1000 * combination with send_one_fd().
1001 */
1002
1003 k = recvmsg_safe(transport_fd, &mh, MSG_CMSG_CLOEXEC | flags);
1004 if (k < 0)
1005 return k;
1006
1007 found = cmsg_find(&mh, SOL_SOCKET, SCM_RIGHTS, CMSG_LEN(sizeof(int)));
1008 if (!found) {
1009 cmsg_close_all(&mh);
1010
1011 /* If didn't receive an FD or any data, return an error. */
1012 if (k == 0)
1013 return -EIO;
1014 }
1015
1016 if (found)
1017 *ret_fd = *(int*) CMSG_DATA(found);
1018 else
1019 *ret_fd = -1;
1020
1021 return k;
1022 }
1023
1024 int receive_one_fd(int transport_fd, int flags) {
1025 int fd;
1026 ssize_t k;
1027
1028 k = receive_one_fd_iov(transport_fd, NULL, 0, flags, &fd);
1029 if (k == 0)
1030 return fd;
1031
1032 /* k must be negative, since receive_one_fd_iov() only returns
1033 * a positive value if data was received through the iov. */
1034 assert(k < 0);
1035 return (int) k;
1036 }
1037
1038 ssize_t next_datagram_size_fd(int fd) {
1039 ssize_t l;
1040 int k;
1041
1042 /* This is a bit like FIONREAD/SIOCINQ, however a bit more powerful. The difference being: recv(MSG_PEEK) will
1043 * actually cause the next datagram in the queue to be validated regarding checksums, which FIONREAD doesn't
1044 * do. This difference is actually of major importance as we need to be sure that the size returned here
1045 * actually matches what we will read with recvmsg() next, as otherwise we might end up allocating a buffer of
1046 * the wrong size. */
1047
1048 l = recv(fd, NULL, 0, MSG_PEEK|MSG_TRUNC);
1049 if (l < 0) {
1050 if (IN_SET(errno, EOPNOTSUPP, EFAULT))
1051 goto fallback;
1052
1053 return -errno;
1054 }
1055 if (l == 0)
1056 goto fallback;
1057
1058 return l;
1059
1060 fallback:
1061 k = 0;
1062
1063 /* Some sockets (AF_PACKET) do not support null-sized recv() with MSG_TRUNC set, let's fall back to FIONREAD
1064 * for them. Checksums don't matter for raw sockets anyway, hence this should be fine. */
1065
1066 if (ioctl(fd, FIONREAD, &k) < 0)
1067 return -errno;
1068
1069 return (ssize_t) k;
1070 }
1071
1072 /* Put a limit on how many times will attempt to call accept4(). We loop
1073 * only on "transient" errors, but let's make sure we don't loop forever. */
1074 #define MAX_FLUSH_ITERATIONS 1024
1075
1076 int flush_accept(int fd) {
1077
1078 int r, b;
1079 socklen_t l = sizeof(b);
1080
1081 /* Similar to flush_fd() but flushes all incoming connections by accepting and immediately closing
1082 * them. */
1083
1084 if (getsockopt(fd, SOL_SOCKET, SO_ACCEPTCONN, &b, &l) < 0)
1085 return -errno;
1086
1087 assert(l == sizeof(b));
1088 if (!b) /* Let's check if this socket accepts connections before calling accept(). accept4() can
1089 * return EOPNOTSUPP if the fd is not a listening socket, which we should treat as a fatal
1090 * error, or in case the incoming TCP connection triggered a network issue, which we want to
1091 * treat as a transient error. Thus, let's rule out the first reason for EOPNOTSUPP early, so
1092 * we can loop safely on transient errors below. */
1093 return -ENOTTY;
1094
1095 for (unsigned iteration = 0;; iteration++) {
1096 int cfd;
1097
1098 r = fd_wait_for_event(fd, POLLIN, 0);
1099 if (r < 0) {
1100 if (r == -EINTR)
1101 continue;
1102
1103 return r;
1104 }
1105 if (r == 0)
1106 return 0;
1107
1108 if (iteration >= MAX_FLUSH_ITERATIONS)
1109 return log_debug_errno(SYNTHETIC_ERRNO(EBUSY),
1110 "Failed to flush connections within " STRINGIFY(MAX_FLUSH_ITERATIONS) " iterations.");
1111
1112 cfd = accept4(fd, NULL, NULL, SOCK_NONBLOCK|SOCK_CLOEXEC);
1113 if (cfd < 0) {
1114 if (errno == EAGAIN)
1115 return 0;
1116
1117 if (ERRNO_IS_ACCEPT_AGAIN(errno))
1118 continue;
1119
1120 return -errno;
1121 }
1122
1123 safe_close(cfd);
1124 }
1125 }
1126
1127 struct cmsghdr* cmsg_find(struct msghdr *mh, int level, int type, socklen_t length) {
1128 struct cmsghdr *cmsg;
1129
1130 assert(mh);
1131
1132 CMSG_FOREACH(cmsg, mh)
1133 if (cmsg->cmsg_level == level &&
1134 cmsg->cmsg_type == type &&
1135 (length == (socklen_t) -1 || length == cmsg->cmsg_len))
1136 return cmsg;
1137
1138 return NULL;
1139 }
1140
1141 int socket_ioctl_fd(void) {
1142 int fd;
1143
1144 /* Create a socket to invoke the various network interface ioctl()s on. Traditionally only AF_INET was good for
1145 * that. Since kernel 4.6 AF_NETLINK works for this too. We first try to use AF_INET hence, but if that's not
1146 * available (for example, because it is made unavailable via SECCOMP or such), we'll fall back to the more
1147 * generic AF_NETLINK. */
1148
1149 fd = socket(AF_INET, SOCK_DGRAM|SOCK_CLOEXEC, 0);
1150 if (fd < 0)
1151 fd = socket(AF_NETLINK, SOCK_RAW|SOCK_CLOEXEC, NETLINK_GENERIC);
1152 if (fd < 0)
1153 return -errno;
1154
1155 return fd;
1156 }
1157
1158 int sockaddr_un_unlink(const struct sockaddr_un *sa) {
1159 const char *p, * nul;
1160
1161 assert(sa);
1162
1163 if (sa->sun_family != AF_UNIX)
1164 return -EPROTOTYPE;
1165
1166 if (sa->sun_path[0] == 0) /* Nothing to do for abstract sockets */
1167 return 0;
1168
1169 /* The path in .sun_path is not necessarily NUL terminated. Let's fix that. */
1170 nul = memchr(sa->sun_path, 0, sizeof(sa->sun_path));
1171 if (nul)
1172 p = sa->sun_path;
1173 else
1174 p = memdupa_suffix0(sa->sun_path, sizeof(sa->sun_path));
1175
1176 if (unlink(p) < 0)
1177 return -errno;
1178
1179 return 1;
1180 }
1181
1182 int sockaddr_un_set_path(struct sockaddr_un *ret, const char *path) {
1183 size_t l;
1184
1185 assert(ret);
1186 assert(path);
1187
1188 /* Initialize ret->sun_path from the specified argument. This will interpret paths starting with '@' as
1189 * abstract namespace sockets, and those starting with '/' as regular filesystem sockets. It won't accept
1190 * anything else (i.e. no relative paths), to avoid ambiguities. Note that this function cannot be used to
1191 * reference paths in the abstract namespace that include NUL bytes in the name. */
1192
1193 l = strlen(path);
1194 if (l < 2)
1195 return -EINVAL;
1196 if (!IN_SET(path[0], '/', '@'))
1197 return -EINVAL;
1198
1199 /* Don't allow paths larger than the space in sockaddr_un. Note that we are a tiny bit more restrictive than
1200 * the kernel is: we insist on NUL termination (both for abstract namespace and regular file system socket
1201 * addresses!), which the kernel doesn't. We do this to reduce chance of incompatibility with other apps that
1202 * do not expect non-NUL terminated file system path. */
1203 if (l+1 > sizeof(ret->sun_path))
1204 return -EINVAL;
1205
1206 *ret = (struct sockaddr_un) {
1207 .sun_family = AF_UNIX,
1208 };
1209
1210 if (path[0] == '@') {
1211 /* Abstract namespace socket */
1212 memcpy(ret->sun_path + 1, path + 1, l); /* copy *with* trailing NUL byte */
1213 return (int) (offsetof(struct sockaddr_un, sun_path) + l); /* 🔥 *don't* 🔥 include trailing NUL in size */
1214
1215 } else {
1216 assert(path[0] == '/');
1217
1218 /* File system socket */
1219 memcpy(ret->sun_path, path, l + 1); /* copy *with* trailing NUL byte */
1220 return (int) (offsetof(struct sockaddr_un, sun_path) + l + 1); /* include trailing NUL in size */
1221 }
1222 }
1223
1224 int socket_bind_to_ifname(int fd, const char *ifname) {
1225 assert(fd >= 0);
1226
1227 /* Call with NULL to drop binding */
1228
1229 if (setsockopt(fd, SOL_SOCKET, SO_BINDTODEVICE, ifname, strlen_ptr(ifname)) < 0)
1230 return -errno;
1231
1232 return 0;
1233 }
1234
1235 int socket_bind_to_ifindex(int fd, int ifindex) {
1236 char ifname[IF_NAMESIZE];
1237 int r;
1238
1239 assert(fd >= 0);
1240
1241 if (ifindex <= 0) {
1242 /* Drop binding */
1243 if (setsockopt(fd, SOL_SOCKET, SO_BINDTODEVICE, NULL, 0) < 0)
1244 return -errno;
1245
1246 return 0;
1247 }
1248
1249 r = setsockopt_int(fd, SOL_SOCKET, SO_BINDTOIFINDEX, ifindex);
1250 if (r != -ENOPROTOOPT)
1251 return r;
1252
1253 /* Fall back to SO_BINDTODEVICE on kernels < 5.0 which didn't have SO_BINDTOIFINDEX */
1254 r = format_ifname(ifindex, ifname);
1255 if (r < 0)
1256 return r;
1257
1258 return socket_bind_to_ifname(fd, ifname);
1259 }
1260
1261 ssize_t recvmsg_safe(int sockfd, struct msghdr *msg, int flags) {
1262 ssize_t n;
1263
1264 /* A wrapper around recvmsg() that checks for MSG_CTRUNC, and turns it into an error, in a reasonably
1265 * safe way, closing any SCM_RIGHTS fds in the error path.
1266 *
1267 * Note that unlike our usual coding style this might modify *msg on failure. */
1268
1269 n = recvmsg(sockfd, msg, flags);
1270 if (n < 0)
1271 return -errno;
1272
1273 if (FLAGS_SET(msg->msg_flags, MSG_CTRUNC)) {
1274 cmsg_close_all(msg);
1275 return -EXFULL; /* a recognizable error code */
1276 }
1277
1278 return n;
1279 }
1280
1281 int socket_get_family(int fd, int *ret) {
1282 int af;
1283 socklen_t sl = sizeof(af);
1284
1285 if (getsockopt(fd, SOL_SOCKET, SO_DOMAIN, &af, &sl) < 0)
1286 return -errno;
1287
1288 if (sl != sizeof(af))
1289 return -EINVAL;
1290
1291 return af;
1292 }
1293
1294 int socket_set_recvpktinfo(int fd, int af, bool b) {
1295 int r;
1296
1297 if (af == AF_UNSPEC) {
1298 r = socket_get_family(fd, &af);
1299 if (r < 0)
1300 return r;
1301 }
1302
1303 switch (af) {
1304
1305 case AF_INET:
1306 return setsockopt_int(fd, IPPROTO_IP, IP_PKTINFO, b);
1307
1308 case AF_INET6:
1309 return setsockopt_int(fd, IPPROTO_IPV6, IPV6_RECVPKTINFO, b);
1310
1311 case AF_NETLINK:
1312 return setsockopt_int(fd, SOL_NETLINK, NETLINK_PKTINFO, b);
1313
1314 case AF_PACKET:
1315 return setsockopt_int(fd, SOL_PACKET, PACKET_AUXDATA, b);
1316
1317 default:
1318 return -EAFNOSUPPORT;
1319 }
1320 }
1321
1322 int socket_set_unicast_if(int fd, int af, int ifi) {
1323 be32_t ifindex_be = htobe32(ifi);
1324 int r;
1325
1326 if (af == AF_UNSPEC) {
1327 r = socket_get_family(fd, &af);
1328 if (r < 0)
1329 return r;
1330 }
1331
1332 switch (af) {
1333
1334 case AF_INET:
1335 if (setsockopt(fd, IPPROTO_IP, IP_UNICAST_IF, &ifindex_be, sizeof(ifindex_be)) < 0)
1336 return -errno;
1337
1338 return 0;
1339
1340 case AF_INET6:
1341 if (setsockopt(fd, IPPROTO_IPV6, IPV6_UNICAST_IF, &ifindex_be, sizeof(ifindex_be)) < 0)
1342 return -errno;
1343
1344 return 0;
1345
1346 default:
1347 return -EAFNOSUPPORT;
1348 }
1349 }
1350
1351 int socket_set_option(int fd, int af, int opt_ipv4, int opt_ipv6, int val) {
1352 int r;
1353
1354 if (af == AF_UNSPEC) {
1355 r = socket_get_family(fd, &af);
1356 if (r < 0)
1357 return r;
1358 }
1359
1360 switch (af) {
1361
1362 case AF_INET:
1363 return setsockopt_int(fd, IPPROTO_IP, opt_ipv4, val);
1364
1365 case AF_INET6:
1366 return setsockopt_int(fd, IPPROTO_IPV6, opt_ipv6, val);
1367
1368 default:
1369 return -EAFNOSUPPORT;
1370 }
1371 }
1372
1373 int socket_get_mtu(int fd, int af, size_t *ret) {
1374 int mtu, r;
1375
1376 if (af == AF_UNSPEC) {
1377 r = socket_get_family(fd, &af);
1378 if (r < 0)
1379 return r;
1380 }
1381
1382 switch (af) {
1383
1384 case AF_INET:
1385 r = getsockopt_int(fd, IPPROTO_IP, IP_MTU, &mtu);
1386 break;
1387
1388 case AF_INET6:
1389 r = getsockopt_int(fd, IPPROTO_IPV6, IPV6_MTU, &mtu);
1390 break;
1391
1392 default:
1393 return -EAFNOSUPPORT;
1394 }
1395
1396 if (r < 0)
1397 return r;
1398 if (mtu <= 0)
1399 return -EINVAL;
1400
1401 *ret = (size_t) mtu;
1402 return 0;
1403 }