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