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