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