]> git.ipfire.org Git - thirdparty/systemd.git/blame - src/basic/socket-util.c
Merge pull request #30610 from YHNdnzj/logind-serialize-pidref
[thirdparty/systemd.git] / src / basic / socket-util.c
CommitLineData
db9ecf05 1/* SPDX-License-Identifier: LGPL-2.1-or-later */
a7334b09 2
42f4e3c4 3#include <arpa/inet.h>
07630cea 4#include <errno.h>
11c3a366 5#include <limits.h>
542563ba 6#include <net/if.h>
b31f535c 7#include <netdb.h>
2583fbea 8#include <netinet/ip.h>
60d9771c 9#include <poll.h>
07630cea 10#include <stddef.h>
11c3a366 11#include <stdint.h>
07630cea 12#include <stdio.h>
11c3a366 13#include <stdlib.h>
f5947a5e 14#include <sys/ioctl.h>
07630cea 15#include <unistd.h>
4252696a 16#include <linux/if.h>
42f4e3c4 17
b5efdb8a 18#include "alloc-util.h"
4ff9bc2e 19#include "errno-util.h"
15dca371 20#include "escape.h"
2583fbea 21#include "fd-util.h"
07630cea 22#include "fileio.h"
f97b34a6 23#include "format-util.h"
0f2d351f 24#include "io-util.h"
93cc7779 25#include "log.h"
0a970718 26#include "memory-util.h"
6bedfcbb 27#include "parse-util.h"
9eb977db 28#include "path-util.h"
dccca82b 29#include "process-util.h"
2583fbea 30#include "socket-util.h"
8b43440b 31#include "string-table.h"
07630cea 32#include "string-util.h"
ef76dff2 33#include "strv.h"
83e03c4f 34#include "sysctl-util.h"
ee104e11 35#include "user-util.h"
ef76dff2 36#include "utf8.h"
42f4e3c4 37
349cc4a5 38#if ENABLE_IDN
cadc80b8 39# define IDN_FLAGS NI_IDN
6326a143
WB
40#else
41# define IDN_FLAGS 0
42#endif
43
598d2428
LB
44/* From the kernel's include/net/scm.h */
45#ifndef SCM_MAX_FD
46# define SCM_MAX_FD 253
47#endif
48
398ce0bc 49static const char* const socket_address_type_table[] = {
955bb7fa
ZJS
50 [SOCK_STREAM] = "Stream",
51 [SOCK_DGRAM] = "Datagram",
52 [SOCK_RAW] = "Raw",
53 [SOCK_RDM] = "ReliableDatagram",
398ce0bc 54 [SOCK_SEQPACKET] = "SequentialPacket",
955bb7fa 55 [SOCK_DCCP] = "DatagramCongestionControl",
398ce0bc
YW
56};
57
58DEFINE_STRING_TABLE_LOOKUP(socket_address_type, int);
59
15dca371 60int socket_address_verify(const SocketAddress *a, bool strict) {
42f4e3c4
LP
61 assert(a);
62
15dca371
ZJS
63 /* With 'strict' we enforce additional sanity constraints which are not set by the standard,
64 * but should only apply to sockets we create ourselves. */
65
542563ba 66 switch (socket_address_family(a)) {
42f4e3c4 67
7a22745a
LP
68 case AF_INET:
69 if (a->size != sizeof(struct sockaddr_in))
70 return -EINVAL;
42f4e3c4 71
4d49b48c 72 if (a->sockaddr.in.sin_port == 0)
7a22745a 73 return -EINVAL;
42f4e3c4 74
44ab2347 75 if (!IN_SET(a->type, 0, SOCK_STREAM, SOCK_DGRAM))
7a22745a 76 return -EINVAL;
42f4e3c4 77
7a22745a
LP
78 return 0;
79
80 case AF_INET6:
81 if (a->size != sizeof(struct sockaddr_in6))
82 return -EINVAL;
42f4e3c4 83
7a22745a
LP
84 if (a->sockaddr.in6.sin6_port == 0)
85 return -EINVAL;
42f4e3c4 86
44ab2347 87 if (!IN_SET(a->type, 0, SOCK_STREAM, SOCK_DGRAM))
7a22745a 88 return -EINVAL;
42f4e3c4 89
7a22745a 90 return 0;
42f4e3c4 91
7a22745a
LP
92 case AF_UNIX:
93 if (a->size < offsetof(struct sockaddr_un, sun_path))
94 return -EINVAL;
15dca371
ZJS
95 if (a->size > sizeof(struct sockaddr_un) + !strict)
96 /* If !strict, allow one extra byte, since getsockname() on Linux will append
97 * a NUL byte if we have path sockets that are above sun_path's full size. */
8e8132c6 98 return -EINVAL;
42f4e3c4 99
8e8132c6 100 if (a->size > offsetof(struct sockaddr_un, sun_path) &&
15dca371
ZJS
101 a->sockaddr.un.sun_path[0] != 0 &&
102 strict) {
103 /* Only validate file system sockets here, and only in strict mode */
8e8132c6 104 const char *e;
7a22745a 105
8e8132c6
LP
106 e = memchr(a->sockaddr.un.sun_path, 0, sizeof(a->sockaddr.un.sun_path));
107 if (e) {
15dca371 108 /* If there's an embedded NUL byte, make sure the size of the socket address matches it */
7a22745a
LP
109 if (a->size != offsetof(struct sockaddr_un, sun_path) + (e - a->sockaddr.un.sun_path) + 1)
110 return -EINVAL;
8e8132c6 111 } else {
d7b34e38 112 /* If there's no embedded NUL byte, then the size needs to match the whole
8e8132c6
LP
113 * structure or the structure with one extra NUL byte suffixed. (Yeah, Linux is awful,
114 * and considers both equivalent: getsockname() even extends sockaddr_un beyond its
7802194a 115 * size if the path is non NUL terminated.) */
8e8132c6
LP
116 if (!IN_SET(a->size, sizeof(a->sockaddr.un.sun_path), sizeof(a->sockaddr.un.sun_path)+1))
117 return -EINVAL;
42f4e3c4 118 }
7a22745a 119 }
42f4e3c4 120
44ab2347 121 if (!IN_SET(a->type, 0, SOCK_STREAM, SOCK_DGRAM, SOCK_SEQPACKET))
7a22745a 122 return -EINVAL;
42f4e3c4 123
7a22745a
LP
124 return 0;
125
126 case AF_NETLINK:
127
128 if (a->size != sizeof(struct sockaddr_nl))
129 return -EINVAL;
130
44ab2347 131 if (!IN_SET(a->type, 0, SOCK_RAW, SOCK_DGRAM))
7a22745a
LP
132 return -EINVAL;
133
134 return 0;
135
0fc0f14b
SH
136 case AF_VSOCK:
137 if (a->size != sizeof(struct sockaddr_vm))
138 return -EINVAL;
139
44ab2347 140 if (!IN_SET(a->type, 0, SOCK_STREAM, SOCK_DGRAM))
0fc0f14b
SH
141 return -EINVAL;
142
143 return 0;
144
7a22745a
LP
145 default:
146 return -EAFNOSUPPORT;
42f4e3c4
LP
147 }
148}
149
4d49b48c 150int socket_address_print(const SocketAddress *a, char **ret) {
42f4e3c4 151 int r;
4d49b48c 152
42f4e3c4 153 assert(a);
4d49b48c 154 assert(ret);
42f4e3c4 155
15dca371
ZJS
156 r = socket_address_verify(a, false); /* We do non-strict validation, because we want to be
157 * able to pretty-print any socket the kernel considers
158 * valid. We still need to do validation to know if we
159 * can meaningfully print the address. */
4d49b48c 160 if (r < 0)
42f4e3c4
LP
161 return r;
162
4d49b48c 163 if (socket_address_family(a) == AF_NETLINK) {
7fd1b19b 164 _cleanup_free_ char *sfamily = NULL;
7a22745a 165
f8b69d1d 166 r = netlink_family_to_string_alloc(a->protocol, &sfamily);
7a22745a 167 if (r < 0)
f8b69d1d 168 return r;
4d49b48c
LP
169
170 r = asprintf(ret, "%s %u", sfamily, a->sockaddr.nl.nl_groups);
8520cfa5
MS
171 if (r < 0)
172 return -ENOMEM;
7a22745a
LP
173
174 return 0;
175 }
176
3b1c5241 177 return sockaddr_pretty(&a->sockaddr.sa, a->size, false, true, ret);
42f4e3c4
LP
178}
179
4f2d528d
LP
180bool socket_address_can_accept(const SocketAddress *a) {
181 assert(a);
182
183 return
3742095b 184 IN_SET(a->type, SOCK_STREAM, SOCK_SEQPACKET);
4f2d528d 185}
a16e1123
LP
186
187bool socket_address_equal(const SocketAddress *a, const SocketAddress *b) {
188 assert(a);
189 assert(b);
190
191 /* Invalid addresses are unequal to all */
15dca371
ZJS
192 if (socket_address_verify(a, false) < 0 ||
193 socket_address_verify(b, false) < 0)
a16e1123
LP
194 return false;
195
196 if (a->type != b->type)
197 return false;
198
a16e1123
LP
199 if (socket_address_family(a) != socket_address_family(b))
200 return false;
201
202 switch (socket_address_family(a)) {
203
204 case AF_INET:
4d49b48c 205 if (a->sockaddr.in.sin_addr.s_addr != b->sockaddr.in.sin_addr.s_addr)
a16e1123
LP
206 return false;
207
4d49b48c 208 if (a->sockaddr.in.sin_port != b->sockaddr.in.sin_port)
a16e1123
LP
209 return false;
210
211 break;
212
213 case AF_INET6:
214 if (memcmp(&a->sockaddr.in6.sin6_addr, &b->sockaddr.in6.sin6_addr, sizeof(a->sockaddr.in6.sin6_addr)) != 0)
215 return false;
216
217 if (a->sockaddr.in6.sin6_port != b->sockaddr.in6.sin6_port)
218 return false;
219
220 break;
221
222 case AF_UNIX:
710708a5
MS
223 if (a->size <= offsetof(struct sockaddr_un, sun_path) ||
224 b->size <= offsetof(struct sockaddr_un, sun_path))
225 return false;
226
a16e1123
LP
227 if ((a->sockaddr.un.sun_path[0] == 0) != (b->sockaddr.un.sun_path[0] == 0))
228 return false;
229
230 if (a->sockaddr.un.sun_path[0]) {
563e6846 231 if (!path_equal_or_inode_same(a->sockaddr.un.sun_path, b->sockaddr.un.sun_path, 0))
a16e1123
LP
232 return false;
233 } else {
c78e47a6
MS
234 if (a->size != b->size)
235 return false;
236
b12c1e7c 237 if (memcmp(a->sockaddr.un.sun_path, b->sockaddr.un.sun_path, a->size) != 0)
a16e1123
LP
238 return false;
239 }
240
241 break;
242
7a22745a 243 case AF_NETLINK:
7a22745a
LP
244 if (a->protocol != b->protocol)
245 return false;
246
247 if (a->sockaddr.nl.nl_groups != b->sockaddr.nl.nl_groups)
248 return false;
249
250 break;
251
0fc0f14b
SH
252 case AF_VSOCK:
253 if (a->sockaddr.vm.svm_cid != b->sockaddr.vm.svm_cid)
254 return false;
255
256 if (a->sockaddr.vm.svm_port != b->sockaddr.vm.svm_port)
257 return false;
258
259 break;
260
a16e1123
LP
261 default:
262 /* Cannot compare, so we assume the addresses are different */
263 return false;
264 }
265
266 return true;
267}
268
a57f7e2c 269const char* socket_address_get_path(const SocketAddress *a) {
6e2ef85b
LP
270 assert(a);
271
272 if (socket_address_family(a) != AF_UNIX)
a57f7e2c 273 return NULL;
6e2ef85b
LP
274
275 if (a->sockaddr.un.sun_path[0] == 0)
a57f7e2c 276 return NULL;
a16e1123 277
48e6a2dc
LP
278 /* Note that this is only safe because we know that there's an extra NUL byte after the sockaddr_un
279 * structure. On Linux AF_UNIX file system socket addresses don't have to be NUL terminated if they take up the
280 * full sun_path space. */
281 assert_cc(sizeof(union sockaddr_union) >= sizeof(struct sockaddr_un)+1);
a57f7e2c 282 return a->sockaddr.un.sun_path;
a16e1123 283}
c0120d99 284
5bfcc1c6 285bool socket_ipv6_is_supported(void) {
571ec995 286 static int cached = -1;
f89f1e8f 287
571ec995
LP
288 if (cached < 0) {
289
290 if (access("/proc/net/if_inet6", F_OK) < 0) {
291
292 if (errno != ENOENT) {
293 log_debug_errno(errno, "Unexpected error when checking whether /proc/net/if_inet6 exists: %m");
294 return false;
295 }
296
297 cached = false;
298 } else
299 cached = true;
300 }
301
302 return cached;
5bfcc1c6
FF
303}
304
83e03c4f 305bool socket_ipv6_is_enabled(void) {
f96f5d54 306 _cleanup_free_ char *v = NULL;
83e03c4f
LP
307 int r;
308
309 /* Much like socket_ipv6_is_supported(), but also checks that the sysctl that disables IPv6 on all
310 * interfaces isn't turned on */
311
312 if (!socket_ipv6_is_supported())
90ab5042 313 return false;
f89f1e8f 314
83e03c4f
LP
315 r = sysctl_read_ip_property(AF_INET6, "all", "disable_ipv6", &v);
316 if (r < 0) {
317 log_debug_errno(r, "Unexpected error reading 'net.ipv6.conf.all.disable_ipv6' sysctl: %m");
318 return true;
319 }
320
321 r = parse_boolean(v);
322 if (r < 0) {
323 log_debug_errno(r, "Failed to pare 'net.ipv6.conf.all.disable_ipv6' sysctl: %m");
324 return true;
325 }
326
327 return !r;
5bfcc1c6
FF
328}
329
01e10de3 330bool socket_address_matches_fd(const SocketAddress *a, int fd) {
dbafedac
MS
331 SocketAddress b;
332 socklen_t solen;
01e10de3
LP
333
334 assert(a);
335 assert(fd >= 0);
336
dbafedac
MS
337 b.size = sizeof(b.sockaddr);
338 if (getsockname(fd, &b.sockaddr.sa, &b.size) < 0)
01e10de3
LP
339 return false;
340
dbafedac 341 if (b.sockaddr.sa.sa_family != a->sockaddr.sa.sa_family)
01e10de3
LP
342 return false;
343
dbafedac
MS
344 solen = sizeof(b.type);
345 if (getsockopt(fd, SOL_SOCKET, SO_TYPE, &b.type, &solen) < 0)
01e10de3
LP
346 return false;
347
dbafedac 348 if (b.type != a->type)
01e10de3
LP
349 return false;
350
351 if (a->protocol != 0) {
dbafedac
MS
352 solen = sizeof(b.protocol);
353 if (getsockopt(fd, SOL_SOCKET, SO_PROTOCOL, &b.protocol, &solen) < 0)
01e10de3
LP
354 return false;
355
dbafedac 356 if (b.protocol != a->protocol)
01e10de3
LP
357 return false;
358 }
359
02233928 360 return socket_address_equal(a, &b);
01e10de3
LP
361}
362
f6aac5bf 363int sockaddr_port(const struct sockaddr *_sa, unsigned *ret_port) {
31325971 364 const union sockaddr_union *sa = (const union sockaddr_union*) _sa;
3b1c5241 365
f6aac5bf
LP
366 /* Note, this returns the port as 'unsigned' rather than 'uint16_t', as AF_VSOCK knows larger ports */
367
3b1c5241
SL
368 assert(sa);
369
0fc0f14b 370 switch (sa->sa.sa_family) {
f6aac5bf 371
0fc0f14b 372 case AF_INET:
f6aac5bf 373 *ret_port = be16toh(sa->in.sin_port);
0fc0f14b 374 return 0;
3b1c5241 375
0fc0f14b 376 case AF_INET6:
f6aac5bf 377 *ret_port = be16toh(sa->in6.sin6_port);
0fc0f14b
SH
378 return 0;
379
380 case AF_VSOCK:
f6aac5bf 381 *ret_port = sa->vm.svm_port;
0fc0f14b
SH
382 return 0;
383
384 default:
385 return -EAFNOSUPPORT;
386 }
3b1c5241
SL
387}
388
31325971
LP
389const union in_addr_union *sockaddr_in_addr(const struct sockaddr *_sa) {
390 const union sockaddr_union *sa = (const union sockaddr_union*) _sa;
391
392 if (!sa)
393 return NULL;
394
395 switch (sa->sa.sa_family) {
396
397 case AF_INET:
398 return (const union in_addr_union*) &sa->in.sin_addr;
399
400 case AF_INET6:
401 return (const union in_addr_union*) &sa->in6.sin6_addr;
402
403 default:
404 return NULL;
405 }
406}
407
c1b91f06
LP
408int sockaddr_set_in_addr(
409 union sockaddr_union *u,
410 int family,
411 const union in_addr_union *a,
412 uint16_t port) {
413
414 assert(u);
415 assert(a);
416
417 switch (family) {
418
419 case AF_INET:
420 u->in = (struct sockaddr_in) {
421 .sin_family = AF_INET,
422 .sin_addr = a->in,
423 .sin_port = htobe16(port),
424 };
425
426 return 0;
427
428 case AF_INET6:
429 u->in6 = (struct sockaddr_in6) {
430 .sin6_family = AF_INET6,
431 .sin6_addr = a->in6,
432 .sin6_port = htobe16(port),
433 };
434
435 return 0;
436
437 default:
438 return -EAFNOSUPPORT;
439
440 }
441}
442
836f9cfe
LP
443int sockaddr_pretty(
444 const struct sockaddr *_sa,
445 socklen_t salen,
446 bool translate_ipv6,
447 bool include_port,
448 char **ret) {
449
4d49b48c 450 union sockaddr_union *sa = (union sockaddr_union*) _sa;
8569a776 451 char *p;
fc25ad25 452 int r;
8569a776 453
4d49b48c
LP
454 assert(sa);
455 assert(salen >= sizeof(sa->sa.sa_family));
8569a776 456
4d49b48c 457 switch (sa->sa.sa_family) {
8569a776
LP
458
459 case AF_INET: {
460 uint32_t a;
461
8e38570e 462 a = be32toh(sa->in.sin_addr.s_addr);
8569a776 463
fc25ad25
ZJS
464 if (include_port)
465 r = asprintf(&p,
3b1c5241
SL
466 "%u.%u.%u.%u:%u",
467 a >> 24, (a >> 16) & 0xFF, (a >> 8) & 0xFF, a & 0xFF,
8e38570e 468 be16toh(sa->in.sin_port));
fc25ad25
ZJS
469 else
470 r = asprintf(&p,
3b1c5241 471 "%u.%u.%u.%u",
fc25ad25
ZJS
472 a >> 24, (a >> 16) & 0xFF, (a >> 8) & 0xFF, a & 0xFF);
473 if (r < 0)
474 return -ENOMEM;
8569a776
LP
475 break;
476 }
477
478 case AF_INET6: {
479 static const unsigned char ipv4_prefix[] = {
480 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xFF, 0xFF
481 };
482
fc25ad25
ZJS
483 if (translate_ipv6 &&
484 memcmp(&sa->in6.sin6_addr, ipv4_prefix, sizeof(ipv4_prefix)) == 0) {
4d49b48c 485 const uint8_t *a = sa->in6.sin6_addr.s6_addr+12;
fc25ad25
ZJS
486 if (include_port)
487 r = asprintf(&p,
3b1c5241
SL
488 "%u.%u.%u.%u:%u",
489 a[0], a[1], a[2], a[3],
8e38570e 490 be16toh(sa->in6.sin6_port));
fc25ad25
ZJS
491 else
492 r = asprintf(&p,
3b1c5241 493 "%u.%u.%u.%u",
fc25ad25
ZJS
494 a[0], a[1], a[2], a[3]);
495 if (r < 0)
496 return -ENOMEM;
8569a776 497 } else {
071e522e 498 const char *a = IN6_ADDR_TO_STRING(&sa->in6.sin6_addr);
3b1c5241
SL
499
500 if (include_port) {
01afd0f7 501 if (asprintf(&p,
b16d17a6 502 "[%s]:%u%s%s",
3b1c5241 503 a,
b16d17a6
ZJS
504 be16toh(sa->in6.sin6_port),
505 sa->in6.sin6_scope_id != 0 ? "%" : "",
01afd0f7 506 FORMAT_IFNAME_FULL(sa->in6.sin6_scope_id, FORMAT_IFNAME_IFINDEX)) < 0)
3b1c5241
SL
507 return -ENOMEM;
508 } else {
01afd0f7
YW
509 if (sa->in6.sin6_scope_id != 0)
510 p = strjoin(a, "%", FORMAT_IFNAME_FULL(sa->in6.sin6_scope_id, FORMAT_IFNAME_IFINDEX));
511 else
512 p = strdup(a);
3b1c5241
SL
513 if (!p)
514 return -ENOMEM;
515 }
8569a776
LP
516 }
517
518 break;
519 }
520
4d49b48c 521 case AF_UNIX:
15dca371 522 if (salen <= offsetof(struct sockaddr_un, sun_path) ||
994b9d4e 523 (sa->un.sun_path[0] == 0 && salen == offsetof(struct sockaddr_un, sun_path) + 1))
15dca371 524 /* The name must have at least one character (and the leading NUL does not count) */
4d49b48c 525 p = strdup("<unnamed>");
994b9d4e 526 else {
085b39e9
LP
527 /* Note that we calculate the path pointer here through the .un_buffer[] field, in order to
528 * outtrick bounds checking tools such as ubsan, which are too smart for their own good: on
529 * Linux the kernel may return sun_path[] data one byte longer than the declared size of the
530 * field. */
531 char *path = (char*) sa->un_buffer + offsetof(struct sockaddr_un, sun_path);
15dca371 532 size_t path_len = salen - offsetof(struct sockaddr_un, sun_path);
8569a776 533
085b39e9 534 if (path[0] == 0) {
15dca371
ZJS
535 /* Abstract socket. When parsing address information from, we
536 * explicitly reject overly long paths and paths with embedded NULs.
537 * But we might get such a socket from the outside. Let's return
538 * something meaningful and printable in this case. */
4d49b48c 539
15dca371 540 _cleanup_free_ char *e = NULL;
4d49b48c 541
085b39e9 542 e = cescape_length(path + 1, path_len - 1);
15dca371
ZJS
543 if (!e)
544 return -ENOMEM;
4d49b48c 545
15dca371
ZJS
546 p = strjoin("@", e);
547 } else {
085b39e9 548 if (path[path_len - 1] == '\0')
15dca371 549 /* We expect a terminating NUL and don't print it */
b3a9d980 550 path_len--;
15dca371 551
085b39e9 552 p = cescape_length(path, path_len);
15dca371 553 }
4d49b48c 554 }
994b9d4e
LP
555 if (!p)
556 return -ENOMEM;
8569a776
LP
557
558 break;
8569a776 559
0fc0f14b 560 case AF_VSOCK:
3a484991
ZJS
561 if (include_port) {
562 if (sa->vm.svm_cid == VMADDR_CID_ANY)
563 r = asprintf(&p, "vsock::%u", sa->vm.svm_port);
564 else
565 r = asprintf(&p, "vsock:%u:%u", sa->vm.svm_cid, sa->vm.svm_port);
566 } else
0fc0f14b
SH
567 r = asprintf(&p, "vsock:%u", sa->vm.svm_cid);
568 if (r < 0)
569 return -ENOMEM;
570 break;
571
8569a776 572 default:
15411c0c 573 return -EOPNOTSUPP;
8569a776
LP
574 }
575
576 *ret = p;
577 return 0;
578}
579
366b7db4 580int getpeername_pretty(int fd, bool include_port, char **ret) {
4d49b48c 581 union sockaddr_union sa;
b31f535c 582 socklen_t salen = sizeof(sa);
eff05270 583 int r;
4d49b48c
LP
584
585 assert(fd >= 0);
586 assert(ret);
587
4d49b48c
LP
588 if (getpeername(fd, &sa.sa, &salen) < 0)
589 return -errno;
590
591 if (sa.sa.sa_family == AF_UNIX) {
a995ce47 592 struct ucred ucred = UCRED_INVALID;
4d49b48c
LP
593
594 /* UNIX connection sockets are anonymous, so let's use
595 * PID/UID as pretty credentials instead */
596
eff05270
LP
597 r = getpeercred(fd, &ucred);
598 if (r < 0)
599 return r;
4d49b48c 600
de0671ee 601 if (asprintf(ret, "PID "PID_FMT"/UID "UID_FMT, ucred.pid, ucred.uid) < 0)
4d49b48c
LP
602 return -ENOMEM;
603
604 return 0;
605 }
606
607 /* For remote sockets we translate IPv6 addresses back to IPv4
608 * if applicable, since that's nicer. */
609
366b7db4 610 return sockaddr_pretty(&sa.sa, salen, true, include_port, ret);
4d49b48c
LP
611}
612
613int getsockname_pretty(int fd, char **ret) {
614 union sockaddr_union sa;
b31f535c 615 socklen_t salen = sizeof(sa);
4d49b48c
LP
616
617 assert(fd >= 0);
618 assert(ret);
619
4d49b48c
LP
620 if (getsockname(fd, &sa.sa, &salen) < 0)
621 return -errno;
622
623 /* For local sockets we do not translate IPv6 addresses back
624 * to IPv6 if applicable, since this is usually used for
625 * listening sockets where the difference between IPv4 and
626 * IPv6 matters. */
627
3b1c5241 628 return sockaddr_pretty(&sa.sa, salen, false, true, ret);
4d49b48c
LP
629}
630
b31f535c
ZJS
631int socknameinfo_pretty(union sockaddr_union *sa, socklen_t salen, char **_ret) {
632 int r;
633 char host[NI_MAXHOST], *ret;
634
635 assert(_ret);
636
6326a143 637 r = getnameinfo(&sa->sa, salen, host, sizeof(host), NULL, 0, IDN_FLAGS);
b31f535c 638 if (r != 0) {
b31f535c
ZJS
639 int saved_errno = errno;
640
3b1c5241 641 r = sockaddr_pretty(&sa->sa, salen, true, true, &ret);
f647962d 642 if (r < 0)
1938ac51 643 return r;
b31f535c 644
279d3c9c 645 log_debug_errno(saved_errno, "getnameinfo(%s) failed: %m", ret);
cb651834
ZJS
646 } else {
647 ret = strdup(host);
648 if (!ret)
1938ac51 649 return -ENOMEM;
cb651834 650 }
b31f535c
ZJS
651
652 *_ret = ret;
653 return 0;
654}
655
7a22745a 656static const char* const netlink_family_table[] = {
0d7e34e3
ZJS
657 [NETLINK_ROUTE] = "route",
658 [NETLINK_FIREWALL] = "firewall",
659 [NETLINK_INET_DIAG] = "inet-diag",
660 [NETLINK_NFLOG] = "nflog",
661 [NETLINK_XFRM] = "xfrm",
662 [NETLINK_SELINUX] = "selinux",
663 [NETLINK_ISCSI] = "iscsi",
664 [NETLINK_AUDIT] = "audit",
665 [NETLINK_FIB_LOOKUP] = "fib-lookup",
666 [NETLINK_CONNECTOR] = "connector",
667 [NETLINK_NETFILTER] = "netfilter",
668 [NETLINK_IP6_FW] = "ip6-fw",
669 [NETLINK_DNRTMSG] = "dnrtmsg",
7a22745a 670 [NETLINK_KOBJECT_UEVENT] = "kobject-uevent",
0d7e34e3
ZJS
671 [NETLINK_GENERIC] = "generic",
672 [NETLINK_SCSITRANSPORT] = "scsitransport",
673 [NETLINK_ECRYPTFS] = "ecryptfs",
674 [NETLINK_RDMA] = "rdma",
7a22745a
LP
675};
676
f8b69d1d 677DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(netlink_family, int, INT_MAX);
7a22745a 678
c0120d99
LP
679static const char* const socket_address_bind_ipv6_only_table[_SOCKET_ADDRESS_BIND_IPV6_ONLY_MAX] = {
680 [SOCKET_ADDRESS_DEFAULT] = "default",
681 [SOCKET_ADDRESS_BOTH] = "both",
682 [SOCKET_ADDRESS_IPV6_ONLY] = "ipv6-only"
683};
684
685DEFINE_STRING_TABLE_LOOKUP(socket_address_bind_ipv6_only, SocketAddressBindIPv6Only);
f01e5736 686
b54e98ef 687SocketAddressBindIPv6Only socket_address_bind_ipv6_only_or_bool_from_string(const char *n) {
6f90844f
YW
688 int r;
689
690 r = parse_boolean(n);
691 if (r > 0)
692 return SOCKET_ADDRESS_IPV6_ONLY;
693 if (r == 0)
694 return SOCKET_ADDRESS_BOTH;
695
696 return socket_address_bind_ipv6_only_from_string(n);
697}
698
f01e5736
LP
699bool sockaddr_equal(const union sockaddr_union *a, const union sockaddr_union *b) {
700 assert(a);
701 assert(b);
702
703 if (a->sa.sa_family != b->sa.sa_family)
704 return false;
705
706 if (a->sa.sa_family == AF_INET)
707 return a->in.sin_addr.s_addr == b->in.sin_addr.s_addr;
708
709 if (a->sa.sa_family == AF_INET6)
710 return memcmp(&a->in6.sin6_addr, &b->in6.sin6_addr, sizeof(a->in6.sin6_addr)) == 0;
711
0fc0f14b
SH
712 if (a->sa.sa_family == AF_VSOCK)
713 return a->vm.svm_cid == b->vm.svm_cid;
714
f01e5736
LP
715 return false;
716}
2583fbea 717
d9d9b2a0 718int fd_set_sndbuf(int fd, size_t n, bool increase) {
2583fbea
LP
719 int r, value;
720 socklen_t l = sizeof(value);
721
1263c85e
YW
722 if (n > INT_MAX)
723 return -ERANGE;
724
2583fbea 725 r = getsockopt(fd, SOL_SOCKET, SO_SNDBUF, &value, &l);
d9d9b2a0 726 if (r >= 0 && l == sizeof(value) && increase ? (size_t) value >= n*2 : (size_t) value == n*2)
2583fbea
LP
727 return 0;
728
b92f3507
YW
729 /* First, try to set the buffer size with SO_SNDBUF. */
730 r = setsockopt_int(fd, SOL_SOCKET, SO_SNDBUF, n);
731 if (r < 0)
732 return r;
2583fbea 733
b92f3507
YW
734 /* SO_SNDBUF above may set to the kernel limit, instead of the requested size.
735 * So, we need to check the actual buffer size here. */
67f5ae2d 736 l = sizeof(value);
b92f3507 737 r = getsockopt(fd, SOL_SOCKET, SO_SNDBUF, &value, &l);
d9d9b2a0 738 if (r >= 0 && l == sizeof(value) && increase ? (size_t) value >= n*2 : (size_t) value == n*2)
b92f3507
YW
739 return 1;
740
741 /* If we have the privileges we will ignore the kernel limit. */
742 r = setsockopt_int(fd, SOL_SOCKET, SO_SNDBUFFORCE, n);
743 if (r < 0)
744 return r;
2583fbea
LP
745
746 return 1;
747}
748
d9d9b2a0 749int fd_set_rcvbuf(int fd, size_t n, bool increase) {
2583fbea
LP
750 int r, value;
751 socklen_t l = sizeof(value);
752
1263c85e
YW
753 if (n > INT_MAX)
754 return -ERANGE;
755
2583fbea 756 r = getsockopt(fd, SOL_SOCKET, SO_RCVBUF, &value, &l);
d9d9b2a0 757 if (r >= 0 && l == sizeof(value) && increase ? (size_t) value >= n*2 : (size_t) value == n*2)
2583fbea
LP
758 return 0;
759
b92f3507
YW
760 /* First, try to set the buffer size with SO_RCVBUF. */
761 r = setsockopt_int(fd, SOL_SOCKET, SO_RCVBUF, n);
762 if (r < 0)
763 return r;
2583fbea 764
b92f3507
YW
765 /* SO_RCVBUF above may set to the kernel limit, instead of the requested size.
766 * So, we need to check the actual buffer size here. */
67f5ae2d 767 l = sizeof(value);
b92f3507 768 r = getsockopt(fd, SOL_SOCKET, SO_RCVBUF, &value, &l);
d9d9b2a0 769 if (r >= 0 && l == sizeof(value) && increase ? (size_t) value >= n*2 : (size_t) value == n*2)
b92f3507
YW
770 return 1;
771
772 /* If we have the privileges we will ignore the kernel limit. */
773 r = setsockopt_int(fd, SOL_SOCKET, SO_RCVBUFFORCE, n);
774 if (r < 0)
775 return r;
9e5b6496 776
2583fbea
LP
777 return 1;
778}
779
780static const char* const ip_tos_table[] = {
0d7e34e3
ZJS
781 [IPTOS_LOWDELAY] = "low-delay",
782 [IPTOS_THROUGHPUT] = "throughput",
2583fbea 783 [IPTOS_RELIABILITY] = "reliability",
0d7e34e3 784 [IPTOS_LOWCOST] = "low-cost",
2583fbea
LP
785};
786
787DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(ip_tos, int, 0xff);
788
5a3586db
YW
789bool ifname_valid_char(char a) {
790 if ((unsigned char) a >= 127U)
791 return false;
792
793 if ((unsigned char) a <= 32U)
794 return false;
795
796 if (IN_SET(a,
797 ':', /* colons are used by the legacy "alias" interface logic */
798 '/', /* slashes cannot work, since we need to use network interfaces in sysfs paths, and in paths slashes are separators */
799 '%')) /* %d is used in the kernel's weird foo%d format string naming feature which we really really don't want to ever run into by accident */
800 return false;
801
802 return true;
803}
804
2313524a 805bool ifname_valid_full(const char *p, IfnameValidFlags flags) {
ef76dff2
LP
806 bool numeric = true;
807
808 /* Checks whether a network interface name is valid. This is inspired by dev_valid_name() in the kernel sources
809 * but slightly stricter, as we only allow non-control, non-space ASCII characters in the interface name. We
810 * also don't permit names that only container numbers, to avoid confusion with numeric interface indexes. */
811
2313524a
ZJS
812 assert(!(flags & ~_IFNAME_VALID_ALL));
813
ef76dff2
LP
814 if (isempty(p))
815 return false;
816
ee29bd5d
LP
817 /* A valid ifindex? If so, it's valid iff IFNAME_VALID_NUMERIC is set */
818 if (parse_ifindex(p) >= 0)
819 return flags & IFNAME_VALID_NUMERIC;
820
2313524a 821 if (flags & IFNAME_VALID_ALTERNATIVE) {
4252696a
YW
822 if (strlen(p) >= ALTIFNAMSIZ)
823 return false;
824 } else {
825 if (strlen(p) >= IFNAMSIZ)
826 return false;
827 }
ef76dff2 828
49bfc877 829 if (dot_or_dot_dot(p))
ef76dff2
LP
830 return false;
831
07a7441a
LP
832 /* Let's refuse "all" and "default" as interface name, to avoid collisions with the special sysctl
833 * directories /proc/sys/net/{ipv4,ipv6}/conf/{all,default} */
6aebfec3 834 if (!FLAGS_SET(flags, IFNAME_VALID_SPECIAL) && STR_IN_SET(p, "all", "default"))
07a7441a
LP
835 return false;
836
2313524a 837 for (const char *t = p; *t; t++) {
5a3586db 838 if (!ifname_valid_char(*t))
ef76dff2
LP
839 return false;
840
ff25d338 841 numeric = numeric && ascii_isdigit(*t);
ef76dff2
LP
842 }
843
ee29bd5d
LP
844 /* It's fully numeric but didn't parse as valid ifindex above? if so, it must be too large or zero or
845 * so, let's refuse that. */
846 if (numeric)
847 return false;
ef76dff2
LP
848
849 return true;
850}
851
26808948
SS
852bool address_label_valid(const char *p) {
853
854 if (isempty(p))
855 return false;
856
857 if (strlen(p) >= IFNAMSIZ)
858 return false;
859
860 while (*p) {
861 if ((uint8_t) *p >= 127U)
862 return false;
863
864 if ((uint8_t) *p <= 31U)
865 return false;
866 p++;
867 }
868
869 return true;
870}
871
2583fbea
LP
872int getpeercred(int fd, struct ucred *ucred) {
873 socklen_t n = sizeof(struct ucred);
874 struct ucred u;
2583fbea
LP
875
876 assert(fd >= 0);
877 assert(ucred);
878
fccad706 879 if (getsockopt(fd, SOL_SOCKET, SO_PEERCRED, &u, &n) < 0)
2583fbea
LP
880 return -errno;
881
882 if (n != sizeof(struct ucred))
883 return -EIO;
884
bbcc701e
LP
885 /* Check if the data is actually useful and not suppressed due to namespacing issues */
886 if (!pid_is_valid(u.pid))
2583fbea
LP
887 return -ENODATA;
888
bbcc701e
LP
889 /* Note that we don't check UID/GID here, as namespace translation works differently there: instead of
890 * receiving in "invalid" user/group we get the overflow UID/GID. */
891
2583fbea
LP
892 *ucred = u;
893 return 0;
894}
895
896int getpeersec(int fd, char **ret) {
217d8967 897 _cleanup_free_ char *s = NULL;
2583fbea 898 socklen_t n = 64;
2583fbea
LP
899
900 assert(fd >= 0);
901 assert(ret);
902
217d8967
LP
903 for (;;) {
904 s = new0(char, n+1);
905 if (!s)
906 return -ENOMEM;
2583fbea 907
989740eb
LP
908 if (getsockopt(fd, SOL_SOCKET, SO_PEERSEC, s, &n) >= 0) {
909 s[n] = 0;
217d8967 910 break;
989740eb 911 }
2583fbea
LP
912
913 if (errno != ERANGE)
914 return -errno;
915
217d8967 916 s = mfree(s);
2583fbea
LP
917 }
918
217d8967 919 if (isempty(s))
2583fbea 920 return -EOPNOTSUPP;
2583fbea 921
ae2a15bc 922 *ret = TAKE_PTR(s);
217d8967 923
2583fbea
LP
924 return 0;
925}
926
43f2c88d
LP
927int getpeergroups(int fd, gid_t **ret) {
928 socklen_t n = sizeof(gid_t) * 64;
929 _cleanup_free_ gid_t *d = NULL;
930
75f40779 931 assert(fd >= 0);
43f2c88d
LP
932 assert(ret);
933
934 for (;;) {
935 d = malloc(n);
936 if (!d)
937 return -ENOMEM;
938
939 if (getsockopt(fd, SOL_SOCKET, SO_PEERGROUPS, d, &n) >= 0)
940 break;
941
942 if (errno != ERANGE)
943 return -errno;
944
945 d = mfree(d);
946 }
947
948 assert_se(n % sizeof(gid_t) == 0);
949 n /= sizeof(gid_t);
950
951 if ((socklen_t) (int) n != n)
952 return -E2BIG;
953
1cc6c93a 954 *ret = TAKE_PTR(d);
43f2c88d
LP
955
956 return (int) n;
957}
958
da5e0c44
LP
959int getpeerpidfd(int fd) {
960 socklen_t n = sizeof(int);
961 int pidfd = -EBADF;
962
963 assert(fd >= 0);
964
965 if (getsockopt(fd, SOL_SOCKET, SO_PEERPIDFD, &pidfd, &n) < 0)
966 return -errno;
967
968 if (n != sizeof(int))
969 return -EIO;
970
971 return pidfd;
972}
973
598d2428
LB
974ssize_t send_many_fds_iov_sa(
975 int transport_fd,
976 int *fds_array, size_t n_fds_array,
977 const struct iovec *iov, size_t iovlen,
978 const struct sockaddr *sa, socklen_t len,
979 int flags) {
980
981 _cleanup_free_ struct cmsghdr *cmsg = NULL;
982 struct msghdr mh = {
983 .msg_name = (struct sockaddr*) sa,
984 .msg_namelen = len,
985 .msg_iov = (struct iovec *)iov,
986 .msg_iovlen = iovlen,
987 };
988 ssize_t k;
989
990 assert(transport_fd >= 0);
991 assert(fds_array || n_fds_array == 0);
992
993 /* The kernel will reject sending more than SCM_MAX_FD FDs at once */
994 if (n_fds_array > SCM_MAX_FD)
995 return -E2BIG;
996
997 /* We need either an FD array or data to send. If there's nothing, return an error. */
998 if (n_fds_array == 0 && !iov)
999 return -EINVAL;
1000
1001 if (n_fds_array > 0) {
1002 mh.msg_controllen = CMSG_SPACE(sizeof(int) * n_fds_array);
1003 mh.msg_control = cmsg = malloc(mh.msg_controllen);
1004 if (!cmsg)
1005 return -ENOMEM;
1006
1007 *cmsg = (struct cmsghdr) {
1008 .cmsg_len = CMSG_LEN(sizeof(int) * n_fds_array),
1009 .cmsg_level = SOL_SOCKET,
1010 .cmsg_type = SCM_RIGHTS,
1011 };
1012 memcpy(CMSG_DATA(cmsg), fds_array, sizeof(int) * n_fds_array);
1013 }
1014 k = sendmsg(transport_fd, &mh, MSG_NOSIGNAL | flags);
1015 if (k < 0)
1016 return (ssize_t) -errno;
1017
1018 return k;
1019}
1020
d34673ec 1021ssize_t send_one_fd_iov_sa(
726f4c47
ZJS
1022 int transport_fd,
1023 int fd,
f621b8d7 1024 const struct iovec *iov, size_t iovlen,
726f4c47
ZJS
1025 const struct sockaddr *sa, socklen_t len,
1026 int flags) {
1027
fb29cdbe 1028 CMSG_BUFFER_TYPE(CMSG_SPACE(sizeof(int))) control = {};
2583fbea 1029 struct msghdr mh = {
726f4c47
ZJS
1030 .msg_name = (struct sockaddr*) sa,
1031 .msg_namelen = len,
f621b8d7 1032 .msg_iov = (struct iovec *)iov,
d34673ec 1033 .msg_iovlen = iovlen,
2583fbea 1034 };
d34673ec 1035 ssize_t k;
2583fbea
LP
1036
1037 assert(transport_fd >= 0);
2583fbea 1038
d34673ec
FB
1039 /*
1040 * We need either an FD or data to send.
1041 * If there's nothing, return an error.
1042 */
1043 if (fd < 0 && !iov)
1044 return -EINVAL;
2583fbea 1045
d34673ec
FB
1046 if (fd >= 0) {
1047 struct cmsghdr *cmsg;
2583fbea 1048
d34673ec
FB
1049 mh.msg_control = &control;
1050 mh.msg_controllen = sizeof(control);
1051
1052 cmsg = CMSG_FIRSTHDR(&mh);
1053 cmsg->cmsg_level = SOL_SOCKET;
1054 cmsg->cmsg_type = SCM_RIGHTS;
1055 cmsg->cmsg_len = CMSG_LEN(sizeof(int));
1056 memcpy(CMSG_DATA(cmsg), &fd, sizeof(int));
d34673ec
FB
1057 }
1058 k = sendmsg(transport_fd, &mh, MSG_NOSIGNAL | flags);
1059 if (k < 0)
1060 return (ssize_t) -errno;
1061
1062 return k;
2583fbea
LP
1063}
1064
d34673ec
FB
1065int send_one_fd_sa(
1066 int transport_fd,
1067 int fd,
1068 const struct sockaddr *sa, socklen_t len,
1069 int flags) {
1070
1071 assert(fd >= 0);
1072
1073 return (int) send_one_fd_iov_sa(transport_fd, fd, NULL, 0, sa, len, flags);
1074}
1075
598d2428
LB
1076ssize_t receive_many_fds_iov(
1077 int transport_fd,
1078 struct iovec *iov, size_t iovlen,
1079 int **ret_fds_array, size_t *ret_n_fds_array,
1080 int flags) {
1081
1082 CMSG_BUFFER_TYPE(CMSG_SPACE(sizeof(int) * SCM_MAX_FD)) control;
1083 struct msghdr mh = {
1084 .msg_control = &control,
1085 .msg_controllen = sizeof(control),
1086 .msg_iov = iov,
1087 .msg_iovlen = iovlen,
1088 };
1089 _cleanup_free_ int *fds_array = NULL;
1090 size_t n_fds_array = 0;
1091 struct cmsghdr *cmsg;
1092 ssize_t k;
1093
1094 assert(transport_fd >= 0);
1095 assert(ret_fds_array);
1096 assert(ret_n_fds_array);
1097
1098 /*
1099 * Receive many FDs via @transport_fd. We don't care for the transport-type. We retrieve all the FDs
1100 * at once. This is best used in combination with send_many_fds().
1101 */
1102
1103 k = recvmsg_safe(transport_fd, &mh, MSG_CMSG_CLOEXEC | flags);
1104 if (k < 0)
1105 return k;
1106
1107 CMSG_FOREACH(cmsg, &mh)
1108 if (cmsg->cmsg_level == SOL_SOCKET && cmsg->cmsg_type == SCM_RIGHTS) {
1109 size_t n = (cmsg->cmsg_len - CMSG_LEN(0)) / sizeof(int);
1110
1111 fds_array = GREEDY_REALLOC(fds_array, n_fds_array + n);
1112 if (!fds_array) {
1113 cmsg_close_all(&mh);
1114 return -ENOMEM;
1115 }
1116
1117 memcpy(fds_array + n_fds_array, CMSG_TYPED_DATA(cmsg, int), sizeof(int) * n);
1118 n_fds_array += n;
1119 }
1120
1121 if (n_fds_array == 0) {
1122 cmsg_close_all(&mh);
1123
1124 /* If didn't receive an FD or any data, return an error. */
1125 if (k == 0)
1126 return -EIO;
1127 }
1128
1129 *ret_fds_array = TAKE_PTR(fds_array);
1130 *ret_n_fds_array = n_fds_array;
1131
1132 return k;
1133}
1134
1135int receive_many_fds(int transport_fd, int **ret_fds_array, size_t *ret_n_fds_array, int flags) {
1136 ssize_t k;
1137
1138 k = receive_many_fds_iov(transport_fd, NULL, 0, ret_fds_array, ret_n_fds_array, flags);
1139 if (k == 0)
1140 return 0;
1141
1142 /* k must be negative, since receive_many_fds_iov() only returns a positive value if data was received
1143 * through the iov. */
1144 assert(k < 0);
1145 return (int) k;
1146}
1147
d34673ec
FB
1148ssize_t receive_one_fd_iov(
1149 int transport_fd,
1150 struct iovec *iov, size_t iovlen,
1151 int flags,
1152 int *ret_fd) {
1153
fb29cdbe 1154 CMSG_BUFFER_TYPE(CMSG_SPACE(sizeof(int))) control;
2583fbea
LP
1155 struct msghdr mh = {
1156 .msg_control = &control,
1157 .msg_controllen = sizeof(control),
d34673ec
FB
1158 .msg_iov = iov,
1159 .msg_iovlen = iovlen,
2583fbea 1160 };
dac556fa 1161 struct cmsghdr *found;
d34673ec 1162 ssize_t k;
2583fbea
LP
1163
1164 assert(transport_fd >= 0);
d34673ec 1165 assert(ret_fd);
2583fbea
LP
1166
1167 /*
1168 * Receive a single FD via @transport_fd. We don't care for
1169 * the transport-type. We retrieve a single FD at most, so for
1170 * packet-based transports, the caller must ensure to send
1171 * only a single FD per packet. This is best used in
1172 * combination with send_one_fd().
1173 */
1174
3691bcf3 1175 k = recvmsg_safe(transport_fd, &mh, MSG_CMSG_CLOEXEC | flags);
d34673ec 1176 if (k < 0)
3691bcf3 1177 return k;
2583fbea 1178
dac556fa 1179 found = cmsg_find(&mh, SOL_SOCKET, SCM_RIGHTS, CMSG_LEN(sizeof(int)));
3691bcf3 1180 if (!found) {
2583fbea 1181 cmsg_close_all(&mh);
d34673ec 1182
3691bcf3
LP
1183 /* If didn't receive an FD or any data, return an error. */
1184 if (k == 0)
1185 return -EIO;
1186 }
2583fbea 1187
d34673ec 1188 if (found)
b1d02191 1189 *ret_fd = *CMSG_TYPED_DATA(found, int);
d34673ec 1190 else
254d1313 1191 *ret_fd = -EBADF;
d34673ec
FB
1192
1193 return k;
1194}
1195
1196int receive_one_fd(int transport_fd, int flags) {
1197 int fd;
1198 ssize_t k;
1199
1200 k = receive_one_fd_iov(transport_fd, NULL, 0, flags, &fd);
1201 if (k == 0)
1202 return fd;
1203
1204 /* k must be negative, since receive_one_fd_iov() only returns
1205 * a positive value if data was received through the iov. */
1206 assert(k < 0);
1207 return (int) k;
2583fbea 1208}
4edc2c9b
LP
1209
1210ssize_t next_datagram_size_fd(int fd) {
1211 ssize_t l;
1212 int k;
1213
1214 /* This is a bit like FIONREAD/SIOCINQ, however a bit more powerful. The difference being: recv(MSG_PEEK) will
96d49011 1215 * actually cause the next datagram in the queue to be validated regarding checksums, which FIONREAD doesn't
4edc2c9b
LP
1216 * do. This difference is actually of major importance as we need to be sure that the size returned here
1217 * actually matches what we will read with recvmsg() next, as otherwise we might end up allocating a buffer of
1218 * the wrong size. */
1219
1220 l = recv(fd, NULL, 0, MSG_PEEK|MSG_TRUNC);
1221 if (l < 0) {
3742095b 1222 if (IN_SET(errno, EOPNOTSUPP, EFAULT))
4edc2c9b
LP
1223 goto fallback;
1224
1225 return -errno;
1226 }
1227 if (l == 0)
1228 goto fallback;
1229
1230 return l;
1231
1232fallback:
1233 k = 0;
1234
1235 /* Some sockets (AF_PACKET) do not support null-sized recv() with MSG_TRUNC set, let's fall back to FIONREAD
1236 * for them. Checksums don't matter for raw sockets anyway, hence this should be fine. */
1237
1238 if (ioctl(fd, FIONREAD, &k) < 0)
1239 return -errno;
1240
1241 return (ssize_t) k;
1242}
60d9771c 1243
67962036
ZJS
1244/* Put a limit on how many times will attempt to call accept4(). We loop
1245 * only on "transient" errors, but let's make sure we don't loop forever. */
1246#define MAX_FLUSH_ITERATIONS 1024
1247
60d9771c
LP
1248int flush_accept(int fd) {
1249
f3d75364
LP
1250 int r, b;
1251 socklen_t l = sizeof(b);
1252
644cb4cc
ZJS
1253 /* Similar to flush_fd() but flushes all incoming connections by accepting and immediately closing
1254 * them. */
f3d75364
LP
1255
1256 if (getsockopt(fd, SOL_SOCKET, SO_ACCEPTCONN, &b, &l) < 0)
1257 return -errno;
60d9771c 1258
f3d75364 1259 assert(l == sizeof(b));
644cb4cc
ZJS
1260 if (!b) /* Let's check if this socket accepts connections before calling accept(). accept4() can
1261 * return EOPNOTSUPP if the fd is not a listening socket, which we should treat as a fatal
1262 * error, or in case the incoming TCP connection triggered a network issue, which we want to
1263 * treat as a transient error. Thus, let's rule out the first reason for EOPNOTSUPP early, so
1264 * we can loop safely on transient errors below. */
f3d75364 1265 return -ENOTTY;
60d9771c 1266
67962036 1267 for (unsigned iteration = 0;; iteration++) {
60d9771c
LP
1268 int cfd;
1269
0f2d351f 1270 r = fd_wait_for_event(fd, POLLIN, 0);
60d9771c 1271 if (r < 0) {
0f2d351f 1272 if (r == -EINTR)
60d9771c
LP
1273 continue;
1274
0f2d351f 1275 return r;
4ff9bc2e
LP
1276 }
1277 if (r == 0)
60d9771c
LP
1278 return 0;
1279
67962036
ZJS
1280 if (iteration >= MAX_FLUSH_ITERATIONS)
1281 return log_debug_errno(SYNTHETIC_ERRNO(EBUSY),
1282 "Failed to flush connections within " STRINGIFY(MAX_FLUSH_ITERATIONS) " iterations.");
1283
60d9771c
LP
1284 cfd = accept4(fd, NULL, NULL, SOCK_NONBLOCK|SOCK_CLOEXEC);
1285 if (cfd < 0) {
60d9771c
LP
1286 if (errno == EAGAIN)
1287 return 0;
1288
4ff9bc2e
LP
1289 if (ERRNO_IS_ACCEPT_AGAIN(errno))
1290 continue;
1291
60d9771c
LP
1292 return -errno;
1293 }
1294
4ff9bc2e 1295 safe_close(cfd);
60d9771c
LP
1296 }
1297}
29206d46
LP
1298
1299struct cmsghdr* cmsg_find(struct msghdr *mh, int level, int type, socklen_t length) {
1300 struct cmsghdr *cmsg;
1301
1302 assert(mh);
1303
1304 CMSG_FOREACH(cmsg, mh)
1305 if (cmsg->cmsg_level == level &&
1306 cmsg->cmsg_type == type &&
1307 (length == (socklen_t) -1 || length == cmsg->cmsg_len))
1308 return cmsg;
1309
1310 return NULL;
1311}
429b4350 1312
4836f4c6
YW
1313void* cmsg_find_and_copy_data(struct msghdr *mh, int level, int type, void *buf, size_t buf_len) {
1314 struct cmsghdr *cmsg;
1315
1316 assert(mh);
1317 assert(buf);
1318 assert(buf_len > 0);
1319
1320 /* This is similar to cmsg_find_data(), but copy the found data to buf. This should be typically used
da890466 1321 * when reading possibly unaligned data such as timestamp, as time_t is 64-bit and size_t is 32-bit on
4836f4c6
YW
1322 * RISCV32. See issue #27241. */
1323
1324 cmsg = cmsg_find(mh, level, type, CMSG_LEN(buf_len));
1325 if (!cmsg)
1326 return NULL;
1327
1328 return memcpy_safe(buf, CMSG_DATA(cmsg), buf_len);
1329}
1330
429b4350
LP
1331int socket_ioctl_fd(void) {
1332 int fd;
1333
1334 /* Create a socket to invoke the various network interface ioctl()s on. Traditionally only AF_INET was good for
1335 * that. Since kernel 4.6 AF_NETLINK works for this too. We first try to use AF_INET hence, but if that's not
1336 * available (for example, because it is made unavailable via SECCOMP or such), we'll fall back to the more
1337 * generic AF_NETLINK. */
1338
1339 fd = socket(AF_INET, SOCK_DGRAM|SOCK_CLOEXEC, 0);
1340 if (fd < 0)
1341 fd = socket(AF_NETLINK, SOCK_RAW|SOCK_CLOEXEC, NETLINK_GENERIC);
1342 if (fd < 0)
1343 return -errno;
1344
1345 return fd;
1346}
9f20fc28
LP
1347
1348int sockaddr_un_unlink(const struct sockaddr_un *sa) {
1349 const char *p, * nul;
1350
1351 assert(sa);
1352
1353 if (sa->sun_family != AF_UNIX)
1354 return -EPROTOTYPE;
1355
1356 if (sa->sun_path[0] == 0) /* Nothing to do for abstract sockets */
1357 return 0;
1358
1359 /* The path in .sun_path is not necessarily NUL terminated. Let's fix that. */
1360 nul = memchr(sa->sun_path, 0, sizeof(sa->sun_path));
1361 if (nul)
1362 p = sa->sun_path;
1363 else
1364 p = memdupa_suffix0(sa->sun_path, sizeof(sa->sun_path));
1365
1366 if (unlink(p) < 0)
1367 return -errno;
1368
1369 return 1;
1370}
5cf91ea9
LP
1371
1372int sockaddr_un_set_path(struct sockaddr_un *ret, const char *path) {
1373 size_t l;
1374
1375 assert(ret);
1376 assert(path);
1377
1378 /* Initialize ret->sun_path from the specified argument. This will interpret paths starting with '@' as
1379 * abstract namespace sockets, and those starting with '/' as regular filesystem sockets. It won't accept
1380 * anything else (i.e. no relative paths), to avoid ambiguities. Note that this function cannot be used to
1381 * reference paths in the abstract namespace that include NUL bytes in the name. */
1382
1383 l = strlen(path);
c097bf1f 1384 if (l < 2)
5cf91ea9
LP
1385 return -EINVAL;
1386 if (!IN_SET(path[0], '/', '@'))
1387 return -EINVAL;
5cf91ea9
LP
1388
1389 /* Don't allow paths larger than the space in sockaddr_un. Note that we are a tiny bit more restrictive than
1390 * the kernel is: we insist on NUL termination (both for abstract namespace and regular file system socket
1391 * addresses!), which the kernel doesn't. We do this to reduce chance of incompatibility with other apps that
7802194a 1392 * do not expect non-NUL terminated file system path. */
5cf91ea9 1393 if (l+1 > sizeof(ret->sun_path))
dfa2b389
LP
1394 return path[0] == '@' ? -EINVAL : -ENAMETOOLONG; /* return a recognizable error if this is
1395 * too long to fit into a sockaddr_un, but
1396 * is a file system path, and thus might be
1397 * connectible via O_PATH indirection. */
5cf91ea9
LP
1398
1399 *ret = (struct sockaddr_un) {
1400 .sun_family = AF_UNIX,
1401 };
1402
1403 if (path[0] == '@') {
1404 /* Abstract namespace socket */
1405 memcpy(ret->sun_path + 1, path + 1, l); /* copy *with* trailing NUL byte */
1406 return (int) (offsetof(struct sockaddr_un, sun_path) + l); /* 🔥 *don't* 🔥 include trailing NUL in size */
1407
1408 } else {
1409 assert(path[0] == '/');
1410
1411 /* File system socket */
1412 memcpy(ret->sun_path, path, l + 1); /* copy *with* trailing NUL byte */
1413 return (int) (offsetof(struct sockaddr_un, sun_path) + l + 1); /* include trailing NUL in size */
1414 }
1415}
5d594d01
LP
1416
1417int socket_bind_to_ifname(int fd, const char *ifname) {
1418 assert(fd >= 0);
1419
1420 /* Call with NULL to drop binding */
1421
7c248223 1422 return RET_NERRNO(setsockopt(fd, SOL_SOCKET, SO_BINDTODEVICE, ifname, strlen_ptr(ifname)));
5d594d01
LP
1423}
1424
1425int socket_bind_to_ifindex(int fd, int ifindex) {
01afd0f7 1426 char ifname[IF_NAMESIZE];
5e958e1d 1427 int r;
5d594d01
LP
1428
1429 assert(fd >= 0);
1430
7c248223 1431 if (ifindex <= 0)
5d594d01 1432 /* Drop binding */
7c248223 1433 return RET_NERRNO(setsockopt(fd, SOL_SOCKET, SO_BINDTODEVICE, NULL, 0));
5d594d01 1434
5e958e1d
YW
1435 r = setsockopt_int(fd, SOL_SOCKET, SO_BINDTOIFINDEX, ifindex);
1436 if (r != -ENOPROTOOPT)
1437 return r;
5d594d01
LP
1438
1439 /* Fall back to SO_BINDTODEVICE on kernels < 5.0 which didn't have SO_BINDTOIFINDEX */
01afd0f7
YW
1440 r = format_ifname(ifindex, ifname);
1441 if (r < 0)
1442 return r;
5d594d01
LP
1443
1444 return socket_bind_to_ifname(fd, ifname);
1445}
47eae6ce
LP
1446
1447ssize_t recvmsg_safe(int sockfd, struct msghdr *msg, int flags) {
1448 ssize_t n;
1449
1450 /* A wrapper around recvmsg() that checks for MSG_CTRUNC, and turns it into an error, in a reasonably
1451 * safe way, closing any SCM_RIGHTS fds in the error path.
1452 *
1453 * Note that unlike our usual coding style this might modify *msg on failure. */
1454
1455 n = recvmsg(sockfd, msg, flags);
1456 if (n < 0)
1457 return -errno;
1458
1459 if (FLAGS_SET(msg->msg_flags, MSG_CTRUNC)) {
1460 cmsg_close_all(msg);
1461 return -EXFULL; /* a recognizable error code */
1462 }
1463
1464 return n;
35a3eb9b
LP
1465}
1466
5f64d2bf 1467int socket_get_family(int fd) {
35a3eb9b
LP
1468 int af;
1469 socklen_t sl = sizeof(af);
1470
1471 if (getsockopt(fd, SOL_SOCKET, SO_DOMAIN, &af, &sl) < 0)
1472 return -errno;
1473
5d0fe423
LP
1474 if (sl != sizeof(af))
1475 return -EINVAL;
1476
1477 return af;
1478}
1479
1480int socket_set_recvpktinfo(int fd, int af, bool b) {
5d0fe423
LP
1481
1482 if (af == AF_UNSPEC) {
5f64d2bf
LP
1483 af = socket_get_family(fd);
1484 if (af < 0)
1485 return af;
5d0fe423
LP
1486 }
1487
35a3eb9b
LP
1488 switch (af) {
1489
1490 case AF_INET:
1491 return setsockopt_int(fd, IPPROTO_IP, IP_PKTINFO, b);
47eae6ce 1492
35a3eb9b
LP
1493 case AF_INET6:
1494 return setsockopt_int(fd, IPPROTO_IPV6, IPV6_RECVPKTINFO, b);
1495
1496 case AF_NETLINK:
1497 return setsockopt_int(fd, SOL_NETLINK, NETLINK_PKTINFO, b);
1498
2d6d4136
LP
1499 case AF_PACKET:
1500 return setsockopt_int(fd, SOL_PACKET, PACKET_AUXDATA, b);
1501
35a3eb9b
LP
1502 default:
1503 return -EAFNOSUPPORT;
1504 }
47eae6ce 1505}
5d0fe423 1506
5d0fe423
LP
1507int socket_set_unicast_if(int fd, int af, int ifi) {
1508 be32_t ifindex_be = htobe32(ifi);
5d0fe423
LP
1509
1510 if (af == AF_UNSPEC) {
5f64d2bf
LP
1511 af = socket_get_family(fd);
1512 if (af < 0)
1513 return af;
5d0fe423
LP
1514 }
1515
1516 switch (af) {
1517
1518 case AF_INET:
7c248223 1519 return RET_NERRNO(setsockopt(fd, IPPROTO_IP, IP_UNICAST_IF, &ifindex_be, sizeof(ifindex_be)));
5d0fe423
LP
1520
1521 case AF_INET6:
7c248223 1522 return RET_NERRNO(setsockopt(fd, IPPROTO_IPV6, IPV6_UNICAST_IF, &ifindex_be, sizeof(ifindex_be)));
5d0fe423
LP
1523
1524 default:
1525 return -EAFNOSUPPORT;
1526 }
1527}
1528
402506ce 1529int socket_set_option(int fd, int af, int opt_ipv4, int opt_ipv6, int val) {
5d0fe423 1530 if (af == AF_UNSPEC) {
5f64d2bf
LP
1531 af = socket_get_family(fd);
1532 if (af < 0)
1533 return af;
5d0fe423
LP
1534 }
1535
1536 switch (af) {
1537
1538 case AF_INET:
402506ce 1539 return setsockopt_int(fd, IPPROTO_IP, opt_ipv4, val);
5d0fe423
LP
1540
1541 case AF_INET6:
402506ce 1542 return setsockopt_int(fd, IPPROTO_IPV6, opt_ipv6, val);
5d0fe423
LP
1543
1544 default:
1545 return -EAFNOSUPPORT;
1546 }
1547}
52975f86
LP
1548
1549int socket_get_mtu(int fd, int af, size_t *ret) {
1550 int mtu, r;
1551
1552 if (af == AF_UNSPEC) {
5f64d2bf
LP
1553 af = socket_get_family(fd);
1554 if (af < 0)
1555 return af;
52975f86
LP
1556 }
1557
1558 switch (af) {
1559
1560 case AF_INET:
1561 r = getsockopt_int(fd, IPPROTO_IP, IP_MTU, &mtu);
1562 break;
1563
1564 case AF_INET6:
1565 r = getsockopt_int(fd, IPPROTO_IPV6, IPV6_MTU, &mtu);
1566 break;
1567
1568 default:
1569 return -EAFNOSUPPORT;
1570 }
1571
1572 if (r < 0)
1573 return r;
1574 if (mtu <= 0)
1575 return -EINVAL;
1576
1577 *ret = (size_t) mtu;
1578 return 0;
1579}
2679aee4 1580
9a603dc2 1581static int connect_unix_path_simple(int fd, const char *path) {
2679aee4
LP
1582 union sockaddr_union sa = {
1583 .un.sun_family = AF_UNIX,
1584 };
9a603dc2 1585 size_t l;
2679aee4
LP
1586
1587 assert(fd >= 0);
2679aee4
LP
1588 assert(path);
1589
9a603dc2
LP
1590 l = strlen(path);
1591 assert(l > 0);
1592 assert(l < sizeof(sa.un.sun_path));
1593
1594 memcpy(sa.un.sun_path, path, l + 1);
1595 return RET_NERRNO(connect(fd, &sa.sa, offsetof(struct sockaddr_un, sun_path) + l + 1));
1596}
1597
1598static int connect_unix_inode(int fd, int inode_fd) {
1599 assert(fd >= 0);
1600 assert(inode_fd >= 0);
1601
1602 return connect_unix_path_simple(fd, FORMAT_PROC_FD_PATH(inode_fd));
1603}
1604
1605int connect_unix_path(int fd, int dir_fd, const char *path) {
1606 _cleanup_close_ int inode_fd = -EBADF;
1607
1608 assert(fd >= 0);
1609 assert(dir_fd == AT_FDCWD || dir_fd >= 0);
1610
2679aee4
LP
1611 /* Connects to the specified AF_UNIX socket in the file system. Works around the 108 byte size limit
1612 * in sockaddr_un, by going via O_PATH if needed. This hence works for any kind of path. */
1613
9a603dc2
LP
1614 if (!path)
1615 return connect_unix_inode(fd, dir_fd); /* If no path is specified, then dir_fd refers to the socket inode to connect to. */
2679aee4
LP
1616
1617 /* Refuse zero length path early, to make sure AF_UNIX stack won't mistake this for an abstract
1618 * namespace path, since first char is NUL */
9a603dc2 1619 if (isempty(path))
2679aee4
LP
1620 return -EINVAL;
1621
9a603dc2
LP
1622 /* Shortcut for the simple case */
1623 if (dir_fd == AT_FDCWD && strlen(path) < sizeof_field(struct sockaddr_un, sun_path))
1624 return connect_unix_path_simple(fd, path);
2679aee4 1625
9a603dc2
LP
1626 /* If dir_fd is specified, then we need to go the indirect O_PATH route, because connectat() does not
1627 * exist. If the path is too long, we also need to take the indirect route, since we can't fit this
1628 * into a sockaddr_un directly. */
2679aee4 1629
9a603dc2
LP
1630 inode_fd = openat(dir_fd, path, O_PATH|O_CLOEXEC);
1631 if (inode_fd < 0)
1632 return -errno;
2679aee4 1633
9a603dc2 1634 return connect_unix_inode(fd, inode_fd);
2679aee4 1635}
747b5d96
LB
1636
1637int socket_address_parse_unix(SocketAddress *ret_address, const char *s) {
1638 struct sockaddr_un un;
1639 int r;
1640
1641 assert(ret_address);
1642 assert(s);
1643
1644 if (!IN_SET(*s, '/', '@'))
1645 return -EPROTO;
1646
1647 r = sockaddr_un_set_path(&un, s);
1648 if (r < 0)
1649 return r;
1650
1651 *ret_address = (SocketAddress) {
1652 .sockaddr.un = un,
1653 .size = r,
1654 };
1655
1656 return 0;
1657}
1658
1659int socket_address_parse_vsock(SocketAddress *ret_address, const char *s) {
1660 /* AF_VSOCK socket in vsock:cid:port notation */
1661 _cleanup_free_ char *n = NULL;
1662 char *e, *cid_start;
1663 unsigned port, cid;
c31984e3 1664 int type, r;
747b5d96
LB
1665
1666 assert(ret_address);
1667 assert(s);
1668
c31984e3
DDM
1669 if ((cid_start = startswith(s, "vsock:")))
1670 type = 0;
1671 else if ((cid_start = startswith(s, "vsock-dgram:")))
1672 type = SOCK_DGRAM;
1673 else if ((cid_start = startswith(s, "vsock-seqpacket:")))
1674 type = SOCK_SEQPACKET;
1675 else if ((cid_start = startswith(s, "vsock-stream:")))
1676 type = SOCK_STREAM;
1677 else
747b5d96
LB
1678 return -EPROTO;
1679
1680 e = strchr(cid_start, ':');
1681 if (!e)
1682 return -EINVAL;
1683
1684 r = safe_atou(e+1, &port);
1685 if (r < 0)
1686 return r;
1687
1688 n = strndup(cid_start, e - cid_start);
1689 if (!n)
1690 return -ENOMEM;
1691
1692 if (isempty(n))
1693 cid = VMADDR_CID_ANY;
1694 else {
1695 r = safe_atou(n, &cid);
1696 if (r < 0)
1697 return r;
1698 }
1699
1700 *ret_address = (SocketAddress) {
1701 .sockaddr.vm = {
1702 .svm_cid = cid,
1703 .svm_family = AF_VSOCK,
1704 .svm_port = port,
1705 },
c31984e3 1706 .type = type,
747b5d96
LB
1707 .size = sizeof(struct sockaddr_vm),
1708 };
1709
1710 return 0;
1711}