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