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