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