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