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