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