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