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