• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

systemd / systemd / 14766779411

30 Apr 2025 04:55PM UTC coverage: 72.225% (-0.06%) from 72.282%
14766779411

push

github

web-flow
wait-online: handle varlink connection errors while waiting for DNS (#37283)

Currently, if systemd-networkd-wait-online is started with --dns, and
systemd-resolved is not running, it will exit with an error right away.
Similarly, if systemd-resolved is restarted while waiting for DNS
configuration, systemd-networkd-wait-online will not attempt to
re-connect, and will potentially never see subsequent DNS
configurations.

Improve this by adding socket units for the systemd-resolved varlink
servers, and re-establish the connection in systemd-networkd-wait-online
when we receive `SD_VARLINK_ERROR_DISCONNECTED`.

8 of 16 new or added lines in 2 files covered. (50.0%)

5825 existing lines in 217 files now uncovered.

297168 of 411450 relevant lines covered (72.22%)

695892.62 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

84.07
/src/basic/socket-util.c
1
/* SPDX-License-Identifier: LGPL-2.1-or-later */
2

3
#include <arpa/inet.h>
4
#include <errno.h>
5
#include <limits.h>
6
#include <linux/if.h>
7
#include <net/if.h>
8
#include <netdb.h>
9
#include <netinet/ip.h>
10
#include <poll.h>
11
#include <stddef.h>
12
#include <stdint.h>
13
#include <stdio.h>
14
#include <stdlib.h>
15
#include <sys/ioctl.h>
16
#include <unistd.h>
17

18
#include "alloc-util.h"
19
#include "errno-util.h"
20
#include "escape.h"
21
#include "fd-util.h"
22
#include "fileio.h"
23
#include "format-ifname.h"
24
#include "io-util.h"
25
#include "log.h"
26
#include "memory-util.h"
27
#include "parse-util.h"
28
#include "path-util.h"
29
#include "process-util.h"
30
#include "random-util.h"
31
#include "socket-util.h"
32
#include "string-table.h"
33
#include "string-util.h"
34
#include "strv.h"
35
#include "sysctl-util.h"
36
#include "user-util.h"
37
#include "utf8.h"
38

39
#if ENABLE_IDN
40
#  define IDN_FLAGS NI_IDN
41
#else
42
#  define IDN_FLAGS 0
43
#endif
44

45
/* From the kernel's include/net/scm.h */
46
#ifndef SCM_MAX_FD
47
#  define SCM_MAX_FD 253
48
#endif
49

50
static const char* const socket_address_type_table[] = {
51
        [SOCK_STREAM] =    "Stream",
52
        [SOCK_DGRAM] =     "Datagram",
53
        [SOCK_RAW] =       "Raw",
54
        [SOCK_RDM] =       "ReliableDatagram",
55
        [SOCK_SEQPACKET] = "SequentialPacket",
56
        [SOCK_DCCP] =      "DatagramCongestionControl",
57
};
58

UNCOV
59
DEFINE_STRING_TABLE_LOOKUP(socket_address_type, int);
×
60

61
int socket_address_verify(const SocketAddress *a, bool strict) {
8,063✔
62
        assert(a);
8,063✔
63

64
        /* With 'strict' we enforce additional sanity constraints which are not set by the standard,
65
         * but should only apply to sockets we create ourselves. */
66

67
        switch (socket_address_family(a)) {
8,063✔
68

69
        case AF_INET:
25✔
70
                if (a->size != sizeof(struct sockaddr_in))
25✔
71
                        return -EINVAL;
72

73
                if (a->sockaddr.in.sin_port == 0)
25✔
74
                        return -EINVAL;
75

76
                if (!IN_SET(a->type, 0, SOCK_STREAM, SOCK_DGRAM))
25✔
77
                        return -EINVAL;
1✔
78

79
                return 0;
80

81
        case AF_INET6:
16✔
82
                if (a->size != sizeof(struct sockaddr_in6))
16✔
83
                        return -EINVAL;
84

85
                if (a->sockaddr.in6.sin6_port == 0)
16✔
86
                        return -EINVAL;
87

88
                if (!IN_SET(a->type, 0, SOCK_STREAM, SOCK_DGRAM))
16✔
UNCOV
89
                        return -EINVAL;
×
90

91
                return 0;
92

93
        case AF_UNIX:
7,588✔
94
                if (a->size < offsetof(struct sockaddr_un, sun_path))
7,588✔
95
                        return -EINVAL;
96
                if (a->size > sizeof(struct sockaddr_un) + !strict)
7,588✔
97
                        /* If !strict, allow one extra byte, since getsockname() on Linux will append
98
                         * a NUL byte if we have path sockets that are above sun_path's full size. */
99
                        return -EINVAL;
100

101
                if (a->size > offsetof(struct sockaddr_un, sun_path) &&
7,588✔
102
                    a->sockaddr.un.sun_path[0] != 0 &&
7,588✔
103
                    strict) {
104
                        /* Only validate file system sockets here, and only in strict mode */
105
                        const char *e;
2,282✔
106

107
                        e = memchr(a->sockaddr.un.sun_path, 0, sizeof(a->sockaddr.un.sun_path));
2,282✔
108
                        if (e) {
2,282✔
109
                                /* If there's an embedded NUL byte, make sure the size of the socket address matches it */
110
                                if (a->size != offsetof(struct sockaddr_un, sun_path) + (e - a->sockaddr.un.sun_path) + 1)
2,282✔
111
                                        return -EINVAL;
112
                        } else {
113
                                /* If there's no embedded NUL byte, then the size needs to match the whole
114
                                 * structure or the structure with one extra NUL byte suffixed. (Yeah, Linux is awful,
115
                                 * and considers both equivalent: getsockname() even extends sockaddr_un beyond its
116
                                 * size if the path is non NUL terminated.) */
UNCOV
117
                                if (!IN_SET(a->size, sizeof(a->sockaddr.un.sun_path), sizeof(a->sockaddr.un.sun_path)+1))
×
118
                                        return -EINVAL;
119
                        }
120
                }
121

122
                if (!IN_SET(a->type, 0, SOCK_STREAM, SOCK_DGRAM, SOCK_SEQPACKET))
7,588✔
UNCOV
123
                        return -EINVAL;
×
124

125
                return 0;
126

127
        case AF_NETLINK:
349✔
128

129
                if (a->size != sizeof(struct sockaddr_nl))
349✔
130
                        return -EINVAL;
131

132
                if (!IN_SET(a->type, 0, SOCK_RAW, SOCK_DGRAM))
349✔
UNCOV
133
                        return -EINVAL;
×
134

135
                return 0;
136

137
        case AF_VSOCK:
68✔
138
                if (a->size != sizeof(struct sockaddr_vm))
68✔
139
                        return -EINVAL;
140

141
                if (!IN_SET(a->type, 0, SOCK_STREAM, SOCK_DGRAM))
68✔
UNCOV
142
                        return -EINVAL;
×
143

144
                return 0;
145

146
        default:
147
                return -EAFNOSUPPORT;
148
        }
149
}
150

151
int socket_address_print(const SocketAddress *a, char **ret) {
1,679✔
152
        int r;
1,679✔
153

154
        assert(a);
1,679✔
155
        assert(ret);
1,679✔
156

157
        r = socket_address_verify(a, false); /* We do non-strict validation, because we want to be
1,679✔
158
                                              * able to pretty-print any socket the kernel considers
159
                                              * valid. We still need to do validation to know if we
160
                                              * can meaningfully print the address. */
161
        if (r < 0)
1,679✔
162
                return r;
163

164
        if (socket_address_family(a) == AF_NETLINK) {
1,679✔
165
                _cleanup_free_ char *sfamily = NULL;
115✔
166

167
                r = netlink_family_to_string_alloc(a->protocol, &sfamily);
115✔
168
                if (r < 0)
115✔
169
                        return r;
170

171
                r = asprintf(ret, "%s %u", sfamily, a->sockaddr.nl.nl_groups);
115✔
172
                if (r < 0)
115✔
173
                        return -ENOMEM;
174

175
                return 0;
115✔
176
        }
177

178
        return sockaddr_pretty(&a->sockaddr.sa, a->size, false, true, ret);
1,564✔
179
}
180

181
bool socket_address_can_accept(const SocketAddress *a) {
4,753✔
182
        assert(a);
4,753✔
183

184
        return
4,753✔
185
                IN_SET(a->type, SOCK_STREAM, SOCK_SEQPACKET);
4,753✔
186
}
187

188
bool socket_address_equal(const SocketAddress *a, const SocketAddress *b) {
2,003✔
189
        assert(a);
2,003✔
190
        assert(b);
2,003✔
191

192
        /* Invalid addresses are unequal to all */
193
        if (socket_address_verify(a, false) < 0 ||
4,006✔
194
            socket_address_verify(b, false) < 0)
2,003✔
195
                return false;
196

197
        if (a->type != b->type)
2,002✔
198
                return false;
199

200
        if (socket_address_family(a) != socket_address_family(b))
2,001✔
201
                return false;
202

203
        switch (socket_address_family(a)) {
1,999✔
204

205
        case AF_INET:
6✔
206
                if (a->sockaddr.in.sin_addr.s_addr != b->sockaddr.in.sin_addr.s_addr)
6✔
207
                        return false;
208

209
                if (a->sockaddr.in.sin_port != b->sockaddr.in.sin_port)
5✔
210
                        return false;
1✔
211

212
                break;
213

214
        case AF_INET6:
2✔
215
                if (memcmp(&a->sockaddr.in6.sin6_addr, &b->sockaddr.in6.sin6_addr, sizeof(a->sockaddr.in6.sin6_addr)) != 0)
2✔
216
                        return false;
217

218
                if (a->sockaddr.in6.sin6_port != b->sockaddr.in6.sin6_port)
2✔
UNCOV
219
                        return false;
×
220

221
                break;
222

223
        case AF_UNIX:
1,885✔
224
                if (a->size <= offsetof(struct sockaddr_un, sun_path) ||
1,885✔
225
                    b->size <= offsetof(struct sockaddr_un, sun_path))
1,885✔
226
                        return false;
227

228
                if ((a->sockaddr.un.sun_path[0] == 0) != (b->sockaddr.un.sun_path[0] == 0))
1,885✔
229
                        return false;
230

231
                if (a->sockaddr.un.sun_path[0]) {
1,620✔
232
                        if (!path_equal_or_inode_same(a->sockaddr.un.sun_path, b->sockaddr.un.sun_path, 0))
1,618✔
233
                                return false;
443✔
234
                } else {
235
                        if (a->size != b->size)
2✔
236
                                return false;
237

238
                        if (memcmp(a->sockaddr.un.sun_path, b->sockaddr.un.sun_path, a->size) != 0)
2✔
UNCOV
239
                                return false;
×
240
                }
241

242
                break;
243

244
        case AF_NETLINK:
87✔
245
                if (a->protocol != b->protocol)
87✔
246
                        return false;
247

248
                if (a->sockaddr.nl.nl_groups != b->sockaddr.nl.nl_groups)
87✔
249
                        return false;
1✔
250

251
                break;
252

253
        case AF_VSOCK:
19✔
254
                if (a->sockaddr.vm.svm_cid != b->sockaddr.vm.svm_cid)
19✔
255
                        return false;
256

257
                if (a->sockaddr.vm.svm_port != b->sockaddr.vm.svm_port)
18✔
258
                        return false;
1✔
259

260
                break;
261

262
        default:
263
                /* Cannot compare, so we assume the addresses are different */
264
                return false;
265
        }
266

267
        return true;
268
}
269

270
const char* socket_address_get_path(const SocketAddress *a) {
10,601✔
271
        assert(a);
10,601✔
272

273
        if (socket_address_family(a) != AF_UNIX)
10,601✔
274
                return NULL;
275

276
        if (a->sockaddr.un.sun_path[0] == 0)
10,115✔
277
                return NULL;
278

279
        /* Note that this is only safe because we know that there's an extra NUL byte after the sockaddr_un
280
         * structure. On Linux AF_UNIX file system socket addresses don't have to be NUL terminated if they take up the
281
         * full sun_path space. */
282
        assert_cc(sizeof(union sockaddr_union) >= sizeof(struct sockaddr_un)+1);
10,114✔
283
        return a->sockaddr.un.sun_path;
10,114✔
284
}
285

286
bool socket_ipv6_is_supported(void) {
141,163✔
287
        static int cached = -1;
141,163✔
288

289
        if (cached < 0) {
141,163✔
290

291
                if (access("/proc/net/if_inet6", F_OK) < 0) {
1,132✔
292

UNCOV
293
                        if (errno != ENOENT) {
×
294
                                log_debug_errno(errno, "Unexpected error when checking whether /proc/net/if_inet6 exists: %m");
×
295
                                return false;
×
296
                        }
297

UNCOV
298
                        cached = false;
×
299
                } else
300
                        cached = true;
1,132✔
301
        }
302

303
        return cached;
141,163✔
304
}
305

306
bool socket_ipv6_is_enabled(void) {
101,979✔
307
        _cleanup_free_ char *v = NULL;
101,979✔
308
        int r;
101,979✔
309

310
        /* Much like socket_ipv6_is_supported(), but also checks that the sysctl that disables IPv6 on all
311
         * interfaces isn't turned on */
312

313
        if (!socket_ipv6_is_supported())
101,979✔
314
                return false;
315

316
        r = sysctl_read_ip_property(AF_INET6, "all", "disable_ipv6", &v);
101,979✔
317
        if (r < 0) {
101,979✔
UNCOV
318
                log_debug_errno(r, "Unexpected error reading 'net.ipv6.conf.all.disable_ipv6' sysctl: %m");
×
319
                return true;
×
320
        }
321

322
        r = parse_boolean(v);
101,979✔
323
        if (r < 0) {
101,979✔
UNCOV
324
                log_debug_errno(r, "Failed to pare 'net.ipv6.conf.all.disable_ipv6' sysctl: %m");
×
325
                return true;
×
326
        }
327

328
        return !r;
101,979✔
329
}
330

331
bool socket_address_matches_fd(const SocketAddress *a, int fd) {
952✔
332
        SocketAddress b;
952✔
333
        socklen_t solen;
952✔
334

335
        assert(a);
952✔
336
        assert(fd >= 0);
952✔
337

338
        b.size = sizeof(b.sockaddr);
952✔
339
        if (getsockname(fd, &b.sockaddr.sa, &b.size) < 0)
952✔
340
                return false;
952✔
341

342
        if (b.sockaddr.sa.sa_family != a->sockaddr.sa.sa_family)
952✔
343
                return false;
344

345
        solen = sizeof(b.type);
835✔
346
        if (getsockopt(fd, SOL_SOCKET, SO_TYPE, &b.type, &solen) < 0)
835✔
347
                return false;
348

349
        if (b.type != a->type)
835✔
350
                return false;
351

352
        if (a->protocol != 0)  {
708✔
UNCOV
353
                solen = sizeof(b.protocol);
×
354
                if (getsockopt(fd, SOL_SOCKET, SO_PROTOCOL, &b.protocol, &solen) < 0)
×
355
                        return false;
356

UNCOV
357
                if (b.protocol != a->protocol)
×
358
                        return false;
359
        }
360

361
        return socket_address_equal(a, &b);
708✔
362
}
363

UNCOV
364
int sockaddr_port(const struct sockaddr *_sa, unsigned *ret_port) {
×
365
        const union sockaddr_union *sa = (const union sockaddr_union*) _sa;
×
366

367
        /* Note, this returns the port as 'unsigned' rather than 'uint16_t', as AF_VSOCK knows larger ports */
368

UNCOV
369
        assert(sa);
×
370

UNCOV
371
        switch (sa->sa.sa_family) {
×
372

UNCOV
373
        case AF_INET:
×
374
                *ret_port = be16toh(sa->in.sin_port);
×
375
                return 0;
×
376

UNCOV
377
        case AF_INET6:
×
378
                *ret_port = be16toh(sa->in6.sin6_port);
×
379
                return 0;
×
380

UNCOV
381
        case AF_VSOCK:
×
382
                *ret_port = sa->vm.svm_port;
×
383
                return 0;
×
384

385
        default:
386
                return -EAFNOSUPPORT;
387
        }
388
}
389

390
const union in_addr_union *sockaddr_in_addr(const struct sockaddr *_sa) {
396✔
391
        const union sockaddr_union *sa = (const union sockaddr_union*) _sa;
396✔
392

393
        if (!sa)
396✔
394
                return NULL;
395

396
        switch (sa->sa.sa_family) {
396✔
397

398
        case AF_INET:
299✔
399
                return (const union in_addr_union*) &sa->in.sin_addr;
299✔
400

401
        case AF_INET6:
97✔
402
                return (const union in_addr_union*) &sa->in6.sin6_addr;
97✔
403

404
        default:
405
                return NULL;
406
        }
407
}
408

409
int sockaddr_set_in_addr(
692✔
410
                union sockaddr_union *u,
411
                int family,
412
                const union in_addr_union *a,
413
                uint16_t port) {
414

415
        assert(u);
692✔
416
        assert(a);
692✔
417

418
        switch (family) {
692✔
419

420
        case AF_INET:
689✔
421
                u->in = (struct sockaddr_in) {
689✔
422
                        .sin_family = AF_INET,
423
                        .sin_addr = a->in,
689✔
424
                        .sin_port = htobe16(port),
689✔
425
                };
426

427
                return 0;
689✔
428

429
        case AF_INET6:
3✔
430
                u->in6 = (struct sockaddr_in6) {
3✔
431
                        .sin6_family = AF_INET6,
432
                        .sin6_addr = a->in6,
3✔
433
                        .sin6_port = htobe16(port),
3✔
434
                };
435

436
                return 0;
3✔
437

438
        default:
439
                return -EAFNOSUPPORT;
440

441
        }
442
}
443

444
int sockaddr_pretty(
9,440✔
445
                const struct sockaddr *_sa,
446
                socklen_t salen,
447
                bool translate_ipv6,
448
                bool include_port,
449
                char **ret) {
450

451
        union sockaddr_union *sa = (union sockaddr_union*) _sa;
9,440✔
452
        char *p;
9,440✔
453
        int r;
9,440✔
454

455
        assert(sa);
9,440✔
456
        assert(salen >= sizeof(sa->sa.sa_family));
9,440✔
457
        assert(ret);
9,440✔
458

459
        switch (sa->sa.sa_family) {
9,440✔
460

461
        case AF_INET: {
80✔
462
                uint32_t a;
80✔
463

464
                a = be32toh(sa->in.sin_addr.s_addr);
80✔
465

466
                if (include_port)
80✔
467
                        r = asprintf(&p,
80✔
468
                                     "%u.%u.%u.%u:%u",
469
                                     a >> 24, (a >> 16) & 0xFF, (a >> 8) & 0xFF, a & 0xFF,
470
                                     be16toh(sa->in.sin_port));
80✔
471
                else
UNCOV
472
                        r = asprintf(&p,
×
473
                                     "%u.%u.%u.%u",
474
                                     a >> 24, (a >> 16) & 0xFF, (a >> 8) & 0xFF, a & 0xFF);
475
                if (r < 0)
80✔
476
                        return -ENOMEM;
9,440✔
477
                break;
478
        }
479

480
        case AF_INET6: {
18✔
481
                static const unsigned char ipv4_prefix[] = {
18✔
482
                        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xFF, 0xFF
483
                };
484

485
                if (translate_ipv6 &&
18✔
486
                    memcmp(&sa->in6.sin6_addr, ipv4_prefix, sizeof(ipv4_prefix)) == 0) {
10✔
UNCOV
487
                        const uint8_t *a = sa->in6.sin6_addr.s6_addr+12;
×
488
                        if (include_port)
×
489
                                r = asprintf(&p,
×
490
                                             "%u.%u.%u.%u:%u",
UNCOV
491
                                             a[0], a[1], a[2], a[3],
×
492
                                             be16toh(sa->in6.sin6_port));
×
493
                        else
UNCOV
494
                                r = asprintf(&p,
×
495
                                             "%u.%u.%u.%u",
UNCOV
496
                                             a[0], a[1], a[2], a[3]);
×
497
                        if (r < 0)
×
498
                                return -ENOMEM;
499
                } else {
500
                        const char *a = IN6_ADDR_TO_STRING(&sa->in6.sin6_addr);
18✔
501

502
                        if (include_port) {
18✔
503
                                if (asprintf(&p,
16✔
504
                                             "[%s]:%u%s%s",
505
                                             a,
506
                                             be16toh(sa->in6.sin6_port),
16✔
507
                                             sa->in6.sin6_scope_id != 0 ? "%" : "",
16✔
508
                                             FORMAT_IFNAME_FULL(sa->in6.sin6_scope_id, FORMAT_IFNAME_IFINDEX)) < 0)
16✔
UNCOV
509
                                        return -ENOMEM;
×
510
                        } else {
511
                                if (sa->in6.sin6_scope_id != 0)
2✔
UNCOV
512
                                        p = strjoin(a, "%", FORMAT_IFNAME_FULL(sa->in6.sin6_scope_id, FORMAT_IFNAME_IFINDEX));
×
513
                                else
514
                                        p = strdup(a);
2✔
515
                                if (!p)
2✔
516
                                        return -ENOMEM;
517
                        }
518
                }
519

520
                break;
521
        }
522

523
        case AF_UNIX:
9,320✔
524
                if (salen <= offsetof(struct sockaddr_un, sun_path) ||
9,320✔
525
                    (sa->un.sun_path[0] == 0 && salen == offsetof(struct sockaddr_un, sun_path) + 1))
9,318✔
526
                        /* The name must have at least one character (and the leading NUL does not count) */
527
                        p = strdup("<unnamed>");
4✔
528
                else {
529
                        /* Note that we calculate the path pointer here through the .un_buffer[] field, in order to
530
                         * outtrick bounds checking tools such as ubsan, which are too smart for their own good: on
531
                         * Linux the kernel may return sun_path[] data one byte longer than the declared size of the
532
                         * field. */
533
                        char *path = (char*) sa->un_buffer + offsetof(struct sockaddr_un, sun_path);
9,316✔
534
                        size_t path_len = salen - offsetof(struct sockaddr_un, sun_path);
9,316✔
535

536
                        if (path[0] == 0) {
9,316✔
537
                                /* Abstract socket. When parsing address information from, we
538
                                 * explicitly reject overly long paths and paths with embedded NULs.
539
                                 * But we might get such a socket from the outside. Let's return
540
                                 * something meaningful and printable in this case. */
541

542
                                _cleanup_free_ char *e = NULL;
8✔
543

544
                                e = cescape_length(path + 1, path_len - 1);
8✔
545
                                if (!e)
8✔
UNCOV
546
                                        return -ENOMEM;
×
547

548
                                p = strjoin("@", e);
8✔
549
                        } else {
550
                                if (path[path_len - 1] == '\0')
9,308✔
551
                                        /* We expect a terminating NUL and don't print it */
552
                                        path_len--;
9,307✔
553

554
                                p = cescape_length(path, path_len);
9,308✔
555
                        }
556
                }
557
                if (!p)
9,320✔
558
                        return -ENOMEM;
559

560
                break;
561

562
        case AF_VSOCK:
22✔
563
                if (include_port) {
22✔
564
                        if (sa->vm.svm_cid == VMADDR_CID_ANY)
22✔
565
                                r = asprintf(&p, "vsock::%u", sa->vm.svm_port);
19✔
566
                        else
567
                                r = asprintf(&p, "vsock:%u:%u", sa->vm.svm_cid, sa->vm.svm_port);
3✔
568
                } else
UNCOV
569
                        r = asprintf(&p, "vsock:%u", sa->vm.svm_cid);
×
570
                if (r < 0)
22✔
571
                        return -ENOMEM;
572
                break;
573

574
        default:
575
                return -EOPNOTSUPP;
576
        }
577

578
        *ret = p;
9,440✔
579
        return 0;
9,440✔
580
}
581

582
int getpeername_pretty(int fd, bool include_port, char **ret) {
4✔
583
        union sockaddr_union sa;
4✔
584
        socklen_t salen = sizeof(sa);
4✔
585
        int r;
4✔
586

587
        assert(fd >= 0);
4✔
588
        assert(ret);
4✔
589

590
        if (getpeername(fd, &sa.sa, &salen) < 0)
4✔
UNCOV
591
                return -errno;
×
592

593
        if (sa.sa.sa_family == AF_UNIX) {
4✔
594
                struct ucred ucred = UCRED_INVALID;
2✔
595

596
                /* UNIX connection sockets are anonymous, so let's use
597
                 * PID/UID as pretty credentials instead */
598

599
                r = getpeercred(fd, &ucred);
2✔
600
                if (r < 0)
2✔
601
                        return r;
2✔
602

603
                if (asprintf(ret, "PID "PID_FMT"/UID "UID_FMT, ucred.pid, ucred.uid) < 0)
2✔
604
                        return -ENOMEM;
605

606
                return 0;
2✔
607
        }
608

609
        /* For remote sockets we translate IPv6 addresses back to IPv4
610
         * if applicable, since that's nicer. */
611

612
        return sockaddr_pretty(&sa.sa, salen, true, include_port, ret);
2✔
613
}
614

615
int getsockname_pretty(int fd, char **ret) {
1✔
616
        union sockaddr_union sa;
1✔
617
        socklen_t salen = sizeof(sa);
1✔
618

619
        assert(fd >= 0);
1✔
620
        assert(ret);
1✔
621

622
        if (getsockname(fd, &sa.sa, &salen) < 0)
1✔
UNCOV
623
                return -errno;
×
624

625
        /* For local sockets we do not translate IPv6 addresses back
626
         * to IPv6 if applicable, since this is usually used for
627
         * listening sockets where the difference between IPv4 and
628
         * IPv6 matters. */
629

630
        return sockaddr_pretty(&sa.sa, salen, false, true, ret);
1✔
631
}
632

UNCOV
633
int socknameinfo_pretty(const struct sockaddr *sa, socklen_t salen, char **ret) {
×
634
        char host[NI_MAXHOST];
×
635
        int r;
×
636

UNCOV
637
        assert(sa);
×
638
        assert(salen >= sizeof(sa_family_t));
×
639
        assert(ret);
×
640

UNCOV
641
        r = getnameinfo(sa, salen, host, sizeof(host), /* service= */ NULL, /* service_len= */ 0, IDN_FLAGS);
×
642
        if (r != 0) {
×
643
                if (r == EAI_MEMORY)
×
644
                        return log_oom_debug();
×
645
                if (r == EAI_SYSTEM)
×
646
                        log_debug_errno(errno, "getnameinfo() failed, ignoring: %m");
×
647
                else
UNCOV
648
                        log_debug("getnameinfo() failed, ignoring: %s", gai_strerror(r));
×
649

UNCOV
650
                return sockaddr_pretty(sa, salen, /* translate_ipv6= */ true, /* include_port= */ true, ret);
×
651
        }
652

UNCOV
653
        return strdup_to(ret, host);
×
654
}
655

656
static const char* const netlink_family_table[] = {
657
        [NETLINK_ROUTE]          = "route",
658
        [NETLINK_FIREWALL]       = "firewall",
659
        [NETLINK_INET_DIAG]      = "inet-diag",
660
        [NETLINK_NFLOG]          = "nflog",
661
        [NETLINK_XFRM]           = "xfrm",
662
        [NETLINK_SELINUX]        = "selinux",
663
        [NETLINK_ISCSI]          = "iscsi",
664
        [NETLINK_AUDIT]          = "audit",
665
        [NETLINK_FIB_LOOKUP]     = "fib-lookup",
666
        [NETLINK_CONNECTOR]      = "connector",
667
        [NETLINK_NETFILTER]      = "netfilter",
668
        [NETLINK_IP6_FW]         = "ip6-fw",
669
        [NETLINK_DNRTMSG]        = "dnrtmsg",
670
        [NETLINK_KOBJECT_UEVENT] = "kobject-uevent",
671
        [NETLINK_GENERIC]        = "generic",
672
        [NETLINK_SCSITRANSPORT]  = "scsitransport",
673
        [NETLINK_ECRYPTFS]       = "ecryptfs",
674
        [NETLINK_RDMA]           = "rdma",
675
};
676

677
DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(netlink_family, int, INT_MAX);
540✔
678

679
static const char* const socket_address_bind_ipv6_only_table[_SOCKET_ADDRESS_BIND_IPV6_ONLY_MAX] = {
680
        [SOCKET_ADDRESS_DEFAULT] = "default",
681
        [SOCKET_ADDRESS_BOTH] = "both",
682
        [SOCKET_ADDRESS_IPV6_ONLY] = "ipv6-only"
683
};
684

685
DEFINE_STRING_TABLE_LOOKUP(socket_address_bind_ipv6_only, SocketAddressBindIPv6Only);
160✔
686

UNCOV
687
SocketAddressBindIPv6Only socket_address_bind_ipv6_only_or_bool_from_string(const char *n) {
×
688
        int r;
×
689

UNCOV
690
        r = parse_boolean(n);
×
691
        if (r > 0)
×
692
                return SOCKET_ADDRESS_IPV6_ONLY;
UNCOV
693
        if (r == 0)
×
694
                return SOCKET_ADDRESS_BOTH;
695

UNCOV
696
        return socket_address_bind_ipv6_only_from_string(n);
×
697
}
698

699
bool sockaddr_equal(const union sockaddr_union *a, const union sockaddr_union *b) {
7✔
700
        assert(a);
7✔
701
        assert(b);
7✔
702

703
        if (a->sa.sa_family != b->sa.sa_family)
7✔
704
                return false;
705

706
        if (a->sa.sa_family == AF_INET)
6✔
707
                return a->in.sin_addr.s_addr == b->in.sin_addr.s_addr;
4✔
708

709
        if (a->sa.sa_family == AF_INET6)
2✔
710
                return memcmp(&a->in6.sin6_addr, &b->in6.sin6_addr, sizeof(a->in6.sin6_addr)) == 0;
1✔
711

712
        if (a->sa.sa_family == AF_VSOCK)
1✔
713
                return a->vm.svm_cid == b->vm.svm_cid;
1✔
714

715
        return false;
716
}
717

718
int fd_set_sndbuf(int fd, size_t n, bool increase) {
402,540✔
719
        int r, value;
402,540✔
720
        socklen_t l = sizeof(value);
402,540✔
721

722
        if (n > INT_MAX)
402,540✔
723
                return -ERANGE;
402,540✔
724

725
        r = getsockopt(fd, SOL_SOCKET, SO_SNDBUF, &value, &l);
402,540✔
726
        if (r >= 0 && l == sizeof(value) && increase ? (size_t) value >= n*2 : (size_t) value == n*2)
402,540✔
727
                return 0;
728

729
        /* First, try to set the buffer size with SO_SNDBUF. */
730
        r = setsockopt_int(fd, SOL_SOCKET, SO_SNDBUF, n);
402,540✔
731
        if (r < 0)
402,540✔
732
                return r;
733

734
        /* SO_SNDBUF above may set to the kernel limit, instead of the requested size.
735
         * So, we need to check the actual buffer size here. */
736
        l = sizeof(value);
402,540✔
737
        r = getsockopt(fd, SOL_SOCKET, SO_SNDBUF, &value, &l);
402,540✔
738
        if (r >= 0 && l == sizeof(value) && increase ? (size_t) value >= n*2 : (size_t) value == n*2)
402,540✔
739
                return 1;
740

741
        /* If we have the privileges we will ignore the kernel limit. */
742
        r = setsockopt_int(fd, SOL_SOCKET, SO_SNDBUFFORCE, n);
402,540✔
743
        if (r < 0)
402,540✔
744
                return r;
33,527✔
745

746
        return 1;
747
}
748

749
int fd_set_rcvbuf(int fd, size_t n, bool increase) {
32,815✔
750
        int r, value;
32,815✔
751
        socklen_t l = sizeof(value);
32,815✔
752

753
        if (n > INT_MAX)
32,815✔
754
                return -ERANGE;
32,815✔
755

756
        r = getsockopt(fd, SOL_SOCKET, SO_RCVBUF, &value, &l);
32,815✔
757
        if (r >= 0 && l == sizeof(value) && increase ? (size_t) value >= n*2 : (size_t) value == n*2)
32,815✔
758
                return 0;
759

760
        /* First, try to set the buffer size with SO_RCVBUF. */
761
        r = setsockopt_int(fd, SOL_SOCKET, SO_RCVBUF, n);
32,814✔
762
        if (r < 0)
32,814✔
763
                return r;
764

765
        /* SO_RCVBUF above may set to the kernel limit, instead of the requested size.
766
         * So, we need to check the actual buffer size here. */
767
        l = sizeof(value);
32,814✔
768
        r = getsockopt(fd, SOL_SOCKET, SO_RCVBUF, &value, &l);
32,814✔
769
        if (r >= 0 && l == sizeof(value) && increase ? (size_t) value >= n*2 : (size_t) value == n*2)
32,814✔
770
                return 1;
771

772
        /* If we have the privileges we will ignore the kernel limit. */
773
        r = setsockopt_int(fd, SOL_SOCKET, SO_RCVBUFFORCE, n);
32,814✔
774
        if (r < 0)
32,814✔
775
                return r;
7,163✔
776

777
        return 1;
778
}
779

780
static const char* const ip_tos_table[] = {
781
        [IPTOS_LOWDELAY]    = "low-delay",
782
        [IPTOS_THROUGHPUT]  = "throughput",
783
        [IPTOS_RELIABILITY] = "reliability",
784
        [IPTOS_LOWCOST]     = "low-cost",
785
};
786

UNCOV
787
DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(ip_tos, int, 0xff);
×
788

789
bool ifname_valid_char(char a) {
445,018✔
790
        if ((unsigned char) a >= 127U)
445,018✔
791
                return false;
792

793
        if ((unsigned char) a <= 32U)
445,018✔
794
                return false;
795

796
        if (IN_SET(a,
445,014✔
797
                   ':',  /* colons are used by the legacy "alias" interface logic */
798
                   '/',  /* slashes cannot work, since we need to use network interfaces in sysfs paths, and in paths slashes are separators */
799
                   '%')) /* %d is used in the kernel's weird foo%d format string naming feature which we really really don't want to ever run into by accident */
800
                return false;
10✔
801

802
        return true;
803
}
804

805
bool ifname_valid_full(const char *p, IfnameValidFlags flags) {
127,987✔
806
        bool numeric = true;
127,987✔
807

808
        /* Checks whether a network interface name is valid. This is inspired by dev_valid_name() in the kernel sources
809
         * but slightly stricter, as we only allow non-control, non-space ASCII characters in the interface name. We
810
         * also don't permit names that only container numbers, to avoid confusion with numeric interface indexes. */
811

812
        assert(!(flags & ~_IFNAME_VALID_ALL));
127,987✔
813

814
        if (isempty(p))
127,987✔
815
                return false;
816

817
        /* A valid ifindex? If so, it's valid iff IFNAME_VALID_NUMERIC is set */
818
        if (parse_ifindex(p) >= 0)
123,604✔
819
                return flags & IFNAME_VALID_NUMERIC;
57✔
820

821
        if (flags & IFNAME_VALID_ALTERNATIVE) {
123,547✔
822
                if (strlen(p) >= ALTIFNAMSIZ)
11,691✔
823
                        return false;
824
        } else {
825
                if (strlen(p) >= IFNAMSIZ)
111,856✔
826
                        return false;
827
        }
828

829
        if (dot_or_dot_dot(p))
123,540✔
830
                return false;
831

832
        /* Let's refuse "all" and "default" as interface name, to avoid collisions with the special sysctl
833
         * directories /proc/sys/net/{ipv4,ipv6}/conf/{all,default} */
834
        if (!FLAGS_SET(flags, IFNAME_VALID_SPECIAL) && STR_IN_SET(p, "all", "default"))
123,538✔
UNCOV
835
                return false;
×
836

837
        for (const char *t = p; *t; t++) {
561,688✔
838
                if (!ifname_valid_char(*t))
438,164✔
839
                        return false;
840

841
                numeric = numeric && ascii_isdigit(*t);
561,678✔
842
        }
843

844
        /* It's fully numeric but didn't parse as valid ifindex above? if so, it must be too large or zero or
845
         * so, let's refuse that. */
846
        if (numeric)
123,524✔
847
                return false;
2✔
848

849
        return true;
850
}
851

852
bool address_label_valid(const char *p) {
44✔
853

854
        if (isempty(p))
44✔
855
                return false;
856

857
        if (strlen(p) >= IFNAMSIZ)
44✔
858
                return false;
859

860
        while (*p) {
376✔
861
                if ((uint8_t) *p >= 127U)
332✔
862
                        return false;
863

864
                if ((uint8_t) *p <= 31U)
332✔
865
                        return false;
866
                p++;
332✔
867
        }
868

869
        return true;
870
}
871

872
int getpeercred(int fd, struct ucred *ucred) {
66,524✔
873
        socklen_t n = sizeof(struct ucred);
66,524✔
874
        struct ucred u;
66,524✔
875

876
        assert(fd >= 0);
66,524✔
877
        assert(ucred);
66,524✔
878

879
        if (getsockopt(fd, SOL_SOCKET, SO_PEERCRED, &u, &n) < 0)
66,524✔
UNCOV
880
                return -errno;
×
881

882
        if (n != sizeof(struct ucred))
66,524✔
883
                return -EIO;
884

885
        /* Check if the data is actually useful and not suppressed due to namespacing issues */
886
        if (!pid_is_valid(u.pid))
66,524✔
887
                return -ENODATA;
888

889
        /* Note that we don't check UID/GID here, as namespace translation works differently there: instead of
890
         * receiving in "invalid" user/group we get the overflow UID/GID. */
891

892
        *ucred = u;
66,524✔
893
        return 0;
66,524✔
894
}
895

896
int getpeersec(int fd, char **ret) {
19,978✔
897
        _cleanup_free_ char *s = NULL;
39,956✔
898
        socklen_t n = 64;
19,978✔
899

900
        assert(fd >= 0);
19,978✔
901
        assert(ret);
19,978✔
902

903
        for (;;) {
19,978✔
904
                s = new0(char, n+1);
19,978✔
905
                if (!s)
19,978✔
906
                        return -ENOMEM;
907

908
                if (getsockopt(fd, SOL_SOCKET, SO_PEERSEC, s, &n) >= 0) {
19,978✔
909
                        s[n] = 0;
7,107✔
910
                        break;
7,107✔
911
                }
912

913
                if (errno != ERANGE)
12,871✔
914
                        return -errno;
12,871✔
915

UNCOV
916
                s = mfree(s);
×
917
        }
918

919
        if (isempty(s))
7,107✔
920
                return -EOPNOTSUPP;
921

922
        *ret = TAKE_PTR(s);
7,107✔
923

924
        return 0;
7,107✔
925
}
926

927
int getpeergroups(int fd, gid_t **ret) {
19,979✔
928
        socklen_t n = sizeof(gid_t) * 64U;
19,979✔
929
        _cleanup_free_ gid_t *d = NULL;
19,979✔
930

931
        assert(fd >= 0);
19,979✔
932
        assert(ret);
19,979✔
933

934
        long ngroups_max = sysconf(_SC_NGROUPS_MAX);
19,979✔
935
        if (ngroups_max > 0)
19,979✔
936
                n = MAX(n, sizeof(gid_t) * (socklen_t) ngroups_max);
19,979✔
937

938
        for (;;) {
19,979✔
939
                d = malloc(n);
19,979✔
940
                if (!d)
19,979✔
941
                        return -ENOMEM;
942

943
                if (getsockopt(fd, SOL_SOCKET, SO_PEERGROUPS, d, &n) >= 0)
19,979✔
944
                        break;
945

UNCOV
946
                if (errno != ERANGE)
×
947
                        return -errno;
×
948

UNCOV
949
                d = mfree(d);
×
950
        }
951

952
        assert_se(n % sizeof(gid_t) == 0);
19,979✔
953
        n /= sizeof(gid_t);
19,979✔
954

955
        if (n > INT_MAX)
19,979✔
956
                return -E2BIG;
957

958
        *ret = TAKE_PTR(d);
19,979✔
959

960
        return (int) n;
19,979✔
961
}
962

963
int getpeerpidfd(int fd) {
20,257✔
964
        socklen_t n = sizeof(int);
20,257✔
965
        int pidfd = -EBADF;
20,257✔
966

967
        assert(fd >= 0);
20,257✔
968

969
        if (getsockopt(fd, SOL_SOCKET, SO_PEERPIDFD, &pidfd, &n) < 0)
20,257✔
970
                return -errno;
2✔
971

972
        if (n != sizeof(int))
20,255✔
973
                return -EIO;
974

975
        return pidfd;
20,255✔
976
}
977

978
int getpeerpidref(int fd, PidRef *ret) {
4✔
979
        int r;
4✔
980

981
        assert(fd >= 0);
4✔
982
        assert(ret);
4✔
983

984
        int pidfd = getpeerpidfd(fd);
4✔
985
        if (pidfd < 0) {
4✔
UNCOV
986
                if (!ERRNO_IS_NEG_NOT_SUPPORTED(pidfd))
×
987
                        return pidfd;
×
988

UNCOV
989
                struct ucred ucred;
×
990
                r = getpeercred(fd, &ucred);
×
991
                if (r < 0)
×
992
                        return r;
993

UNCOV
994
                return pidref_set_pid(ret, ucred.pid);
×
995
        }
996

997
        return pidref_set_pidfd_consume(ret, pidfd);
4✔
998
}
999

1000
ssize_t send_many_fds_iov_sa(
1✔
1001
                int transport_fd,
1002
                int *fds_array, size_t n_fds_array,
1003
                const struct iovec *iov, size_t iovlen,
1004
                const struct sockaddr *sa, socklen_t len,
1005
                int flags) {
1006

1007
        _cleanup_free_ struct cmsghdr *cmsg = NULL;
1✔
1008
        struct msghdr mh = {
1✔
1009
                .msg_name = (struct sockaddr*) sa,
1010
                .msg_namelen = len,
1011
                .msg_iov = (struct iovec *)iov,
1012
                .msg_iovlen = iovlen,
1013
        };
1014
        ssize_t k;
1✔
1015

1016
        assert(transport_fd >= 0);
1✔
1017
        assert(fds_array || n_fds_array == 0);
1✔
1018

1019
        /* The kernel will reject sending more than SCM_MAX_FD FDs at once */
1020
        if (n_fds_array > SCM_MAX_FD)
1✔
1021
                return -E2BIG;
1022

1023
        /* We need either an FD array or data to send. If there's nothing, return an error. */
1024
        if (n_fds_array == 0 && !iov)
1✔
1025
                return -EINVAL;
1026

1027
        if (n_fds_array > 0) {
1✔
1028
                mh.msg_controllen = CMSG_SPACE(sizeof(int) * n_fds_array);
1✔
1029
                mh.msg_control = cmsg = malloc(mh.msg_controllen);
1✔
1030
                if (!cmsg)
1✔
1031
                        return -ENOMEM;
1032

1033
                *cmsg = (struct cmsghdr) {
1✔
1034
                        .cmsg_len = CMSG_LEN(sizeof(int) * n_fds_array),
1✔
1035
                        .cmsg_level = SOL_SOCKET,
1036
                        .cmsg_type = SCM_RIGHTS,
1037
                };
1038
                memcpy(CMSG_DATA(cmsg), fds_array, sizeof(int) * n_fds_array);
1✔
1039
        }
1040
        k = sendmsg(transport_fd, &mh, MSG_NOSIGNAL | flags);
1✔
1041
        if (k < 0)
1✔
UNCOV
1042
                return (ssize_t) -errno;
×
1043

1044
        return k;
1045
}
1046

1047
ssize_t send_one_fd_iov_sa(
741✔
1048
                int transport_fd,
1049
                int fd,
1050
                const struct iovec *iov, size_t iovlen,
1051
                const struct sockaddr *sa, socklen_t len,
1052
                int flags) {
1053

1054
        CMSG_BUFFER_TYPE(CMSG_SPACE(sizeof(int))) control = {};
741✔
1055
        struct msghdr mh = {
741✔
1056
                .msg_name = (struct sockaddr*) sa,
1057
                .msg_namelen = len,
1058
                .msg_iov = (struct iovec *)iov,
1059
                .msg_iovlen = iovlen,
1060
        };
1061
        ssize_t k;
741✔
1062

1063
        assert(transport_fd >= 0);
741✔
1064

1065
        /*
1066
         * We need either an FD or data to send.
1067
         * If there's nothing, return an error.
1068
         */
1069
        if (fd < 0 && !iov)
741✔
1070
                return -EINVAL;
741✔
1071

1072
        if (fd >= 0) {
740✔
1073
                struct cmsghdr *cmsg;
738✔
1074

1075
                mh.msg_control = &control;
738✔
1076
                mh.msg_controllen = sizeof(control);
738✔
1077

1078
                cmsg = CMSG_FIRSTHDR(&mh);
738✔
1079
                cmsg->cmsg_level = SOL_SOCKET;
738✔
1080
                cmsg->cmsg_type = SCM_RIGHTS;
738✔
1081
                cmsg->cmsg_len = CMSG_LEN(sizeof(int));
738✔
1082
                memcpy(CMSG_DATA(cmsg), &fd, sizeof(int));
738✔
1083
        }
1084
        k = sendmsg(transport_fd, &mh, MSG_NOSIGNAL | flags);
740✔
1085
        if (k < 0)
740✔
UNCOV
1086
                return (ssize_t) -errno;
×
1087

1088
        return k;
1089
}
1090

1091
int send_one_fd_sa(
6✔
1092
                int transport_fd,
1093
                int fd,
1094
                const struct sockaddr *sa, socklen_t len,
1095
                int flags) {
1096

1097
        assert(fd >= 0);
6✔
1098

1099
        return (int) send_one_fd_iov_sa(transport_fd, fd, NULL, 0, sa, len, flags);
6✔
1100
}
1101

1102
ssize_t receive_many_fds_iov(
1✔
1103
                int transport_fd,
1104
                struct iovec *iov, size_t iovlen,
1105
                int **ret_fds_array, size_t *ret_n_fds_array,
1106
                int flags) {
1107

1108
        CMSG_BUFFER_TYPE(CMSG_SPACE(sizeof(int) * SCM_MAX_FD)) control;
1✔
1109
        struct msghdr mh = {
1✔
1110
                .msg_control = &control,
1111
                .msg_controllen = sizeof(control),
1112
                .msg_iov = iov,
1113
                .msg_iovlen = iovlen,
1114
        };
1115
        _cleanup_free_ int *fds_array = NULL;
1✔
1116
        size_t n_fds_array = 0;
1✔
1117
        struct cmsghdr *cmsg;
1✔
1118
        ssize_t k;
1✔
1119

1120
        assert(transport_fd >= 0);
1✔
1121
        assert(ret_fds_array);
1✔
1122
        assert(ret_n_fds_array);
1✔
1123

1124
        /*
1125
         * Receive many FDs via @transport_fd. We don't care for the transport-type. We retrieve all the FDs
1126
         * at once. This is best used in combination with send_many_fds().
1127
         */
1128

1129
        k = recvmsg_safe(transport_fd, &mh, MSG_CMSG_CLOEXEC | flags);
1✔
1130
        if (k < 0)
1✔
1131
                return k;
1132

1133
        CMSG_FOREACH(cmsg, &mh)
4✔
1134
                if (cmsg->cmsg_level == SOL_SOCKET && cmsg->cmsg_type == SCM_RIGHTS) {
1✔
1135
                        size_t n = (cmsg->cmsg_len - CMSG_LEN(0)) / sizeof(int);
1✔
1136

1137
                        if (!GREEDY_REALLOC_APPEND(fds_array, n_fds_array, CMSG_TYPED_DATA(cmsg, int), n)) {
1✔
UNCOV
1138
                                cmsg_close_all(&mh);
×
1139
                                return -ENOMEM;
1140
                        }
1141
                }
1142

1143
        if (n_fds_array == 0) {
1✔
UNCOV
1144
                cmsg_close_all(&mh);
×
1145

1146
                /* If didn't receive an FD or any data, return an error. */
UNCOV
1147
                if (k == 0)
×
1148
                        return -EIO;
1149
        }
1150

1151
        *ret_fds_array = TAKE_PTR(fds_array);
1✔
1152
        *ret_n_fds_array = n_fds_array;
1✔
1153

1154
        return k;
1✔
1155
}
1156

UNCOV
1157
int receive_many_fds(int transport_fd, int **ret_fds_array, size_t *ret_n_fds_array, int flags) {
×
1158
        ssize_t k;
×
1159

UNCOV
1160
        k = receive_many_fds_iov(transport_fd, NULL, 0, ret_fds_array, ret_n_fds_array, flags);
×
1161
        if (k == 0)
×
1162
                return 0;
1163

1164
        /* k must be negative, since receive_many_fds_iov() only returns a positive value if data was received
1165
         * through the iov. */
UNCOV
1166
        assert(k < 0);
×
1167
        return (int) k;
×
1168
}
1169

1170
ssize_t receive_one_fd_iov(
5,101✔
1171
                int transport_fd,
1172
                struct iovec *iov, size_t iovlen,
1173
                int flags,
1174
                int *ret_fd) {
1175

1176
        CMSG_BUFFER_TYPE(CMSG_SPACE(sizeof(int))) control;
5,101✔
1177
        struct msghdr mh = {
5,101✔
1178
                .msg_control = &control,
1179
                .msg_controllen = sizeof(control),
1180
                .msg_iov = iov,
1181
                .msg_iovlen = iovlen,
1182
        };
1183
        struct cmsghdr *found;
5,101✔
1184
        ssize_t k;
5,101✔
1185

1186
        assert(transport_fd >= 0);
5,101✔
1187
        assert(ret_fd);
5,101✔
1188

1189
        /*
1190
         * Receive a single FD via @transport_fd. We don't care for
1191
         * the transport-type. We retrieve a single FD at most, so for
1192
         * packet-based transports, the caller must ensure to send
1193
         * only a single FD per packet.  This is best used in
1194
         * combination with send_one_fd().
1195
         */
1196

1197
        k = recvmsg_safe(transport_fd, &mh, MSG_CMSG_CLOEXEC | flags);
5,101✔
1198
        if (k < 0)
5,101✔
1199
                return k;
5,101✔
1200

1201
        found = cmsg_find(&mh, SOL_SOCKET, SCM_RIGHTS, CMSG_LEN(sizeof(int)));
4,920✔
1202
        if (!found) {
4,920✔
1203
                cmsg_close_all(&mh);
1,542✔
1204

1205
                /* If didn't receive an FD or any data, return an error. */
1206
                if (k == 0)
1,542✔
1207
                        return -EIO;
1208
        }
1209

1210
        if (found)
3,379✔
1211
                *ret_fd = *CMSG_TYPED_DATA(found, int);
3,378✔
1212
        else
1213
                *ret_fd = -EBADF;
1✔
1214

1215
        return k;
1216
}
1217

1218
int receive_one_fd(int transport_fd, int flags) {
587✔
1219
        int fd;
587✔
1220
        ssize_t k;
587✔
1221

1222
        k = receive_one_fd_iov(transport_fd, NULL, 0, flags, &fd);
587✔
1223
        if (k == 0)
587✔
1224
                return fd;
519✔
1225

1226
        /* k must be negative, since receive_one_fd_iov() only returns
1227
         * a positive value if data was received through the iov. */
1228
        assert(k < 0);
68✔
1229
        return (int) k;
68✔
1230
}
1231

1232
ssize_t next_datagram_size_fd(int fd) {
205,383✔
1233
        ssize_t l;
205,383✔
1234
        int k;
205,383✔
1235

1236
        /* This is a bit like FIONREAD/SIOCINQ, however a bit more powerful. The difference being: recv(MSG_PEEK) will
1237
         * actually cause the next datagram in the queue to be validated regarding checksums, which FIONREAD doesn't
1238
         * do. This difference is actually of major importance as we need to be sure that the size returned here
1239
         * actually matches what we will read with recvmsg() next, as otherwise we might end up allocating a buffer of
1240
         * the wrong size. */
1241

1242
        l = recv(fd, NULL, 0, MSG_PEEK|MSG_TRUNC);
205,383✔
1243
        if (l < 0) {
205,383✔
1244
                if (IN_SET(errno, EOPNOTSUPP, EFAULT))
546✔
UNCOV
1245
                        goto fallback;
×
1246

1247
                return -errno;
546✔
1248
        }
1249
        if (l == 0)
204,837✔
1250
                goto fallback;
65✔
1251

1252
        return l;
1253

1254
fallback:
65✔
1255
        k = 0;
65✔
1256

1257
        /* Some sockets (AF_PACKET) do not support null-sized recv() with MSG_TRUNC set, let's fall back to FIONREAD
1258
         * for them. Checksums don't matter for raw sockets anyway, hence this should be fine. */
1259

1260
        if (ioctl(fd, FIONREAD, &k) < 0)
65✔
UNCOV
1261
                return -errno;
×
1262

1263
        return (ssize_t) k;
65✔
1264
}
1265

1266
/* Put a limit on how many times will attempt to call accept4(). We loop
1267
 * only on "transient" errors, but let's make sure we don't loop forever. */
1268
#define MAX_FLUSH_ITERATIONS 1024
1269

1270
int flush_accept(int fd) {
13✔
1271

1272
        int r, b;
13✔
1273
        socklen_t l = sizeof(b);
13✔
1274

1275
        /* Similar to flush_fd() but flushes all incoming connections by accepting and immediately closing
1276
         * them. */
1277

1278
        if (getsockopt(fd, SOL_SOCKET, SO_ACCEPTCONN, &b, &l) < 0)
13✔
UNCOV
1279
                return -errno;
×
1280

1281
        assert(l == sizeof(b));
13✔
1282
        if (!b) /* Let's check if this socket accepts connections before calling accept(). accept4() can
13✔
1283
                 * return EOPNOTSUPP if the fd is not a listening socket, which we should treat as a fatal
1284
                 * error, or in case the incoming TCP connection triggered a network issue, which we want to
1285
                 * treat as a transient error. Thus, let's rule out the first reason for EOPNOTSUPP early, so
1286
                 * we can loop safely on transient errors below. */
1287
                return -ENOTTY;
1288

1289
        for (unsigned iteration = 0;; iteration++) {
2✔
1290
                int cfd;
6✔
1291

1292
                r = fd_wait_for_event(fd, POLLIN, 0);
6✔
1293
                if (r < 0) {
6✔
UNCOV
1294
                        if (r == -EINTR)
×
1295
                                continue;
×
1296

1297
                        return r;
1298
                }
1299
                if (r == 0)
6✔
1300
                        return 0;
1301

1302
                if (iteration >= MAX_FLUSH_ITERATIONS)
2✔
UNCOV
1303
                        return log_debug_errno(SYNTHETIC_ERRNO(EBUSY),
×
1304
                                               "Failed to flush connections within " STRINGIFY(MAX_FLUSH_ITERATIONS) " iterations.");
1305

1306
                cfd = accept4(fd, NULL, NULL, SOCK_NONBLOCK|SOCK_CLOEXEC);
2✔
1307
                if (cfd < 0) {
2✔
UNCOV
1308
                        if (errno == EAGAIN)
×
1309
                                return 0;
1310

UNCOV
1311
                        if (ERRNO_IS_ACCEPT_AGAIN(errno))
×
1312
                                continue;
×
1313

UNCOV
1314
                        return -errno;
×
1315
                }
1316

1317
                safe_close(cfd);
2✔
1318
        }
1319
}
1320

1321
struct cmsghdr* cmsg_find(struct msghdr *mh, int level, int type, socklen_t length) {
370,282✔
1322
        struct cmsghdr *cmsg;
370,282✔
1323

1324
        assert(mh);
370,282✔
1325

1326
        CMSG_FOREACH(cmsg, mh)
741,106✔
1327
                if (cmsg->cmsg_level == level &&
349,237✔
1328
                    cmsg->cmsg_type == type &&
348,966✔
1329
                    (length == (socklen_t) -1 || length == cmsg->cmsg_len))
348,525✔
1330
                        return cmsg;
1331

1332
        return NULL;
1333
}
1334

1335
void* cmsg_find_and_copy_data(struct msghdr *mh, int level, int type, void *buf, size_t buf_len) {
305✔
1336
        struct cmsghdr *cmsg;
305✔
1337

1338
        assert(mh);
305✔
1339
        assert(buf);
305✔
1340
        assert(buf_len > 0);
305✔
1341

1342
        /* This is similar to cmsg_find_data(), but copy the found data to buf. This should be typically used
1343
         * when reading possibly unaligned data such as timestamp, as time_t is 64-bit and size_t is 32-bit on
1344
         * RISCV32. See issue #27241. */
1345

1346
        cmsg = cmsg_find(mh, level, type, CMSG_LEN(buf_len));
305✔
1347
        if (!cmsg)
305✔
1348
                return NULL;
1349

1350
        return memcpy_safe(buf, CMSG_DATA(cmsg), buf_len);
300✔
1351
}
1352

1353
int socket_ioctl_fd(void) {
4,286✔
1354
        int fd;
4,286✔
1355

1356
        /* Create a socket to invoke the various network interface ioctl()s on. Traditionally only AF_INET was good for
1357
         * that. Since kernel 4.6 AF_NETLINK works for this too. We first try to use AF_INET hence, but if that's not
1358
         * available (for example, because it is made unavailable via SECCOMP or such), we'll fall back to the more
1359
         * generic AF_NETLINK. */
1360

1361
        fd = socket(AF_INET, SOCK_DGRAM|SOCK_CLOEXEC, 0);
4,286✔
1362
        if (fd < 0)
4,286✔
UNCOV
1363
                fd = socket(AF_NETLINK, SOCK_RAW|SOCK_CLOEXEC, NETLINK_GENERIC);
×
1364
        if (fd < 0)
×
1365
                return -errno;
×
1366

1367
        return fd;
1368
}
1369

1370
int sockaddr_un_unlink(const struct sockaddr_un *sa) {
1,462✔
1371
        const char *p, * nul;
1,462✔
1372

1373
        assert(sa);
1,462✔
1374

1375
        if (sa->sun_family != AF_UNIX)
1,462✔
1376
                return -EPROTOTYPE;
1377

1378
        if (sa->sun_path[0] == 0) /* Nothing to do for abstract sockets */
1,462✔
1379
                return 0;
1380

1381
        /* The path in .sun_path is not necessarily NUL terminated. Let's fix that. */
1382
        nul = memchr(sa->sun_path, 0, sizeof(sa->sun_path));
1,462✔
1383
        if (nul)
1,462✔
1384
                p = sa->sun_path;
1385
        else
UNCOV
1386
                p = memdupa_suffix0(sa->sun_path, sizeof(sa->sun_path));
×
1387

1388
        if (unlink(p) < 0)
1,462✔
1389
                return -errno;
1,323✔
1390

1391
        return 1;
1392
}
1393

1394
int sockaddr_un_set_path(struct sockaddr_un *ret, const char *path) {
369,830✔
1395
        size_t l;
369,830✔
1396

1397
        assert(ret);
369,830✔
1398
        assert(path);
369,830✔
1399

1400
        /* Initialize ret->sun_path from the specified argument. This will interpret paths starting with '@' as
1401
         * abstract namespace sockets, and those starting with '/' as regular filesystem sockets. It won't accept
1402
         * anything else (i.e. no relative paths), to avoid ambiguities. Note that this function cannot be used to
1403
         * reference paths in the abstract namespace that include NUL bytes in the name. */
1404

1405
        l = strlen(path);
369,830✔
1406
        if (l < 2)
369,830✔
1407
                return -EINVAL;
1408
        if (!IN_SET(path[0], '/', '@'))
369,829✔
1409
                return -EINVAL;
1410

1411
        /* Don't allow paths larger than the space in sockaddr_un. Note that we are a tiny bit more restrictive than
1412
         * the kernel is: we insist on NUL termination (both for abstract namespace and regular file system socket
1413
         * addresses!), which the kernel doesn't. We do this to reduce chance of incompatibility with other apps that
1414
         * do not expect non-NUL terminated file system path. */
1415
        if (l+1 > sizeof(ret->sun_path))
369,829✔
1416
                return path[0] == '@' ? -EINVAL : -ENAMETOOLONG; /* return a recognizable error if this is
2✔
1417
                                                                  * too long to fit into a sockaddr_un, but
1418
                                                                  * is a file system path, and thus might be
1419
                                                                  * connectible via O_PATH indirection. */
1420

1421
        *ret = (struct sockaddr_un) {
369,827✔
1422
                .sun_family = AF_UNIX,
1423
        };
1424

1425
        if (path[0] == '@') {
369,827✔
1426
                /* Abstract namespace socket */
1427
                memcpy(ret->sun_path + 1, path + 1, l); /* copy *with* trailing NUL byte */
213,840✔
1428
                return (int) (offsetof(struct sockaddr_un, sun_path) + l); /* 🔥 *don't* 🔥 include trailing NUL in size */
213,840✔
1429

1430
        } else {
1431
                assert(path[0] == '/');
155,987✔
1432

1433
                /* File system socket */
1434
                memcpy(ret->sun_path, path, l + 1); /* copy *with* trailing NUL byte */
155,987✔
1435
                return (int) (offsetof(struct sockaddr_un, sun_path) + l + 1); /* include trailing NUL in size */
155,987✔
1436
        }
1437
}
1438

1439
int socket_bind_to_ifname(int fd, const char *ifname) {
1✔
1440
        assert(fd >= 0);
1✔
1441

1442
        /* Call with NULL to drop binding */
1443

1444
        return RET_NERRNO(setsockopt(fd, SOL_SOCKET, SO_BINDTODEVICE, ifname, strlen_ptr(ifname)));
2✔
1445
}
1446

1447
int socket_bind_to_ifindex(int fd, int ifindex) {
708✔
1448
        assert(fd >= 0);
708✔
1449

1450
        if (ifindex <= 0)
708✔
1451
                /* Drop binding */
1452
                return RET_NERRNO(setsockopt(fd, SOL_SOCKET, SO_BINDTODEVICE, NULL, 0));
54✔
1453

1454
        return setsockopt_int(fd, SOL_SOCKET, SO_BINDTOIFINDEX, ifindex);
654✔
1455
}
1456

1457
int socket_autobind(int fd, char **ret_name) {
240✔
1458
        _cleanup_free_ char *name = NULL;
240✔
1459
        uint64_t random;
240✔
1460
        int r;
240✔
1461

1462
        /* Generate a random abstract socket name and bind fd to it. This is modeled after the kernel
1463
         * "autobind" feature, but uses 64-bit random number internally. */
1464

1465
        assert(fd >= 0);
240✔
1466
        assert(ret_name);
240✔
1467

1468
        random = random_u64();
240✔
1469

1470
        if (asprintf(&name, "@%" PRIu64, random) < 0)
240✔
1471
                return -ENOMEM;
1472

1473
        union sockaddr_union sa;
240✔
1474
        assert_cc(DECIMAL_STR_MAX(uint64_t) < sizeof(sa.un.sun_path));
240✔
1475

1476
        r = sockaddr_un_set_path(&sa.un, name);
240✔
1477
        if (r < 0)
240✔
1478
                return r;
1479

1480
        if (bind(fd, &sa.sa, r) < 0)
240✔
UNCOV
1481
                return -errno;
×
1482

1483
        *ret_name = TAKE_PTR(name);
240✔
1484
        return 0;
240✔
1485
}
1486

1487
ssize_t recvmsg_safe(int sockfd, struct msghdr *msg, int flags) {
2,881,480✔
1488
        ssize_t n;
2,881,480✔
1489

1490
        /* A wrapper around recvmsg() that checks for MSG_CTRUNC and MSG_TRUNC, and turns them into an error,
1491
         * in a reasonably safe way, closing any received fds in the error path.
1492
         *
1493
         * Note that unlike our usual coding style this might modify *msg on failure. */
1494

1495
        assert(sockfd >= 0);
2,881,480✔
1496
        assert(msg);
2,881,480✔
1497

1498
        n = recvmsg(sockfd, msg, flags);
2,881,480✔
1499
        if (n < 0)
2,881,480✔
1500
                return -errno;
268,873✔
1501

1502
        if (FLAGS_SET(msg->msg_flags, MSG_CTRUNC) ||
2,612,607✔
1503
            (!FLAGS_SET(flags, MSG_PEEK) && FLAGS_SET(msg->msg_flags, MSG_TRUNC))) {
2,612,607✔
UNCOV
1504
                cmsg_close_all(msg);
×
1505
                return FLAGS_SET(msg->msg_flags, MSG_CTRUNC) ? -ECHRNG : -EXFULL;
×
1506
        }
1507

1508
        return n;
1509
}
1510

1511
int socket_get_family(int fd) {
18,524✔
1512
        int af;
18,524✔
1513
        socklen_t sl = sizeof(af);
18,524✔
1514

1515
        if (getsockopt(fd, SOL_SOCKET, SO_DOMAIN, &af, &sl) < 0)
18,524✔
UNCOV
1516
                return -errno;
×
1517

1518
        if (sl != sizeof(af))
18,524✔
1519
                return -EINVAL;
1520

1521
        return af;
18,524✔
1522
}
1523

1524
int socket_set_recvpktinfo(int fd, int af, bool b) {
11,797✔
1525

1526
        if (af == AF_UNSPEC) {
11,797✔
UNCOV
1527
                af = socket_get_family(fd);
×
1528
                if (af < 0)
×
1529
                        return af;
1530
        }
1531

1532
        switch (af) {
11,797✔
1533

1534
        case AF_INET:
6,222✔
1535
                return setsockopt_int(fd, IPPROTO_IP, IP_PKTINFO, b);
6,222✔
1536

1537
        case AF_INET6:
5,542✔
1538
                return setsockopt_int(fd, IPPROTO_IPV6, IPV6_RECVPKTINFO, b);
5,542✔
1539

1540
        case AF_NETLINK:
33✔
1541
                return setsockopt_int(fd, SOL_NETLINK, NETLINK_PKTINFO, b);
33✔
1542

UNCOV
1543
        case AF_PACKET:
×
1544
                return setsockopt_int(fd, SOL_PACKET, PACKET_AUXDATA, b);
×
1545

1546
        default:
1547
                return -EAFNOSUPPORT;
1548
        }
1549
}
1550

1551
int socket_set_unicast_if(int fd, int af, int ifi) {
121✔
1552
        be32_t ifindex_be = htobe32(ifi);
121✔
1553

1554
        if (af == AF_UNSPEC) {
121✔
UNCOV
1555
                af = socket_get_family(fd);
×
1556
                if (af < 0)
×
1557
                        return af;
121✔
1558
        }
1559

1560
        switch (af) {
121✔
1561

1562
        case AF_INET:
91✔
1563
                return RET_NERRNO(setsockopt(fd, IPPROTO_IP, IP_UNICAST_IF, &ifindex_be, sizeof(ifindex_be)));
91✔
1564

1565
        case AF_INET6:
30✔
1566
                return RET_NERRNO(setsockopt(fd, IPPROTO_IPV6, IPV6_UNICAST_IF, &ifindex_be, sizeof(ifindex_be)));
30✔
1567

1568
        default:
1569
                return -EAFNOSUPPORT;
1570
        }
1571
}
1572

1573
int socket_set_option(int fd, int af, int opt_ipv4, int opt_ipv6, int val) {
23,395✔
1574
        if (af == AF_UNSPEC) {
23,395✔
UNCOV
1575
                af = socket_get_family(fd);
×
1576
                if (af < 0)
×
1577
                        return af;
1578
        }
1579

1580
        switch (af) {
23,395✔
1581

1582
        case AF_INET:
12,304✔
1583
                return setsockopt_int(fd, IPPROTO_IP, opt_ipv4, val);
12,304✔
1584

1585
        case AF_INET6:
11,091✔
1586
                return setsockopt_int(fd, IPPROTO_IPV6, opt_ipv6, val);
11,091✔
1587

1588
        default:
1589
                return -EAFNOSUPPORT;
1590
        }
1591
}
1592

1593
int socket_get_mtu(int fd, int af, size_t *ret) {
674✔
1594
        int mtu, r;
674✔
1595

1596
        if (af == AF_UNSPEC) {
674✔
UNCOV
1597
                af = socket_get_family(fd);
×
1598
                if (af < 0)
×
1599
                        return af;
674✔
1600
        }
1601

1602
        switch (af) {
674✔
1603

1604
        case AF_INET:
301✔
1605
                r = getsockopt_int(fd, IPPROTO_IP, IP_MTU, &mtu);
301✔
1606
                break;
1607

1608
        case AF_INET6:
373✔
1609
                r = getsockopt_int(fd, IPPROTO_IPV6, IPV6_MTU, &mtu);
373✔
1610
                break;
1611

1612
        default:
1613
                return -EAFNOSUPPORT;
1614
        }
1615

1616
        if (r < 0)
674✔
1617
                return r;
1618
        if (mtu <= 0)
620✔
1619
                return -EINVAL;
1620

1621
        *ret = (size_t) mtu;
620✔
1622
        return 0;
620✔
1623
}
1624

1625
static int connect_unix_path_simple(int fd, const char *path) {
162,410✔
1626
        union sockaddr_union sa = {
162,410✔
1627
                .un.sun_family = AF_UNIX,
1628
        };
1629
        size_t l;
162,410✔
1630

1631
        assert(fd >= 0);
162,410✔
1632
        assert(path);
162,410✔
1633

1634
        l = strlen(path);
162,410✔
1635
        assert(l > 0);
162,410✔
1636
        assert(l < sizeof(sa.un.sun_path));
162,410✔
1637

1638
        memcpy(sa.un.sun_path, path, l + 1);
162,410✔
1639
        return RET_NERRNO(connect(fd, &sa.sa, offsetof(struct sockaddr_un, sun_path) + l + 1));
162,410✔
1640
}
1641

1642
static int connect_unix_inode(int fd, int inode_fd) {
14✔
1643
        assert(fd >= 0);
14✔
1644
        assert(inode_fd >= 0);
14✔
1645

1646
        return connect_unix_path_simple(fd, FORMAT_PROC_FD_PATH(inode_fd));
14✔
1647
}
1648

1649
int connect_unix_path(int fd, int dir_fd, const char *path) {
162,410✔
1650
        _cleanup_close_ int inode_fd = -EBADF;
162,410✔
1651

1652
        assert(fd >= 0);
162,410✔
1653
        assert(dir_fd == AT_FDCWD || dir_fd >= 0);
162,410✔
1654

1655
        /* Connects to the specified AF_UNIX socket in the file system. Works around the 108 byte size limit
1656
         * in sockaddr_un, by going via O_PATH if needed. This hence works for any kind of path. */
1657

1658
        if (!path)
162,410✔
1659
                return connect_unix_inode(fd, dir_fd); /* If no path is specified, then dir_fd refers to the socket inode to connect to. */
1✔
1660

1661
        /* Refuse zero length path early, to make sure AF_UNIX stack won't mistake this for an abstract
1662
         * namespace path, since first char is NUL */
1663
        if (isempty(path))
324,819✔
1664
                return -EINVAL;
1665

1666
        /* Shortcut for the simple case */
1667
        if (dir_fd == AT_FDCWD && strlen(path) < sizeof_field(struct sockaddr_un, sun_path))
162,409✔
1668
                return connect_unix_path_simple(fd, path);
162,396✔
1669

1670
        /* If dir_fd is specified, then we need to go the indirect O_PATH route, because connectat() does not
1671
         * exist. If the path is too long, we also need to take the indirect route, since we can't fit this
1672
         * into a sockaddr_un directly. */
1673

1674
        inode_fd = openat(dir_fd, path, O_PATH|O_CLOEXEC);
13✔
1675
        if (inode_fd < 0)
13✔
UNCOV
1676
                return -errno;
×
1677

1678
        return connect_unix_inode(fd, inode_fd);
13✔
1679
}
1680

1681
int socket_address_parse_unix(SocketAddress *ret_address, const char *s) {
219,019✔
1682
        struct sockaddr_un un;
219,019✔
1683
        int r;
219,019✔
1684

1685
        assert(ret_address);
219,019✔
1686
        assert(s);
219,019✔
1687

1688
        if (!IN_SET(*s, '/', '@'))
219,019✔
1689
                return -EPROTO;
219,019✔
1690

1691
        r = sockaddr_un_set_path(&un, s);
218,580✔
1692
        if (r < 0)
218,580✔
1693
                return r;
1694

1695
        *ret_address = (SocketAddress) {
218,578✔
1696
                .sockaddr.un = un,
1697
                .size = r,
1698
        };
1699

1700
        return 0;
218,578✔
1701
}
1702

1703
int vsock_parse_port(const char *s, unsigned *ret) {
371✔
1704
        int r;
371✔
1705

1706
        assert(ret);
371✔
1707

1708
        if (!s)
371✔
1709
                return -EINVAL;
371✔
1710

1711
        unsigned u;
371✔
1712
        r = safe_atou(s, &u);
371✔
1713
        if (r < 0)
371✔
1714
                return r;
1715

1716
        /* Port 0 is apparently valid and not special in AF_VSOCK (unlike on IP). But VMADDR_PORT_ANY
1717
         * (UINT32_MAX) is. Hence refuse that. */
1718

1719
        if (u == VMADDR_PORT_ANY)
368✔
1720
                return -EINVAL;
1721

1722
        *ret = u;
368✔
1723
        return 0;
368✔
1724
}
1725

1726
int vsock_parse_cid(const char *s, unsigned *ret) {
331✔
1727
        assert(ret);
331✔
1728

1729
        if (!s)
331✔
1730
                return -EINVAL;
1731

1732
        /* Parsed an AF_VSOCK "CID". This is a 32bit entity, and the usual type is "unsigned". We recognize
1733
         * the three special CIDs as strings, and otherwise parse the numeric CIDs. */
1734

1735
        if (streq(s, "hypervisor"))
331✔
UNCOV
1736
                *ret = VMADDR_CID_HYPERVISOR;
×
1737
        else if (streq(s, "local"))
331✔
UNCOV
1738
                *ret = VMADDR_CID_LOCAL;
×
1739
        else if (streq(s, "host"))
331✔
UNCOV
1740
                *ret = VMADDR_CID_HOST;
×
1741
        else
1742
                return safe_atou(s, ret);
331✔
1743

1744
        return 0;
1745
}
1746

1747
int socket_address_parse_vsock(SocketAddress *ret_address, const char *s) {
439✔
1748
        /* AF_VSOCK socket in vsock:cid:port notation */
1749
        _cleanup_free_ char *n = NULL;
439✔
1750
        char *e, *cid_start;
439✔
1751
        unsigned port, cid;
439✔
1752
        int type, r;
439✔
1753

1754
        assert(ret_address);
439✔
1755
        assert(s);
439✔
1756

1757
        if ((cid_start = startswith(s, "vsock:")))
439✔
1758
                type = 0;
1759
        else if ((cid_start = startswith(s, "vsock-dgram:")))
387✔
1760
                type = SOCK_DGRAM;
1761
        else if ((cid_start = startswith(s, "vsock-seqpacket:")))
387✔
1762
                type = SOCK_SEQPACKET;
1763
        else if ((cid_start = startswith(s, "vsock-stream:")))
387✔
1764
                type = SOCK_STREAM;
1765
        else
1766
                return -EPROTO;
1767

1768
        e = strchr(cid_start, ':');
373✔
1769
        if (!e)
373✔
1770
                return -EINVAL;
1771

1772
        r = vsock_parse_port(e+1, &port);
371✔
1773
        if (r < 0)
371✔
1774
                return r;
1775

1776
        n = strndup(cid_start, e - cid_start);
368✔
1777
        if (!n)
368✔
1778
                return -ENOMEM;
1779

1780
        if (isempty(n))
368✔
1781
                cid = VMADDR_CID_ANY;
37✔
1782
        else {
1783
                r = vsock_parse_cid(n, &cid);
331✔
1784
                if (r < 0)
331✔
1785
                        return r;
1786
        }
1787

1788
        *ret_address = (SocketAddress) {
365✔
1789
                .sockaddr.vm = {
1790
                        .svm_family = AF_VSOCK,
1791
                        .svm_cid = cid,
1792
                        .svm_port = port,
1793
                },
1794
                .type = type,
1795
                .size = sizeof(struct sockaddr_vm),
1796
        };
1797

1798
        return 0;
365✔
1799
}
1800

1801
int vsock_get_local_cid(unsigned *ret) {
16✔
1802
        _cleanup_close_ int vsock_fd = -EBADF;
16✔
1803

1804
        vsock_fd = open("/dev/vsock", O_RDONLY|O_CLOEXEC);
16✔
1805
        if (vsock_fd < 0)
16✔
1806
                return log_debug_errno(errno, "Failed to open /dev/vsock: %m");
13✔
1807

1808
        unsigned tmp;
3✔
1809
        if (ioctl(vsock_fd, IOCTL_VM_SOCKETS_GET_LOCAL_CID, ret ?: &tmp) < 0)
6✔
UNCOV
1810
                return log_debug_errno(errno, "Failed to query local AF_VSOCK CID: %m");
×
1811

1812
        return 0;
1813
}
1814

1815
int netlink_socket_get_multicast_groups(int fd, size_t *ret_len, uint32_t **ret_groups) {
12,010✔
1816
        _cleanup_free_ uint32_t *groups = NULL;
24,020✔
1817
        socklen_t len = 0, old_len;
12,010✔
1818

1819
        assert(fd >= 0);
12,010✔
1820

1821
        if (getsockopt(fd, SOL_NETLINK, NETLINK_LIST_MEMBERSHIPS, NULL, &len) < 0)
12,010✔
UNCOV
1822
                return -errno;
×
1823

1824
        if (len == 0)
12,010✔
1825
                goto finalize;
11,593✔
1826

1827
        groups = new0(uint32_t, len);
417✔
1828
        if (!groups)
417✔
1829
                return -ENOMEM;
1830

1831
        old_len = len;
417✔
1832

1833
        if (getsockopt(fd, SOL_NETLINK, NETLINK_LIST_MEMBERSHIPS, groups, &len) < 0)
417✔
UNCOV
1834
                return -errno;
×
1835

1836
        if (old_len != len)
417✔
1837
                return -EIO;
1838

1839
finalize:
417✔
1840
        if (ret_len)
12,010✔
1841
                *ret_len = len;
12,010✔
1842
        if (ret_groups)
12,010✔
1843
                *ret_groups = TAKE_PTR(groups);
12,010✔
1844

1845
        return 0;
1846
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc