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